@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.
@@ -17,6 +17,26 @@
17
17
  */
18
18
  export declare function admitMember(members: Set<unknown>, value: unknown): void;
19
19
 
20
+ /**
21
+ * Admits a stable readable value with only lossless repairs and returns the parser's value.
22
+ *
23
+ * @remarks
24
+ * Reads must remain stable across artifacts. Guard-valid input skips both reports and parses
25
+ * once. Repairs use audit, parse once, and explain only on parse failure. Unresolved unions,
26
+ * extras, lossy repairs, and a capped audit refuse. An own optional undefined field omitted or
27
+ * filled by its declared default is not a repair. The result preserves parser ownership, including union input identity.
28
+ * A read failure returns its cause rather than throwing.
29
+ * Snapshot a foreign object before admission, as Tool.execute does. A getter changing between
30
+ * is and parse can publish a value that no recorded repair describes. A shallow snapshot only
31
+ * stabilizes its own level; nested foreign values must also provide stable reads.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * admitValue(createContract(numberShape()), '3') // success carrying 3 and its type repair
36
+ * ```
37
+ */
38
+ export declare function admitValue<T>(contract: ContractInterface<T>, value: unknown): Result<ContractAdmission<T>, ContractRefusal>;
39
+
20
40
  /**
21
41
  * Records an object as entered on a traversal's active path.
22
42
  *
@@ -207,6 +227,23 @@ export declare function attempt<T>(callback: () => T): Result<T>;
207
227
  /** Covers every fault an audit reports — the parse faults plus undeclared keys. */
208
228
  export declare type AuditFault = Fault | ExtraFault;
209
229
 
230
+ /** Describes the closed shape built for audit faults, including paired discriminator hints. */
231
+ export declare type AuditFaultShape = ReturnType<FaultShaper['build']>;
232
+
233
+ /**
234
+ * Returns the shared closed audit-fault shape, building it on the first call.
235
+ *
236
+ * @remarks
237
+ * Numeric bounds, counts, and discriminator literals must be finite. Discriminator hints
238
+ * carry both key and expected together. The inferred union is assignable to AuditFault.
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * createContract(auditFaultShape()).is({ reason: 'extra', path: ['typo'] }) // true
243
+ * ```
244
+ */
245
+ export declare function auditFaultShape(): AuditFaultShape;
246
+
210
247
  /**
211
248
  * Represents a compiled strict-domain diagnostic — the shape of `compileAuditor`
212
249
  * bound to one shape.
@@ -381,8 +418,10 @@ export declare function buildSampleMemo(): SampleMemo;
381
418
  * OBTAIN the string — the reporter coerces through `parseString`, the auditor
382
419
  * demands a primitive string — and share every constraint afterwards through
383
420
  * this helper, so a constraint cannot drift between them.
384
- * Faults come out in declaration order — `min`, then `max`, then
421
+ * Faults come out in declaration order — `date`, then `min`, then `max`, then
385
422
  * `pattern` — because a report is read top to bottom and its order is public.
423
+ * `expected` is `'date'` on a date string shape and `'string'` otherwise, as
424
+ * {@link buildNumberFaults} names `'integer'`.
386
425
  *
387
426
  * The declaration's pattern is applied through an OWNED stateless rebuild
388
427
  * ({@link readPattern}) asked through {@link matchesPattern}, so the shape's own
@@ -875,7 +914,8 @@ export declare function compileGenerator(shape: ContractShape, random?: RandomFu
875
914
  * § Validation and contracts requires. It requests
876
915
  * exactly the `guard` root of a fresh {@link ContractCompiler}, which owns the
877
916
  * declaration once through {@link ownShape} and validates that snapshot once,
878
- * so an unfrozen caller-owned graph compiles from a snapshot and excessive
917
+ * unless the builders already did, so an unfrozen caller-owned graph compiles
918
+ * from a snapshot and excessive
879
919
  * nesting, cycles, and excessive expansion are rejected before any guard is
880
920
  * built.
881
921
  *
@@ -1028,6 +1068,46 @@ export declare function compileSchema(shape: ContractShape): JSONSchema;
1028
1068
  */
1029
1069
  export declare function complementOf<TBase, TExcluded extends TBase>(base: Guard<TBase>, excluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded)): Guard<Exclude<TBase, TExcluded>>;
1030
1070
 
1071
+ /**
1072
+ * Computes the number of days in a month of the Gregorian calendar.
1073
+ *
1074
+ * @remarks
1075
+ * February has 29 days in a year divisible by 4, except a century year not divisible
1076
+ * by 400. The caller supplies a month from 1 to 12.
1077
+ *
1078
+ * @param year - The calendar year
1079
+ * @param month - The month, from 1 for January to 12 for December
1080
+ * @returns The days in that month, from 28 to 31
1081
+ *
1082
+ * @example
1083
+ * ```ts
1084
+ * computeMonthLength(2024, 2) // 29
1085
+ * computeMonthLength(1900, 2) // 28
1086
+ * ```
1087
+ */
1088
+ export declare function computeMonthLength(year: number, month: number): number;
1089
+
1090
+ /**
1091
+ * Counts the surrogate pairs in a string, stopping at a limit.
1092
+ *
1093
+ * @remarks
1094
+ * A regular-expression literal builds a fresh `RegExp` per evaluation, so this call
1095
+ * owns the `lastIndex` that is its cursor, and the captured `exec` reads the internal
1096
+ * slots and no member a caller can replace. Text with no surrogate costs one native
1097
+ * scan, and a string of pairs costs one `exec` per pair up to the limit.
1098
+ *
1099
+ * @param value - The string to scan
1100
+ * @param limit - The count to stop at
1101
+ * @returns The number of surrogate pairs, or `limit` when the string holds at least that many
1102
+ *
1103
+ * @example
1104
+ * ```ts
1105
+ * computeSurrogatePairs('😀a😀', 8) // 2
1106
+ * computeSurrogatePairs('😀😀😀', 2) // 2
1107
+ * ```
1108
+ */
1109
+ export declare function computeSurrogatePairs(value: string, limit: number): number;
1110
+
1031
1111
  /**
1032
1112
  * Runs a public door's whole body and publishes only this package's error class.
1033
1113
  *
@@ -1122,6 +1202,22 @@ export declare const CONTRACT_CODES: readonly ContractCode[];
1122
1202
  */
1123
1203
  export declare const CONTRACT_ERROR_BRAND: unique symbol;
1124
1204
 
1205
+ /**
1206
+ * Carries an admitted value and the lossless repairs made while parsing it.
1207
+ *
1208
+ * @remarks
1209
+ * The value keeps the parser's ownership: a union may return the caller's input by identity.
1210
+ *
1211
+ * @example
1212
+ * ```ts
1213
+ * const admitted: ContractAdmission<number> = { value: 3, repairs: [] }
1214
+ * ```
1215
+ */
1216
+ export declare interface ContractAdmission<T> {
1217
+ readonly value: T;
1218
+ readonly repairs: readonly AuditFault[];
1219
+ }
1220
+
1125
1221
  /**
1126
1222
  * Names the machine-readable category carried by a {@link ContractError}.
1127
1223
  *
@@ -1173,7 +1269,9 @@ export declare type ContractCode =
1173
1269
  * chain pays a hundred clones of shrinking graphs and a hundred validations —
1174
1270
  * quadratic work for a linear declaration. Here ownership runs once, validation runs once over
1175
1271
  * that owned result, and each unique node and structural edge is indexed once
1176
- * into children-before-parent order. Every artifact family is then a single
1272
+ * into children-before-parent order. A declaration a builder sealed is frozen and
1273
+ * validated all the way down already, so it takes neither and is indexed as it
1274
+ * stands. Every artifact family is then a single
1177
1275
  * postorder pass whose entries are keyed by node identity, so a shared child is
1178
1276
  * compiled once however many parents point at it. The same asymmetry exists on
1179
1277
  * the VALUE side and is answered the same way: `guard`, `auditor` and `reporter`
@@ -1185,7 +1283,9 @@ export declare type ContractCode =
1185
1283
  * getters after it replay. A getter builds its own family and no other, except
1186
1284
  * that `parser`, `reporter` and `generator` build the guard plan when the graph
1187
1285
  * holds a union, because a union's membership question IS a guard question in
1188
- * all three.
1286
+ * all three, and every getter builds it when the graph holds a default, because
1287
+ * a default that its inner shape refuses refuses at whichever artifact is read
1288
+ * first.
1189
1289
  *
1190
1290
  * One terminal lifecycle covers preparation and every family. A failure settles
1191
1291
  * the compiler: later getters rethrow that exact error, while an artifact
@@ -1464,6 +1564,19 @@ export declare interface ContractInterface<T> {
1464
1564
  generate(random?: RandomFunction): T;
1465
1565
  }
1466
1566
 
1567
+ /**
1568
+ * Carries bounded admission faults and the cause of an unreadable value when present.
1569
+ *
1570
+ * @example
1571
+ * ```ts
1572
+ * const refused: ContractRefusal = { faults: [{ reason: 'extra', path: ['typo'] }] }
1573
+ * ```
1574
+ */
1575
+ export declare interface ContractRefusal {
1576
+ readonly faults: readonly AuditFault[];
1577
+ readonly cause?: unknown;
1578
+ }
1579
+
1467
1580
  /**
1468
1581
  * Describes a value declaratively — a declaration the shape builders build and
1469
1582
  * the compilers turn into a guard, a parser, a JSON Schema, and a generator.
@@ -1473,7 +1586,7 @@ export declare interface ContractInterface<T> {
1473
1586
  * element shape, an `ObjectShape` a map of them). {@link validateShape}
1474
1587
  * enforces an acyclic graph within {@link COMPILE_DEPTH_LIMIT}.
1475
1588
  */
1476
- export declare type ContractShape = StringShape | NumberShape | BooleanShape | NullShape | LiteralShape | ArrayShape | ObjectShape | UnionShape | OptionalShape | NullableShape | JSONShape | RawShape;
1589
+ export declare type ContractShape = StringShape | NumberShape | BooleanShape | NullShape | LiteralShape | ArrayShape | ObjectShape | UnionShape | OptionalShape | NullableShape | JSONShape | ShapeShape | RawShape;
1477
1590
 
1478
1591
  /**
1479
1592
  * Compiles a {@link ContractShape} into a {@link ContractInterface} — the
@@ -1489,24 +1602,30 @@ export declare type ContractShape = StringShape | NumberShape | BooleanShape | N
1489
1602
  * snapshot — ownership already refuses a malformed structural slot, scalar
1490
1603
  * field, or bound rather than normalizing it, so a second walk of the caller's
1491
1604
  * live source only added a population that could disagree with the one the
1492
- * artifacts actually use.
1493
- * Every artifact is precompiled, so `audit`, `explain` and `generate` re-walk
1494
- * and re-gate nothing on a later call; `contract.audit` and `compileAuditor` are
1495
- * the same compiled function reached by different names.
1496
- * The bundle is eager by intent. Its members are plain data properties holding
1497
- * the compiled artifacts, so `const { is, parse } = createContract(shape)`
1498
- * destructures those exact values and a spread of the result copies them; a
1499
- * lazily compiled member would compile on either, which spends the laziness
1500
- * rather than saving it. A malformed declaration refuses at this call rather
1501
- * than at the first read of whichever member a caller happens to touch, so the
1502
- * failure arrives at the call the caller made — carrying the authoring door's
1503
- * own diagnosis, which this door adopts rather than rewraps. Every member is
1504
- * self-contained, and the compiler this call builds releases its working set
1505
- * before the call returns. The contract keeps part of the declaration even so:
1506
- * the auditor and reporter plans close over the owned leaf and array nodes they
1507
- * read their bounds from, so a kept contract retains those nodes and, through
1508
- * an array node's `items` field, the subgraph beneath them. Nothing the caller
1509
- * keeps reaches back into the compiler.
1605
+ * artifacts actually use. A declaration made entirely by this package's builders
1606
+ * is frozen and validated all the way down already, so it is that owned graph.
1607
+ * Every artifact compiles once, so `audit`, `explain` and `generate` re-walk and
1608
+ * re-gate nothing on a later call; `contract.audit` and `compileAuditor` run the
1609
+ * same compiled plan reached by different names.
1610
+ * A declaration made entirely by builders compiles its schema at this call and
1611
+ * its function members together on the first call to any of them, so a module
1612
+ * can declare contracts as data and pay only for the ones it uses. Any other
1613
+ * declaration, and a bare leaf, compiles every member at this call. Either way
1614
+ * the members are plain data properties, so `const { is, parse } =
1615
+ * createContract(shape)` destructures those exact values, a spread of the result
1616
+ * copies them, and neither compiles anything. A malformed declaration refuses at
1617
+ * this call rather than at the first read of whichever member a caller happens
1618
+ * to touch, so the failure arrives at the call the caller made — carrying the
1619
+ * authoring door's own diagnosis, which this door adopts rather than rewraps.
1620
+ * Every compiled member is self-contained, and the compiler this call builds
1621
+ * releases its working set once every member has compiled. The contract keeps
1622
+ * part of the declaration even so: the auditor and reporter plans close over the
1623
+ * leaf and array nodes they read their bounds from, and a contract with deferred
1624
+ * members retains its declaration. Nothing the caller keeps reaches back into the
1625
+ * compiler. A deferred member compiled on a host whose members were replaced after
1626
+ * this call would outlive the replacement, so it refuses to compile until they are
1627
+ * restored: until then its guard answers `false`, its parser `undefined`, and its
1628
+ * diagnostics and generator refuse.
1510
1629
  *
1511
1630
  * @param shape - The shape to compile
1512
1631
  * @returns A contract bundling `schema` / `is` / `parse` / `audit` / `explain` / `generate`
@@ -1535,6 +1654,40 @@ export declare function createContract<S extends ContractShape>(shape: S): Contr
1535
1654
 
1536
1655
  export declare function createContract(shape: ContractShape): ContractInterface<unknown>;
1537
1656
 
1657
+ /**
1658
+ * Holds `10`, the length of every `YYYY-MM-DD` date a date string shape admits.
1659
+ *
1660
+ * @remarks
1661
+ * A date string shape whose `min` or `max` excludes this length admits no value, so
1662
+ * building one refuses with code `range`.
1663
+ *
1664
+ * @example
1665
+ * ```ts
1666
+ * DATE_LENGTH // 10
1667
+ * ```
1668
+ */
1669
+ export declare const DATE_LENGTH = 10;
1670
+
1671
+ /**
1672
+ * Builds a calendar-date {@link StringShape} — forces `date: true`.
1673
+ *
1674
+ * @remarks
1675
+ * The guard and the parser admit exactly a calendar-valid `YYYY-MM-DD` and coerce
1676
+ * nothing, so `2026-02-30`, `2026-1-10`, and a date-time all refuse. The emitted JSON
1677
+ * Schema carries `"format": "date"`. Options other than `min`, `max`, and `description`
1678
+ * refuse, because a dropped `pattern` would widen the shape.
1679
+ *
1680
+ * @param options - Optional length bounds and `description` (no `date` or `pattern` key)
1681
+ * @returns A date string shape
1682
+ * @throws {ContractError} When an option key is unknown, or a present bound is invalid or excludes length 10
1683
+ *
1684
+ * @example
1685
+ * ```ts
1686
+ * createContract(dateShape()).is('2024-02-29') // true
1687
+ * ```
1688
+ */
1689
+ export declare function dateShape(options?: Omit<StringShapeOptions, 'date' | 'pattern'>): StringShape;
1690
+
1538
1691
  /**
1539
1692
  * Derives `min`/`max` shape bounds from a pair of non-negative-integer JSON
1540
1693
  * Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`).
@@ -1582,6 +1735,49 @@ export declare function deriveLengthBounds(min: unknown, max: unknown): BoundsRe
1582
1735
  */
1583
1736
  export declare function deriveRangeBounds(min: unknown, max: unknown): BoundsRead;
1584
1737
 
1738
+ /**
1739
+ * Describes one fault as the line a caller corrects from, naming what to send where the schema
1740
+ * says.
1741
+ *
1742
+ * @remarks
1743
+ * Each line opens with the fault's path (or `value` at the root) and reason. An `extra` fault lists
1744
+ * its parent's keys only when the declaring arms agree. A literal names candidates only where
1745
+ * the declarations agree; lists are deduplicated and bounded. A received preview stays as written
1746
+ * within PREVIEW_LIMIT and without control or line-separator characters; otherwise it is encoded
1747
+ * through preview. Received, constraint, and limit details read only own fields. A `variant` or
1748
+ * `oneOf` fault says that the value matches none of the declared forms, or several where one must
1749
+ * match, and summarizes each form through `renderForm`. It names no fault of any one form, because
1750
+ * none of them holds for the others. Those summaries share half of `FAULT_TEXT_LIMIT`.
1751
+ *
1752
+ * @param fault - The fault to describe
1753
+ * @param schema - The compiled schema the fault's path reads
1754
+ * @returns The line, with no line break
1755
+ *
1756
+ * @example
1757
+ * ```ts
1758
+ * import { describeFaultLine } from '@orkestrel/contract'
1759
+ *
1760
+ * describeFaultLine({ reason: 'missing', path: ['left'], expected: 'number' }, {}) // 'left: missing; expected number'
1761
+ * ```
1762
+ */
1763
+ export declare function describeFaultLine(fault: AuditFault, schema: JSONSchema): string;
1764
+
1765
+ /**
1766
+ * Describes bounded faults with encoded values and a schema-derived correction summary.
1767
+ *
1768
+ * @remarks
1769
+ * Default: 2048 UTF-16 code units. A smaller non-negative integer limit reserves a caller's
1770
+ * heading budget. The report reserves room for omitted-fault and cap notices, and ends with a
1771
+ * send summary when a schema is supplied. Untrusted names, descriptions, and strings use preview.
1772
+ *
1773
+ * @example
1774
+ * ```ts
1775
+ * describeFaults([{ reason: 'missing', path: ['age'], expected: 'number' }])
1776
+ * // 'age: missing; expected number'
1777
+ * ```
1778
+ */
1779
+ export declare function describeFaults(faults: readonly AuditFault[], schema?: JSONSchema, options?: FaultTextOptions): string;
1780
+
1585
1781
  /**
1586
1782
  * Draws and validates one generator random sample.
1587
1783
  *
@@ -1771,6 +1967,62 @@ export declare function escapeRegExp(value: string): string;
1771
1967
  /** Evaluates a compiled node at one diagnostic path. */
1772
1968
  export declare type EvaluationFunction<T> = (value: unknown, path: readonly string[]) => T;
1773
1969
 
1970
+ /**
1971
+ * Extracts a schema's forms: the schema itself, then its union arms, so a read looks
1972
+ * through a nullable the same way everywhere.
1973
+ *
1974
+ * @param schema - The schema to read, or `undefined` where none was found
1975
+ * @returns The forms, empty when there is no schema
1976
+ *
1977
+ * @example
1978
+ * ```ts
1979
+ * import { extractForms } from '@orkestrel/contract'
1980
+ *
1981
+ * const object = { type: 'object' } as const
1982
+ * extractForms({ anyOf: [object] }) // [{ anyOf: [object] }, object]
1983
+ * ```
1984
+ */
1985
+ export declare function extractForms(schema: JSONSchema | undefined): readonly JSONSchema[];
1986
+
1987
+ /**
1988
+ * Extracts a fault's path as its segments, reading a string path as one segment.
1989
+ *
1990
+ * @param fault - The fault to read
1991
+ * @returns The path's segments, empty at the root
1992
+ *
1993
+ * @example
1994
+ * ```ts
1995
+ * import { extractPath } from '@orkestrel/contract'
1996
+ *
1997
+ * extractPath({ reason: 'extra', path: ['page', 'typo'] }) // ['page', 'typo']
1998
+ * ```
1999
+ */
2000
+ export declare function extractPath(fault: AuditFault): readonly string[];
2001
+
2002
+ /**
2003
+ * Extracts the part of a schema a path reaches, through properties, array items, record values,
2004
+ * and the arms of a union.
2005
+ *
2006
+ * @remarks
2007
+ * Each path segment takes one step, so a union that nests itself cannot hold the walk. Only a
2008
+ * schema's own `properties` keys match, so `constructor` reaches nothing. The walk keeps every
2009
+ * matching union declaration until the end; differing declarations yield no schema. Independently
2010
+ * built declarations agree when their canonical JSON encodings agree.
2011
+ *
2012
+ * @param schema - The schema to walk
2013
+ * @param path - The segments to follow
2014
+ * @returns The schema at that path, or `undefined` where no declaration or no agreement exists
2015
+ *
2016
+ * @example
2017
+ * ```ts
2018
+ * import { extractSchema } from '@orkestrel/contract'
2019
+ *
2020
+ * const schema = { type: 'object', properties: { limit: { type: 'number' } } } as const
2021
+ * extractSchema(schema, ['limit']) // { type: 'number' }
2022
+ * ```
2023
+ */
2024
+ export declare function extractSchema(schema: JSONSchema, path: readonly string[]): JSONSchema | undefined;
2025
+
1774
2026
  /**
1775
2027
  * Represents a key present on a value that its closed object shape does not declare.
1776
2028
  *
@@ -1816,12 +2068,16 @@ export declare function failure<E>(error: E): Failure<E>;
1816
2068
  * - `'type'` — the value could not coerce to `expected` at all.
1817
2069
  * - `'missing'` — a required object property was absent.
1818
2070
  * - `'constraint'` — the value coerced to `expected` but violated one
1819
- * refinement (`min` / `max` / `pattern` / `integer`); `limit` carries the
2071
+ * refinement (`min` / `max` / `pattern` / `date` / `integer`); `limit` carries the
1820
2072
  * violated bound/pattern when applicable.
1821
2073
  * - `'variant'` — an `anyOf`-mode union matched no variant; `variants` is the
1822
2074
  * variant count, followed (in the report) by the closest variant's own faults.
1823
2075
  * - `'oneOf'` — a `oneOf`-mode union matched zero or two-or-more variants;
1824
2076
  * `matched` is the raw match count.
2077
+ *
2078
+ * A union whose arms a required literal property can tell apart reports the named
2079
+ * arm's own faults in place of either, and when the value names no one arm, `key`
2080
+ * and `expected` on these two say which property would and what it may hold.
1825
2081
  */
1826
2082
  export declare type Fault = {
1827
2083
  readonly reason: 'type';
@@ -1843,12 +2099,42 @@ export declare type Fault = {
1843
2099
  readonly reason: 'variant';
1844
2100
  readonly path: FieldPath;
1845
2101
  readonly variants: number;
2102
+ readonly key?: string;
2103
+ readonly expected?: readonly LiteralValue[];
1846
2104
  } | {
1847
2105
  readonly reason: 'oneOf';
1848
2106
  readonly path: FieldPath;
1849
2107
  readonly matched: number;
2108
+ readonly key?: string;
2109
+ readonly expected?: readonly LiteralValue[];
1850
2110
  };
1851
2111
 
2112
+ /**
2113
+ * Lists every {@link FaultConstraint}, frozen.
2114
+ *
2115
+ * @remarks
2116
+ * The runtime source of truth for the vocabulary, which {@link isFault} reads.
2117
+ *
2118
+ * @example
2119
+ * ```ts
2120
+ * FAULT_CONSTRAINTS.includes('min') // true
2121
+ * ```
2122
+ */
2123
+ export declare const FAULT_CONSTRAINTS: readonly FaultConstraint[];
2124
+
2125
+ /**
2126
+ * Lists every {@link FaultKind}, frozen.
2127
+ *
2128
+ * @remarks
2129
+ * The runtime source of truth for the vocabulary, which {@link isFault} reads.
2130
+ *
2131
+ * @example
2132
+ * ```ts
2133
+ * FAULT_KINDS.includes('string') // true
2134
+ * ```
2135
+ */
2136
+ export declare const FAULT_KINDS: readonly FaultKind[];
2137
+
1852
2138
  /**
1853
2139
  * Caps at `64` the number of {@link Fault} / {@link AuditFault} entries a single
1854
2140
  * `explain` or `audit` report ever returns, frozen.
@@ -1864,23 +2150,109 @@ export declare type Fault = {
1864
2150
  */
1865
2151
  export declare const FAULT_LIMIT = 64;
1866
2152
 
2153
+ /** Caps the keys or literal candidates named in a fault line. */
2154
+ export declare const FAULT_LIST_LIMIT = 12;
2155
+
2156
+ /** Caps a schema summary's UTF-16 code units. */
2157
+ export declare const FAULT_SCHEMA_LIMIT = 160;
2158
+
2159
+ /** Caps a fault message at 2048 UTF-16 code units. */
2160
+ export declare const FAULT_TEXT_LIMIT = 2048;
2161
+
1867
2162
  /**
1868
2163
  * Names the refinement a {@link Fault} of reason `'constraint'` violates.
1869
2164
  *
1870
2165
  * @remarks
1871
- * The vocabulary is `'min'`, `'max'`, `'pattern'`, and `'integer'`.
2166
+ * The vocabulary is `'min'`, `'max'`, `'pattern'`, `'date'`, and `'integer'`.
1872
2167
  */
1873
- export declare type FaultConstraint = 'min' | 'max' | 'pattern' | 'integer';
2168
+ export declare type FaultConstraint = 'min' | 'max' | 'pattern' | 'date' | 'integer';
1874
2169
 
1875
2170
  /**
1876
2171
  * Names the kind of value a {@link Fault} expected — the shape-projected counterpart of
1877
2172
  * a `ContractShape`'s `category`.
1878
2173
  *
1879
2174
  * @remarks
1880
- * The vocabulary is `'string'`, `'number'`, `'integer'`, `'boolean'`, `'null'`,
1881
- * `'literal'`, `'array'`, `'object'`, `'union'`, and `'json'`.
2175
+ * The vocabulary is `'string'`, `'date'`, `'number'`, `'integer'`, `'boolean'`, `'null'`,
2176
+ * `'literal'`, `'array'`, `'object'`, `'union'`, `'json'`, and `'shape'`.
2177
+ */
2178
+ export declare type FaultKind = 'string' | 'date' | 'number' | 'integer' | 'boolean' | 'null' | 'literal' | 'array' | 'object' | 'union' | 'json' | 'shape';
2179
+
2180
+ /**
2181
+ * Retains a lazily built fault declaration without building shapes during module evaluation.
2182
+ *
2183
+ * @example
2184
+ * ```ts
2185
+ * FaultShaper.shape === FaultShaper.shape // true
2186
+ * ```
2187
+ */
2188
+ declare class FaultShaper {
2189
+ #private;
2190
+ /** Returns the shared fault declaration, building it on the first read. */
2191
+ static get shape(): AuditFaultShape;
2192
+ /**
2193
+ * Builds a closed fault union whose inferred values satisfy the audit fault contract.
2194
+ *
2195
+ * @example
2196
+ * ```ts
2197
+ * createContract(new FaultShaper().build()).is({ reason: 'extra', path: [] }) // true
2198
+ * ```
2199
+ */
2200
+ build(): UnionShape<readonly [ObjectShape< {
2201
+ reason: LiteralShape<readonly ["type"]>;
2202
+ path: UnionShape<readonly [StringShape, ArrayShape<StringShape>]>;
2203
+ expected: LiteralShape<readonly FaultKind[]>;
2204
+ received: StringShape;
2205
+ }, false>, ObjectShape< {
2206
+ reason: LiteralShape<readonly ["missing"]>;
2207
+ path: UnionShape<readonly [StringShape, ArrayShape<StringShape>]>;
2208
+ expected: LiteralShape<readonly FaultKind[]>;
2209
+ }, false>, ObjectShape< {
2210
+ reason: LiteralShape<readonly ["constraint"]>;
2211
+ path: UnionShape<readonly [StringShape, ArrayShape<StringShape>]>;
2212
+ expected: LiteralShape<readonly FaultKind[]>;
2213
+ constraint: LiteralShape<readonly FaultConstraint[]>;
2214
+ limit: OptionalShape<UnionShape<readonly [NumberShape, StringShape]>>;
2215
+ received: StringShape;
2216
+ }, false>, ObjectShape< {
2217
+ reason: LiteralShape<readonly ["variant"]>;
2218
+ path: UnionShape<readonly [StringShape, ArrayShape<StringShape>]>;
2219
+ variants: NumberShape;
2220
+ }, false>, ObjectShape< {
2221
+ reason: LiteralShape<readonly ["variant"]>;
2222
+ path: UnionShape<readonly [StringShape, ArrayShape<StringShape>]>;
2223
+ variants: NumberShape;
2224
+ key: StringShape;
2225
+ expected: ArrayShape<UnionShape<readonly [StringShape, NumberShape, BooleanShape]>>;
2226
+ }, false>, ObjectShape< {
2227
+ reason: LiteralShape<readonly ["oneOf"]>;
2228
+ path: UnionShape<readonly [StringShape, ArrayShape<StringShape>]>;
2229
+ matched: NumberShape;
2230
+ }, false>, ObjectShape< {
2231
+ reason: LiteralShape<readonly ["oneOf"]>;
2232
+ path: UnionShape<readonly [StringShape, ArrayShape<StringShape>]>;
2233
+ matched: NumberShape;
2234
+ key: StringShape;
2235
+ expected: ArrayShape<UnionShape<readonly [StringShape, NumberShape, BooleanShape]>>;
2236
+ }, false>, ObjectShape< {
2237
+ reason: LiteralShape<readonly ["extra"]>;
2238
+ path: UnionShape<readonly [StringShape, ArrayShape<StringShape>]>;
2239
+ }, false>]>;
2240
+ }
2241
+
2242
+ /**
2243
+ * Reserves a caller's text budget for a bounded fault report.
2244
+ *
2245
+ * @remarks
2246
+ * The limit is a non-negative integer of UTF-16 code units, at most 2048. Default: 2048.
2247
+ *
2248
+ * @example
2249
+ * ```ts
2250
+ * const options: FaultTextOptions = { limit: 1024 }
2251
+ * ```
1882
2252
  */
1883
- export declare type FaultKind = 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'literal' | 'array' | 'object' | 'union' | 'json';
2253
+ export declare interface FaultTextOptions {
2254
+ readonly limit?: number;
2255
+ }
1884
2256
 
1885
2257
  /**
1886
2258
  * Addresses one field in a record: a single key, or an ordered list of keys to
@@ -2033,7 +2405,7 @@ export declare function holds(callback: () => boolean): boolean;
2033
2405
  * nesting. {@link InferIndex} and {@link InferOpenIndex} apply the identical
2034
2406
  * tuple guard to their own `A` parameter for the same reason.
2035
2407
  */
2036
- export declare type Infer<S extends ContractShape> = [ContractShape] extends [S] ? unknown : S extends StringShape ? string : S extends NumberShape ? number : S extends BooleanShape ? boolean : S extends NullShape ? null : S extends {
2408
+ export declare type Infer<S extends ContractShape> = [ContractShape] extends [S] ? unknown : S extends ShapeShape ? ContractShape : S extends StringShape ? string : S extends NumberShape ? number : S extends BooleanShape ? boolean : S extends NullShape ? null : S extends {
2037
2409
  readonly category: 'literal';
2038
2410
  readonly values: infer V;
2039
2411
  } ? V extends ReadonlyArray<infer L> ? L : never : S extends {
@@ -2664,6 +3036,23 @@ export declare function isAsyncGeneratorFunction(value: unknown): value is (...a
2664
3036
  */
2665
3037
  export declare function isAsyncIterable<T = unknown>(value: unknown): value is AsyncIterable<T>;
2666
3038
 
3039
+ /**
3040
+ * Determines whether a value is exactly one {@link AuditFault}.
3041
+ *
3042
+ * @remarks
3043
+ * Every {@link Fault}, and the undeclared-key fault an audit adds.
3044
+ *
3045
+ * @param value - The value to inspect
3046
+ * @returns True if the value is a well-formed audit fault; false otherwise
3047
+ *
3048
+ * @example
3049
+ * ```ts
3050
+ * isAuditFault({ reason: 'extra', path: ['a'] }) // true
3051
+ * isAuditFault({}) // false
3052
+ * ```
3053
+ */
3054
+ export declare function isAuditFault(value: unknown): value is AuditFault;
3055
+
2667
3056
  /** Determines whether a value is a bigint.
2668
3057
  *
2669
3058
  * @param value - The value to inspect
@@ -2964,6 +3353,39 @@ export declare function isFailure<T, E>(result: Result<T, E>): result is Failure
2964
3353
  */
2965
3354
  export declare function isFalse(value: unknown): value is false;
2966
3355
 
3356
+ /**
3357
+ * Determines whether a value is exactly one {@link Fault}.
3358
+ *
3359
+ * @remarks
3360
+ * A closed reading of the union: each reason's required fields, each with its own
3361
+ * vocabulary, and no other key, so `{}` and a fault carrying a stray field both answer
3362
+ * `false`. An undeclared-key fault is an {@link AuditFault} and answers `false` here.
3363
+ *
3364
+ * @param value - The value to inspect
3365
+ * @returns True if the value is a well-formed fault; false otherwise
3366
+ *
3367
+ * @example
3368
+ * ```ts
3369
+ * isFault({ reason: 'missing', path: ['a'], expected: 'string' }) // true
3370
+ * isFault({}) // false
3371
+ * ```
3372
+ */
3373
+ export declare function isFault(value: unknown): value is Fault;
3374
+
3375
+ /**
3376
+ * Determines whether a value is the {@link FieldPath} a fault carries: a key, or a dense list of keys.
3377
+ *
3378
+ * @param value - The value to inspect
3379
+ * @returns True if the value is a string or a dense array of strings; false otherwise
3380
+ *
3381
+ * @example
3382
+ * ```ts
3383
+ * isFaultPath(['user', 'name']) // true
3384
+ * isFaultPath([1]) // false
3385
+ * ```
3386
+ */
3387
+ export declare function isFaultPath(value: unknown): value is FieldPath;
3388
+
2967
3389
  /** Determines whether a value is a finite number (excludes `NaN` and `±Infinity`).
2968
3390
  *
2969
3391
  * @param value - The value to inspect
@@ -3798,10 +4220,13 @@ export declare class JSONCloner implements JSONClonerInterface {
3798
4220
  /**
3799
4221
  * Clones the retained source into exact, deeply frozen JSON data.
3800
4222
  *
4223
+ * @param budget - Remaining nodes shared with an enclosing ownership operation
3801
4224
  * @returns The settled JSON snapshot
3802
4225
  * @throws {ContractError} When the source is inexact, cyclic, unreadable, or cloning is reentered
3803
4226
  */
3804
- clone(): JSONValue;
4227
+ clone(budget?: {
4228
+ left: number;
4229
+ }): JSONValue;
3805
4230
  }
3806
4231
 
3807
4232
  /**
@@ -3827,10 +4252,13 @@ export declare interface JSONClonerInterface {
3827
4252
  * alike. Active reentry permanently settles the instance with one exact cause-free
3828
4253
  * `clone` poison shared by the nested call, the outer call, and every later call.
3829
4254
  *
4255
+ * @param budget - Remaining nodes shared with an enclosing ownership operation; omitted for an independent snapshot
3830
4256
  * @returns The settled JSON snapshot
3831
4257
  * @throws {ContractError} When the source is inexact, cyclic, unreadable, or cloning is reentered
3832
4258
  */
3833
- clone(): JSONValue;
4259
+ clone(budget?: {
4260
+ left: number;
4261
+ }): JSONValue;
3834
4262
  }
3835
4263
 
3836
4264
  /**
@@ -3879,6 +4307,7 @@ export declare type JSONRecord = {
3879
4307
  export declare interface JSONSchema {
3880
4308
  readonly type?: JSONSchemaType;
3881
4309
  readonly description?: string;
4310
+ readonly default?: JSONValue;
3882
4311
  readonly enum?: readonly LiteralValue[];
3883
4312
  readonly minLength?: number;
3884
4313
  readonly maxLength?: number;
@@ -4121,6 +4550,47 @@ export declare function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): G
4121
4550
 
4122
4551
  export declare function mapOf(keyPredicate: (value: unknown) => boolean, valuePredicate: (value: unknown) => boolean): Guard<ReadonlyMap<unknown, unknown>>;
4123
4552
 
4553
+ /**
4554
+ * Checks whether a string is exactly a calendar-valid `YYYY-MM-DD` date.
4555
+ *
4556
+ * @remarks
4557
+ * Refuses a date-time, surrounding whitespace, and a date the Gregorian calendar
4558
+ * lacks, such as `2026-02-29`. Backs a date string shape and {@link classifyFormat}'s
4559
+ * `date`.
4560
+ *
4561
+ * @param value - The candidate string
4562
+ * @returns True if `value` is a calendar-valid `YYYY-MM-DD`; false otherwise
4563
+ * @throws The exact value thrown by a redirected pattern dispatch
4564
+ *
4565
+ * @example
4566
+ * ```ts
4567
+ * matchesCalendarDate('2024-02-29') // true
4568
+ * matchesCalendarDate('2026-02-29') // false
4569
+ * ```
4570
+ */
4571
+ export declare function matchesCalendarDate(value: string): boolean;
4572
+
4573
+ /**
4574
+ * Determines whether an object holds exactly the named own keys.
4575
+ *
4576
+ * @remarks
4577
+ * Every required key must be own, and every own key, symbols and non-enumerable ones
4578
+ * included, must be named, so an inherited field and a stray one both answer `false`.
4579
+ *
4580
+ * @param value - The object to inspect
4581
+ * @param required - The keys it must own
4582
+ * @param optional - The keys it may own
4583
+ * @returns True if its own keys are exactly those; false otherwise
4584
+ *
4585
+ * @example
4586
+ * ```ts
4587
+ * matchesExactKeys({ a: 1 }, ['a']) // true
4588
+ * matchesExactKeys({ a: 1, b: 2 }, ['a']) // false
4589
+ * matchesExactKeys({ a: 1, b: 2 }, ['a'], ['b']) // true
4590
+ * ```
4591
+ */
4592
+ export declare function matchesExactKeys(value: object, required: readonly string[], optional?: readonly string[]): boolean;
4593
+
4124
4594
  /**
4125
4595
  * Checks whether a supported ISO-8601 date or date-time names a real instant.
4126
4596
  *
@@ -4194,13 +4664,16 @@ export declare function matchesJSONDepth(value: unknown): boolean;
4194
4664
  *
4195
4665
  * Beside the ancestor set the walk keeps a walk-local PROVED set, so a node
4196
4666
  * whose whole subtree already matched is not re-walked when a second path
4197
- * reaches it. Removing the recursion alone left the work exponential in shared
4667
+ * reaches it. A supplied capture budget instead charges each occurrence that
4668
+ * ownership would copy; exhaustion throws `structure` with a `clone` cause.
4669
+ * Removing the recursion alone left the work exponential in shared
4198
4670
  * aliases: thirty aliases — thirty-one ordinary records — cost `2^30` visits
4199
4671
  * through `isJSONValue`, `parseJSONValue`, `canonicalStringify` and every
4200
4672
  * `jsonShape` contract.
4201
4673
  *
4202
4674
  * @param entry - The value to inspect
4203
4675
  * @param ancestors - Objects on the active traversal path
4676
+ * @param budget - Remaining capture nodes; aliases are charged for each copied occurrence when supplied
4204
4677
  * @returns True if the value is a cycle-free JSON value; false otherwise
4205
4678
  *
4206
4679
  * @example
@@ -4209,7 +4682,37 @@ export declare function matchesJSONDepth(value: unknown): boolean;
4209
4682
  * matchesJSONValue(Number.NaN, new WeakSet()) // false
4210
4683
  * ```
4211
4684
  */
4212
- export declare function matchesJSONValue(entry: unknown, ancestors: WeakSet<object>): entry is JSONValue;
4685
+ export declare function matchesJSONValue(entry: unknown, ancestors: WeakSet<object>, budget?: {
4686
+ left: number;
4687
+ }): entry is JSONValue;
4688
+
4689
+ /**
4690
+ * Determines whether a repair `parse` made kept everything the value said.
4691
+ *
4692
+ * @remarks
4693
+ * `parse`'s coercions are published and form input relies on them, but some change what
4694
+ * a value means: `1` to `true`, `'9007199254740993'` to `...992`, `'1e-400'` to `0`,
4695
+ * `'0x10'` to `16`. A door that must not guess asks this about each fault `audit` reported,
4696
+ * since `audit` already names every nested repair with its path and the kind it wanted.
4697
+ *
4698
+ * Only a `type` fault is a repair. A number needs a string whose trim is the number's own
4699
+ * text, so `'30'` and `' 30 '` pass while `'30.0'`, `'007'`, `'0x10'`, `'1e3'`, `'+5'`,
4700
+ * `'.5'`, `'-0'`, and `'9007199254740993'` do not. A boolean needs `'true'` or `'false'`,
4701
+ * a literal its trimmed text, and a string a finite number. Anything else refuses.
4702
+ *
4703
+ * @param fault - A fault `audit` reported
4704
+ * @param input - The value as it arrived
4705
+ * @param parsed - What `parse` made of it
4706
+ * @returns True if the repair loses nothing; false otherwise
4707
+ *
4708
+ * @example
4709
+ * ```ts
4710
+ * const fault = { reason: 'type', path: ['a'], expected: 'number', received: '' } as const
4711
+ * matchesLosslessRepair(fault, { a: ' 30 ' }, { a: 30 }) // true
4712
+ * matchesLosslessRepair(fault, { a: '30.0' }, { a: 30 }) // false
4713
+ * ```
4714
+ */
4715
+ export declare function matchesLosslessRepair(fault: AuditFault, input: unknown, parsed: unknown): boolean;
4213
4716
 
4214
4717
  /**
4215
4718
  * Determines whether a value is a member of a collected vocabulary, by
@@ -4324,6 +4827,44 @@ export declare function matchesPattern(pattern: RegExp, value: string): boolean;
4324
4827
  */
4325
4828
  export declare function matchesRecordBrand(value: unknown): boolean;
4326
4829
 
4830
+ /**
4831
+ * Checks whether a string's length in code points falls within optional bounds.
4832
+ *
4833
+ * @remarks
4834
+ * Counts what JSON Schema's `minLength` and `maxLength` count: a surrogate pair is
4835
+ * one, and a lone surrogate is one. A string holds at most `.length` code points and
4836
+ * at least half that, so `.length` decides every bound it can with no count. The
4837
+ * count runs only where a bound sits between those two figures, which limits its
4838
+ * work to about twice the bound rather than to the size of the string.
4839
+ *
4840
+ * @param value - The string to measure
4841
+ * @param min - The inclusive lower bound, when there is one
4842
+ * @param max - The inclusive upper bound, when there is one
4843
+ * @returns True if the code-point count is within every present bound; false otherwise
4844
+ *
4845
+ * @example
4846
+ * ```ts
4847
+ * matchesStringLength('😀😀', undefined, 2) // true
4848
+ * matchesStringLength('😀', 2, undefined) // false
4849
+ * ```
4850
+ */
4851
+ export declare function matchesStringLength(value: string, min: number | undefined, max: number | undefined): boolean;
4852
+
4853
+ /**
4854
+ * Checks whether a type fault describes an own undefined field omitted or defaulted by a successful parse.
4855
+ *
4856
+ * @remarks
4857
+ * Reads own members directly so absence and an unreadable member cannot stand for undefined.
4858
+ * A compiled parser fills an undefined field only through its declared default; it never coerces it.
4859
+ * Required reads propagate their cause to the admission boundary.
4860
+ *
4861
+ * @example
4862
+ * ```ts
4863
+ * matchesUndefinedField({ reason: 'type', path: ['note'], expected: 'string', received: 'undefined' }, { note: undefined }, {}) // true
4864
+ * ```
4865
+ */
4866
+ export declare function matchesUndefinedField(fault: AuditFault, value: unknown, parsed: unknown): boolean;
4867
+
4327
4868
  /**
4328
4869
  * Determines whether an object is already on a traversal's active path.
4329
4870
  *
@@ -4658,9 +5199,11 @@ export declare function omitVisited(visited: WeakSet<object>, value: object): vo
4658
5199
  * {@link unionShape}'s guard.
4659
5200
  * - **Parser**: judged on the RAW input's guard matches only, with NO
4660
5201
  * coercion fallback for an ambiguous input. When exactly one variant's
4661
- * guard accepts the raw value, that variant's parser runs. Zero matches or
5202
+ * guard accepts the raw value, the input itself is returned. Zero matches or
4662
5203
  * two-or-more matches both parse to `undefined` — a value ambiguous
4663
- * between variants has no well-defined coercion target.
5204
+ * between variants has no well-defined coercion target. A value that names one
5205
+ * arm through a required literal is not ambiguous, so as in {@link unionShape}
5206
+ * that arm answers alone, and its parser may coerce.
4664
5207
  *
4665
5208
  * Prefer {@link unionShape} when a value may legitimately satisfy more than
4666
5209
  * one variant (for example overlapping shapes) and any match is acceptable. Prefer
@@ -4714,10 +5257,19 @@ export declare type OptionalFromGuards<S extends GuardsShape, K extends Readonly
4714
5257
  */
4715
5258
  export declare function optionalOf<T>(guard: Guard<T>): Guard<T | undefined>;
4716
5259
 
4717
- /** Wraps an inner shape that may be absent (`undefined`). */
5260
+ /**
5261
+ * Wraps an inner shape that may be absent (`undefined`).
5262
+ *
5263
+ * @remarks
5264
+ * `default` holds the JSON value the compiled parser fills when the property is
5265
+ * absent or `undefined`. It leaves `is`, `audit`, `explain`, and `generate`
5266
+ * unchanged, because an absent optional stays canonical. It must satisfy `inner`,
5267
+ * and it may sit only on a property of a closed object with no union ancestor.
5268
+ */
4718
5269
  export declare interface OptionalShape<S extends ContractShape = ContractShape> {
4719
5270
  readonly category: 'optional';
4720
5271
  readonly inner: S;
5272
+ readonly default?: JSONValue;
4721
5273
  }
4722
5274
 
4723
5275
  /**
@@ -4725,12 +5277,28 @@ export declare interface OptionalShape<S extends ContractShape = ContractShape>
4725
5277
  *
4726
5278
  * @remarks
4727
5279
  * As an {@link objectShape} property, the field becomes a true optional property
4728
- * in the inferred type.
5280
+ * in the inferred type. A `default` is captured as an owned frozen copy, and the
5281
+ * compiled parser fills it where the property is absent or `undefined`; the guard,
5282
+ * the audit, the report, and the generator keep treating the property as optional.
5283
+ * The compilers refuse a default `inner` refuses, a default under a union, and a
5284
+ * default on a property of an open object.
4729
5285
  *
4730
5286
  * @param inner - The wrapped shape
5287
+ * @param options - Optional `default`, a JSON value
4731
5288
  * @returns An optional shape
5289
+ * @throws {ContractError} When a present `default` is not a JSON value, `undefined` included
5290
+ *
5291
+ * @example
5292
+ * ```ts
5293
+ * const retries = optionalShape(integerShape({ min: 0 }), { default: 3 })
5294
+ * ```
4732
5295
  */
4733
- export declare function optionalShape<S extends ContractShape>(inner: S): OptionalShape<S>;
5296
+ export declare function optionalShape<S extends ContractShape>(inner: S, options?: OptionalShapeOptions): OptionalShape<S>;
5297
+
5298
+ /** Groups the options for {@link OptionalShape} (through `optionalShape`). */
5299
+ export declare interface OptionalShapeOptions {
5300
+ readonly default?: JSONValue;
5301
+ }
4734
5302
 
4735
5303
  /**
4736
5304
  * Combines `left` and `right` with logical OR — passes when at least one passes.
@@ -5405,6 +5973,8 @@ export declare interface RawShape {
5405
5973
  * For values the shape DSL can't express. The fragment is recursively checked
5406
5974
  * against the lean {@link JSONSchema} vocabulary before ownership is taken;
5407
5975
  * malformed or unsupported keywords throw a coded {@link ContractError}. The
5976
+ * refusal path starts at `schema` and names the nested keyword or member.
5977
+ * A non-record root is refused at `schema` itself. The
5408
5978
  * compiled guard accepts every
5409
5979
  * DEFINED value — `undefined` alone fails, because it is the parser's failure
5410
5980
  * sentinel; wrap the shape in {@link optionalShape} to admit absence. The
@@ -5798,6 +6368,87 @@ export declare interface RecordShapeOptions {
5798
6368
  */
5799
6369
  export declare function refuseExpansion(expansion: number | undefined): void;
5800
6370
 
6371
+ /**
6372
+ * Refuses an options record that holds a key its builder does not read.
6373
+ *
6374
+ * @remarks
6375
+ * The door for an option that decides what a contract accepts, where a misspelled key
6376
+ * would otherwise read as an absent option and fail open. It looks at own enumerable
6377
+ * string keys, so an inherited or symbol-keyed member is not a misspelling.
6378
+ *
6379
+ * @param source - The builder options, when there are any
6380
+ * @param keys - The keys that builder reads
6381
+ * @param builder - The builder name used in the refusal
6382
+ * @param shape - The shape category used in structured error context
6383
+ * @throws {ContractError} When the record holds any other key
6384
+ *
6385
+ * @example
6386
+ * ```ts
6387
+ * refuseOptionKeys({ strict: true }, ['strict'], 'schemaToShape', 'schema') // returns
6388
+ * refuseOptionKeys({ strct: true }, ['strict'], 'schemaToShape', 'schema') // throws
6389
+ * ```
6390
+ */
6391
+ export declare function refuseOptionKeys(source: object | undefined, keys: readonly string[], builder: string, shape: string): void;
6392
+
6393
+ /**
6394
+ * Renders a schema as a short summary of what to send, such as `{"city": string, "note"?: string}`.
6395
+ *
6396
+ * @remarks
6397
+ * An object lists its required keys first and marks the rest with `?`, at most `FAULT_LIST_LIMIT`
6398
+ * of them. A leaf or array keeps its numeric bounds, pattern, and format, a union joins its forms with ` | `,
6399
+ * and a schema that says nothing reads `any`. Each nested form takes half the room of its parent, and
6400
+ * below 16 characters a form stops at its type, so a schema that holds itself still ends. Text past
6401
+ * `room` is cut and closes with `…`. A type word outside JSON Schema's vocabulary is encoded.
6402
+ *
6403
+ * @param schema - The schema to summarize
6404
+ * @param room - The characters the summary can take. Default: `FAULT_SCHEMA_LIMIT`
6405
+ * @returns The summary
6406
+ *
6407
+ * @example
6408
+ * ```ts
6409
+ * import { renderForm } from '@orkestrel/contract'
6410
+ *
6411
+ * renderForm({ type: 'object', properties: { zip: { type: 'number' } }, required: ['zip'] }) // '{"zip": number}'
6412
+ * ```
6413
+ */
6414
+ export declare function renderForm(schema: JSONSchema, room?: number): string;
6415
+
6416
+ /**
6417
+ * Renders a list as text, naming at most `FAULT_LIST_LIMIT` of its entries and counting the rest.
6418
+ *
6419
+ * @param entries - The rendered entries
6420
+ * @returns The entries joined with `, `
6421
+ *
6422
+ * @example
6423
+ * ```ts
6424
+ * import { renderList } from '@orkestrel/contract'
6425
+ *
6426
+ * renderList(['city', 'units']) // 'city, units'
6427
+ * ```
6428
+ */
6429
+ export declare function renderList(entries: readonly string[]): string;
6430
+
6431
+ /**
6432
+ * Renders a path as text, encoding what a caller could have sent and eliding the middle of a long
6433
+ * one.
6434
+ *
6435
+ * @remarks
6436
+ * A segment that is not a plain identifier is JSON-encoded and length-capped, because a key the
6437
+ * caller sent is untrusted text. A path of more than four segments past 120 characters keeps its
6438
+ * first segment and its last three.
6439
+ *
6440
+ * @param path - The segments to render
6441
+ * @returns The segments joined with `.`, empty at the root
6442
+ *
6443
+ * @example
6444
+ * ```ts
6445
+ * import { renderPath } from '@orkestrel/contract'
6446
+ *
6447
+ * renderPath(['rows', '0', 'a b']) // 'rows.0."a b"'
6448
+ * ```
6449
+ */
6450
+ export declare function renderPath(path: readonly string[]): string;
6451
+
5801
6452
  /**
5802
6453
  * Represents a compiled coercive-domain diagnostic — the shape of
5803
6454
  * `compileReporter` bound to one shape.
@@ -6159,8 +6810,9 @@ export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<
6159
6810
  /**
6160
6811
  * Converts a runtime `JSONSchema` value into a validating {@link ContractShape}
6161
6812
  * — the inverse of {@link compileSchema}. Unlike direct {@link rawShape}
6162
- * construction, which rejects malformed supported-vocabulary keywords, this
6163
- * conversion is total and widens an inexpressible input to a valid raw `{}`.
6813
+ * construction, which rejects malformed supported-vocabulary keywords, the
6814
+ * lenient conversion is total and widens an inexpressible input to a valid raw
6815
+ * `{}`, and a strict conversion refuses that input.
6164
6816
  *
6165
6817
  * @remarks
6166
6818
  * Readable malformed, cyclic, or deeply nested schema nodes widen to
@@ -6211,9 +6863,39 @@ export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<
6211
6863
  * when the conversion widened anywhere — `schema` / `is` / `parse` / `explain`
6212
6864
  * stay total.
6213
6865
  *
6866
+ * LENIENT LAW: a value a JSON Schema accepts is never refused by the shape a
6867
+ * lenient conversion builds from it, because the walk widens what it cannot read.
6868
+ * So `oneOf` builds an inclusive union, a `true` arm is a raw variant and a `false`
6869
+ * arm is dropped, an `enum` holding `null` admits it, `nullable: true` wraps the
6870
+ * node, a present `patternProperties` opens the object, a present `prefixItems`
6871
+ * widens the elements, and a `$ref` widens the node before anything beside it is read.
6872
+ * A schema past the compile limit keeps only its root's type, an array's bounds, and an
6873
+ * object's required keys and closure, with every value below them raw.
6874
+ *
6875
+ * DEFAULTS: a lenient conversion carries a property's `default` when the key is
6876
+ * not `required`, its object is closed with no union ancestor, and the value is
6877
+ * one the property's primitive or literal guard accepts. It drops every other
6878
+ * `default`, because carrying it would make the shape refuse to compile.
6879
+ *
6880
+ * STRICT: `{ strict: true }` is the door for a foreign schema. It refuses, with
6881
+ * code `structure`, every node the lenient walk would widen, every keyword it
6882
+ * would ignore (`pattern`, every `format` but `'date'` on a string node, `nullable`,
6883
+ * `patternProperties`, `propertyNames`, `prefixItems`, and anything else outside
6884
+ * {@link STRICT_SCHEMA_KEYWORDS}), a malformed keyword or annotation, a boolean schema, an `enum` entry
6885
+ * that is neither a finite primitive nor `null`, a contradictory bound, a date format whose
6886
+ * length bounds exclude length 10, a `required` name not in
6887
+ * `properties`, breadth past {@link INFER_BREADTH_LIMIT}, and a `default` with no
6888
+ * optional property to fill. An object with no `additionalProperties` closes
6889
+ * rather than opens, and `oneOf` keeps exactly-one, because a strict walk reads
6890
+ * every keyword that could keep two arms apart. Below a `oneOf` that object refuses
6891
+ * instead, since closing it could change which arms match. A strict conversion is the
6892
+ * one walk that asserts a `format`: it reads `format: 'date'` on a string node as a
6893
+ * date string shape, so a compiled {@link dateShape} round-trips.
6894
+ *
6214
6895
  * @param schema - The JSON Schema value to convert
6896
+ * @param options - Optional `strict`, default `false`
6215
6897
  * @returns The built {@link ContractShape}
6216
- * @throws {ContractError} When schema traversal fails
6898
+ * @throws {ContractError} When schema traversal fails, or when a strict conversion refuses
6217
6899
  *
6218
6900
  * @example
6219
6901
  * ```ts
@@ -6223,7 +6905,18 @@ export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<
6223
6905
  * contract.parse({ id: 'nope' }) // undefined
6224
6906
  * ```
6225
6907
  */
6226
- export declare function schemaToShape(schema: JSONSchema): ContractShape;
6908
+ export declare function schemaToShape(schema: JSONSchema, options?: SchemaToShapeOptions): ContractShape;
6909
+
6910
+ /**
6911
+ * Groups the options for converting a JSON Schema (through `schemaToShape`).
6912
+ *
6913
+ * @remarks
6914
+ * `strict` (default `false`) refuses what the lenient conversion widens or
6915
+ * ignores, and closes an object with no `additionalProperties`.
6916
+ */
6917
+ export declare interface SchemaToShapeOptions {
6918
+ readonly strict?: boolean;
6919
+ }
6227
6920
 
6228
6921
  /**
6229
6922
  * Builds a deterministic pseudo-random source seeded from a single number.
@@ -6312,6 +7005,16 @@ export declare function setOf<T>(elementGuard: Guard<T>): Guard<ReadonlySet<T>>;
6312
7005
 
6313
7006
  export declare function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>>;
6314
7007
 
7008
+ /**
7009
+ * Lists the fields recognized for every contract declaration category, frozen.
7010
+ *
7011
+ * @example
7012
+ * ```ts
7013
+ * SHAPE_FIELDS.shape // ['description']
7014
+ * ```
7015
+ */
7016
+ export declare const SHAPE_FIELDS: Readonly<Record<string, readonly string[]>>;
7017
+
6315
7018
  /**
6316
7019
  * Owns the state of one contract-shape snapshot operation.
6317
7020
  *
@@ -6396,6 +7099,56 @@ export declare interface ShapeProperty {
6396
7099
  readonly child: ContractShape | undefined;
6397
7100
  }
6398
7101
 
7102
+ /**
7103
+ * Describes a value that is a structurally valid contract declaration.
7104
+ *
7105
+ * @remarks
7106
+ * Acceptance is a successful {@link validateShape}, including its expansion bound.
7107
+ * Parsing preserves identity and never compiles the value or fills its defaults.
7108
+ * The shallow schema over-approximates declarations whose JSON projection preserves
7109
+ * their own enumerable data. Values with a different projection or no JSON projection
7110
+ * fall outside this schema, including custom `toJSON`, hidden keys, proxy omissions,
7111
+ * and extra members containing a BigInt or a cycle. Structural acceptance is unchanged.
7112
+ * It describes only the category and cannot
7113
+ * teach a language model to author a complete nested declaration. The guard decides.
7114
+ *
7115
+ * @example
7116
+ * ```ts
7117
+ * const declaration: ShapeShape = { category: 'shape' }
7118
+ * createContract(declaration).is(numberShape()) // true
7119
+ * ```
7120
+ */
7121
+ export declare interface ShapeShape {
7122
+ readonly category: 'shape';
7123
+ readonly description?: string;
7124
+ }
7125
+
7126
+ /**
7127
+ * Builds a {@link ShapeShape}.
7128
+ *
7129
+ * @param options - Optional description
7130
+ * @returns A shape-valued declaration
7131
+ *
7132
+ * @example
7133
+ * ```ts
7134
+ * const definition = objectShape({ shape: shapeShape() })
7135
+ * ```
7136
+ */
7137
+ export declare function shapeShape(options?: ShapeShapeOptions): ShapeShape;
7138
+
7139
+ /**
7140
+ * Configures the description of a shape-valued declaration.
7141
+ *
7142
+ * @example
7143
+ * ```ts
7144
+ * const options: ShapeShapeOptions = { description: 'A question declaration' }
7145
+ * shapeShape(options).description // 'A question declaration'
7146
+ * ```
7147
+ */
7148
+ export declare interface ShapeShapeOptions {
7149
+ readonly description?: string;
7150
+ }
7151
+
6399
7152
  /**
6400
7153
  * Projects a {@link ContractShape} to the {@link FaultKind} it describes.
6401
7154
  *
@@ -6403,7 +7156,8 @@ export declare interface ShapeProperty {
6403
7156
  * A structural mapping used by {@link compileReporter} to fill a `Fault`'s
6404
7157
  * `expected` field and by {@link compileAuditor} to fill an `AuditFault`'s:
6405
7158
  * most shapes map to their own `category` (`numberShape` maps to
6406
- * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /
7159
+ * `'integer'` when `integer: true`, else `'number'`, and `stringShape` maps to
7160
+ * `'date'` when `date: true`, else `'string'`); `optionalShape` /
6407
7161
  * `nullableShape` project through to their inner shape's kind, and `rawShape`
6408
7162
  * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.
6409
7163
  *
@@ -6447,7 +7201,7 @@ export declare class ShapeValidator implements ShapeValidatorInterface {
6447
7201
  *
6448
7202
  * @param shape - The live shape source validated by each call
6449
7203
  */
6450
- constructor(shape: ContractShape);
7204
+ constructor(shape: unknown);
6451
7205
  /**
6452
7206
  * Reports the number of nodes the last successful {@link validate} found the
6453
7207
  * source expands into.
@@ -6538,6 +7292,26 @@ export declare interface ShapeValidatorInterface {
6538
7292
  */
6539
7293
  export declare function sortValues<T extends string | number>(values: readonly T[]): readonly T[];
6540
7294
 
7295
+ /**
7296
+ * Lists the JSON Schema keywords a strict `schemaToShape` conversion reads, frozen.
7297
+ *
7298
+ * @remarks
7299
+ * The keywords a shape can honour, plus the annotations that assert nothing and so
7300
+ * lose nothing when a shape drops them: `title`, `$schema`, `$id`, `$comment`,
7301
+ * `examples`, `deprecated`, `readOnly`, and `writeOnly`. Every other keyword refuses.
7302
+ * `pattern` and `format` are absent because no compiled shape asserts them, so a
7303
+ * schema holding one would convert to a shape wider than the schema it came from. The
7304
+ * one exception is `format: 'date'` on a string node, which a strict conversion reads
7305
+ * as a date string shape.
7306
+ *
7307
+ * @example
7308
+ * ```ts
7309
+ * STRICT_SCHEMA_KEYWORDS.includes('title') // true
7310
+ * STRICT_SCHEMA_KEYWORDS.includes('pattern') // false
7311
+ * ```
7312
+ */
7313
+ export declare const STRICT_SCHEMA_KEYWORDS: readonly string[];
7314
+
6541
7315
  /**
6542
7316
  * Caps at `65536` the length, in UTF-16 code units, of any single string one schema
6543
7317
  * retains, frozen.
@@ -6557,9 +7331,9 @@ export declare const STRING_LIMIT = 65536;
6557
7331
  *
6558
7332
  * @remarks
6559
7333
  * The refinement half of {@link StringShapeOptions}: the same `min`, `max`, and
6560
- * `pattern` members, without the `description` a shape carries for its emitted
6561
- * schema. A guard publishes no description, so the two surfaces share the
6562
- * refinements and nothing else.
7334
+ * `pattern` members, without the `date` flag and the `description` a shape
7335
+ * carries for its emitted schema. A compiled date shape composes this guard with
7336
+ * {@link matchesCalendarDate}.
6563
7337
  */
6564
7338
  export declare interface StringGuardOptions {
6565
7339
  readonly min?: number;
@@ -6572,8 +7346,9 @@ export declare interface StringGuardOptions {
6572
7346
  * refinements — `min` / `max` length and a `pattern`.
6573
7347
  *
6574
7348
  * @remarks
6575
- * Composes {@link isString} with {@link boundsOf} on the string's `.length` and
6576
- * an owned stateless pattern (the same refinement {@link matchOf} performs).
7349
+ * Composes {@link isString} with {@link matchesStringLength}, which counts code
7350
+ * points as the `minLength` and `maxLength` a string shape emits do, and an owned
7351
+ * stateless pattern (the same refinement {@link matchOf} performs).
6577
7352
  * When `min`, `max`, and `pattern` are all absent it returns the bare {@link isString} guard
6578
7353
  * (the unconstrained fast path), so an unrefined string leaf pays no wrapping
6579
7354
  * cost. The single source of the string refinement shared by the compiled guard
@@ -6595,7 +7370,15 @@ export declare interface StringGuardOptions {
6595
7370
  */
6596
7371
  export declare function stringOf(options?: StringGuardOptions): Guard<string>;
6597
7372
 
6598
- /** Describes a string with optional length and pattern constraints. */
7373
+ /**
7374
+ * Describes a string with optional length, pattern, and calendar-date constraints.
7375
+ *
7376
+ * @remarks
7377
+ * `min` and `max` count code points, as the `minLength` and `maxLength` the shape
7378
+ * emits do, so one astral character has a length of one. `date` restricts the string
7379
+ * to a calendar-valid `YYYY-MM-DD` and emits `format: 'date'`; a shape that declares
7380
+ * `date` declares no `pattern`.
7381
+ */
6599
7382
  export declare interface StringShape {
6600
7383
  readonly category: 'string';
6601
7384
  readonly min?: number;
@@ -6605,6 +7388,7 @@ export declare interface StringShape {
6605
7388
  * Builders and cloners expose an owned fresh frozen zero-state copy per read.
6606
7389
  */
6607
7390
  readonly pattern?: RegExp;
7391
+ readonly date?: boolean;
6608
7392
  readonly description?: string;
6609
7393
  }
6610
7394
 
@@ -6615,10 +7399,12 @@ export declare interface StringShape {
6615
7399
  * A supplied pattern is captured by source and flags. The shape exposes a fresh
6616
7400
  * frozen zero-state `RegExp` on every `pattern` read, so neither the caller's
6617
7401
  * original nor a value read from the shape can drift later compiled artifacts.
7402
+ * `date: true` restricts the string to a calendar-valid `YYYY-MM-DD`, as
7403
+ * {@link dateShape} builds it.
6618
7404
  *
6619
- * @param options - Optional length (`min` / `max`), `pattern`, and `description`
7405
+ * @param options - Optional length (`min` / `max`), `pattern`, `date`, and `description`
6620
7406
  * @returns A string shape
6621
- * @throws {ContractError} When a present bound is invalid, `pattern` is not a `RegExp`, or `pattern` has flags
7407
+ * @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
6622
7408
  *
6623
7409
  * @example
6624
7410
  * ```ts
@@ -6632,6 +7418,7 @@ export declare interface StringShapeOptions {
6632
7418
  readonly min?: number;
6633
7419
  readonly max?: number;
6634
7420
  readonly pattern?: RegExp;
7421
+ readonly date?: boolean;
6635
7422
  readonly description?: string;
6636
7423
  }
6637
7424
 
@@ -6732,6 +7519,16 @@ export declare function transformOf<T, U>(base: Guard<T>, project: (value: T) =>
6732
7519
 
6733
7520
  export declare function transformOf<T>(base: Guard<T>, project: (value: T) => unknown, target: (value: unknown) => boolean): Guard<T>;
6734
7521
 
7522
+ /**
7523
+ * Truncates text to a UTF-16 budget without splitting a surrogate pair.
7524
+ *
7525
+ * @example
7526
+ * ```ts
7527
+ * truncateFaultText('abcdef', 4) // 'abc…'
7528
+ * ```
7529
+ */
7530
+ export declare function truncateFaultText(text: string, limit: number): string;
7531
+
6735
7532
  /** Maps a tuple of element guards to a readonly tuple of their guarded types. */
6736
7533
  export declare type TupleFromGuards<Ts extends ReadonlyArray<Guard<unknown>>> = Readonly<{
6737
7534
  [K in keyof Ts]: GuardType<Ts[K]>;
@@ -6832,6 +7629,13 @@ export declare interface UnionShape<V extends readonly ContractShape[] = readonl
6832
7629
  /**
6833
7630
  * Builds a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).
6834
7631
  *
7632
+ * @remarks
7633
+ * When every arm is an object declaring one required literal property, and a value's
7634
+ * own property exactly equals a literal only one arm holds, that arm answers: `explain`
7635
+ * and `audit` report its faults at their real paths, and `parse` repairs through it
7636
+ * alone. Any other value reports `variant`, with `key` and `expected` saying what would
7637
+ * have named an arm. `is` does not change.
7638
+ *
6835
7639
  * @param variants - The candidate shapes; the first match wins at runtime
6836
7640
  * @returns A union shape whose `Infer` is the union of the variants
6837
7641
  *
@@ -6876,14 +7680,15 @@ export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void
6876
7680
  * eager well-formedness pass — there is no second prepass and no alias for it:
6877
7681
  * it enforces every bound domain and range used by the artifacts, including
6878
7682
  * non-empty literal/union vocabularies, finite literal numbers, integer-range
6879
- * satisfiability, unflagged string patterns, optional-shape placement, and the
6880
- * recursively supported raw-schema vocabulary where every present property or
6881
- * dense union member is a record.
7683
+ * satisfiability, unflagged string patterns, optional-shape and default
7684
+ * placement, and the recursively supported raw-schema vocabulary where every
7685
+ * present property or dense union member is a record. It judges a default's
7686
+ * structure only; each compiler refuses a default its inner guard refuses.
6882
7687
  * Active ancestors are tracked so shared children remain legal. Every
6883
7688
  * standalone compiler reaches this same validation once, over its owned
6884
7689
  * snapshot, through {@link ContractCompiler} preparation.
6885
- * Failures have deterministic precedence independent of traversal order: depth,
6886
- * then structure, then cycle, then field and vocabulary policy.
7690
+ * Cyclic graphs refuse before depth measurement, with structure before cycle.
7691
+ * Acyclic graphs report depth before structure, then field and vocabulary policy.
6887
7692
  *
6888
7693
  * @param shape - The shape graph to gate
6889
7694
  * @returns Nothing; successful return means recursive compilation is structurally safe, depth-safe, and bounded in emitted nodes
@@ -6894,7 +7699,7 @@ export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void
6894
7699
  * validateShape(stringShape({ min: 1 })) // returns; the declaration is compilable
6895
7700
  * ```
6896
7701
  */
6897
- export declare function validateShape(shape: ContractShape): void;
7702
+ export declare function validateShape(shape: unknown): void;
6898
7703
 
6899
7704
  /**
6900
7705
  * Infers a `JSONSchema` for one unknown value — the reverse direction of