@oh-my-pi/omptype 17.2.6 → 17.2.7

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.
@@ -7,21 +7,38 @@
7
7
  * construction stores only the path, the expectation, and the offending value.
8
8
  * All human-readable strings are built lazily on property access.
9
9
  */
10
+ /** Context supplied to configurable error formatters. */
11
+ export interface ErrorContext {
12
+ readonly code: string;
13
+ readonly path: readonly PropertyKey[];
14
+ readonly data: unknown;
15
+ readonly expected: string;
16
+ readonly actual: string;
17
+ readonly problem: string;
18
+ }
19
+ /** Per-schema overrides for validation error text. */
20
+ export interface ErrorConfig {
21
+ readonly expected?: string | ((context: ErrorContext) => string);
22
+ readonly actual?: string | ((context: ErrorContext) => string);
23
+ readonly problem?: string | ((context: ErrorContext) => string);
24
+ readonly message?: string | ((context: ErrorContext) => string);
25
+ }
10
26
  /** A single validation failure at one path. */
11
27
  export declare class OmpError {
28
+ #private;
12
29
  /** Property path from the root to the failing value (empty at root). */
13
30
  readonly path: PropertyKey[];
14
- /** Human-readable expectation, e.g. `"a string"` or `"at most 3600"`. */
15
- readonly expected: string;
16
31
  /** The value that failed validation. */
17
32
  readonly data: unknown;
18
33
  constructor(
19
34
  /** Property path from the root to the failing value (empty at root). */
20
- path: PropertyKey[],
21
- /** Human-readable expectation, e.g. `"a string"` or `"at most 3600"`. */
22
- expected: string,
35
+ path: PropertyKey[], expected: string,
23
36
  /** The value that failed validation. */
24
- data: unknown);
37
+ data: unknown, config?: ErrorConfig);
38
+ /** Stable category for programmatic error handling. */
39
+ get code(): string;
40
+ /** Human-readable expectation, including a configured override. */
41
+ get expected(): string;
25
42
  /** Short description of the received value, e.g. `"a number"` or `"missing"`. */
26
43
  get actual(): string;
27
44
  /** Path-less problem statement: `must be <expected> (was <actual>)`. */
@@ -33,19 +50,37 @@ export declare class OmpError {
33
50
  /** Sentinel for a required key that was absent (distinguishes from `undefined`). */
34
51
  export declare const MISSING: unique symbol;
35
52
  /**
36
- * Aggregate of validation failures; the value returned by a schema call on
37
- * invalid input. Array-like so callers can `.map()` over entries.
53
+ * Single-failure validation result with a lazy array-like entry.
54
+ *
55
+ * Validators fast-fail, so allocating an `Array` subclass and a separate entry
56
+ * on every rejection only penalizes callers that inspect errors by identity.
57
+ * Indexing, iteration, and `map` materialize the entry on demand.
38
58
  */
39
- export declare class OmpErrors extends Array<OmpError> {
40
- static get [Symbol.species](): typeof Array;
41
- /** Single-failure constructor used by generated validators. */
42
- static single(path: PropertyKey[], expected: string, data: unknown): OmpErrors;
43
- /** Prefix every entry's path with `key` (used when nesting sub-schemas). */
59
+ type StoredPath = PropertyKey[] | PropertyKey | undefined;
60
+ export declare class OmpErrors implements Iterable<OmpError> {
61
+ #private;
62
+ /** Number of failures; omptype validators fast-fail on the first error. */
63
+ readonly length = 1;
64
+ constructor(path: StoredPath, expected: string, data: unknown, config?: ErrorConfig);
65
+ /** First and only validation failure, materialized on demand. */
66
+ get 0(): OmpError;
67
+ static single(path: PropertyKey[], expected: string, data: unknown, config?: ErrorConfig): OmpErrors;
68
+ /** Prefix the failure path with `key` when nesting sub-schemas. */
44
69
  prefix(key: PropertyKey): this;
45
- /** Human-readable digest of every failure, one per line. Built lazily. */
70
+ /** Apply schema-local message formatting without rebuilding the failure. */
71
+ configure(config: ErrorConfig): this;
72
+ /** Index the failure by its dotted property path (`""` for the root). */
73
+ get byPath(): Readonly<Record<string, OmpError>>;
74
+ /** Transform the failure entry into a plain array. */
75
+ map<result>(fn: (error: OmpError, index: number, errors: OmpErrors) => result): result[];
76
+ /** Select the failure entry into a plain array. */
77
+ filter(fn: (error: OmpError, index: number, errors: OmpErrors) => unknown): OmpError[];
78
+ /** Iterate over the single failure entry. */
79
+ [Symbol.iterator](): IterableIterator<OmpError>;
80
+ /** Human-readable failure text, materialized only when requested. */
46
81
  get summary(): string;
47
82
  toString(): string;
48
- /** Throw a `TraversalError` carrying the summary. */
83
+ /** Throw a `TraversalError` carrying this result. */
49
84
  throw(): never;
50
85
  }
51
86
  /** Error thrown by `Type.assert` on invalid input. */
@@ -61,3 +96,4 @@ export declare class TraversalError extends Error {
61
96
  export declare class OmpTypeError extends Error {
62
97
  constructor(message: string);
63
98
  }
99
+ export {};
@@ -1,10 +1,9 @@
1
1
  /**
2
2
  * omptype — ArkType-compatible schema validation with a lazy JIT runtime.
3
3
  *
4
- * Drop-in for the arktype surface this repo uses:
5
- * `type()`, `Type`, `type.errors` / `OmpErrors`, `type.enumerated()`,
6
- * `.or/.and/.array/.pipe/.narrow/.describe/.default/.allows/.assert/.toJsonSchema`,
7
- * plus `typeof schema.infer` static inference.
4
+ * ArkType-compatible `type()`/`Type`, keyword modules, recursive scopes,
5
+ * composition and morph APIs, structured errors, input/output inference, and
6
+ * JSON Schema emission.
8
7
  */
9
8
  export * from "./errors.js";
10
9
  export * from "./infer.js";
@@ -1,49 +1,126 @@
1
- /** Type-level output inference for the definition forms accepted by omptype. */
1
+ /** Type-level input and output inference for definitions accepted by omptype. */
2
2
  type Whitespace = " " | "\n" | "\r" | "\t";
3
3
  type TrimLeft<s extends string> = s extends `${Whitespace}${infer rest}` ? TrimLeft<rest> : s;
4
4
  type TrimRight<s extends string> = s extends `${infer rest}${Whitespace}` ? TrimRight<rest> : s;
5
5
  type Trim<s extends string> = TrimLeft<TrimRight<s>>;
6
- type InferPrimitive<s extends string> = s extends "string" | "string.url" ? string : s extends "number" | "number.integer" ? number : s extends "boolean" ? boolean : s extends "null" ? null : s extends "undefined" ? undefined : s extends "unknown" ? unknown : s extends "object" ? object : s extends "bigint" ? bigint : s extends "true" ? true : s extends "false" ? false : never;
7
- type InferMember<member extends string> = Trim<member> extends infer s extends string ? s extends `${infer element}[]` ? InferMember<element>[] : s extends `'${infer literal}'` | `"${infer literal}"` ? literal : s extends `${infer literal extends number}` ? literal : InferPrimitive<s> extends infer primitive ? [primitive] extends [never] ? s extends `${string}string${string}` ? string : s extends `${string}number${string}` ? number : unknown : primitive : unknown : unknown;
8
- /** Split top-level unions without distributing over the accumulated members. */
6
+ /**
7
+ * Flat keyword lookup. An indexed access is one instantiation level, unlike a
8
+ * nested conditional chain — this sits under every string-DSL property, so its
9
+ * depth is multiplied by every layer of object nesting above it.
10
+ * `never` is intentionally absent: the parser rejects it and the fallback in
11
+ * `InferMember` treats a missing entry as "not a primitive".
12
+ */
13
+ interface PrimitiveMap {
14
+ string: string;
15
+ "string.url": string;
16
+ number: number;
17
+ "number.integer": number;
18
+ boolean: boolean;
19
+ null: null;
20
+ undefined: undefined;
21
+ unknown: unknown;
22
+ any: unknown;
23
+ object: object;
24
+ bigint: bigint;
25
+ symbol: symbol;
26
+ Date: Date;
27
+ true: true;
28
+ false: false;
29
+ }
30
+ type Merge<left, right> = left extends object ? right extends object ? Omit<left, keyof right> & right : never : never;
31
+ type InferUtility<s extends string> = s extends `Record<${string},${infer value}>` ? Record<string, InferString<value>> : s extends `Array<${infer element}>` ? InferString<element>[] : s extends `Partial<${infer value}>` ? Partial<InferString<value>> : s extends `Required<${infer value}>` ? Required<InferString<value>> : s extends `Pick<${infer value},${infer keys}>` ? Pick<InferString<value>, Extract<InferString<keys>, keyof InferString<value>>> : s extends `Omit<${infer value},${infer keys}>` ? Omit<InferString<value>, Extract<InferString<keys>, keyof InferString<value>>> : s extends `Merge<${infer left},${infer right}>` ? Merge<InferString<left>, InferString<right>> : never;
32
+ /**
33
+ * Member inference as a flat false-branch chain: TypeScript tail-evaluates
34
+ * chained conditionals in the false position, so this stays at constant
35
+ * instantiation depth where the previous `extends infer` ladder nested every
36
+ * fallback inside a true branch and accumulated depth per step.
37
+ */
38
+ type InferMember<member extends string> = Trim<member> extends infer s extends string ? InferMemberTrimmed<s> : unknown;
39
+ type InferMemberTrimmed<s extends string> = s extends `(${infer inner})` ? InferString<inner> : s extends `${infer element}[]` ? InferMember<element>[] : s extends `'${infer literal}'` | `"${infer literal}"` ? literal : s extends `d'${string}'` | `d"${string}"` ? Date : s extends `\`${string}\`` ? string : s extends `/${string}/${string}` | `/${string}/` ? string : s extends `${infer literal extends number}` ? literal : s extends keyof PrimitiveMap ? PrimitiveMap[s] : InferUtility<s> extends infer utility ? [utility] extends [never] ? InferMemberFallback<s> : utility : unknown;
40
+ type InferMemberFallback<s extends string> = s extends `string.${string}` ? string : s extends `${string}Date${string}` ? Date : s extends `${string}string${string}` ? string : s extends `${string}number${string}` ? number : unknown;
41
+ /** Split unions without distributing over the accumulated members. */
9
42
  type InferUnion<s extends string, result = never> = s extends `${infer head}|${infer tail}` ? InferUnion<tail, result | InferMember<head>> : result | InferMember<s>;
10
43
  type HasInlineDefault<s extends string> = s extends `${string}=${string}` ? s extends `${string}<${string}` | `${string}>${string}` ? false : true : false;
11
44
  type WithoutInlineDefault<s extends string> = HasInlineDefault<s> extends true ? (s extends `${infer base}=${string}` ? Trim<base> : s) : s;
12
- /** String-DSL-only inference; safe inside recursive interfaces (never probes `Type`). */
13
- export type InferString<s extends string> = WithoutInlineDefault<Trim<s>> extends infer trimmed extends string ? trimmed extends `${infer base}?` ? InferString<base> : trimmed extends `(${infer inner})[]` ? InferUnion<inner>[] : InferUnion<trimmed> : unknown;
14
- type HasDefault<def> = def extends string ? HasInlineDefault<def> : def extends {
45
+ type InferStringOutput<s extends string> = s extends "string.numeric.parse" | "string.integer.parse" | "parse.number" | "parse.integer" ? number : s extends "string.date.parse" | "string.date.iso.parse" | "string.date.epoch.parse" | "parse.date" ? Date : s extends "string.url.parse" | "parse.url" ? URL : s extends "string.json.parse" | "parse.json" ? unknown : s extends "parse.boolean" ? boolean : s extends "parse.bigint" ? bigint : InferUnion<s>;
46
+ /** String-DSL output inference. */
47
+ export type InferString<s extends string> = WithoutInlineDefault<Trim<s>> extends infer trimmed extends string ? trimmed extends `${infer base}?` ? InferString<base> : trimmed extends `(${infer inner})[]` ? InferUnion<inner>[] : InferStringOutput<trimmed> : unknown;
48
+ /** String-DSL input inference, preserving the source side of morph keywords. */
49
+ export type InferStringIn<s extends string> = WithoutInlineDefault<Trim<s>> extends infer trimmed extends string ? trimmed extends `${string}.parse` | `parse.${string}` ? string : InferString<trimmed> : unknown;
50
+ type HasDefault<def> = def extends string ? HasInlineDefault<def> : def extends readonly [unknown, "=", unknown] ? true : def extends {
15
51
  readonly hasDefault: true;
16
52
  } ? true : false;
17
- type DefinitionKeys<def extends object> = Exclude<keyof def, "+" | "[string]">;
18
- /** Optional when the key carries a `?` suffix or the string value does (`limit: "number?"`). */
19
- type IsOptionalProp<key, def> = key extends `${string}?` ? true : def extends string ? Trim<def> extends `${string}?` ? true : false : false;
53
+ type DefinitionKeys<def extends object> = Exclude<keyof def, "+" | "[string]" | "...">;
54
+ type IsOptionalProp<key, def> = key extends `${string}?` ? true : def extends string ? Trim<def> extends `${string}?` ? true : false : def extends readonly [unknown, "?"] ? true : false;
20
55
  type PropName<key extends PropertyKey> = key extends `${infer name}?` ? name : key;
21
- type RequiredProperties<def extends object> = {
22
- -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? HasDefault<def[key]> extends true ? PropName<key> : never : PropName<key>]-?: InferDef<def[key]>;
23
- };
24
- type OptionalProperties<def extends object> = {
25
- -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? HasDefault<def[key]> extends true ? never : PropName<key> : never]?: InferDef<def[key]>;
26
- };
56
+ type UnwrapProperty<def> = def extends readonly [infer value, "?" | "=", ...unknown[]] ? value : def;
27
57
  type Simplify<t> = {
28
58
  [key in keyof t]: t[key];
29
59
  };
30
- type PropertiesOf<def extends object> = Simplify<RequiredProperties<def> & OptionalProperties<def>>;
31
- type InferObject<def extends object> = "[string]" extends keyof def ? [DefinitionKeys<def>] extends [never] ? Record<string, InferDef<def["[string]"]>> : PropertiesOf<def> & Record<string, InferDef<def["[string]"]>> : PropertiesOf<def>;
32
- /** Object-literal inference for fluent composition without re-inspecting the containing `Type`. */
60
+ type OutputRequired<def extends object> = {
61
+ -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? HasDefault<def[key]> extends true ? PropName<key> : never : PropName<key>]-?: InferDef<UnwrapProperty<def[key]>>;
62
+ };
63
+ type OutputOptional<def extends object> = {
64
+ -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? HasDefault<def[key]> extends true ? never : PropName<key> : never]?: InferDef<UnwrapProperty<def[key]>>;
65
+ };
66
+ type InputRequired<def extends object> = {
67
+ -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? never : HasDefault<def[key]> extends true ? never : PropName<key>]-?: InferDefIn<UnwrapProperty<def[key]>>;
68
+ };
69
+ type InputOptional<def extends object> = {
70
+ -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? PropName<key> : HasDefault<def[key]> extends true ? PropName<key> : never]?: InferDefIn<UnwrapProperty<def[key]>>;
71
+ };
72
+ /**
73
+ * CYCLE SAFETY: when a fluent generic method is called on a schema whose def
74
+ * embeds other schemas, TypeScript instantiates `InferDef<def>` while `def`
75
+ * is still generic. `"..." extends keyof def` resolves TRUE under permissive
76
+ * instantiation (`keyof any` contains every literal), so spread/index members
77
+ * cannot be deferred by wrapper conditionals — a bare `InferDef<def["..."]>`
78
+ * member re-enters this expansion and instantiates without bound (TS2589).
79
+ * Interface members only instantiate when resolved, so routing the recursive
80
+ * reference through `DefBox` keeps generic instantiation shallow: it stops at
81
+ * a type reference plus an indexed access instead of expanding `InferDef`.
82
+ */
83
+ interface DefBox<def> {
84
+ readonly out: InferDef<def>;
85
+ readonly in: InferDefIn<def>;
86
+ }
87
+ type OutputSpread<def extends object> = "..." extends keyof def ? DefBox<def["..."]>["out"] : unknown;
88
+ type InputSpread<def extends object> = "..." extends keyof def ? DefBox<def["..."]>["in"] : unknown;
89
+ type OutputIndex<def extends object> = "[string]" extends keyof def ? Record<string, DefBox<def["[string]"]>["out"]> : unknown;
90
+ type InputIndex<def extends object> = "[string]" extends keyof def ? Record<string, DefBox<def["[string]"]>["in"]> : unknown;
91
+ type InferObject<def extends object> = "[string]" extends keyof def ? [DefinitionKeys<def>] extends [never] ? Record<string, DefBox<def["[string]"]>["out"]> : Simplify<OutputRequired<def> & OutputOptional<def> & OutputSpread<def>> & OutputIndex<def> : Simplify<OutputRequired<def> & OutputOptional<def> & OutputSpread<def>>;
92
+ type InferObjectIn<def extends object> = "[string]" extends keyof def ? [DefinitionKeys<def>] extends [never] ? Record<string, DefBox<def["[string]"]>["in"]> : Simplify<InputRequired<def> & InputOptional<def> & InputSpread<def>> & InputIndex<def> : Simplify<InputRequired<def> & InputOptional<def> & InputSpread<def>>;
93
+ /** Object-literal inference used by fluent composition overloads. */
33
94
  export type InferObjectDef<def extends object> = InferObject<def>;
34
95
  type InferLiteralDef<def> = def extends string ? InferString<def> : def extends object ? InferObjectLiteral<def> : unknown;
35
- type LiteralRequiredProperties<def extends object> = {
36
- -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? HasDefault<def[key]> extends true ? PropName<key> : never : PropName<key>]-?: InferLiteralDef<def[key]>;
96
+ type LiteralRequired<def extends object> = {
97
+ -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? HasDefault<def[key]> extends true ? PropName<key> : never : PropName<key>]-?: InferLiteralDef<UnwrapProperty<def[key]>>;
37
98
  };
38
- type LiteralOptionalProperties<def extends object> = {
39
- -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? HasDefault<def[key]> extends true ? never : PropName<key> : never]?: InferLiteralDef<def[key]>;
99
+ type LiteralOptional<def extends object> = {
100
+ -readonly [key in DefinitionKeys<def> as IsOptionalProp<key, def[key]> extends true ? HasDefault<def[key]> extends true ? never : PropName<key> : never]?: InferLiteralDef<UnwrapProperty<def[key]>>;
40
101
  };
41
- /** Object-literal-only inference for fluent branches; never inspects embedded schema types. */
42
- export type InferObjectLiteral<def extends object> = Simplify<LiteralRequiredProperties<def> & LiteralOptionalProperties<def>>;
102
+ /** Object-literal-only inference that does not inspect embedded schema internals. */
103
+ export type InferObjectLiteral<def extends object> = Simplify<LiteralRequired<def> & LiteralOptional<def>>;
104
+ type InstanceOf<ctor> = ctor extends abstract new (...args: never[]) => infer instance ? instance : never;
105
+ type SpreadOutput<def> = InferDef<def> extends readonly (infer element)[] ? element[] : never[];
106
+ type SpreadInput<def> = InferDefIn<def> extends readonly (infer element)[] ? element[] : never[];
107
+ type InferTupleOutput<defs extends readonly unknown[], result extends unknown[] = []> = defs extends readonly [] ? result : defs extends readonly ["...", infer spread, ...infer rest] ? [...result, ...SpreadOutput<spread>, ...InferTupleOutput<rest>] : defs extends readonly [infer head, ...infer rest] ? head extends readonly [infer value, "?"] ? InferTupleOutput<rest, [...result, InferDef<value>?]> : head extends readonly [infer value, "=", unknown] ? InferTupleOutput<rest, [...result, InferDef<value>]> : InferTupleOutput<rest, [...result, InferDef<head>]> : result;
108
+ type InferTupleInput<defs extends readonly unknown[], result extends unknown[] = []> = defs extends readonly [] ? result : defs extends readonly ["...", infer spread, ...infer rest] ? [...result, ...SpreadInput<spread>, ...InferTupleInput<rest>] : defs extends readonly [infer head, ...infer rest] ? head extends readonly [infer value, "?" | "=", ...unknown[]] ? InferTupleInput<rest, [...result, InferDefIn<value>?]> : InferTupleInput<rest, [...result, InferDefIn<head>]> : result;
109
+ /**
110
+ * True only for `any` (`1 & any` is `any`; `0 extends any` holds). During
111
+ * relation checking TypeScript instantiates these aliases permissively with
112
+ * every type parameter replaced by `any`, and under `any` the object branch
113
+ * recurses forever (`any["..."]` is `any` again). Cutting `any` off up front
114
+ * makes permissive instantiation terminate immediately, mirroring ArkType's
115
+ * `anyOrNever` guards.
116
+ */
117
+ type IsAny<def> = 0 extends 1 & def ? true : false;
43
118
  /** Infer the validated output type produced by a definition. */
44
- export type InferDef<def = unknown> = def extends {
45
- infer: infer output;
46
- } ? output : def extends string ? InferString<def> : def extends readonly [infer element, "[]"] ? InferDef<element>[] : def extends object ? InferObject<def> : unknown;
47
- /** Input-side defaults and morphs are not distinguished yet. */
48
- export type InferDefIn<def = unknown> = InferDef<def>;
119
+ export type InferDef<def = unknown> = IsAny<def> extends true ? unknown : def extends {
120
+ readonly infer: infer output;
121
+ } ? output : def extends string ? InferString<def> : def extends RegExp ? string : def extends readonly [infer element, "[]"] ? InferDef<element>[] : def extends readonly [infer left, "|", infer right] ? InferDef<left> | InferDef<right> : def extends readonly [infer left, "&", infer right] ? InferDef<left> & InferDef<right> : def extends readonly [unknown, "=>", (...args: never[]) => infer output] ? output : def extends readonly [unknown, "|>", infer output] ? InferDef<output> : def extends readonly [infer base, ":", unknown] | readonly [infer base, "@", unknown] ? InferDef<base> : def extends readonly ["keyof", infer base] ? keyof InferDef<base> : def extends readonly ["instanceof", ...infer constructors] ? InstanceOf<constructors[number]> : def extends readonly ["===", ...infer values] ? values[number] : def extends readonly unknown[] ? InferTupleOutput<def> : def extends object ? InferObject<def> : unknown;
122
+ /** Infer values accepted before defaults and morphs are applied. */
123
+ export type InferDefIn<def = unknown> = IsAny<def> extends true ? unknown : def extends {
124
+ readonly inferIn: infer input;
125
+ } ? input : def extends string ? InferStringIn<def> : def extends RegExp ? string : def extends readonly [infer element, "[]"] ? InferDefIn<element>[] : def extends readonly [infer left, "|", infer right] ? InferDefIn<left> | InferDefIn<right> : def extends readonly [infer left, "&", infer right] ? InferDefIn<left> & InferDefIn<right> : def extends readonly [infer input, "=>", unknown] | readonly [infer input, "|>", unknown] ? InferDefIn<input> : def extends readonly [infer base, ":", unknown] | readonly [infer base, "@", unknown] ? InferDefIn<base> : def extends readonly ["keyof", infer base] ? keyof InferDefIn<base> : def extends readonly ["instanceof", ...infer constructors] ? InstanceOf<constructors[number]> : def extends readonly ["===", ...infer values] ? values[number] : def extends readonly unknown[] ? InferTupleInput<def> : def extends object ? InferObjectIn<def> : unknown;
49
126
  export {};
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Tree-walking validator used for a schema's first few calls (before the JIT
3
- * compiler kicks in) and as the fallback for IR shapes the compiler declines.
2
+ * Tree-walking validator used for a schema's first few calls and as the
3
+ * targeted fallback for recursive or predicate-only JIT subtrees.
4
4
  *
5
5
  * Semantics must stay in lockstep with `compile.ts`:
6
6
  * - success returns the output value; the input is returned as-is unless the
@@ -12,6 +12,8 @@ import { OmpErrors } from "./errors.js";
12
12
  import { type IR } from "./ir.js";
13
13
  /** Validate `value` against `ir`; returns output value or `OmpErrors`. */
14
14
  export declare function walk(ir: IR, value: unknown): unknown;
15
+ /** True when a union failure can be replaced with a more specific nested error. */
16
+ export declare function canRefineUnionFailure(member: IR): boolean;
15
17
  /**
16
18
  * Detailed failure for a union: descend into the member the value was clearly
17
19
  * aimed at — unique runtime-kind match, else an object member whose literal
@@ -21,4 +23,4 @@ export declare function walk(ir: IR, value: unknown): unknown;
21
23
  */
22
24
  export declare function unionFail(ir: IR & {
23
25
  k: "union";
24
- }, v: unknown, path: PropertyKey[]): OmpErrors;
26
+ }, v: unknown, path: PropertyKey[], expected?: string): OmpErrors;
@@ -9,8 +9,13 @@
9
9
  * consumed by the interpreter (`interp.ts`), the JIT compiler (`compile.ts`),
10
10
  * and the JSON Schema emitter (`json-schema.ts`).
11
11
  */
12
+ import { OmpErrors } from "./errors.js";
12
13
  /** Brand carried by `Type` instances so the parser can embed them in defs. */
13
14
  export declare const IR_BRAND: unique symbol;
15
+ declare const kMorph: unique symbol;
16
+ interface IRAnalysis {
17
+ [kMorph]?: boolean;
18
+ }
14
19
  /**
15
20
  * The parser-facing surface of an embedded `Type` instance.
16
21
  * `type.ts` implements this on every schema it creates.
@@ -31,7 +36,32 @@ export interface EmbeddableSchema {
31
36
  }
32
37
  /** Policy for undeclared object keys. */
33
38
  export type Extras = "keep" | "reject" | "delete";
34
- export type IR = {
39
+ /** Constructor accepted by `type.instanceOf` and tuple `instanceof` expressions. */
40
+ export type Constructor = abstract new (...args: never[]) => object;
41
+ /** Context available to in-definition morph callbacks. */
42
+ export interface MorphContext {
43
+ /** Return a validation error at the current path. */
44
+ error(expectation: string): OmpErrors;
45
+ /** Alias of `error` matching ArkType's rejection vocabulary. */
46
+ reject(expectation: string): OmpErrors;
47
+ }
48
+ /** One fixed tuple position, optionally absent or defaulted. */
49
+ export interface TupleItemIR {
50
+ val: IR;
51
+ opt: boolean;
52
+ def?: unknown;
53
+ defFactory?: boolean;
54
+ hasDefault?: boolean;
55
+ }
56
+ /** Fixed, optional, variadic, and postfix tuple sequence. */
57
+ export interface TupleIR {
58
+ k: "tuple";
59
+ prefix: TupleItemIR[];
60
+ variadic?: IR;
61
+ postfix: IR[];
62
+ desc?: string;
63
+ }
64
+ export type IR = IRAnalysis & ({
35
65
  k: "unknown";
36
66
  desc?: string;
37
67
  } | {
@@ -46,6 +76,12 @@ export type IR = {
46
76
  } | {
47
77
  k: "bigint";
48
78
  desc?: string;
79
+ } | {
80
+ k: "symbol";
81
+ desc?: string;
82
+ } | {
83
+ k: "never";
84
+ desc?: string;
49
85
  }
50
86
  /** Any non-null object (the bare `object` keyword). */
51
87
  | {
@@ -64,6 +100,7 @@ export type IR = {
64
100
  xmin?: boolean;
65
101
  xmax?: boolean;
66
102
  int?: boolean;
103
+ divisor?: number;
67
104
  desc?: string;
68
105
  } | {
69
106
  k: "lit";
@@ -73,25 +110,52 @@ export type IR = {
73
110
  k: "union";
74
111
  members: IR[];
75
112
  desc?: string;
113
+ } | {
114
+ k: "intersection";
115
+ members: IR[];
116
+ desc?: string;
76
117
  } | {
77
118
  k: "array";
78
119
  el: IR;
79
120
  min?: number;
80
121
  max?: number;
81
122
  desc?: string;
82
- } | {
123
+ } | TupleIR | {
83
124
  k: "object";
84
125
  props: PropIR[];
85
126
  index?: IR;
86
127
  extras: Extras;
87
128
  desc?: string;
129
+ } | {
130
+ k: "refine";
131
+ base: IR;
132
+ pred: (value: unknown) => boolean;
133
+ expected: string;
134
+ json?: Record<string, unknown>;
135
+ desc?: string;
136
+ } | {
137
+ k: "morph";
138
+ input: IR;
139
+ fn: (value: unknown, context: MorphContext) => unknown;
140
+ out?: IR;
141
+ desc?: string;
142
+ } | {
143
+ k: "instance";
144
+ ctor: Constructor;
145
+ expected: string;
146
+ desc?: string;
147
+ } | {
148
+ k: "alias";
149
+ name: string;
150
+ resolve: () => IR;
151
+ desc?: string;
88
152
  }
89
153
  /** Embedded schema with runtime steps; validated by calling `run`. */
90
154
  | {
91
155
  k: "sub";
92
156
  schema: EmbeddableSchema;
93
157
  desc?: string;
94
- };
158
+ });
95
159
  export interface PropIR {
96
160
  key: string;
97
161
  opt: boolean;
@@ -102,14 +166,19 @@ export interface PropIR {
102
166
  hasDefault?: boolean;
103
167
  }
104
168
  /** Definition input accepted by `type()` and object property values. */
105
- export type Def = string | EmbeddableSchema | readonly Def[] | {
106
- readonly [k: string]: Def;
169
+ export type Def = string | RegExp | Date | EmbeddableSchema | readonly unknown[] | {
170
+ readonly [k: string]: unknown;
107
171
  };
172
+ /** Resolve a named scope alias to its lazy IR reference. */
173
+ export type AliasResolver = (name: string) => IR | undefined;
108
174
  /** Embed a schema value: inline pure structure, keep `sub` nodes for stepped schemas. */
109
175
  export declare function embed(schema: EmbeddableSchema): IR;
110
- /** Parse a definition (string DSL, object literal, tuple, or embedded schema) into IR. */
111
- export declare function parseDef(def: Def): IR;
176
+ /** Build the runtime schema for an object's or tuple's keys. */
177
+ export declare function keyOf(node: IR): IR;
178
+ /** Parse a definition, optionally resolving names from an enclosing scope. */
179
+ export declare function parseDef(def: unknown, resolve?: AliasResolver): IR;
112
180
  /** True when validating `ir` can produce an output different from its input. */
113
181
  export declare function hasMorph(ir: IR): boolean;
114
182
  /** Human-readable expectation for error messages, e.g. `"a string"`. */
115
183
  export declare function expectedOf(ir: IR): string;
184
+ export {};
@@ -1,8 +1,13 @@
1
1
  import type { IR } from "./ir.js";
2
2
  export interface JsonSchemaOptions {
3
3
  description?: string;
4
+ target?: string;
5
+ dialect?: string;
6
+ fallback?: (context: {
7
+ base: Record<string, unknown>;
8
+ }) => unknown;
4
9
  }
5
10
  type JsonSchema = Record<string, unknown>;
6
- /** Emit the draft-2020-12 JSON Schema represented by an IR tree. */
11
+ /** Emit the requested JSON Schema dialect represented by an IR tree. */
7
12
  export declare function irToJsonSchema(ir: IR, options?: JsonSchemaOptions): JsonSchema;
8
13
  export {};
@@ -0,0 +1,7 @@
1
+ import type { IR } from "./ir.js";
2
+ /** Lower a built-in keyword into fresh validation IR. */
3
+ export declare function keywordIR(name: string): IR | undefined;
4
+ /** Lower a regular expression into a string refinement. */
5
+ export declare function patternIR(regex: RegExp): IR;
6
+ /** Lower an ArkType-style template literal into a string pattern. */
7
+ export declare function templateIR(source: string): IR;