arktype 2.0.0-beta.0 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright 2023 ArkType
1
+ Copyright 2024 ArkType
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
4
 
package/out/ark.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { type Ark, type ArkErrors, type inferred } from "@ark/schema";
2
- import type { CastableBase } from "@ark/util";
2
+ import type { GenericHktParser } from "./generic.js";
3
3
  import type { MatchParser } from "./match.js";
4
4
  import type { Module } from "./module.js";
5
5
  import { type Scope } from "./scope.js";
6
- import type { DeclarationParser, DefinitionParser, Type, TypeParser } from "./type.js";
6
+ import type { DeclarationParser, DefinitionParser, TypeParser } from "./type.js";
7
7
  export declare const ambient: Scope<Ark>;
8
8
  export declare const ark: Module<Ark>;
9
9
  export declare const type: TypeParser<{}>;
@@ -12,13 +12,8 @@ export declare namespace type {
12
12
  [inferred]?: t;
13
13
  };
14
14
  type errors = ArkErrors;
15
- interface of<t, $ = {}> extends Type<t, $> {
16
- }
17
- interface infer<t extends Type<object>> extends CastableBase<t["infer"]> {
18
- }
19
- interface inferIn<t extends Type<object>> extends CastableBase<t["inferIn"]> {
20
- }
21
15
  }
16
+ export declare const generic: GenericHktParser<{}>;
22
17
  export declare const match: MatchParser<{}>;
23
18
  export declare const define: DefinitionParser<{}>;
24
19
  export declare const declare: DeclarationParser<{}>;
package/out/ark.js CHANGED
@@ -3,6 +3,7 @@ import { scope } from "./scope.js";
3
3
  export const ambient = scope(keywordNodes);
4
4
  export const ark = ambient.export();
5
5
  export const type = ambient.type;
6
+ export const generic = ambient.generic;
6
7
  export const match = ambient.match;
7
8
  export const define = ambient.define;
8
9
  export const declare = ambient.declare;
package/out/generic.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { GenericParamAst, GenericParamDef, GenericRoot, writeUnsatisfiedParameterConstraintMessage } from "@ark/schema";
2
- import { type array, type Callable, type conform, type ErrorMessage, type keyError, type typeToString, type WhiteSpaceToken } from "@ark/util";
1
+ import type { ConstrainedGenericParamDef, GenericHkt, GenericParamAst, GenericParamDef, GenericProps, GenericRoot, LazyGenericBody } from "@ark/schema";
2
+ import { type array, type Callable, type conform, type ErrorMessage, type ErrorType, type WhiteSpaceToken } from "@ark/util";
3
3
  import type { inferDefinition } from "./parser/definition.js";
4
4
  import type { inferAstRoot } from "./parser/semantic/infer.js";
5
5
  import type { validateAst } from "./parser/semantic/validate.js";
@@ -10,18 +10,28 @@ import type { ParseContext } from "./scope.js";
10
10
  import type { inferTypeRoot, Type, validateTypeRoot } from "./type.js";
11
11
  export type ParameterString<params extends string = string> = `<${params}>`;
12
12
  export type extractParams<s extends ParameterString> = s extends ParameterString<infer params> ? params : never;
13
- export type validateParameterString<s extends ParameterString, $> = parseGenericParams<extractParams<s>, $> extends keyError<infer message> ? ErrorMessage<message> : s;
14
- export type validateGenericArg<param extends GenericParamAst, def, $> = validateTypeRoot<def, $> extends infer result ? result extends ErrorMessage ? result : inferTypeRoot<def, $> extends param[1] ? def : ErrorMessage<writeUnsatisfiedParameterConstraintMessage<param[0], typeToString<param[1]>, "">> : never;
15
- export type GenericInstantiation<params extends array<GenericParamAst> = array<GenericParamAst>, def = any, $ = any> = <const args>(...args: conform<args, {
16
- [i in keyof params]: validateGenericArg<params[i], args[i & keyof args], $>;
17
- }>) => Type<inferDefinition<def, $, bindGenericArgs<params, $, args>>, $>;
13
+ export type validateParameterString<s extends ParameterString, $> = parseGenericParams<extractParams<s>, $> extends infer e extends ErrorMessage ? e : s;
14
+ export type validateGenericArg<arg, param extends GenericParamAst, $> = inferTypeRoot<arg, $> extends param[1] ? arg : ErrorType<`Invalid argument for ${param[0]}`, [expected: param[1]]>;
15
+ export type GenericInstantiator<params extends array<GenericParamAst>, def, $, args$> = <const args extends {
16
+ [i in keyof params]: validateTypeRoot<args[i & keyof args], args$>;
17
+ }>(
18
+ /** @ts-expect-error treat as array */
19
+ ...args: {
20
+ [i in keyof args]: validateGenericArg<args[i], params[i & keyof params & `${number}`], args$>;
21
+ }) => Type<def extends GenericHkt ? GenericHkt.instantiate<def, {
22
+ [i in keyof args]: inferTypeRoot<args[i], args$>;
23
+ }> : inferDefinition<def, $, bindGenericArgs<params, args$, args>>, $>;
18
24
  type bindGenericArgs<params extends array<GenericParamAst>, $, args> = {
19
25
  [i in keyof params & `${number}` as params[i][0]]: inferTypeRoot<args[i & keyof args], $>;
20
26
  };
21
- export type baseGenericArgs<params extends array<GenericParamAst>> = {
27
+ type baseGenericResolutions<params extends array<GenericParamAst>, $> = baseGenericConstraints<params> extends infer baseConstraints ? {
28
+ [k in keyof baseConstraints]: Type<baseConstraints[k], $>;
29
+ } : never;
30
+ export type baseGenericConstraints<params extends array<GenericParamAst>> = {
22
31
  [i in keyof params & `${number}` as params[i][0]]: params[i][1];
23
32
  };
24
- export interface Generic<params extends array<GenericParamAst> = array<GenericParamAst>, bodyDef = unknown, $ = {}> extends Callable<GenericInstantiation<params, bodyDef, $>>, GenericRoot<params, bodyDef, $> {
33
+ export interface Generic<params extends array<GenericParamAst> = array<GenericParamAst>, bodyDef = unknown, $ = {}, args$ = $> extends Callable<GenericInstantiator<params, bodyDef, $, args$>>, GenericProps<params, bodyDef, $> {
34
+ internal: GenericRoot<params, bodyDef, $>;
25
35
  }
26
36
  export type GenericDeclaration<name extends string = string, params extends ParameterString = ParameterString> = `${name}${params}`;
27
37
  export type parseValidGenericParams<def extends ParameterString, $> = conform<parseGenericParams<extractParams<def>, $>, array<GenericParamAst>>;
@@ -40,15 +50,25 @@ declare const paramsTerminators: {
40
50
  type ParamsTerminator = keyof typeof paramsTerminators;
41
51
  declare const parseName: (scanner: Scanner, result: GenericParamDef[], ctx: ParseContext) => GenericParamDef[];
42
52
  type parseName<unscanned extends string, result extends array<GenericParamAst>, $> = parseNextNameChar<Scanner.skipWhitespace<unscanned>, "", result, $>;
43
- type parseNextNameChar<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = unscanned extends `${infer lookahead}${infer nextUnscanned}` ? lookahead extends ParamsTerminator ? name extends "" ? keyError<emptyGenericParameterMessage> : lookahead extends "," ? parseName<nextUnscanned, [...result, [name, unknown]], $> : lookahead extends ":" | WhiteSpaceToken ? _parseOptionalConstraint<unscanned, name, result, $> : never : parseNextNameChar<nextUnscanned, `${name}${lookahead}`, result, $> : name extends "" ? result : [...result, [name, unknown]];
53
+ 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 ":" | WhiteSpaceToken ? _parseOptionalConstraint<unscanned, name, result, $> : never : parseNextNameChar<nextUnscanned, `${name}${lookahead}`, result, $> : name extends "" ? result : [...result, [name, unknown]];
44
54
  declare const extendsToken = "extends ";
45
55
  type ConstrainingToken = ":" | typeof extendsToken;
46
56
  declare const _parseOptionalConstraint: (scanner: Scanner, name: string, result: GenericParamDef[], ctx: ParseContext) => GenericParamDef[];
47
- type _parseOptionalConstraint<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = Scanner.skipWhitespace<unscanned> extends (`${ConstrainingToken}${infer nextUnscanned}`) ? parseUntilFinalizer<state.initialize<nextUnscanned>, $, {}> extends (infer finalArgState extends StaticState) ? validateAst<finalArgState["root"], $, {}> extends (ErrorMessage<infer message>) ? keyError<message> : parseName<finalArgState["unscanned"], [
57
+ type _parseOptionalConstraint<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = Scanner.skipWhitespace<unscanned> extends (`${ConstrainingToken}${infer nextUnscanned}`) ? parseUntilFinalizer<state.initialize<nextUnscanned>, $, {}> extends (infer finalArgState extends StaticState) ? validateAst<finalArgState["root"], $, {}> extends (infer e extends ErrorMessage) ? e : parseName<finalArgState["unscanned"], [
48
58
  ...result,
49
59
  [name, inferAstRoot<finalArgState["root"], $, {}>]
50
60
  ], $> : never : parseName<Scanner.skipWhitespace<unscanned> extends `,${infer nextUnscanned}` ? nextUnscanned : unscanned, [
51
61
  ...result,
52
62
  [name, unknown]
53
63
  ], $>;
64
+ type genericParamDefToAst<schema extends GenericParamDef, $> = schema extends string ? [schema, unknown] : schema extends ConstrainedGenericParamDef ? [
65
+ schema[0],
66
+ inferTypeRoot<schema[1], $>
67
+ ] : never;
68
+ export type genericParamDefsToAst<schemas extends array<GenericParamDef>, $> = [
69
+ ...{
70
+ [i in keyof schemas]: genericParamDefToAst<schemas[i], $>;
71
+ }
72
+ ];
73
+ export type GenericHktParser<$ = {}> = <const paramsDef extends array<GenericParamDef>>(...params: paramsDef) => <hkt extends abstract new () => GenericHkt, params extends Array<GenericParamAst> = genericParamDefsToAst<paramsDef, $>>(instantiateDef: LazyGenericBody<baseGenericResolutions<params, $>>, hkt: hkt) => Generic<params, InstanceType<hkt>, $, $>;
54
74
  export {};
package/out/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- export { ArkError, ArkErrors as ArkErrors } from "@ark/schema";
1
+ export { ArkError, ArkErrors, GenericHkt } from "@ark/schema";
2
2
  export type { Ark, ArkConfig, Out, constrained, inferred } from "@ark/schema";
3
- export { ambient, ark, declare, define, match, type } from "./ark.js";
3
+ export { ambient, ark, declare, define, generic, match, type } from "./ark.js";
4
+ export type { Generic } from "./generic.js";
4
5
  export { Module } from "./module.js";
5
6
  export { scope, type Scope, type inferScope, type validateScope } from "./scope.js";
6
7
  export { Type, type AnyType, type inferTypeRoot, type validateTypeRoot } from "./type.js";
package/out/index.js CHANGED
@@ -1,5 +1,5 @@
1
- export { ArkError, ArkErrors as ArkErrors } from "@ark/schema";
2
- export { ambient, ark, declare, define, match, type } from "./ark.js";
1
+ export { ArkError, ArkErrors, GenericHkt } from "@ark/schema";
2
+ export { ambient, ark, declare, define, generic, match, type } from "./ark.js";
3
3
  export { Module } from "./module.js";
4
4
  export { scope } from "./scope.js";
5
5
  export { Type } from "./type.js";
package/out/match.d.ts CHANGED
@@ -64,7 +64,7 @@ type MatchInvocationContext = {
64
64
  thens: readonly ((...args: never[]) => unknown)[];
65
65
  initialInputs: unknown;
66
66
  };
67
- export type MatchInvocation<ctx extends MatchInvocationContext> = <data extends ctx["initialInputs"]>(data: data) => {
67
+ export type MatchInvocation<ctx extends MatchInvocationContext> = <const data extends ctx["initialInputs"]>(data: data) => {
68
68
  [i in numericStringKeyOf<ctx["thens"]>]: isDisjoint<data, Parameters<ctx["thens"][i]>[0]> extends true ? never : ReturnType<ctx["thens"][i]>;
69
69
  }[numericStringKeyOf<ctx["thens"]>];
70
70
  export declare const createMatchParser: <$>($: Scope) => MatchParser<$>;
package/out/module.d.ts CHANGED
@@ -1,10 +1,13 @@
1
- import { RootModule, type PreparsedNodeResolution } from "@ark/schema";
1
+ import { RootModule, type arkKind, type GenericProps } from "@ark/schema";
2
2
  import type { anyOrNever } from "@ark/util";
3
+ import type { Generic } from "./generic.js";
3
4
  import type { Type } from "./type.js";
4
5
  type exportScope<$> = {
5
- [k in keyof $]: $[k] extends PreparsedNodeResolution ? [
6
+ [k in keyof $]: $[k] extends {
7
+ [arkKind]: "module";
8
+ } ? [
6
9
  $[k]
7
- ] extends [anyOrNever] ? Type<$[k], $> : $[k] : Type<$[k], $>;
10
+ ] extends [anyOrNever] ? Type<$[k], $> : $[k] : $[k] extends GenericProps<infer params, infer bodyDef, infer args$> ? Generic<params, bodyDef, $, args$> : Type<$[k], $>;
8
11
  };
9
12
  export declare const Module: new <$ = {}>(types: exportScope<$>) => Module<$>;
10
13
  export type Module<$ = {}> = RootModule<exportScope<$>>;
@@ -1,5 +1,5 @@
1
1
  import { type BaseRoot, type Default, type IndexNode, type of, type OptionalNode, type RequiredNode, type UndeclaredKeyBehavior, type writeInvalidPropertyKeyMessage } from "@ark/schema";
2
- import { type anyOrNever, type Dict, type ErrorMessage, type EscapeToken, type Key, type keyError, type listable, type merge, type show } from "@ark/util";
2
+ import { type anyOrNever, type Dict, type ErrorMessage, type ErrorType, type EscapeToken, type Key, type listable, type merge, type show } from "@ark/util";
3
3
  import type { ParseContext } from "../scope.js";
4
4
  import type { inferDefinition, validateDefinition } from "./definition.js";
5
5
  import type { astToString } from "./semantic/utils.js";
@@ -17,7 +17,7 @@ type _inferObjectLiteral<def extends object, $, args> = {
17
17
  -readonly [k in keyof def as optionalKeyFrom<k>]?: inferDefinition<def[k], $, args>;
18
18
  };
19
19
  export type validateObjectLiteral<def, $, args> = {
20
- [k in keyof def]: k extends IndexKey<infer indexDef> ? validateString<indexDef, $, args> extends ErrorMessage<infer message> ? keyError<message> : inferDefinition<indexDef, $, args> extends (PropertyKey | of<PropertyKey, {}>) ? validateDefinition<def[k], $, args> : keyError<writeInvalidPropertyKeyMessage<indexDef>> : k extends "..." ? inferDefinition<def[k], $, args> extends object ? validateDefinition<def[k], $, args> : keyError<writeInvalidSpreadTypeMessage<astToString<def[k]>>> : k extends "+" ? UndeclaredKeyBehavior : validateDefaultableValue<def, k, $, args>;
20
+ [k in keyof def]: k extends IndexKey<infer indexDef> ? validateString<indexDef, $, args> extends ErrorMessage<infer message> ? ErrorType<message> : inferDefinition<indexDef, $, args> extends (PropertyKey | of<PropertyKey, {}>) ? validateDefinition<def[k], $, args> : ErrorType<writeInvalidPropertyKeyMessage<indexDef>> : k extends "..." ? inferDefinition<def[k], $, args> extends object ? validateDefinition<def[k], $, args> : ErrorType<writeInvalidSpreadTypeMessage<astToString<def[k]>>> : k extends "+" ? UndeclaredKeyBehavior : validateDefaultableValue<def, k, $, args>;
21
21
  };
22
22
  type validateDefaultableValue<def, k extends keyof def, $, args> = def[k] extends DefaultValueTuple ? validateDefaultValueTuple<def[k], k, $, args> : validateDefinition<def[k], $, args>;
23
23
  type DefaultValueTuple<baseDef = unknown, defaultValue = unknown> = readonly [
@@ -1,7 +1,7 @@
1
- import type { Root, writeIndivisibleMessage } from "@ark/schema";
1
+ import type { SchemaRoot, writeIndivisibleMessage } from "@ark/schema";
2
2
  import type { ErrorMessage } from "@ark/util";
3
3
  import type { inferAstIn } from "./infer.js";
4
4
  import type { validateAst } from "./validate.js";
5
5
  export type validateDivisor<l, $, args> = inferAstIn<l, $, args> extends infer data ? [
6
6
  data
7
- ] extends [number] ? validateAst<l, $, args> : ErrorMessage<writeIndivisibleMessage<Root<data>>> : never;
7
+ ] extends [number] ? validateAst<l, $, args> : ErrorMessage<writeIndivisibleMessage<SchemaRoot<data>>> : never;
@@ -1,4 +1,4 @@
1
- import type { Date, DateLiteral, Default, GenericProps, LimitLiteral, RegexLiteral, constrain, distillIn, distillOut, inferIntersection, normalizeLimit, string } from "@ark/schema";
1
+ import type { Date, DateLiteral, Default, GenericHkt, GenericProps, LimitLiteral, RegexLiteral, constrain, distillIn, distillOut, inferIntersection, normalizeLimit, string } from "@ark/schema";
2
2
  import type { BigintLiteral, array } from "@ark/util";
3
3
  import type { UnparsedScope, resolve, tryInferSubmoduleReference } from "../../scope.js";
4
4
  import type { inferDefinition } from "../definition.js";
@@ -9,7 +9,9 @@ export type inferAstIn<ast, $, args> = distillIn<inferAstRoot<ast, $, args>>;
9
9
  export type inferAstOut<ast, $, args> = distillOut<inferAstRoot<ast, $, args>>;
10
10
  export type inferConstrainableAst<ast, $, args> = ast extends array ? inferExpression<ast, $, args> : ast extends string ? inferTerminal<ast, $, args> : never;
11
11
  export type GenericInstantiationAst<generic extends GenericProps = GenericProps, argAsts extends unknown[] = unknown[]> = [generic, "<>", argAsts];
12
- export type inferExpression<ast extends array, $, args> = ast extends GenericInstantiationAst<infer generic, infer argAsts> ? inferDefinition<generic["bodyDef"], generic["$"]["t"] extends UnparsedScope ? $ : generic["$"]["t"], {
12
+ export type inferExpression<ast extends array, $, args> = ast extends GenericInstantiationAst<infer generic, infer argAsts> ? generic["bodyDef"] extends GenericHkt ? GenericHkt.instantiate<generic["bodyDef"], {
13
+ [i in keyof argAsts]: inferConstrainableAst<argAsts[i], $, args>;
14
+ }> : inferDefinition<generic["bodyDef"], generic["$"]["t"] extends UnparsedScope ? $ : generic["$"]["t"], {
13
15
  [i in keyof generic["params"] & `${number}` as generic["names"][i & keyof generic["names"]]]: inferConstrainableAst<argAsts[i & keyof argAsts], $, args>;
14
16
  }> : ast[1] extends "[]" ? inferConstrainableAst<ast[0], $, args>[] : ast[1] extends "|" ? inferConstrainableAst<ast[0], $, args> | inferConstrainableAst<ast[2], $, args> : ast[1] extends "&" ? inferIntersection<inferConstrainableAst<ast[0], $, args>, inferConstrainableAst<ast[2], $, args>> : ast[1] extends "=" ? inferTerminal<ast[2] & string, $, args> extends infer defaultValue ? (In?: inferConstrainableAst<ast[0], $, args>) => Default<defaultValue> : never : ast[1] extends Comparator ? ast[0] extends LimitLiteral ? constrainBound<inferConstrainableAst<ast[2], $, args>, ast[1], ast[0]> : constrainBound<inferConstrainableAst<ast[0], $, args>, ast[1], ast[2]> : ast[1] extends "%" ? constrain<inferConstrainableAst<ast[0], $, args>, "divisor", ast[2] & number> : ast[0] extends "keyof" ? keyof inferConstrainableAst<ast[1], $, args> : never;
15
17
  export type constrainBound<constrainableIn, comparator extends Comparator, limit> = distillIn<constrainableIn> extends infer In ? comparator extends "==" ? In extends number ? limit : In extends Date ? Date.literal<normalizeLimit<limit>> : constrain<constrainableIn, "exactLength", limit & number> : constrain<constrainableIn, In extends number ? comparator extends MinComparator ? "min" : "max" : In extends string | array ? comparator extends MinComparator ? "minLength" : "maxLength" : comparator extends MinComparator ? "after" : "before", {
@@ -14,7 +14,7 @@ export type validateAst<ast, $, args> = ast extends string ? validateStringAst<a
14
14
  ast: ast;
15
15
  };
16
16
  type writeUnexpectedExpressionMessage<expression extends string> = `Unexpectedly failed to parse the expression resulting from ${expression}`;
17
- type validateGenericArgs<params extends array<GenericParamAst>, argAsts extends array, $, args, indices extends 1[]> = argAsts extends readonly [infer arg, ...infer argsTail] ? validateAst<arg, $, args> extends ErrorMessage<infer message> ? ErrorMessage<message> : inferAstRoot<arg, $, args> extends params[indices["length"]][1] ? validateGenericArgs<params, argsTail, $, args, [...indices, 1]> : ErrorMessage<writeUnsatisfiedParameterConstraintMessage<params[indices["length"]][0], typeToString<params[indices["length"]][1]>, astToString<arg>>> : undefined;
17
+ type validateGenericArgs<params extends array<GenericParamAst>, argAsts extends array, $, args, indices extends 1[]> = argAsts extends readonly [infer arg, ...infer argsTail] ? validateAst<arg, $, args> extends infer e extends ErrorMessage ? e : inferAstRoot<arg, $, args> extends params[indices["length"]][1] ? validateGenericArgs<params, argsTail, $, args, [...indices, 1]> : ErrorMessage<writeUnsatisfiedParameterConstraintMessage<params[indices["length"]][0], typeToString<params[indices["length"]][1]>, astToString<arg>>> : undefined;
18
18
  export declare const writeUnsatisfiableExpressionError: <expression extends string>(expression: expression) => writeUnsatisfiableExpressionError<expression>;
19
19
  export type writeUnsatisfiableExpressionError<expression extends string> = `${expression} results in an unsatisfiable type`;
20
20
  export declare const writePrefixedPrivateReferenceMessage: <def extends PrivateDeclaration>(def: def) => writePrefixedPrivateReferenceMessage<def>;
@@ -26,5 +26,5 @@ type validateStringAst<def extends string, $> = def extends `${infer n extends n
26
26
  } ? ErrorMessage<writeMissingSubmoduleAccessMessage<def>> : undefined : def extends ErrorMessage ? def : undefined;
27
27
  export type maybeExtractAlias<def extends string, $> = def extends keyof $ ? def : `#${def}` extends keyof $ ? `#${def}` : null;
28
28
  export type validateString<def extends string, $, args> = validateAst<parseString<def, $, args>, $, args> extends (infer result extends ErrorMessage) ? result extends Completion<infer text> ? text : result : def;
29
- type validateInfix<ast extends InfixExpression, $, args> = validateAst<ast[0], $, args> extends ErrorMessage<infer message> ? ErrorMessage<message> : validateAst<ast[2], $, args> extends ErrorMessage<infer message> ? ErrorMessage<message> : undefined;
29
+ type validateInfix<ast extends InfixExpression, $, args> = validateAst<ast[0], $, args> extends infer e extends ErrorMessage ? e : validateAst<ast[2], $, args> extends infer e extends ErrorMessage ? e : undefined;
30
30
  export {};
package/out/scope.d.ts CHANGED
@@ -1,14 +1,14 @@
1
- import { RawRootScope, type AliasDefEntry, type ArkConfig, type BaseRoot, type GenericArgResolutions, type GenericParamAst, type GenericParamDef, type GenericProps, type PreparsedNodeResolution, type PrivateDeclaration, type RawRootResolutions, type RootScope, type arkKind, type destructuredExportContext, type destructuredImportContext, type exportedNameOf, type writeDuplicateAliasError } from "@ark/schema";
2
- import { type anyOrNever, type array, type keyError, type nominal, type show } from "@ark/util";
3
- import { parseGenericParams, type Generic, type GenericDeclaration, type ParameterString, type baseGenericArgs, type parseValidGenericParams } from "./generic.js";
1
+ import { InternalBaseScope, type AliasDefEntry, type ArkConfig, type BaseRoot, type BaseScope, type GenericArgResolutions, type GenericParamAst, type GenericParamDef, type GenericProps, type InternalResolutions, type PreparsedNodeResolution, type PrivateDeclaration, type arkKind, type destructuredExportContext, type destructuredImportContext, type exportedNameOf, type writeDuplicateAliasError } from "@ark/schema";
2
+ import { type ErrorType, type anyOrNever, type array, type nominal, type show } from "@ark/util";
3
+ import { parseGenericParams, type Generic, type GenericDeclaration, type GenericHktParser, type ParameterString, type baseGenericConstraints, type parseValidGenericParams } from "./generic.js";
4
4
  import { type MatchParser } from "./match.js";
5
5
  import type { Module } from "./module.js";
6
6
  import { type inferDefinition, type validateDefinition } from "./parser/definition.js";
7
7
  import type { ParsedDefault } from "./parser/string/shift/operator/default.js";
8
- import { RawTypeParser, type DeclarationParser, type DefinitionParser, type Type, type TypeParser } from "./type.js";
8
+ import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type Type, type TypeParser } from "./type.js";
9
9
  export type ScopeParser = <const def>(def: validateScope<def>, config?: ArkConfig) => Scope<inferScope<def>>;
10
10
  export type validateScope<def> = {
11
- [k in keyof def]: k extends symbol ? unknown : parseScopeKey<k, def>["params"] extends infer params ? params extends array<GenericParamAst> ? params["length"] extends 0 ? def[k] extends Type | PreparsedResolution ? def[k] : k extends PrivateDeclaration<infer name extends keyof def & string> ? keyError<writeDuplicateAliasError<name>> : validateDefinition<def[k], bootstrapAliases<def>, {}> : validateDefinition<def[k], bootstrapAliases<def>, baseGenericArgs<params>> : params : never;
11
+ [k in keyof def]: k extends symbol ? unknown : parseScopeKey<k, def>["params"] extends infer params ? params extends array<GenericParamAst> ? params["length"] extends 0 ? def[k] extends Type | PreparsedResolution ? def[k] : k extends PrivateDeclaration<infer name extends keyof def & string> ? ErrorType<writeDuplicateAliasError<name>> : validateDefinition<def[k], bootstrapAliases<def>, {}> : validateDefinition<def[k], bootstrapAliases<def>, baseGenericConstraints<params>> : params : never;
12
12
  };
13
13
  export type inferScope<def> = inferBootstrapped<bootstrapAliases<def>>;
14
14
  export type bindThis<def> = {
@@ -40,27 +40,19 @@ export type moduleKeyOf<$> = {
40
40
  }[keyof $];
41
41
  export type tryInferSubmoduleReference<$, token> = token extends `${infer submodule extends moduleKeyOf<$>}.${infer subalias}` ? subalias extends keyof $[submodule] ? $[submodule][subalias] : never : token extends `${infer submodule}.${infer subalias}` ? submodule extends moduleKeyOf<ArkEnv.$> ? subalias extends keyof ArkEnv.$[submodule] ? ArkEnv.$[submodule][subalias] : never : never : never;
42
42
  export interface ParseContext extends TypeParseOptions {
43
- $: RawScope;
43
+ $: InternalScope;
44
44
  }
45
45
  export interface TypeParseOptions {
46
46
  args?: GenericArgResolutions;
47
47
  }
48
48
  export declare const scope: ScopeParser;
49
- export interface Scope<$ = any> extends RootScope<$> {
50
- type: TypeParser<$>;
51
- match: MatchParser<$>;
52
- declare: DeclarationParser<$>;
53
- define: DefinitionParser<$>;
54
- import<names extends exportedNameOf<$>[]>(...names: names): Module<show<destructuredImportContext<$, names>>>;
55
- export<names extends exportedNameOf<$>[]>(...names: names): Module<show<destructuredExportContext<$, names>>>;
56
- }
57
- export declare class RawScope<$ extends RawRootResolutions = RawRootResolutions> extends RawRootScope<$> {
49
+ export declare class InternalScope<$ extends InternalResolutions = InternalResolutions> extends InternalBaseScope<$> {
58
50
  private parseCache;
59
51
  constructor(def: Record<string, unknown>, config?: ArkConfig);
60
- type: RawTypeParser;
52
+ type: InternalTypeParser;
61
53
  match: MatchParser<$>;
62
54
  declare: () => {
63
- type: RawTypeParser;
55
+ type: InternalTypeParser;
64
56
  };
65
57
  define: (def: unknown) => unknown;
66
58
  preparseAlias(k: string, v: unknown): AliasDefEntry;
@@ -69,16 +61,27 @@ export declare class RawScope<$ extends RawRootResolutions = RawRootResolutions>
69
61
  parse<defaultable extends boolean = false>(def: unknown, ctx: ParseContext, defaultable?: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
70
62
  parseString<defaultable extends boolean>(def: string, ctx: ParseContext, defaultable: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
71
63
  }
64
+ export interface Scope<$ = any> extends BaseScope<$> {
65
+ type: TypeParser<$>;
66
+ match: MatchParser<$>;
67
+ declare: DeclarationParser<$>;
68
+ define: DefinitionParser<$>;
69
+ generic: GenericHktParser<$>;
70
+ import<names extends exportedNameOf<$>[]>(...names: names): Module<show<destructuredImportContext<$, names>>>;
71
+ export<names extends exportedNameOf<$>[]>(...names: names): Module<show<destructuredExportContext<$, names>>>;
72
+ }
73
+ export declare const Scope: new <$ = any>() => Scope<$>;
72
74
  export declare const writeShallowCycleErrorMessage: (name: string, seen: string[]) => string;
73
75
  export type ParsedScopeKey = {
74
76
  name: string;
75
77
  params: array<GenericParamDef>;
76
78
  };
77
- export type parseScopeKey<k, def> = k extends `${infer name}<${infer params}>` ? {
78
- name: name;
79
- params: parseGenericParams<params, bootstrapAliases<def>>;
80
- } : {
79
+ export type parseScopeKey<k, def> = k extends `${infer name}<${infer params}>` ? parseGenericScopeKey<name, params, def> : {
81
80
  name: k;
82
81
  params: [];
83
82
  };
83
+ type parseGenericScopeKey<name extends string, params extends string, def> = {
84
+ name: name;
85
+ params: parseGenericParams<params, bootstrapAliases<def>>;
86
+ };
84
87
  export {};
package/out/scope.js CHANGED
@@ -32,7 +32,7 @@ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn,
32
32
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
33
  done = true;
34
34
  };
35
- import { RawRootScope, hasArkKind, parseGeneric } from "@ark/schema";
35
+ import { InternalBaseScope, hasArkKind, parseGeneric } from "@ark/schema";
36
36
  import { bound, domainOf, hasDomain, isThunk, throwParseError } from "@ark/util";
37
37
  import { parseGenericParams } from "./generic.js";
38
38
  import { createMatchParser } from "./match.js";
@@ -41,13 +41,13 @@ import { DynamicState } from "./parser/string/reduce/dynamic.js";
41
41
  import { writeUnexpectedCharacterMessage } from "./parser/string/shift/operator/operator.js";
42
42
  import { Scanner } from "./parser/string/shift/scanner.js";
43
43
  import { fullStringParse } from "./parser/string/string.js";
44
- import { RawTypeParser } from "./type.js";
45
- export const scope = ((def, config = {}) => new RawScope(def, config));
46
- let RawScope = (() => {
47
- let _classSuper = RawRootScope;
44
+ import { InternalTypeParser } from "./type.js";
45
+ export const scope = ((def, config = {}) => new InternalScope(def, config));
46
+ let InternalScope = (() => {
47
+ let _classSuper = InternalBaseScope;
48
48
  let _instanceExtraInitializers = [];
49
49
  let _parseRoot_decorators;
50
- return class RawScope extends _classSuper {
50
+ return class InternalScope extends _classSuper {
51
51
  static {
52
52
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
53
53
  _parseRoot_decorators = [bound];
@@ -58,7 +58,7 @@ let RawScope = (() => {
58
58
  constructor(def, config) {
59
59
  super(def, config);
60
60
  }
61
- type = new RawTypeParser(this);
61
+ type = new InternalTypeParser(this);
62
62
  match = createMatchParser(this);
63
63
  declare = (() => ({
64
64
  type: this.type
@@ -127,5 +127,6 @@ let RawScope = (() => {
127
127
  }
128
128
  };
129
129
  })();
130
- export { RawScope };
130
+ export { InternalScope };
131
+ export const Scope = InternalScope;
131
132
  export const writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join(":")}`;
package/out/type.d.ts CHANGED
@@ -1,30 +1,28 @@
1
- import { ArkErrors, BaseRoot, type BaseMeta, type ConstraintKind, type Disjoint, type DivisorSchema, type ExactLengthSchema, type ExclusiveDateRangeSchema, type ExclusiveNumericRangeSchema, type InclusiveDateRangeSchema, type InclusiveNumericRangeSchema, type InnerRoot, type Morph, type MorphAst, type NodeSchema, type Out, type PatternSchema, type Predicate, type Prerequisite, type PrimitiveConstraintKind, type Root, type constrain, type constraintKindOf, type distillIn, type distillOut, type exclusivizeRangeSchema, type indexInto, type indexOf, type inferIntersection, type inferMorphOut, type inferPipes, type inferPredicate, type writeInvalidOperandMessage } from "@ark/schema";
2
- import { Callable, type Constructor, type ErrorMessage, type array, type conform } from "@ark/util";
1
+ import { ArkErrors, BaseRoot, type BaseMeta, type Disjoint, type DivisorSchema, type ExactLengthSchema, type ExclusiveDateRangeSchema, type ExclusiveNumericRangeSchema, type InclusiveDateRangeSchema, type InclusiveNumericRangeSchema, type Morph, type MorphAst, type NodeSchema, type Out, type PatternSchema, type Predicate, type PrimitiveConstraintKind, type Root, type arkKeyOf, type constrain, type constraintKindOf, type distillIn, type distillOut, type exclusivizeRangeSchema, type getArkKey, type inferIntersection, type inferMorphOut, type inferPipes, type inferPredicate, type toArkKey, type validateChainedAsArgs, type validateChainedConstraint, type validateStructuralOperand } from "@ark/schema";
2
+ import { Callable, type Constructor, type array, type conform, type unset } from "@ark/util";
3
3
  import type { type } from "./ark.js";
4
- import { type Generic, type ParameterString, type baseGenericArgs, type parseValidGenericParams, type validateParameterString } from "./generic.js";
4
+ import { type Generic, type ParameterString, type baseGenericConstraints, type parseValidGenericParams, type validateParameterString } from "./generic.js";
5
5
  import type { inferDefinition, validateDeclared, validateDefinition } from "./parser/definition.js";
6
6
  import type { IndexOneOperator, IndexZeroOperator, TupleInfixOperator } from "./parser/tuple.js";
7
- import type { RawScope, Scope, bindThis } from "./scope.js";
7
+ import type { InternalScope, Scope, bindThis } from "./scope.js";
8
8
  /** The convenience properties attached to `type` */
9
9
  export type TypeParserAttachments = Omit<TypeParser, never>;
10
10
  export interface TypeParser<$ = {}> {
11
11
  <const def>(def: validateTypeRoot<def, $>): Type<inferTypeRoot<def, $>, $>;
12
12
  <const zero, const one, const rest extends array>(_0: zero extends IndexZeroOperator ? zero : validateTypeRoot<zero, $>, _1: zero extends "keyof" ? validateTypeRoot<one, $> : zero extends "instanceof" ? conform<one, Constructor> : zero extends "===" ? conform<one, unknown> : conform<one, IndexOneOperator>, ..._2: zero extends "===" ? rest : zero extends "instanceof" ? conform<rest, readonly Constructor[]> : one extends TupleInfixOperator ? one extends ":" ? [Predicate<distillIn<inferTypeRoot<zero, $>>>] : one extends "=>" ? [Morph<distillOut<inferTypeRoot<zero, $>>, unknown>] : one extends "@" ? [string | BaseMeta] : [validateTypeRoot<rest[0], $>] : []): Type<inferTypeRoot<[zero, one, ...rest], $>, $>;
13
- <params extends ParameterString, const def>(params: validateParameterString<params, $>, def: validateDefinition<def, $, baseGenericArgs<parseValidGenericParams<params, $>>>): Generic<parseValidGenericParams<params, $>, def, $>;
13
+ <params extends ParameterString, const def>(params: validateParameterString<params, $>, def: validateDefinition<def, $, baseGenericConstraints<parseValidGenericParams<params, $>>>): Generic<parseValidGenericParams<params, $>, def, $>;
14
14
  raw(def: unknown): Type<any, $>;
15
15
  errors: typeof ArkErrors;
16
16
  }
17
- export declare class RawTypeParser extends Callable<(...args: unknown[]) => BaseRoot | Generic, TypeParserAttachments> {
18
- constructor($: RawScope);
17
+ export declare class InternalTypeParser extends Callable<(...args: unknown[]) => BaseRoot | Generic, TypeParserAttachments> {
18
+ constructor($: InternalScope);
19
19
  }
20
20
  export type DeclarationParser<$> = <preinferred>() => {
21
21
  type: <def>(def: validateDeclared<preinferred, def, $, bindThis<def>>) => Type<preinferred, $>;
22
22
  };
23
- type validateChainedConstraint<kind extends ConstraintKind, t extends {
24
- inferIn: unknown;
25
- }> = t["inferIn"] extends Prerequisite<kind> ? t : ErrorMessage<writeInvalidOperandMessage<kind, Root<t["inferIn"]>>>;
26
- declare class _Type<t = unknown, $ = any> extends InnerRoot<t, $> {
23
+ declare class _Type<t = unknown, $ = any> extends Root<t, $> {
27
24
  $: Scope<$>;
25
+ as<t = unset>(...args: validateChainedAsArgs<t>): Type<t, $>;
28
26
  get in(): Type<this["tIn"], $>;
29
27
  get out(): Type<this["tOut"], $>;
30
28
  intersect<def>(def: validateTypeRoot<def, $>): Type<inferIntersection<t, inferTypeRoot<def, $>>> | Disjoint;
@@ -41,13 +39,25 @@ declare class _Type<t = unknown, $ = any> extends InnerRoot<t, $> {
41
39
  pipe<a extends Morph<this["infer"]>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, d extends Morph<inferMorphOut<c>>, e extends Morph<inferMorphOut<d>>, f extends Morph<inferMorphOut<e>>, g extends Morph<inferMorphOut<f>>>(a: a, b: b, c: c, d: d, e: e, f: f, g: g): Type<inferPipes<t, [a, b, c, d, e, f, g]>, $>;
42
40
  narrow<predicate extends Predicate<distillOut<t>>>(predicate: predicate): Type<t extends MorphAst ? inferPredicate<this["tOut"], predicate> extends infer narrowed ? (In: this["tIn"]) => Out<narrowed> : never : inferPredicate<t, predicate>, $>;
43
41
  equals<def>(def: validateTypeRoot<def, $>): this is Type<inferTypeRoot<def>, $>;
44
- extract<def>(r: validateTypeRoot<def, $>): Type<t, $>;
45
- exclude<def>(r: validateTypeRoot<def, $>): Type<t, $>;
42
+ extract<def>(r: validateTypeRoot<def, $>): Type<Extract<t, inferTypeRoot<def, $>>, $>;
43
+ exclude<def>(r: validateTypeRoot<def, $>): Type<Exclude<t, inferTypeRoot<def, $>>, $>;
46
44
  extends<def>(other: validateTypeRoot<def, $>): this is Type<inferTypeRoot<def>, $>;
47
45
  overlaps<def>(r: validateTypeRoot<def, $>): boolean;
48
- get<k1 extends indexOf<t>>(k1: k1 | type.cast<k1>): Type<indexInto<t, k1>, $>;
49
- get<k1 extends indexOf<t>, k2 extends indexOf<indexInto<t, k1>>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>): Type<indexInto<indexInto<t, k1>, k2>, $>;
50
- get<k1 extends indexOf<t>, k2 extends indexOf<indexInto<t, k1>>, k3 extends indexOf<indexInto<indexInto<t, k1>, k2>>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>, k3: k3 | type.cast<k3>): Type<indexInto<indexInto<indexInto<t, k1>, k2>, k3>, $>;
46
+ omit<const key extends arkKeyOf<t> = never>(this: validateStructuralOperand<"omit", this>, ...keys: array<key | type.cast<key>>): Type<{
47
+ [k in keyof t as Exclude<toArkKey<t, k>, key>]: t[k];
48
+ }, $>;
49
+ pick<const key extends arkKeyOf<t> = never>(this: validateStructuralOperand<"pick", this>, ...keys: array<key | type.cast<key>>): Type<{
50
+ [k in keyof t as Extract<toArkKey<t, k>, key>]: t[k];
51
+ }, $>;
52
+ required(this: validateStructuralOperand<"required", this>): Type<{
53
+ [k in keyof this["inferIn"]]-?: this["inferIn"][k];
54
+ }, $>;
55
+ partial(this: validateStructuralOperand<"partial", this>): Type<{
56
+ [k in keyof this["inferIn"]]?: this["inferIn"][k];
57
+ }, $>;
58
+ get<k1 extends arkKeyOf<t>>(k1: k1 | type.cast<k1>): Type<getArkKey<t, k1>, $>;
59
+ get<k1 extends arkKeyOf<t>, k2 extends arkKeyOf<getArkKey<t, k1>>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>): Type<getArkKey<getArkKey<t, k1>, k2>, $>;
60
+ get<k1 extends arkKeyOf<t>, k2 extends arkKeyOf<getArkKey<t, k1>>, k3 extends arkKeyOf<getArkKey<getArkKey<t, k1>, k2>>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>, k3: k3 | type.cast<k3>): Type<getArkKey<getArkKey<getArkKey<t, k1>, k2>, k3>, $>;
51
61
  constrain<kind extends PrimitiveConstraintKind, const def extends NodeSchema<kind>>(kind: conform<kind, constraintKindOf<this["inferIn"]>>, def: def): Type<constrain<t, kind, def>, $>;
52
62
  satisfying<predicate extends Predicate<distillIn<t>>>(predicate: predicate): Type<t extends MorphAst ? (In: inferPredicate<this["tIn"], predicate>) => Out<this["tOut"]> : inferPredicate<t, predicate>, $>;
53
63
  divisibleBy<const schema extends DivisorSchema>(this: validateChainedConstraint<"divisor", this>, schema: schema): Type<constrain<t, "divisor", schema>, $>;
package/out/type.js CHANGED
@@ -1,7 +1,7 @@
1
- import { ArkErrors, BaseRoot } from "@ark/schema";
1
+ import { ArkErrors, BaseRoot, GenericRoot } from "@ark/schema";
2
2
  import { Callable } from "@ark/util";
3
3
  import { parseGenericParams } from "./generic.js";
4
- export class RawTypeParser extends Callable {
4
+ export class InternalTypeParser extends Callable {
5
5
  constructor($) {
6
6
  super((...args) => {
7
7
  if (args.length === 1) {
@@ -18,8 +18,7 @@ export class RawTypeParser extends Callable {
18
18
  $,
19
19
  args: {}
20
20
  });
21
- const def = args[1];
22
- return $.generic(params, def);
21
+ return new GenericRoot(params, args[1], $, $);
23
22
  }
24
23
  // otherwise, treat as a tuple expression. technically, this also allows
25
24
  // non-expression tuple definitions to be parsed, but it's not a supported
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "arktype",
3
3
  "description": "TypeScript's 1:1 validator, optimized from editor to runtime",
4
- "version": "2.0.0-beta.0",
4
+ "version": "2.0.0-beta.2",
5
5
  "license": "MIT",
6
6
  "author": {
7
7
  "name": "David Blass",
@@ -25,8 +25,8 @@
25
25
  "out"
26
26
  ],
27
27
  "dependencies": {
28
- "@ark/util": "0.1.0",
29
- "@ark/schema": "0.2.0"
28
+ "@ark/util": "0.1.2",
29
+ "@ark/schema": "0.2.2"
30
30
  },
31
31
  "publishConfig": {
32
32
  "access": "public"