🚀. Socket Launch Week Day 3:Socket Firewall Now Blocks Malicious VS Code and Open VSX Extensions.Learn more
Sign In

arktype

Package Overview
Dependencies
Maintainers
1
Versions
151
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

arktype - npm Package Compare versions

Comparing version
2.1.22
to
2.1.23
+30
out/declare.d.ts
import type { anyOrNever, array, defined, equals, ErrorMessage, ErrorType, optionalKeyOf, requiredKeyOf, show, unset } from "@ark/util";
import type { distill } from "./attributes.ts";
import type { type } from "./keywords/keywords.ts";
import type { inferDefinition, ThunkCast } from "./parser/definition.ts";
import type { TupleExpression } from "./parser/tupleExpressions.ts";
import type { bindThis } from "./scope.ts";
import type { Type } from "./type.ts";
export type DeclarationParser<$> = <preinferred = unset, ctx extends DeclareContext = {}>() => {
type: <const def>(def: [preinferred] extends [unset] ? [
preinferred
] extends [anyOrNever] ? validateDeclared<preinferred, def, $, ctx> : ErrorMessage<`declare<ExternalType>() requires a generic argument`> : validateDeclared<preinferred, def, $, ctx>) => Type<finalizePreinferred<preinferred, def, $, ctx>, $>;
};
type finalizePreinferred<preinferred, def, $, ctx extends DeclareContext> = ctx["side"] extends distill.Side ? ctx["side"] extends "in" ? (In: preinferred) => type.infer.Out<def, $> : (In: type.infer.In<def, $>) => preinferred : preinferred;
export type DeclareContext = {
side?: "in" | "out";
};
export type validateDeclared<declared, def, $, ctx extends DeclareContext> = def extends type.validate<def, $> ? validateInference<def, declared, $, bindThis<def>, ctx> : type.validate<def, $>;
type validateInference<def, declared, $, args, ctx extends DeclareContext> = def extends RegExp | type.cast<unknown> | ThunkCast | TupleExpression ? validateShallowInference<inferDefinition<def, $, args>, declared, ctx> : def extends array ? declared extends array ? {
[i in keyof declared]: i extends keyof def ? validateInference<def[i], declared[i], $, args, ctx> : declared[i];
} : show<declarationMismatch<inferDefinition<def, $, args>, declared>> : def extends object ? show<{
[k in requiredKeyOf<declared>]: k extends keyof def ? validateInference<def[k], declared[k], $, args, ctx> : declared[k];
} & {
[k in optionalKeyOf<declared> & string as `${k}?`]: `${k}?` extends (keyof def) ? validateInference<def[`${k}?`], defined<declared[k]>, $, args, ctx> : declared[k];
}> : validateShallowInference<inferDefinition<def, $, args>, declared, ctx>;
type validateShallowInference<t, declared, ctx extends DeclareContext, inferred = ctx["side"] extends distill.Side ? distill<t, ctx["side"]> : t> = equals<inferred, declared> extends true ? unknown : show<declarationMismatch<inferred, declared>>;
type declarationMismatch<inferred, declared> = ErrorType<{
declared: declared;
inferred: inferred;
}>;
export {};
export {};
import type { BaseRoot, IntersectionNode } from "@ark/schema";
import { Callable, type applyElementLabels, type conform, type Fn, type get } from "@ark/util";
import type { distill } from "./attributes.ts";
import type { type } from "./keywords/keywords.ts";
import type { validateInnerDefinition } from "./parser/definition.ts";
import type { inferTupleLiteral, validateTupleLiteral } from "./parser/tupleLiteral.ts";
import type { InternalScope, Scope } from "./scope.ts";
import type { Type } from "./type.ts";
export interface FnParser<$ = {}> {
<const args extends readonly unknown[], paramsT extends readonly unknown[] = inferTupleLiteral<args extends readonly [...infer params, ":", unknown] ? params : args, $, {}>, returnT = args extends readonly [...unknown[], ":", infer returnDef] ? type.infer<returnDef, $> : unknown>(...args: {
[i in keyof args]: conform<args[i], get<validateFnArgs<args, $>, i>>;
}): <internalSignature extends (...args: distill.Out<paramsT>) => distill.In<returnT>, externalSignature extends Fn = (...args: applyElementLabels<distill.In<paramsT>, Parameters<internalSignature>>) => args extends readonly [...unknown[], ":", unknown] ? distill.Out<returnT> : ReturnType<internalSignature>>(implementation: internalSignature) => TypedFn<externalSignature, $, args extends readonly [...unknown[], ":", unknown] ? Return.introspectable : {}>;
/**
* The {@link Scope} in which definitions passed to this function will be parsed.
*/
$: Scope<$>;
/**
* An alias of `fn` with no type-level validation or inference.
*
* Useful when wrapping `fn` or using it to parse a dynamic definition.
*/
raw: RawFnParser;
}
export type RawFnParser = (...args: unknown[]) => (...args: unknown[]) => unknown;
export declare class InternalFnParser extends Callable<(...args: unknown[]) => Fn> {
constructor($: InternalScope);
}
export declare namespace TypedFn {
type meta = {
introspectableReturn?: true;
};
}
export interface TypedFn<signature extends Fn = Fn, $ = {}, meta extends TypedFn.meta = {}> extends Callable<signature> {
expression: string;
params: signature extends Fn<infer params> ? Type<params, $> : never;
returns: Type<meta extends Return.introspectable ? ReturnType<signature> : unknown, $>;
}
export declare class InternalTypedFn extends Callable<(...args: unknown[]) => unknown> {
raw: Fn;
params: IntersectionNode;
returns: BaseRoot;
expression: string;
constructor(raw: Fn, params: IntersectionNode, returns: BaseRoot);
}
export declare namespace Return {
interface introspectable {
introspectableReturn: true;
}
}
type validateFnArgs<args, $> = args extends readonly unknown[] ? args extends readonly [...infer paramDefs, ":", infer returnDef] ? readonly [
...validateFnParamDefs<paramDefs, $>,
":",
type.validate<returnDef, $>
] : validateFnParamDefs<args, $> : never;
type validateFnParamDefs<paramDefs extends readonly unknown[], $> = paramDefs extends validateTupleLiteral<paramDefs, $, {}> ? paramDefs : paramDefs extends {
[i in keyof paramDefs]: paramDefs[i] extends "..." ? paramDefs[i] : validateInnerDefinition<paramDefs[i], $, {}>;
} ? validateTupleLiteral<paramDefs, $, {}> : {
[i in keyof paramDefs]: validateInnerDefinition<paramDefs[i], $, {}>;
};
export declare const badFnReturnTypeMessage = "\":\" must be followed by exactly one return type e.g:\nfn(\"string\", \":\", \"number\")(s => s.length)";
export {};
import { Callable, throwParseError } from "@ark/util";
export class InternalFnParser extends Callable {
constructor($) {
const attach = {
$: $,
raw: $.fn
};
super((...signature) => {
const returnOperatorIndex = signature.indexOf(":");
const lastParamIndex = returnOperatorIndex === -1 ?
signature.length - 1
: returnOperatorIndex - 1;
const paramDefs = signature.slice(0, lastParamIndex + 1);
const paramTuple = $.parse(paramDefs).assertHasKind("intersection");
let returnType = $.intrinsic.unknown;
if (returnOperatorIndex !== -1) {
if (returnOperatorIndex !== signature.length - 2)
return throwParseError(badFnReturnTypeMessage);
returnType = $.parse(signature[returnOperatorIndex + 1]);
}
return (impl) => new InternalTypedFn(impl, paramTuple, returnType);
}, { attach });
}
}
export class InternalTypedFn extends Callable {
raw;
params;
returns;
expression;
constructor(raw, params, returns) {
const typedName = `typed ${raw.name}`;
const typed = {
// assign to a key with the expected name to force it to be created that way
[typedName]: (...args) => {
const validatedArgs = params.assert(args);
const returned = raw(...validatedArgs);
return returns.assert(returned);
}
}[typedName];
super(typed);
this.raw = raw;
this.params = params;
this.returns = returns;
let argsExpression = params.expression;
if (argsExpression[0] === "[" && argsExpression.at(-1) === "]")
argsExpression = argsExpression.slice(1, -1);
else if (argsExpression.endsWith("[]"))
argsExpression = `...${argsExpression}`;
this.expression = `(${argsExpression}) => ${returns?.expression ?? "unknown"}`;
}
}
export const badFnReturnTypeMessage = `":" must be followed by exactly one return type e.g:
fn("string", ":", "number")(s => s.length)`;
import { type Scanner } from "@ark/util";
import type { Comparator } from "../reduce/shared.ts";
export declare const terminatingChars: {
readonly " ": 1;
readonly "\n": 1;
readonly "\t": 1;
readonly "<": 1;
readonly ">": 1;
readonly "=": 1;
readonly "|": 1;
readonly "&": 1;
readonly ")": 1;
readonly "[": 1;
readonly "%": 1;
readonly ",": 1;
readonly ":": 1;
readonly "?": 1;
readonly "#": 1;
};
export type TerminatingChar = keyof typeof terminatingChars;
export declare const finalizingLookaheads: {
readonly ">": 1;
readonly ",": 1;
readonly "": 1;
readonly "=": 1;
readonly "?": 1;
};
export type FinalizingLookahead = keyof typeof finalizingLookaheads;
export declare const lookaheadIsFinalizing: (lookahead: string, unscanned: string) => lookahead is ">" | "," | "=" | "?";
export type lookaheadIsFinalizing<lookahead extends string, unscanned extends string> = lookahead extends ">" ? unscanned extends `=${infer nextUnscanned}` ? nextUnscanned extends `=${string}` ? true : false : Scanner.skipWhitespace<unscanned> extends ("" | `${TerminatingChar}${string}`) ? true : false : lookahead extends "=" ? unscanned extends `=${string}` ? false : true : lookahead extends "," | "?" ? true : false;
export type InfixToken = Comparator | "|" | "&" | "%" | ":" | "=>" | "|>" | "#" | "@" | "=";
export type PostfixToken = "[]" | "?";
export type OperatorToken = InfixToken | PostfixToken;
import { isKeyOf, whitespaceChars } from "@ark/util";
export const terminatingChars = {
"<": 1,
">": 1,
"=": 1,
"|": 1,
"&": 1,
")": 1,
"[": 1,
"%": 1,
",": 1,
":": 1,
"?": 1,
"#": 1,
...whitespaceChars
};
export const finalizingLookaheads = {
">": 1,
",": 1,
"": 1,
"=": 1,
"?": 1
};
export const lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">" ?
unscanned[0] === "=" ?
// >== would only occur in an expression like Array<number>==5
// otherwise, >= would only occur as part of a bound like number>=5
unscanned[1] === "="
// if > is the end of a generic instantiation, the next token will be
// an operator or the end of the string
: unscanned.trimStart() === "" ||
isKeyOf(unscanned.trimStart()[0], terminatingChars)
// "=" is a finalizer on its own (representing a default value),
// but not with a second "=" (an equality comparator)
: lookahead === "=" ? unscanned[0] !== "="
// "," and "?" are unambiguously finalizers
: lookahead === "," || lookahead === "?";
import type { ExactLength, ExclusiveNumericRangeSchema, InclusiveNumericRangeSchema } from "@ark/schema";
import type { ObjectType } from "./object.ts";
interface Type<
/** @ts-ignore cast variance */
out t extends readonly unknown[] = readonly unknown[], $ = {}> extends ObjectType<t, $> {
atLeastLength(schema: InclusiveNumericRangeSchema): this;
atMostLength(schema: InclusiveNumericRangeSchema): this;
moreThanLength(schema: ExclusiveNumericRangeSchema): this;
lessThanLength(schema: ExclusiveNumericRangeSchema): this;
exactlyLength(schema: ExactLength.Schema): this;
}
export type { Type as ArrayType };
import type { BaseNode, BaseRoot, Disjoint, JsonSchema, NodeSelector, Predicate, StandardSchemaV1, ToJsonSchema, TypeMeta, UndeclaredKeyBehavior } from "@ark/schema";
import type { anyOrNever, array, Callable, ErrorMessage, inferred, JsonStructure, unset } from "@ark/util";
import type { defaultFor, distill, inferIntersection, inferPipe, InferredMorph, Out, To } from "../attributes.ts";
import type { ArkAmbient } from "../config.ts";
import type { type } from "../keywords/keywords.ts";
import type { NaryPipeParser } from "../nary.ts";
import type { Scope } from "../scope.ts";
import type { ArrayType } from "./array.ts";
import type { instantiateType } from "./instantiate.ts";
/** @ts-ignore cast variance */
export interface Inferred<out t = unknown, $ = {}> {
internal: BaseRoot;
[inferred]: t;
/**
* precompiled JS used to optimize validation
*
* ⚠️ will be `undefined` in [jitless](https://arktype.io/docs/configuration#jitless) mode
*/
precompilation: string | undefined;
/**
* generic parameter representing this Type
*
* 🥸 inference-only property that will be `undefined` at runtime
*
* ⚠️ May contain types representing morphs or default values that would
* be inaccurate if used directly for runtime values. In those cases,
* you should use {@link infer} or {@link inferIn} on this object instead.
*/
t: t;
/**
* #### {@link Scope} in which chained methods are parsed
*/
$: Scope<$>;
/**
* #### type of output this returns
*
* 🥸 inference-only property that will be `undefined` at runtime
*
* @example
* const parseNumber = type("string").pipe(s => Number.parseInt(s))
* type ParsedNumber = typeof parseNumber.infer // number
*/
infer: this["inferOut"];
/**
* type of output this returns
*
* 🔗 alias of {@link infer}
* 🥸 inference-only property that will be `undefined` at runtime
*
*
* @example
* const parseNumber = type("string").pipe(s => Number.parseInt(s))
* type ParsedNumber = typeof parseNumber.infer // number
*/
inferOut: distill.Out<t>;
/**
* type of output that can be introspected at runtime (e.g. via {@link out})
*
* ⚠️ If your Type contains morphs, they will be inferred as `unknown` unless
* they are an ArkType keyword or have an explicitly defined output validator.
*
* 🥸 inference-only property that will be `undefined` at runtime
*
* @example
* const Unmorphed = type("string")
* // with no morphs, we can introspect the input and output as a single Type
* type UnmorphedOut = typeof Unmorphed.inferIntrospectableOut // string
*
* const Morphed = type("string").pipe(s => s.length)
* // with a standard user-defined morph, TypeScript can infer a
* // return type from your function, but we have no way to
* // know the shape at runtime
* type MorphOut = typeof Morphed.inferIntrospectableOut // unknown
*
* const Validated = type("string").pipe(s => s.length).to("number")
* // morphs with validated output, including all morph keywords, are introspectable
* type ValidatedMorphOut = typeof Validated.inferIntrospectableOut
*/
inferIntrospectableOut: distill.introspectable.Out<t>;
/**
* #### type of input this allows
*
* 🥸 inference-only property that will be `undefined` at runtime
*
* @example
* const parseNumber = type("string").pipe(s => Number.parseInt(s))
* type UnparsedNumber = typeof parseNumber.inferIn // string
*/
inferIn: distill.In<t>;
/**
* #### internal JSON representation
*/
json: JsonStructure;
/**
* alias of {@link json} for `JSON.stringify` compatibility
*/
toJSON(): JsonStructure;
/**
* #### generate a JSON Schema
*
* @throws {ToJsonSchema.Error} if this cannot be converted to JSON Schema
*/
toJsonSchema(options?: ToJsonSchema.Options): JsonSchema;
/**
* #### metadata like custom descriptions and error messages
*
* ✅ type {@link https://arktype.io/docs/configuration#custom | can be customized} for your project
*/
meta: ArkAmbient.meta;
/**
* #### human-readable English description
*
* ✅ works best for primitive values
*
* @example
* const N = type("0 < number <= 100")
* console.log(N.description) // positive and at most 100
*/
description: string;
/**
* #### syntax string similar to native TypeScript
*
* ✅ works well for both primitives and structures
*
* @example
* const Loc = type({ coords: ["number", "number"] })
* console.log(Loc.expression) // { coords: [number, number] }
*/
expression: string;
/**
* #### validate and return transformed data or throw
*
* ✅ sugar to avoid checking for {@link type.errors} if they are unrecoverable
*
* @example
* const CriticalPayload = type({
* superImportantValue: "string"
* })
* // throws TraversalError: superImportantValue must be a string (was missing)
* const data = CriticalPayload.assert({ irrelevantValue: "whoops" })
* console.log(data.superImportantValue) // valid output can be accessed directly
*
* @throws {TraversalError}
*/
assert(data: unknown): this["infer"];
/**
* #### check input without applying morphs
*
* ✅ good for stuff like filtering that doesn't benefit from detailed errors
*
* @example
* const Numeric = type("number | bigint")
* // [0, 2n]
* const numerics = [0, "one", 2n].filter(Numeric.allows)
*/
allows(data: unknown): data is this["inferIn"];
/**
* #### add metadata to shallow references
*
* ⚠️ does not affect error messages within properties of an object
*
* @example
* const NotOdd = type("number % 2").configure({ description: "not odd" })
* // all constraints at the root are affected
* const odd = NotOdd(3) // must be not odd (was 3)
* const nonNumber = NotOdd("two") // must be not odd (was "two")
*
* const NotOddBox = type({
* // we should have referenced notOdd or added meta here
* notOdd: "number % 2",
* // but instead chained from the root object
* }).configure({ description: "not odd" })
* // error message at path notOdd is not affected
* const oddProp = NotOddBox({ notOdd: 3 }) // notOdd must be even (was 3)
* // error message at root is affected, leading to a misleading description
* const nonObject = NotOddBox(null) // must be not odd (was null)
*/
configure: NodeSelector.SelectableFn<TypeMeta.MappableInput, this>;
/**
* #### add description to shallow references
*
* 🔗 equivalent to `.configure({ description })` (see {@link configure})
* ⚠️ does not affect error messages within properties of an object
*
* @example
* const AToZ = type(/^a.*z$/).describe("a string like 'a...z'")
* const good = AToZ("alcatraz") // "alcatraz"
* // ArkErrors: must be a string like 'a...z' (was "albatross")
* const badPattern = AToZ("albatross")
*/
describe: NodeSelector.SelectableFn<string, this>;
/**
* #### apply undeclared key behavior
*
* - `"ignore"` (default) - allow and preserve extra properties
* - `"reject"` - disallow extra properties
* - `"delete"` - clone and remove extra properties from output
*/
onUndeclaredKey(behavior: UndeclaredKeyBehavior): this;
/**
* #### deeply apply undeclared key behavior
*
* - `"ignore"` (default) - allow and preserve extra properties
* - `"reject"` - disallow extra properties
* - `"delete"` - clone and remove extra properties from output
*/
onDeepUndeclaredKey(behavior: UndeclaredKeyBehavior): this;
/**
* #### alias for {@link assert} with typed input
*
* @example
* const T = type({ foo: "string" });
* // TypeScript: foo must be a string (was 5)
* const data = T.from({ foo: 5 });
*/
from(literal: this["inferIn"]): this["infer"];
/**
* #### deeply extract inputs
*
* ✅ will never include morphs
* ✅ good for generating JSON Schema or other non-transforming formats
*
* @example
* const User = type({
* age: "string.numeric.parse"
* })
* // { age: 25 } (age parsed to a number)
* const out = User({ age: "25" })
* // { age: "25" } (age is still a string)
* const inOut = User.in({ age: "25" })
*/
get in(): instantiateType<this["inferIn"], $>;
/**
* #### deeply extract outputs
*
* ✅ will never include morphs
* ⚠️ if your type includes morphs, their output will likely be unknown unless they
* were defined with an explicit output validator via `.to(outputDef)` or `.pipe(morph, outputType)`
*
* @example
* const join = type("string[]").pipe(a => a.join(","))
*
* const T = type({
* // all keywords have introspectable output
* keyword: "string.numeric.parse",
* // TypeScript knows this returns a string, but we can't introspect that at runtime
* unvalidated: join,
* // if needed, it can be made introspectable with an output validator
* validated: join.to("string")
* })
*
* // Type<{ keyword: number; unvalidated: unknown; validated: string }>
* const baseOut = base.out
*/
get out(): instantiateType<this["inferIntrospectableOut"], $>;
/**
* #### add a compile-time brand to output
*
* 🥸 inference-only function that does nothing runtime
*
* @example
* const Palindrome = type("string")
* .narrow(s => s === [...s].reverse().join(""))
* .brand("palindrome")
* // Brand<string, "palindrome">
* const out = Palindrome.assert("racecar")
*/
brand<const name extends string, r = instantiateType<type.brand<t, name>, $>>(name: name): r extends infer _ ? _ : never;
/**
* #### an array of this
*
* @example
* // Type<{ rebmun: number }[]>
* const T = type({ rebmun: "number" }).array();
*/
array(): ArrayType<t[], $>;
/**
* #### {@link https://arktype.io/docs/objects#properties-optional | optional definition}
*
* ⚠️ unlike most other methods, this creates a definition rather than a Type (read why)
*
* @example
* const Prop = type({ foo: "number" })
* // Type<{ bar?: { foo: number } }>
* const Obj = type({ bar: Prop.optional() })
*/
optional(): [this, "?"];
/**
* #### {@link https://arktype.io/docs/objects#properties-defaultable | defaultable definition}
*
* ✅ object defaults can be returned from a function
* ⚠️ throws if the default value is not allowed
* ⚠️ unlike most other methods, this creates a definition rather than a Type (read why)
*
* @example
* // Type<{ count: Default<number, 0> }>
* const State = type({ count: type.number.default(0) })
* const Prop = type({ nested: "boolean" })
* const ForObj = type({
* key: Prop.default(() => ({ nested: false }))
* })
*/
default<const value extends defaultFor<this["inferIn"]>>(value: value): [this, "=", value];
/**
* #### apply a predicate function to input
*
* ⚠️ the behavior of {@link narrow}, this method's output counterpart, is usually more desirable
* ✅ most useful for morphs with input types that are re-used externally
* 🥸 {@link https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates | Type predicates} can be used as casts
*
* @example
* const stringifyUser = type({ name: "string" }).pipe(user => JSON.stringify(user))
* const stringifySafe = stringifyUser.filter(user => user.name !== "Bobby Tables")
* // Type<(In: `${string}Z`) => To<Date>>
* const WithPredicate = type("string.date.parse").filter((s): s is `${string}Z` =>
* s.endsWith("Z")
* )
*/
filter<narrowed extends this["inferIn"] = never, r = instantiateType<[
narrowed
] extends [never] ? t : t extends InferredMorph<never, infer o> ? (In: narrowed) => o : narrowed, $>>(predicate: Predicate.Castable<this["inferIn"], narrowed>): r extends infer _ ? _ : never;
/**
* #### apply a predicate function to output
*
* ✅ go-to fallback for validation not composable via built-in types and operators
* ✅ runs after all other validators and morphs, if present
* 🥸 {@link https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates | Type predicates} can be used as casts
*
* @example
* const Palindrome = type("string").narrow(s => s === [...s].reverse().join(""))
*
* const PalindromicEmail = type("string.date.parse").narrow((date, ctx) =>
* date.getFullYear() === 2025 || ctx.mustBe("the current year")
* )
* // Type<`${string}.tsx`>
* const WithPredicate = type("string").narrow((s): s is `${string}.tsx` => /\.tsx?$/.test(s))
*/
narrow<narrowed extends this["infer"] = never, r = instantiateType<[
narrowed
] extends [never] ? t : t extends InferredMorph<infer i, infer o> ? o extends To ? (In: i) => To<narrowed> : (In: i) => Out<narrowed> : narrowed, $>>(predicate: Predicate.Castable<this["infer"], narrowed>): r extends infer _ ? _ : never;
/**
* #### pipe output through arbitrary transformations or other Types
*
* @example
* const User = type({ name: "string" })
*
* // parse a string and validate that the result as a user
* const parseUser = type("string").pipe(s => JSON.parse(s), user)
*/
pipe: ChainedPipeParser<$, t>;
/**
* #### parse a definition as an output validator
*
* 🔗 `to({ name: "string" })` is equivalent to `.pipe(type({ name: "string" }))`
*
* @example
* // parse a string and validate that the result as a user
* const parseUser = type("string").pipe(s => JSON.parse(s)).to({ name: "string" })
*/
to<const def, r = instantiateType<inferPipe<t, type.infer<def, $>>, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
/**
* #### query internal node references
*
* @experimental filters and returns the Type's internal representation from `@ark/schema`
*
* @example
* // ["blue", "red"]
* const values = type("'red' | 'blue'").select("unit").map(u => u.unit)
*/
select: BaseNode["select"];
}
/** @ts-ignore cast variance */
interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => distill.Out<t> | ArkEnv.onFail>, Inferred<t, $> {
/**
* #### cast the way this is inferred
*
* 🥸 inference-only function that does nothing runtime
*
* @example
* // Type<`LEEEEEEEE${string}ROY`>
* const Leeroy = type(/^LE{8,}ROY$/).as<`LEEEEEEEE${string}ROY`>()
*/
as<castTo = unset>(...args: validateChainedAsArgs<castTo>): instantiateType<castTo, $>;
/**
* #### intersect the parsed Type, throwing if the result is unsatisfiable
*
* @example
* // Type<{ foo: number; bar: string }>
* const T = type({ foo: "number" }).and({ bar: "string" })
* // ParseError: Intersection at foo of number and string results in an unsatisfiable type
* const Bad = type({ foo: "number" }).and({ foo: "string" })
*/
and<const def, r = instantiateType<inferIntersection<t, type.infer<def, $>>, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
/**
* #### union with the parsed Type
*
* ⚠️ a union that could apply different morphs to the same data is a ParseError ({@link https://arktype.io/docs/expressions#union-morphs | docs})
*
* @example
* // Type<string | { box: string }>
* const T = type("string").or({ box: "string" })
*/
or<const def, r = instantiateType<t | type.infer<def, $>, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
/**
* #### intersect the parsed Type, returning an introspectable {@link Disjoint} if the result is unsatisfiable
*
* @example
* // Type<{ foo: number; bar: string }>
* const T = type({ foo: "number" }).intersect({ bar: "string" })
* const Bad = type("number > 10").intersect("number < 5")
* // logs "Intersection of > 10 and < 5 results in an unsatisfiable type"
* if (Bad instanceof Disjoint) console.log(`${bad.summary}`)
*/
intersect<const def, r = instantiateType<inferIntersection<t, type.infer<def, $>>, $>>(def: type.validate<def, $>): r extends infer _ ? _ | Disjoint : never;
/**
* #### check if the parsed Type's constraints are identical
*
* ✅ equal types have identical input and output constraints and transforms
* ✅ ignores associated {@link meta}, which does not affect the set of allowed values
*
* @example
* const DivisibleBy6 = type.number.divisibleBy(6).moreThan(0)
* // false (left side must also be positive)
* DivisibleBy6.equals("number % 6")
* // false (right side has an additional <100 constraint)
* console.log(DivisibleBy6.equals("0 < (number % 6) < 100"))
* const ThirdTry = type("(number % 2) > 0").divisibleBy(3)
* // true (types are normalized and reduced)
* console.log(DivisibleBy6.equals(ThirdTry))
*/
equals<const def>(def: type.validate<def, $>): boolean;
/**
* #### narrow this based on an {@link equals} check
*
* ✅ ignores associated {@link meta}, which does not affect the set of allowed values
*
* @example
* const N = type.raw(`${Math.random()}`)
* // Type<0.5> | undefined
* const Ez = N.ifEquals("0.5")
*/
ifEquals<const def, r = type.instantiate<def, $>>(def: type.validate<def, $>): r extends infer _ ? _ | undefined : never;
/**
* #### check if this is a subtype of the parsed Type
*
* ✅ a subtype must include all constraints from the base type
* ✅ unlike {@link equals}, additional constraints may be present
* ✅ ignores associated {@link meta}, which does not affect the set of allowed values
*
* @example
* type.string.extends("unknown") // true
* type.string.extends(/^a.*z$/) // false
*/
extends<const def>(other: type.validate<def, $>): boolean;
/**
* #### narrow this based on an {@link extends} check
*
* ✅ ignores associated {@link meta}, which does not affect the set of allowed values
*
* @example
* const N = type(Math.random() > 0.5 ? "true" : "0") // Type<0 | true>
* const Ez = N.ifExtends("boolean") // Type<true> | undefined
*/
ifExtends<const def, r = type.instantiate<def, $>>(other: type.validate<def, $>): r extends infer _ ? _ | undefined : never;
/**
* #### check if a value could satisfy this and the parsed Type
*
* ⚠️ will return true unless a {@link Disjoint} can be proven
*
* @example
* type.string.overlaps("string | number") // true (e.g. "foo")
* type("string | number").overlaps("1") // true (1)
* type("number > 0").overlaps("number < 0") // false (no values exist)
*
* const NoAt = type("string").narrow(s => !s.includes("@"))
* NoAt.overlaps("string.email") // true (no values exist, but not provable)
*/
overlaps<const def>(r: type.validate<def, $>): boolean;
/**
* #### extract branches {@link extend}ing the parsed Type
*
* @example
* // Type<true | 0 | 2>
* const T = type("boolean | 0 | 'one' | 2 | bigint").extract("number | 0n | true")
*/
extract<const def, r = instantiateType<t extends type.infer<def, $> ? t : never, $>>(r: type.validate<def, $>): r extends infer _ extends r ? _ : never;
/**
* #### exclude branches {@link extend}ing the parsed Type
*
* @example
*
* // Type<false | 'one' | bigint>
* const T = type("boolean | 0 | 'one' | 2 | bigint").exclude("number | 0n | true")
*/
exclude<const def, r = instantiateType<t extends type.infer<def, $> ? never : t, $>>(r: type.validate<def, $>): r extends infer _ ? _ : never;
/**
* @experimental
* Map and optionally reduce branches of a union. Types that are not unions
* are treated as a single branch.
*
* @param mapBranch - the mapping function, accepting a branch Type
* Returning another `Type` is common, but any value can be returned and
* inferred as part of the output.
*
* @param [reduceMapped] - an operation to perform on the mapped branches
* Can be used to e.g. merge an array of returned Types representing
* branches back to a single union.
*/
distribute<mapOut, reduceOut = mapOut[]>(mapBranch: (branch: Type, i: number, branches: array<Type>) => mapOut, reduceMapped?: (mappedBranches: mapOut[]) => reduceOut): reduceOut;
/** The Type's [StandardSchema](https://github.com/standard-schema/standard-schema) properties */
"~standard": StandardSchemaV1.ArkTypeProps<this["inferIn"], this["inferOut"]>;
/** @deprecated */
apply: Function["apply"];
/** @deprecated */
bind: Function["bind"];
/** @deprecated */
call: Function["call"];
/** @deprecated */
caller: Function;
/** @deprecated */
length: number;
/** @deprecated */
name: string;
/** @deprecated */
prototype: Function["prototype"];
/** @deprecated */
arguments: Function["arguments"];
/** @deprecated */
Symbol: never;
}
export interface ChainedPipeParser<$, t> extends NaryPipeParser<$, t> {
try: NaryPipeParser<$, t>;
}
type validateChainedAsArgs<t> = [
t
] extends [unset] ? [
t
] extends [anyOrNever] ? [
] : [
ErrorMessage<"as requires an explicit type parameter like myType.as<t>()">
] : [];
export type { Type as BaseType };
import type { ExclusiveDateRangeSchema, InclusiveDateRangeSchema } from "@ark/schema";
import type { ObjectType } from "./object.ts";
/** @ts-ignore cast variance */
interface Type<out t extends globalThis.Date = globalThis.Date, $ = {}> extends ObjectType<t, $> {
atOrAfter(schema: InclusiveDateRangeSchema): this;
atOrBefore(schema: InclusiveDateRangeSchema): this;
laterThan(schema: ExclusiveDateRangeSchema): this;
earlierThan(schema: ExclusiveDateRangeSchema): this;
}
export type { Type as DateType };
import type { anyOrNever, array } from "@ark/util";
import type { ArrayType } from "./array.ts";
import type { BaseType } from "./base.ts";
import type { DateType } from "./date.ts";
import type { NumberType } from "./number.ts";
import type { ObjectType } from "./object.ts";
import type { StringType } from "./string.ts";
export type instantiateType<t, $> = [
t
] extends [anyOrNever] ? BaseType<t, $> : [t] extends [object] ? [
t
] extends [array] ? ArrayType<t, $> : [t] extends [Date] ? DateType<t, $> : ObjectType<t, $> : [t] extends [string] ? StringType<t, $> : [t] extends [number] ? NumberType<t, $> : BaseType<t, $>;
import type { Divisor, ExclusiveNumericRangeSchema, InclusiveNumericRangeSchema } from "@ark/schema";
import type { BaseType } from "./base.ts";
/** @ts-ignore cast variance */
interface Type<out t extends number = number, $ = {}> extends BaseType<t, $> {
divisibleBy(schema: Divisor.Schema): this;
atLeast(schema: InclusiveNumericRangeSchema): this;
atMost(schema: InclusiveNumericRangeSchema): this;
moreThan(schema: ExclusiveNumericRangeSchema): this;
lessThan(schema: ExclusiveNumericRangeSchema): this;
}
export type { Type as NumberType };
import type { BaseMappedPropInner, OptionalMappedPropInner, Prop } from "@ark/schema";
import type { arkGet, arkIndexableOf, arkKeyOf, array, ErrorType, inferred, intersectUnion, JsonStructure, Key, listable, merge, optionalKeyOf, show, toArkKey } from "@ark/util";
import type { Default, withDefault } from "../attributes.ts";
import type { type } from "../keywords/keywords.ts";
import type { ArrayType } from "./array.ts";
import type { BaseType } from "./base.ts";
import type { instantiateType } from "./instantiate.ts";
/** @ts-ignore cast variance */
interface Type<out t extends object = object, $ = {}> extends BaseType<t, $> {
readonly(): t extends array ? ArrayType<{
readonly [i in keyof t]: t[i];
}, $> : Type<{
readonly [k in keyof t]: t[k];
}, $>;
keyof(): instantiateType<arkKeyOf<t>, $>;
/**
* Get the `Type` of a property of this `Type<object>`.
* @example type({ foo: "string" }).get("foo") // Type<string>
*/
get<const k1 extends arkIndexableOf<t>, r = instantiateType<arkGet<t, k1>, $>>(k1: k1 | type.cast<k1>): r extends infer _ ? _ : never;
get<const k1 extends arkIndexableOf<t>, const k2 extends arkIndexableOf<arkGet<t, k1>>, r = instantiateType<arkGet<arkGet<t, k1>, k2>, $>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>): r extends infer _ ? _ : never;
get<const k1 extends arkIndexableOf<t>, const k2 extends arkIndexableOf<arkGet<t, k1>>, const k3 extends arkIndexableOf<arkGet<arkGet<t, k1>, k2>>, r = instantiateType<arkGet<arkGet<arkGet<t, k1>, k2>, k3>, $>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>, k3: k3 | type.cast<k3>): r extends infer _ ? _ : never;
/**
* Create a copy of this `Type` with only the specified properties.
* @example type({ foo: "string", bar: "number" }).pick("foo") // Type<{ foo: string }>
*/
pick<const key extends arkKeyOf<t> = never>(...keys: (key | type.cast<key>)[]): Type<{
[k in keyof t as Extract<toArkKey<t, k>, key>]: t[k];
}, $>;
/**
* Create a copy of this `Type` with all properties except the specified ones.
* @example type({ foo: "string", bar: "number" }).omit("foo") // Type<{ bar: number }>
*/
omit<const key extends arkKeyOf<t> = never>(...keys: (key | type.cast<key>)[]): Type<{
[k in keyof t as Exclude<toArkKey<t, k>, key>]: t[k];
}, $>;
/**
* Merge another `Type` definition, overriding properties of this `Type` with the duplicate keys.
* @example type({ a: "1", b: "2" }).merge({ b: "3", c: "4" }) // Type<{ a: 1, b: 3, c: 4 }>
*/
merge<const def, inferredDef = type.infer<def, $>, r = Type<merge<t, inferredDef>, $>>(def: type.validate<def, $> & (inferredDef extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredDef]>)): r extends infer _ ? _ : never;
/**
* Create a copy of this `Type` with all properties required.
* @example const T = type({ "foo?"": "string" }).required() // Type<{ foo: string }>
*/
required(): Type<{
[k in keyof t]-?: t[k];
}, $>;
/**
* Create a copy of this `Type` with all properties optional.
* @example: const T = type({ foo: "string" }).optional() // Type<{ foo?: string }>
*/
partial(): Type<{
[k in keyof t]?: t[k];
}, $>;
map<transformed extends listable<MappedTypeProp>, r = Type<constructMapped<t, transformed>, $>>(flatMapEntry: (entry: typePropOf<t, $>) => transformed): r extends infer _ ? _ : never;
/**
* List of property info of this `Type<object>`.
* @example type({ foo: "string = "" }).props // [{ kind: "required", key: "foo", value: Type<string>, default: "" }]
*/
props: array<typePropOf<t, $>>;
}
type typePropOf<o, $> = keyof o extends infer k ? k extends keyof o ? typeProp<o, k, $> : never : never;
type typeProp<o, k extends keyof o, $, t = o[k] & ({} | null)> = t extends Default<infer t, infer defaultValue> ? DefaultedTypeProp<k & Key, t, defaultValue, $> : BaseTypeProp<k extends optionalKeyOf<o> ? "optional" : "required", k & Key, t, $>;
export interface BaseTypeProp<kind extends Prop.Kind = Prop.Kind, k extends Key = Key,
/** @ts-ignore cast variance */
out v = unknown, $ = {}> {
kind: kind;
key: k;
value: instantiateType<v, $>;
meta: ArkEnv.meta;
toJSON: () => JsonStructure;
}
export interface DefaultedTypeProp<k extends Key = Key, v = unknown, defaultValue = v, $ = {}> extends BaseTypeProp<"optional", k, v, $> {
default: defaultValue;
}
type MappedTypeProp<k extends Key = Key, v = unknown> = BaseMappedTypeProp<k, v> | OptionalMappedTypeProp<k, v>;
type BaseMappedTypeProp<k extends Key, v> = merge<BaseMappedPropInner, {
key: k;
value: type.cast<v>;
}>;
type OptionalMappedTypeProp<k extends Key, v> = merge<OptionalMappedPropInner, {
key: k;
value: type.cast<v>;
default?: v;
}>;
type constructMapped<t, transformed extends listable<MappedTypeProp>> = show<intersectUnion<fromTypeProps<t, transformed extends array ? transformed : [transformed]>>>;
type fromTypeProps<t, props extends array<MappedTypeProp>> = show<{
[prop in props[number] as Extract<applyHomomorphicOptionality<t, prop>, {
kind: "required";
}>["key"]]: prop["value"][inferred];
} & {
[prop in props[number] as Extract<applyHomomorphicOptionality<t, prop>, {
kind: "optional";
default?: never;
}>["key"]]?: prop["value"][inferred];
} & {
[prop in props[number] as Extract<applyHomomorphicOptionality<t, prop>, {
kind: "optional";
default: unknown;
}>["key"]]: withDefault<prop["value"][inferred], prop["default" & keyof prop]>;
}>;
export type NonObjectMergeErrorMessage = "Merged type must be an object";
type applyHomomorphicOptionality<t, prop extends MappedTypeProp> = prop["kind"] extends string ? prop : prop & {
kind: prop["key"] extends optionalKeyOf<t> ? "optional" : "required";
};
export type { Type as ObjectType };
import type { regex } from "@ark/regex";
import type { ExactLength, ExclusiveNumericRangeSchema, InclusiveNumericRangeSchema, Pattern } from "@ark/schema";
import type { BaseType } from "./base.ts";
/** @ts-ignore cast variance */
interface Type<out t extends string = string, $ = {}> extends BaseType<t, $> {
matching<const schema extends Pattern.Schema>(schema: schema): schema extends string ? Type<regex.infer<schema>, $> : schema extends {
rule: infer pattern extends string;
} ? Type<regex.infer<pattern>, $> : this;
atLeastLength(schema: InclusiveNumericRangeSchema): this;
atMostLength(schema: InclusiveNumericRangeSchema): this;
moreThanLength(schema: ExclusiveNumericRangeSchema): this;
lessThanLength(schema: ExclusiveNumericRangeSchema): this;
exactlyLength(schema: ExactLength.Schema): this;
}
export type { Type as StringType };
+22
-25

@@ -12,21 +12,21 @@ import type { ArkError, ArkErrors, Morph } from "@ark/schema";

export type normalizeLimit<limit> = limit extends DateLiteral<infer source> ? source : limit extends number | string ? limit : never;
export type distill<t, endpoint extends distill.Endpoint> = finalizeDistillation<t, _distill<t, endpoint>>;
export type distill<t, side extends distill.Side> = finalizeDistillation<t, _distill<t, side>>;
export declare namespace distill {
type Endpoint = "in" | "out" | "out.introspectable";
type Side = "in" | "out" | "introspectableOut";
type In<t> = distill<t, "in">;
type Out<t> = distill<t, "out">;
namespace introspectable {
type Out<t> = distill<t, "out.introspectable">;
type Out<t> = distill<t, "introspectableOut">;
}
}
type finalizeDistillation<t, distilled> = equals<t, distilled> extends true ? t : distilled;
type _distill<t, endpoint extends distill.Endpoint> = t extends undefined ? t : [t] extends [anyOrNever] ? t : unknown extends t ? unknown : t extends Brand<infer base> ? endpoint extends "in" ? base : t : t extends TerminallyInferredObject | Primitive ? t : t extends Function ? t extends (...args: never) => anyOrNever ? t : t extends InferredMorph<infer i, infer o> ? distillIo<i, o, endpoint> : t : t extends Default<infer constraint> ? _distill<constraint, endpoint> : t extends array ? distillArray<t, endpoint> : isSafelyMappable<t> extends true ? distillMappable<t, endpoint> : t;
type distillMappable<o, endpoint extends distill.Endpoint> = endpoint extends "in" ? show<{
[k in keyof o as k extends inferredDefaultKeyOf<o> ? never : k]: _distill<o[k], endpoint>;
type _distill<t, side extends distill.Side> = t extends undefined ? t : [t] extends [anyOrNever] ? t : unknown extends t ? unknown : t extends Brand<infer base> ? side extends "in" ? base : t : t extends TerminallyInferredObject | Primitive ? t : t extends Function ? t extends (...args: never) => anyOrNever ? t : t extends InferredMorph<infer i, infer o> ? distillIo<i, o, side> : t : t extends Default<infer constraint> ? _distill<constraint, side> : t extends array ? distillArray<t, side> : isSafelyMappable<t> extends true ? distillMappable<t, side> : t;
type distillMappable<o, side extends distill.Side> = side extends "in" ? show<{
[k in keyof o as k extends inferredDefaultKeyOf<o> ? never : k]: _distill<o[k], side>;
} & {
[k in inferredDefaultKeyOf<o>]?: _distill<o[k], endpoint>;
[k in inferredDefaultKeyOf<o>]?: _distill<o[k], side>;
}> : {
[k in keyof o]: _distill<o[k], endpoint>;
[k in keyof o]: _distill<o[k], side>;
};
type distillIo<i, o extends Out, endpoint extends distill.Endpoint> = endpoint extends "out" ? _distill<o["t"], endpoint> : endpoint extends "in" ? _distill<i, endpoint> : o extends To<infer validatedOut> ? _distill<validatedOut, endpoint> : unknown;
type distillIo<i, o extends Out, side extends distill.Side> = side extends "out" ? _distill<o["t"], side> : side extends "in" ? _distill<i, side> : o extends To<infer validatedOut> ? _distill<validatedOut, side> : unknown;
type unwrapInput<t> = t extends InferredMorph<infer i> ? t extends anyOrNever ? t : i : t;

@@ -36,16 +36,13 @@ type inferredDefaultKeyOf<o> = keyof o extends infer k ? k extends keyof o ? unwrapInput<o[k]> extends Default<infer t> ? [

] extends [anyOrNever] ? never : k : never : never : never;
type distillArray<t extends array, endpoint extends distill.Endpoint> = t[number][] extends t ? alignReadonly<_distill<t[number], endpoint>[], t> : distillNonArraykeys<t, alignReadonly<distillArrayFromPrefix<[...t], endpoint, []>, t>, endpoint>;
type distillArray<t extends array, side extends distill.Side> = t[number][] extends t ? alignReadonly<_distill<t[number], side>[], t> : distillNonArraykeys<t, alignReadonly<distillArrayFromPrefix<[...t], side, []>, t>, side>;
type alignReadonly<result extends unknown[], original extends array> = original extends unknown[] ? result : Readonly<result>;
type distillNonArraykeys<originalArray extends array, distilledArray, endpoint extends distill.Endpoint> = keyof originalArray extends keyof distilledArray ? distilledArray : distilledArray & _distill<{
type distillNonArraykeys<originalArray extends array, distilledArray, side extends distill.Side> = keyof originalArray extends keyof distilledArray ? distilledArray : distilledArray & _distill<{
[k in keyof originalArray as k extends keyof distilledArray ? never : k]: originalArray[k];
}, endpoint>;
type distillArrayFromPrefix<t extends array, endpoint extends distill.Endpoint, prefix extends array> = t extends readonly [infer head, ...infer tail] ? distillArrayFromPrefix<tail, endpoint, [
...prefix,
_distill<head, endpoint>
]> : [...prefix, ...distillArrayFromPostfix<t, endpoint, []>];
type distillArrayFromPostfix<t extends array, endpoint extends distill.Endpoint, postfix extends array> = t extends readonly [...infer init, infer last] ? distillArrayFromPostfix<init, endpoint, [
_distill<last, endpoint>,
...postfix
]> : [...{
[i in keyof t]: _distill<t[i], endpoint>;
}, side>;
type distillArrayFromPrefix<t extends array, side extends distill.Side, prefix extends array> = t extends readonly [infer head, ...infer tail] ? distillArrayFromPrefix<tail, side, [
side,
head
] extends ["in", Default] ? [...prefix, _distill<head, side>?] : [...prefix, _distill<head, side>]> : [...prefix, ...distillArrayFromPostfix<t, side, []>];
type distillArrayFromPostfix<t extends array, side extends distill.Side, postfix extends array> = t extends readonly [...infer init, infer last] ? distillArrayFromPostfix<init, side, [_distill<last, side>, ...postfix]> : [...{
[i in keyof t]: _distill<t[i], side>;
}, ...postfix];

@@ -79,3 +76,3 @@ type BuiltinTerminalObjectKind = Exclude<arkPrototypes.NonDegenerateName, "Array" | "Function">;

}
export type InferredMorph<i = any, o extends Out = Out> = (In: i) => o;
export type InferredMorph<i = never, o extends Out = Out> = (In: i) => o;
declare const defaultsToKey: " defaultsTo";

@@ -89,3 +86,3 @@ export type Default<t = unknown, v = unknown> = {

] extends [InferredMorph<infer i, infer o>] ? (In: Default<i, v>) => o : never;
type normalizeMorphDistribution<t, undistributedIn = t extends InferredMorph<infer i> ? i : never, undistributedOut extends Out = t extends InferredMorph<any, infer o> ? [
type normalizeMorphDistribution<t, undistributedIn = t extends InferredMorph<infer i> ? i : never, undistributedOut extends Out = t extends InferredMorph<never, infer o> ? [
o

@@ -102,3 +99,3 @@ ] extends [To<infer unwrappedOut>] ? To<unwrappedOut> : o : never> = (Extract<t, InferredMorph> extends anyOrNever ? never : Extract<t, InferredMorph> extends InferredMorph<infer i, infer o> ? [

l & r
] extends [infer t extends anyOrNever] ? t : l extends InferredMorph<infer lIn, infer lOut> ? r extends InferredMorph<any, infer rOut> ? piped extends true ? (In: lIn) => rOut : never : piped extends true ? (In: lIn) => To<r> : (In: _inferIntersection<lIn, r, false>) => lOut : r extends InferredMorph<infer rIn, infer rOut> ? (In: _inferIntersection<rIn, l, false>) => rOut : [l, r] extends [object, object] ? intersectObjects<l, r, piped> extends infer result ? result : never : l & r;
] extends [infer t extends anyOrNever] ? t : l extends InferredMorph<infer lIn, infer lOut> ? r extends InferredMorph<never, infer rOut> ? piped extends true ? (In: lIn) => rOut : never : piped extends true ? (In: lIn) => To<r> : (In: _inferIntersection<lIn, r, false>) => lOut : r extends InferredMorph<infer rIn, infer rOut> ? (In: _inferIntersection<rIn, l, false>) => rOut : [l, r] extends [object, object] ? intersectObjects<l, r, piped> extends infer result ? result : never : l & r;
interface MorphableIntersection<piped extends boolean> extends Hkt<[unknown, unknown]> {

@@ -108,3 +105,3 @@ body: _inferIntersection<this[0], this[1], piped>;

type intersectObjects<l, r, piped extends boolean> = l extends array ? r extends array ? intersectArrays<l, r, MorphableIntersection<piped>> : // for an intersection with exactly one array operand like { name: string } & string[],
l & r : r extends array ? l & r : show<{
l & r : r extends array ? l & r : keyof l & keyof r extends never ? show<l & r> : show<{
[k in keyof l]: k extends keyof r ? _inferIntersection<l[k], r[k], piped> : l[k];

@@ -111,0 +108,0 @@ } & {

import { GenericRoot, type arkKind, type BaseParseContext, type GenericAst, type GenericParamAst, type GenericParamDef, type genericParamNames, type LazyGenericBody } from "@ark/schema";
import { type array, type Callable, type conform, type ErrorMessage, type ErrorType, type Hkt, type JsonStructure, type WhitespaceChar } from "@ark/util";
import { type array, type Callable, type conform, type ErrorMessage, type ErrorType, type Hkt, type JsonStructure, type Scanner, type WhitespaceChar } from "@ark/util";
import type { type } from "./keywords/keywords.ts";

@@ -7,4 +7,3 @@ import type { inferAstRoot } from "./parser/ast/infer.ts";

import type { inferDefinition } from "./parser/definition.ts";
import type { state, StaticState } from "./parser/reduce/static.ts";
import type { ArkTypeScanner } from "./parser/shift/scanner.ts";
import type { s, StaticState } from "./parser/reduce/static.ts";
import { parseUntilFinalizer } from "./parser/string.ts";

@@ -16,3 +15,3 @@ import type { Scope } from "./scope.ts";

export type validateParameterString<s extends ParameterString, $> = parseGenericParams<extractParams<s>, $> extends infer e extends ErrorMessage ? e : s;
export type validateGenericArg<arg, param extends GenericParamAst, $> = type.infer<arg, $> extends param[1] ? unknown : ErrorType<`Invalid argument for ${param[0]}`, [expected: param[1]]>;
export type validateGenericArg<arg, param extends GenericParamAst, $> = type.infer<arg, $> extends param[1] ? unknown : ErrorType<[`Invalid argument for ${param[0]}`, expected: param[1]]>;
export type GenericInstantiator<params extends array<GenericParamAst>, def, $, args$> = params["length"] extends 1 ? {

@@ -92,15 +91,15 @@ <const a, r = instantiateGeneric<def, params, [a], $, args$>>(a: type.validate<a, args$> & validateGenericArg<a, params[0], args$>): r extends infer _ ? _ : never;

export type emptyGenericParameterMessage = typeof emptyGenericParameterMessage;
export type parseGenericParams<def extends string, $> = parseNextNameChar<ArkTypeScanner.skipWhitespace<def>, "", [
export type parseGenericParams<def extends string, $> = parseNextNameChar<Scanner.skipWhitespace<def>, "", [
], $>;
type ParamsTerminator = WhitespaceChar | ",";
export declare const parseGenericParamName: (scanner: ArkTypeScanner, result: GenericParamDef[], ctx: BaseParseContext) => GenericParamDef[];
type parseName<unscanned extends string, result extends array<GenericParamAst>, $> = parseNextNameChar<ArkTypeScanner.skipWhitespace<unscanned>, "", result, $>;
export declare const parseGenericParamName: (scanner: Scanner, result: GenericParamDef[], ctx: BaseParseContext) => GenericParamDef[];
type parseName<unscanned extends string, result extends array<GenericParamAst>, $> = parseNextNameChar<Scanner.skipWhitespace<unscanned>, "", result, $>;
type parseNextNameChar<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = unscanned extends `${infer lookahead}${infer nextUnscanned}` ? lookahead extends ParamsTerminator ? name extends "" ? ErrorMessage<emptyGenericParameterMessage> : lookahead extends "," ? parseName<nextUnscanned, [...result, [name, unknown]], $> : lookahead extends WhitespaceChar ? _parseOptionalConstraint<nextUnscanned, name, result, $> : never : parseNextNameChar<nextUnscanned, `${name}${lookahead}`, result, $> : name extends "" ? result : [...result, [name, unknown]];
declare const extendsToken = "extends ";
type extendsToken = typeof extendsToken;
declare const _parseOptionalConstraint: (scanner: ArkTypeScanner, name: string, result: GenericParamDef[], ctx: BaseParseContext) => GenericParamDef[];
type _parseOptionalConstraint<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = ArkTypeScanner.skipWhitespace<unscanned> extends (`${extendsToken}${infer nextUnscanned}`) ? parseUntilFinalizer<state.initialize<nextUnscanned>, $, {}> extends (infer finalArgState extends StaticState) ? validateAst<finalArgState["root"], $, {}> extends (infer e extends ErrorMessage) ? e : parseName<finalArgState["unscanned"], [
declare const _parseOptionalConstraint: (scanner: Scanner, name: string, result: GenericParamDef[], ctx: BaseParseContext) => GenericParamDef[];
type _parseOptionalConstraint<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = Scanner.skipWhitespace<unscanned> extends (`${extendsToken}${infer nextUnscanned}`) ? parseUntilFinalizer<s.initialize<nextUnscanned>, $, {}> extends (infer finalArgState extends StaticState) ? validateAst<finalArgState["root"], $, {}> extends (infer e extends ErrorMessage) ? e : parseName<finalArgState["unscanned"], [
...result,
[name, inferAstRoot<finalArgState["root"], $, {}>]
], $> : never : parseName<ArkTypeScanner.skipWhitespace<unscanned> extends (`,${infer nextUnscanned}`) ? nextUnscanned : unscanned, [
], $> : never : parseName<Scanner.skipWhitespace<unscanned> extends `,${infer nextUnscanned}` ? nextUnscanned : unscanned, [
...result,

@@ -107,0 +106,0 @@ [name, unknown]

import { GenericRoot } from "@ark/schema";
import { throwParseError } from "@ark/util";
import { DynamicState } from "./parser/reduce/dynamic.js";
import { RuntimeState } from "./parser/reduce/dynamic.js";
import { terminatingChars } from "./parser/shift/tokens.js";
import { parseUntilFinalizer } from "./parser/string.js";

@@ -9,3 +10,3 @@ export const Generic = GenericRoot;

scanner.shiftUntilNonWhitespace();
const name = scanner.shiftUntilNextTerminator();
const name = scanner.shiftUntilLookahead(terminatingChars);
if (name === "") {

@@ -34,5 +35,5 @@ // if we've reached the end of the string and have parsed at least one

}
const s = parseUntilFinalizer(new DynamicState(scanner, ctx));
const s = parseUntilFinalizer(new RuntimeState(scanner, ctx));
result.push([name, s.root]);
return parseGenericParamName(scanner, result, ctx);
};

@@ -0,1 +1,2 @@

export { regex } from "@ark/regex";
export { ArkError, ArkErrors, Traversal, TraversalError, type ArkSchemaConfig, type ArkSchemaScopeConfig, type JsonSchema } from "@ark/schema";

@@ -7,3 +8,2 @@ export { Hkt, inferred, ParseError } from "@ark/util";

export { ark, declare, define, generic, keywords, match, type, type Ark } from "./keywords/keywords.ts";
export type { BaseType } from "./methods/base.ts";
export { Module, type BoundModule, type Submodule } from "./module.ts";

@@ -13,1 +13,2 @@ export type { inferDefinition, validateDefinition } from "./parser/definition.ts";

export { Type } from "./type.ts";
export type { BaseType } from "./variants/base.ts";

@@ -0,1 +1,2 @@

export { regex } from "@ark/regex";
export { ArkError, ArkErrors, Traversal, TraversalError } from "@ark/schema";

@@ -2,0 +3,0 @@ export { Hkt, inferred, ParseError } from "@ark/util";

import type { ArkErrors, arkKind, flatResolutionsOf } from "@ark/schema";
import type { Brand, inferred } from "@ark/util";
import type { distill, InferredMorph, Out, To } from "../attributes.ts";
import type { DeclarationParser } from "../declare.ts";
import type { FnParser } from "../fn.ts";
import type { GenericParser } from "../generic.ts";
import type { MatchParser } from "../match.ts";
import type { BaseType } from "../methods/base.ts";
import type { instantiateType } from "../methods/instantiate.ts";
import type { BoundModule, Module } from "../module.ts";
import type { inferDefinition, validateDefinition } from "../parser/definition.ts";
import { type bindThis, type Scope } from "../scope.ts";
import type { DeclarationParser, DefinitionParser, SchemaParser, Type, TypeParser } from "../type.ts";
import type { DefinitionParser, SchemaParser, Type, TypeParser } from "../type.ts";
import type { BaseType } from "../variants/base.ts";
import type { instantiateType } from "../variants/instantiate.ts";
import { arkBuiltins } from "./builtins.ts";

@@ -64,2 +66,3 @@ import { arkPrototypes } from "./constructors.ts";

export declare const match: MatchParser<{}>;
export declare const fn: FnParser<{}>;
export declare const generic: GenericParser<{}>;

@@ -66,0 +69,0 @@ export declare const schema: SchemaParser<{}>;

@@ -44,2 +44,3 @@ import { $arkTypeRegistry, scope } from "../scope.js";

export const match = ark.match;
export const fn = ark.fn;
export const generic = ark.generic;

@@ -46,0 +47,0 @@ export const schema = ark.schema;

@@ -386,14 +386,3 @@ import { ArkErrors, intrinsic, node, rootSchema } from "@ark/schema";

});
const isParsableUrl = (s) => {
if (URL.canParse)
return URL.canParse(s);
// TODO[2025-04-30] remove once Node 18 is EOL and we can rely on URL.canParse
try {
new URL(s);
return true;
}
catch {
return false;
}
};
const isParsableUrl = (s) => URL.canParse(s);
const urlRoot = rootSchema({

@@ -400,0 +389,0 @@ domain: "string",

import { type ArkErrors, type BaseRoot, type Morph } from "@ark/schema";
import { Callable, type conform, type ErrorMessage, type ErrorType, type isDisjoint, type Key, type numericStringKeyOf, type propValueOf, type unionToTuple } from "@ark/util";
import { Callable, type conform, type ErrorMessage, type ErrorType, type isDisjoint, type Key, type numericStringKeyOf, type propValueOf, type show, type unionToTuple } from "@ark/util";
import type { distill, Out } from "./attributes.ts";
import type { type } from "./keywords/keywords.ts";
import type { Inferred } from "./methods/base.ts";
import type { BaseCompletions } from "./parser/string.ts";
import type { InternalScope } from "./scope.ts";
import type { Inferred } from "./variants/base.ts";
type MatchParserContext<input = unknown> = {

@@ -73,8 +73,3 @@ cases: Morph[];

} : t;
type _finalizeCaseArg<t, ctx extends MatchParserContext, endpoint extends "in" | "out"> = [
distill<t, "in">,
distill<t, endpoint>
] extends [infer i, infer result] ? [
i
] extends [ctx["input"]] ? result : Extract<ctx["input"], i> extends never ? result : Extract<ctx["input"], result> : never;
type _finalizeCaseArg<t, ctx extends MatchParserContext, endpoint extends "in" | "out", ctxInput = ctx["input"]> = ctxInput extends unknown ? t extends unknown ? distill<t, endpoint> extends infer result ? ctxInput extends result ? ctxInput : show<ctxInput & result> : never : never : never;
type CaseParser<ctx extends MatchParserContext> = <const def, ret>(def: type.validate<def, ctx["$"]>, resolve: (In: inferCaseArg<def, ctx, "out">) => ret) => ChainableMatchParser<addCasesToContext<ctx, [(In: inferCaseArg<def, ctx, "in">) => ret]>>;

@@ -81,0 +76,0 @@ type validateKey<key extends Key, ctx extends MatchParserContext> = ctx["key"] extends Key ? ErrorMessage<doubleAtMessage> : ctx["cases"]["length"] extends 0 ? keyof ctx["input"] extends never ? key : conform<key, keyof ctx["input"]> : ErrorMessage<chainedAtMessage>;

@@ -5,5 +5,5 @@ import type { Morph } from "@ark/schema";

import type { type } from "./keywords/keywords.ts";
import type { instantiateType } from "./methods/instantiate.ts";
import type { NonObjectMergeErrorMessage } from "./methods/object.ts";
import type { Type } from "./type.ts";
import type { instantiateType } from "./variants/instantiate.ts";
import type { NonObjectMergeErrorMessage } from "./variants/object.ts";
export type NaryUnionParser<$> = {

@@ -224,7 +224,7 @@ (): Type<never, $>;

(): Type<object, $>;
<const a, inferredA = type.infer<a, $>, r = Type<inferredA, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>)): r extends infer _ ? _ : never;
<const a, const b, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, r = Type<merge<inferredA, inferredB>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<"Merged type must be an object", [actual: inferredB]>)): r extends infer _ ? _ : never;
<const a, const b, const c, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, r = Type<inferNaryMerge<[inferredA, inferredB, inferredC]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, r = Type<inferNaryMerge<[inferredA, inferredB, inferredC, inferredD]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, r = Type<inferNaryMerge<[inferredA, inferredB, inferredC, inferredD, inferredE]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>)): r extends infer _ ? _ : never;
<const a, inferredA = type.infer<a, $>, r = Type<inferredA, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>)): r extends infer _ ? _ : never;
<const a, const b, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, r = Type<merge<inferredA, inferredB>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>)): r extends infer _ ? _ : never;
<const a, const b, const c, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, r = Type<inferNaryMerge<[inferredA, inferredB, inferredC]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, r = Type<inferNaryMerge<[inferredA, inferredB, inferredC, inferredD]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, r = Type<inferNaryMerge<[inferredA, inferredB, inferredC, inferredD, inferredE]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, r = Type<inferNaryMerge<[

@@ -237,3 +237,3 @@ inferredA,

inferredF
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, r = Type<inferNaryMerge<[

@@ -247,3 +247,3 @@ inferredA,

inferredG
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, r = Type<inferNaryMerge<[

@@ -258,3 +258,3 @@ inferredA,

inferredH
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, const i, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, inferredI = type.infer<i, $>, r = Type<inferNaryMerge<[

@@ -270,3 +270,3 @@ inferredA,

inferredI
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredI]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredI]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, const i, const j, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, inferredI = type.infer<i, $>, inferredJ = type.infer<j, $>, r = Type<inferNaryMerge<[

@@ -283,3 +283,3 @@ inferredA,

inferredJ
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredJ]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredJ]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, const i, const j, const k, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, inferredI = type.infer<i, $>, inferredJ = type.infer<j, $>, inferredK = type.infer<k, $>, r = Type<inferNaryMerge<[

@@ -297,3 +297,3 @@ inferredA,

inferredK
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredK]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredK]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, const i, const j, const k, const l, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, inferredI = type.infer<i, $>, inferredJ = type.infer<j, $>, inferredK = type.infer<k, $>, inferredL = type.infer<l, $>, r = Type<inferNaryMerge<[

@@ -312,3 +312,3 @@ inferredA,

inferredL
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredL]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredL]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, const i, const j, const k, const l, const m, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, inferredI = type.infer<i, $>, inferredJ = type.infer<j, $>, inferredK = type.infer<k, $>, inferredL = type.infer<l, $>, inferredM = type.infer<m, $>, r = Type<inferNaryMerge<[

@@ -328,3 +328,3 @@ inferredA,

inferredM
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredM]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredM]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, const i, const j, const k, const l, const m, const n, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, inferredI = type.infer<i, $>, inferredJ = type.infer<j, $>, inferredK = type.infer<k, $>, inferredL = type.infer<l, $>, inferredM = type.infer<m, $>, inferredN = type.infer<n, $>, r = Type<inferNaryMerge<[

@@ -345,3 +345,3 @@ inferredA,

inferredN
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredM]>), n: type.validate<n, $> & (inferredN extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredN]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredM]>), n: type.validate<n, $> & (inferredN extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredN]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, const i, const j, const k, const l, const m, const n, const o, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, inferredI = type.infer<i, $>, inferredJ = type.infer<j, $>, inferredK = type.infer<k, $>, inferredL = type.infer<l, $>, inferredM = type.infer<m, $>, inferredN = type.infer<n, $>, inferredO = type.infer<o, $>, r = Type<inferNaryMerge<[

@@ -363,3 +363,3 @@ inferredA,

inferredO
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredM]>), n: type.validate<n, $> & (inferredN extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredN]>), o: type.validate<o, $> & (inferredO extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredO]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredM]>), n: type.validate<n, $> & (inferredN extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredN]>), o: type.validate<o, $> & (inferredO extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredO]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, const i, const j, const k, const l, const m, const n, const o, const p, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, inferredI = type.infer<i, $>, inferredJ = type.infer<j, $>, inferredK = type.infer<k, $>, inferredL = type.infer<l, $>, inferredM = type.infer<m, $>, inferredN = type.infer<n, $>, inferredO = type.infer<o, $>, inferredP = type.infer<p, $>, r = Type<inferNaryMerge<[

@@ -382,3 +382,3 @@ inferredA,

inferredP
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredM]>), n: type.validate<n, $> & (inferredN extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredN]>), o: type.validate<o, $> & (inferredO extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredO]>), p: type.validate<p, $> & (inferredP extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredP]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredM]>), n: type.validate<n, $> & (inferredN extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredN]>), o: type.validate<o, $> & (inferredO extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredO]>), p: type.validate<p, $> & (inferredP extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredP]>)): r extends infer _ ? _ : never;
<const a, const b, const c, const d, const e, const f, const g, const h, const i, const j, const k, const l, const m, const n, const o, const p, const q, inferredA = type.infer<a, $>, inferredB = type.infer<b, $>, inferredC = type.infer<c, $>, inferredD = type.infer<d, $>, inferredE = type.infer<e, $>, inferredF = type.infer<f, $>, inferredG = type.infer<g, $>, inferredH = type.infer<h, $>, inferredI = type.infer<i, $>, inferredJ = type.infer<j, $>, inferredK = type.infer<k, $>, inferredL = type.infer<l, $>, inferredM = type.infer<m, $>, inferredN = type.infer<n, $>, inferredO = type.infer<o, $>, inferredP = type.infer<p, $>, inferredQ = type.infer<q, $>, r = Type<inferNaryMerge<[

@@ -402,7 +402,8 @@ inferredA,

inferredQ
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredM]>), n: type.validate<n, $> & (inferredN extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredN]>), o: type.validate<o, $> & (inferredO extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredO]>), p: type.validate<p, $> & (inferredP extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredP]>), q: type.validate<q, $> & (inferredQ extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredQ]>)): r extends infer _ ? _ : never;
]>, $>>(a: type.validate<a, $> & (inferredA extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredA]>), b: type.validate<b, $> & (inferredB extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredB]>), c: type.validate<c, $> & (inferredC extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredC]>), d: type.validate<d, $> & (inferredD extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredD]>), e: type.validate<e, $> & (inferredE extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredE]>), f: type.validate<f, $> & (inferredF extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredF]>), g: type.validate<g, $> & (inferredG extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredG]>), h: type.validate<h, $> & (inferredH extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredH]>), i: type.validate<i, $> & (inferredI extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredI]>), j: type.validate<j, $> & (inferredJ extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredJ]>), k: type.validate<k, $> & (inferredK extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredK]>), l: type.validate<l, $> & (inferredL extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredL]>), m: type.validate<m, $> & (inferredM extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredM]>), n: type.validate<n, $> & (inferredN extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredN]>), o: type.validate<o, $> & (inferredO extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredO]>), p: type.validate<p, $> & (inferredP extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredP]>), q: type.validate<q, $> & (inferredQ extends object ? unknown : ErrorType<[NonObjectMergeErrorMessage, actual: inferredQ]>)): r extends infer _ ? _ : never;
<const defs extends readonly unknown[], r = Type<inferNaryMerge<{
[i in keyof defs]: type.infer<defs[i], $>;
}>, $>>(...defs: {
[i in keyof defs]: type.validate<defs[i], $> & (type.infer<defs[i], $> extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [
[i in keyof defs]: type.validate<defs[i], $> & (type.infer<defs[i], $> extends object ? unknown : ErrorType<[
NonObjectMergeErrorMessage,
actual: type.infer<defs[i], $>

@@ -409,0 +410,0 @@ ]>);

@@ -6,3 +6,3 @@ import type { arkKeyOf, array } from "@ark/util";

import type { Comparator } from "../reduce/shared.ts";
import type { ArkTypeScanner } from "../shift/scanner.ts";
import type { InfixToken, PostfixToken } from "../shift/tokens.ts";
import type { GenericInstantiationAst, inferGenericInstantiation } from "./generic.ts";

@@ -25,3 +25,3 @@ export type inferAstRoot<ast, $, args> = ast extends array ? inferExpression<ast, $, args> : never;

export type PrefixExpression<operator extends PrefixOperator = PrefixOperator, operand = unknown> = [operator, operand];
export type PostfixExpression<operator extends ArkTypeScanner.PostfixToken = ArkTypeScanner.PostfixToken, operand = unknown> = readonly [operand, operator];
export type InfixExpression<operator extends ArkTypeScanner.InfixToken = ArkTypeScanner.InfixToken, l = unknown, r = unknown> = [l, operator, r];
export type PostfixExpression<operator extends PostfixToken = PostfixToken, operand = unknown> = readonly [operand, operator];
export type InfixExpression<operator extends InfixToken = InfixToken, l = unknown, r = unknown> = [l, operator, r];
import type { satisfy, Stringifiable } from "@ark/util";
import type { Comparator } from "../reduce/shared.ts";
import type { ArkTypeScanner } from "../shift/scanner.ts";
import type { OperatorToken } from "../shift/tokens.ts";
import type { DefAst, InferredAst, InfixExpression, PostfixExpression } from "./infer.ts";
export type astToString<ast> = ast extends InferredAst | DefAst ? ast[2] : ast extends PostfixExpression<infer operator, infer operand> ? operator extends "[]" ? `${astToString<operand>}[]` : never : ast extends InfixExpression<infer operator, infer l, infer r> ? operator extends "&" | "|" | "%" | Comparator ? `${astToString<l>} ${operator} ${astToString<r>}` : never : ast extends Stringifiable ? `${ast extends bigint ? `${ast}n` : ast}` : "...";
export type ConstraintOperator = satisfy<ArkTypeScanner.OperatorToken, "%" | Comparator>;
export type ConstraintOperator = satisfy<OperatorToken, "%" | Comparator>;
export type writeConstrainedMorphMessage<constrainedAst> = `To constrain the output of ${astToString<constrainedAst>}, pipe like myMorph.to('number > 0').
To constrain the input, intersect like myMorph.and('number > 0').`;
import { type BaseParseContext, type BaseRoot } from "@ark/schema";
import { type anyOrNever, type array, type defined, type equals, type ErrorMessage, type Fn, type ifEmptyObjectLiteral, type objectKindOrDomainOf, type optionalKeyOf, type Primitive, type requiredKeyOf, type show } from "@ark/util";
import { type anyOrNever, type array, type ErrorMessage, type Fn, type ifEmptyObjectLiteral, type objectKindOrDomainOf, type Primitive } from "@ark/util";
import type { type } from "../keywords/keywords.ts";

@@ -19,19 +19,6 @@ import type { InnerParseResult } from "../scope.ts";

def
] extends [Terminal] ? def : def extends string ? validateString<def, $, args> : def extends BadDefinitionType ? ErrorMessage<writeBadDefinitionTypeMessage<objectKindOrDomainOf<def>>> : unknown extends def ? BaseCompletions<$, args> | {} : def extends readonly unknown[] ? validateTuple<def, $, args> : validateObjectLiteral<def, $, args>;
] extends [Terminal] ? def : def extends string ? validateString<def, $, args> : unknown extends def ? BaseCompletions<$, args> | {} : def extends readonly unknown[] ? validateTuple<def, $, args> : def extends BadDefinitionType ? ErrorMessage<writeBadDefinitionTypeMessage<objectKindOrDomainOf<def>>> : validateObjectLiteral<def, $, args>;
export declare const parseTuple: (def: array, ctx: BaseParseContext) => BaseRoot;
export type validateTuple<def extends array, $, args> = maybeValidateTupleExpression<def, $, args> extends infer result ? result extends null ? validateTupleLiteral<def, $, args> : result : never;
export type inferTuple<def extends array, $, args> = def extends TupleExpression ? inferTupleExpression<def, $, args> : inferTupleLiteral<def, $, args>;
export type validateDeclared<declared, def, $, args> = def extends type.validate<def, $, args> ? validateInference<def, declared, $, args> : type.validate<def, $, args>;
type validateInference<def, declared, $, args> = def extends RegExp | type.cast<unknown> | ThunkCast | TupleExpression ? validateShallowInference<def, declared, $, args> : def extends array ? declared extends array ? {
[i in keyof declared]: i extends keyof def ? validateInference<def[i], declared[i], $, args> : declared[i];
} : show<declarationMismatch<def, declared, $, args>> : def extends object ? show<{
[k in requiredKeyOf<declared>]: k extends keyof def ? validateInference<def[k], declared[k], $, args> : declared[k];
} & {
[k in optionalKeyOf<declared> & string as `${k}?`]: `${k}?` extends (keyof def) ? validateInference<def[`${k}?`], defined<declared[k]>, $, args> : declared[k];
}> : validateShallowInference<def, declared, $, args>;
type validateShallowInference<def, declared, $, args> = equals<inferDefinition<def, $, args>, declared> extends true ? def : show<declarationMismatch<def, declared, $, args>>;
type declarationMismatch<def, declared, $, args> = {
declared: declared;
inferred: inferDefinition<def, $, args>;
};
type Terminal = type.cast<unknown> | Fn | RegExp;

@@ -38,0 +25,0 @@ export type ThunkCast<t = unknown> = () => type.cast<t>;

import { type BaseParseContext, type BaseRoot, type writeInvalidPropertyKeyMessage } from "@ark/schema";
import { type anyOrNever, type Dict, type ErrorMessage, type ErrorType, type EscapeChar, type Key, type merge, type show } from "@ark/util";
import { Backslash, type anyOrNever, type Dict, type ErrorMessage, type ErrorType, type Key, type merge, type show } from "@ark/util";
import type { validateString } from "./ast/validate.ts";

@@ -48,3 +48,3 @@ import type { inferDefinition } from "./definition.ts";

normalized: k;
}> : k extends `${infer inner}?` ? inner extends `${infer baseName}${EscapeChar}` ? PreparsedKey.from<{
}> : k extends `${infer inner}?` ? inner extends `${infer baseName}${Backslash}` ? PreparsedKey.from<{
kind: "required";

@@ -59,3 +59,3 @@ normalized: `${baseName}?`;

kind: "spread";
} : k extends `${EscapeChar}${infer escapedMeta extends MetaKey}` ? PreparsedKey.from<{
} : k extends `${Backslash}${infer escapedMeta extends MetaKey}` ? PreparsedKey.from<{
kind: "required";

@@ -68,3 +68,3 @@ normalized: escapedMeta;

kind: "required";
normalized: k extends (`${EscapeChar}${infer escapedIndexKey extends IndexKey}`) ? escapedIndexKey : k extends Key ? k : `${k & number}`;
normalized: k extends (`${Backslash}${infer escapedIndexKey extends IndexKey}`) ? escapedIndexKey : k extends Key ? k : `${k & number}`;
}>;

@@ -71,0 +71,0 @@ export declare const writeInvalidSpreadTypeMessage: <def extends string>(def: def) => writeInvalidSpreadTypeMessage<def>;

import { intrinsic, normalizeIndex } from "@ark/schema";
import { append, escapeChar, isArray, isEmptyObject, printable, stringAndSymbolicEntriesOf, throwParseError } from "@ark/util";
import { append, Backslash, isArray, isEmptyObject, printable, stringAndSymbolicEntriesOf, throwParseError } from "@ark/util";
import { invalidDefaultableKeyKindMessage, invalidOptionalKeyKindMessage, parseProperty } from "./property.js";

@@ -95,3 +95,3 @@ export const parseObjectLiteral = (def, ctx) => {

: key.at(-1) === "?" ?
key.at(-2) === escapeChar ?
key.at(-2) === Backslash ?
{ kind: "required", normalized: `${key.slice(0, -2)}?` }

@@ -104,3 +104,3 @@ : {

{ kind: "index", normalized: key.slice(1, -1) }
: key[0] === escapeChar && key[1] === "[" && key.at(-1) === "]" ?
: key[0] === Backslash && key[1] === "[" && key.at(-1) === "]" ?
{ kind: "required", normalized: key.slice(1) }

@@ -107,0 +107,0 @@ : key === "..." ? { kind: "spread" }

import type { BaseParseContext, BaseRoot } from "@ark/schema";
import { type requireKeys } from "@ark/util";
import { type requireKeys, type Scanner } from "@ark/util";
import type { LimitLiteral } from "../../attributes.ts";
import type { ArkTypeScanner } from "../shift/scanner.ts";
import type { FinalizingLookahead, InfixToken } from "../shift/tokens.ts";
import { type BranchOperator, type Comparator, type MinComparator, type OpenLeftBound, type StringifiablePrefixOperator } from "./shared.ts";

@@ -13,17 +13,17 @@ type BranchState = {

};
export type DynamicStateWithRoot = requireKeys<DynamicState, "root">;
export declare class DynamicState {
export type RootedRuntimeState = requireKeys<RuntimeState, "root">;
export declare class RuntimeState {
root: BaseRoot | undefined;
branches: BranchState;
finalizer: ArkTypeScanner.FinalizingLookahead | undefined;
finalizer: FinalizingLookahead | undefined;
groups: BranchState[];
scanner: ArkTypeScanner;
scanner: Scanner;
ctx: BaseParseContext;
constructor(scanner: ArkTypeScanner, ctx: BaseParseContext);
constructor(scanner: Scanner, ctx: BaseParseContext);
error(message: string): never;
hasRoot(): this is DynamicStateWithRoot;
hasRoot(): this is RootedRuntimeState;
setRoot(root: BaseRoot): void;
unsetRoot(): this["root"];
constrainRoot(...args: Parameters<BaseRoot<any>["constrain"]>): void;
finalize(finalizer: ArkTypeScanner.FinalizingLookahead): void;
finalize(finalizer: FinalizingLookahead): void;
reduceLeftBound(limit: LimitLiteral, comparator: Comparator): void;

@@ -35,10 +35,10 @@ finalizeBranches(): void;

pushRootToBranch(token: BranchOperator): void;
parseUntilFinalizer(): DynamicStateWithRoot;
parseOperator(this: DynamicStateWithRoot): void;
parseUntilFinalizer(): RootedRuntimeState;
parseOperator(this: RootedRuntimeState): void;
parseOperand(): void;
private assertRangeUnset;
reduceGroupOpen(): void;
previousOperator(): MinComparator | StringifiablePrefixOperator | ArkTypeScanner.InfixToken | undefined;
previousOperator(): MinComparator | StringifiablePrefixOperator | InfixToken | undefined;
shiftedByOne(): this;
}
export {};

@@ -1,8 +0,7 @@

import { isKeyOf, throwInternalError, throwParseError } from "@ark/util";
import { isKeyOf, throwInternalError, throwParseError, writeUnclosedGroupMessage, writeUnmatchedGroupCloseMessage } from "@ark/util";
import { parseOperand } from "../shift/operand/operand.js";
import { parseOperator } from "../shift/operator/operator.js";
import { parseUntilFinalizer } from "../string.js";
import { invertedComparators, minComparators, writeMultipleLeftBoundsMessage, writeOpenRangeMessage, writeUnclosedGroupMessage, writeUnmatchedGroupCloseMessage, writeUnpairableComparatorMessage } from "./shared.js";
export class DynamicState {
// set root type to `any` so that all constraints can be applied
import { invertedComparators, minComparators, writeMultipleLeftBoundsMessage, writeOpenRangeMessage, writeUnpairableComparatorMessage } from "./shared.js";
export class RuntimeState {
root;

@@ -81,4 +80,5 @@ branches = {

const topBranchState = this.groups.pop();
if (!topBranchState)
return this.error(writeUnmatchedGroupCloseMessage(this.scanner.unscanned));
if (!topBranchState) {
return this.error(writeUnmatchedGroupCloseMessage(")", this.scanner.unscanned));
}
this.branches = topBranchState;

@@ -119,3 +119,3 @@ }

parseUntilFinalizer() {
return parseUntilFinalizer(new DynamicState(this.scanner, this.ctx));
return parseUntilFinalizer(new RuntimeState(this.scanner, this.ctx));
}

@@ -122,0 +122,0 @@ parseOperator() {

@@ -34,6 +34,2 @@ import type { LimitLiteral } from "../../attributes.ts";

};
export declare const writeUnmatchedGroupCloseMessage: <unscanned extends string>(unscanned: unscanned) => writeUnmatchedGroupCloseMessage<unscanned>;
export type writeUnmatchedGroupCloseMessage<unscanned extends string> = `Unmatched )${unscanned extends "" ? "" : ` before ${unscanned}`}`;
export declare const writeUnclosedGroupMessage: <missingChar extends string>(missingChar: missingChar) => writeUnclosedGroupMessage<missingChar>;
export type writeUnclosedGroupMessage<missingChar extends string> = `Missing ${missingChar}`;
export declare const writeOpenRangeMessage: <min extends LimitLiteral, comparator extends MinComparator>(min: min, comparator: comparator) => writeOpenRangeMessage<min, comparator>;

@@ -40,0 +36,0 @@ export type writeOpenRangeMessage<min extends LimitLiteral, comparator extends MinComparator> = `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`;

@@ -23,6 +23,4 @@ export const minComparators = {

};
export const writeUnmatchedGroupCloseMessage = (unscanned) => `Unmatched )${(unscanned === "" ? "" : ` before ${unscanned}`)}`;
export const writeUnclosedGroupMessage = (missingChar) => `Missing ${missingChar}`;
export const writeOpenRangeMessage = (min, comparator) => `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`;
export const writeUnpairableComparatorMessage = (comparator) => `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`;
export const writeMultipleLeftBoundsMessage = (openLimit, openComparator, limit, comparator) => `An expression may have at most one left bound (parsed ${openLimit}${invertedComparators[openComparator]}, ${limit}${invertedComparators[comparator]})`;

@@ -1,5 +0,5 @@

import type { Completion, ErrorMessage, defined } from "@ark/util";
import type { Completion, ErrorMessage, defined, writeUnclosedGroupMessage, writeUnmatchedGroupCloseMessage } from "@ark/util";
import type { LimitLiteral } from "../../attributes.ts";
import type { ArkTypeScanner } from "../shift/scanner.ts";
import type { BranchOperator, Comparator, InvertedComparators, MaxComparator, MinComparator, OpenLeftBound, StringifiablePrefixOperator, writeMultipleLeftBoundsMessage, writeOpenRangeMessage, writeUnclosedGroupMessage, writeUnmatchedGroupCloseMessage, writeUnpairableComparatorMessage } from "./shared.ts";
import type { FinalizingLookahead } from "../shift/tokens.ts";
import type { BranchOperator, Comparator, InvertedComparators, MaxComparator, MinComparator, OpenLeftBound, StringifiablePrefixOperator, writeMultipleLeftBoundsMessage, writeOpenRangeMessage, writeUnpairableComparatorMessage } from "./shared.ts";
export type StaticState = {

@@ -9,3 +9,3 @@ root: unknown;

groups: BranchState[];
finalizer: ArkTypeScanner.FinalizingLookahead | ErrorMessage | undefined;
finalizer: FinalizingLookahead | ErrorMessage | undefined;
scanned: string;

@@ -22,3 +22,3 @@ unscanned: string;

export type AutocompletePrefix = `${StringifiablePrefixOperator} `;
export declare namespace state {
export declare namespace s {
type initialize<def extends string> = from<{

@@ -92,3 +92,3 @@ root: undefined;

}>;
type reduceLeftBound<s extends StaticState, limit extends LimitLiteral, comparator extends Comparator, unscanned extends string> = comparator extends "<" | "<=" ? s["branches"]["leftBound"] extends {} ? state.error<writeMultipleLeftBoundsMessage<s["branches"]["leftBound"]["limit"], s["branches"]["leftBound"]["comparator"], limit, InvertedComparators[comparator]>> : from<{
type reduceLeftBound<s extends StaticState, limit extends LimitLiteral, comparator extends Comparator, unscanned extends string> = comparator extends "<" | "<=" ? s["branches"]["leftBound"] extends {} ? s.error<writeMultipleLeftBoundsMessage<s["branches"]["leftBound"]["limit"], s["branches"]["leftBound"]["comparator"], limit, InvertedComparators[comparator]>> : from<{
root: undefined;

@@ -109,4 +109,4 @@ branches: {

unscanned: unscanned;
}> : state.error<writeUnpairableComparatorMessage<comparator>>;
type reduceRange<s extends StaticState, minLimit extends LimitLiteral, minComparator extends MinComparator, maxComparator extends MaxComparator, maxLimit extends LimitLiteral, unscanned extends string> = state.from<{
}> : s.error<writeUnpairableComparatorMessage<comparator>>;
type reduceRange<s extends StaticState, minLimit extends LimitLiteral, minComparator extends MinComparator, maxComparator extends MaxComparator, maxLimit extends LimitLiteral, unscanned extends string> = s.from<{
root: [minLimit, minComparator, [s["root"], maxComparator, maxLimit]];

@@ -125,3 +125,3 @@ branches: {

}>;
type reduceSingleBound<s extends StaticState, comparator extends Comparator, limit extends number | string, unscanned extends string> = state.from<{
type reduceSingleBound<s extends StaticState, comparator extends Comparator, limit extends number | string, unscanned extends string> = s.from<{
root: [s["root"], comparator, limit];

@@ -158,3 +158,3 @@ branches: {

unscanned: unscanned;
}> : state.error<writeUnmatchedGroupCloseMessage<unscanned>>;
}> : s.error<writeUnmatchedGroupCloseMessage<")", unscanned>>;
type reduceGroupOpen<s extends StaticState, unscanned extends string> = from<{

@@ -168,3 +168,3 @@ groups: [...s["groups"], s["branches"]];

}>;
type finalize<s extends StaticState, finalizer extends ArkTypeScanner.FinalizingLookahead> = s["groups"] extends [] ? s["branches"]["leftBound"] extends {} ? openRangeError<s["branches"]["leftBound"]> : from<{
type finalize<s extends StaticState, finalizer extends FinalizingLookahead> = s["groups"] extends [] ? s["branches"]["leftBound"] extends {} ? openRangeError<s["branches"]["leftBound"]> : from<{
root: mergeToPipe<s>;

@@ -176,4 +176,4 @@ groups: s["groups"];

unscanned: s["unscanned"];
}> : state.error<writeUnclosedGroupMessage<")">>;
type openRangeError<range extends defined<BranchState["leftBound"]>> = state.error<writeOpenRangeMessage<range["limit"], range["comparator"]>>;
}> : s.error<writeUnclosedGroupMessage<")">>;
type openRangeError<range extends defined<BranchState["leftBound"]>> = s.error<writeOpenRangeMessage<range["limit"], range["comparator"]>>;
type previousOperator<s extends StaticState> = s["branches"]["leftBound"] extends {} ? s["branches"]["leftBound"]["comparator"] : s["branches"]["prefixes"] extends ([

@@ -180,0 +180,0 @@ ...unknown[],

@@ -0,11 +1,11 @@

import type { regex } from "@ark/regex";
import { type Scanner } from "@ark/util";
import type { InferredAst } from "../../ast/infer.ts";
import type { DynamicState } from "../../reduce/dynamic.ts";
import type { StaticState, state } from "../../reduce/static.ts";
import type { ArkTypeScanner } from "../scanner.ts";
export type StringLiteral<Text extends string = string> = DoubleQuotedStringLiteral<Text> | SingleQuotedStringLiteral<Text>;
export type DoubleQuotedStringLiteral<Text extends string = string> = `"${Text}"`;
export type SingleQuotedStringLiteral<Text extends string = string> = `'${Text}'`;
export declare const parseEnclosed: (s: DynamicState, enclosing: EnclosingStartToken) => void;
export type parseEnclosed<s extends StaticState, enclosingStart extends EnclosingStartToken, unscanned extends string> = ArkTypeScanner.shiftUntil<unscanned, EnclosingTokens[enclosingStart]> extends ArkTypeScanner.shiftResult<infer scanned, infer nextUnscanned> ? nextUnscanned extends "" ? state.error<writeUnterminatedEnclosedMessage<scanned, enclosingStart>> : state.setRoot<s, InferredAst<enclosingStart extends EnclosingQuote ? scanned : enclosingStart extends "/" ? string : Date, `${enclosingStart}${scanned}${EnclosingTokens[enclosingStart]}`>, nextUnscanned extends ArkTypeScanner.shift<string, infer unscanned> ? unscanned : ""> : never;
import type { RuntimeState } from "../../reduce/dynamic.ts";
import type { StaticState, s } from "../../reduce/static.ts";
export type StringLiteral<contents extends string = string> = DoubleQuotedStringLiteral<contents> | SingleQuotedStringLiteral<contents>;
export type DoubleQuotedStringLiteral<contents extends string = string> = `"${contents}"`;
export type SingleQuotedStringLiteral<contents extends string = string> = `'${contents}'`;
export declare const parseEnclosed: (s: RuntimeState, enclosing: EnclosingStartToken) => void;
export type parseEnclosed<s extends StaticState, enclosingStart extends EnclosingStartToken, unscanned extends string> = Scanner.shiftUntilEscapable<unscanned, EnclosingTokens[enclosingStart], ""> extends Scanner.shiftResult<infer scanned, infer nextUnscanned> ? nextUnscanned extends "" ? s.error<writeUnterminatedEnclosedMessage<scanned, enclosingStart>> : s.setRoot<s, InferredAst<enclosingStart extends EnclosingQuote ? scanned : enclosingStart extends "/" ? regex.infer<scanned> : Date, `${enclosingStart}${scanned}${EnclosingTokens[enclosingStart]}`>, nextUnscanned extends Scanner.shift<string, infer unscanned> ? unscanned : ""> : never;
export declare const enclosingQuote: {

@@ -21,3 +21,12 @@ readonly "'": 1;

};
export declare const enclosingLiteralTokens: {
readonly "d'": "'";
readonly 'd"': "\"";
readonly "'": "'";
readonly '"': "\"";
};
export type EnclosingLiteralTokens = typeof enclosingLiteralTokens;
export type EnclosingLiteralStartToken = keyof EnclosingLiteralTokens;
export declare const enclosingTokens: {
readonly "/": "/";
readonly "d'": "'";

@@ -27,3 +36,2 @@ readonly 'd"': "\"";

readonly '"': "\"";
readonly "/": "/";
};

@@ -30,0 +38,0 @@ export type EnclosingTokens = typeof enclosingTokens;

import { isKeyOf, throwParseError } from "@ark/util";
import { tryParseDate, writeInvalidDateMessage } from "./date.js";
export const parseEnclosed = (s, enclosing) => {
const enclosed = s.scanner.shiftUntil(untilLookaheadIsClosing[enclosingTokens[enclosing]]);
const enclosed = s.scanner.shiftUntilEscapable(untilLookaheadIsClosing[enclosingTokens[enclosing]]);
if (s.scanner.lookahead === "")

@@ -37,7 +37,10 @@ return s.error(writeUnterminatedEnclosedMessage(enclosed, enclosing));

};
export const enclosingTokens = {
export const enclosingLiteralTokens = {
"d'": "'",
'd"': '"',
"'": "'",
'"': '"',
'"': '"'
};
export const enclosingTokens = {
...enclosingLiteralTokens,
"/": "/"

@@ -44,0 +47,0 @@ };

import type { BaseRoot, GenericAst, genericParamNames, GenericRoot } from "@ark/schema";
import type { array, ErrorMessage, join } from "@ark/util";
import type { DynamicState } from "../../reduce/dynamic.ts";
import { writeUnclosedGroupMessage } from "../../reduce/shared.ts";
import type { state, StaticState } from "../../reduce/static.ts";
import { writeUnclosedGroupMessage, type array, type ErrorMessage, type join } from "@ark/util";
import type { RuntimeState } from "../../reduce/dynamic.ts";
import type { s, StaticState } from "../../reduce/static.ts";
import type { parseUntilFinalizer } from "../../string.ts";
export declare const parseGenericArgs: (name: string, g: GenericRoot, s: DynamicState) => BaseRoot[];
export declare const parseGenericArgs: (name: string, g: GenericRoot, s: RuntimeState) => BaseRoot[];
export type parseGenericArgs<name extends string, g extends GenericAst, unscanned extends string, $, args> = _parseGenericArgs<name, g, unscanned, $, args, [], []>;
declare const _parseGenericArgs: (name: string, g: GenericRoot, s: DynamicState, argNodes: BaseRoot[]) => BaseRoot[];
declare const _parseGenericArgs: (name: string, g: GenericRoot, s: RuntimeState, argNodes: BaseRoot[]) => BaseRoot[];
export type ParsedArgs<result extends unknown[] = unknown[], unscanned extends string = string> = {

@@ -14,3 +13,3 @@ result: result;

};
type _parseGenericArgs<name extends string, g extends GenericAst, unscanned extends string, $, args, argDefs extends string[], argAsts extends unknown[]> = parseUntilFinalizer<state.initialize<unscanned>, $, args> extends (infer finalArgState extends StaticState) ? {
type _parseGenericArgs<name extends string, g extends GenericAst, unscanned extends string, $, args, argDefs extends string[], argAsts extends unknown[]> = parseUntilFinalizer<s.initialize<unscanned>, $, args> extends (infer finalArgState extends StaticState) ? {
defs: [

@@ -26,5 +25,5 @@ ...argDefs,

unscanned: infer nextUnscanned extends string;
}) ? finalArgState["finalizer"] extends ">" ? nextAsts["length"] extends g["paramsAst"]["length"] ? ParsedArgs<nextAsts, nextUnscanned> : state.error<writeInvalidGenericArgCountMessage<name, genericParamNames<g["paramsAst"]>, nextDefs>> : finalArgState["finalizer"] extends "," ? _parseGenericArgs<name, g, nextUnscanned, $, args, nextDefs, nextAsts> : finalArgState["finalizer"] extends ErrorMessage ? finalArgState : state.error<writeUnclosedGroupMessage<">">> : never : never;
}) ? finalArgState["finalizer"] extends ">" ? nextAsts["length"] extends g["paramsAst"]["length"] ? ParsedArgs<nextAsts, nextUnscanned> : s.error<writeInvalidGenericArgCountMessage<name, genericParamNames<g["paramsAst"]>, nextDefs>> : finalArgState["finalizer"] extends "," ? _parseGenericArgs<name, g, nextUnscanned, $, args, nextDefs, nextAsts> : finalArgState["finalizer"] extends ErrorMessage ? finalArgState : s.error<writeUnclosedGroupMessage<">">> : never : never;
export declare const writeInvalidGenericArgCountMessage: <name extends string, params extends array<string>, argDefs extends array<string>>(name: name, params: params, argDefs: argDefs) => writeInvalidGenericArgCountMessage<name, params, argDefs>;
export type writeInvalidGenericArgCountMessage<name extends string, params extends array<string>, argDefs extends array<string>> = `${name}<${join<params, ", ">}> requires exactly ${params["length"]} args (got ${argDefs["length"]}${argDefs["length"] extends (0) ? "" : `: ${join<argDefs, ",">}`})`;
export {};

@@ -1,2 +0,2 @@

import { writeUnclosedGroupMessage } from "../../reduce/shared.js";
import { writeUnclosedGroupMessage } from "@ark/util";
export const parseGenericArgs = (name, g, s) => _parseGenericArgs(name, g, s, []);

@@ -3,0 +3,0 @@ const _parseGenericArgs = (name, g, s, argNodes) => {

@@ -1,9 +0,8 @@

import { type WhitespaceChar } from "@ark/util";
import type { DynamicState } from "../../reduce/dynamic.ts";
import type { StaticState, state } from "../../reduce/static.ts";
import { type Scanner, type WhitespaceChar } from "@ark/util";
import type { RuntimeState } from "../../reduce/dynamic.ts";
import type { StaticState, s } from "../../reduce/static.ts";
import type { BaseCompletions } from "../../string.ts";
import type { ArkTypeScanner } from "../scanner.ts";
import { parseEnclosed, type EnclosingQuote, type EnclosingStartToken } from "./enclosed.ts";
import { parseUnenclosed } from "./unenclosed.ts";
export declare const parseOperand: (s: DynamicState) => void;
export type parseOperand<s extends StaticState, $, args> = s["unscanned"] extends (ArkTypeScanner.shift<infer lookahead, infer unscanned>) ? lookahead extends "(" ? state.reduceGroupOpen<s, unscanned> : lookahead extends EnclosingStartToken ? parseEnclosed<s, lookahead, unscanned> : lookahead extends WhitespaceChar ? parseOperand<state.scanTo<s, unscanned>, $, args> : lookahead extends "d" ? unscanned extends (ArkTypeScanner.shift<infer enclosing extends EnclosingQuote, infer nextUnscanned>) ? parseEnclosed<s, `d${enclosing}`, nextUnscanned> : parseUnenclosed<s, $, args> : parseUnenclosed<s, $, args> : state.completion<`${s["scanned"]}${BaseCompletions<$, args>}`>;
export declare const parseOperand: (s: RuntimeState) => void;
export type parseOperand<s extends StaticState, $, args> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "(" ? s.reduceGroupOpen<s, unscanned> : lookahead extends EnclosingStartToken ? parseEnclosed<s, lookahead, unscanned> : lookahead extends WhitespaceChar ? parseOperand<s.scanTo<s, unscanned>, $, args> : lookahead extends "d" ? unscanned extends (Scanner.shift<infer enclosing extends EnclosingQuote, infer nextUnscanned>) ? parseEnclosed<s, `d${enclosing}`, nextUnscanned> : parseUnenclosed<s, $, args> : parseUnenclosed<s, $, args> : s.completion<`${s["scanned"]}${BaseCompletions<$, args>}`>;
import { writeUnresolvableMessage, type BaseRoot, type GenericAst, type GenericRoot, type arkKind, type genericParamNames, type resolvableReferenceIn, type writeNonSubmoduleDotMessage } from "@ark/schema";
import { type BigintLiteral, type NumberLiteral, type join, type lastOf } from "@ark/util";
import { type BigintLiteral, type NumberLiteral, type Scanner, type join, type lastOf } from "@ark/util";
import type { ArkAmbient } from "../../../config.ts";

@@ -8,18 +8,18 @@ import type { resolutionToAst } from "../../../scope.ts";

import { writePrefixedPrivateReferenceMessage } from "../../ast/validate.ts";
import type { DynamicState } from "../../reduce/dynamic.ts";
import type { StaticState, state } from "../../reduce/static.ts";
import type { RuntimeState } from "../../reduce/dynamic.ts";
import type { StaticState, s } from "../../reduce/static.ts";
import type { BaseCompletions } from "../../string.ts";
import type { ArkTypeScanner } from "../scanner.ts";
import { type TerminatingChar } from "../tokens.ts";
import { parseGenericArgs, writeInvalidGenericArgCountMessage, type ParsedArgs } from "./genericArgs.ts";
export declare const parseUnenclosed: (s: DynamicState) => void;
export type parseUnenclosed<s extends StaticState, $, args> = ArkTypeScanner.shiftUntilNextTerminator<s["unscanned"]> extends (ArkTypeScanner.shiftResult<infer token, infer unscanned>) ? tryResolve<s, unscanned, token, $, args> extends state.from<infer s> ? s : never : never;
type parseResolution<s extends StaticState, unscanned extends string, alias extends string, resolution, $, args> = resolutionToAst<alias, resolution> extends infer ast ? ast extends GenericAst ? parseGenericInstantiation<alias, ast, state.scanTo<s, unscanned>, $, args> : state.setRoot<s, ast, unscanned> : never;
export declare const parseGenericInstantiation: (name: string, g: GenericRoot, s: DynamicState) => BaseRoot;
export type parseGenericInstantiation<name extends string, g extends GenericAst, s extends StaticState, $, args> = ArkTypeScanner.skipWhitespace<s["unscanned"]> extends `<${infer unscanned}` ? parseGenericArgs<name, g, unscanned, $, args> extends infer result ? result extends ParsedArgs<infer argAsts, infer nextUnscanned> ? state.setRoot<s, GenericInstantiationAst<g, argAsts>, nextUnscanned> : result : never : state.error<writeInvalidGenericArgCountMessage<name, genericParamNames<g["paramsAst"]>, [
export declare const parseUnenclosed: (s: RuntimeState) => void;
export type parseUnenclosed<s extends StaticState, $, args> = Scanner.shiftUntil<s["unscanned"], TerminatingChar> extends (Scanner.shiftResult<infer token, infer unscanned>) ? tryResolve<s, unscanned, token, $, args> extends s.from<infer s> ? s : never : never;
type parseResolution<s extends StaticState, unscanned extends string, alias extends string, resolution, $, args> = resolutionToAst<alias, resolution> extends infer ast ? ast extends GenericAst ? parseGenericInstantiation<alias, ast, s.scanTo<s, unscanned>, $, args> : s.setRoot<s, ast, unscanned> : never;
export declare const parseGenericInstantiation: (name: string, g: GenericRoot, s: RuntimeState) => BaseRoot;
export type parseGenericInstantiation<name extends string, g extends GenericAst, s extends StaticState, $, args> = Scanner.skipWhitespace<s["unscanned"]> extends `<${infer unscanned}` ? parseGenericArgs<name, g, unscanned, $, args> extends infer result ? result extends ParsedArgs<infer argAsts, infer nextUnscanned> ? s.setRoot<s, GenericInstantiationAst<g, argAsts>, nextUnscanned> : result : never : s.error<writeInvalidGenericArgCountMessage<name, genericParamNames<g["paramsAst"]>, [
]>>;
type tryResolve<s extends StaticState, unscanned extends string, token extends string, $, args> = token extends keyof args ? parseResolution<s, unscanned, token, args[token], $, args> : token extends keyof $ ? parseResolution<s, unscanned, token, $[token], $, args> : `#${token}` extends keyof $ ? parseResolution<s, unscanned, token, $[`#${token}`], $, args> : token extends keyof ArkAmbient.$ ? parseResolution<s, unscanned, token, ArkAmbient.$[token], $, args> : token extends NumberLiteral<infer n> ? state.setRoot<s, InferredAst<n, token>, unscanned> : token extends (`${infer submodule extends keyof $ & string}.${infer reference}`) ? tryResolveSubmodule<token, $[submodule], reference, s, unscanned, $, args, [
type tryResolve<s extends StaticState, unscanned extends string, token extends string, $, args> = token extends keyof args ? parseResolution<s, unscanned, token, args[token], $, args> : token extends keyof $ ? parseResolution<s, unscanned, token, $[token], $, args> : token extends keyof ArkAmbient.$ ? parseResolution<s, unscanned, token, ArkAmbient.$[token], $, args> : `#${token}` extends keyof $ ? parseResolution<s, unscanned, token, $[`#${token}`], $, args> : token extends NumberLiteral<infer n> ? s.setRoot<s, InferredAst<n, token>, unscanned> : token extends (`${infer submodule extends keyof $ & string}.${infer reference}`) ? tryResolveSubmodule<token, $[submodule], reference, s, unscanned, $, args, [
submodule
]> : token extends (`${infer submodule extends keyof ArkAmbient.$ & string}.${infer reference}`) ? tryResolveSubmodule<token, ArkAmbient.$[submodule], reference, s, unscanned, $, args, [
submodule
]> : token extends BigintLiteral<infer b> ? state.setRoot<s, InferredAst<b, token>, unscanned> : token extends "keyof" ? state.addPrefix<s, "keyof", unscanned> : unresolvableState<s, token, $, args, []>;
]> : token extends BigintLiteral<infer b> ? s.setRoot<s, InferredAst<b, token>, unscanned> : token extends "keyof" ? s.addPrefix<s, "keyof", unscanned> : unresolvableState<s, token, $, args, []>;
type tryResolveSubmodule<token extends string, resolution, reference extends string, s extends StaticState, unscanned extends string, $, args, submodulePath extends string[]> = resolution extends {

@@ -30,3 +30,3 @@ [arkKind]: "module";

nestedSubmodule
]> : unresolvableState<s, reference, resolution, {}, submodulePath> : state.error<writeNonSubmoduleDotMessage<lastOf<submodulePath>>>;
]> : unresolvableState<s, reference, resolution, {}, submodulePath> : s.error<writeNonSubmoduleDotMessage<lastOf<submodulePath>>>;
/** Provide valid completions for the current token, or fallback to an

@@ -37,9 +37,6 @@ * unresolvable error if there are none */

s["unscanned"]
] extends ([
"",
ArkTypeScanner.shift<"#", infer unscanned>
]) ? ArkTypeScanner.shiftUntilNextTerminator<unscanned> extends (ArkTypeScanner.shiftResult<infer name, string>) ? state.error<writePrefixedPrivateReferenceMessage<name>> : never : validReferenceFromToken<token, resolutions, args, submodulePath> extends (never) ? state.error<writeUnresolvableMessage<qualifiedReference<token, submodulePath>>> : state.completion<`${s["scanned"]}${qualifiedReference<validReferenceFromToken<token, resolutions, args, submodulePath>, submodulePath>}`>;
] extends ["", Scanner.shift<"#", infer unscanned>] ? Scanner.shiftUntil<unscanned, TerminatingChar> extends (Scanner.shiftResult<infer name, string>) ? s.error<writePrefixedPrivateReferenceMessage<name>> : never : validReferenceFromToken<token, resolutions, args, submodulePath> extends (never) ? s.error<writeUnresolvableMessage<qualifiedReference<token, submodulePath>>> : s.completion<`${s["scanned"]}${qualifiedReference<validReferenceFromToken<token, resolutions, args, submodulePath>, submodulePath>}`>;
type qualifiedReference<reference extends string, submodulePath extends string[]> = join<[...submodulePath, reference], ".">;
type validReferenceFromToken<token extends string, $, args, submodulePath extends string[]> = Extract<submodulePath["length"] extends 0 ? BaseCompletions<$, args> : resolvableReferenceIn<$>, `${token}${string}`>;
export declare const writeMissingOperandMessage: (s: DynamicState) => string;
export declare const writeMissingOperandMessage: (s: RuntimeState) => string;
export type writeMissingRightOperandMessage<token extends string, unscanned extends string = ""> = `Token '${token}' requires a right operand${unscanned extends "" ? "" : ` before '${unscanned}'`}`;

@@ -46,0 +43,0 @@ export declare const writeMissingRightOperandMessage: <token extends string, unscanned extends string>(token: token, unscanned?: unscanned) => writeMissingRightOperandMessage<token, unscanned>;

import { hasArkKind, writeUnresolvableMessage } from "@ark/schema";
import { printable, throwParseError, tryParseWellFormedBigint, tryParseWellFormedNumber } from "@ark/util";
import { writePrefixedPrivateReferenceMessage } from "../../ast/validate.js";
import { terminatingChars } from "../tokens.js";
import { parseGenericArgs, writeInvalidGenericArgCountMessage } from "./genericArgs.js";
export const parseUnenclosed = (s) => {
const token = s.scanner.shiftUntilNextTerminator();
const token = s.scanner.shiftUntilLookahead(terminatingChars);
if (token === "keyof")

@@ -24,3 +25,3 @@ s.addPrefix("keyof");

s.scanner.lookahead === "#" ?
writePrefixedPrivateReferenceMessage(s.shiftedByOne().scanner.shiftUntilNextTerminator())
writePrefixedPrivateReferenceMessage(s.shiftedByOne().scanner.shiftUntilLookahead(terminatingChars))
: writeMissingOperandMessage(s)

@@ -27,0 +28,0 @@ : writeUnresolvableMessage(token));

import { type BaseRoot, type BoundKind } from "@ark/schema";
import { type KeySet } from "@ark/util";
import { type KeySet, type Scanner } from "@ark/util";
import type { DateLiteral } from "../../../attributes.ts";
import type { InferredAst } from "../../ast/infer.ts";
import type { astToString } from "../../ast/utils.ts";
import type { DynamicState, DynamicStateWithRoot } from "../../reduce/dynamic.ts";
import type { RootedRuntimeState, RuntimeState } from "../../reduce/dynamic.ts";
import { writeUnpairableComparatorMessage, type Comparator, type InvertedComparators, type MaxComparator } from "../../reduce/shared.ts";
import type { state, StaticState } from "../../reduce/static.ts";
import type { s, StaticState } from "../../reduce/static.ts";
import type { parseOperand } from "../operand/operand.ts";
import type { ArkTypeScanner } from "../scanner.ts";
export declare const parseBound: (s: DynamicStateWithRoot, start: ComparatorStartChar) => void;
export type parseBound<s extends StaticState, start extends ComparatorStartChar, unscanned extends string, $, args> = shiftComparator<start, unscanned> extends infer shiftResultOrError ? shiftResultOrError extends (ArkTypeScanner.shiftResult<infer comparator extends Comparator, infer nextUnscanned>) ? s["root"] extends (InferredAst<Date | number, `${infer limit extends number | DateLiteral}`>) ? state.reduceLeftBound<s, limit, comparator, nextUnscanned> : parseRightBound<state.scanTo<s, nextUnscanned>, comparator, $, args> : shiftResultOrError : never;
export declare const parseBound: (s: RootedRuntimeState, start: ComparatorStartChar) => void;
export type parseBound<s extends StaticState, start extends ComparatorStartChar, unscanned extends string, $, args> = shiftComparator<start, unscanned> extends infer shiftResultOrError ? shiftResultOrError extends (Scanner.shiftResult<infer comparator extends Comparator, infer nextUnscanned>) ? s["root"] extends (InferredAst<Date | number, `${infer limit extends number | DateLiteral}`>) ? s.reduceLeftBound<s, limit, comparator, nextUnscanned> : parseRightBound<s.scanTo<s, nextUnscanned>, comparator, $, args> : shiftResultOrError : never;
type OneCharComparator = ">" | "<";
export type ComparatorStartChar = Comparator extends `${infer char}${string}` ? char : never;
export declare const comparatorStartChars: KeySet<ComparatorStartChar>;
declare const shiftComparator: (s: DynamicState, start: ComparatorStartChar) => Comparator;
declare const shiftComparator: (s: RuntimeState, start: ComparatorStartChar) => Comparator;
type shiftComparator<start extends ComparatorStartChar, unscanned extends string> = unscanned extends `=${infer nextUnscanned}` ? [`${start}=`, nextUnscanned] : [start & OneCharComparator, unscanned];
export declare const writeIncompatibleRangeMessage: (l: BoundKind, r: BoundKind) => string;
export declare const getBoundKinds: (comparator: Comparator, limit: number | DateLiteral, root: BaseRoot, boundKind: BoundExpressionKind) => BoundKind[];
export declare const parseRightBound: (s: DynamicStateWithRoot, comparator: Comparator) => void;
export type parseRightBound<s extends StaticState, comparator extends Comparator, $, args> = parseOperand<s, $, args> extends infer nextState extends StaticState ? nextState["root"] extends (InferredAst<unknown, `${infer limit extends number | DateLiteral}`>) ? s["branches"]["leftBound"] extends {} ? comparator extends MaxComparator ? state.reduceRange<s, s["branches"]["leftBound"]["limit"], s["branches"]["leftBound"]["comparator"], comparator, limit, nextState["unscanned"]> : state.error<writeUnpairableComparatorMessage<comparator>> : state.reduceSingleBound<s, comparator, limit, nextState["unscanned"]> : state.error<writeInvalidLimitMessage<comparator, astToString<nextState["root"]>, "right">> : never;
export declare const parseRightBound: (s: RootedRuntimeState, comparator: Comparator) => void;
export type parseRightBound<s extends StaticState, comparator extends Comparator, $, args> = parseOperand<s, $, args> extends infer nextState extends StaticState ? nextState["root"] extends (InferredAst<unknown, `${infer limit extends number | DateLiteral}`>) ? s["branches"]["leftBound"] extends {} ? comparator extends MaxComparator ? s.reduceRange<s, s["branches"]["leftBound"]["limit"], s["branches"]["leftBound"]["comparator"], comparator, limit, nextState["unscanned"]> : s.error<writeUnpairableComparatorMessage<comparator>> : s.reduceSingleBound<s, comparator, limit, nextState["unscanned"]> : s.error<writeInvalidLimitMessage<comparator, astToString<nextState["root"]>, "right">> : never;
export declare const writeInvalidLimitMessage: <comparator extends Comparator, limit extends string | number, boundKind extends BoundExpressionKind>(comparator: comparator, limit: limit, boundKind: boundKind) => writeInvalidLimitMessage<comparator, limit, boundKind>;

@@ -23,0 +22,0 @@ export type writeInvalidLimitMessage<comparator extends Comparator, limit extends string | number, boundKind extends BoundExpressionKind> = `Comparator ${boundKind extends "left" ? InvertedComparators[comparator] : comparator} must be ${boundKind extends "left" ? "preceded" : "followed"} by a corresponding literal (was ${limit})`;

import type { emptyBrandNameMessage } from "@ark/schema";
import type { DynamicStateWithRoot } from "../../reduce/dynamic.ts";
import type { StaticState, state } from "../../reduce/static.ts";
import type { ArkTypeScanner } from "../scanner.ts";
export declare const parseBrand: (s: DynamicStateWithRoot) => void;
export type parseBrand<s extends StaticState, unscanned extends string> = ArkTypeScanner.shiftUntilNextTerminator<ArkTypeScanner.skipWhitespace<unscanned>> extends (ArkTypeScanner.shiftResult<`${infer brandName}`, infer nextUnscanned>) ? brandName extends "" ? state.error<emptyBrandNameMessage> : state.setRoot<s, [s["root"], "#", brandName], nextUnscanned> : never;
import type { Scanner } from "@ark/util";
import type { RootedRuntimeState } from "../../reduce/dynamic.ts";
import type { StaticState, s } from "../../reduce/static.ts";
import { type TerminatingChar } from "../tokens.ts";
export declare const parseBrand: (s: RootedRuntimeState) => void;
export type parseBrand<s extends StaticState, unscanned extends string> = Scanner.shiftUntil<Scanner.skipWhitespace<unscanned>, TerminatingChar> extends Scanner.shiftResult<`${infer brandName}`, infer nextUnscanned> ? brandName extends "" ? s.error<emptyBrandNameMessage> : s.setRoot<s, [s["root"], "#", brandName], nextUnscanned> : never;

@@ -0,5 +1,6 @@

import { terminatingChars } from "../tokens.js";
export const parseBrand = (s) => {
s.scanner.shiftUntilNonWhitespace();
const brandName = s.scanner.shiftUntilNextTerminator();
const brandName = s.scanner.shiftUntilLookahead(terminatingChars);
s.root = s.root.brand(brandName);
};
import type { BaseRoot } from "@ark/schema";
import type { BigintLiteral, ErrorMessage, NumberLiteral, trim } from "@ark/util";
import type { BigintLiteral, ErrorMessage, NumberLiteral, Scanner, trim } from "@ark/util";
import type { DateLiteral } from "../../../attributes.ts";
import type { DynamicStateWithRoot } from "../../reduce/dynamic.ts";
import type { StringLiteral } from "../operand/enclosed.ts";
import type { RootedRuntimeState } from "../../reduce/dynamic.ts";
import type { EnclosingLiteralStartToken, EnclosingLiteralTokens, StringLiteral } from "../operand/enclosed.ts";
type UnitLiteralKeyword = "null" | "undefined" | "true" | "false";
export type UnitLiteral = StringLiteral | BigintLiteral | NumberLiteral | DateLiteral | UnitLiteralKeyword;
export type UnitLiteral = UnenclosedUnitLiteral | EnclosedUnitLiteral;
export type UnenclosedUnitLiteral = BigintLiteral | NumberLiteral | UnitLiteralKeyword;
export type EnclosedUnitLiteral = StringLiteral | DateLiteral;
export type ParsedDefaultableProperty = readonly [BaseRoot, "=", unknown];
export declare const parseDefault: (s: DynamicStateWithRoot) => ParsedDefaultableProperty;
export type parseDefault<root, unscanned extends string> = trim<unscanned> extends infer defaultValue extends UnitLiteral ? [
export declare const parseDefault: (s: RootedRuntimeState) => ParsedDefaultableProperty;
export type parseDefault<root, unscanned extends string> = trim<unscanned> extends infer defaultExpression extends string ? defaultExpression extends UnenclosedUnitLiteral ? [
root,
"=",
defaultValue
] : ErrorMessage<writeNonLiteralDefaultMessage<trim<unscanned>>>;
defaultExpression
] : defaultExpression extends (`${infer start extends EnclosingLiteralStartToken}${string}`) ? defaultExpression extends `${start}${infer nextUnscanned}` ? isValidEnclosedLiteral<start, nextUnscanned> extends true ? [
root,
"=",
defaultExpression
] : ErrorMessage<writeNonLiteralDefaultMessage<defaultExpression>> : never : ErrorMessage<writeNonLiteralDefaultMessage<defaultExpression>> : never;
export type isValidEnclosedLiteral<start extends EnclosingLiteralStartToken, unscanned extends string> = Scanner.shiftUntilEscapable<unscanned, EnclosingLiteralTokens[start], ""> extends Scanner.shiftResult<string, infer nextUnscanned> ? nextUnscanned extends EnclosingLiteralTokens[start] ? true : false : false;
export declare const writeNonLiteralDefaultMessage: <defaultDef extends string>(defaultDef: defaultDef) => writeNonLiteralDefaultMessage<defaultDef>;
export type writeNonLiteralDefaultMessage<defaultDef extends string> = `Default value '${defaultDef}' must a literal value`;
export type writeNonLiteralDefaultMessage<defaultDef extends string> = `Default value '${defaultDef}' must be a literal value`;
export {};

@@ -15,2 +15,2 @@ export const parseDefault = (s) => {

};
export const writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must a literal value`;
export const writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must be a literal value`;

@@ -1,7 +0,8 @@

import type { DynamicStateWithRoot } from "../../reduce/dynamic.ts";
import type { StaticState, state } from "../../reduce/static.ts";
import type { ArkTypeScanner } from "../scanner.ts";
export declare const parseDivisor: (s: DynamicStateWithRoot) => void;
export type parseDivisor<s extends StaticState, unscanned extends string> = ArkTypeScanner.shiftUntilNextTerminator<ArkTypeScanner.skipWhitespace<unscanned>> extends ArkTypeScanner.shiftResult<infer scanned, infer nextUnscanned> ? scanned extends `${infer divisor extends number}` ? divisor extends 0 ? state.error<writeInvalidDivisorMessage<0>> : state.setRoot<s, [s["root"], "%", divisor], nextUnscanned> : state.error<writeInvalidDivisorMessage<scanned>> : never;
import { type Scanner } from "@ark/util";
import type { RootedRuntimeState } from "../../reduce/dynamic.ts";
import type { StaticState, s } from "../../reduce/static.ts";
import { type TerminatingChar } from "../tokens.ts";
export declare const parseDivisor: (s: RootedRuntimeState) => void;
export type parseDivisor<s extends StaticState, unscanned extends string> = Scanner.shiftUntil<Scanner.skipWhitespace<unscanned>, TerminatingChar> extends Scanner.shiftResult<infer scanned, infer nextUnscanned> ? scanned extends `${infer divisor extends number}` ? divisor extends 0 ? s.error<writeInvalidDivisorMessage<0>> : s.setRoot<s, [s["root"], "%", divisor], nextUnscanned> : s.error<writeInvalidDivisorMessage<scanned>> : never;
export declare const writeInvalidDivisorMessage: <divisor extends string | number>(divisor: divisor) => writeInvalidDivisorMessage<divisor>;
export type writeInvalidDivisorMessage<divisor extends string | number> = `% operator must be followed by a non-zero integer literal (was ${divisor})`;
import { tryParseInteger } from "@ark/util";
import { terminatingChars } from "../tokens.js";
export const parseDivisor = (s) => {
const divisorToken = s.scanner.shiftUntilNextTerminator();
s.scanner.shiftUntilNonWhitespace();
const divisorToken = s.scanner.shiftUntilLookahead(terminatingChars);
const divisor = tryParseInteger(divisorToken, {

@@ -5,0 +7,0 @@ errorOnFail: writeInvalidDivisorMessage(divisorToken)

@@ -1,10 +0,10 @@

import { type WhitespaceChar } from "@ark/util";
import type { DynamicStateWithRoot } from "../../reduce/dynamic.ts";
import type { StaticState, state } from "../../reduce/static.ts";
import { ArkTypeScanner } from "../scanner.ts";
import { type Scanner, type WhitespaceChar } from "@ark/util";
import type { RootedRuntimeState } from "../../reduce/dynamic.ts";
import type { StaticState, s } from "../../reduce/static.ts";
import { lookaheadIsFinalizing, type FinalizingLookahead } from "../tokens.ts";
import { parseBound, type ComparatorStartChar } from "./bounds.ts";
import { parseBrand } from "./brand.ts";
import { parseDivisor } from "./divisor.ts";
export declare const parseOperator: (s: DynamicStateWithRoot) => void;
export type parseOperator<s extends StaticState, $, args> = s["unscanned"] extends (ArkTypeScanner.shift<infer lookahead, infer unscanned>) ? lookahead extends "[" ? unscanned extends ArkTypeScanner.shift<"]", infer nextUnscanned> ? state.setRoot<s, [s["root"], "[]"], nextUnscanned> : state.error<incompleteArrayTokenMessage> : lookahead extends "|" ? unscanned extends ArkTypeScanner.shift<">", infer nextUnscanned> ? state.reduceBranch<s, "|>", nextUnscanned> : state.reduceBranch<s, lookahead, unscanned> : lookahead extends "&" ? state.reduceBranch<s, lookahead, unscanned> : lookahead extends ")" ? state.finalizeGroup<s, unscanned> : ArkTypeScanner.lookaheadIsFinalizing<lookahead, unscanned> extends true ? state.finalize<state.scanTo<s, unscanned>, lookahead & ArkTypeScanner.FinalizingLookahead> : lookahead extends ComparatorStartChar ? parseBound<s, lookahead, unscanned, $, args> : lookahead extends "%" ? parseDivisor<s, unscanned> : lookahead extends "#" ? parseBrand<s, unscanned> : lookahead extends WhitespaceChar ? parseOperator<state.scanTo<s, unscanned>, $, args> : state.error<writeUnexpectedCharacterMessage<lookahead>> : state.finalize<s, "">;
export declare const parseOperator: (s: RootedRuntimeState) => void;
export type parseOperator<s extends StaticState, $, args> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "[" ? unscanned extends Scanner.shift<"]", infer nextUnscanned> ? s.setRoot<s, [s["root"], "[]"], nextUnscanned> : s.error<incompleteArrayTokenMessage> : lookahead extends "|" ? unscanned extends Scanner.shift<">", infer nextUnscanned> ? s.reduceBranch<s, "|>", nextUnscanned> : s.reduceBranch<s, lookahead, unscanned> : lookahead extends "&" ? s.reduceBranch<s, lookahead, unscanned> : lookahead extends ")" ? s.finalizeGroup<s, unscanned> : lookaheadIsFinalizing<lookahead, unscanned> extends true ? s.finalize<s.scanTo<s, unscanned>, lookahead & FinalizingLookahead> : lookahead extends ComparatorStartChar ? parseBound<s, lookahead, unscanned, $, args> : lookahead extends "%" ? parseDivisor<s, unscanned> : lookahead extends "#" ? parseBrand<s, unscanned> : lookahead extends WhitespaceChar ? parseOperator<s.scanTo<s, unscanned>, $, args> : s.error<writeUnexpectedCharacterMessage<lookahead>> : s.finalize<s, "">;
export declare const writeUnexpectedCharacterMessage: <char extends string, shouldBe extends string>(char: char, shouldBe?: shouldBe) => writeUnexpectedCharacterMessage<char, shouldBe>;

@@ -11,0 +11,0 @@ export type writeUnexpectedCharacterMessage<char extends string, shouldBe extends string = ""> = `'${char}' is not allowed here${shouldBe extends "" ? "" : ` (should be ${shouldBe})`}`;

import { isKeyOf, whitespaceChars } from "@ark/util";
import { ArkTypeScanner } from "../scanner.js";
import { lookaheadIsFinalizing } from "../tokens.js";
import { comparatorStartChars, parseBound } from "./bounds.js";

@@ -19,3 +19,3 @@ import { parseBrand } from "./brand.js";

: lookahead === ")" ? s.finalizeGroup()
: ArkTypeScanner.lookaheadIsFinalizing(lookahead, s.scanner.unscanned) ?
: lookaheadIsFinalizing(lookahead, s.scanner.unscanned) ?
s.finalize(lookahead)

@@ -22,0 +22,0 @@ : isKeyOf(lookahead, comparatorStartChars) ? parseBound(s, lookahead)

@@ -6,5 +6,5 @@ import type { BaseParseContext, resolvableReferenceIn } from "@ark/schema";

import type { inferAstRoot } from "./ast/infer.ts";
import { DynamicState, type DynamicStateWithRoot } from "./reduce/dynamic.ts";
import { RuntimeState, type RootedRuntimeState } from "./reduce/dynamic.ts";
import type { StringifiablePrefixOperator } from "./reduce/shared.ts";
import type { state, StaticState } from "./reduce/static.ts";
import type { s, StaticState } from "./reduce/static.ts";
import type { parseOperand } from "./shift/operand/operand.ts";

@@ -21,12 +21,12 @@ import { parseDefault } from "./shift/operator/default.ts";

"[]"
] : fullStringParse<state.initialize<def>, $, args> : fullStringParse<state.initialize<def>, $, args>;
] : fullStringParse<s.initialize<def>, $, args> : fullStringParse<s.initialize<def>, $, args>;
export type inferString<def extends string, $, args> = inferAstRoot<parseString<def, $, args>, $, args>;
export type BaseCompletions<$, args, otherSuggestions extends string = never> = resolvableReferenceIn<$> | resolvableReferenceIn<ArkAmbient.$> | (keyof args & string) | StringifiablePrefixOperator | otherSuggestions;
export declare const fullStringParse: (s: DynamicState) => InnerParseResult;
export declare const fullStringParse: (s: RuntimeState) => InnerParseResult;
type fullStringParse<s extends StaticState, $, args> = extractFinalizedResult<parseUntilFinalizer<s, $, args>>;
export declare const parseUntilFinalizer: (s: DynamicState) => DynamicStateWithRoot;
export declare const parseUntilFinalizer: (s: RuntimeState) => RootedRuntimeState;
export type parseUntilFinalizer<s extends StaticState, $, args> = s["finalizer"] extends undefined ? parseUntilFinalizer<next<s, $, args>, $, args> : s;
declare const next: (s: DynamicState) => void;
declare const next: (s: RuntimeState) => void;
type next<s extends StaticState, $, args> = s["root"] extends undefined ? parseOperand<s, $, args> : parseOperator<s, $, args>;
export type extractFinalizedResult<s extends StaticState> = s["finalizer"] extends "" ? s["root"] : s["finalizer"] extends ErrorMessage ? s["finalizer"] : s["finalizer"] extends "?" ? [s["root"], "?"] : s["finalizer"] extends "=" ? parseDefault<s["root"], s["unscanned"]> : ErrorMessage<writeUnexpectedCharacterMessage<s["finalizer"] & string>>;
export {};

@@ -1,6 +0,5 @@

import { throwInternalError, throwParseError } from "@ark/util";
import { DynamicState } from "./reduce/dynamic.js";
import { Scanner, throwInternalError, throwParseError } from "@ark/util";
import { RuntimeState } from "./reduce/dynamic.js";
import { parseDefault } from "./shift/operator/default.js";
import { writeUnexpectedCharacterMessage } from "./shift/operator/operator.js";
import { ArkTypeScanner } from "./shift/scanner.js";
export const parseString = (def, ctx) => {

@@ -15,3 +14,3 @@ const aliasResolution = ctx.$.maybeResolveRoot(def);

}
const s = new DynamicState(new ArkTypeScanner(def), ctx);
const s = new RuntimeState(new Scanner(def), ctx);
const node = fullStringParse(s);

@@ -18,0 +17,0 @@ if (s.finalizer === ">")

@@ -1,2 +0,2 @@

import { type BaseParseContext, type BaseRoot, type Morph, type Predicate, type TypeMeta, type unwrapDefault } from "@ark/schema";
import { type BaseParseContext, type BaseRoot, type Morph, type NodeSelector, type Predicate, type TypeMeta, type unwrapDefault } from "@ark/schema";
import { type array, type BuiltinObjectKind, type Constructor, type Domain, type show } from "@ark/util";

@@ -7,3 +7,3 @@ import type { defaultFor, distill, inferIntersection, inferMorphOut, inferPipe, inferPredicate, Out, withDefault } from "../attributes.ts";

import { writeMissingRightOperandMessage } from "./shift/operand/unenclosed.ts";
import type { ArkTypeScanner } from "./shift/scanner.ts";
import type { InfixToken } from "./shift/tokens.ts";
import type { BaseCompletions } from "./string.ts";

@@ -20,3 +20,4 @@ export declare const maybeParseTupleExpression: (def: array, ctx: BaseParseContext) => BaseRoot | null;

def["length"] extends 2 ? writeMissingRightOperandMessage<def[1]> : def[1],
def[1] extends "|" ? validateDefinition<def[2], $, args> : def[1] extends "&" ? validateDefinition<def[2], $, args> : def[1] extends ":" ? Predicate<type.infer.Out<def[0], $, args>> : def[1] extends "=>" ? Morph<type.infer.Out<def[0], $, args>> : def[1] extends "|>" ? validateDefinition<def[2], $, args> : def[1] extends "=" ? defaultFor<type.infer.In<def[0], $, args>> : def[1] extends "@" ? TypeMeta.MappableInput : validateDefinition<def[2], $, args>
def[1] extends "|" ? validateDefinition<def[2], $, args> : def[1] extends "&" ? validateDefinition<def[2], $, args> : def[1] extends ":" ? Predicate<type.infer.Out<def[0], $, args>> : def[1] extends "=>" ? Morph<type.infer.Out<def[0], $, args>> : def[1] extends "|>" ? validateDefinition<def[2], $, args> : def[1] extends "=" ? defaultFor<type.infer.In<def[0], $, args>> : def[1] extends "@" ? TypeMeta.MappableInput : validateDefinition<def[2], $, args>,
...(def[1] extends "@" ? [NodeSelector?] : [])
];

@@ -67,7 +68,3 @@ export type UnparsedTupleExpressionInput = {

export type IndexOneOperator = keyof typeof indexOneParsers;
export type InfixExpression = readonly [
unknown,
ArkTypeScanner.InfixToken,
...unknown[]
];
export type InfixExpression = readonly [unknown, InfixToken, ...unknown[]];
type IndexZeroParser<token extends string> = (def: IndexZeroExpression<token>, ctx: BaseParseContext) => BaseRoot;

@@ -74,0 +71,0 @@ type IndexZeroExpression<token extends string = IndexZeroOperator> = readonly [

@@ -37,3 +37,3 @@ import { Disjoint, intersectNodesRoot, pipeNodesRoot } from "@ark/schema";

};
const parseAttributeTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configureReferences(def[2], "shallow");
const parseMetaTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configure(def[2], def[3]);
const defineIndexOneParsers = (parsers) => parsers;

@@ -50,3 +50,3 @@ const postfixParsers = defineIndexOneParsers({

"|>": parseBranchTuple,
"@": parseAttributeTuple,
"@": parseMetaTuple,
// since object and tuple literals parse there via `parseProperty`,

@@ -53,0 +53,0 @@ // they must be shallow if parsed directly as a tuple expression

import { BaseScope, type AliasDefEntry, type ArkSchemaRegistry, type ArkSchemaScopeConfig, type BaseNode, type BaseParseContext, type BaseParseContextInput, type BaseParseOptions, type BaseRoot, type GenericAst, type GenericParamAst, type GenericParamDef, type NodeKind, type NodeSchema, type PreparsedNodeResolution, type PrivateDeclaration, type RootKind, type RootSchema, type arkKind, type exportedNameOf, type nodeOfKind, type reducibleKindOf, type toInternalScope, type writeDuplicateAliasError } from "@ark/schema";
import { type Brand, type ErrorType, type JsonStructure, type anyOrNever, type array, type flattenListable, type noSuggest } from "@ark/util";
import type { DeclarationParser } from "./declare.ts";
import { InternalFnParser, type FnParser } from "./fn.ts";
import { type GenericDeclaration, type GenericParser, type ParameterString, type baseGenericConstraints, type parseGenericParams, type parseValidGenericParams } from "./generic.ts";

@@ -12,3 +14,3 @@ import type { Ark, type } from "./keywords/keywords.ts";

import type { ParsedDefaultableProperty } from "./parser/shift/operator/default.ts";
import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type EnumeratedTypeParser, type InstanceOfTypeParser, type SchemaParser, type TypeParser, type UnitTypeParser, type ValueOfTypeParser } from "./type.ts";
import { InternalTypeParser, type DefinitionParser, type EnumeratedTypeParser, type InstanceOfTypeParser, type SchemaParser, type TypeParser, type UnitTypeParser, type ValueOfTypeParser } from "./type.ts";
/** The convenience properties attached to `scope` */

@@ -87,2 +89,3 @@ export type ScopeParserAttachments = Omit<ScopeParser, never>;

pipe: NaryPipeParser<$>;
fn: InternalFnParser;
match: InternalMatchParser;

@@ -123,2 +126,3 @@ declare: () => {

match: MatchParser<$>;
fn: FnParser<$>;
declare: DeclarationParser<$>;

@@ -125,0 +129,0 @@ define: DefinitionParser<$>;

import { $ark, BaseScope, hasArkKind, parseGeneric } from "@ark/schema";
import { enumValues, flatMorph, isArray, isThunk, throwParseError } from "@ark/util";
import { Scanner, enumValues, flatMorph, isArray, isThunk, throwParseError } from "@ark/util";
import { InternalFnParser } from "./fn.js";
import { parseGenericParamName } from "./generic.js";

@@ -7,3 +8,2 @@ import { InternalMatchParser } from "./match.js";

import { parseInnerDefinition } from "./parser/definition.js";
import { ArkTypeScanner } from "./parser/shift/scanner.js";
import { InternalTypeParser } from "./type.js";

@@ -50,3 +50,3 @@ export const $arkTypeRegistry = $ark;

parseGenericParams(def, opts) {
return parseGenericParamName(new ArkTypeScanner(def), [], this.createParseContext({
return parseGenericParamName(new Scanner(def), [], this.createParseContext({
...opts,

@@ -93,2 +93,3 @@ def,

pipe = (...morphs) => this.intrinsic.unknown.pipe(...morphs);
fn = new InternalFnParser(this);
match = new InternalMatchParser(this);

@@ -95,0 +96,0 @@ declare = () => ({

@@ -1,13 +0,14 @@

import { ArkErrors, BaseRoot, type BaseParseOptions, type Morph, type Predicate, type RootSchema, type TypeMeta } from "@ark/schema";
import { ArkErrors, BaseRoot, type BaseParseOptions, type Morph, type NodeSelector, type Predicate, type RootSchema, type TypeMeta } from "@ark/schema";
import { Callable, Hkt, type Constructor, type array, type conform } from "@ark/util";
import type { distill } from "./attributes.ts";
import type { DeclarationParser } from "./declare.ts";
import type { FnParser } from "./fn.ts";
import type { Generic, GenericParser, ParameterString, baseGenericConstraints, parseValidGenericParams, validateParameterString } from "./generic.ts";
import type { Ark, keywords, type } from "./keywords/keywords.ts";
import type { MatchParser } from "./match.ts";
import type { BaseType } from "./methods/base.ts";
import type { instantiateType } from "./methods/instantiate.ts";
import type { NaryIntersectionParser, NaryMergeParser, NaryPipeParser, NaryUnionParser } from "./nary.ts";
import type { validateDeclared } from "./parser/definition.ts";
import type { ArgTwoOperator, IndexZeroOperator, TupleInfixOperator } from "./parser/tupleExpressions.ts";
import type { InternalScope, ModuleParser, Scope, ScopeParser, bindThis } from "./scope.ts";
import type { InternalScope, ModuleParser, Scope, ScopeParser } from "./scope.ts";
import type { BaseType } from "./variants/base.ts";
import type { instantiateType } from "./variants/instantiate.ts";
/** The convenience properties attached to `type` */

@@ -41,3 +42,3 @@ export type TypeParserAttachments = Omit<TypeParser, never>;

*/
<const zero, const one, const rest extends array, r = type.instantiate<[zero, one, ...rest], $>>(_0: zero extends IndexZeroOperator ? zero : type.validate<zero, $>, _1: zero extends "keyof" ? type.validate<one, $> : zero extends "instanceof" ? conform<one, Constructor> : zero extends "===" ? conform<one, unknown> : conform<one, ArgTwoOperator>, ..._2: zero extends "===" ? rest : zero extends "instanceof" ? conform<rest, readonly Constructor[]> : one extends TupleInfixOperator ? one extends ":" ? [Predicate<distill.In<type.infer<zero, $>>>] : one extends "=>" ? [Morph<distill.Out<type.infer<zero, $>>, unknown>] : one extends "|>" ? [type.validate<rest[0], $>] : one extends "@" ? [TypeMeta.MappableInput] : [type.validate<rest[0], $>] : []): r extends infer _ ? _ : never;
<const zero, const one, const rest extends array, r = type.instantiate<[zero, one, ...rest], $>>(_0: zero extends IndexZeroOperator ? zero : type.validate<zero, $>, _1: zero extends "keyof" ? type.validate<one, $> : zero extends "instanceof" ? conform<one, Constructor> : zero extends "===" ? conform<one, unknown> : conform<one, ArgTwoOperator>, ..._2: zero extends "===" ? rest : zero extends "instanceof" ? conform<rest, readonly Constructor[]> : one extends TupleInfixOperator ? one extends ":" ? [Predicate<distill.In<type.infer<zero, $>>>] : one extends "=>" ? [Morph<distill.Out<type.infer<zero, $>>, unknown>] : one extends "|>" ? [type.validate<rest[0], $>] : one extends "@" ? [TypeMeta.MappableInput, NodeSelector?] : [type.validate<rest[0], $>] : []): r extends infer _ ? _ : never;
/**

@@ -51,3 +52,2 @@ * An alias of the {@link ArkErrors} class, an instance of which is returned when a {@link Type}

* if(out instanceof type.errors) console.log(out.summary)
*
*/

@@ -70,2 +70,3 @@ errors: typeof ArkErrors;

define: DefinitionParser<$>;
declare: DeclarationParser<$>;
generic: GenericParser<$>;

@@ -124,2 +125,12 @@ match: MatchParser<$>;

pipe: NaryPipeParser<$>;
/**
* Define a validated function
* @example
* const len = type.fn("string | unknown[]", ":", "number")(s => s.length)
* len("foo") // 3
* // TypeScript: boolean is not assignable to string | unknown[]
* // Runtime (throws): must be a string or an object (was boolean)
* len(true)
*/
fn: FnParser<$>;
}

@@ -129,5 +140,2 @@ export declare class InternalTypeParser extends Callable<(...args: unknown[]) => BaseRoot | Generic, TypeParserAttachments> {

}
export type DeclarationParser<$> = <preinferred>() => {
type: <const def>(def: validateDeclared<preinferred, def, $, bindThis<def>>) => Type<preinferred, $>;
};
export type UnitTypeParser<$> = <const t>(value: t) => Type<t, $>;

@@ -134,0 +142,0 @@ export type InstanceOfTypeParser<$> = <const t extends object>(ctor: Constructor<t>) => Type<t, $>;

@@ -12,2 +12,3 @@ import { ArkErrors, BaseRoot, GenericRoot } from "@ark/schema";

scope: $.constructor.scope,
declare: $.declare,
define: $.define,

@@ -26,3 +27,4 @@ match: $.match,

merge: $.merge,
pipe: $.pipe
pipe: $.pipe,
fn: $.fn
},

@@ -51,3 +53,2 @@ // also won't be defined during bootstrapping

}, {
bind: $,
attach

@@ -54,0 +55,0 @@ });

{
"name": "arktype",
"description": "TypeScript's 1:1 validator, optimized from editor to runtime",
"version": "2.1.22",
"version": "2.1.23",
"license": "MIT",

@@ -37,4 +37,5 @@ "repository": {

"dependencies": {
"@ark/util": "0.49.0",
"@ark/schema": "0.49.0"
"@ark/util": "0.50.0",
"@ark/regex": "0.0.0",
"@ark/schema": "0.50.0"
},

@@ -41,0 +42,0 @@ "publishConfig": {

+23
-29

@@ -6,3 +6,3 @@ <h1 align="center">ArkType</h1>

It can be used to check external data like JSON payloads or form submissions at the boundaries of your code (similar to Zod or Yup).
It can be used to check external data like JSON payloads or forms at the boundaries of your code (similar to Zod or Yup).

@@ -54,11 +54,12 @@ <video

<tr>
<th>get-convex</th>
<th>inspatiallabs</th>
<th>sam-goodwin</th>
<th>inspatiallabs</th>
</tr>
<tr>
<td>
<a href="https://github.com/sam-goodwin"
<a href="https://github.com/get-convex"
><img
height="64px"
src="https://avatars.githubusercontent.com/sam-goodwin"
src="https://avatars.githubusercontent.com/get-convex"
/></a>

@@ -73,2 +74,9 @@ </td>

</td>
<td>
<a href="https://github.com/sam-goodwin"
><img
height="64px"
src="https://avatars.githubusercontent.com/sam-goodwin"
/></a>
</td>
</tr>

@@ -81,17 +89,10 @@ </table>

<tr>
<th>fubhy</th>
<th>tmm</th>
<th>mishushakov</th>
<th>mewhhaha</th>
<th>jahands</th>
<th>drwpwrs</th>
<th>Phalangers</th>
</tr>
<tr>
<td>
<a href="https://github.com/fubhy"
><img
height="64px"
src="https://avatars.githubusercontent.com/fubhy"
/></a>
</td>
<td>
<a href="https://github.com/tmm"

@@ -104,7 +105,2 @@ ><img

<td>
<a href="https://github.com/mishushakov"
><img height="64px" src="https://avatars.githubusercontent.com/mishushakov"
/></a>
</td>
<td>
<a href="https://github.com/mewhhaha"

@@ -116,3 +112,3 @@ ><img

</td>
<td>
<td>
<a href="https://github.com/jahands"

@@ -124,11 +120,2 @@ ><img

</td>
</tr>
<tr>
<th>drwpwrs</th>
<th>Phalangers</th>
<th>WilliamConnatser</th>
<th>JameEnder</th>
<th>tylim88</th>
</tr>
<tr>
<td>

@@ -148,2 +135,9 @@ <a href="https://github.com/drwpwrs"

</td>
</tr>
<tr>
<th>WilliamConnatser</th>
<th>JameEnder</th>
<th>tylim88</th>
</tr>
<tr>
<td>

@@ -163,3 +157,3 @@ <a href="https://github.com/WilliamConnatser"

</td>
<td>
<td>
<a href="https://github.com/tylim88"

@@ -166,0 +160,0 @@ ><img

import type { ExactLength, ExclusiveNumericRangeSchema, InclusiveNumericRangeSchema } from "@ark/schema";
import type { ObjectType } from "./object.ts";
interface Type<
/** @ts-ignore cast variance */
out t extends readonly unknown[] = readonly unknown[], $ = {}> extends ObjectType<t, $> {
atLeastLength(schema: InclusiveNumericRangeSchema): this;
atMostLength(schema: InclusiveNumericRangeSchema): this;
moreThanLength(schema: ExclusiveNumericRangeSchema): this;
lessThanLength(schema: ExclusiveNumericRangeSchema): this;
exactlyLength(schema: ExactLength.Schema): this;
}
export type { Type as ArrayType };
import type { BaseNode, BaseRoot, Disjoint, JsonSchema, NodeSelector, Predicate, StandardSchemaV1, ToJsonSchema, TypeMeta, UndeclaredKeyBehavior } from "@ark/schema";
import type { anyOrNever, array, Callable, ErrorMessage, inferred, JsonStructure, unset } from "@ark/util";
import type { defaultFor, distill, inferIntersection, inferPipe, InferredMorph, Out, To } from "../attributes.ts";
import type { ArkAmbient } from "../config.ts";
import type { type } from "../keywords/keywords.ts";
import type { NaryPipeParser } from "../nary.ts";
import type { Scope } from "../scope.ts";
import type { ArrayType } from "./array.ts";
import type { instantiateType } from "./instantiate.ts";
/** @ts-ignore cast variance */
export interface Inferred<out t = unknown, $ = {}> {
internal: BaseRoot;
[inferred]: t;
/**
* precompiled JS used to optimize validation
*
* ⚠️ will be `undefined` in [jitless](https://arktype.io/docs/configuration#jitless) mode
*/
precompilation: string | undefined;
/**
* generic parameter representing this Type
*
* 🥸 inference-only property that will be `undefined` at runtime
*
* ⚠️ May contain types representing morphs or default values that would
* be inaccurate if used directly for runtime values. In those cases,
* you should use {@link infer} or {@link inferIn} on this object instead.
*/
t: t;
/**
* #### {@link Scope} in which chained methods are parsed
*/
$: Scope<$>;
/**
* #### type of output this returns
*
* 🥸 inference-only property that will be `undefined` at runtime
*
* @example
* const parseNumber = type("string").pipe(s => Number.parseInt(s))
* type ParsedNumber = typeof parseNumber.infer // number
*/
infer: this["inferOut"];
/**
* type of output this returns
*
* 🔗 alias of {@link infer}
* 🥸 inference-only property that will be `undefined` at runtime
*
*
* @example
* const parseNumber = type("string").pipe(s => Number.parseInt(s))
* type ParsedNumber = typeof parseNumber.infer // number
*/
inferOut: distill.Out<t>;
/**
* type of output that can be introspected at runtime (e.g. via {@link out})
*
* ⚠️ If your Type contains morphs, they will be inferred as `unknown` unless
* they are an ArkType keyword or have an explicitly defined output validator.
*
* 🥸 inference-only property that will be `undefined` at runtime
*
* @example
* const Unmorphed = type("string")
* // with no morphs, we can introspect the input and output as a single Type
* type UnmorphedOut = typeof Unmorphed.inferIntrospectableOut // string
*
* const Morphed = type("string").pipe(s => s.length)
* // with a standard user-defined morph, TypeScript can infer a
* // return type from your function, but we have no way to
* // know the shape at runtime
* type MorphOut = typeof Morphed.inferIntrospectableOut // unknown
*
* const Validated = type("string").pipe(s => s.length).to("number")
* // morphs with validated output, including all morph keywords, are introspectable
* type ValidatedMorphOut = typeof Validated.inferIntrospectableOut
*/
inferIntrospectableOut: distill.introspectable.Out<t>;
/**
* #### type of input this allows
*
* 🥸 inference-only property that will be `undefined` at runtime
*
* @example
* const parseNumber = type("string").pipe(s => Number.parseInt(s))
* type UnparsedNumber = typeof parseNumber.inferIn // string
*/
inferIn: distill.In<t>;
/**
* #### internal JSON representation
*/
json: JsonStructure;
/**
* alias of {@link json} for `JSON.stringify` compatibility
*/
toJSON(): JsonStructure;
/**
* #### generate a JSON Schema
*
* @throws {ToJsonSchema.Error} if this cannot be converted to JSON Schema
*/
toJsonSchema(options?: ToJsonSchema.Options): JsonSchema;
/**
* #### metadata like custom descriptions and error messages
*
* ✅ type {@link https://arktype.io/docs/configuration#custom | can be customized} for your project
*/
meta: ArkAmbient.meta;
/**
* #### human-readable English description
*
* ✅ works best for primitive values
*
* @example
* const N = type("0 < number <= 100")
* console.log(N.description) // positive and at most 100
*/
description: string;
/**
* #### syntax string similar to native TypeScript
*
* ✅ works well for both primitives and structures
*
* @example
* const Loc = type({ coords: ["number", "number"] })
* console.log(Loc.expression) // { coords: [number, number] }
*/
expression: string;
/**
* #### validate and return transformed data or throw
*
* ✅ sugar to avoid checking for {@link type.errors} if they are unrecoverable
*
* @example
* const CriticalPayload = type({
* superImportantValue: "string"
* })
* // throws TraversalError: superImportantValue must be a string (was missing)
* const data = CriticalPayload.assert({ irrelevantValue: "whoops" })
* console.log(data.superImportantValue) // valid output can be accessed directly
*
* @throws {TraversalError}
*/
assert(data: unknown): this["infer"];
/**
* #### check input without applying morphs
*
* ✅ good for stuff like filtering that doesn't benefit from detailed errors
*
* @example
* const Numeric = type("number | bigint")
* // [0, 2n]
* const numerics = [0, "one", 2n].filter(Numeric.allows)
*/
allows(data: unknown): data is this["inferIn"];
/**
* #### add metadata to shallow references
*
* ⚠️ does not affect error messages within properties of an object
*
* @example
* const NotOdd = type("number % 2").configure({ description: "not odd" })
* // all constraints at the root are affected
* const odd = NotOdd(3) // must be not odd (was 3)
* const nonNumber = NotOdd("two") // must be not odd (was "two")
*
* const NotOddBox = type({
* // we should have referenced notOdd or added meta here
* notOdd: "number % 2",
* // but instead chained from the root object
* }).configure({ description: "not odd" })
* // error message at path notOdd is not affected
* const oddProp = NotOddBox({ notOdd: 3 }) // notOdd must be even (was 3)
* // error message at root is affected, leading to a misleading description
* const nonObject = NotOddBox(null) // must be not odd (was null)
*/
configure: NodeSelector.SelectableFn<TypeMeta.MappableInput, this>;
/**
* #### add description to shallow references
*
* 🔗 equivalent to `.configure({ description })` (see {@link configure})
* ⚠️ does not affect error messages within properties of an object
*
* @example
* const AToZ = type(/^a.*z$/).describe("a string like 'a...z'")
* const good = AToZ("alcatraz") // "alcatraz"
* // ArkErrors: must be a string like 'a...z' (was "albatross")
* const badPattern = AToZ("albatross")
*/
describe: NodeSelector.SelectableFn<string, this>;
/**
* #### apply undeclared key behavior
*
* - `"ignore"` (default) - allow and preserve extra properties
* - `"reject"` - disallow extra properties
* - `"delete"` - clone and remove extra properties from output
*/
onUndeclaredKey(behavior: UndeclaredKeyBehavior): this;
/**
* #### deeply apply undeclared key behavior
*
* - `"ignore"` (default) - allow and preserve extra properties
* - `"reject"` - disallow extra properties
* - `"delete"` - clone and remove extra properties from output
*/
onDeepUndeclaredKey(behavior: UndeclaredKeyBehavior): this;
/**
* #### alias for {@link assert} with typed input
*
* @example
* const T = type({ foo: "string" });
* // TypeScript: foo must be a string (was 5)
* const data = T.from({ foo: 5 });
*/
from(literal: this["inferIn"]): this["infer"];
/**
* #### deeply extract inputs
*
* ✅ will never include morphs
* ✅ good for generating JSON Schema or other non-transforming formats
*
* @example
* const User = type({
* age: "string.numeric.parse"
* })
* // { age: 25 } (age parsed to a number)
* const out = User({ age: "25" })
* // { age: "25" } (age is still a string)
* const inOut = User.in({ age: "25" })
*/
get in(): instantiateType<this["inferIn"], $>;
/**
* #### deeply extract outputs
*
* ✅ will never include morphs
* ⚠️ if your type includes morphs, their output will likely be unknown unless they
* were defined with an explicit output validator via `.to(outputDef)` or `.pipe(morph, outputType)`
*
* @example
* const join = type("string[]").pipe(a => a.join(","))
*
* const T = type({
* // all keywords have introspectable output
* keyword: "string.numeric.parse",
* // TypeScript knows this returns a string, but we can't introspect that at runtime
* unvalidated: join,
* // if needed, it can be made introspectable with an output validator
* validated: join.to("string")
* })
*
* // Type<{ keyword: number; unvalidated: unknown; validated: string }>
* const baseOut = base.out
*/
get out(): instantiateType<this["inferIntrospectableOut"], $>;
/**
* #### add a compile-time brand to output
*
* 🥸 inference-only function that does nothing runtime
*
* @example
* const Palindrome = type("string")
* .narrow(s => s === [...s].reverse().join(""))
* .brand("palindrome")
* // Brand<string, "palindrome">
* const out = Palindrome.assert("racecar")
*/
brand<const name extends string, r = instantiateType<type.brand<t, name>, $>>(name: name): r extends infer _ ? _ : never;
/**
* #### an array of this
*
* @example
* // Type<{ rebmun: number }[]>
* const T = type({ rebmun: "number" }).array();
*/
array(): ArrayType<t[], $>;
/**
* #### {@link https://arktype.io/docs/objects#properties-optional | optional definition}
*
* ⚠️ unlike most other methods, this creates a definition rather than a Type (read why)
*
* @example
* const Prop = type({ foo: "number" })
* // Type<{ bar?: { foo: number } }>
* const Obj = type({ bar: Prop.optional() })
*/
optional(): [this, "?"];
/**
* #### {@link https://arktype.io/docs/objects#properties-defaultable | defaultable definition}
*
* ✅ object defaults can be returned from a function
* ⚠️ throws if the default value is not allowed
* ⚠️ unlike most other methods, this creates a definition rather than a Type (read why)
*
* @example
* // Type<{ count: Default<number, 0> }>
* const State = type({ count: type.number.default(0) })
* const Prop = type({ nested: "boolean" })
* const ForObj = type({
* key: Prop.default(() => ({ nested: false }))
* })
*/
default<const value extends defaultFor<this["inferIn"]>>(value: value): [this, "=", value];
/**
* #### apply a predicate function to input
*
* ⚠️ the behavior of {@link narrow}, this method's output counterpart, is usually more desirable
* ✅ most useful for morphs with input types that are re-used externally
* 🥸 {@link https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates | Type predicates} can be used as casts
*
* @example
* const stringifyUser = type({ name: "string" }).pipe(user => JSON.stringify(user))
* const stringifySafe = stringifyUser.filter(user => user.name !== "Bobby Tables")
* // Type<(In: `${string}Z`) => To<Date>>
* const WithPredicate = type("string.date.parse").filter((s): s is `${string}Z` =>
* s.endsWith("Z")
* )
*/
filter<narrowed extends this["inferIn"] = never, r = instantiateType<[
narrowed
] extends [never] ? t : t extends InferredMorph<any, infer o> ? (In: narrowed) => o : narrowed, $>>(predicate: Predicate.Castable<this["inferIn"], narrowed>): r extends infer _ ? _ : never;
/**
* #### apply a predicate function to output
*
* ✅ go-to fallback for validation not composable via built-in types and operators
* ✅ runs after all other validators and morphs, if present
* 🥸 {@link https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates | Type predicates} can be used as casts
*
* @example
* const Palindrome = type("string").narrow(s => s === [...s].reverse().join(""))
*
* const PalindromicEmail = type("string.date.parse").narrow((date, ctx) =>
* date.getFullYear() === 2025 || ctx.mustBe("the current year")
* )
* // Type<`${string}.tsx`>
* const WithPredicate = type("string").narrow((s): s is `${string}.tsx` => /\.tsx?$/.test(s))
*/
narrow<narrowed extends this["infer"] = never, r = instantiateType<[
narrowed
] extends [never] ? t : t extends InferredMorph<infer i, infer o> ? o extends To ? (In: i) => To<narrowed> : (In: i) => Out<narrowed> : narrowed, $>>(predicate: Predicate.Castable<this["infer"], narrowed>): r extends infer _ ? _ : never;
/**
* #### pipe output through arbitrary transformations or other Types
*
* @example
* const User = type({ name: "string" })
*
* // parse a string and validate that the result as a user
* const parseUser = type("string").pipe(s => JSON.parse(s), user)
*/
pipe: ChainedPipeParser<$, t>;
/**
* #### parse a definition as an output validator
*
* 🔗 `to({ name: "string" })` is equivalent to `.pipe(type({ name: "string" }))`
*
* @example
* // parse a string and validate that the result as a user
* const parseUser = type("string").pipe(s => JSON.parse(s)).to({ name: "string" })
*/
to<const def, r = instantiateType<inferPipe<t, type.infer<def, $>>, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
/**
* #### query internal node references
*
* @experimental filters and returns the Type's internal representation from `@ark/schema`
*
* @example
* // ["blue", "red"]
* const values = type("'red' | 'blue'").select("unit").map(u => u.unit)
*/
select: BaseNode["select"];
}
/** @ts-ignore cast variance */
interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => distill.Out<t> | ArkEnv.onFail>, Inferred<t, $> {
/**
* #### cast the way this is inferred
*
* 🥸 inference-only function that does nothing runtime
*
* @example
* // Type<`LEEEEEEEE${string}ROY`>
* const Leeroy = type(/^LE{8,}ROY$/).as<`LEEEEEEEE${string}ROY`>()
*/
as<castTo = unset>(...args: validateChainedAsArgs<castTo>): instantiateType<castTo, $>;
/**
* #### intersect the parsed Type, throwing if the result is unsatisfiable
*
* @example
* // Type<{ foo: number; bar: string }>
* const T = type({ foo: "number" }).and({ bar: "string" })
* // ParseError: Intersection at foo of number and string results in an unsatisfiable type
* const Bad = type({ foo: "number" }).and({ foo: "string" })
*/
and<const def, r = instantiateType<inferIntersection<t, type.infer<def, $>>, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
/**
* #### union with the parsed Type
*
* ⚠️ a union that could apply different morphs to the same data is a ParseError ({@link https://arktype.io/docs/expressions#union-morphs | docs})
*
* @example
* // Type<string | { box: string }>
* const T = type("string").or({ box: "string" })
*/
or<const def, r = instantiateType<t | type.infer<def, $>, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
/**
* #### intersect the parsed Type, returning an introspectable {@link Disjoint} if the result is unsatisfiable
*
* @example
* // Type<{ foo: number; bar: string }>
* const T = type({ foo: "number" }).intersect({ bar: "string" })
* const Bad = type("number > 10").intersect("number < 5")
* // logs "Intersection of > 10 and < 5 results in an unsatisfiable type"
* if (Bad instanceof Disjoint) console.log(`${bad.summary}`)
*/
intersect<const def, r = instantiateType<inferIntersection<t, type.infer<def, $>>, $>>(def: type.validate<def, $>): r extends infer _ ? _ | Disjoint : never;
/**
* #### check if the parsed Type's constraints are identical
*
* ✅ equal types have identical input and output constraints and transforms
* ✅ ignores associated {@link meta}, which does not affect the set of allowed values
*
* @example
* const DivisibleBy6 = type.number.divisibleBy(6).moreThan(0)
* // false (left side must also be positive)
* DivisibleBy6.equals("number % 6")
* // false (right side has an additional <100 constraint)
* console.log(DivisibleBy6.equals("0 < (number % 6) < 100"))
* const ThirdTry = type("(number % 2) > 0").divisibleBy(3)
* // true (types are normalized and reduced)
* console.log(DivisibleBy6.equals(ThirdTry))
*/
equals<const def>(def: type.validate<def, $>): boolean;
/**
* #### narrow this based on an {@link equals} check
*
* ✅ ignores associated {@link meta}, which does not affect the set of allowed values
*
* @example
* const N = type.raw(`${Math.random()}`)
* // Type<0.5> | undefined
* const Ez = N.ifEquals("0.5")
*/
ifEquals<const def, r = type.instantiate<def, $>>(def: type.validate<def, $>): r extends infer _ ? _ | undefined : never;
/**
* #### check if this is a subtype of the parsed Type
*
* ✅ a subtype must include all constraints from the base type
* ✅ unlike {@link equals}, additional constraints may be present
* ✅ ignores associated {@link meta}, which does not affect the set of allowed values
*
* @example
* type.string.extends("unknown") // true
* type.string.extends(/^a.*z$/) // false
*/
extends<const def>(other: type.validate<def, $>): boolean;
/**
* #### narrow this based on an {@link extends} check
*
* ✅ ignores associated {@link meta}, which does not affect the set of allowed values
*
* @example
* const N = type(Math.random() > 0.5 ? "true" : "0") // Type<0 | true>
* const Ez = N.ifExtends("boolean") // Type<true> | undefined
*/
ifExtends<const def, r = type.instantiate<def, $>>(other: type.validate<def, $>): r extends infer _ ? _ | undefined : never;
/**
* #### check if a value could satisfy this and the parsed Type
*
* ⚠️ will return true unless a {@link Disjoint} can be proven
*
* @example
* type.string.overlaps("string | number") // true (e.g. "foo")
* type("string | number").overlaps("1") // true (1)
* type("number > 0").overlaps("number < 0") // false (no values exist)
*
* const NoAt = type("string").narrow(s => !s.includes("@"))
* NoAt.overlaps("string.email") // true (no values exist, but not provable)
*/
overlaps<const def>(r: type.validate<def, $>): boolean;
/**
* #### extract branches {@link extend}ing the parsed Type
*
* @example
* // Type<true | 0 | 2>
* const T = type("boolean | 0 | 'one' | 2 | bigint").extract("number | 0n | true")
*/
extract<const def, r = instantiateType<t extends type.infer<def, $> ? t : never, $>>(r: type.validate<def, $>): r extends infer _ extends r ? _ : never;
/**
* #### exclude branches {@link extend}ing the parsed Type
*
* @example
*
* // Type<false | 'one' | bigint>
* const T = type("boolean | 0 | 'one' | 2 | bigint").exclude("number | 0n | true")
*/
exclude<const def, r = instantiateType<t extends type.infer<def, $> ? never : t, $>>(r: type.validate<def, $>): r extends infer _ ? _ : never;
/**
* @experimental
* Map and optionally reduce branches of a union. Types that are not unions
* are treated as a single branch.
*
* @param mapBranch - the mapping function, accepting a branch Type
* Returning another `Type` is common, but any value can be returned and
* inferred as part of the output.
*
* @param [reduceMapped] - an operation to perform on the mapped branches
* Can be used to e.g. merge an array of returned Types representing
* branches back to a single union.
*/
distribute<mapOut, reduceOut = mapOut[]>(mapBranch: (branch: Type, i: number, branches: array<Type>) => mapOut, reduceMapped?: (mappedBranches: mapOut[]) => reduceOut): reduceOut;
/** The Type's [StandardSchema](https://github.com/standard-schema/standard-schema) properties */
"~standard": StandardSchemaV1.ArkTypeProps<this["inferIn"], this["inferOut"]>;
/** @deprecated */
apply: Function["apply"];
/** @deprecated */
bind: Function["bind"];
/** @deprecated */
call: Function["call"];
/** @deprecated */
caller: Function;
/** @deprecated */
length: number;
/** @deprecated */
name: string;
/** @deprecated */
prototype: Function["prototype"];
/** @deprecated */
arguments: Function["arguments"];
/** @deprecated */
Symbol: never;
}
export interface ChainedPipeParser<$, t> extends NaryPipeParser<$, t> {
try: NaryPipeParser<$, t>;
}
type validateChainedAsArgs<t> = [
t
] extends [unset] ? [
t
] extends [anyOrNever] ? [
] : [
ErrorMessage<"as requires an explicit type parameter like myType.as<t>()">
] : [];
export type { Type as BaseType };
import type { ExclusiveDateRangeSchema, InclusiveDateRangeSchema } from "@ark/schema";
import type { ObjectType } from "./object.ts";
/** @ts-ignore cast variance */
interface Type<out t extends globalThis.Date = globalThis.Date, $ = {}> extends ObjectType<t, $> {
atOrAfter(schema: InclusiveDateRangeSchema): this;
atOrBefore(schema: InclusiveDateRangeSchema): this;
laterThan(schema: ExclusiveDateRangeSchema): this;
earlierThan(schema: ExclusiveDateRangeSchema): this;
}
export type { Type as DateType };
import type { anyOrNever, array } from "@ark/util";
import type { ArrayType } from "./array.ts";
import type { BaseType } from "./base.ts";
import type { DateType } from "./date.ts";
import type { NumberType } from "./number.ts";
import type { ObjectType } from "./object.ts";
import type { StringType } from "./string.ts";
export type instantiateType<t, $> = [
t
] extends [anyOrNever] ? BaseType<t, $> : [t] extends [object] ? [
t
] extends [array] ? ArrayType<t, $> : [t] extends [Date] ? DateType<t, $> : ObjectType<t, $> : [t] extends [string] ? StringType<t, $> : [t] extends [number] ? NumberType<t, $> : BaseType<t, $>;
import type { Divisor, ExclusiveNumericRangeSchema, InclusiveNumericRangeSchema } from "@ark/schema";
import type { BaseType } from "./base.ts";
/** @ts-ignore cast variance */
interface Type<out t extends number = number, $ = {}> extends BaseType<t, $> {
divisibleBy(schema: Divisor.Schema): this;
atLeast(schema: InclusiveNumericRangeSchema): this;
atMost(schema: InclusiveNumericRangeSchema): this;
moreThan(schema: ExclusiveNumericRangeSchema): this;
lessThan(schema: ExclusiveNumericRangeSchema): this;
}
export type { Type as NumberType };
import type { BaseMappedPropInner, OptionalMappedPropInner, Prop } from "@ark/schema";
import type { arkGet, arkIndexableOf, arkKeyOf, array, ErrorType, inferred, intersectUnion, JsonStructure, Key, listable, merge, optionalKeyOf, show, toArkKey } from "@ark/util";
import type { Default, withDefault } from "../attributes.ts";
import type { type } from "../keywords/keywords.ts";
import type { ArrayType } from "./array.ts";
import type { BaseType } from "./base.ts";
import type { instantiateType } from "./instantiate.ts";
/** @ts-ignore cast variance */
interface Type<out t extends object = object, $ = {}> extends BaseType<t, $> {
readonly(): t extends array ? ArrayType<{
readonly [i in keyof t]: t[i];
}, $> : Type<{
readonly [k in keyof t]: t[k];
}, $>;
keyof(): instantiateType<arkKeyOf<t>, $>;
/**
* Get the `Type` of a property of this `Type<object>`.
* @example type({ foo: "string" }).get("foo") // Type<string>
*/
get<const k1 extends arkIndexableOf<t>, r = instantiateType<arkGet<t, k1>, $>>(k1: k1 | type.cast<k1>): r extends infer _ ? _ : never;
get<const k1 extends arkIndexableOf<t>, const k2 extends arkIndexableOf<arkGet<t, k1>>, r = instantiateType<arkGet<arkGet<t, k1>, k2>, $>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>): r extends infer _ ? _ : never;
get<const k1 extends arkIndexableOf<t>, const k2 extends arkIndexableOf<arkGet<t, k1>>, const k3 extends arkIndexableOf<arkGet<arkGet<t, k1>, k2>>, r = instantiateType<arkGet<arkGet<arkGet<t, k1>, k2>, k3>, $>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>, k3: k3 | type.cast<k3>): r extends infer _ ? _ : never;
/**
* Create a copy of this `Type` with only the specified properties.
* @example type({ foo: "string", bar: "number" }).pick("foo") // Type<{ foo: string }>
*/
pick<const key extends arkKeyOf<t> = never>(...keys: (key | type.cast<key>)[]): Type<{
[k in keyof t as Extract<toArkKey<t, k>, key>]: t[k];
}, $>;
/**
* Create a copy of this `Type` with all properties except the specified ones.
* @example type({ foo: "string", bar: "number" }).omit("foo") // Type<{ bar: number }>
*/
omit<const key extends arkKeyOf<t> = never>(...keys: (key | type.cast<key>)[]): Type<{
[k in keyof t as Exclude<toArkKey<t, k>, key>]: t[k];
}, $>;
/**
* Merge another `Type` definition, overriding properties of this `Type` with the duplicate keys.
* @example type({ a: "1", b: "2" }).merge({ b: "3", c: "4" }) // Type<{ a: 1, b: 3, c: 4 }>
*/
merge<const def, inferredDef = type.infer<def, $>, r = Type<merge<t, inferredDef>, $>>(def: type.validate<def, $> & (inferredDef extends object ? unknown : ErrorType<NonObjectMergeErrorMessage, [actual: inferredDef]>)): r extends infer _ ? _ : never;
/**
* Create a copy of this `Type` with all properties required.
* @example const T = type({ "foo?"": "string" }).required() // Type<{ foo: string }>
*/
required(): Type<{
[k in keyof t]-?: t[k];
}, $>;
/**
* Create a copy of this `Type` with all properties optional.
* @example: const T = type({ foo: "string" }).optional() // Type<{ foo?: string }>
*/
partial(): Type<{
[k in keyof t]?: t[k];
}, $>;
map<transformed extends listable<MappedTypeProp>, r = Type<constructMapped<t, transformed>, $>>(flatMapEntry: (entry: typePropOf<t, $>) => transformed): r extends infer _ ? _ : never;
/**
* List of property info of this `Type<object>`.
* @example type({ foo: "string = "" }).props // [{ kind: "required", key: "foo", value: Type<string>, default: "" }]
*/
props: array<typePropOf<t, $>>;
}
type typePropOf<o, $> = keyof o extends infer k ? k extends keyof o ? typeProp<o, k, $> : never : never;
type typeProp<o, k extends keyof o, $, t = o[k] & ({} | null)> = t extends Default<infer t, infer defaultValue> ? DefaultedTypeProp<k & Key, t, defaultValue, $> : BaseTypeProp<k extends optionalKeyOf<o> ? "optional" : "required", k & Key, t, $>;
export interface BaseTypeProp<kind extends Prop.Kind = Prop.Kind, k extends Key = Key,
/** @ts-ignore cast variance */
out v = unknown, $ = {}> {
kind: kind;
key: k;
value: instantiateType<v, $>;
meta: ArkEnv.meta;
toJSON: () => JsonStructure;
}
export interface DefaultedTypeProp<k extends Key = Key, v = unknown, defaultValue = v, $ = {}> extends BaseTypeProp<"optional", k, v, $> {
default: defaultValue;
}
type MappedTypeProp<k extends Key = Key, v = unknown> = BaseMappedTypeProp<k, v> | OptionalMappedTypeProp<k, v>;
type BaseMappedTypeProp<k extends Key, v> = merge<BaseMappedPropInner, {
key: k;
value: type.cast<v>;
}>;
type OptionalMappedTypeProp<k extends Key, v> = merge<OptionalMappedPropInner, {
key: k;
value: type.cast<v>;
default?: v;
}>;
type constructMapped<t, transformed extends listable<MappedTypeProp>> = show<intersectUnion<fromTypeProps<t, transformed extends array ? transformed : [transformed]>>>;
type fromTypeProps<t, props extends array<MappedTypeProp>> = show<{
[prop in props[number] as Extract<applyHomomorphicOptionality<t, prop>, {
kind: "required";
}>["key"]]: prop["value"][inferred];
} & {
[prop in props[number] as Extract<applyHomomorphicOptionality<t, prop>, {
kind: "optional";
default?: never;
}>["key"]]?: prop["value"][inferred];
} & {
[prop in props[number] as Extract<applyHomomorphicOptionality<t, prop>, {
kind: "optional";
default: unknown;
}>["key"]]: withDefault<prop["value"][inferred], prop["default" & keyof prop]>;
}>;
export type NonObjectMergeErrorMessage = "Merged type must be an object";
type applyHomomorphicOptionality<t, prop extends MappedTypeProp> = prop["kind"] extends string ? prop : prop & {
kind: prop["key"] extends optionalKeyOf<t> ? "optional" : "required";
};
export type { Type as ObjectType };
import type { ExactLength, ExclusiveNumericRangeSchema, InclusiveNumericRangeSchema, Pattern } from "@ark/schema";
import type { BaseType } from "./base.ts";
/** @ts-ignore cast variance */
interface Type<out t extends string = string, $ = {}> extends BaseType<t, $> {
matching(schema: Pattern.Schema): this;
atLeastLength(schema: InclusiveNumericRangeSchema): this;
atMostLength(schema: InclusiveNumericRangeSchema): this;
moreThanLength(schema: ExclusiveNumericRangeSchema): this;
lessThanLength(schema: ExclusiveNumericRangeSchema): this;
exactlyLength(schema: ExactLength.Schema): this;
}
export type { Type as StringType };
import { Scanner, type EscapeChar, type WhitespaceChar } from "@ark/util";
import type { Comparator } from "../reduce/shared.ts";
export declare class ArkTypeScanner<lookahead extends string = string> extends Scanner<lookahead> {
shiftUntilNextTerminator(): string;
static terminatingChars: {
readonly " ": 1;
readonly "\n": 1;
readonly "\t": 1;
readonly "<": 1;
readonly ">": 1;
readonly "=": 1;
readonly "|": 1;
readonly "&": 1;
readonly ")": 1;
readonly "[": 1;
readonly "%": 1;
readonly ",": 1;
readonly ":": 1;
readonly "?": 1;
readonly "#": 1;
};
static finalizingLookaheads: {
readonly ">": 1;
readonly ",": 1;
readonly "": 1;
readonly "=": 1;
readonly "?": 1;
};
static lookaheadIsFinalizing: (lookahead: string, unscanned: string) => lookahead is ">" | "," | "=" | "?";
}
export declare namespace ArkTypeScanner {
type lookaheadIsFinalizing<lookahead extends string, unscanned extends string> = lookahead extends ">" ? unscanned extends `=${infer nextUnscanned}` ? nextUnscanned extends `=${string}` ? true : false : ArkTypeScanner.skipWhitespace<unscanned> extends ("" | `${TerminatingChar}${string}`) ? true : false : lookahead extends "=" ? unscanned extends `=${string}` ? false : true : lookahead extends "," | "?" ? true : false;
type TerminatingChar = keyof typeof ArkTypeScanner.terminatingChars;
type FinalizingLookahead = keyof typeof ArkTypeScanner.finalizingLookaheads;
type InfixToken = Comparator | "|" | "&" | "%" | ":" | "=>" | "|>" | "#" | "@" | "=";
type PostfixToken = "[]" | "?";
type OperatorToken = InfixToken | PostfixToken;
type shift<lookahead extends string, unscanned extends string> = `${lookahead}${unscanned}`;
type shiftUntil<unscanned extends string, terminator extends string, scanned extends string = ""> = unscanned extends shift<infer lookahead, infer nextUnscanned> ? lookahead extends terminator ? scanned extends `${infer base}${EscapeChar}` ? shiftUntil<nextUnscanned, terminator, `${base}${lookahead}`> : [scanned, unscanned] : shiftUntil<nextUnscanned, terminator, `${scanned}${lookahead}`> : [scanned, ""];
type shiftUntilNot<unscanned extends string, nonTerminator extends string, scanned extends string = ""> = unscanned extends shift<infer lookahead, infer nextUnscanned> ? lookahead extends nonTerminator ? shiftUntilNot<nextUnscanned, nonTerminator, `${scanned}${lookahead}`> : [scanned, unscanned] : [scanned, ""];
type shiftUntilNextTerminator<unscanned extends string> = shiftUntil<unscanned, TerminatingChar>;
type skipWhitespace<unscanned extends string> = shiftUntilNot<unscanned, WhitespaceChar>[1];
type shiftResult<scanned extends string, unscanned extends string> = [
scanned,
unscanned
];
}
import { isKeyOf, Scanner, whitespaceChars } from "@ark/util";
export class ArkTypeScanner extends Scanner {
shiftUntilNextTerminator() {
this.shiftUntilNonWhitespace();
return this.shiftUntil(() => this.lookahead in ArkTypeScanner.terminatingChars);
}
static terminatingChars = {
"<": 1,
">": 1,
"=": 1,
"|": 1,
"&": 1,
")": 1,
"[": 1,
"%": 1,
",": 1,
":": 1,
"?": 1,
"#": 1,
...whitespaceChars
};
static finalizingLookaheads = {
">": 1,
",": 1,
"": 1,
"=": 1,
"?": 1
};
static lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">" ?
unscanned[0] === "=" ?
// >== would only occur in an expression like Array<number>==5
// otherwise, >= would only occur as part of a bound like number>=5
unscanned[1] === "="
// if > is the end of a generic instantiation, the next token will be
// an operator or the end of the string
: unscanned.trimStart() === "" ||
isKeyOf(unscanned.trimStart()[0], ArkTypeScanner.terminatingChars)
// "=" is a finalizer on its own (representing a default value),
// but not with a second "=" (an equality comparator)
: lookahead === "=" ? unscanned[0] !== "="
// "," and "?" are unambiguously finalizers
: lookahead === "," || lookahead === "?";
}