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