@orkestrel/contract 0.0.21 → 0.0.23

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,6 +1,53 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  // src/core/constants.ts
3
3
  /**
4
+ * Lists the fields recognized for every contract declaration category, frozen.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * SHAPE_FIELDS.shape // ['description']
9
+ * ```
10
+ */
11
+ var SHAPE_FIELDS = Object.freeze({
12
+ string: Object.freeze([
13
+ "min",
14
+ "max",
15
+ "pattern",
16
+ "date",
17
+ "description"
18
+ ]),
19
+ number: Object.freeze([
20
+ "integer",
21
+ "min",
22
+ "max",
23
+ "description"
24
+ ]),
25
+ boolean: Object.freeze(["description"]),
26
+ null: Object.freeze(["description"]),
27
+ literal: Object.freeze(["values", "description"]),
28
+ array: Object.freeze([
29
+ "items",
30
+ "min",
31
+ "max",
32
+ "description"
33
+ ]),
34
+ object: Object.freeze([
35
+ "properties",
36
+ "additionalProperties",
37
+ "description"
38
+ ]),
39
+ union: Object.freeze([
40
+ "variants",
41
+ "mode",
42
+ "description"
43
+ ]),
44
+ optional: Object.freeze(["inner", "default"]),
45
+ nullable: Object.freeze(["inner"]),
46
+ json: Object.freeze(["description"]),
47
+ raw: Object.freeze(["schema"]),
48
+ shape: Object.freeze(["description"])
49
+ });
50
+ /**
4
51
  * Holds the registry-global key used to recognize {@link ContractError} values
5
52
  * across package copies.
6
53
  *
@@ -296,6 +343,50 @@ var JSON_SCHEMA_TYPES = Object.freeze([
296
343
  "string"
297
344
  ]);
298
345
  /**
346
+ * Lists the JSON Schema keywords a strict `schemaToShape` conversion reads, frozen.
347
+ *
348
+ * @remarks
349
+ * The keywords a shape can honour, plus the annotations that assert nothing and so
350
+ * lose nothing when a shape drops them: `title`, `$schema`, `$id`, `$comment`,
351
+ * `examples`, `deprecated`, `readOnly`, and `writeOnly`. Every other keyword refuses.
352
+ * `pattern` and `format` are absent because no compiled shape asserts them, so a
353
+ * schema holding one would convert to a shape wider than the schema it came from. The
354
+ * one exception is `format: 'date'` on a string node, which a strict conversion reads
355
+ * as a date string shape.
356
+ *
357
+ * @example
358
+ * ```ts
359
+ * STRICT_SCHEMA_KEYWORDS.includes('title') // true
360
+ * STRICT_SCHEMA_KEYWORDS.includes('pattern') // false
361
+ * ```
362
+ */
363
+ var STRICT_SCHEMA_KEYWORDS = Object.freeze([
364
+ "type",
365
+ "title",
366
+ "description",
367
+ "$schema",
368
+ "$id",
369
+ "$comment",
370
+ "examples",
371
+ "deprecated",
372
+ "readOnly",
373
+ "writeOnly",
374
+ "default",
375
+ "enum",
376
+ "minLength",
377
+ "maxLength",
378
+ "minimum",
379
+ "maximum",
380
+ "minItems",
381
+ "maxItems",
382
+ "items",
383
+ "properties",
384
+ "required",
385
+ "additionalProperties",
386
+ "anyOf",
387
+ "oneOf"
388
+ ]);
389
+ /**
299
390
  * Lists every declared {@link ContractCode} refusal category, frozen.
300
391
  *
301
392
  * @remarks
@@ -329,6 +420,49 @@ var CONTRACT_CODES = Object.freeze([
329
420
  "expansion"
330
421
  ]);
331
422
  /**
423
+ * Lists every {@link FaultKind}, frozen.
424
+ *
425
+ * @remarks
426
+ * The runtime source of truth for the vocabulary, which {@link isFault} reads.
427
+ *
428
+ * @example
429
+ * ```ts
430
+ * FAULT_KINDS.includes('string') // true
431
+ * ```
432
+ */
433
+ var FAULT_KINDS = Object.freeze([
434
+ "string",
435
+ "date",
436
+ "number",
437
+ "integer",
438
+ "boolean",
439
+ "null",
440
+ "literal",
441
+ "array",
442
+ "object",
443
+ "union",
444
+ "json",
445
+ "shape"
446
+ ]);
447
+ /**
448
+ * Lists every {@link FaultConstraint}, frozen.
449
+ *
450
+ * @remarks
451
+ * The runtime source of truth for the vocabulary, which {@link isFault} reads.
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * FAULT_CONSTRAINTS.includes('min') // true
456
+ * ```
457
+ */
458
+ var FAULT_CONSTRAINTS = Object.freeze([
459
+ "min",
460
+ "max",
461
+ "pattern",
462
+ "date",
463
+ "integer"
464
+ ]);
465
+ /**
332
466
  * Caps at `64` the number of {@link Fault} / {@link AuditFault} entries a single
333
467
  * `explain` or `audit` report ever returns, frozen.
334
468
  *
@@ -549,6 +683,19 @@ var FORMAT_PATTERNS = Object.freeze({
549
683
  uri: /^[a-z][a-z0-9+.-]*:\/\//i
550
684
  });
551
685
  /**
686
+ * Holds `10`, the length of every `YYYY-MM-DD` date a date string shape admits.
687
+ *
688
+ * @remarks
689
+ * A date string shape whose `min` or `max` excludes this length admits no value, so
690
+ * building one refuses with code `range`.
691
+ *
692
+ * @example
693
+ * ```ts
694
+ * DATE_LENGTH // 10
695
+ * ```
696
+ */
697
+ var DATE_LENGTH = 10;
698
+ /**
552
699
  * Caps at `1024` the number of choices one schema field may offer, frozen.
553
700
  *
554
701
  * @remarks
@@ -613,6 +760,12 @@ var TEXT_LIMIT = 1048576;
613
760
  * ```
614
761
  */
615
762
  var NODE_LIMIT = 16384;
763
+ /** Caps a fault message at 2048 UTF-16 code units. */
764
+ var FAULT_TEXT_LIMIT = 2048;
765
+ /** Caps the keys or literal candidates named in a fault line. */
766
+ var FAULT_LIST_LIMIT = 12;
767
+ /** Caps a schema summary's UTF-16 code units. */
768
+ var FAULT_SCHEMA_LIMIT = 160;
616
769
  // src/core/errors.ts
617
770
  /**
618
771
  * Carries a machine-readable contract category, optional context, and an exact optional
@@ -1263,6 +1416,103 @@ function isObject(value) {
1263
1416
  function isRecord(value) {
1264
1417
  return holds(() => matchesRecordBrand(value));
1265
1418
  }
1419
+ /**
1420
+ * Determines whether a value is the {@link FieldPath} a fault carries: a key, or a dense list of keys.
1421
+ *
1422
+ * @param value - The value to inspect
1423
+ * @returns True if the value is a string or a dense array of strings; false otherwise
1424
+ *
1425
+ * @example
1426
+ * ```ts
1427
+ * isFaultPath(['user', 'name']) // true
1428
+ * isFaultPath([1]) // false
1429
+ * ```
1430
+ */
1431
+ function isFaultPath(value) {
1432
+ if (isString(value)) return true;
1433
+ return holds(() => {
1434
+ if (!isArray(value)) return false;
1435
+ const snapshot = readArrayEntries(value);
1436
+ if (isFailure(snapshot) || !snapshot.value.dense) return false;
1437
+ return !INTRINSICS.reflect.apply(INTRINSICS.some, snapshot.value.entries, [(entry) => !isString(entry)]);
1438
+ });
1439
+ }
1440
+ /**
1441
+ * Determines whether a value is exactly one {@link Fault}.
1442
+ *
1443
+ * @remarks
1444
+ * A closed reading of the union: each reason's required fields, each with its own
1445
+ * vocabulary, and no other key, so `{}` and a fault carrying a stray field both answer
1446
+ * `false`. An undeclared-key fault is an {@link AuditFault} and answers `false` here.
1447
+ *
1448
+ * @param value - The value to inspect
1449
+ * @returns True if the value is a well-formed fault; false otherwise
1450
+ *
1451
+ * @example
1452
+ * ```ts
1453
+ * isFault({ reason: 'missing', path: ['a'], expected: 'string' }) // true
1454
+ * isFault({}) // false
1455
+ * ```
1456
+ */
1457
+ function isFault(value) {
1458
+ return holds(() => {
1459
+ if (!isRecord(value) || !isFaultPath(value.path)) return false;
1460
+ const kind = INTRINSICS.reflect.apply(INTRINSICS.some, FAULT_KINDS, [(entry) => entry === value.expected]);
1461
+ const named = INTRINSICS.own(value, "key") || INTRINSICS.own(value, "expected");
1462
+ const list = readArrayEntries(isArray(value.expected) ? value.expected : [void 0]);
1463
+ 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)]);
1464
+ switch (value.reason) {
1465
+ case "type": return kind && isString(value.received) && matchesExactKeys(value, [
1466
+ "reason",
1467
+ "path",
1468
+ "expected",
1469
+ "received"
1470
+ ]);
1471
+ case "missing": return kind && matchesExactKeys(value, [
1472
+ "reason",
1473
+ "path",
1474
+ "expected"
1475
+ ]);
1476
+ 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, [
1477
+ "reason",
1478
+ "path",
1479
+ "expected",
1480
+ "constraint",
1481
+ "received"
1482
+ ], ["limit"]);
1483
+ case "variant": return isNonNegativeInteger(value.variants) && hinted && matchesExactKeys(value, [
1484
+ "reason",
1485
+ "path",
1486
+ "variants"
1487
+ ], named ? ["key", "expected"] : []);
1488
+ case "oneOf": return isNonNegativeInteger(value.matched) && hinted && matchesExactKeys(value, [
1489
+ "reason",
1490
+ "path",
1491
+ "matched"
1492
+ ], named ? ["key", "expected"] : []);
1493
+ default: return false;
1494
+ }
1495
+ });
1496
+ }
1497
+ /**
1498
+ * Determines whether a value is exactly one {@link AuditFault}.
1499
+ *
1500
+ * @remarks
1501
+ * Every {@link Fault}, and the undeclared-key fault an audit adds.
1502
+ *
1503
+ * @param value - The value to inspect
1504
+ * @returns True if the value is a well-formed audit fault; false otherwise
1505
+ *
1506
+ * @example
1507
+ * ```ts
1508
+ * isAuditFault({ reason: 'extra', path: ['a'] }) // true
1509
+ * isAuditFault({}) // false
1510
+ * ```
1511
+ */
1512
+ function isAuditFault(value) {
1513
+ if (isFault(value)) return true;
1514
+ return holds(() => isRecord(value) && value.reason === "extra" && isFaultPath(value.path) && matchesExactKeys(value, ["reason", "path"]));
1515
+ }
1266
1516
  /** Determines whether a value is a `Map`.
1267
1517
  *
1268
1518
  * @param value - The value to inspect
@@ -1906,6 +2156,126 @@ function isJSONPrimitive(value) {
1906
2156
  }
1907
2157
  // src/core/helpers.ts
1908
2158
  /**
2159
+ * Admits a stable readable value with only lossless repairs and returns the parser's value.
2160
+ *
2161
+ * @remarks
2162
+ * Reads must remain stable across artifacts. Guard-valid input skips both reports and parses
2163
+ * once. Repairs use audit, parse once, and explain only on parse failure. Unresolved unions,
2164
+ * extras, lossy repairs, and a capped audit refuse. An own optional undefined field omitted or
2165
+ * filled by its declared default is not a repair. The result preserves parser ownership, including union input identity.
2166
+ * A read failure returns its cause rather than throwing.
2167
+ * Snapshot a foreign object before admission, as Tool.execute does. A getter changing between
2168
+ * is and parse can publish a value that no recorded repair describes. A shallow snapshot only
2169
+ * stabilizes its own level; nested foreign values must also provide stable reads.
2170
+ *
2171
+ * @example
2172
+ * ```ts
2173
+ * admitValue(createContract(numberShape()), '3') // success carrying 3 and its type repair
2174
+ * ```
2175
+ */
2176
+ function admitValue(contract, value) {
2177
+ try {
2178
+ if (contract.is(value)) {
2179
+ const parsed = contract.parse(value);
2180
+ if (parsed === void 0 && value !== void 0) return failure({ faults: [] });
2181
+ return success({
2182
+ value: parsed === void 0 ? value : parsed,
2183
+ repairs: []
2184
+ });
2185
+ }
2186
+ const audited = contract.audit(value);
2187
+ const parsed = contract.parse(value);
2188
+ const explained = parsed === void 0 ? contract.explain(value) : [];
2189
+ const repairs = audited.filter((fault) => matchesLosslessRepair(fault, value, parsed));
2190
+ const refused = audited.filter((fault) => !repairs.includes(fault) && !matchesUndefinedField(fault, value, parsed));
2191
+ const merged = [...explained, ...refused];
2192
+ const faults = [...new Map(merged.map((fault) => [JSON.stringify([fault.reason, extractPath(fault)]), fault])).values()];
2193
+ const covers = faults.filter((fault) => fault.reason === "variant" || fault.reason === "oneOf").map((fault) => extractPath(fault));
2194
+ const uncovered = faults.filter((fault) => {
2195
+ const path = extractPath(fault);
2196
+ const room = fault.reason === "variant" || fault.reason === "oneOf" ? 1 : 0;
2197
+ return !covers.some((cover) => cover.length + room <= path.length && cover.every((segment, index) => segment === path[index]));
2198
+ });
2199
+ if (uncovered.length > 0) return failure({ faults: limitEntries(uncovered, 64) });
2200
+ if (audited.length >= 64) return failure({ faults: limitEntries(audited, 64) });
2201
+ if (parsed === void 0) return failure({ faults: limitEntries(audited, 64) });
2202
+ return success({
2203
+ value: parsed,
2204
+ repairs
2205
+ });
2206
+ } catch (cause) {
2207
+ return failure({
2208
+ faults: [],
2209
+ cause
2210
+ });
2211
+ }
2212
+ }
2213
+ /**
2214
+ * Checks whether a type fault describes an own undefined field omitted or defaulted by a successful parse.
2215
+ *
2216
+ * @remarks
2217
+ * Reads own members directly so absence and an unreadable member cannot stand for undefined.
2218
+ * A compiled parser fills an undefined field only through its declared default; it never coerces it.
2219
+ * Required reads propagate their cause to the admission boundary.
2220
+ *
2221
+ * @example
2222
+ * ```ts
2223
+ * matchesUndefinedField({ reason: 'type', path: ['note'], expected: 'string', received: 'undefined' }, { note: undefined }, {}) // true
2224
+ * ```
2225
+ */
2226
+ function matchesUndefinedField(fault, value, parsed) {
2227
+ if (fault.reason !== "type" || parsed === void 0) return false;
2228
+ const path = extractPath(fault);
2229
+ const key = path.at(-1);
2230
+ if (key === void 0) return false;
2231
+ 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]);
2232
+ return isObject(raw) && INTRINSICS.own(raw, key) && INTRINSICS.reflect.read(raw, key) === void 0 && isObject(result);
2233
+ }
2234
+ /**
2235
+ * Truncates text to a UTF-16 budget without splitting a surrogate pair.
2236
+ *
2237
+ * @example
2238
+ * ```ts
2239
+ * truncateFaultText('abcdef', 4) // 'abc…'
2240
+ * ```
2241
+ */
2242
+ function truncateFaultText(text, limit) {
2243
+ if (limit <= 0) return "";
2244
+ if (text.length <= limit) return text;
2245
+ return `${text.slice(0, limit - 1).replace(/[\uD800-\uDBFF]$/u, "")}…`;
2246
+ }
2247
+ /**
2248
+ * Describes bounded faults with encoded values and a schema-derived correction summary.
2249
+ *
2250
+ * @remarks
2251
+ * Default: 2048 UTF-16 code units. A smaller non-negative integer limit reserves a caller's
2252
+ * heading budget. The report reserves room for omitted-fault and cap notices, and ends with a
2253
+ * send summary when a schema is supplied. Untrusted names, descriptions, and strings use preview.
2254
+ *
2255
+ * @example
2256
+ * ```ts
2257
+ * describeFaults([{ reason: 'missing', path: ['age'], expected: 'number' }])
2258
+ * // 'age: missing; expected number'
2259
+ * ```
2260
+ */
2261
+ function describeFaults(faults, schema, options) {
2262
+ const requested = options?.limit ?? 2048;
2263
+ if (!isInteger(requested) || requested < 0) throw new ContractError("Fault text limit must be a non-negative integer", { code: "range" });
2264
+ const limit = Math.min(requested, FAULT_TEXT_LIMIT);
2265
+ const send = schema === void 0 ? "" : `send ${renderForm(schema, Math.min(160, Math.floor(limit / 3)))}`;
2266
+ const lines = limitEntries(faults, 64).map((fault) => describeFaultLine(fault, schema ?? {}));
2267
+ const room = Math.max(0, limit - send.length - 82);
2268
+ const kept = lines.filter((_, index) => lines.slice(0, index + 1).join("\n").length <= room);
2269
+ const hidden = faults.length - kept.length;
2270
+ const note = [...hidden > 0 ? [`and ${String(hidden)} more faults`] : [], ...faults.length >= 64 ? [`the report stops at ${String(64)}`] : []].join(", ");
2271
+ return truncateFaultText([
2272
+ ...kept,
2273
+ ...kept.length === 0 && lines.length > 0 && room > 0 ? [truncateFaultText(lines[0] ?? "", room)] : [],
2274
+ ...note.length === 0 ? [] : [note],
2275
+ ...send.length === 0 ? [] : [send]
2276
+ ].join("\n"), limit);
2277
+ }
2278
+ /**
1909
2279
  * Iterates indices while rereading the upper bound before every step.
1910
2280
  *
1911
2281
  * @remarks
@@ -2488,6 +2858,93 @@ function matchesPattern(pattern, value) {
2488
2858
  return INTRINSICS.reflect.apply(INTRINSICS.captures, pattern, [value]) !== null;
2489
2859
  }
2490
2860
  /**
2861
+ * Checks whether a string's length in code points falls within optional bounds.
2862
+ *
2863
+ * @remarks
2864
+ * Counts what JSON Schema's `minLength` and `maxLength` count: a surrogate pair is
2865
+ * one, and a lone surrogate is one. A string holds at most `.length` code points and
2866
+ * at least half that, so `.length` decides every bound it can with no count. The
2867
+ * count runs only where a bound sits between those two figures, which limits its
2868
+ * work to about twice the bound rather than to the size of the string.
2869
+ *
2870
+ * @param value - The string to measure
2871
+ * @param min - The inclusive lower bound, when there is one
2872
+ * @param max - The inclusive upper bound, when there is one
2873
+ * @returns True if the code-point count is within every present bound; false otherwise
2874
+ *
2875
+ * @example
2876
+ * ```ts
2877
+ * matchesStringLength('😀😀', undefined, 2) // true
2878
+ * matchesStringLength('😀', 2, undefined) // false
2879
+ * ```
2880
+ */
2881
+ function matchesStringLength(value, min, max) {
2882
+ const length = value.length;
2883
+ if (min !== void 0 && length < min) return false;
2884
+ if (max !== void 0 && length > 2 * max) return false;
2885
+ if ((min === void 0 || INTRINSICS.ceil(length / 2) >= min) && (max === void 0 || length <= max)) return true;
2886
+ const points = length - computeSurrogatePairs(value, length - (min === void 0 ? max ?? 0 : min - 1));
2887
+ return (min === void 0 || points >= min) && (max === void 0 || points <= max);
2888
+ }
2889
+ /**
2890
+ * Counts the surrogate pairs in a string, stopping at a limit.
2891
+ *
2892
+ * @remarks
2893
+ * A regular-expression literal builds a fresh `RegExp` per evaluation, so this call
2894
+ * owns the `lastIndex` that is its cursor, and the captured `exec` reads the internal
2895
+ * slots and no member a caller can replace. Text with no surrogate costs one native
2896
+ * scan, and a string of pairs costs one `exec` per pair up to the limit.
2897
+ *
2898
+ * @param value - The string to scan
2899
+ * @param limit - The count to stop at
2900
+ * @returns The number of surrogate pairs, or `limit` when the string holds at least that many
2901
+ *
2902
+ * @example
2903
+ * ```ts
2904
+ * computeSurrogatePairs('😀a😀', 8) // 2
2905
+ * computeSurrogatePairs('😀😀😀', 2) // 2
2906
+ * ```
2907
+ */
2908
+ function computeSurrogatePairs(value, limit) {
2909
+ const pair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
2910
+ const steps = limit > 0 ? INTRINSICS.ceil(limit) : 0;
2911
+ for (const step of iterateIndices(() => steps)) if (INTRINSICS.reflect.apply(INTRINSICS.captures, pair, [value]) === null) return step;
2912
+ return steps;
2913
+ }
2914
+ /**
2915
+ * Refuses an options record that holds a key its builder does not read.
2916
+ *
2917
+ * @remarks
2918
+ * The door for an option that decides what a contract accepts, where a misspelled key
2919
+ * would otherwise read as an absent option and fail open. It looks at own enumerable
2920
+ * string keys, so an inherited or symbol-keyed member is not a misspelling.
2921
+ *
2922
+ * @param source - The builder options, when there are any
2923
+ * @param keys - The keys that builder reads
2924
+ * @param builder - The builder name used in the refusal
2925
+ * @param shape - The shape category used in structured error context
2926
+ * @throws {ContractError} When the record holds any other key
2927
+ *
2928
+ * @example
2929
+ * ```ts
2930
+ * refuseOptionKeys({ strict: true }, ['strict'], 'schemaToShape', 'schema') // returns
2931
+ * refuseOptionKeys({ strct: true }, ['strict'], 'schemaToShape', 'schema') // throws
2932
+ * ```
2933
+ */
2934
+ function refuseOptionKeys(source, keys, builder, shape) {
2935
+ if (source === void 0) return;
2936
+ const first = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(INTRINSICS.keys(source)), [(key) => !INTRINSICS.reflect.apply(INTRINSICS.some, keys, [(name) => name === key])])[0];
2937
+ if (first === void 0) return;
2938
+ const known = INTRINSICS.reflect.apply(INTRINSICS.join, keys, [", "]);
2939
+ throw new ContractError(`${builder}: unknown option ${preview(first)}; the options are ${known}`, {
2940
+ code: "structure",
2941
+ context: {
2942
+ path: [first],
2943
+ shape
2944
+ }
2945
+ });
2946
+ }
2947
+ /**
2491
2948
  * Escapes every regular-expression metacharacter in a text, so the text
2492
2949
  * matches literally inside a larger `RegExp` source.
2493
2950
  *
@@ -2813,7 +3270,7 @@ function readValue(callback, reader, options) {
2813
3270
  };
2814
3271
  const requested = options?.code;
2815
3272
  const subject = options?.subject;
2816
- const code = requested !== void 0 && matchesMember(collectMembers(CONTRACT_CODES), requested) ? requested : "structure";
3273
+ const code = requested !== void 0 && INTRINSICS.reflect.apply(INTRINSICS.some, CONTRACT_CODES, [(known) => known === requested]) ? requested : "structure";
2817
3274
  return {
2818
3275
  reader: isString(reader) ? reader : "readValue",
2819
3276
  subject: isString(subject) ? subject : "value",
@@ -3309,6 +3766,70 @@ function resolveField(record, path) {
3309
3766
  return isSuccess(outcome) ? outcome.value : void 0;
3310
3767
  }
3311
3768
  /**
3769
+ * Determines whether an object holds exactly the named own keys.
3770
+ *
3771
+ * @remarks
3772
+ * Every required key must be own, and every own key, symbols and non-enumerable ones
3773
+ * included, must be named, so an inherited field and a stray one both answer `false`.
3774
+ *
3775
+ * @param value - The object to inspect
3776
+ * @param required - The keys it must own
3777
+ * @param optional - The keys it may own
3778
+ * @returns True if its own keys are exactly those; false otherwise
3779
+ *
3780
+ * @example
3781
+ * ```ts
3782
+ * matchesExactKeys({ a: 1 }, ['a']) // true
3783
+ * matchesExactKeys({ a: 1, b: 2 }, ['a']) // false
3784
+ * matchesExactKeys({ a: 1, b: 2 }, ['a'], ['b']) // true
3785
+ * ```
3786
+ */
3787
+ function matchesExactKeys(value, required, optional = []) {
3788
+ if (INTRINSICS.reflect.apply(INTRINSICS.some, required, [(key) => !INTRINSICS.own(value, key)])) return false;
3789
+ 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])]);
3790
+ }
3791
+ /**
3792
+ * Determines whether a repair `parse` made kept everything the value said.
3793
+ *
3794
+ * @remarks
3795
+ * `parse`'s coercions are published and form input relies on them, but some change what
3796
+ * a value means: `1` to `true`, `'9007199254740993'` to `...992`, `'1e-400'` to `0`,
3797
+ * `'0x10'` to `16`. A door that must not guess asks this about each fault `audit` reported,
3798
+ * since `audit` already names every nested repair with its path and the kind it wanted.
3799
+ *
3800
+ * Only a `type` fault is a repair. A number needs a string whose trim is the number's own
3801
+ * text, so `'30'` and `' 30 '` pass while `'30.0'`, `'007'`, `'0x10'`, `'1e3'`, `'+5'`,
3802
+ * `'.5'`, `'-0'`, and `'9007199254740993'` do not. A boolean needs `'true'` or `'false'`,
3803
+ * a literal its trimmed text, and a string a finite number. Anything else refuses.
3804
+ *
3805
+ * @param fault - A fault `audit` reported
3806
+ * @param input - The value as it arrived
3807
+ * @param parsed - What `parse` made of it
3808
+ * @returns True if the repair loses nothing; false otherwise
3809
+ *
3810
+ * @example
3811
+ * ```ts
3812
+ * const fault = { reason: 'type', path: ['a'], expected: 'number', received: '' } as const
3813
+ * matchesLosslessRepair(fault, { a: ' 30 ' }, { a: 30 }) // true
3814
+ * matchesLosslessRepair(fault, { a: '30.0' }, { a: 30 }) // false
3815
+ * ```
3816
+ */
3817
+ function matchesLosslessRepair(fault, input, parsed) {
3818
+ if (fault.reason !== "type") return false;
3819
+ const keys = isString(fault.path) ? [fault.path] : fault.path;
3820
+ const route = INTRINSICS.from(iterateIndices(() => keys.length + 1), (index) => index === 0 ? "root" : keys[index - 1] ?? "");
3821
+ const raw = resolveField({ root: input }, route);
3822
+ const value = resolveField({ root: parsed }, route);
3823
+ switch (fault.expected) {
3824
+ case "number":
3825
+ case "integer": return isString(raw) && isNumber(value) && raw.trim() === INTRINSICS.text(value);
3826
+ case "literal": return isString(raw) && (isString(value) || isNumber(value) || isBoolean(value)) && raw.trim() === INTRINSICS.text(value);
3827
+ case "boolean": return raw === "true" || raw === "false";
3828
+ case "string": return isFiniteNumber(raw);
3829
+ default: return false;
3830
+ }
3831
+ }
3832
+ /**
3312
3833
  * Determines whether a readable value stays within the fixed JSON container-depth limit.
3313
3834
  *
3314
3835
  * @remarks
@@ -3416,13 +3937,16 @@ function matchesJSONDepth(value) {
3416
3937
  *
3417
3938
  * Beside the ancestor set the walk keeps a walk-local PROVED set, so a node
3418
3939
  * whose whole subtree already matched is not re-walked when a second path
3419
- * reaches it. Removing the recursion alone left the work exponential in shared
3940
+ * reaches it. A supplied capture budget instead charges each occurrence that
3941
+ * ownership would copy; exhaustion throws `structure` with a `clone` cause.
3942
+ * Removing the recursion alone left the work exponential in shared
3420
3943
  * aliases: thirty aliases — thirty-one ordinary records — cost `2^30` visits
3421
3944
  * through `isJSONValue`, `parseJSONValue`, `canonicalStringify` and every
3422
3945
  * `jsonShape` contract.
3423
3946
  *
3424
3947
  * @param entry - The value to inspect
3425
3948
  * @param ancestors - Objects on the active traversal path
3949
+ * @param budget - Remaining capture nodes; aliases are charged for each copied occurrence when supplied
3426
3950
  * @returns True if the value is a cycle-free JSON value; false otherwise
3427
3951
  *
3428
3952
  * @example
@@ -3431,8 +3955,12 @@ function matchesJSONDepth(value) {
3431
3955
  * matchesJSONValue(Number.NaN, new WeakSet()) // false
3432
3956
  * ```
3433
3957
  */
3434
- function matchesJSONValue(entry, ancestors) {
3958
+ function matchesJSONValue(entry, ancestors, budget) {
3435
3959
  return readValue(() => {
3960
+ if (budget !== void 0) {
3961
+ if (!INTRINSICS.safe(budget.left)) throw new ContractError("matchesJSONValue: invalid node budget", { code: "clone" });
3962
+ budget.left = INTRINSICS.min(budget.left, CLONE_NODE_LIMIT);
3963
+ }
3436
3964
  const stack = [{
3437
3965
  operation: "enter",
3438
3966
  value: entry
@@ -3446,11 +3974,18 @@ function matchesJSONValue(entry, ancestors) {
3446
3974
  admitVisited(proved, frame.value);
3447
3975
  continue;
3448
3976
  }
3977
+ if (budget !== void 0) {
3978
+ budget.left -= 1;
3979
+ if (budget.left < 0) throw new ContractError(`validateShape: default exceeds the capture node limit ${CLONE_NODE_LIMIT}`, {
3980
+ code: "clone",
3981
+ context: { limit: CLONE_NODE_LIMIT }
3982
+ });
3983
+ }
3449
3984
  const node = frame.value;
3450
3985
  if (node === null || isString(node) || isBoolean(node) || isFiniteNumber(node)) continue;
3451
3986
  if (INTRINSICS.array(node)) {
3452
3987
  if (matchesVisited(ancestors, node)) return false;
3453
- if (matchesVisited(proved, node)) continue;
3988
+ if (budget === void 0 && matchesVisited(proved, node)) continue;
3454
3989
  const snapshot = readArrayEntries(node);
3455
3990
  if (isFailure(snapshot)) throw snapshot.error;
3456
3991
  if (!snapshot.value.dense) return false;
@@ -3471,7 +4006,7 @@ function matchesJSONValue(entry, ancestors) {
3471
4006
  }
3472
4007
  if (!isRecord(node)) return false;
3473
4008
  if (matchesVisited(ancestors, node)) return false;
3474
- if (matchesVisited(proved, node)) continue;
4009
+ if (budget === void 0 && matchesVisited(proved, node)) continue;
3475
4010
  admitVisited(ancestors, node);
3476
4011
  stack[stack.length] = {
3477
4012
  operation: "exit",
@@ -3581,7 +4116,7 @@ function schemaToObject(schema) {
3581
4116
  return contain(() => {
3582
4117
  return readValue(() => {
3583
4118
  INTRINSICS.values(schema);
3584
- if (schema.type === "object") return schema;
4119
+ if (INTRINSICS.own(schema, "type") && schema.type === "object") return schema;
3585
4120
  return {
3586
4121
  type: "object",
3587
4122
  properties: { value: schema },
@@ -3714,6 +4249,27 @@ function canonicalStringify(value) {
3714
4249
  }, "canonicalStringify");
3715
4250
  }
3716
4251
  /**
4252
+ * Computes the number of days in a month of the Gregorian calendar.
4253
+ *
4254
+ * @remarks
4255
+ * February has 29 days in a year divisible by 4, except a century year not divisible
4256
+ * by 400. The caller supplies a month from 1 to 12.
4257
+ *
4258
+ * @param year - The calendar year
4259
+ * @param month - The month, from 1 for January to 12 for December
4260
+ * @returns The days in that month, from 28 to 31
4261
+ *
4262
+ * @example
4263
+ * ```ts
4264
+ * computeMonthLength(2024, 2) // 29
4265
+ * computeMonthLength(1900, 2) // 28
4266
+ * ```
4267
+ */
4268
+ function computeMonthLength(year, month) {
4269
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
4270
+ return month === 2 ? 28 + INTRINSICS.numeric(leap) : 31 - INTRINSICS.numeric(month === 4 || month === 6 || month === 9 || month === 11);
4271
+ }
4272
+ /**
3717
4273
  * Checks whether a supported ISO-8601 date or date-time names a real instant.
3718
4274
  *
3719
4275
  * @remarks
@@ -3744,9 +4300,7 @@ function matchesISOInstant(value) {
3744
4300
  const month = INTRINSICS.numeric(monthText);
3745
4301
  const day = INTRINSICS.numeric(dayText);
3746
4302
  if (month < 1 || month > 12) return false;
3747
- const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
3748
- const limit = month === 2 ? 28 + INTRINSICS.numeric(leap) : 31 - INTRINSICS.numeric(month === 4 || month === 6 || month === 9 || month === 11);
3749
- if (day < 1 || day > limit) return false;
4303
+ if (day < 1 || day > computeMonthLength(year, month)) return false;
3750
4304
  const hourText = match?.[4];
3751
4305
  const minuteText = match?.[5];
3752
4306
  const secondText = match?.[6];
@@ -3763,6 +4317,27 @@ function matchesISOInstant(value) {
3763
4317
  return isSuccess(outcome) && outcome.value;
3764
4318
  }
3765
4319
  /**
4320
+ * Checks whether a string is exactly a calendar-valid `YYYY-MM-DD` date.
4321
+ *
4322
+ * @remarks
4323
+ * Refuses a date-time, surrounding whitespace, and a date the Gregorian calendar
4324
+ * lacks, such as `2026-02-29`. Backs a date string shape and {@link classifyFormat}'s
4325
+ * `date`.
4326
+ *
4327
+ * @param value - The candidate string
4328
+ * @returns True if `value` is a calendar-valid `YYYY-MM-DD`; false otherwise
4329
+ * @throws The exact value thrown by a redirected pattern dispatch
4330
+ *
4331
+ * @example
4332
+ * ```ts
4333
+ * matchesCalendarDate('2024-02-29') // true
4334
+ * matchesCalendarDate('2026-02-29') // false
4335
+ * ```
4336
+ */
4337
+ function matchesCalendarDate(value) {
4338
+ return matchesPattern(/^\d{4}-\d{2}-\d{2}$/, value) && matchesISOInstant(value);
4339
+ }
4340
+ /**
3766
4341
  * Classifies an already-bounded string against the pattern-only and
3767
4342
  * calendar-checked {@link SchemaFormat} vocabulary.
3768
4343
  *
@@ -3784,7 +4359,7 @@ function matchesISOInstant(value) {
3784
4359
  function classifyFormat(value) {
3785
4360
  if (matchesPattern(FORMAT_PATTERNS.uuid, value)) return "uuid";
3786
4361
  if (matchesPattern(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/, value) && matchesISOInstant(value)) return "date-time";
3787
- if (matchesPattern(/^\d{4}-\d{2}-\d{2}$/, value) && matchesISOInstant(value)) return "date";
4362
+ if (matchesCalendarDate(value)) return "date";
3788
4363
  if (matchesPattern(/^\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/, value) && matchesISOInstant(`1970-01-01T${value}`)) return "time";
3789
4364
  if (matchesPattern(FORMAT_PATTERNS.email, value)) return "email";
3790
4365
  if (matchesPattern(FORMAT_PATTERNS.uri, value)) return "uri";
@@ -4001,8 +4576,10 @@ function preview(value) {
4001
4576
  * OBTAIN the string — the reporter coerces through `parseString`, the auditor
4002
4577
  * demands a primitive string — and share every constraint afterwards through
4003
4578
  * this helper, so a constraint cannot drift between them.
4004
- * Faults come out in declaration order — `min`, then `max`, then
4579
+ * Faults come out in declaration order — `date`, then `min`, then `max`, then
4005
4580
  * `pattern` — because a report is read top to bottom and its order is public.
4581
+ * `expected` is `'date'` on a date string shape and `'string'` otherwise, as
4582
+ * {@link buildNumberFaults} names `'integer'`.
4006
4583
  *
4007
4584
  * The declaration's pattern is applied through an OWNED stateless rebuild
4008
4585
  * ({@link readPattern}) asked through {@link matchesPattern}, so the shape's own
@@ -4049,30 +4626,39 @@ function preview(value) {
4049
4626
  */
4050
4627
  function buildStringFaults(shape, value, path, pattern) {
4051
4628
  return readValue(() => {
4629
+ const dated = INTRINSICS.own(shape, "date") && shape.date === true;
4630
+ const expected = dated ? "date" : "string";
4052
4631
  const faults = [];
4053
- if (shape.min !== void 0 && value.length < shape.min) faults[faults.length] = {
4632
+ if (dated && !matchesCalendarDate(value)) faults[faults.length] = {
4633
+ reason: "constraint",
4634
+ path,
4635
+ expected,
4636
+ constraint: "date",
4637
+ received: preview(value)
4638
+ };
4639
+ if (INTRINSICS.own(shape, "min") && shape.min !== void 0 && !matchesStringLength(value, shape.min, void 0)) faults[faults.length] = {
4054
4640
  reason: "constraint",
4055
4641
  path,
4056
- expected: "string",
4642
+ expected,
4057
4643
  constraint: "min",
4058
4644
  limit: shape.min,
4059
4645
  received: preview(value)
4060
4646
  };
4061
- if (shape.max !== void 0 && value.length > shape.max) faults[faults.length] = {
4647
+ if (INTRINSICS.own(shape, "max") && shape.max !== void 0 && !matchesStringLength(value, void 0, shape.max)) faults[faults.length] = {
4062
4648
  reason: "constraint",
4063
4649
  path,
4064
- expected: "string",
4650
+ expected,
4065
4651
  constraint: "max",
4066
4652
  limit: shape.max,
4067
4653
  received: preview(value)
4068
4654
  };
4069
- const stateless = pattern ?? (shape.pattern === void 0 ? void 0 : readPattern(shape.pattern));
4655
+ const stateless = pattern ?? (!INTRINSICS.own(shape, "pattern") || shape.pattern === void 0 ? void 0 : readPattern(shape.pattern));
4070
4656
  if (stateless !== void 0 && !matchesPattern(stateless, value)) {
4071
4657
  const limit = readPatternSource(stateless);
4072
4658
  faults[faults.length] = {
4073
4659
  reason: "constraint",
4074
4660
  path,
4075
- expected: "string",
4661
+ expected,
4076
4662
  constraint: "pattern",
4077
4663
  ...limit === void 0 ? {} : { limit },
4078
4664
  received: preview(value)
@@ -4106,16 +4692,16 @@ function buildStringFaults(shape, value, path, pattern) {
4106
4692
  */
4107
4693
  function buildNumberFaults(shape, value, path) {
4108
4694
  return readValue(() => {
4109
- const expected = shape.integer === true ? "integer" : "number";
4695
+ const expected = INTRINSICS.own(shape, "integer") && shape.integer === true ? "integer" : "number";
4110
4696
  const faults = [];
4111
- if (shape.integer === true && !INTRINSICS.integer(value)) faults[faults.length] = {
4697
+ if (INTRINSICS.own(shape, "integer") && shape.integer === true && !INTRINSICS.integer(value)) faults[faults.length] = {
4112
4698
  reason: "constraint",
4113
4699
  path,
4114
4700
  expected,
4115
4701
  constraint: "integer",
4116
4702
  received: preview(value)
4117
4703
  };
4118
- if (shape.min !== void 0 && value < shape.min) faults[faults.length] = {
4704
+ if (INTRINSICS.own(shape, "min") && shape.min !== void 0 && value < shape.min) faults[faults.length] = {
4119
4705
  reason: "constraint",
4120
4706
  path,
4121
4707
  expected,
@@ -4123,7 +4709,7 @@ function buildNumberFaults(shape, value, path) {
4123
4709
  limit: shape.min,
4124
4710
  received: preview(value)
4125
4711
  };
4126
- if (shape.max !== void 0 && value > shape.max) faults[faults.length] = {
4712
+ if (INTRINSICS.own(shape, "max") && shape.max !== void 0 && value > shape.max) faults[faults.length] = {
4127
4713
  reason: "constraint",
4128
4714
  path,
4129
4715
  expected,
@@ -4161,7 +4747,7 @@ function buildNumberFaults(shape, value, path) {
4161
4747
  function buildArrayFaults(shape, length, path) {
4162
4748
  return readValue(() => {
4163
4749
  const faults = [];
4164
- if (shape.min !== void 0 && length < shape.min) faults[faults.length] = {
4750
+ if (INTRINSICS.own(shape, "min") && shape.min !== void 0 && length < shape.min) faults[faults.length] = {
4165
4751
  reason: "constraint",
4166
4752
  path,
4167
4753
  expected: "array",
@@ -4169,7 +4755,7 @@ function buildArrayFaults(shape, length, path) {
4169
4755
  limit: shape.min,
4170
4756
  received: INTRINSICS.text(length)
4171
4757
  };
4172
- if (shape.max !== void 0 && length > shape.max) faults[faults.length] = {
4758
+ if (INTRINSICS.own(shape, "max") && shape.max !== void 0 && length > shape.max) faults[faults.length] = {
4173
4759
  reason: "constraint",
4174
4760
  path,
4175
4761
  expected: "array",
@@ -4219,7 +4805,8 @@ function selectClosestFaults(reports) {
4219
4805
  * A structural mapping used by {@link compileReporter} to fill a `Fault`'s
4220
4806
  * `expected` field and by {@link compileAuditor} to fill an `AuditFault`'s:
4221
4807
  * most shapes map to their own `category` (`numberShape` maps to
4222
- * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /
4808
+ * `'integer'` when `integer: true`, else `'number'`, and `stringShape` maps to
4809
+ * `'date'` when `date: true`, else `'string'`); `optionalShape` /
4223
4810
  * `nullableShape` project through to their inner shape's kind, and `rawShape`
4224
4811
  * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.
4225
4812
  *
@@ -4242,8 +4829,8 @@ function selectClosestFaults(reports) {
4242
4829
  function shapeToKind(shape) {
4243
4830
  return readValue(() => {
4244
4831
  switch (shape.category) {
4245
- case "string": return "string";
4246
- case "number": return shape.integer === true ? "integer" : "number";
4832
+ case "string": return INTRINSICS.own(shape, "date") && shape.date === true ? "date" : "string";
4833
+ case "number": return INTRINSICS.own(shape, "integer") && shape.integer === true ? "integer" : "number";
4247
4834
  case "boolean": return "boolean";
4248
4835
  case "null": return "null";
4249
4836
  case "literal": return "literal";
@@ -4251,6 +4838,7 @@ function shapeToKind(shape) {
4251
4838
  case "object": return "object";
4252
4839
  case "union": return "union";
4253
4840
  case "json": return "json";
4841
+ case "shape": return "shape";
4254
4842
  case "optional": return shapeToKind(shape.inner);
4255
4843
  case "nullable": return shapeToKind(shape.inner);
4256
4844
  case "raw": return "json";
@@ -4395,56 +4983,283 @@ for (const generator of [iterateIndices, encodeParts]) {
4395
4983
  INTRINSICS.freeze(generator.prototype);
4396
4984
  INTRINSICS.freeze(generator);
4397
4985
  }
4398
- // src/core/JSONCloner.ts
4399
4986
  /**
4400
- * Owns the state of one exact JSON snapshot operation.
4987
+ * Extracts a fault's path as its segments, reading a string path as one segment.
4988
+ *
4989
+ * @param fault - The fault to read
4990
+ * @returns The path's segments, empty at the root
4991
+ *
4992
+ * @example
4993
+ * ```ts
4994
+ * import { extractPath } from '@orkestrel/contract'
4995
+ *
4996
+ * extractPath({ reason: 'extra', path: ['page', 'typo'] }) // ['page', 'typo']
4997
+ * ```
4998
+ */
4999
+ function extractPath(fault) {
5000
+ return isString(fault.path) ? [fault.path] : fault.path;
5001
+ }
5002
+ /**
5003
+ * Extracts a schema's forms: the schema itself, then its union arms, so a read looks
5004
+ * through a nullable the same way everywhere.
5005
+ *
5006
+ * @param schema - The schema to read, or `undefined` where none was found
5007
+ * @returns The forms, empty when there is no schema
5008
+ *
5009
+ * @example
5010
+ * ```ts
5011
+ * import { extractForms } from '@orkestrel/contract'
5012
+ *
5013
+ * const object = { type: 'object' } as const
5014
+ * extractForms({ anyOf: [object] }) // [{ anyOf: [object] }, object]
5015
+ * ```
5016
+ */
5017
+ function extractForms(schema) {
5018
+ if (schema === void 0) return [];
5019
+ const anyOf = INTRINSICS.own(schema, "anyOf") ? schema.anyOf : void 0;
5020
+ const oneOf = INTRINSICS.own(schema, "oneOf") ? schema.oneOf : void 0;
5021
+ return [schema, ...anyOf ?? oneOf ?? []];
5022
+ }
5023
+ /**
5024
+ * Extracts the part of a schema a path reaches, through properties, array items, record values,
5025
+ * and the arms of a union.
4401
5026
  *
4402
5027
  * @remarks
4403
- * Construction retains the source without observing it. The first
4404
- * {@link clone} call performs one iterative descriptor walk and settles
4405
- * permanently. Success replays the exact frozen root; failure rethrows the
4406
- * exact class-owned error. Nonredirectable terminal failure releases partial
4407
- * traversal working state while retaining the source and exact error. Reentry
4408
- * poisons the active operation and every later call with one shared cause-free
4409
- * error.
5028
+ * Each path segment takes one step, so a union that nests itself cannot hold the walk. Only a
5029
+ * schema's own `properties` keys match, so `constructor` reaches nothing. The walk keeps every
5030
+ * matching union declaration until the end; differing declarations yield no schema. Independently
5031
+ * built declarations agree when their canonical JSON encodings agree.
4410
5032
  *
4411
- * @param value - The unknown value to retain for cloning
5033
+ * @param schema - The schema to walk
5034
+ * @param path - The segments to follow
5035
+ * @returns The schema at that path, or `undefined` where no declaration or no agreement exists
4412
5036
  *
4413
5037
  * @example
4414
5038
  * ```ts
4415
- * const source = { settings: { enabled: true } }
4416
- * const cloner = new JSONCloner(source)
4417
- * const clone = cloner.clone()
4418
- * source.settings.enabled = false
4419
- * cloner.clone() === clone // true
5039
+ * import { extractSchema } from '@orkestrel/contract'
5040
+ *
5041
+ * const schema = { type: 'object', properties: { limit: { type: 'number' } } } as const
5042
+ * extractSchema(schema, ['limit']) // { type: 'number' }
4420
5043
  * ```
4421
5044
  */
4422
- var JSONCloner = class JSONCloner {
4423
- static #weakSet = WeakSet;
4424
- static #emptyPending = [];
4425
- #source;
4426
- #owned;
4427
- #active;
4428
- #pending;
4429
- #produced;
4430
- #poison;
4431
- #terminal;
4432
- constructor(value) {
4433
- this.#source = value;
4434
- this.#owned = new JSONCloner.#weakSet();
4435
- this.#active = new JSONCloner.#weakSet();
4436
- this.#pending = [];
4437
- this.#produced = 0;
4438
- this.#poison = void 0;
4439
- this.#terminal = void 0;
5045
+ function extractSchema(schema, path) {
5046
+ const nodes = path.reduce((parents, key) => Array.from(new Set(parents.flatMap((node) => extractForms(node)).map((form) => {
5047
+ const properties = INTRINSICS.own(form, "properties") ? form.properties : void 0;
5048
+ const additional = INTRINSICS.own(form, "additionalProperties") ? form.additionalProperties : void 0;
5049
+ return properties !== void 0 && INTRINSICS.own(properties, key) ? properties[key] : isRecord(additional) ? additional : INTRINSICS.own(form, "items") ? form.items : void 0;
5050
+ }).filter((child) => child !== void 0))), [schema]);
5051
+ const first = nodes[0];
5052
+ if (nodes.length < 2) return first;
5053
+ const encoded = canonicalStringify(first);
5054
+ return encoded !== void 0 && nodes.every((node) => canonicalStringify(node) === encoded) ? first : void 0;
5055
+ }
5056
+ /**
5057
+ * Renders a path as text, encoding what a caller could have sent and eliding the middle of a long
5058
+ * one.
5059
+ *
5060
+ * @remarks
5061
+ * A segment that is not a plain identifier is JSON-encoded and length-capped, because a key the
5062
+ * caller sent is untrusted text. A path of more than four segments past 120 characters keeps its
5063
+ * first segment and its last three.
5064
+ *
5065
+ * @param path - The segments to render
5066
+ * @returns The segments joined with `.`, empty at the root
5067
+ *
5068
+ * @example
5069
+ * ```ts
5070
+ * import { renderPath } from '@orkestrel/contract'
5071
+ *
5072
+ * renderPath(['rows', '0', 'a b']) // 'rows.0."a b"'
5073
+ * ```
5074
+ */
5075
+ function renderPath(path) {
5076
+ const segments = path.map((segment) => /^[\w$-]{1,64}$/u.test(segment) ? segment : preview(segment));
5077
+ const text = segments.join(".");
5078
+ return segments.length <= 4 || text.length <= 120 ? text : [
5079
+ ...segments.slice(0, 1),
5080
+ "…",
5081
+ ...segments.slice(-3)
5082
+ ].join(".");
5083
+ }
5084
+ /**
5085
+ * Renders a list as text, naming at most `FAULT_LIST_LIMIT` of its entries and counting the rest.
5086
+ *
5087
+ * @param entries - The rendered entries
5088
+ * @returns The entries joined with `, `
5089
+ *
5090
+ * @example
5091
+ * ```ts
5092
+ * import { renderList } from '@orkestrel/contract'
5093
+ *
5094
+ * renderList(['city', 'units']) // 'city, units'
5095
+ * ```
5096
+ */
5097
+ function renderList(entries) {
5098
+ const listed = entries.slice(0, 12).join(", ");
5099
+ return entries.length > 12 ? `${listed} and ${String(entries.length - 12)} more` : listed;
5100
+ }
5101
+ /**
5102
+ * Renders a schema as a short summary of what to send, such as `{"city": string, "note"?: string}`.
5103
+ *
5104
+ * @remarks
5105
+ * An object lists its required keys first and marks the rest with `?`, at most `FAULT_LIST_LIMIT`
5106
+ * of them. A leaf or array keeps its numeric bounds, pattern, and format, a union joins its forms with ` | `,
5107
+ * and a schema that says nothing reads `any`. Each nested form takes half the room of its parent, and
5108
+ * below 16 characters a form stops at its type, so a schema that holds itself still ends. Text past
5109
+ * `room` is cut and closes with `…`. A type word outside JSON Schema's vocabulary is encoded.
5110
+ *
5111
+ * @param schema - The schema to summarize
5112
+ * @param room - The characters the summary can take. Default: `FAULT_SCHEMA_LIMIT`
5113
+ * @returns The summary
5114
+ *
5115
+ * @example
5116
+ * ```ts
5117
+ * import { renderForm } from '@orkestrel/contract'
5118
+ *
5119
+ * renderForm({ type: 'object', properties: { zip: { type: 'number' } }, required: ['zip'] }) // '{"zip": number}'
5120
+ * ```
5121
+ */
5122
+ function renderForm(schema, room = 160) {
5123
+ const deep = room >= 16;
5124
+ const inner = Math.floor(room / 2);
5125
+ const anyOf = INTRINSICS.own(schema, "anyOf") ? schema.anyOf : void 0;
5126
+ const oneOf = INTRINSICS.own(schema, "oneOf") ? schema.oneOf : void 0;
5127
+ const forms = anyOf ?? oneOf;
5128
+ const required = (INTRINSICS.own(schema, "required") ? schema.required : void 0) ?? [];
5129
+ const entries = Object.entries((INTRINSICS.own(schema, "properties") ? schema.properties : void 0) ?? {});
5130
+ const type = INTRINSICS.own(schema, "type") ? schema.type : void 0;
5131
+ const enumeration = INTRINSICS.own(schema, "enum") ? schema.enum : void 0;
5132
+ const additional = INTRINSICS.own(schema, "additionalProperties") ? schema.additionalProperties : void 0;
5133
+ 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)}`);
5134
+ const left = entries.length - listed.length;
5135
+ const child = type === "array" ? INTRINSICS.own(schema, "items") ? schema.items : void 0 : isRecord(additional) ? additional : void 0;
5136
+ const bounds = Object.entries(schema).filter(([key]) => [
5137
+ "minLength",
5138
+ "maxLength",
5139
+ "minimum",
5140
+ "maximum",
5141
+ "minItems",
5142
+ "maxItems",
5143
+ "pattern",
5144
+ "format"
5145
+ ].includes(key)).map(([key, value]) => `${key} ${preview(value)}`);
5146
+ 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(", ")}}` : [
5147
+ type === void 0 ? entries.length > 0 ? "object" : "any" : JSON_SCHEMA_TYPES.some((name) => name === type) ? type : preview(type),
5148
+ ...deep && child !== void 0 ? [` of ${renderForm(child, inner)}`] : [],
5149
+ ...bounds.length > 0 ? [` (${bounds.join(", ")})`] : []
5150
+ ].join(""), room);
5151
+ }
5152
+ /**
5153
+ * Describes one fault as the line a caller corrects from, naming what to send where the schema
5154
+ * says.
5155
+ *
5156
+ * @remarks
5157
+ * Each line opens with the fault's path (or `value` at the root) and reason. An `extra` fault lists
5158
+ * its parent's keys only when the declaring arms agree. A literal names candidates only where
5159
+ * the declarations agree; lists are deduplicated and bounded. A received preview stays as written
5160
+ * within PREVIEW_LIMIT and without control or line-separator characters; otherwise it is encoded
5161
+ * through preview. Received, constraint, and limit details read only own fields. A `variant` or
5162
+ * `oneOf` fault says that the value matches none of the declared forms, or several where one must
5163
+ * match, and summarizes each form through `renderForm`. It names no fault of any one form, because
5164
+ * none of them holds for the others. Those summaries share half of `FAULT_TEXT_LIMIT`.
5165
+ *
5166
+ * @param fault - The fault to describe
5167
+ * @param schema - The compiled schema the fault's path reads
5168
+ * @returns The line, with no line break
5169
+ *
5170
+ * @example
5171
+ * ```ts
5172
+ * import { describeFaultLine } from '@orkestrel/contract'
5173
+ *
5174
+ * describeFaultLine({ reason: 'missing', path: ['left'], expected: 'number' }, {}) // 'left: missing; expected number'
5175
+ * ```
5176
+ */
5177
+ function describeFaultLine(fault, schema) {
5178
+ const path = extractPath(fault);
5179
+ const head = `${renderPath(path) || "value"}: ${fault.reason}`;
5180
+ if (fault.reason === "extra") {
5181
+ 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 ?? {}));
5182
+ const first = declarations[0] ?? [];
5183
+ const keys = declarations.every((declared) => declared.length === first.length && declared.every((key) => first.includes(key))) ? first : [];
5184
+ 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])))}`;
5185
+ }
5186
+ const node = extractSchema(schema, path);
5187
+ const anyOf = node !== void 0 && INTRINSICS.own(node, "anyOf") ? node.anyOf : void 0;
5188
+ const oneOf = node !== void 0 && INTRINSICS.own(node, "oneOf") ? node.oneOf : void 0;
5189
+ if (fault.reason === "variant" || fault.reason === "oneOf") {
5190
+ const count = fault.reason === "variant" ? fault.variants : oneOf?.length;
5191
+ const forms = count === void 0 ? "the declared forms" : `the ${String(count)} declared forms`;
5192
+ 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}`;
5193
+ const declared = anyOf ?? oneOf ?? [];
5194
+ const shown = declared.slice(0, 12);
5195
+ const room = Math.min(160, Math.floor(FAULT_TEXT_LIMIT / 2 / Math.max(shown.length, 1)));
5196
+ const more = declared.length - shown.length;
5197
+ const summary = shown.length === 0 ? "" : `, one of: ${shown.map((form) => renderForm(form, room)).join(" or ")}${more > 0 ? ` and ${String(more)} more` : ""}`;
5198
+ 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}`;
5199
+ }
5200
+ 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] : []]) : [];
5201
+ const description = node !== void 0 && INTRINSICS.own(node, "description") ? node.description : void 0;
5202
+ const received = "received" in fault && INTRINSICS.own(fault, "received") ? fault.received : void 0;
5203
+ const shown = received !== void 0 && received.length <= 64 && !/[\p{Cc}\p{Zl}\p{Zp}]/u.test(received) ? received : preview(received);
5204
+ return [
5205
+ head,
5206
+ `expected ${fault.expected}`,
5207
+ ...received !== void 0 ? [`received ${shown}`] : [],
5208
+ ..."constraint" in fault && INTRINSICS.own(fault, "constraint") ? [`constraint ${fault.constraint}`] : [],
5209
+ ..."limit" in fault && INTRINSICS.own(fault, "limit") && fault.limit !== void 0 ? [`limit ${preview(fault.limit)}`] : [],
5210
+ ...description === void 0 ? [] : [`description ${preview(description)}`],
5211
+ ...candidates.length > 0 ? [`send one of ${renderList(Array.from(new Set(candidates), (value) => preview(value)))}`] : []
5212
+ ].join("; ");
5213
+ }
5214
+ // src/core/JSONCloner.ts
5215
+ /**
5216
+ * Owns the state of one exact JSON snapshot operation.
5217
+ *
5218
+ * @remarks
5219
+ * Construction retains the source without observing it. The first
5220
+ * {@link clone} call performs one iterative descriptor walk and settles
5221
+ * permanently. Success replays the exact frozen root; failure rethrows the
5222
+ * exact class-owned error. Nonredirectable terminal failure releases partial
5223
+ * traversal working state while retaining the source and exact error. Reentry
5224
+ * poisons the active operation and every later call with one shared cause-free
5225
+ * error.
5226
+ *
5227
+ * @param value - The unknown value to retain for cloning
5228
+ *
5229
+ * @example
5230
+ * ```ts
5231
+ * const source = { settings: { enabled: true } }
5232
+ * const cloner = new JSONCloner(source)
5233
+ * const clone = cloner.clone()
5234
+ * source.settings.enabled = false
5235
+ * cloner.clone() === clone // true
5236
+ * ```
5237
+ */
5238
+ var JSONCloner = class JSONCloner {
5239
+ static #weakSet = WeakSet;
5240
+ static #emptyPending = [];
5241
+ #source;
5242
+ #owned;
5243
+ #active;
5244
+ #pending;
5245
+ #poison;
5246
+ #terminal;
5247
+ constructor(value) {
5248
+ this.#source = value;
5249
+ this.#owned = new JSONCloner.#weakSet();
5250
+ this.#active = new JSONCloner.#weakSet();
5251
+ this.#pending = [];
5252
+ this.#poison = void 0;
5253
+ this.#terminal = void 0;
4440
5254
  }
4441
5255
  /**
4442
5256
  * Clones the retained source into exact, deeply frozen JSON data.
4443
5257
  *
5258
+ * @param budget - Remaining nodes shared with an enclosing ownership operation
4444
5259
  * @returns The settled JSON snapshot
4445
5260
  * @throws {ContractError} When the source is inexact, cyclic, unreadable, or cloning is reentered
4446
5261
  */
4447
- clone() {
5262
+ clone(budget = { left: CLONE_NODE_LIMIT }) {
4448
5263
  const terminal = this.#terminal;
4449
5264
  if (terminal !== void 0) {
4450
5265
  if (isSuccess(terminal)) return terminal.value;
@@ -4456,7 +5271,7 @@ var JSONCloner = class JSONCloner {
4456
5271
  throw poison;
4457
5272
  }
4458
5273
  this.#poison = this.#create("JSONCloner.clone: JSON cloning may not be reentered");
4459
- const outcome = attempt(() => this.#execute());
5274
+ const outcome = attempt(() => this.#execute(budget));
4460
5275
  const interruption = this.#terminal;
4461
5276
  if (interruption !== void 0) {
4462
5277
  if (isSuccess(interruption)) return interruption.value;
@@ -4474,12 +5289,14 @@ var JSONCloner = class JSONCloner {
4474
5289
  this.#pending = JSONCloner.#emptyPending;
4475
5290
  throw error;
4476
5291
  }
4477
- #execute() {
4478
- const root = this.#capture(this.#source);
4479
- this.#drain();
5292
+ #execute(budget) {
5293
+ if (!INTRINSICS.safe(budget.left)) this.#refuse("cloneJSONValue: invalid node budget");
5294
+ budget.left = INTRINSICS.min(budget.left, CLONE_NODE_LIMIT);
5295
+ const root = this.#capture(this.#source, budget);
5296
+ this.#drain(budget);
4480
5297
  return root;
4481
5298
  }
4482
- #drain() {
5299
+ #drain(budget) {
4483
5300
  while (this.#pending.length > 0) {
4484
5301
  const frame = this.#pending[this.#pending.length - 1];
4485
5302
  if (frame === void 0) continue;
@@ -4492,7 +5309,7 @@ var JSONCloner = class JSONCloner {
4492
5309
  continue;
4493
5310
  }
4494
5311
  frame.index += 1;
4495
- const clone = this.#capture(entry[1]);
5312
+ const clone = this.#capture(entry[1], budget);
4496
5313
  INTRINSICS.define(frame.clone, entry[0], {
4497
5314
  value: clone,
4498
5315
  enumerable: true,
@@ -4501,9 +5318,9 @@ var JSONCloner = class JSONCloner {
4501
5318
  });
4502
5319
  }
4503
5320
  }
4504
- #capture(value) {
4505
- this.#produced += 1;
4506
- if (this.#produced > 262144) this.#refuse("cloneJSONValue: snapshot exceeds the node limit");
5321
+ #capture(value, budget) {
5322
+ budget.left -= 1;
5323
+ if (budget.left < 0) this.#refuse(`cloneJSONValue: snapshot exceeds the node limit ${CLONE_NODE_LIMIT}`, CLONE_NODE_LIMIT);
4507
5324
  if (value === null || typeof value === "string" || typeof value === "boolean") return value;
4508
5325
  if (typeof value === "number") {
4509
5326
  if (INTRINSICS.finite(value)) return value;
@@ -4566,10 +5383,13 @@ var JSONCloner = class JSONCloner {
4566
5383
  return [key, descriptor.value];
4567
5384
  });
4568
5385
  }
4569
- #create(message) {
5386
+ #create(message, limit) {
4570
5387
  const error = new ContractError(message, {
4571
5388
  code: "clone",
4572
- context: { shape: "json" }
5389
+ context: {
5390
+ shape: "json",
5391
+ ...limit === void 0 ? {} : { limit }
5392
+ }
4573
5393
  });
4574
5394
  admitVisited(this.#owned, error);
4575
5395
  return error;
@@ -4577,10 +5397,10 @@ var JSONCloner = class JSONCloner {
4577
5397
  #owns(error) {
4578
5398
  return isObject(error) && matchesVisited(this.#owned, error);
4579
5399
  }
4580
- #refuse(message) {
5400
+ #refuse(message, limit) {
4581
5401
  const terminal = this.#terminal;
4582
5402
  if (terminal !== void 0 && isFailure(terminal)) throw terminal.error;
4583
- throw this.#create(message);
5403
+ throw this.#create(message, limit);
4584
5404
  }
4585
5405
  static {
4586
5406
  INTRINSICS.freeze(JSONCloner.#emptyPending);
@@ -4786,7 +5606,24 @@ var SchemaCloner = class SchemaCloner {
4786
5606
  var ShapePass = class ShapePass {
4787
5607
  static #weakSet = WeakSet;
4788
5608
  static #weakMap = WeakMap;
5609
+ static #arrays = Array.prototype;
5610
+ static #pop = Array.prototype.pop;
5611
+ static #iterators = INTRINSICS.prototype(INTRINSICS.reflect.apply(INTRINSICS.indices, [], []));
5612
+ static #blank = INTRINSICS.freeze(new INTRINSICS.pattern(""));
5613
+ static #fields = [
5614
+ "min",
5615
+ "max",
5616
+ "pattern",
5617
+ "date",
5618
+ "description",
5619
+ "integer",
5620
+ "additionalProperties",
5621
+ "mode",
5622
+ "default"
5623
+ ];
5624
+ static #seals = new ShapePass.#weakMap();
4789
5625
  #source;
5626
+ #budget;
4790
5627
  #stack = [];
4791
5628
  #path = [];
4792
5629
  #active = new ShapePass.#weakSet();
@@ -4796,20 +5633,91 @@ var ShapePass = class ShapePass {
4796
5633
  #height = [];
4797
5634
  #reach = [];
4798
5635
  #via = [];
5636
+ #within = [];
4799
5637
  #counts = [];
4800
5638
  #schemas = new ShapePass.#weakMap();
4801
5639
  #children = [];
4802
5640
  #category;
4803
5641
  #raw = 0;
5642
+ #defaulted = false;
5643
+ #open = false;
4804
5644
  #structure;
4805
5645
  #cycle;
4806
5646
  #domain;
4807
- #clock = 0;
4808
- #oldest = 0;
4809
- #trail = [];
4810
5647
  #poison;
4811
- constructor(shape) {
5648
+ constructor(shape, budget) {
4812
5649
  this.#source = shape;
5650
+ this.#budget = budget;
5651
+ }
5652
+ /**
5653
+ * Validates a node fresh from a builder, freezes it, and records what the walk found.
5654
+ *
5655
+ * @remarks
5656
+ * The node's own fields are always observed, and each child is answered from its
5657
+ * seal rather than walked. Anything short of a clean answer takes the whole walk
5658
+ * instead, which is what authors every refusal, so a refusal reads the same and
5659
+ * fires at the same call as it would with no seals at all. That second look is safe
5660
+ * because the first read nothing a caller wrote: the node is this package's own
5661
+ * literal, and a child with no seal stops the survey before it is read.
5662
+ *
5663
+ * @param shape - The builder's fresh node, which no caller has seen
5664
+ * @param check - What the whole walk validates, when the node is only legal in a slot
5665
+ * @returns The frozen node
5666
+ * @throws {ContractError} When the node is refused
5667
+ */
5668
+ static seal(shape, check = shape) {
5669
+ const frozen = INTRINSICS.freeze(shape);
5670
+ if (!new ShapePass(shape).#survey(check === shape ? 0 : 1)) new ShapePass(check, { left: CLONE_NODE_LIMIT }).validate();
5671
+ return frozen;
5672
+ }
5673
+ /**
5674
+ * Reports the expansion of a sealed node a compiler can take as it stands.
5675
+ *
5676
+ * @remarks
5677
+ * `undefined` sends the caller to its own ownership and validation: the node was
5678
+ * never sealed, an inherited field would answer a walk of it, or it is an `optional`
5679
+ * node, which a walk refuses as a root.
5680
+ *
5681
+ * @param shape - The declaration to look up
5682
+ * @returns The expansion a walk would report, or `undefined`
5683
+ */
5684
+ static expansionOf(shape) {
5685
+ if (ShapePass.polluted()) return void 0;
5686
+ const seal = INTRINSICS.reflect.apply(INTRINSICS.recall, ShapePass.#seals, [shape]);
5687
+ return seal === void 0 || seal.category === "optional" ? void 0 : seal.count;
5688
+ }
5689
+ /**
5690
+ * Reports whether a walk could answer differently from a seal.
5691
+ *
5692
+ * @remarks
5693
+ * A field a node may leave out reads through to `Object.prototype`, which is a
5694
+ * verdict about the declaration, and a {@link tampered} host breaks a walk into a
5695
+ * refusal a seal would otherwise skip.
5696
+ *
5697
+ * @returns True when a walk has to answer rather than a seal
5698
+ */
5699
+ static polluted() {
5700
+ if (ShapePass.tampered()) return true;
5701
+ return INTRINSICS.reflect.apply(INTRINSICS.some, ShapePass.#fields, [(field) => INTRINSICS.own(INTRINSICS.base, field)]);
5702
+ }
5703
+ /**
5704
+ * Reports whether a member a walk or a compile runs on has been replaced.
5705
+ *
5706
+ * @remarks
5707
+ * An index on either prototype, reached by array writes, a replaced `pop` or array
5708
+ * iterator `next`, and a flag getter a pattern's `flags` reads. An array's `length`
5709
+ * always passes its highest index, and own keys list an index first, so one read
5710
+ * answers for every index, and a name that merely opens with a digit only costs a walk.
5711
+ *
5712
+ * @returns True when the host is not the one this package loaded on
5713
+ */
5714
+ static tampered() {
5715
+ if (ShapePass.#arrays.length !== 0) return true;
5716
+ const first = INTRINSICS.reflect.members(INTRINSICS.base)[0];
5717
+ if (typeof first === "string" && first >= "0" && first < ":") return true;
5718
+ if (INTRINSICS.describe(ShapePass.#arrays, "pop")?.value !== ShapePass.#pop) return true;
5719
+ if (INTRINSICS.describe(ShapePass.#iterators, "next")?.value !== INTRINSICS.advance) return true;
5720
+ return !holds(() => readPatternFlags(ShapePass.#blank) === "");
4813
5721
  }
4814
5722
  /** Poisons this pass and throws the same refusal on every reentry. */
4815
5723
  interrupt() {
@@ -4831,6 +5739,34 @@ var ShapePass = class ShapePass {
4831
5739
  cause: outcome.error
4832
5740
  });
4833
5741
  }
5742
+ #survey(lift) {
5743
+ if (ShapePass.polluted()) return false;
5744
+ const shape = this.#source;
5745
+ if (!isRecord(shape)) return false;
5746
+ const outcome = attempt(() => this.#observe(shape, 0));
5747
+ if (isFailure(outcome) || !outcome.value || this.#domain !== void 0) return false;
5748
+ const seal = {
5749
+ category: shape.category,
5750
+ reach: this.#raw,
5751
+ count: 1,
5752
+ defaulted: this.#defaulted,
5753
+ held: this.#defaulted
5754
+ };
5755
+ for (const index of iterateIndices(() => this.#children.length)) {
5756
+ const child = this.#children[index];
5757
+ const known = INTRINSICS.reflect.apply(INTRINSICS.recall, ShapePass.#seals, [child?.shape]);
5758
+ if (child === void 0 || known === void 0) return false;
5759
+ if (known.category === "optional" && !child.optional) return false;
5760
+ if (known.held && shape.category === "union") return false;
5761
+ if (known.defaulted && this.#open) return false;
5762
+ seal.reach = INTRINSICS.max(seal.reach, known.reach + 1);
5763
+ seal.count += known.count;
5764
+ seal.held ||= known.held;
5765
+ }
5766
+ if (seal.reach + lift > 512) return false;
5767
+ INTRINSICS.reflect.apply(INTRINSICS.retain, ShapePass.#seals, [shape, seal]);
5768
+ return true;
5769
+ }
4834
5770
  #execute() {
4835
5771
  this.#stack[this.#stack.length] = {
4836
5772
  operation: "enter",
@@ -4852,9 +5788,11 @@ var ShapePass = class ShapePass {
4852
5788
  this.#path.length -= frame.segments;
4853
5789
  return;
4854
5790
  }
4855
- const segments = (frame.first === void 0 ? 0 : 1) + (frame.second === void 0 ? 0 : 1);
4856
- if (frame.first !== void 0) this.#path[this.#path.length] = frame.first;
4857
- if (frame.second !== void 0) this.#path[this.#path.length] = frame.second;
5791
+ const first = INTRINSICS.own(frame, "first") ? frame.first : void 0;
5792
+ const second = INTRINSICS.own(frame, "second") ? frame.second : void 0;
5793
+ const segments = (first === void 0 ? 0 : 1) + (second === void 0 ? 0 : 1);
5794
+ if (first !== void 0) this.#path[this.#path.length] = first;
5795
+ if (second !== void 0) this.#path[this.#path.length] = second;
4858
5796
  const current = frame.shape;
4859
5797
  if (typeof current !== "object" || current === null || !isRecord(current)) {
4860
5798
  this.#structure ??= new ContractError("validateShape: every structural child must be a shape", {
@@ -4881,7 +5819,10 @@ var ShapePass = class ShapePass {
4881
5819
  this.#children = [];
4882
5820
  this.#category = void 0;
4883
5821
  this.#raw = 0;
5822
+ this.#defaulted = false;
5823
+ this.#open = false;
4884
5824
  const outcome = attempt(() => this.#observe(current, frame.depth));
5825
+ this.#spend(0);
4885
5826
  if (isFailure(outcome) || !outcome.value) {
4886
5827
  this.#structure ??= new ContractError("validateShape: every node must be a recognized shape", {
4887
5828
  code: "structure",
@@ -4898,7 +5839,7 @@ var ShapePass = class ShapePass {
4898
5839
  if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) return this.#refuse("validateShape: every node must be a recognized shape");
4899
5840
  const category = current.category;
4900
5841
  if (current.category !== category || descriptor.value !== category) return this.#refuse("validateShape: every node must be a recognized shape");
4901
- const fields = this.#recognize(category);
5842
+ const fields = typeof category === "string" && INTRINSICS.own(SHAPE_FIELDS, category) ? SHAPE_FIELDS[category] : void 0;
4902
5843
  if (fields === void 0) return this.#refuse("validateShape: every node must be a recognized shape");
4903
5844
  this.#category = category;
4904
5845
  if (!this.#scan(current, fields)) return false;
@@ -4927,45 +5868,6 @@ var ShapePass = class ShapePass {
4927
5868
  }
4928
5869
  return this.#populate(current);
4929
5870
  }
4930
- #recognize(category) {
4931
- switch (category) {
4932
- case "string": return [
4933
- "min",
4934
- "max",
4935
- "pattern",
4936
- "description"
4937
- ];
4938
- case "number": return [
4939
- "integer",
4940
- "min",
4941
- "max",
4942
- "description"
4943
- ];
4944
- case "boolean":
4945
- case "null":
4946
- case "json": return ["description"];
4947
- case "literal": return ["values", "description"];
4948
- case "array": return [
4949
- "items",
4950
- "min",
4951
- "max",
4952
- "description"
4953
- ];
4954
- case "object": return [
4955
- "properties",
4956
- "additionalProperties",
4957
- "description"
4958
- ];
4959
- case "union": return [
4960
- "variants",
4961
- "mode",
4962
- "description"
4963
- ];
4964
- case "optional":
4965
- case "nullable": return ["inner"];
4966
- case "raw": return ["schema"];
4967
- }
4968
- }
4969
5871
  #scan(current, fields) {
4970
5872
  for (const fieldIndex of iterateIndices(() => fields.length)) {
4971
5873
  const field = fields[fieldIndex];
@@ -4988,9 +5890,14 @@ var ShapePass = class ShapePass {
4988
5890
  }
4989
5891
  #constrain(current) {
4990
5892
  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");
5893
+ if (current.category === "optional" && INTRINSICS.own(current, "default")) {
5894
+ if (!holds(() => matchesJSONValue(current.default, new ShapePass.#weakSet(), this.#budget))) return this.#refuse("validateShape: an optional default must be a JSON value", "default");
5895
+ this.#defaulted = true;
5896
+ }
4991
5897
  if (current.category === "string") {
4992
5898
  if (current.min !== void 0 && typeof current.min !== "number") return this.#refuse("validateShape: string min must be a number", "min");
4993
5899
  if (current.max !== void 0 && typeof current.max !== "number") return this.#refuse("validateShape: string max must be a number", "max");
5900
+ if (current.date !== void 0 && typeof current.date !== "boolean") return this.#refuse("validateShape: string date must be a boolean", "date");
4994
5901
  if (current.pattern !== void 0) {
4995
5902
  const pattern = current.pattern;
4996
5903
  if (!isRegExp(pattern)) return this.#refuse("validateShape: string pattern must be a RegExp", "pattern");
@@ -5023,7 +5930,7 @@ var ShapePass = class ShapePass {
5023
5930
  received: INTRINSICS.text(current.max)
5024
5931
  }
5025
5932
  });
5026
- 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", {
5933
+ 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", {
5027
5934
  code: "range",
5028
5935
  context: {
5029
5936
  path: pathOf(this.#path),
@@ -5042,7 +5949,7 @@ var ShapePass = class ShapePass {
5042
5949
  }
5043
5950
  if (current.category === "array" && current.min !== void 0 && typeof current.min !== "number") return this.#refuse("validateShape: array min must be a number", "min");
5044
5951
  if (current.category === "array" && current.max !== void 0 && typeof current.max !== "number") return this.#refuse("validateShape: array max must be a number", "max");
5045
- 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", {
5952
+ 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", {
5046
5953
  code: "bound",
5047
5954
  context: {
5048
5955
  path: pathOf(this.#path),
@@ -5051,7 +5958,7 @@ var ShapePass = class ShapePass {
5051
5958
  received: INTRINSICS.text(current.min)
5052
5959
  }
5053
5960
  });
5054
- 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", {
5961
+ 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", {
5055
5962
  code: "bound",
5056
5963
  context: {
5057
5964
  path: pathOf(this.#path),
@@ -5060,7 +5967,7 @@ var ShapePass = class ShapePass {
5060
5967
  received: INTRINSICS.text(current.max)
5061
5968
  }
5062
5969
  });
5063
- 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", {
5970
+ 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", {
5064
5971
  code: "range",
5065
5972
  context: {
5066
5973
  path: pathOf(this.#path),
@@ -5082,7 +5989,7 @@ var ShapePass = class ShapePass {
5082
5989
  });
5083
5990
  }
5084
5991
  #restrict(current, source = "", flags = "") {
5085
- 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", {
5992
+ 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", {
5086
5993
  code: "bound",
5087
5994
  context: {
5088
5995
  path: pathOf(this.#path),
@@ -5091,7 +5998,7 @@ var ShapePass = class ShapePass {
5091
5998
  received: INTRINSICS.text(current.min)
5092
5999
  }
5093
6000
  });
5094
- 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", {
6001
+ 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", {
5095
6002
  code: "bound",
5096
6003
  context: {
5097
6004
  path: pathOf(this.#path),
@@ -5108,15 +6015,31 @@ var ShapePass = class ShapePass {
5108
6015
  received: `/${source}/${flags}`
5109
6016
  }
5110
6017
  });
5111
- 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", {
6018
+ 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", {
5112
6019
  code: "range",
5113
6020
  context: {
5114
6021
  path: pathOf(this.#path),
5115
6022
  shape: "string"
5116
6023
  }
5117
6024
  });
6025
+ if (this.#domain === void 0 && current.date === true && current.pattern !== void 0) this.#domain = new ContractError("validateShape: a string shape declares date or pattern, never both", {
6026
+ code: "pattern",
6027
+ context: {
6028
+ path: pathOf(this.#path),
6029
+ shape: "string"
6030
+ }
6031
+ });
6032
+ if (this.#domain === void 0 && current.date === true && (typeof current.min === "number" && current.min > 10 || typeof current.max === "number" && current.max < 10)) this.#domain = new ContractError(`validateShape: a date string shape needs min and max to admit length 10`, {
6033
+ code: "range",
6034
+ context: {
6035
+ path: pathOf(this.#path),
6036
+ shape: "string",
6037
+ limit: 10
6038
+ }
6039
+ });
5118
6040
  }
5119
6041
  #inspect(source) {
6042
+ if (this.#structure !== void 0) return true;
5120
6043
  if (!isRecord(source)) return this.#refuse("validateShape: raw schema must be a plain record", "schema");
5121
6044
  const active = new ShapePass.#weakSet();
5122
6045
  const stack = [{
@@ -5131,24 +6054,27 @@ var ShapePass = class ShapePass {
5131
6054
  this.#settleSchema(frame.schema, frame.nested);
5132
6055
  continue;
5133
6056
  }
6057
+ const first = INTRINSICS.own(frame, "first") ? frame.first : void 0;
6058
+ const second = INTRINSICS.own(frame, "second") ? frame.second : void 0;
5134
6059
  const schema = frame.schema;
5135
- if (!isRecord(schema)) return this.#refuse("validateShape: every raw schema child must be a plain record", "schema");
5136
- if (matchesVisited(active, schema)) return this.#refuse("validateShape: a raw schema may not contain a cycle", "schema");
6060
+ if (!isRecord(schema)) return this.#refuseSchema("validateShape: every raw schema child must be a plain record", stack, first, second, void 0);
6061
+ if (matchesVisited(active, schema)) return this.#refuseSchema("validateShape: a raw schema may not contain a cycle", stack, first, second, void 0);
5137
6062
  if (INTRINSICS.reflect.apply(INTRINSICS.recall, this.#schemas, [schema]) !== void 0) continue;
5138
6063
  admitVisited(active, schema);
5139
6064
  const keyList = INTRINSICS.keys(schema);
5140
6065
  for (const keyIndex of iterateIndices(() => keyList.length)) {
5141
6066
  const key = keyList[keyIndex];
5142
6067
  if (key === void 0) continue;
5143
- 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");
6068
+ 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);
5144
6069
  }
5145
- const category = schema.type;
5146
- 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");
5147
- if (schema.description !== void 0 && typeof schema.description !== "string") return this.#refuse("validateShape: raw schema description must be a string", "schema");
5148
- if (schema.format !== void 0 && typeof schema.format !== "string") return this.#refuse("validateShape: raw schema format must be a string", "schema");
5149
- if (schema.pattern !== void 0) {
5150
- if (typeof schema.pattern !== "string") return this.#refuse("validateShape: raw schema pattern must be a string", "schema");
5151
- if (isFailure(attempt(() => INTRINSICS.reflect.apply(INTRINSICS.pattern, void 0, [schema.pattern])))) return this.#refuse("validateShape: raw schema pattern must be valid", "schema");
6070
+ const category = INTRINSICS.own(schema, "type") ? schema.type : void 0;
6071
+ 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");
6072
+ 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");
6073
+ if (INTRINSICS.own(schema, "default") && !isJSONValue(schema.default)) return this.#refuseSchema("validateShape: raw schema default must be a JSON value", stack, first, second, "default");
6074
+ 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");
6075
+ if (INTRINSICS.own(schema, "pattern") && schema.pattern !== void 0) {
6076
+ if (typeof schema.pattern !== "string") return this.#refuseSchema("validateShape: raw schema pattern must be a string", stack, first, second, "pattern");
6077
+ 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");
5152
6078
  }
5153
6079
  const lengthList = [
5154
6080
  "minLength",
@@ -5159,77 +6085,95 @@ var ShapePass = class ShapePass {
5159
6085
  for (const lengthIndex of iterateIndices(() => lengthList.length)) {
5160
6086
  const key = lengthList[lengthIndex];
5161
6087
  if (key === void 0) continue;
5162
- const value = schema[key];
5163
- 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");
6088
+ const value = INTRINSICS.own(schema, key) ? schema[key] : void 0;
6089
+ 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);
5164
6090
  }
5165
6091
  const rangeList = ["minimum", "maximum"];
5166
6092
  for (const rangeIndex of iterateIndices(() => rangeList.length)) {
5167
6093
  const key = rangeList[rangeIndex];
5168
6094
  if (key === void 0) continue;
5169
- const value = schema[key];
5170
- if (value !== void 0 && (typeof value !== "number" || !INTRINSICS.finite(value))) return this.#refuse("validateShape: raw schema numeric bounds must be finite numbers", "schema");
6095
+ const value = INTRINSICS.own(schema, key) ? schema[key] : void 0;
6096
+ 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);
5171
6097
  }
5172
- const population = schema.enum;
6098
+ const population = INTRINSICS.own(schema, "enum") ? schema.enum : void 0;
5173
6099
  if (population !== void 0) {
5174
- if (!INTRINSICS.array(population)) return this.#refuse("validateShape: raw schema enum must be a non-empty array", "schema");
6100
+ if (!INTRINSICS.array(population)) return this.#refuseSchema("validateShape: raw schema enum must be a non-empty array", stack, first, second, "enum");
5175
6101
  const snapshot = readArrayEntries(population);
5176
- if (isFailure(snapshot) || snapshot.value.entries.length === 0) return this.#refuse("validateShape: raw schema enum must be a non-empty array", "schema");
5177
- if (!snapshot.value.dense) return this.#refuse("validateShape: raw schema enum must be dense", "schema");
6102
+ 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");
6103
+ if (!snapshot.value.dense) return this.#refuseSchema("validateShape: raw schema enum must be dense", stack, first, second, "enum");
5178
6104
  const values = collectMembers([]);
5179
6105
  for (const valueIndex of iterateIndices(() => snapshot.value.entries.length)) {
5180
6106
  const value = snapshot.value.entries[valueIndex];
5181
- 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");
6107
+ 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));
5182
6108
  admitMember(values, value);
5183
6109
  }
5184
6110
  }
5185
- const names = schema.required;
6111
+ const names = INTRINSICS.own(schema, "required") ? schema.required : void 0;
5186
6112
  if (names !== void 0) {
5187
- if (!INTRINSICS.array(names)) return this.#refuse("validateShape: raw schema required must be an array", "schema");
6113
+ if (!INTRINSICS.array(names)) return this.#refuseSchema("validateShape: raw schema required must be an array", stack, first, second, "required");
5188
6114
  const snapshot = readArrayEntries(names);
5189
- if (isFailure(snapshot)) return this.#refuse("validateShape: raw schema required must be an array", "schema");
5190
- if (!snapshot.value.dense) return this.#refuse("validateShape: raw schema required must be dense", "schema");
6115
+ if (isFailure(snapshot)) return this.#refuseSchema("validateShape: raw schema required must be an array", stack, first, second, "required");
6116
+ if (!snapshot.value.dense) return this.#refuseSchema("validateShape: raw schema required must be dense", stack, first, second, "required");
5191
6117
  const required = collectMembers([]);
5192
6118
  for (const valueIndex of iterateIndices(() => snapshot.value.entries.length)) {
5193
6119
  const value = snapshot.value.entries[valueIndex];
5194
6120
  if (value === void 0) continue;
5195
- if (typeof value !== "string" || matchesMember(required, value)) return this.#refuse("validateShape: raw schema required values must be unique strings", "schema");
6121
+ 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));
5196
6122
  admitMember(required, value);
5197
6123
  }
5198
6124
  }
5199
6125
  const nested = [];
5200
- if (schema.items !== void 0) nested[nested.length] = schema.items;
5201
- if (schema.properties !== void 0) {
5202
- if (!isRecord(schema.properties)) return this.#refuse("validateShape: raw schema properties must be a plain record", "schema");
6126
+ const edges = [];
6127
+ if (INTRINSICS.own(schema, "items") && schema.items !== void 0) {
6128
+ edges[nested.length] = ["items"];
6129
+ nested[nested.length] = schema.items;
6130
+ }
6131
+ if (INTRINSICS.own(schema, "properties") && schema.properties !== void 0) {
6132
+ if (!isRecord(schema.properties)) return this.#refuseSchema("validateShape: raw schema properties must be a plain record", stack, first, second, "properties");
5203
6133
  const propertyList = INTRINSICS.keys(schema.properties);
5204
6134
  for (const propertyIndex of iterateIndices(() => propertyList.length)) {
5205
6135
  const key = propertyList[propertyIndex];
5206
6136
  if (key === void 0) continue;
5207
- nested[nested.length] = schema.properties[key];
6137
+ edges[nested.length] = ["properties", key];
6138
+ nested[nested.length] = INTRINSICS.own(schema.properties, key) ? schema.properties[key] : void 0;
5208
6139
  }
5209
6140
  }
5210
- if (schema.additionalProperties !== void 0 && schema.additionalProperties !== true && schema.additionalProperties !== false) nested[nested.length] = schema.additionalProperties;
6141
+ if (INTRINSICS.own(schema, "additionalProperties") && schema.additionalProperties !== void 0 && schema.additionalProperties !== true && schema.additionalProperties !== false) {
6142
+ edges[nested.length] = ["additionalProperties"];
6143
+ nested[nested.length] = schema.additionalProperties;
6144
+ }
5211
6145
  const unionList = ["anyOf", "oneOf"];
5212
6146
  for (const unionIndex of iterateIndices(() => unionList.length)) {
5213
6147
  const key = unionList[unionIndex];
5214
6148
  if (key === void 0) continue;
5215
- const variants = schema[key];
6149
+ const variants = INTRINSICS.own(schema, key) ? schema[key] : void 0;
5216
6150
  if (variants === void 0) continue;
5217
- if (!INTRINSICS.array(variants)) return this.#refuse("validateShape: raw schema unions must be non-empty arrays", "schema");
6151
+ if (!INTRINSICS.array(variants)) return this.#refuseSchema("validateShape: raw schema unions must be non-empty arrays", stack, first, second, key);
5218
6152
  const snapshot = readArrayEntries(variants);
5219
- if (isFailure(snapshot) || snapshot.value.entries.length === 0) return this.#refuse("validateShape: raw schema unions must be non-empty arrays", "schema");
5220
- if (!snapshot.value.dense) return this.#refuse("validateShape: raw schema unions must be dense arrays", "schema");
5221
- for (const variantIndex of iterateIndices(() => snapshot.value.entries.length)) nested[nested.length] = snapshot.value.entries[variantIndex];
6153
+ if (isFailure(snapshot) || snapshot.value.entries.length === 0) return this.#refuseSchema("validateShape: raw schema unions must be non-empty arrays", stack, first, second, key);
6154
+ if (!snapshot.value.dense) return this.#refuseSchema("validateShape: raw schema unions must be dense arrays", stack, first, second, key);
6155
+ for (const variantIndex of iterateIndices(() => snapshot.value.entries.length)) {
6156
+ edges[nested.length] = [key, INTRINSICS.text(variantIndex)];
6157
+ nested[nested.length] = snapshot.value.entries[variantIndex];
6158
+ }
5222
6159
  }
5223
6160
  stack[stack.length] = {
5224
6161
  operation: "exit",
5225
6162
  schema,
5226
- nested
6163
+ nested,
6164
+ ...first === void 0 ? {} : { first },
6165
+ ...second === void 0 ? {} : { second }
5227
6166
  };
5228
6167
  for (const offset of iterateIndices(() => nested.length)) {
5229
6168
  const index = nested.length - 1 - offset;
6169
+ const childFirst = edges[index]?.[0];
6170
+ const edge = edges[index];
6171
+ const childSecond = edge !== void 0 && INTRINSICS.own(edge, 1) ? edge[1] : void 0;
5230
6172
  stack[stack.length] = {
5231
6173
  operation: "enter",
5232
- schema: nested[index]
6174
+ schema: nested[index],
6175
+ ...childFirst === void 0 ? {} : { first: childFirst },
6176
+ ...childSecond === void 0 ? {} : { second: childSecond }
5233
6177
  };
5234
6178
  }
5235
6179
  }
@@ -5246,6 +6190,7 @@ var ShapePass = class ShapePass {
5246
6190
  #populate(current) {
5247
6191
  switch (current.category) {
5248
6192
  case "array":
6193
+ this.#spend(1);
5249
6194
  this.#children[this.#children.length] = {
5250
6195
  shape: current.items,
5251
6196
  first: "items",
@@ -5259,6 +6204,7 @@ var ShapePass = class ShapePass {
5259
6204
  for (const keyIndex of iterateIndices(() => keys.length)) {
5260
6205
  const key = keys[keyIndex];
5261
6206
  if (key === void 0) continue;
6207
+ this.#spend(1);
5262
6208
  const descriptorOutcome = attempt(() => INTRINSICS.describe(properties, key));
5263
6209
  if (isFailure(descriptorOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
5264
6210
  const descriptor = descriptorOutcome.value;
@@ -5271,10 +6217,16 @@ var ShapePass = class ShapePass {
5271
6217
  };
5272
6218
  continue;
5273
6219
  }
5274
- const childOutcome = attempt(() => current.properties[key]);
6220
+ const childOutcome = attempt(() => {
6221
+ const population = current.properties;
6222
+ return isRecord(population) ? population[key] : void 0;
6223
+ });
5275
6224
  if (isFailure(childOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
5276
6225
  const child = childOutcome.value;
5277
- const stable = attempt(() => INTRINSICS.same(current.properties[key], child) && INTRINSICS.same(descriptor.value, child));
6226
+ const stable = attempt(() => {
6227
+ const population = current.properties;
6228
+ return isRecord(population) && INTRINSICS.same(population[key], child) && INTRINSICS.same(descriptor.value, child);
6229
+ });
5278
6230
  if (isFailure(stable)) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
5279
6231
  if (!stable.value) {
5280
6232
  this.#children[this.#children.length] = {
@@ -5293,11 +6245,15 @@ var ShapePass = class ShapePass {
5293
6245
  };
5294
6246
  }
5295
6247
  const extra = current.additionalProperties;
5296
- if (extra !== void 0 && extra !== true && extra !== false) this.#children[this.#children.length] = {
5297
- shape: extra,
5298
- first: "additionalProperties",
5299
- optional: false
5300
- };
6248
+ this.#open = extra !== void 0 && extra !== false;
6249
+ if (extra !== void 0 && extra !== true && extra !== false) {
6250
+ this.#spend(1);
6251
+ this.#children[this.#children.length] = {
6252
+ shape: extra,
6253
+ first: "additionalProperties",
6254
+ optional: false
6255
+ };
6256
+ }
5301
6257
  break;
5302
6258
  }
5303
6259
  case "union": {
@@ -5316,6 +6272,7 @@ var ShapePass = class ShapePass {
5316
6272
  });
5317
6273
  for (const index of iterateIndices(() => length)) {
5318
6274
  const key = INTRINSICS.text(index);
6275
+ this.#spend(1);
5319
6276
  const descriptorOutcome = attempt(() => INTRINSICS.describe(current.variants, key));
5320
6277
  if (isFailure(descriptorOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "variants", key);
5321
6278
  const descriptor = descriptorOutcome.value;
@@ -5329,7 +6286,10 @@ var ShapePass = class ShapePass {
5329
6286
  continue;
5330
6287
  }
5331
6288
  const variant = variants[index];
5332
- const stable = attempt(() => INTRINSICS.same(current.variants[index], variant) && INTRINSICS.same(descriptor.value, variant));
6289
+ const stable = attempt(() => {
6290
+ const population = current.variants;
6291
+ return INTRINSICS.array(population) && INTRINSICS.same(population[index], variant) && INTRINSICS.same(descriptor.value, variant);
6292
+ });
5333
6293
  if (isFailure(stable)) return this.#refuse("validateShape: every node must be a recognized shape", "variants", key);
5334
6294
  if (!stable.value) {
5335
6295
  this.#children[this.#children.length] = {
@@ -5371,7 +6331,10 @@ var ShapePass = class ShapePass {
5371
6331
  const descriptor = descriptorOutcome.value;
5372
6332
  if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) return this.#refuse("validateShape: values must be a dense data array", "values", key);
5373
6333
  const value = literals[index];
5374
- const stable = attempt(() => INTRINSICS.same(current.values[index], value) && INTRINSICS.same(descriptor.value, value));
6334
+ const stable = attempt(() => {
6335
+ const population = current.values;
6336
+ return INTRINSICS.array(population) && INTRINSICS.same(population[index], value) && INTRINSICS.same(descriptor.value, value);
6337
+ });
5375
6338
  if (isFailure(stable)) return this.#refuse("validateShape: every node must be a recognized shape", "values", key);
5376
6339
  if (!stable.value) return this.#refuse("validateShape: values must be a stable data array", "values", key);
5377
6340
  if (!isLiteralValue(value)) return this.#refuse("validateShape: every literal value must be a string, number, or boolean", "values", key);
@@ -5389,14 +6352,28 @@ var ShapePass = class ShapePass {
5389
6352
  break;
5390
6353
  }
5391
6354
  case "optional":
5392
- case "nullable": this.#children[this.#children.length] = {
5393
- shape: current.inner,
5394
- first: "inner",
5395
- optional: false
5396
- };
6355
+ case "nullable":
6356
+ this.#spend(1);
6357
+ this.#children[this.#children.length] = {
6358
+ shape: current.inner,
6359
+ first: "inner",
6360
+ optional: false
6361
+ };
5397
6362
  }
5398
6363
  return true;
5399
6364
  }
6365
+ #spend(count) {
6366
+ const budget = this.#budget;
6367
+ if (budget === void 0) return;
6368
+ budget.left -= count;
6369
+ if (budget.left < 0) throw new ContractError(`validateShape: capture exceeds the node limit ${CLONE_NODE_LIMIT}`, {
6370
+ code: "clone",
6371
+ context: {
6372
+ path: pathOf(this.#path),
6373
+ limit: CLONE_NODE_LIMIT
6374
+ }
6375
+ });
6376
+ }
5400
6377
  #schedule(current, depth, segments) {
5401
6378
  admitVisited(this.#active, current);
5402
6379
  const children = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(this.#children), [(child) => child !== void 0]);
@@ -5415,7 +6392,7 @@ var ShapePass = class ShapePass {
5415
6392
  depth: depth + 1,
5416
6393
  optional: child.optional,
5417
6394
  first: child.first,
5418
- ...child.second === void 0 ? {} : { second: child.second }
6395
+ ...INTRINSICS.own(child, "second") && child.second !== void 0 ? { second: child.second } : {}
5419
6396
  };
5420
6397
  }
5421
6398
  return captured;
@@ -5426,25 +6403,27 @@ var ShapePass = class ShapePass {
5426
6403
  shape,
5427
6404
  category: this.#category,
5428
6405
  children,
5429
- raw: this.#raw
6406
+ raw: this.#raw,
6407
+ defaulted: this.#defaulted,
6408
+ open: this.#open
5430
6409
  };
5431
6410
  INTRINSICS.reflect.apply(INTRINSICS.retain, this.#index, [shape, index]);
5432
6411
  return index;
5433
6412
  }
5434
6413
  #locate(shape) {
5435
- if (shape === void 0) return void 0;
6414
+ if (typeof shape !== "object" || shape === null) return void 0;
5436
6415
  return INTRINSICS.reflect.apply(INTRINSICS.recall, this.#index, [shape]);
5437
6416
  }
5438
6417
  #measure() {
6418
+ if (this.#cycle !== void 0) {
6419
+ this.#finish();
6420
+ return;
6421
+ }
5439
6422
  for (const index of iterateIndices(() => this.#captures.length)) {
5440
6423
  this.#height[index] = 0;
5441
6424
  this.#reach[index] = 0;
5442
6425
  this.#counts[index] = 1;
5443
6426
  }
5444
- if (this.#cycle !== void 0) {
5445
- this.#trace();
5446
- return;
5447
- }
5448
6427
  for (const step of iterateIndices(() => this.#post.length)) {
5449
6428
  const index = this.#post[step];
5450
6429
  if (index === void 0) continue;
@@ -5482,7 +6461,7 @@ var ShapePass = class ShapePass {
5482
6461
  this.#via[located] = {
5483
6462
  parent: index,
5484
6463
  first: child.first,
5485
- ...child.second === void 0 ? {} : { second: child.second }
6464
+ ...INTRINSICS.own(child, "second") && child.second !== void 0 ? { second: child.second } : {}
5486
6465
  };
5487
6466
  }
5488
6467
  }
@@ -5495,11 +6474,52 @@ var ShapePass = class ShapePass {
5495
6474
  context: { path: pathOf(this.#ascend(index), "schema") }
5496
6475
  });
5497
6476
  }
6477
+ this.#placeDefaults();
6478
+ }
6479
+ #placeDefaults() {
6480
+ if (!INTRINSICS.reflect.apply(INTRINSICS.some, this.#captures, [(capture) => capture.defaulted])) return;
6481
+ for (const offset of iterateIndices(() => this.#post.length)) {
6482
+ const index = this.#post[this.#post.length - 1 - offset];
6483
+ if (index === void 0) continue;
6484
+ const capture = this.#captures[index];
6485
+ if (capture === void 0) continue;
6486
+ const enclosed = capture.category === "union" || INTRINSICS.own(this.#within, index) && this.#within[index] !== void 0;
6487
+ for (const edge of iterateIndices(() => capture.children.length)) {
6488
+ const child = capture.children[edge];
6489
+ if (child === void 0) continue;
6490
+ const located = this.#locate(child.shape);
6491
+ if (located === void 0) continue;
6492
+ if (enclosed && (!INTRINSICS.own(this.#within, located) || this.#within[located] === void 0)) this.#within[located] = {
6493
+ parent: index,
6494
+ first: child.first,
6495
+ ...INTRINSICS.own(child, "second") && child.second !== void 0 ? { second: child.second } : {}
6496
+ };
6497
+ if (this.#captures[located]?.defaulted !== true) continue;
6498
+ 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", {
6499
+ code: "placement",
6500
+ context: {
6501
+ path: pathOf(this.#route(index), child.first, INTRINSICS.own(child, "second") ? child.second : void 0),
6502
+ shape: "optional"
6503
+ }
6504
+ });
6505
+ 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", {
6506
+ code: "placement",
6507
+ context: {
6508
+ path: pathOf(this.#ascend(index), child.first, INTRINSICS.own(child, "second") ? child.second : void 0),
6509
+ shape: "optional"
6510
+ }
6511
+ });
6512
+ }
6513
+ }
6514
+ }
6515
+ #route(index) {
6516
+ const edge = INTRINSICS.own(this.#within, index) ? this.#within[index] : void 0;
6517
+ return edge === void 0 ? this.#ascend(index) : pathOf(this.#route(edge.parent), edge.first, INTRINSICS.own(edge, "second") ? edge.second : void 0);
5498
6518
  }
5499
6519
  #ascend(index) {
5500
6520
  if (index === 0) return [];
5501
- const edge = this.#via[index];
5502
- return edge === void 0 ? [] : pathOf(this.#ascend(edge.parent), edge.first, edge.second);
6521
+ const edge = INTRINSICS.own(this.#via, index) ? this.#via[index] : void 0;
6522
+ return edge === void 0 ? [] : pathOf(this.#ascend(edge.parent), edge.first, INTRINSICS.own(edge, "second") ? edge.second : void 0);
5503
6523
  }
5504
6524
  #witness(index, depth, path) {
5505
6525
  if (depth <= 512) {
@@ -5510,7 +6530,7 @@ var ShapePass = class ShapePass {
5510
6530
  const reached = located === void 0 ? 0 : this.#height[located] ?? 0;
5511
6531
  return depth + 1 + reached > 512;
5512
6532
  }])];
5513
- if (chosen !== void 0) return this.#witness(this.#locate(chosen.shape), depth + 1, pathOf(path, chosen.first, chosen.second));
6533
+ 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));
5514
6534
  }
5515
6535
  throw new ContractError("validateShape: a shape exceeds the compilation depth limit", {
5516
6536
  code: "depth",
@@ -5520,86 +6540,24 @@ var ShapePass = class ShapePass {
5520
6540
  }
5521
6541
  });
5522
6542
  }
5523
- #trace() {
5524
- const settled = [];
5525
- const order = [];
5526
- const active = new ShapePass.#weakSet();
5527
- const stack = [{
5528
- operation: "enter",
5529
- index: 0,
5530
- depth: 0
5531
- }];
5532
- while (stack.length > 0) {
5533
- const frame = stack.pop();
5534
- if (frame === void 0) continue;
5535
- if (frame.operation === "exit") {
5536
- const capture = this.#captures[frame.index];
5537
- if (capture !== void 0) omitVisited(active, capture.shape);
5538
- if (this.#oldest >= (order[frame.index] ?? 0) && (settled[frame.index] ?? -1) < frame.depth) settled[frame.index] = frame.depth;
5539
- if (frame.outer < this.#oldest) this.#oldest = frame.outer;
5540
- this.#trail.length -= frame.segments;
5541
- continue;
5542
- }
5543
- const segments = (frame.first === void 0 ? 0 : 1) + (frame.second === void 0 ? 0 : 1);
5544
- if (frame.first !== void 0) this.#trail[this.#trail.length] = frame.first;
5545
- if (frame.second !== void 0) this.#trail[this.#trail.length] = frame.second;
5546
- if (frame.depth > 512) throw new ContractError("validateShape: a shape exceeds the compilation depth limit", {
5547
- code: "depth",
5548
- context: {
5549
- path: pathOf(this.#trail),
5550
- limit: 512
5551
- }
5552
- });
5553
- const index = frame.index;
5554
- const capture = index === void 0 ? void 0 : this.#captures[index];
5555
- if (index === void 0 || capture === void 0) {
5556
- this.#trail.length -= segments;
5557
- continue;
5558
- }
5559
- if (matchesVisited(active, capture.shape)) {
5560
- const blocker = order[index] ?? 0;
5561
- if (blocker < this.#oldest) this.#oldest = blocker;
5562
- this.#trail.length -= segments;
5563
- continue;
5564
- }
5565
- const recorded = settled[index];
5566
- if (recorded !== void 0 && frame.depth <= recorded) {
5567
- this.#trail.length -= segments;
5568
- continue;
5569
- }
5570
- admitVisited(active, capture.shape);
5571
- order[index] = this.#clock;
5572
- this.#clock += 1;
5573
- stack[stack.length] = {
5574
- operation: "exit",
5575
- index,
5576
- depth: frame.depth,
5577
- segments,
5578
- outer: this.#oldest
5579
- };
5580
- this.#oldest = this.#clock;
5581
- for (const offset of iterateIndices(() => capture.children.length)) {
5582
- const edge = capture.children.length - 1 - offset;
5583
- const child = capture.children[edge];
5584
- if (child === void 0) continue;
5585
- stack[stack.length] = {
5586
- operation: "enter",
5587
- index: this.#locate(child.shape),
5588
- depth: frame.depth + 1,
5589
- first: child.first,
5590
- ...child.second === void 0 ? {} : { second: child.second }
5591
- };
5592
- }
5593
- }
5594
- }
5595
6543
  #finish() {
5596
6544
  if (this.#structure !== void 0) throw this.#structure;
5597
6545
  if (this.#cycle !== void 0) throw this.#cycle;
5598
6546
  if (this.#domain !== void 0) throw this.#domain;
5599
6547
  }
5600
- #refuse(message, first, second) {
6548
+ #refuseSchema(message, stack, first, second, keyword, member) {
6549
+ if (this.#structure !== void 0) return false;
6550
+ 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) : []]);
6551
+ const prefix = [];
6552
+ appendEntries(prefix, this.#path);
6553
+ prefix[prefix.length] = "schema";
6554
+ appendEntries(prefix, ancestors);
6555
+ const path = pathOf(prefix, first, second);
6556
+ return this.#refuse(message, keyword, member, path);
6557
+ }
6558
+ #refuse(message, first, second, prefix = this.#path) {
5601
6559
  if (this.#structure === void 0) {
5602
- const path = pathOf(this.#path, first, second);
6560
+ const path = pathOf(prefix, first, second);
5603
6561
  this.#structure = new ContractError(message, {
5604
6562
  code: "structure",
5605
6563
  context: { path }
@@ -5667,7 +6625,7 @@ var ShapeValidator = class ShapeValidator {
5667
6625
  */
5668
6626
  validate() {
5669
6627
  INTRINSICS.reflect.apply(INTRINSICS.sweep, this.#passes, [(pass) => pass.interrupt()]);
5670
- const pass = new ShapePass(this.#source);
6628
+ const pass = new ShapePass(this.#source, { left: CLONE_NODE_LIMIT });
5671
6629
  INTRINSICS.reflect.apply(INTRINSICS.admit, this.#passes, [pass]);
5672
6630
  this.#expansion = void 0;
5673
6631
  try {
@@ -5770,6 +6728,7 @@ var ShapeCloner = class ShapeCloner {
5770
6728
  return this.#settle(failure(error));
5771
6729
  }
5772
6730
  #execute() {
6731
+ const budget = { left: CLONE_NODE_LIMIT };
5773
6732
  const paths = this.#paths;
5774
6733
  const memo = this.#memo;
5775
6734
  if (paths === void 0 || memo === void 0) throw this.#unavailable();
@@ -5778,7 +6737,7 @@ var ShapeCloner = class ShapeCloner {
5778
6737
  shape: this.#source,
5779
6738
  depth: 0
5780
6739
  };
5781
- this.#drain();
6740
+ this.#drain(budget);
5782
6741
  this.#wireNodes();
5783
6742
  const root = INTRINSICS.reflect.apply(INTRINSICS.fetch, memo, [this.#source]);
5784
6743
  if (root === void 0) throw this.#create("ShapeCloner.clone: captured root is unavailable", {
@@ -5790,19 +6749,19 @@ var ShapeCloner = class ShapeCloner {
5790
6749
  if (this.#fidelity !== void 0) throw this.#fidelity;
5791
6750
  return root;
5792
6751
  }
5793
- #drain() {
6752
+ #drain(budget) {
5794
6753
  const memo = this.#memo;
5795
6754
  if (memo === void 0) throw this.#unavailable();
5796
6755
  for (const cursor of iterateIndices(() => this.#pending.length)) {
5797
6756
  const entry = this.#pending[cursor];
5798
6757
  if (entry === void 0) continue;
5799
6758
  if (INTRINSICS.reflect.apply(INTRINSICS.keyed, memo, [entry.shape])) continue;
5800
- if (entry.depth > 512) this.#refuseDepth();
5801
- this.#captureNode(entry.shape, entry.depth);
6759
+ if (entry.depth > 512) this.#refuseDepth(budget);
6760
+ this.#captureNode(entry.shape, entry.depth, budget);
5802
6761
  }
5803
6762
  }
5804
- #refuseDepth() {
5805
- this.#validateShape(this.#source);
6763
+ #refuseDepth(budget) {
6764
+ this.#validateShape(this.#source, [], budget);
5806
6765
  throw this.#create("validateShape: a shape exceeds the compilation depth limit", {
5807
6766
  code: "depth",
5808
6767
  context: {
@@ -5811,7 +6770,7 @@ var ShapeCloner = class ShapeCloner {
5811
6770
  }
5812
6771
  });
5813
6772
  }
5814
- #captureShell(source, path) {
6773
+ #captureShell(source, path, budget) {
5815
6774
  if (!matchesRecordBrand(source)) throw this.#create("validateShape: every structural child must be a shape", {
5816
6775
  code: "structure",
5817
6776
  context: { path }
@@ -5833,13 +6792,14 @@ var ShapeCloner = class ShapeCloner {
5833
6792
  case "boolean": return this.#captureSimple(source, path, "boolean");
5834
6793
  case "null": return this.#captureSimple(source, path, "null");
5835
6794
  case "literal": return this.#captureLiteral(source, path);
5836
- case "array": return this.#captureArray(source, path);
5837
- case "object": return this.#captureObject(source, path);
5838
- case "union": return this.#captureUnion(source, path);
5839
- case "optional": return this.#captureWrapper(source, path, "optional");
5840
- case "nullable": return this.#captureWrapper(source, path, "nullable");
6795
+ case "array": return this.#captureArray(source, path, budget);
6796
+ case "object": return this.#captureObject(source, path, budget);
6797
+ case "union": return this.#captureUnion(source, path, budget);
6798
+ case "optional": return this.#captureOptional(source, path, budget);
6799
+ case "nullable": return this.#captureNullable(source, path, budget);
5841
6800
  case "json": return this.#captureSimple(source, path, "json");
5842
- case "raw": return this.#captureRaw(source, path);
6801
+ case "shape": return this.#captureSimple(source, path, "shape");
6802
+ case "raw": return this.#captureRaw(source, path, budget);
5843
6803
  default: throw this.#create("validateShape: every node must be a recognized shape", {
5844
6804
  code: "structure",
5845
6805
  context: { path }
@@ -5927,12 +6887,12 @@ var ShapeCloner = class ShapeCloner {
5927
6887
  flags
5928
6888
  };
5929
6889
  }
5930
- #captureNode(source, depth) {
6890
+ #captureNode(source, depth, budget) {
5931
6891
  const paths = this.#paths;
5932
6892
  const memo = this.#memo;
5933
6893
  if (paths === void 0 || memo === void 0) throw this.#unavailable();
5934
6894
  const path = INTRINSICS.reflect.apply(INTRINSICS.fetch, paths, [source]) ?? [];
5935
- const clone = this.#captureShell(source, path);
6895
+ const clone = this.#captureShell(source, path, budget);
5936
6896
  INTRINSICS.reflect.apply(INTRINSICS.store, memo, [source, clone]);
5937
6897
  this.#sources[this.#sources.length] = source;
5938
6898
  this.#scheduleNode(source, clone, path, depth);
@@ -5941,11 +6901,13 @@ var ShapeCloner = class ShapeCloner {
5941
6901
  const min = this.#captureField(source, "min", path);
5942
6902
  const max = this.#captureField(source, "max", path);
5943
6903
  const pattern = this.#capturePattern(source, path);
6904
+ const date = this.#captureField(source, "date", path);
5944
6905
  const description = this.#captureField(source, "description", path);
5945
6906
  const fields = {
5946
6907
  category: "string",
5947
6908
  ...min === void 0 ? {} : { min },
5948
6909
  ...max === void 0 ? {} : { max },
6910
+ ...date === void 0 ? {} : { date },
5949
6911
  ...description === void 0 ? {} : { description }
5950
6912
  };
5951
6913
  if (pattern === void 0) return fields;
@@ -5981,6 +6943,10 @@ var ShapeCloner = class ShapeCloner {
5981
6943
  category: "null",
5982
6944
  ...description === void 0 ? {} : { description }
5983
6945
  };
6946
+ if (category === "shape") return {
6947
+ category: "shape",
6948
+ ...description === void 0 ? {} : { description }
6949
+ };
5984
6950
  return {
5985
6951
  category: "json",
5986
6952
  ...description === void 0 ? {} : { description }
@@ -5995,7 +6961,8 @@ var ShapeCloner = class ShapeCloner {
5995
6961
  ...description === void 0 ? {} : { description }
5996
6962
  };
5997
6963
  }
5998
- #captureArray(source, path) {
6964
+ #captureArray(source, path, budget) {
6965
+ this.#spend(budget, 1, path);
5999
6966
  const items = this.#captureField(source, "items", path);
6000
6967
  const min = this.#captureField(source, "min", path);
6001
6968
  const max = this.#captureField(source, "max", path);
@@ -6012,7 +6979,7 @@ var ShapeCloner = class ShapeCloner {
6012
6979
  ...description === void 0 ? {} : { description }
6013
6980
  };
6014
6981
  }
6015
- #captureObject(source, path) {
6982
+ #captureObject(source, path, budget) {
6016
6983
  const propertySource = this.#captureField(source, "properties", path);
6017
6984
  const additional = this.#captureField(source, "additionalProperties", path);
6018
6985
  const description = this.#captureField(source, "description", path);
@@ -6020,7 +6987,8 @@ var ShapeCloner = class ShapeCloner {
6020
6987
  code: "structure",
6021
6988
  context: { path: pathOf(path, "properties") }
6022
6989
  });
6023
- this.#captureProperties(source, propertySource, path);
6990
+ this.#captureProperties(source, propertySource, path, budget);
6991
+ if (additional !== void 0 && additional !== true && additional !== false) this.#spend(budget, 1, path);
6024
6992
  return {
6025
6993
  category: "object",
6026
6994
  properties: INTRINSICS.create(null),
@@ -6028,11 +6996,11 @@ var ShapeCloner = class ShapeCloner {
6028
6996
  ...description === void 0 ? {} : { description }
6029
6997
  };
6030
6998
  }
6031
- #captureUnion(source, path) {
6999
+ #captureUnion(source, path, budget) {
6032
7000
  const variantSource = this.#captureField(source, "variants", path);
6033
7001
  const mode = this.#captureField(source, "mode", path);
6034
7002
  const description = this.#captureField(source, "description", path);
6035
- this.#captureVariants(source, variantSource, path);
7003
+ this.#captureVariants(source, variantSource, path, budget);
6036
7004
  return {
6037
7005
  category: "union",
6038
7006
  variants: [],
@@ -6040,21 +7008,41 @@ var ShapeCloner = class ShapeCloner {
6040
7008
  ...description === void 0 ? {} : { description }
6041
7009
  };
6042
7010
  }
6043
- #captureWrapper(source, path, category) {
6044
- const inner = this.#captureField(source, "inner", path);
6045
- if (inner === void 0) throw this.#create("validateShape: every structural child must be a shape", {
7011
+ #captureOptional(source, path, budget) {
7012
+ const inner = this.#captureInner(source, path, budget);
7013
+ const value = this.#captureField(source, "default", path);
7014
+ if (!INTRINSICS.own(source, "default")) return {
7015
+ category: "optional",
7016
+ inner
7017
+ };
7018
+ const owned = isJSONValue(value) ? attempt(() => new JSONCloner(value).clone(budget)) : void 0;
7019
+ if (owned !== void 0 && isFailure(owned) && budget.left < 0 && isContractError(owned.error)) throw this.#prefix(owned.error, pathOf(path, "default"));
7020
+ if (owned === void 0 || isFailure(owned)) throw this.#create("validateShape: an optional default must be a JSON value", {
6046
7021
  code: "structure",
6047
- context: { path: pathOf(path, "inner") }
7022
+ context: { path: pathOf(path, "default") }
6048
7023
  });
6049
- return category === "optional" ? {
7024
+ return {
6050
7025
  category: "optional",
6051
- inner
6052
- } : {
7026
+ inner,
7027
+ default: owned.value
7028
+ };
7029
+ }
7030
+ #captureNullable(source, path, budget) {
7031
+ return {
6053
7032
  category: "nullable",
6054
- inner
7033
+ inner: this.#captureInner(source, path, budget)
6055
7034
  };
6056
7035
  }
6057
- #captureRaw(source, path) {
7036
+ #captureInner(source, path, budget) {
7037
+ this.#spend(budget, 1, path);
7038
+ const inner = this.#captureField(source, "inner", path);
7039
+ if (inner === void 0) throw this.#create("validateShape: every structural child must be a shape", {
7040
+ code: "structure",
7041
+ context: { path: pathOf(path, "inner") }
7042
+ });
7043
+ return inner;
7044
+ }
7045
+ #captureRaw(source, path, budget) {
6058
7046
  const schema = this.#captureField(source, "schema", path);
6059
7047
  if (!isRecord(schema)) throw this.#create("validateShape: raw schema must be a plain record", {
6060
7048
  code: "structure",
@@ -6063,10 +7051,10 @@ var ShapeCloner = class ShapeCloner {
6063
7051
  this.#validateShape({
6064
7052
  category: "raw",
6065
7053
  schema
6066
- });
7054
+ }, path, budget);
6067
7055
  const outcome = attempt(() => new SchemaCloner(schema).clone());
6068
7056
  if (isFailure(outcome)) {
6069
- if (isContractError(outcome.error)) admitVisited(this.#owned, outcome.error);
7057
+ if (isContractError(outcome.error)) throw this.#prefix(outcome.error, pathOf(path, "schema"));
6070
7058
  throw outcome.error;
6071
7059
  }
6072
7060
  return {
@@ -6109,9 +7097,10 @@ var ShapeCloner = class ShapeCloner {
6109
7097
  });
6110
7098
  return value;
6111
7099
  }
6112
- #captureProperties(source, properties, path) {
7100
+ #captureProperties(source, properties, path, budget) {
6113
7101
  const keys = INTRINSICS.keys(properties);
6114
7102
  const snapshot = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(keys), [(key) => {
7103
+ this.#spend(budget, 1, path);
6115
7104
  const descriptor = INTRINSICS.describe(properties, key);
6116
7105
  if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) throw this.#create("validateShape: every structural child must be a shape", {
6117
7106
  code: "structure",
@@ -6138,7 +7127,7 @@ var ShapeCloner = class ShapeCloner {
6138
7127
  if (captured === void 0) throw this.#unavailable();
6139
7128
  INTRINSICS.reflect.apply(INTRINSICS.store, captured, [source, snapshot]);
6140
7129
  }
6141
- #captureVariants(source, variants, path) {
7130
+ #captureVariants(source, variants, path, budget) {
6142
7131
  if (!INTRINSICS.array(variants)) throw this.#create("validateShape: variants must be a finite array", {
6143
7132
  code: "structure",
6144
7133
  context: { path: pathOf(path, "variants") }
@@ -6153,6 +7142,7 @@ var ShapeCloner = class ShapeCloner {
6153
7142
  context: { path: pathOf(path, "variants") }
6154
7143
  });
6155
7144
  const entries = snapshot.value.entries;
7145
+ this.#spend(budget, entries.length, path);
6156
7146
  const captured = this.#variants;
6157
7147
  if (captured === void 0) throw this.#unavailable();
6158
7148
  INTRINSICS.reflect.apply(INTRINSICS.store, captured, [source, entries]);
@@ -6336,12 +7326,40 @@ var ShapeCloner = class ShapeCloner {
6336
7326
  if (clone !== void 0) INTRINSICS.freeze(clone);
6337
7327
  }
6338
7328
  }
6339
- #validateShape(shape) {
6340
- const outcome = attempt(() => new ShapeValidator(shape).validate());
7329
+ #validateShape(shape, path = [], budget) {
7330
+ const outcome = attempt(() => new ShapePass(shape, budget).validate());
6341
7331
  if (isSuccess(outcome)) return;
6342
- if (isContractError(outcome.error)) admitVisited(this.#owned, outcome.error);
7332
+ if (isContractError(outcome.error)) throw this.#prefix(outcome.error, path);
6343
7333
  throw outcome.error;
6344
7334
  }
7335
+ #spend(budget, count, path) {
7336
+ budget.left -= count;
7337
+ if (budget.left < 0) throw this.#create(`cloneShape: capture exceeds the node limit ${CLONE_NODE_LIMIT}`, {
7338
+ code: "clone",
7339
+ context: {
7340
+ path,
7341
+ limit: CLONE_NODE_LIMIT
7342
+ }
7343
+ });
7344
+ }
7345
+ #prefix(error, path) {
7346
+ if (path.length === 0) {
7347
+ admitVisited(this.#owned, error);
7348
+ return error;
7349
+ }
7350
+ const tail = error.context?.path;
7351
+ const location = [];
7352
+ appendEntries(location, path);
7353
+ appendEntries(location, typeof tail === "string" ? [tail] : tail ?? []);
7354
+ return this.#create(error.message, {
7355
+ code: error.code,
7356
+ context: {
7357
+ ...error.context,
7358
+ path: location
7359
+ },
7360
+ ...INTRINSICS.own(error, "cause") ? { cause: error.cause } : {}
7361
+ });
7362
+ }
6345
7363
  #unavailable() {
6346
7364
  return this.#create("ShapeCloner.clone: the capture state is unavailable", {
6347
7365
  code: "clone",
@@ -6507,7 +7525,7 @@ function ownShape(shape) {
6507
7525
  const frozen = holds(() => INTRINSICS.frozen(shape));
6508
7526
  const fidelity = attempt(() => cloneShape(shape));
6509
7527
  if (isSuccess(fidelity)) return fidelity.value;
6510
- if (isContractError(fidelity.error) && fidelity.error.code !== "clone") throw fidelity.error;
7528
+ if (isContractError(fidelity.error) && (fidelity.error.code !== "clone" || fidelity.error.context?.limit === 262144)) throw fidelity.error;
6511
7529
  if (!frozen) throw fidelity.error;
6512
7530
  const validation = attempt(() => new ShapeValidator(shape).validate());
6513
7531
  if (isFailure(validation) && isContractError(validation.error)) throw validation.error;
@@ -6984,8 +8002,9 @@ function matchOf(pattern) {
6984
8002
  * refinements — `min` / `max` length and a `pattern`.
6985
8003
  *
6986
8004
  * @remarks
6987
- * Composes {@link isString} with {@link boundsOf} on the string's `.length` and
6988
- * an owned stateless pattern (the same refinement {@link matchOf} performs).
8005
+ * Composes {@link isString} with {@link matchesStringLength}, which counts code
8006
+ * points as the `minLength` and `maxLength` a string shape emits do, and an owned
8007
+ * stateless pattern (the same refinement {@link matchOf} performs).
6989
8008
  * When `min`, `max`, and `pattern` are all absent it returns the bare {@link isString} guard
6990
8009
  * (the unconstrained fast path), so an unrefined string leaf pays no wrapping
6991
8010
  * cost. The single source of the string refinement shared by the compiled guard
@@ -7012,14 +8031,13 @@ function stringOf(options) {
7012
8031
  "max",
7013
8032
  "pattern"
7014
8033
  ], "stringOf", "string");
7015
- const min = safe?.min;
7016
- const max = safe?.max;
7017
- const source = safe?.pattern;
8034
+ const min = safe !== void 0 && INTRINSICS.own(safe, "min") ? safe.min : void 0;
8035
+ const max = safe !== void 0 && INTRINSICS.own(safe, "max") ? safe.max : void 0;
8036
+ const source = safe !== void 0 && INTRINSICS.own(safe, "pattern") ? safe.pattern : void 0;
7018
8037
  if (source !== void 0 && !isRegExp(source)) throw new ContractError("stringOf: pattern must be a RegExp", { code: "pattern" });
7019
8038
  const pattern = source === void 0 ? void 0 : ownPattern(source, "stringOf");
7020
8039
  if (min === void 0 && max === void 0 && pattern === void 0) return isString;
7021
- const withinLength = boundsOf(min, max);
7022
- return whereOf(isString, (value) => withinLength(value.length) && (pattern === void 0 || matchesPattern(pattern, value)));
8040
+ return whereOf(isString, (value) => matchesStringLength(value, min, max) && (pattern === void 0 || matchesPattern(pattern, value)));
7023
8041
  }, "stringOf");
7024
8042
  }
7025
8043
  /**
@@ -7544,7 +8562,9 @@ function seededRandom(seed) {
7544
8562
  * chain pays a hundred clones of shrinking graphs and a hundred validations —
7545
8563
  * quadratic work for a linear declaration. Here ownership runs once, validation runs once over
7546
8564
  * that owned result, and each unique node and structural edge is indexed once
7547
- * into children-before-parent order. Every artifact family is then a single
8565
+ * into children-before-parent order. A declaration a builder sealed is frozen and
8566
+ * validated all the way down already, so it takes neither and is indexed as it
8567
+ * stands. Every artifact family is then a single
7548
8568
  * postorder pass whose entries are keyed by node identity, so a shared child is
7549
8569
  * compiled once however many parents point at it. The same asymmetry exists on
7550
8570
  * the VALUE side and is answered the same way: `guard`, `auditor` and `reporter`
@@ -7556,7 +8576,9 @@ function seededRandom(seed) {
7556
8576
  * getters after it replay. A getter builds its own family and no other, except
7557
8577
  * that `parser`, `reporter` and `generator` build the guard plan when the graph
7558
8578
  * holds a union, because a union's membership question IS a guard question in
7559
- * all three.
8579
+ * all three, and every getter builds it when the graph holds a default, because
8580
+ * a default that its inner shape refuses refuses at whichever artifact is read
8581
+ * first.
7560
8582
  *
7561
8583
  * One terminal lifecycle covers preparation and every family. A failure settles
7562
8584
  * the compiler: later getters rethrow that exact error, while an artifact
@@ -7776,10 +8798,15 @@ var ContractCompiler = class ContractCompiler {
7776
8798
  shape: "contract"
7777
8799
  }
7778
8800
  });
8801
+ const sealed = ShapePass.expansionOf(source);
8802
+ if (sealed !== void 0) {
8803
+ refuseExpansion(sealed);
8804
+ this.#discover(source);
8805
+ this.#source = void 0;
8806
+ return;
8807
+ }
7779
8808
  const owned = ownShape(source);
7780
- const validator = new ShapeValidator(owned);
7781
- validator.validate();
7782
- refuseExpansion(validator.expansion);
8809
+ refuseExpansion(new ShapePass(owned).validate());
7783
8810
  this.#discover(owned);
7784
8811
  this.#source = void 0;
7785
8812
  }
@@ -7808,7 +8835,9 @@ var ContractCompiler = class ContractCompiler {
7808
8835
  const shape = frame.shape;
7809
8836
  if (INTRINSICS.reflect.apply(INTRINSICS.recall, known, [shape]) !== void 0) continue;
7810
8837
  const index = this.#nodes.length;
7811
- this.#nodes[index] = shape;
8838
+ const node = INTRINSICS.rebase({ ...shape }, null);
8839
+ this.#nodes[index] = node;
8840
+ INTRINSICS.reflect.apply(INTRINSICS.retain, known, [node, index]);
7812
8841
  INTRINSICS.reflect.apply(INTRINSICS.retain, known, [shape, index]);
7813
8842
  this.#stack[this.#stack.length] = {
7814
8843
  operation: "exit",
@@ -7899,6 +8928,54 @@ var ContractCompiler = class ContractCompiler {
7899
8928
  for (const index of iterateIndices(() => this.#nodes.length)) if (this.#nodes[index]?.category === "union") return true;
7900
8929
  return false;
7901
8930
  }
8931
+ #defaults() {
8932
+ for (const index of iterateIndices(() => this.#nodes.length)) {
8933
+ const node = this.#nodes[index];
8934
+ if (node?.category === "optional" && INTRINSICS.own(node, "default")) return true;
8935
+ }
8936
+ return false;
8937
+ }
8938
+ #checkDefaults(shape, path) {
8939
+ switch (shape.category) {
8940
+ case "array":
8941
+ this.#checkDefaults(shape.items, pathOf(path, "items"));
8942
+ return;
8943
+ case "nullable":
8944
+ this.#checkDefaults(shape.inner, pathOf(path, "inner"));
8945
+ return;
8946
+ case "optional":
8947
+ this.#checkDefaults(shape.inner, pathOf(path, "inner"));
8948
+ if (!INTRINSICS.own(shape, "default") || this.#guardAt(shape.inner)(shape.default)) return;
8949
+ throw new ContractError("ContractCompiler: a default must satisfy the shape it fills; change the default or the shape", {
8950
+ code: "structure",
8951
+ context: {
8952
+ path: pathOf(path, "default"),
8953
+ shape: "optional",
8954
+ received: preview(shape.default)
8955
+ }
8956
+ });
8957
+ case "union":
8958
+ for (const index of iterateIndices(() => shape.variants.length)) {
8959
+ const variant = shape.variants[index];
8960
+ if (variant === void 0) continue;
8961
+ this.#checkDefaults(variant, pathOf(path, "variants", INTRINSICS.text(index)));
8962
+ }
8963
+ return;
8964
+ case "object": {
8965
+ const keys = INTRINSICS.keys(shape.properties);
8966
+ for (const index of iterateIndices(() => keys.length)) {
8967
+ const key = keys[index];
8968
+ const child = key === void 0 ? void 0 : shape.properties[key];
8969
+ if (child === void 0) continue;
8970
+ this.#checkDefaults(child, pathOf(path, "properties", key));
8971
+ }
8972
+ const extra = shape.additionalProperties;
8973
+ if (extra !== void 0 && extra !== true && extra !== false) this.#checkDefaults(extra, pathOf(path, "additionalProperties"));
8974
+ return;
8975
+ }
8976
+ default: return;
8977
+ }
8978
+ }
7902
8979
  #repeats(index) {
7903
8980
  const category = this.#node(index).category;
7904
8981
  if (category === "array" || category === "object" || category === "union") return true;
@@ -7910,10 +8987,64 @@ var ContractCompiler = class ContractCompiler {
7910
8987
  #trackFaults(plan) {
7911
8988
  return (value, path) => EvaluationScope.run(plan, value, path, true);
7912
8989
  }
8990
+ #discriminate(owned) {
8991
+ const arms = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(owned.variants), [(variant) => variant?.category === "object"]);
8992
+ const first = arms[0];
8993
+ if (first === void 0 || arms.length !== owned.variants.length) return void 0;
8994
+ 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"])]);
8995
+ const tables = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(keys), [(key) => ContractCompiler.#tableOf(key, arms)]);
8996
+ const named = tables[0];
8997
+ if (named === void 0) return void 0;
8998
+ return {
8999
+ hint: INTRINSICS.freeze({
9000
+ key: named.key,
9001
+ expected: named.expected
9002
+ }),
9003
+ select: (value) => {
9004
+ if (!isObject(value)) return void 0;
9005
+ for (const index of iterateIndices(() => tables.length)) {
9006
+ const table = tables[index];
9007
+ if (table === void 0) continue;
9008
+ const held = attempt(() => INTRINSICS.describe(value, table.key));
9009
+ if (isFailure(held) || held.value === void 0) continue;
9010
+ if (!INTRINSICS.own(held.value, "value")) continue;
9011
+ const arm = INTRINSICS.reflect.apply(INTRINSICS.fetch, table.members, [held.value.value]);
9012
+ if (arm !== void 0 && arm >= 0) return arm;
9013
+ }
9014
+ }
9015
+ };
9016
+ }
9017
+ static #tableOf(key, arms) {
9018
+ const members = new INTRINSICS.map();
9019
+ const expected = [];
9020
+ for (const armIndex of iterateIndices(() => arms.length)) {
9021
+ const node = arms[armIndex]?.properties[key];
9022
+ if (node?.category !== "literal") continue;
9023
+ for (const valueIndex of iterateIndices(() => node.values.length)) {
9024
+ const literal = node.values[valueIndex];
9025
+ if (literal === void 0) continue;
9026
+ const known = INTRINSICS.reflect.apply(INTRINSICS.fetch, members, [literal]);
9027
+ if (known === void 0) expected[expected.length] = literal;
9028
+ const arm = known === void 0 || known === armIndex ? armIndex : -1;
9029
+ INTRINSICS.reflect.apply(INTRINSICS.store, members, [literal, arm]);
9030
+ }
9031
+ }
9032
+ return {
9033
+ key,
9034
+ members,
9035
+ expected: INTRINSICS.freeze(expected)
9036
+ };
9037
+ }
9038
+ static #parseArm(arm, value) {
9039
+ if (arm.guard(value)) return value;
9040
+ const parsed = arm.parse(value);
9041
+ return parsed !== void 0 && arm.guard(parsed) ? parsed : void 0;
9042
+ }
7913
9043
  #buildSchema() {
7914
9044
  const ready = this.#schema;
7915
9045
  if (ready !== void 0) return ready;
7916
9046
  this.#prepare();
9047
+ if (this.#defaults()) this.#buildGuard();
7917
9048
  for (const step of iterateIndices(() => this.#order.length)) {
7918
9049
  const index = this.#order[step];
7919
9050
  if (index === void 0) continue;
@@ -7937,6 +9068,13 @@ var ContractCompiler = class ContractCompiler {
7937
9068
  #schemaOf(index) {
7938
9069
  const owned = this.#node(index);
7939
9070
  switch (owned.category) {
9071
+ case "shape": return INTRINSICS.freeze({
9072
+ type: "object",
9073
+ 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.",
9074
+ properties: INTRINSICS.freeze({ category: INTRINSICS.freeze({ enum: INTRINSICS.freeze(INTRINSICS.keys(SHAPE_FIELDS)) }) }),
9075
+ required: INTRINSICS.freeze(["category"]),
9076
+ additionalProperties: true
9077
+ });
7940
9078
  case "string": {
7941
9079
  const text = owned.pattern === void 0 ? void 0 : readPatternSource(owned.pattern);
7942
9080
  if (owned.pattern !== void 0 && text === void 0) throw new ContractError("compileSchema: pattern source could not be read", {
@@ -7948,6 +9086,7 @@ var ContractCompiler = class ContractCompiler {
7948
9086
  ...owned.min !== void 0 ? { minLength: owned.min } : {},
7949
9087
  ...owned.max !== void 0 ? { maxLength: owned.max } : {},
7950
9088
  ...text !== void 0 ? { pattern: text } : {},
9089
+ ...owned.date === true ? { format: "date" } : {},
7951
9090
  ...owned.description !== void 0 ? { description: owned.description } : {}
7952
9091
  });
7953
9092
  }
@@ -7986,7 +9125,7 @@ var ContractCompiler = class ContractCompiler {
7986
9125
  if (child === void 0) return [];
7987
9126
  return [{
7988
9127
  key,
7989
- schema: this.#schemaAt(child.category === "optional" ? child.inner : child),
9128
+ schema: this.#schemaAt(child),
7990
9129
  required: child.category !== "optional"
7991
9130
  }];
7992
9131
  }]);
@@ -8010,7 +9149,14 @@ var ContractCompiler = class ContractCompiler {
8010
9149
  ...owned.description !== void 0 ? { description: owned.description } : {}
8011
9150
  });
8012
9151
  }
8013
- case "optional": return this.#schemaAt(owned.inner);
9152
+ case "optional": {
9153
+ const emitted = this.#schemaAt(owned.inner);
9154
+ const value = owned.default;
9155
+ return value === void 0 ? emitted : INTRINSICS.freeze({
9156
+ ...emitted,
9157
+ default: value
9158
+ });
9159
+ }
8014
9160
  case "nullable": return INTRINSICS.freeze({ anyOf: INTRINSICS.freeze([this.#schemaAt(owned.inner), INTRINSICS.freeze({ type: "null" })]) });
8015
9161
  case "raw": return cloneSchema(owned.schema);
8016
9162
  }
@@ -8026,6 +9172,7 @@ var ContractCompiler = class ContractCompiler {
8026
9172
  this.#guards[index] = this.#repeats(index) ? this.#trackGuard(plan) : plan;
8027
9173
  }
8028
9174
  const root = this.#guardAt(this.#node(0));
9175
+ if (this.#defaults()) this.#checkDefaults(this.#node(0), []);
8029
9176
  this.#guard = root;
8030
9177
  return root;
8031
9178
  }
@@ -8040,14 +9187,25 @@ var ContractCompiler = class ContractCompiler {
8040
9187
  });
8041
9188
  return compiled;
8042
9189
  }
9190
+ #stringGuard(owned) {
9191
+ const guard = stringOf(INTRINSICS.rebase({
9192
+ ...owned.min === void 0 ? {} : { min: owned.min },
9193
+ ...owned.max === void 0 ? {} : { max: owned.max },
9194
+ ...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
9195
+ }, null));
9196
+ return owned.date === true ? whereOf(guard, matchesCalendarDate) : guard;
9197
+ }
9198
+ static #acceptShape(value) {
9199
+ return isSuccess(attempt(() => {
9200
+ const validator = new ShapeValidator(value);
9201
+ validator.validate();
9202
+ refuseExpansion(validator.expansion);
9203
+ }));
9204
+ }
8043
9205
  #guardOf(index) {
8044
9206
  const owned = this.#node(index);
8045
9207
  switch (owned.category) {
8046
- case "string": return stringOf({
8047
- ...owned.min === void 0 ? {} : { min: owned.min },
8048
- ...owned.max === void 0 ? {} : { max: owned.max },
8049
- ...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
8050
- });
9208
+ case "string": return this.#stringGuard(owned);
8051
9209
  case "number": {
8052
9210
  const base = owned.integer === true ? isInteger : isFiniteNumber;
8053
9211
  if (owned.min === void 0 && owned.max === void 0) return base;
@@ -8056,6 +9214,7 @@ var ContractCompiler = class ContractCompiler {
8056
9214
  case "boolean": return isBoolean;
8057
9215
  case "null": return isNull;
8058
9216
  case "json": return isJSONValue;
9217
+ case "shape": return (value) => ContractCompiler.#acceptShape(value);
8059
9218
  case "literal": return literalOf(owned.values);
8060
9219
  case "array": {
8061
9220
  const base = arrayOf(this.#guardAt(owned.items));
@@ -8132,7 +9291,7 @@ var ContractCompiler = class ContractCompiler {
8132
9291
  const ready = this.#parser;
8133
9292
  if (ready !== void 0) return ready;
8134
9293
  this.#prepare();
8135
- if (this.#unions()) this.#buildGuard();
9294
+ if (this.#unions() || this.#defaults()) this.#buildGuard();
8136
9295
  for (const step of iterateIndices(() => this.#order.length)) {
8137
9296
  const index = this.#order[step];
8138
9297
  if (index === void 0) continue;
@@ -8157,12 +9316,8 @@ var ContractCompiler = class ContractCompiler {
8157
9316
  const owned = this.#node(index);
8158
9317
  switch (owned.category) {
8159
9318
  case "string": {
8160
- if (owned.min === void 0 && owned.max === void 0 && owned.pattern === void 0) return parseString;
8161
- const guard = stringOf({
8162
- ...owned.min === void 0 ? {} : { min: owned.min },
8163
- ...owned.max === void 0 ? {} : { max: owned.max },
8164
- ...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
8165
- });
9319
+ if (owned.min === void 0 && owned.max === void 0 && owned.pattern === void 0 && owned.date !== true) return parseString;
9320
+ const guard = this.#stringGuard(owned);
8166
9321
  return (value) => {
8167
9322
  const parsed = parseString(value);
8168
9323
  return parsed !== void 0 && guard(parsed) ? parsed : void 0;
@@ -8180,6 +9335,7 @@ var ContractCompiler = class ContractCompiler {
8180
9335
  case "boolean": return parseBoolean;
8181
9336
  case "null": return (value) => value === null ? null : void 0;
8182
9337
  case "json": return parseJSONValue;
9338
+ case "shape": return (value) => ContractCompiler.#acceptShape(value) ? value : void 0;
8183
9339
  case "literal": {
8184
9340
  const allowed = literalOf(owned.values);
8185
9341
  return (value) => {
@@ -8227,7 +9383,8 @@ var ContractCompiler = class ContractCompiler {
8227
9383
  return [{
8228
9384
  key,
8229
9385
  parse: this.#parserAt(inner),
8230
- optional
9386
+ optional,
9387
+ fill: optional && INTRINSICS.own(child, "default") ? child.default : void 0
8231
9388
  }];
8232
9389
  }]);
8233
9390
  const known = readValue(() => collectMembers(INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(entries), [(entry) => entry.key])), "compileParser", {
@@ -8251,14 +9408,14 @@ var ContractCompiler = class ContractCompiler {
8251
9408
  for (const entryIndex of iterateIndices(() => entries.length)) {
8252
9409
  const entry = entries[entryIndex];
8253
9410
  if (entry === void 0) continue;
8254
- if (present === void 0 ? (seen & 1 << entryIndex) === 0 : !matchesMember(present, entry.key)) {
8255
- if (entry.optional) continue;
8256
- return;
8257
- }
8258
- const raw = record[entry.key];
9411
+ const raw = (present === void 0 ? (seen & 1 << entryIndex) === 0 : !matchesMember(present, entry.key)) ? void 0 : record[entry.key];
8259
9412
  if (raw === void 0) {
8260
- if (entry.optional) continue;
8261
- return;
9413
+ if (!entry.optional) return void 0;
9414
+ if (entry.fill !== void 0) {
9415
+ const fill = isObject(entry.fill) ? cloneJSONValue(entry.fill) : entry.fill;
9416
+ selected[selected.length] = [entry.key, entry.parse(fill)];
9417
+ }
9418
+ continue;
8262
9419
  }
8263
9420
  const parsed = entry.parse(raw);
8264
9421
  if (parsed === void 0) return void 0;
@@ -8292,12 +9449,19 @@ var ContractCompiler = class ContractCompiler {
8292
9449
  parse: this.#parserAt(variant),
8293
9450
  guard: this.#guardAt(variant)
8294
9451
  }]]);
9452
+ const discriminated = this.#discriminate(owned);
8295
9453
  if (owned.mode === "oneOf") return (value) => {
9454
+ const selected = discriminated?.select(value);
9455
+ const arm = selected === void 0 ? void 0 : variants[selected];
9456
+ if (arm !== void 0) return ContractCompiler.#parseArm(arm, value);
8296
9457
  const matching = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(variants), [(variant) => variant.guard(value)]);
8297
9458
  const only = matching[0];
8298
- return matching.length === 1 && only !== void 0 ? only.parse(value) : void 0;
9459
+ return matching.length === 1 && only !== void 0 ? value : void 0;
8299
9460
  };
8300
9461
  return (value) => {
9462
+ const selected = discriminated?.select(value);
9463
+ const arm = selected === void 0 ? void 0 : variants[selected];
9464
+ if (arm !== void 0) return ContractCompiler.#parseArm(arm, value);
8301
9465
  for (const variantIndex of iterateIndices(() => variants.length)) {
8302
9466
  const variant = variants[variantIndex];
8303
9467
  if (variant === void 0) continue;
@@ -8326,6 +9490,7 @@ var ContractCompiler = class ContractCompiler {
8326
9490
  const ready = this.#auditor;
8327
9491
  if (ready !== void 0) return ready;
8328
9492
  this.#prepare();
9493
+ if (this.#defaults()) this.#buildGuard();
8329
9494
  for (const step of iterateIndices(() => this.#order.length)) {
8330
9495
  const index = this.#order[step];
8331
9496
  if (index === void 0) continue;
@@ -8356,13 +9521,14 @@ var ContractCompiler = class ContractCompiler {
8356
9521
  case "string": {
8357
9522
  const node = owned;
8358
9523
  const declared = owned.pattern;
8359
- const refined = owned.min !== void 0 || owned.max !== void 0 || declared !== void 0;
9524
+ const kind = owned.date === true ? "date" : "string";
9525
+ const refined = owned.min !== void 0 || owned.max !== void 0 || declared !== void 0 || owned.date === true;
8360
9526
  const pattern = declared === void 0 ? void 0 : ownPattern(declared, "compileAuditor");
8361
9527
  return (value, path) => {
8362
9528
  if (!isString(value)) return [{
8363
9529
  reason: "type",
8364
9530
  path,
8365
- expected: "string",
9531
+ expected: kind,
8366
9532
  received: preview(value)
8367
9533
  }];
8368
9534
  return refined ? buildStringFaults(node, value, path, pattern) : [];
@@ -8400,6 +9566,12 @@ var ContractCompiler = class ContractCompiler {
8400
9566
  expected: "json",
8401
9567
  received: preview(value)
8402
9568
  }];
9569
+ case "shape": return (value, path) => ContractCompiler.#acceptShape(value) ? [] : [{
9570
+ reason: "type",
9571
+ path,
9572
+ expected: "shape",
9573
+ received: preview(value)
9574
+ }];
8403
9575
  case "literal": {
8404
9576
  const allowed = literalOf(owned.values);
8405
9577
  return (value, path) => allowed(value) ? [] : [{
@@ -8542,7 +9714,11 @@ var ContractCompiler = class ContractCompiler {
8542
9714
  const plans = INTRINSICS.reflect.apply(INTRINSICS.expand, readIndexView(owned.variants), [(variant) => variant === void 0 ? [] : [this.#auditAt(variant)]]);
8543
9715
  const exclusive = owned.mode === "oneOf";
8544
9716
  const count = owned.variants.length;
9717
+ const discriminated = this.#discriminate(owned);
8545
9718
  return (value, path) => {
9719
+ const selected = discriminated?.select(value);
9720
+ const arm = selected === void 0 ? void 0 : plans[selected];
9721
+ if (arm !== void 0) return arm(value, path);
8546
9722
  const perVariant = [];
8547
9723
  for (const index2 of iterateIndices(() => plans.length)) {
8548
9724
  const plan = plans[index2];
@@ -8559,18 +9735,21 @@ var ContractCompiler = class ContractCompiler {
8559
9735
  if (matched > 1) return [{
8560
9736
  reason: "oneOf",
8561
9737
  path,
8562
- matched
9738
+ matched,
9739
+ ...discriminated?.hint
8563
9740
  }];
8564
9741
  }
8565
9742
  const closest = selectClosestFaults(perVariant);
8566
9743
  const report = [exclusive ? {
8567
9744
  reason: "oneOf",
8568
9745
  path,
8569
- matched: 0
9746
+ matched: 0,
9747
+ ...discriminated?.hint
8570
9748
  } : {
8571
9749
  reason: "variant",
8572
9750
  path,
8573
- variants: count
9751
+ variants: count,
9752
+ ...discriminated?.hint
8574
9753
  }];
8575
9754
  appendEntries(report, closest);
8576
9755
  return limitEntries(report, 64);
@@ -8596,7 +9775,7 @@ var ContractCompiler = class ContractCompiler {
8596
9775
  const ready = this.#reporter;
8597
9776
  if (ready !== void 0) return ready;
8598
9777
  this.#prepare();
8599
- if (this.#unions()) this.#buildGuard();
9778
+ if (this.#unions() || this.#defaults()) this.#buildGuard();
8600
9779
  for (const step of iterateIndices(() => this.#order.length)) {
8601
9780
  const index = this.#order[step];
8602
9781
  if (index === void 0) continue;
@@ -8627,14 +9806,15 @@ var ContractCompiler = class ContractCompiler {
8627
9806
  case "string": {
8628
9807
  const node = owned;
8629
9808
  const declared = owned.pattern;
8630
- const refined = owned.min !== void 0 || owned.max !== void 0 || declared !== void 0;
9809
+ const kind = owned.date === true ? "date" : "string";
9810
+ const refined = owned.min !== void 0 || owned.max !== void 0 || declared !== void 0 || owned.date === true;
8631
9811
  const pattern = declared === void 0 ? void 0 : ownPattern(declared, "compileReporter");
8632
9812
  return (value, path) => {
8633
9813
  const parsed = parseString(value);
8634
9814
  if (parsed === void 0) return [{
8635
9815
  reason: "type",
8636
9816
  path,
8637
- expected: "string",
9817
+ expected: kind,
8638
9818
  received: preview(value)
8639
9819
  }];
8640
9820
  return refined ? buildStringFaults(node, parsed, path, pattern) : [];
@@ -8682,6 +9862,12 @@ var ContractCompiler = class ContractCompiler {
8682
9862
  received: preview(value)
8683
9863
  }];
8684
9864
  }
9865
+ case "shape": return (value, path) => ContractCompiler.#acceptShape(value) ? [] : [{
9866
+ reason: "type",
9867
+ path,
9868
+ expected: "shape",
9869
+ received: preview(value)
9870
+ }];
8685
9871
  case "array": {
8686
9872
  const node = owned;
8687
9873
  const item = this.#reportAt(owned.items);
@@ -8799,7 +9985,11 @@ var ContractCompiler = class ContractCompiler {
8799
9985
  const guards = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(variants), [(variant) => variant.guard]);
8800
9986
  const exclusive = owned.mode === "oneOf";
8801
9987
  const count = owned.variants.length;
9988
+ const discriminated = this.#discriminate(owned);
8802
9989
  return (value, path) => {
9990
+ const selected = discriminated?.select(value);
9991
+ const arm = selected === void 0 ? void 0 : plans[selected];
9992
+ if (arm !== void 0) return arm(value, path);
8803
9993
  const perVariant = [];
8804
9994
  for (const index2 of iterateIndices(() => plans.length)) {
8805
9995
  const plan = plans[index2];
@@ -8816,7 +10006,8 @@ var ContractCompiler = class ContractCompiler {
8816
10006
  const report = [{
8817
10007
  reason: "oneOf",
8818
10008
  path,
8819
- matched: 0
10009
+ matched: 0,
10010
+ ...discriminated?.hint
8820
10011
  }];
8821
10012
  appendEntries(report, closest);
8822
10013
  return limitEntries(report, 64);
@@ -8824,13 +10015,15 @@ var ContractCompiler = class ContractCompiler {
8824
10015
  return [{
8825
10016
  reason: "oneOf",
8826
10017
  path,
8827
- matched
10018
+ matched,
10019
+ ...discriminated?.hint
8828
10020
  }];
8829
10021
  }
8830
10022
  const report = [{
8831
10023
  reason: "variant",
8832
10024
  path,
8833
- variants: count
10025
+ variants: count,
10026
+ ...discriminated?.hint
8834
10027
  }];
8835
10028
  appendEntries(report, closest);
8836
10029
  return limitEntries(report, 64);
@@ -8856,7 +10049,7 @@ var ContractCompiler = class ContractCompiler {
8856
10049
  const ready = this.#generator;
8857
10050
  if (ready !== void 0) return ready;
8858
10051
  this.#prepare();
8859
- if (this.#unions()) this.#buildGuard();
10052
+ if (this.#unions() || this.#defaults()) this.#buildGuard();
8860
10053
  for (const step of iterateIndices(() => this.#order.length)) {
8861
10054
  const index = this.#order[step];
8862
10055
  if (index === void 0) continue;
@@ -8884,6 +10077,13 @@ var ContractCompiler = class ContractCompiler {
8884
10077
  const owned = this.#node(index);
8885
10078
  switch (owned.category) {
8886
10079
  case "string": {
10080
+ if (owned.date === true) return (random) => {
10081
+ const year = 2e3 + INTRINSICS.floor(drawRandom(random, "string") * 100);
10082
+ const month = 1 + INTRINSICS.floor(drawRandom(random, "string") * 12);
10083
+ const length = computeMonthLength(year, month);
10084
+ const day = 1 + INTRINSICS.floor(drawRandom(random, "string") * length);
10085
+ return `${year}-${month < 10 ? "0" : ""}${month}-${day < 10 ? "0" : ""}${day}`;
10086
+ };
8887
10087
  const min = owned.min ?? 0;
8888
10088
  const max = owned.max ?? INTRINSICS.max(min, 12);
8889
10089
  const length = INTRINSICS.max(min, INTRINSICS.min(max, 8));
@@ -8923,6 +10123,11 @@ var ContractCompiler = class ContractCompiler {
8923
10123
  }
8924
10124
  case "boolean": return (random) => drawRandom(random, "boolean") >= .5;
8925
10125
  case "null": return () => null;
10126
+ case "shape": return () => ({
10127
+ category: "object",
10128
+ properties: {},
10129
+ additionalProperties: false
10130
+ });
8926
10131
  case "json": return (random) => {
8927
10132
  const pick = INTRINSICS.floor(drawRandom(random, "json") * 5);
8928
10133
  if (pick === 0) return null;
@@ -9089,14 +10294,15 @@ var ContractCompiler = class ContractCompiler {
9089
10294
  * eager well-formedness pass — there is no second prepass and no alias for it:
9090
10295
  * it enforces every bound domain and range used by the artifacts, including
9091
10296
  * non-empty literal/union vocabularies, finite literal numbers, integer-range
9092
- * satisfiability, unflagged string patterns, optional-shape placement, and the
9093
- * recursively supported raw-schema vocabulary where every present property or
9094
- * dense union member is a record.
10297
+ * satisfiability, unflagged string patterns, optional-shape and default
10298
+ * placement, and the recursively supported raw-schema vocabulary where every
10299
+ * present property or dense union member is a record. It judges a default's
10300
+ * structure only; each compiler refuses a default its inner guard refuses.
9095
10301
  * Active ancestors are tracked so shared children remain legal. Every
9096
10302
  * standalone compiler reaches this same validation once, over its owned
9097
10303
  * snapshot, through {@link ContractCompiler} preparation.
9098
- * Failures have deterministic precedence independent of traversal order: depth,
9099
- * then structure, then cycle, then field and vocabulary policy.
10304
+ * Cyclic graphs refuse before depth measurement, with structure before cycle.
10305
+ * Acyclic graphs report depth before structure, then field and vocabulary policy.
9100
10306
  *
9101
10307
  * @param shape - The shape graph to gate
9102
10308
  * @returns Nothing; successful return means recursive compilation is structurally safe, depth-safe, and bounded in emitted nodes
@@ -9238,9 +10444,104 @@ function compileReporter(shape, value, path = []) {
9238
10444
  function compileAuditor(shape, value, path = []) {
9239
10445
  return contain(() => new ContractCompiler(shape).auditor(value, path), "compileAuditor");
9240
10446
  }
10447
+ // src/core/LazyContract.ts
10448
+ /**
10449
+ * Owns a contract whose function members compile together on the first call to any.
10450
+ *
10451
+ * @remarks
10452
+ * For a declaration made entirely by builders, where preparation and the schema have
10453
+ * already asked everything that can refuse. A module that declares its contracts as
10454
+ * data then pays for a contract only when something uses it, and each member is a
10455
+ * plain function with one identity, so destructuring and spreading compile nothing.
10456
+ *
10457
+ * A compile can still fail for the host's reasons: a first call near the stack limit,
10458
+ * or a host whose members were replaced after this contract was created, which it
10459
+ * refuses to compile on since the result would outlive the replacement. Neither says
10460
+ * anything about a later call, which compiles afresh. Until then a guard answers
10461
+ * `false` and a parser `undefined`, and the diagnostic and seed members publish the
10462
+ * failure as their doors do.
10463
+ */
10464
+ var LazyContract = class {
10465
+ #shape;
10466
+ #pending;
10467
+ #settled;
10468
+ #bundle;
10469
+ /**
10470
+ * Retains a declaration and the compiler already prepared from it.
10471
+ *
10472
+ * @param shape - The sealed declaration
10473
+ * @param compiler - The compiler that owns its prepared index
10474
+ */
10475
+ constructor(shape, compiler) {
10476
+ this.#shape = shape;
10477
+ this.#pending = compiler;
10478
+ }
10479
+ /**
10480
+ * Compiles the schema, which refuses a bad declaration, and publishes the bundle.
10481
+ *
10482
+ * @param schema - The schema the prepared compiler emitted
10483
+ * @returns The frozen bundle, in the key order the compiler's own bundle uses
10484
+ */
10485
+ publish(schema) {
10486
+ return INTRINSICS.freeze({
10487
+ schema,
10488
+ is: this.#is(),
10489
+ parse: this.#parse(),
10490
+ audit: this.#audit(),
10491
+ explain: this.#explain(),
10492
+ generate: this.#generate()
10493
+ });
10494
+ }
10495
+ #is() {
10496
+ return (value) => {
10497
+ const bundle = this.#bundle ?? this.#attempt();
10498
+ return bundle !== void 0 && bundle.is(value);
10499
+ };
10500
+ }
10501
+ #parse() {
10502
+ return (value) => {
10503
+ const bundle = this.#bundle ?? this.#attempt();
10504
+ return bundle === void 0 ? void 0 : bundle.parse(value);
10505
+ };
10506
+ }
10507
+ #audit() {
10508
+ return (value, path = []) => (this.#settled ?? this.#settle("compileAuditor")).auditor(value, path);
10509
+ }
10510
+ #explain() {
10511
+ return (value, path = []) => (this.#settled ?? this.#settle("compileReporter")).reporter(value, path);
10512
+ }
10513
+ #generate() {
10514
+ return (random) => (this.#settled ?? this.#settle("compileGenerator")).generator(random);
10515
+ }
10516
+ #attempt() {
10517
+ attempt(() => this.#settle("createContract"));
10518
+ return this.#bundle;
10519
+ }
10520
+ #settle(door) {
10521
+ return contain(() => {
10522
+ if (ShapePass.tampered()) throw new ContractError(`${door}: a host member this contract compiles on was replaced after it was created`, {
10523
+ code: "structure",
10524
+ context: {
10525
+ path: [],
10526
+ shape: "contract"
10527
+ }
10528
+ });
10529
+ const compiler = this.#pending ?? new ContractCompiler(this.#shape);
10530
+ this.#pending = void 0;
10531
+ this.#bundle = compiler.contract;
10532
+ this.#settled = compiler;
10533
+ return compiler;
10534
+ }, door);
10535
+ }
10536
+ };
9241
10537
  // src/core/factories.ts
9242
10538
  function createContract(shape) {
9243
- return contain(() => new ContractCompiler(shape).contract, "createContract");
10539
+ return contain(() => {
10540
+ const compiler = new ContractCompiler(shape);
10541
+ const expansion = ShapePass.expansionOf(shape);
10542
+ if (expansion === void 0 || expansion === 1) return compiler.contract;
10543
+ return new LazyContract(shape, compiler).publish(compiler.schema);
10544
+ }, "createContract");
9244
10545
  }
9245
10546
  // src/core/ValueInferer.ts
9246
10547
  /**
@@ -9847,7 +11148,9 @@ function samplesToSchema(samples, options) {
9847
11148
  * rather than parameters, so no caller can pre-populate either and change what
9848
11149
  * the conversion widens. Construction observes nothing; `shape` runs the whole
9849
11150
  * walk and every refusal it raises is published by that door under the door's
9850
- * own name.
11151
+ * own name. A strict walk refuses where a lenient one widens, through the one
11152
+ * `#widen` both share, and its per-node `#inspect` refuses every keyword the
11153
+ * lenient precedence would read past.
9851
11154
  *
9852
11155
  * The recursion is `#` private for the same reason it is bounded: it is the
9853
11156
  * class's defining spine, and its state has no meaning outside one call. The
@@ -9863,73 +11166,318 @@ var SchemaShaper = class SchemaShaper {
9863
11166
  static #weakSet = WeakSet;
9864
11167
  static #weakMap = WeakMap;
9865
11168
  #source;
11169
+ #strict;
9866
11170
  #visited;
9867
11171
  #memo;
9868
- constructor(schema) {
11172
+ #enclosed;
11173
+ #exclusive;
11174
+ #path;
11175
+ #oneOfs;
11176
+ #built;
11177
+ #shared;
11178
+ constructor(schema, strict = false) {
9869
11179
  this.#source = schema;
11180
+ this.#strict = strict;
9870
11181
  this.#visited = new SchemaShaper.#weakSet();
9871
11182
  this.#memo = new SchemaShaper.#weakMap();
11183
+ this.#enclosed = new SchemaShaper.#weakMap();
11184
+ this.#exclusive = new SchemaShaper.#weakMap();
11185
+ this.#path = [];
11186
+ this.#oneOfs = 0;
11187
+ this.#built = 0;
11188
+ this.#shared = false;
9872
11189
  }
9873
11190
  /**
9874
11191
  * Converts the retained schema into a validating contract shape.
9875
11192
  *
9876
- * @returns The built shape, widened wherever the schema is inexpressible
9877
- * @throws {ContractError} When schema traversal fails
11193
+ * @returns The built shape, widened wherever a lenient schema is inexpressible
11194
+ * @throws {ContractError} When schema traversal fails, or when a strict conversion refuses
9878
11195
  */
9879
11196
  shape() {
9880
- return this.#convert(this.#source, 32);
11197
+ if (this.#strict && isRecord(this.#source) && INTRINSICS.own(this.#source, "default")) throw this.#refusal("a default needs an optional property to fill", "default");
11198
+ const shape = this.#convert(this.#source, 32, false);
11199
+ return !this.#strict && this.#exceeds(shape) ? this.#shallow(shape) : shape;
11200
+ }
11201
+ #exceeds(shape) {
11202
+ if (!this.#shared && this.#built <= 1024) return false;
11203
+ const validator = new ShapeValidator(shape);
11204
+ validator.validate();
11205
+ return (validator.expansion ?? 0) > COMPILE_NODE_LIMIT;
11206
+ }
11207
+ #shallow(shape) {
11208
+ const raw = rawShape({});
11209
+ switch (shape.category) {
11210
+ case "nullable": return nullableShape(this.#shallow(shape.inner));
11211
+ case "array": return arrayShape(raw, INTRINSICS.rebase({
11212
+ ...shape.min === void 0 ? {} : { min: shape.min },
11213
+ ...shape.max === void 0 ? {} : { max: shape.max },
11214
+ ...shape.description === void 0 ? {} : { description: shape.description }
11215
+ }, null));
11216
+ case "object": {
11217
+ const pairs = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(INTRINSICS.keys(shape.properties)), [(key) => [key, shape.properties[key]?.category === "optional" ? optionalShape(raw) : raw]]);
11218
+ const properties = INTRINSICS.rebase(INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [pairs]) }), null);
11219
+ const extra = shape.additionalProperties;
11220
+ return objectShape(properties, INTRINSICS.rebase({
11221
+ additionalProperties: isObject(extra) ? raw : extra ?? false,
11222
+ ...shape.description === void 0 ? {} : { description: shape.description }
11223
+ }, null));
11224
+ }
11225
+ default: return raw;
11226
+ }
9881
11227
  }
9882
- #convert(schema, depth) {
9883
- if (!(depth > 0)) return rawShape({});
9884
- if (!matchesRecordBrand(schema)) return rawShape({});
9885
- if (matchesVisited(this.#visited, schema)) return rawShape({});
9886
- const depthMemo = INTRINSICS.reflect.apply(INTRINSICS.recall, this.#memo, [schema]);
11228
+ #convert(schema, depth, enclosed) {
11229
+ if (!(depth > 0)) return this.#widen("a schema may not nest past the depth limit", void 0);
11230
+ if (!matchesRecordBrand(schema)) return this.#widen("every schema node must be a plain record", void 0);
11231
+ if (matchesVisited(this.#visited, schema)) return this.#widen("a schema may not contain a cycle", void 0);
11232
+ const memo = this.#oneOfs > 0 ? this.#exclusive : enclosed ? this.#enclosed : this.#memo;
11233
+ const depthMemo = INTRINSICS.reflect.apply(INTRINSICS.recall, memo, [schema]);
9887
11234
  const cached = depthMemo === void 0 ? void 0 : INTRINSICS.reflect.apply(INTRINSICS.fetch, depthMemo, [depth]);
9888
- if (cached) return cached;
11235
+ if (cached) {
11236
+ this.#shared = true;
11237
+ return cached;
11238
+ }
9889
11239
  admitVisited(this.#visited, schema);
9890
11240
  try {
9891
- const shape = this.#build(schema, depth);
9892
- retainDepth(this.#memo, schema, depth, shape);
11241
+ if (this.#strict) this.#inspect(schema);
11242
+ const built = this.#build(schema, depth, enclosed);
11243
+ const shape = INTRINSICS.own(schema, "nullable") && INTRINSICS.reflect.read(schema, "nullable") === true ? nullableShape(built) : built;
11244
+ retainDepth(memo, schema, depth, shape);
9893
11245
  return shape;
9894
11246
  } finally {
9895
11247
  omitVisited(this.#visited, schema);
9896
11248
  }
9897
11249
  }
9898
- #build(schema, depth) {
9899
- const description = isString(schema.description) ? schema.description : void 0;
9900
- if (isArray(schema.enum)) {
11250
+ #descend(schema, depth, enclosed, first, second) {
11251
+ this.#path[this.#path.length] = first;
11252
+ if (second !== void 0) this.#path[this.#path.length] = second;
11253
+ if (this.#strict && first !== "properties" && isRecord(schema) && INTRINSICS.own(schema, "default")) throw this.#refusal("a default needs an optional property to fill", "default");
11254
+ const shape = this.#convert(schema, depth, enclosed);
11255
+ this.#path.length -= second === void 0 ? 1 : 2;
11256
+ return shape;
11257
+ }
11258
+ #widen(message, description, first, second) {
11259
+ if (this.#strict) throw this.#refusal(message, first, second);
11260
+ this.#built += 1;
11261
+ return rawShape(description === void 0 ? {} : { description });
11262
+ }
11263
+ #describe(shape, description) {
11264
+ if (description === void 0) return shape;
11265
+ switch (shape.category) {
11266
+ case "optional": return shape;
11267
+ case "nullable": return nullableShape(this.#describe(shape.inner, description));
11268
+ case "raw": return rawShape({
11269
+ ...shape.schema,
11270
+ description
11271
+ });
11272
+ default: return INTRINSICS.freeze({
11273
+ ...shape,
11274
+ description
11275
+ });
11276
+ }
11277
+ }
11278
+ #refusal(message, first, second, third) {
11279
+ const path = pathOf(this.#path, first, second, third);
11280
+ return new ContractError(`schemaToShape: ${message} at ${truncateFaultText(renderPath(path) || "value", 160)}`, {
11281
+ code: "structure",
11282
+ context: {
11283
+ path,
11284
+ shape: "schema"
11285
+ }
11286
+ });
11287
+ }
11288
+ #inspect(schema) {
11289
+ const keys = INTRINSICS.keys(schema);
11290
+ for (const index of iterateIndices(() => keys.length)) {
11291
+ const key = keys[index];
11292
+ if (key === void 0) continue;
11293
+ if (!(INTRINSICS.reflect.apply(INTRINSICS.some, STRICT_SCHEMA_KEYWORDS, [(keyword) => keyword === key]) || key === "format" && schema.format === "date")) throw this.#refusal("a strict conversion refuses a keyword it cannot honour", key);
11294
+ }
11295
+ this.#inspectAnnotations(schema);
11296
+ if (INTRINSICS.own(schema, "default") && !isJSONValue(schema.default)) throw this.#refusal("a default must be a JSON value", "default");
11297
+ const types = this.#inspectType(schema);
11298
+ this.#inspectForm(schema, types);
11299
+ const hasForm = INTRINSICS.own(schema, "enum") || INTRINSICS.own(schema, "oneOf") || INTRINSICS.own(schema, "anyOf");
11300
+ const object = types.length === 0 && INTRINSICS.own(schema, "properties") ? ["object"] : types;
11301
+ const effective = hasForm ? [] : object;
11302
+ this.#confine(schema, [
11303
+ "minLength",
11304
+ "maxLength",
11305
+ "format"
11306
+ ], this.#names(effective, "string"));
11307
+ this.#confine(schema, ["minimum", "maximum"], this.#names(effective, "number", "integer"));
11308
+ this.#confine(schema, [
11309
+ "items",
11310
+ "minItems",
11311
+ "maxItems"
11312
+ ], this.#names(effective, "array"));
11313
+ this.#confine(schema, [
11314
+ "properties",
11315
+ "required",
11316
+ "additionalProperties"
11317
+ ], this.#names(effective, "object"));
11318
+ this.#inspectLength(INTRINSICS.own(schema, "minLength") ? schema.minLength : void 0, INTRINSICS.own(schema, "maxLength") ? schema.maxLength : void 0, "minLength", "maxLength");
11319
+ this.#inspectLength(INTRINSICS.own(schema, "minItems") ? schema.minItems : void 0, INTRINSICS.own(schema, "maxItems") ? schema.maxItems : void 0, "minItems", "maxItems");
11320
+ this.#inspectRange(schema, this.#names(effective, "integer"));
11321
+ this.#inspectObject(schema);
11322
+ }
11323
+ #inspectAnnotations(schema) {
11324
+ const texts = [
11325
+ "title",
11326
+ "description",
11327
+ "$schema",
11328
+ "$id",
11329
+ "$comment"
11330
+ ];
11331
+ for (const index of iterateIndices(() => texts.length)) {
11332
+ const keyword = texts[index];
11333
+ if (keyword === void 0) continue;
11334
+ const value = INTRINSICS.own(schema, keyword) ? INTRINSICS.reflect.read(schema, keyword) : void 0;
11335
+ if (value !== void 0 && !isString(value)) throw this.#refusal(`${keyword} must be a string`, keyword);
11336
+ }
11337
+ const flags = [
11338
+ "deprecated",
11339
+ "readOnly",
11340
+ "writeOnly"
11341
+ ];
11342
+ for (const index of iterateIndices(() => flags.length)) {
11343
+ const keyword = flags[index];
11344
+ if (keyword === void 0) continue;
11345
+ const value = INTRINSICS.own(schema, keyword) ? INTRINSICS.reflect.read(schema, keyword) : void 0;
11346
+ if (value !== void 0 && !isBoolean(value)) throw this.#refusal(`${keyword} must be a boolean`, keyword);
11347
+ }
11348
+ const examples = INTRINSICS.own(schema, "examples") ? INTRINSICS.reflect.read(schema, "examples") : void 0;
11349
+ if (examples !== void 0 && !isArray(examples)) throw this.#refusal("examples must be an array", "examples");
11350
+ }
11351
+ #inspectType(schema) {
11352
+ const declared = INTRINSICS.own(schema, "type") ? schema.type : void 0;
11353
+ if (declared === void 0) return [];
11354
+ const names = isArray(declared) ? this.#entries(declared, "type") : [declared];
11355
+ const known = names.length > 0 && this.#unique(names);
11356
+ const types = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(JSON_SCHEMA_TYPES), [(type) => INTRINSICS.reflect.apply(INTRINSICS.some, names, [(name) => name === type])]);
11357
+ if (!known || types.length !== names.length) throw this.#refusal("type must name the supported types", "type");
11358
+ return types;
11359
+ }
11360
+ #inspectForm(schema, types) {
11361
+ if (INTRINSICS.own(schema, "enum")) {
11362
+ const members = this.#entries(schema.enum, "enum");
11363
+ const malformed = INTRINSICS.reflect.apply(INTRINSICS.some, members, [(entry) => entry !== null && (!isLiteralValue(entry) || typeof entry === "number" && !isFiniteNumber(entry))]);
11364
+ if (members.length === 0 || malformed || !this.#unique(members)) throw this.#refusal("enum must list unique finite primitives", "enum");
11365
+ 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");
11366
+ if (INTRINSICS.own(schema, "oneOf")) throw this.#refusal("a strict conversion refuses oneOf beside enum", "oneOf");
11367
+ if (INTRINSICS.own(schema, "anyOf")) throw this.#refusal("a strict conversion refuses anyOf beside enum", "anyOf");
11368
+ return;
11369
+ }
11370
+ const keywords = ["oneOf", "anyOf"];
11371
+ for (const index of iterateIndices(() => keywords.length)) {
11372
+ const keyword = keywords[index];
11373
+ if (keyword === void 0 || !INTRINSICS.own(schema, keyword)) continue;
11374
+ const variants = this.#entries(INTRINSICS.reflect.read(schema, keyword), keyword);
11375
+ if (variants.length === 0) throw this.#refusal(`${keyword} needs a variant`, keyword);
11376
+ for (const variantIndex of iterateIndices(() => variants.length)) if (!isRecord(variants[variantIndex])) throw this.#refusal("every variant must be a schema", keyword, INTRINSICS.text(variantIndex));
11377
+ }
11378
+ const union = INTRINSICS.own(schema, "oneOf") || INTRINSICS.own(schema, "anyOf");
11379
+ if (INTRINSICS.own(schema, "oneOf") && INTRINSICS.own(schema, "anyOf")) throw this.#refusal("a strict conversion refuses anyOf beside oneOf", "anyOf");
11380
+ if (union && types.length > 0) throw this.#refusal("a strict conversion refuses type beside a union", "type");
11381
+ }
11382
+ #inspectLength(min, max, minKey, maxKey) {
11383
+ 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);
11384
+ 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);
11385
+ if (isFiniteNumber(min) && isFiniteNumber(max) && min > max) throw this.#refusal("a length range may not be contradictory", minKey);
11386
+ }
11387
+ #inspectRange(schema, integer) {
11388
+ const min = INTRINSICS.own(schema, "minimum") ? schema.minimum : void 0;
11389
+ const max = INTRINSICS.own(schema, "maximum") ? schema.maximum : void 0;
11390
+ if (min !== void 0 && !isFiniteNumber(min)) throw this.#refusal("a range bound must be a finite number", "minimum");
11391
+ if (max !== void 0 && !isFiniteNumber(max)) throw this.#refusal("a range bound must be a finite number", "maximum");
11392
+ if (isFiniteNumber(min) && isFiniteNumber(max)) {
11393
+ if (min > max) throw this.#refusal("a range may not be contradictory", "minimum");
11394
+ if (integer && INTRINSICS.ceil(min) > INTRINSICS.floor(max)) throw this.#refusal("an integer range may not be empty", "minimum");
11395
+ }
11396
+ }
11397
+ #inspectObject(schema) {
11398
+ const properties = INTRINSICS.own(schema, "properties") ? schema.properties : void 0;
11399
+ if (properties !== void 0 && !isRecord(properties)) throw this.#refusal("properties must be a plain record", "properties");
11400
+ const extra = INTRINSICS.own(schema, "additionalProperties") ? schema.additionalProperties : void 0;
11401
+ if (extra !== void 0 && !isBoolean(extra) && !isRecord(extra)) throw this.#refusal("additionalProperties must be a boolean or a schema", "additionalProperties");
11402
+ if (!INTRINSICS.own(schema, "required")) return;
11403
+ const names = this.#entries(schema.required, "required");
11404
+ 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");
11405
+ }
11406
+ #confine(schema, keywords, applies) {
11407
+ if (applies) return;
11408
+ for (const index of iterateIndices(() => keywords.length)) {
11409
+ const keyword = keywords[index];
11410
+ if (keyword !== void 0 && INTRINSICS.own(schema, keyword)) throw this.#refusal("a strict conversion refuses a keyword this node never reads", keyword);
11411
+ }
11412
+ }
11413
+ #names(types, ...names) {
11414
+ return INTRINSICS.reflect.apply(INTRINSICS.some, types, [(type) => INTRINSICS.reflect.apply(INTRINSICS.some, names, [(name) => name === type])]);
11415
+ }
11416
+ #fits(entry, types) {
11417
+ if (entry === null) return this.#names(types, "null");
11418
+ if (isString(entry)) return this.#names(types, "string");
11419
+ if (isBoolean(entry)) return this.#names(types, "boolean");
11420
+ return isInteger(entry) ? this.#names(types, "number", "integer") : this.#names(types, "number");
11421
+ }
11422
+ #entries(value, keyword) {
11423
+ if (!isArray(value)) throw this.#refusal(`${keyword} must be an array`, keyword);
11424
+ const snapshot = readArrayEntries(value);
11425
+ if (isFailure(snapshot)) throw snapshot.error;
11426
+ if (!snapshot.value.dense) throw this.#refusal(`${keyword} must be a dense array`, keyword);
11427
+ return snapshot.value.entries;
11428
+ }
11429
+ #unique(entries) {
11430
+ const seen = collectMembers([]);
11431
+ for (const index of iterateIndices(() => entries.length)) {
11432
+ const entry = entries[index];
11433
+ if (matchesMember(seen, entry)) return false;
11434
+ admitMember(seen, entry);
11435
+ }
11436
+ return true;
11437
+ }
11438
+ #build(schema, depth, enclosed) {
11439
+ this.#built += 1;
11440
+ const description = INTRINSICS.own(schema, "description") && isString(schema.description) ? schema.description : void 0;
11441
+ if (INTRINSICS.own(schema, "$ref")) return this.#widen("a reference is not resolved", description, "$ref");
11442
+ if (INTRINSICS.own(schema, "enum") && isArray(schema.enum)) {
9901
11443
  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]);
9902
- const valid = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(entry) => isLiteralValue(entry) && (typeof entry !== "number" || isFiniteNumber(entry))]);
11444
+ 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");
11445
+ const valid = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(entry) => entry !== null]);
11446
+ const nullable = valid.length < observed.length;
9903
11447
  const pairs = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(valid), [(entry, index) => [`${typeof entry}:${INTRINSICS.text(entry)}`, index]]);
9904
11448
  const reversed = INTRINSICS.reflect.apply(INTRINSICS.flip, pairs, []);
9905
11449
  const first = INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [reversed]) });
9906
11450
  const literals = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(valid), [(entry, index) => first[`${typeof entry}:${INTRINSICS.text(entry)}`] === index]);
9907
- if (literals.length > 0) return literalShape(literals, description === void 0 ? void 0 : { description });
11451
+ if (literals.length > 0) {
11452
+ const literal = literalShape(literals, description === void 0 ? void 0 : { description });
11453
+ return nullable ? nullableShape(literal) : literal;
11454
+ }
11455
+ if (nullable) return nullShape(description === void 0 ? void 0 : { description });
9908
11456
  }
9909
- if (isArray(schema.oneOf)) {
9910
- 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]);
9911
- const records = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [isRecord]);
9912
- if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
9913
- const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(records), [(entry) => this.#convert(entry, depth - 1)]);
9914
- if (variants.length > 0) return INTRINSICS.reflect.apply(oneOfShape, void 0, variants);
11457
+ if (INTRINSICS.own(schema, "oneOf") && isArray(schema.oneOf)) {
11458
+ const union = this.#buildUnion(schema.oneOf, "oneOf", depth, description, enclosed);
11459
+ if (union !== void 0) return union;
9915
11460
  }
9916
- if (isArray(schema.anyOf)) {
9917
- 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]);
9918
- const records = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [isRecord]);
9919
- if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
9920
- const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(records), [(entry) => this.#convert(entry, depth - 1)]);
9921
- if (variants.length > 0) return INTRINSICS.reflect.apply(unionShape, void 0, variants);
11461
+ if (INTRINSICS.own(schema, "anyOf") && isArray(schema.anyOf)) {
11462
+ const union = this.#buildUnion(schema.anyOf, "anyOf", depth, description, enclosed);
11463
+ if (union !== void 0) return union;
9922
11464
  }
9923
- const category = schema.type;
11465
+ const category = INTRINSICS.own(schema, "type") ? schema.type : void 0;
9924
11466
  if (isArray(category)) {
9925
11467
  const observed = INTRINSICS.from(parseEnumValues(category, JSON_SCHEMA_TYPES));
9926
- if (INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry === void 0])) return rawShape(description === void 0 ? {} : { description });
11468
+ if (INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry === void 0])) return this.#widen("type must name the supported types", description, "type");
9927
11469
  const members = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(member, index) => INTRINSICS.reflect.apply(INTRINSICS.find, observed, [(entry) => entry === member]) === index]);
9928
- if (members.length === 0 || members.length > 256) return rawShape(description === void 0 ? {} : { description });
11470
+ if (members.length === 0 || members.length > 256) return this.#widen("type must name the supported types", description, "type");
11471
+ const others = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(members), [(member) => member !== "null"]);
11472
+ const other = others[0];
11473
+ if (members.length === 2 && others.length === 1 && other !== void 0) return nullableShape(this.#build({
11474
+ ...schema,
11475
+ type: other
11476
+ }, depth, enclosed));
9929
11477
  const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(members), [(member) => this.#build({
9930
11478
  ...schema,
9931
11479
  type: member
9932
- }, depth)]);
11480
+ }, depth, enclosed || members.length > 1)]);
9933
11481
  const first = variants[0];
9934
11482
  if (variants.length === 1 && first !== void 0) return first;
9935
11483
  const union = INTRINSICS.reflect.apply(unionShape, void 0, variants);
@@ -9938,45 +11486,92 @@ var SchemaShaper = class SchemaShaper {
9938
11486
  description
9939
11487
  });
9940
11488
  }
9941
- const type = isString(category) ? schema.type : void 0;
9942
- if (type === "string") return stringShape({
9943
- ...deriveLengthBounds(schema.minLength, schema.maxLength),
9944
- ...description === void 0 ? {} : { description }
9945
- });
9946
- if (type === "number") return numberShape({
9947
- ...deriveRangeBounds(schema.minimum, schema.maximum),
9948
- ...description === void 0 ? {} : { description }
9949
- });
11489
+ const type = isString(category) && INTRINSICS.own(schema, "type") ? schema.type : void 0;
11490
+ if (type === "string") {
11491
+ const bounds = deriveLengthBounds(INTRINSICS.own(schema, "minLength") ? schema.minLength : void 0, INTRINSICS.own(schema, "maxLength") ? schema.maxLength : void 0);
11492
+ const formatted = this.#strict && INTRINSICS.own(schema, "format") && schema.format === "date";
11493
+ const dated = formatted && (bounds.min ?? 0) <= 10 && (bounds.max ?? 10) >= 10;
11494
+ if (formatted && !dated) throw this.#refusal(`a date length range must admit length 10`, "format");
11495
+ return stringShape(INTRINSICS.rebase({
11496
+ ...bounds,
11497
+ ...dated ? { date: true } : {},
11498
+ ...description === void 0 ? {} : { description }
11499
+ }, null));
11500
+ }
11501
+ if (type === "number") {
11502
+ const bounds = deriveRangeBounds(INTRINSICS.own(schema, "minimum") ? schema.minimum : void 0, INTRINSICS.own(schema, "maximum") ? schema.maximum : void 0);
11503
+ return numberShape(INTRINSICS.rebase({
11504
+ ...bounds,
11505
+ ...description === void 0 ? {} : { description }
11506
+ }, null));
11507
+ }
9950
11508
  if (type === "integer") {
9951
- const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
9952
- return integerShape(INTRINSICS.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > INTRINSICS.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? description === void 0 ? void 0 : { description } : {
11509
+ const bounds = deriveRangeBounds(INTRINSICS.own(schema, "minimum") ? schema.minimum : void 0, INTRINSICS.own(schema, "maximum") ? schema.maximum : void 0);
11510
+ 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({
9953
11511
  ...bounds,
9954
11512
  ...description === void 0 ? {} : { description }
9955
- });
11513
+ }, null));
9956
11514
  }
9957
11515
  if (type === "boolean") return booleanShape(description === void 0 ? void 0 : { description });
9958
11516
  if (type === "null") return nullShape(description === void 0 ? void 0 : { description });
9959
- if (type === "array") return arrayShape(isRecord(schema.items) ? this.#convert(schema.items, depth - 1) : rawShape({}), {
9960
- ...deriveLengthBounds(schema.minItems, schema.maxItems),
9961
- ...description === void 0 ? {} : { description }
9962
- });
9963
- if (type === "object" || type === void 0 && isRecord(schema.properties)) return this.#buildObject(schema, depth, description);
9964
- return rawShape(description === void 0 ? {} : { description });
11517
+ if (type === "array") {
11518
+ 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");
11519
+ const bounds = deriveLengthBounds(INTRINSICS.own(schema, "minItems") ? schema.minItems : void 0, INTRINSICS.own(schema, "maxItems") ? schema.maxItems : void 0);
11520
+ return arrayShape(items, INTRINSICS.rebase({
11521
+ ...bounds,
11522
+ ...description === void 0 ? {} : { description }
11523
+ }, null));
11524
+ }
11525
+ if (type === "object" || this.#strict && type === void 0 && INTRINSICS.own(schema, "properties") && isRecord(schema.properties)) return this.#buildObject(schema, depth, description, enclosed);
11526
+ 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);
11527
+ return this.#widen("a schema must name a type, an enum, or a union", description);
11528
+ }
11529
+ #buildUnion(list, keyword, depth, description, enclosed) {
11530
+ const observed = INTRINSICS.from(iterateIndices(() => list.length), (index) => list[index]);
11531
+ const arms = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(entry) => entry === true || isRecord(entry)]);
11532
+ if (arms.length > 256) return this.#widen(`${keyword} exceeds the breadth limit`, description, keyword);
11533
+ 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")]);
11534
+ const hasTrue = INTRINSICS.reflect.apply(INTRINSICS.some, arms, [(entry) => entry === true]);
11535
+ const paired = arms.length === 2 && nulls.length === 1 && !hasTrue && !(this.#strict && keyword === "oneOf");
11536
+ const exclusive = this.#strict && keyword === "oneOf" ? 1 : 0;
11537
+ this.#oneOfs += exclusive;
11538
+ const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(arms), [(entry, index) => {
11539
+ if (entry !== true) {
11540
+ const position = paired ? enclosed : true;
11541
+ return this.#descend(entry, depth - 1, position, keyword, INTRINSICS.text(index));
11542
+ }
11543
+ this.#built += 1;
11544
+ return rawShape({});
11545
+ }]);
11546
+ this.#oneOfs -= exclusive;
11547
+ const other = variants[arms[0] === nulls[0] ? 1 : 0];
11548
+ if (paired && other !== void 0) return nullableShape(this.#describe(other, description));
11549
+ if (variants.length > 0) {
11550
+ const build = this.#strict && keyword === "oneOf" ? oneOfShape : unionShape;
11551
+ return this.#describe(INTRINSICS.reflect.apply(build, void 0, variants), description);
11552
+ }
11553
+ return INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry === false]) ? this.#widen(`${keyword} admits nothing`, description, keyword) : void 0;
9965
11554
  }
9966
- #buildObject(schema, depth, description) {
9967
- const propertiesSource = isRecord(schema.properties) ? schema.properties : void 0;
9968
- 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]) : [];
11555
+ #buildObject(schema, depth, description, enclosed) {
11556
+ 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");
11557
+ const propertiesSource = INTRINSICS.own(schema, "properties") && isRecord(schema.properties) ? schema.properties : void 0;
11558
+ 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]) : [];
9969
11559
  const allKeys = propertiesSource === void 0 ? [] : INTRINSICS.keys(propertiesSource);
9970
11560
  const truncated = allKeys.length > 256;
11561
+ if (this.#strict && truncated) throw this.#refusal("properties exceeds the breadth limit", "properties");
9971
11562
  const keys = limitEntries(allKeys, 256);
11563
+ const extra = INTRINSICS.own(schema, "additionalProperties") ? schema.additionalProperties : void 0;
11564
+ const unread = truncated || INTRINSICS.own(schema, "patternProperties");
11565
+ const open = unread || extra !== false && (!this.#strict || extra !== void 0);
9972
11566
  const pairs = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(keys), [(key) => {
9973
- const child = propertiesSource?.[key];
9974
- const childShape = isRecord(child) ? this.#convert(child, depth - 1) : rawShape({});
9975
- return [key, INTRINSICS.reflect.apply(INTRINSICS.some, requiredSource, [(entry) => isString(entry) && entry === key]) ? childShape : optionalShape(childShape)];
11567
+ const child = propertiesSource !== void 0 && INTRINSICS.own(propertiesSource, key) ? propertiesSource[key] : void 0;
11568
+ 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);
11569
+ if (!INTRINSICS.reflect.apply(INTRINSICS.some, requiredSource, [(entry) => isString(entry) && entry === key])) return [key, this.#wrap(key, child, childShape, open || enclosed)];
11570
+ if (this.#strict && isRecord(child) && INTRINSICS.own(child, "default")) throw this.#refusal("a default needs an optional property to fill", "properties", key, "default");
11571
+ return [key, childShape];
9976
11572
  }]);
9977
11573
  const properties = INTRINSICS.rebase(INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [pairs]) }), null);
9978
- const extra = schema.additionalProperties;
9979
- const additionalProperties = truncated ? true : extra === false ? false : isRecord(extra) ? this.#convert(extra, depth - 1) : true;
11574
+ const additionalProperties = unread ? true : isRecord(extra) ? this.#descend(extra, depth - 1, enclosed, "additionalProperties") : open;
9980
11575
  return INTRINSICS.freeze({
9981
11576
  category: "object",
9982
11577
  properties: INTRINSICS.freeze(properties),
@@ -9984,19 +11579,127 @@ var SchemaShaper = class SchemaShaper {
9984
11579
  ...description === void 0 ? {} : { description }
9985
11580
  });
9986
11581
  }
11582
+ #wrap(key, child, shape, sealed) {
11583
+ this.#built += 1;
11584
+ if (!isRecord(child) || !INTRINSICS.own(child, "default")) return optionalShape(shape);
11585
+ const value = child.default;
11586
+ if (!isJSONValue(value)) return optionalShape(shape);
11587
+ if (this.#strict) {
11588
+ 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", {
11589
+ code: "placement",
11590
+ context: {
11591
+ path: pathOf(this.#path, "properties", key, "default"),
11592
+ shape: "schema"
11593
+ }
11594
+ });
11595
+ if (new ContractCompiler(shape).guard(value)) return optionalShape(shape, { default: value });
11596
+ throw this.#refusal("a default must satisfy its schema", "properties", key, "default");
11597
+ }
11598
+ const leaf = shape.category === "string" || shape.category === "number" || shape.category === "boolean" || shape.category === "null" || shape.category === "literal";
11599
+ return !sealed && leaf && new ContractCompiler(shape).guard(value) ? optionalShape(shape, { default: value }) : optionalShape(shape);
11600
+ }
11601
+ };
11602
+ // src/core/FaultShaper.ts
11603
+ /**
11604
+ * Retains a lazily built fault declaration without building shapes during module evaluation.
11605
+ *
11606
+ * @example
11607
+ * ```ts
11608
+ * FaultShaper.shape === FaultShaper.shape // true
11609
+ * ```
11610
+ */
11611
+ var FaultShaper = class FaultShaper {
11612
+ static #shape;
11613
+ /** Returns the shared fault declaration, building it on the first read. */
11614
+ static get shape() {
11615
+ return FaultShaper.#shape ??= new FaultShaper().build();
11616
+ }
11617
+ /**
11618
+ * Builds a closed fault union whose inferred values satisfy the audit fault contract.
11619
+ *
11620
+ * @example
11621
+ * ```ts
11622
+ * createContract(new FaultShaper().build()).is({ reason: 'extra', path: [] }) // true
11623
+ * ```
11624
+ */
11625
+ build() {
11626
+ const path = unionShape(stringShape(), arrayShape(stringShape()));
11627
+ const expected = literalShape(FAULT_KINDS);
11628
+ const hints = arrayShape(unionShape(stringShape(), numberShape(), booleanShape()));
11629
+ return unionShape(objectShape({
11630
+ reason: literalShape(["type"]),
11631
+ path,
11632
+ expected,
11633
+ received: stringShape()
11634
+ }), objectShape({
11635
+ reason: literalShape(["missing"]),
11636
+ path,
11637
+ expected
11638
+ }), objectShape({
11639
+ reason: literalShape(["constraint"]),
11640
+ path,
11641
+ expected,
11642
+ constraint: literalShape(FAULT_CONSTRAINTS),
11643
+ limit: optionalShape(unionShape(numberShape(), stringShape())),
11644
+ received: stringShape()
11645
+ }), objectShape({
11646
+ reason: literalShape(["variant"]),
11647
+ path,
11648
+ variants: integerShape({ min: 0 })
11649
+ }), objectShape({
11650
+ reason: literalShape(["variant"]),
11651
+ path,
11652
+ variants: integerShape({ min: 0 }),
11653
+ key: stringShape(),
11654
+ expected: hints
11655
+ }), objectShape({
11656
+ reason: literalShape(["oneOf"]),
11657
+ path,
11658
+ matched: integerShape({ min: 0 })
11659
+ }), objectShape({
11660
+ reason: literalShape(["oneOf"]),
11661
+ path,
11662
+ matched: integerShape({ min: 0 }),
11663
+ key: stringShape(),
11664
+ expected: hints
11665
+ }), objectShape({
11666
+ reason: literalShape(["extra"]),
11667
+ path
11668
+ }));
11669
+ }
11670
+ static {
11671
+ pinMembers(FaultShaper.prototype, "FaultShaper");
11672
+ }
9987
11673
  };
9988
11674
  // src/core/shapers.ts
9989
11675
  /**
11676
+ * Returns the shared closed audit-fault shape, building it on the first call.
11677
+ *
11678
+ * @remarks
11679
+ * Numeric bounds, counts, and discriminator literals must be finite. Discriminator hints
11680
+ * carry both key and expected together. The inferred union is assignable to AuditFault.
11681
+ *
11682
+ * @example
11683
+ * ```ts
11684
+ * createContract(auditFaultShape()).is({ reason: 'extra', path: ['typo'] }) // true
11685
+ * ```
11686
+ */
11687
+ function auditFaultShape() {
11688
+ return contain(() => FaultShaper.shape, "auditFaultShape");
11689
+ }
11690
+ /**
9990
11691
  * Builds a string {@link StringShape}.
9991
11692
  *
9992
11693
  * @remarks
9993
11694
  * A supplied pattern is captured by source and flags. The shape exposes a fresh
9994
11695
  * frozen zero-state `RegExp` on every `pattern` read, so neither the caller's
9995
11696
  * original nor a value read from the shape can drift later compiled artifacts.
11697
+ * `date: true` restricts the string to a calendar-valid `YYYY-MM-DD`, as
11698
+ * {@link dateShape} builds it.
9996
11699
  *
9997
- * @param options - Optional length (`min` / `max`), `pattern`, and `description`
11700
+ * @param options - Optional length (`min` / `max`), `pattern`, `date`, and `description`
9998
11701
  * @returns A string shape
9999
- * @throws {ContractError} When a present bound is invalid, `pattern` is not a `RegExp`, or `pattern` has flags
11702
+ * @throws {ContractError} When a present bound is invalid, `pattern` is not a `RegExp`, `pattern` has flags, `date` is not a boolean, or `date` meets `pattern` or a bound that excludes length 10
10000
11703
  *
10001
11704
  * @example
10002
11705
  * ```ts
@@ -10009,6 +11712,7 @@ function stringShape(options) {
10009
11712
  "min",
10010
11713
  "max",
10011
11714
  "pattern",
11715
+ "date",
10012
11716
  "description"
10013
11717
  ], "stringShape", "string");
10014
11718
  const pattern = safe?.pattern;
@@ -10061,10 +11765,12 @@ function stringShape(options) {
10061
11765
  ...safe?.min === void 0 ? {} : { min: safe.min },
10062
11766
  ...safe?.max === void 0 ? {} : { max: safe.max },
10063
11767
  ...patternSnapshot === void 0 ? {} : { pattern: new INTRINSICS.pattern(patternSnapshot.source) },
11768
+ ...safe?.date === void 0 || safe.date === false ? {} : { date: safe.date },
10064
11769
  ...safe?.description === void 0 ? {} : { description: safe.description }
10065
11770
  };
11771
+ if (patternSnapshot === void 0 && !ShapePass.polluted()) return ShapePass.seal(shape);
10066
11772
  new ShapeValidator(shape).validate();
10067
- return cloneShape(shape);
11773
+ return ShapePass.seal(cloneShape(shape));
10068
11774
  }, "stringShape");
10069
11775
  }
10070
11776
  /**
@@ -10116,8 +11822,7 @@ function numberShape(options) {
10116
11822
  ...safe?.integer === void 0 ? {} : { integer: safe.integer },
10117
11823
  ...safe?.description === void 0 ? {} : { description: safe.description }
10118
11824
  };
10119
- new ShapeValidator(result).validate();
10120
- return INTRINSICS.freeze(result);
11825
+ return ShapePass.seal(result);
10121
11826
  }, "numberShape");
10122
11827
  }
10123
11828
  /**
@@ -10144,6 +11849,42 @@ function integerShape(options) {
10144
11849
  }, "integerShape");
10145
11850
  }
10146
11851
  /**
11852
+ * Builds a calendar-date {@link StringShape} — forces `date: true`.
11853
+ *
11854
+ * @remarks
11855
+ * The guard and the parser admit exactly a calendar-valid `YYYY-MM-DD` and coerce
11856
+ * nothing, so `2026-02-30`, `2026-1-10`, and a date-time all refuse. The emitted JSON
11857
+ * Schema carries `"format": "date"`. Options other than `min`, `max`, and `description`
11858
+ * refuse, because a dropped `pattern` would widen the shape.
11859
+ *
11860
+ * @param options - Optional length bounds and `description` (no `date` or `pattern` key)
11861
+ * @returns A date string shape
11862
+ * @throws {ContractError} When an option key is unknown, or a present bound is invalid or excludes length 10
11863
+ *
11864
+ * @example
11865
+ * ```ts
11866
+ * createContract(dateShape()).is('2024-02-29') // true
11867
+ * ```
11868
+ */
11869
+ function dateShape(options) {
11870
+ return contain(() => {
11871
+ const safe = readOptions(options, [
11872
+ "min",
11873
+ "max",
11874
+ "description"
11875
+ ], "dateShape", "string");
11876
+ refuseOptionKeys(options, [
11877
+ "min",
11878
+ "max",
11879
+ "description"
11880
+ ], "dateShape", "string");
11881
+ return stringShape({
11882
+ ...safe,
11883
+ date: true
11884
+ });
11885
+ }, "dateShape");
11886
+ }
11887
+ /**
10147
11888
  * Builds a {@link BooleanShape}.
10148
11889
  *
10149
11890
  * @param options - Optional `description`
@@ -10161,8 +11902,7 @@ function booleanShape(options) {
10161
11902
  category: "boolean",
10162
11903
  ...safe?.description === void 0 ? {} : { description: safe.description }
10163
11904
  };
10164
- new ShapeValidator(shape).validate();
10165
- return INTRINSICS.freeze(shape);
11905
+ return ShapePass.seal(shape);
10166
11906
  }, "booleanShape");
10167
11907
  }
10168
11908
  /**
@@ -10183,8 +11923,7 @@ function nullShape(options) {
10183
11923
  category: "null",
10184
11924
  ...safe?.description === void 0 ? {} : { description: safe.description }
10185
11925
  };
10186
- new ShapeValidator(shape).validate();
10187
- return INTRINSICS.freeze(shape);
11926
+ return ShapePass.seal(shape);
10188
11927
  }, "nullShape");
10189
11928
  }
10190
11929
  function literalShape(values, options) {
@@ -10232,8 +11971,7 @@ function literalShape(values, options) {
10232
11971
  values: INTRINSICS.freeze(literals),
10233
11972
  ...safe?.description === void 0 ? {} : { description: safe.description }
10234
11973
  };
10235
- new ShapeValidator(shape).validate();
10236
- return INTRINSICS.freeze(shape);
11974
+ return ShapePass.seal(shape);
10237
11975
  }, "literalShape");
10238
11976
  }
10239
11977
  /**
@@ -10279,8 +12017,7 @@ function arrayShape(items, options) {
10279
12017
  ...safe?.max === void 0 ? {} : { max: safe.max },
10280
12018
  ...safe?.description === void 0 ? {} : { description: safe.description }
10281
12019
  };
10282
- new ShapeValidator(shape).validate();
10283
- return INTRINSICS.freeze(shape);
12020
+ return ShapePass.seal(shape);
10284
12021
  }, "arrayShape");
10285
12022
  }
10286
12023
  /**
@@ -10350,8 +12087,7 @@ function objectShape(properties, options) {
10350
12087
  ...safe?.additionalProperties === void 0 ? {} : { additionalProperties: safe.additionalProperties },
10351
12088
  ...safe?.description === void 0 ? {} : { description: safe.description }
10352
12089
  };
10353
- new ShapeValidator(shape).validate();
10354
- return INTRINSICS.freeze(shape);
12090
+ return ShapePass.seal(shape);
10355
12091
  }, "objectShape");
10356
12092
  }
10357
12093
  /**
@@ -10388,13 +12124,19 @@ function recordShape(values, options) {
10388
12124
  additionalProperties: values,
10389
12125
  ...safe?.description === void 0 ? {} : { description: safe.description }
10390
12126
  };
10391
- new ShapeValidator(shape).validate();
10392
- return INTRINSICS.freeze(shape);
12127
+ return ShapePass.seal(shape);
10393
12128
  }, "recordShape");
10394
12129
  }
10395
12130
  /**
10396
12131
  * Builds a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).
10397
12132
  *
12133
+ * @remarks
12134
+ * When every arm is an object declaring one required literal property, and a value's
12135
+ * own property exactly equals a literal only one arm holds, that arm answers: `explain`
12136
+ * and `audit` report its faults at their real paths, and `parse` repairs through it
12137
+ * alone. Any other value reports `variant`, with `key` and `expected` saying what would
12138
+ * have named an arm. `is` does not change.
12139
+ *
10398
12140
  * @param variants - The candidate shapes; the first match wins at runtime
10399
12141
  * @returns A union shape whose `Infer` is the union of the variants
10400
12142
  *
@@ -10406,11 +12148,7 @@ function recordShape(values, options) {
10406
12148
  */
10407
12149
  function unionShape(...variants) {
10408
12150
  return contain(() => {
10409
- new ShapeValidator({
10410
- category: "union",
10411
- variants
10412
- }).validate();
10413
- return INTRINSICS.freeze({
12151
+ return ShapePass.seal({
10414
12152
  category: "union",
10415
12153
  variants: INTRINSICS.freeze(variants)
10416
12154
  });
@@ -10429,9 +12167,11 @@ function unionShape(...variants) {
10429
12167
  * {@link unionShape}'s guard.
10430
12168
  * - **Parser**: judged on the RAW input's guard matches only, with NO
10431
12169
  * coercion fallback for an ambiguous input. When exactly one variant's
10432
- * guard accepts the raw value, that variant's parser runs. Zero matches or
12170
+ * guard accepts the raw value, the input itself is returned. Zero matches or
10433
12171
  * two-or-more matches both parse to `undefined` — a value ambiguous
10434
- * between variants has no well-defined coercion target.
12172
+ * between variants has no well-defined coercion target. A value that names one
12173
+ * arm through a required literal is not ambiguous, so as in {@link unionShape}
12174
+ * that arm answers alone, and its parser may coerce.
10435
12175
  *
10436
12176
  * Prefer {@link unionShape} when a value may legitimately satisfy more than
10437
12177
  * one variant (for example overlapping shapes) and any match is acceptable. Prefer
@@ -10450,15 +12190,10 @@ function unionShape(...variants) {
10450
12190
  */
10451
12191
  function oneOfShape(...variants) {
10452
12192
  return contain(() => {
10453
- const shape = {
12193
+ return ShapePass.seal({
10454
12194
  category: "union",
10455
- variants,
12195
+ variants: INTRINSICS.freeze(variants),
10456
12196
  mode: "oneOf"
10457
- };
10458
- new ShapeValidator(shape).validate();
10459
- return INTRINSICS.freeze({
10460
- ...shape,
10461
- variants: INTRINSICS.freeze(variants)
10462
12197
  });
10463
12198
  }, "oneOfShape");
10464
12199
  }
@@ -10467,22 +12202,55 @@ function oneOfShape(...variants) {
10467
12202
  *
10468
12203
  * @remarks
10469
12204
  * As an {@link objectShape} property, the field becomes a true optional property
10470
- * in the inferred type.
12205
+ * in the inferred type. A `default` is captured as an owned frozen copy, and the
12206
+ * compiled parser fills it where the property is absent or `undefined`; the guard,
12207
+ * the audit, the report, and the generator keep treating the property as optional.
12208
+ * The compilers refuse a default `inner` refuses, a default under a union, and a
12209
+ * default on a property of an open object.
10471
12210
  *
10472
12211
  * @param inner - The wrapped shape
12212
+ * @param options - Optional `default`, a JSON value
10473
12213
  * @returns An optional shape
12214
+ * @throws {ContractError} When a present `default` is not a JSON value, `undefined` included
12215
+ *
12216
+ * @example
12217
+ * ```ts
12218
+ * const retries = optionalShape(integerShape({ min: 0 }), { default: 3 })
12219
+ * ```
10474
12220
  */
10475
- function optionalShape(inner) {
12221
+ function optionalShape(inner, options) {
10476
12222
  return contain(() => {
12223
+ const safe = readOptions(options, ["default"], "optionalShape", "optional");
12224
+ refuseOptionKeys(options, ["default"], "optionalShape", "optional");
12225
+ const present = options !== void 0 && INTRINSICS.own(options, "default");
12226
+ const value = present ? safe?.default : void 0;
12227
+ if (present && !isJSONValue(value)) throw new ContractError("optionalShape: default must be a JSON value", {
12228
+ code: "structure",
12229
+ context: {
12230
+ path: ["default"],
12231
+ shape: "optional",
12232
+ received: preview(value)
12233
+ }
12234
+ });
12235
+ const owned = value === void 0 ? void 0 : attempt(() => cloneJSONValue(value));
12236
+ if (owned !== void 0 && isFailure(owned)) throw new ContractError("optionalShape: default must be a JSON value", {
12237
+ code: "structure",
12238
+ context: {
12239
+ path: ["default"],
12240
+ shape: "optional",
12241
+ received: preview(value)
12242
+ },
12243
+ cause: owned.error
12244
+ });
10477
12245
  const shape = {
10478
12246
  category: "optional",
10479
- inner
12247
+ inner,
12248
+ ...owned === void 0 ? {} : { default: owned.value }
10480
12249
  };
10481
- new ShapeValidator({
12250
+ return ShapePass.seal(shape, {
10482
12251
  category: "object",
10483
12252
  properties: { value: shape }
10484
- }).validate();
10485
- return INTRINSICS.freeze(shape);
12253
+ });
10486
12254
  }, "optionalShape");
10487
12255
  }
10488
12256
  /**
@@ -10503,8 +12271,7 @@ function nullableShape(inner) {
10503
12271
  category: "nullable",
10504
12272
  inner
10505
12273
  };
10506
- new ShapeValidator(shape).validate();
10507
- return INTRINSICS.freeze(shape);
12274
+ return ShapePass.seal(shape);
10508
12275
  }, "nullableShape");
10509
12276
  }
10510
12277
  /**
@@ -10536,17 +12303,39 @@ function jsonShape(options) {
10536
12303
  category: "json",
10537
12304
  ...safe?.description === void 0 ? {} : { description: safe.description }
10538
12305
  };
10539
- new ShapeValidator(shape).validate();
10540
- return INTRINSICS.freeze(shape);
12306
+ return ShapePass.seal(shape);
10541
12307
  }, "jsonShape");
10542
12308
  }
10543
12309
  /**
12310
+ * Builds a {@link ShapeShape}.
12311
+ *
12312
+ * @param options - Optional description
12313
+ * @returns A shape-valued declaration
12314
+ *
12315
+ * @example
12316
+ * ```ts
12317
+ * const definition = objectShape({ shape: shapeShape() })
12318
+ * ```
12319
+ */
12320
+ function shapeShape(options) {
12321
+ return contain(() => {
12322
+ const safe = readOptions(options, ["description"], "shapeShape", "shape");
12323
+ const shape = {
12324
+ category: "shape",
12325
+ ...safe?.description === void 0 ? {} : { description: safe.description }
12326
+ };
12327
+ return ShapePass.seal(shape);
12328
+ }, "shapeShape");
12329
+ }
12330
+ /**
10544
12331
  * Builds a {@link RawShape} from a supported JSON Schema fragment.
10545
12332
  *
10546
12333
  * @remarks
10547
12334
  * For values the shape DSL can't express. The fragment is recursively checked
10548
12335
  * against the lean {@link JSONSchema} vocabulary before ownership is taken;
10549
12336
  * malformed or unsupported keywords throw a coded {@link ContractError}. The
12337
+ * refusal path starts at `schema` and names the nested keyword or member.
12338
+ * A non-record root is refused at `schema` itself. The
10550
12339
  * compiled guard accepts every
10551
12340
  * DEFINED value — `undefined` alone fails, because it is the parser's failure
10552
12341
  * sentinel; wrap the shape in {@link optionalShape} to admit absence. The
@@ -10574,22 +12363,18 @@ function rawShape(schema) {
10574
12363
  category: "raw",
10575
12364
  schema
10576
12365
  }).validate();
10577
- const owned = cloneSchema(schema);
10578
- new ShapeValidator({
10579
- category: "raw",
10580
- schema: owned
10581
- }).validate();
10582
- return INTRINSICS.freeze({
12366
+ return ShapePass.seal({
10583
12367
  category: "raw",
10584
- schema: owned
12368
+ schema: cloneSchema(schema)
10585
12369
  });
10586
12370
  }, "rawShape");
10587
12371
  }
10588
12372
  /**
10589
12373
  * Converts a runtime `JSONSchema` value into a validating {@link ContractShape}
10590
12374
  * — the inverse of {@link compileSchema}. Unlike direct {@link rawShape}
10591
- * construction, which rejects malformed supported-vocabulary keywords, this
10592
- * conversion is total and widens an inexpressible input to a valid raw `{}`.
12375
+ * construction, which rejects malformed supported-vocabulary keywords, the
12376
+ * lenient conversion is total and widens an inexpressible input to a valid raw
12377
+ * `{}`, and a strict conversion refuses that input.
10593
12378
  *
10594
12379
  * @remarks
10595
12380
  * Readable malformed, cyclic, or deeply nested schema nodes widen to
@@ -10640,9 +12425,39 @@ function rawShape(schema) {
10640
12425
  * when the conversion widened anywhere — `schema` / `is` / `parse` / `explain`
10641
12426
  * stay total.
10642
12427
  *
12428
+ * LENIENT LAW: a value a JSON Schema accepts is never refused by the shape a
12429
+ * lenient conversion builds from it, because the walk widens what it cannot read.
12430
+ * So `oneOf` builds an inclusive union, a `true` arm is a raw variant and a `false`
12431
+ * arm is dropped, an `enum` holding `null` admits it, `nullable: true` wraps the
12432
+ * node, a present `patternProperties` opens the object, a present `prefixItems`
12433
+ * widens the elements, and a `$ref` widens the node before anything beside it is read.
12434
+ * A schema past the compile limit keeps only its root's type, an array's bounds, and an
12435
+ * object's required keys and closure, with every value below them raw.
12436
+ *
12437
+ * DEFAULTS: a lenient conversion carries a property's `default` when the key is
12438
+ * not `required`, its object is closed with no union ancestor, and the value is
12439
+ * one the property's primitive or literal guard accepts. It drops every other
12440
+ * `default`, because carrying it would make the shape refuse to compile.
12441
+ *
12442
+ * STRICT: `{ strict: true }` is the door for a foreign schema. It refuses, with
12443
+ * code `structure`, every node the lenient walk would widen, every keyword it
12444
+ * would ignore (`pattern`, every `format` but `'date'` on a string node, `nullable`,
12445
+ * `patternProperties`, `propertyNames`, `prefixItems`, and anything else outside
12446
+ * {@link STRICT_SCHEMA_KEYWORDS}), a malformed keyword or annotation, a boolean schema, an `enum` entry
12447
+ * that is neither a finite primitive nor `null`, a contradictory bound, a date format whose
12448
+ * length bounds exclude length 10, a `required` name not in
12449
+ * `properties`, breadth past {@link INFER_BREADTH_LIMIT}, and a `default` with no
12450
+ * optional property to fill. An object with no `additionalProperties` closes
12451
+ * rather than opens, and `oneOf` keeps exactly-one, because a strict walk reads
12452
+ * every keyword that could keep two arms apart. Below a `oneOf` that object refuses
12453
+ * instead, since closing it could change which arms match. A strict conversion is the
12454
+ * one walk that asserts a `format`: it reads `format: 'date'` on a string node as a
12455
+ * date string shape, so a compiled {@link dateShape} round-trips.
12456
+ *
10643
12457
  * @param schema - The JSON Schema value to convert
12458
+ * @param options - Optional `strict`, default `false`
10644
12459
  * @returns The built {@link ContractShape}
10645
- * @throws {ContractError} When schema traversal fails
12460
+ * @throws {ContractError} When schema traversal fails, or when a strict conversion refuses
10646
12461
  *
10647
12462
  * @example
10648
12463
  * ```ts
@@ -10652,9 +12467,30 @@ function rawShape(schema) {
10652
12467
  * contract.parse({ id: 'nope' }) // undefined
10653
12468
  * ```
10654
12469
  */
10655
- function schemaToShape(schema) {
12470
+ function schemaToShape(schema, options) {
10656
12471
  return contain(() => {
10657
- return readValue(() => new SchemaShaper(schema).shape(), "schemaToShape", {
12472
+ const safe = readOptions(options, ["strict"], "schemaToShape", "schema");
12473
+ refuseOptionKeys(options, ["strict"], "schemaToShape", "schema");
12474
+ const strict = options !== void 0 && INTRINSICS.own(options, "strict") ? safe?.strict : void 0;
12475
+ if (strict !== void 0 && typeof strict !== "boolean") throw new ContractError("schemaToShape: strict must be a boolean", {
12476
+ code: "structure",
12477
+ context: {
12478
+ path: ["strict"],
12479
+ shape: "schema",
12480
+ received: preview(strict)
12481
+ }
12482
+ });
12483
+ const shaper = new SchemaShaper(schema, strict === true);
12484
+ if (strict !== true) return readValue(() => shaper.shape(), "schemaToShape", {
12485
+ subject: "schema",
12486
+ context: { shape: "schema" }
12487
+ });
12488
+ const outcome = attempt(() => shaper.shape());
12489
+ if (isSuccess(outcome)) return outcome.value;
12490
+ if (isContractError(outcome.error)) throw outcome.error;
12491
+ return readValue(() => {
12492
+ throw outcome.error;
12493
+ }, "schemaToShape", {
10658
12494
  subject: "schema",
10659
12495
  context: { shape: "schema" }
10660
12496
  });
@@ -10668,7 +12504,13 @@ exports.CONTRACT_CODES = CONTRACT_CODES;
10668
12504
  exports.CONTRACT_ERROR_BRAND = CONTRACT_ERROR_BRAND;
10669
12505
  exports.ContractCompiler = ContractCompiler;
10670
12506
  exports.ContractError = ContractError;
12507
+ exports.DATE_LENGTH = DATE_LENGTH;
12508
+ exports.FAULT_CONSTRAINTS = FAULT_CONSTRAINTS;
12509
+ exports.FAULT_KINDS = FAULT_KINDS;
10671
12510
  exports.FAULT_LIMIT = FAULT_LIMIT;
12511
+ exports.FAULT_LIST_LIMIT = FAULT_LIST_LIMIT;
12512
+ exports.FAULT_SCHEMA_LIMIT = FAULT_SCHEMA_LIMIT;
12513
+ exports.FAULT_TEXT_LIMIT = FAULT_TEXT_LIMIT;
10672
12514
  exports.FORMAT_MAX_LENGTH = FORMAT_MAX_LENGTH;
10673
12515
  exports.FORMAT_PATTERNS = FORMAT_PATTERNS;
10674
12516
  exports.GENERATION_ATTEMPT_LIMIT = GENERATION_ATTEMPT_LIMIT;
@@ -10683,18 +12525,22 @@ exports.NAME_LIMIT = NAME_LIMIT;
10683
12525
  exports.NODE_LIMIT = NODE_LIMIT;
10684
12526
  exports.PRESENCE_MASK_LIMIT = PRESENCE_MASK_LIMIT;
10685
12527
  exports.PREVIEW_LIMIT = PREVIEW_LIMIT;
12528
+ exports.SHAPE_FIELDS = SHAPE_FIELDS;
12529
+ exports.STRICT_SCHEMA_KEYWORDS = STRICT_SCHEMA_KEYWORDS;
10686
12530
  exports.STRING_LIMIT = STRING_LIMIT;
10687
12531
  exports.SchemaCloner = SchemaCloner;
10688
12532
  exports.ShapeCloner = ShapeCloner;
10689
12533
  exports.ShapeValidator = ShapeValidator;
10690
12534
  exports.TEXT_LIMIT = TEXT_LIMIT;
10691
12535
  exports.admitMember = admitMember;
12536
+ exports.admitValue = admitValue;
10692
12537
  exports.admitVisited = admitVisited;
10693
12538
  exports.andOf = andOf;
10694
12539
  exports.appendEntries = appendEntries;
10695
12540
  exports.arrayOf = arrayOf;
10696
12541
  exports.arrayShape = arrayShape;
10697
12542
  exports.attempt = attempt;
12543
+ exports.auditFaultShape = auditFaultShape;
10698
12544
  exports.booleanShape = booleanShape;
10699
12545
  exports.boundsOf = boundsOf;
10700
12546
  exports.buildArrayFaults = buildArrayFaults;
@@ -10718,10 +12564,15 @@ exports.compileParser = compileParser;
10718
12564
  exports.compileReporter = compileReporter;
10719
12565
  exports.compileSchema = compileSchema;
10720
12566
  exports.complementOf = complementOf;
12567
+ exports.computeMonthLength = computeMonthLength;
12568
+ exports.computeSurrogatePairs = computeSurrogatePairs;
10721
12569
  exports.contain = contain;
10722
12570
  exports.createContract = createContract;
12571
+ exports.dateShape = dateShape;
10723
12572
  exports.deriveLengthBounds = deriveLengthBounds;
10724
12573
  exports.deriveRangeBounds = deriveRangeBounds;
12574
+ exports.describeFaultLine = describeFaultLine;
12575
+ exports.describeFaults = describeFaults;
10725
12576
  exports.drawRandom = drawRandom;
10726
12577
  exports.encodeLeaf = encodeLeaf;
10727
12578
  exports.encodeParts = encodeParts;
@@ -10730,6 +12581,9 @@ exports.enumerableKeys = enumerableKeys;
10730
12581
  exports.enumerableSymbolCount = enumerableSymbolCount;
10731
12582
  exports.errorToMessage = errorToMessage;
10732
12583
  exports.escapeRegExp = escapeRegExp;
12584
+ exports.extractForms = extractForms;
12585
+ exports.extractPath = extractPath;
12586
+ exports.extractSchema = extractSchema;
10733
12587
  exports.failure = failure;
10734
12588
  exports.holds = holds;
10735
12589
  exports.inferPrimitiveEnum = inferPrimitiveEnum;
@@ -10742,6 +12596,7 @@ exports.isArrayBufferView = isArrayBufferView;
10742
12596
  exports.isAsyncFunction = isAsyncFunction;
10743
12597
  exports.isAsyncGeneratorFunction = isAsyncGeneratorFunction;
10744
12598
  exports.isAsyncIterable = isAsyncIterable;
12599
+ exports.isAuditFault = isAuditFault;
10745
12600
  exports.isBigInt = isBigInt;
10746
12601
  exports.isBigInt64Array = isBigInt64Array;
10747
12602
  exports.isBigUint64Array = isBigUint64Array;
@@ -10761,6 +12616,8 @@ exports.isEmptyString = isEmptyString;
10761
12616
  exports.isError = isError;
10762
12617
  exports.isFailure = isFailure;
10763
12618
  exports.isFalse = isFalse;
12619
+ exports.isFault = isFault;
12620
+ exports.isFaultPath = isFaultPath;
10764
12621
  exports.isFiniteNumber = isFiniteNumber;
10765
12622
  exports.isFloat32Array = isFloat32Array;
10766
12623
  exports.isFloat64Array = isFloat64Array;
@@ -10819,12 +12676,17 @@ exports.literalOf = literalOf;
10819
12676
  exports.literalShape = literalShape;
10820
12677
  exports.mapOf = mapOf;
10821
12678
  exports.matchOf = matchOf;
12679
+ exports.matchesCalendarDate = matchesCalendarDate;
12680
+ exports.matchesExactKeys = matchesExactKeys;
10822
12681
  exports.matchesISOInstant = matchesISOInstant;
10823
12682
  exports.matchesJSONDepth = matchesJSONDepth;
10824
12683
  exports.matchesJSONValue = matchesJSONValue;
12684
+ exports.matchesLosslessRepair = matchesLosslessRepair;
10825
12685
  exports.matchesMember = matchesMember;
10826
12686
  exports.matchesPattern = matchesPattern;
10827
12687
  exports.matchesRecordBrand = matchesRecordBrand;
12688
+ exports.matchesStringLength = matchesStringLength;
12689
+ exports.matchesUndefinedField = matchesUndefinedField;
10828
12690
  exports.matchesVisited = matchesVisited;
10829
12691
  exports.notOf = notOf;
10830
12692
  exports.nullShape = nullShape;
@@ -10883,6 +12745,10 @@ exports.readValue = readValue;
10883
12745
  exports.recordOf = recordOf;
10884
12746
  exports.recordShape = recordShape;
10885
12747
  exports.refuseExpansion = refuseExpansion;
12748
+ exports.refuseOptionKeys = refuseOptionKeys;
12749
+ exports.renderForm = renderForm;
12750
+ exports.renderList = renderList;
12751
+ exports.renderPath = renderPath;
10886
12752
  exports.resolveField = resolveField;
10887
12753
  exports.retainDepth = retainDepth;
10888
12754
  exports.samplesToFormat = samplesToFormat;
@@ -10895,6 +12761,7 @@ exports.schemaToShape = schemaToShape;
10895
12761
  exports.seededRandom = seededRandom;
10896
12762
  exports.selectClosestFaults = selectClosestFaults;
10897
12763
  exports.setOf = setOf;
12764
+ exports.shapeShape = shapeShape;
10898
12765
  exports.shapeToKind = shapeToKind;
10899
12766
  exports.sortValues = sortValues;
10900
12767
  exports.stringOf = stringOf;
@@ -10902,6 +12769,7 @@ exports.stringShape = stringShape;
10902
12769
  exports.stringToFormat = stringToFormat;
10903
12770
  exports.success = success;
10904
12771
  exports.transformOf = transformOf;
12772
+ exports.truncateFaultText = truncateFaultText;
10905
12773
  exports.tupleOf = tupleOf;
10906
12774
  exports.unifySchemas = unifySchemas;
10907
12775
  exports.unionOf = unionOf;