arktype 2.0.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,9 +17,9 @@ interface Type<out t extends object = object, $ = {}> extends BaseType<t, $> {
17
17
  * Get the `Type` of a property of this `Type<object>`.
18
18
  * @example type({ foo: "string" }).get("foo") // Type<string>
19
19
  */
20
- get<const k1 extends arkIndexableOf<t>, r = arkGet<t, k1>>(k1: k1 | type.cast<k1>): instantiateType<r, $>;
21
- get<const k1 extends arkIndexableOf<t>, const k2 extends arkIndexableOf<arkGet<t, k1>>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>): instantiateType<arkGet<arkGet<t, k1>, k2>, $> extends infer r ? r : never;
22
- get<const k1 extends arkIndexableOf<t>, const k2 extends arkIndexableOf<arkGet<t, k1>>, const k3 extends arkIndexableOf<arkGet<arkGet<t, k1>, k2>>, r = arkGet<arkGet<arkGet<t, k1>, k2>, k3>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>, k3: k3 | type.cast<k3>): instantiateType<r, $>;
20
+ get<const k1 extends arkIndexableOf<t>, r = instantiateType<arkGet<t, k1>, $>>(k1: k1 | type.cast<k1>): r extends infer _ ? _ : never;
21
+ 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;
22
+ 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;
23
23
  /**
24
24
  * Create a copy of this `Type` with only the specified properties.
25
25
  * @example type({ foo: "string", bar: "number" }).pick("foo") // Type<{ foo: string }>
@@ -38,7 +38,7 @@ interface Type<out t extends object = object, $ = {}> extends BaseType<t, $> {
38
38
  * Merge another `Type` definition, overriding properties of this `Type` with the duplicate keys.
39
39
  * @example type({ a: "1", b: "2" }).merge({ b: "3", c: "4" }) // Type<{ a: 1, b: 3, c: 4 }>
40
40
  */
41
- merge<const def, r = type.infer<def, $>>(def: type.validate<def, $> & (r extends object ? unknown : ErrorType<"Merged type must be an object", [actual: r]>)): Type<merge<t, r & object>, $>;
41
+ merge<const def, inferredDef = type.infer<def, $>, r = Type<merge<t, inferredDef>, $>>(def: type.validate<def, $> & (inferredDef extends object ? unknown : ErrorType<"Merged type must be an object", [actual: inferredDef]>)): r extends infer _ ? _ : never;
42
42
  /**
43
43
  * Create a copy of this `Type` with all properties required.
44
44
  * @example const T = type({ "foo?"": "string" }).required() // Type<{ foo: string }>
@@ -53,7 +53,7 @@ interface Type<out t extends object = object, $ = {}> extends BaseType<t, $> {
53
53
  partial(): Type<{
54
54
  [k in keyof t]?: t[k];
55
55
  }, $>;
56
- map<transformed extends listable<MappedTypeProp>>(flatMapEntry: (entry: typePropOf<t, $>) => transformed): Type<constructMapped<t, transformed>, $>;
56
+ map<transformed extends listable<MappedTypeProp>, r = Type<constructMapped<t, transformed>, $>>(flatMapEntry: (entry: typePropOf<t, $>) => transformed): r extends infer _ ? _ : never;
57
57
  /**
58
58
  * List of property info of this `Type<object>`.
59
59
  * @example type({ foo: "string = "" }).props // [{ kind: "required", key: "foo", value: Type<string>, default: "" }]
@@ -1,15 +1,15 @@
1
1
  import type { writeUnboundableMessage } from "@ark/schema";
2
2
  import type { ErrorMessage, array, typeToString } from "@ark/util";
3
- import type { LimitLiteral } from "../../attributes.ts";
3
+ import type { InferredMorph, LimitLiteral } from "../../attributes.ts";
4
4
  import type { Comparator } from "../reduce/shared.ts";
5
5
  import type { BoundExpressionKind, writeInvalidLimitMessage } from "../shift/operator/bounds.ts";
6
- import type { inferAstIn } from "./infer.ts";
7
- import type { astToString } from "./utils.ts";
6
+ import type { inferAstRoot } from "./infer.ts";
7
+ import type { astToString, writeConstrainedMorphMessage } from "./utils.ts";
8
8
  import type { validateAst } from "./validate.ts";
9
9
  export type validateRange<l, comparator extends Comparator, r, $, args> = [
10
10
  l
11
11
  ] extends [LimitLiteral] ? validateBound<r, comparator, l, "left", $, args> : [l] extends [[infer leftAst, Comparator, unknown]] ? ErrorMessage<writeDoubleRightBoundMessage<astToString<leftAst>>> : validateBound<l, comparator, r & LimitLiteral, "right", $, args>;
12
- export type validateBound<boundedAst, comparator extends Comparator, limit extends LimitLiteral, boundKind extends BoundExpressionKind, $, args> = inferAstIn<boundedAst, $, args> extends infer bounded ? isNumericallyBoundable<bounded> extends true ? limit extends number ? validateAst<boundedAst, $, args> : ErrorMessage<writeInvalidLimitMessage<comparator, limit, boundKind>> : [bounded] extends [Date] ? validateAst<boundedAst, $, args> : ErrorMessage<writeUnboundableMessage<typeToString<bounded>>> : never;
12
+ export type validateBound<boundedAst, comparator extends Comparator, limit extends LimitLiteral, boundKind extends BoundExpressionKind, $, args> = inferAstRoot<boundedAst, $, args> extends infer bounded ? isNumericallyBoundable<bounded> extends true ? limit extends number ? validateAst<boundedAst, $, args> : ErrorMessage<writeInvalidLimitMessage<comparator, limit, boundKind>> : [bounded] extends [Date] ? validateAst<boundedAst, $, args> : [bounded] extends [InferredMorph] ? ErrorMessage<writeConstrainedMorphMessage<boundedAst>> : ErrorMessage<writeUnboundableMessage<typeToString<bounded>>> : never;
13
13
  type isNumericallyBoundable<bounded> = [
14
14
  bounded
15
15
  ] extends [number] ? true : [bounded] extends [string] ? true : [bounded] extends [array] ? true : false;
@@ -1,7 +1,9 @@
1
1
  import type { writeIndivisibleMessage } from "@ark/schema";
2
2
  import type { ErrorMessage } from "@ark/util";
3
- import type { inferAstIn } from "./infer.ts";
3
+ import type { InferredMorph } from "../../attributes.ts";
4
+ import type { inferAstRoot } from "./infer.ts";
5
+ import type { writeConstrainedMorphMessage } from "./utils.ts";
4
6
  import type { validateAst } from "./validate.ts";
5
- export type validateDivisor<l, $, args> = inferAstIn<l, $, args> extends infer data ? [
7
+ export type validateDivisor<l, $, args> = inferAstRoot<l, $, args> extends infer data ? [
6
8
  data
7
- ] extends [number] ? validateAst<l, $, args> : ErrorMessage<writeIndivisibleMessage<data>> : never;
9
+ ] extends [number] ? validateAst<l, $, args> : [data] extends [InferredMorph] ? ErrorMessage<writeConstrainedMorphMessage<l>> : ErrorMessage<writeIndivisibleMessage<data>> : never;
@@ -1,4 +1,8 @@
1
- import type { Stringifiable } from "@ark/util";
1
+ import type { satisfy, Stringifiable } from "@ark/util";
2
2
  import type { Comparator } from "../reduce/shared.ts";
3
+ import type { ArkTypeScanner } from "../shift/scanner.ts";
3
4
  import type { DefAst, InferredAst, InfixExpression, PostfixExpression } from "./infer.ts";
4
5
  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}` : "...";
6
+ export type ConstraintOperator = satisfy<ArkTypeScanner.OperatorToken, "%" | Comparator>;
7
+ export type writeConstrainedMorphMessage<constrainedAst> = `To constrain the output of ${astToString<constrainedAst>}, pipe like myMorph.to('number > 0').
8
+ To constrain the input, intersect like myMorph.and('number > 0').`;
@@ -12,7 +12,7 @@ export const parseInnerDefinition = (def, ctx) => {
12
12
  // resolutions like "this" or generic args
13
13
  return parseString(def, ctx);
14
14
  }
15
- const scopeCache = (parseCache[ctx.$.id] ??= {});
15
+ const scopeCache = (parseCache[ctx.$.name] ??= {});
16
16
  return (scopeCache[def] ??= parseString(def, ctx));
17
17
  }
18
18
  return hasDomain(def, "object") ?
@@ -21,9 +21,8 @@ export type validateProperty<def, keyKind extends ParsedKeyKind, $, args> = [
21
21
  * })
22
22
  * ```
23
23
  */
24
- def : keyKind extends "spread" ? validateSpread<def, inferDefinition<def, $, args>, $, args> : keyKind extends "undeclared" ? UndeclaredKeyBehavior : keyKind extends "required" ? validateInnerDefinition<def, $, args> : def extends OptionalPropertyDefinition ? ErrorMessage<invalidOptionalKeyKindMessage> : isDefaultable<def, $, args> extends true ? ErrorMessage<invalidDefaultableKeyKindMessage> : validateInnerDefinition<def, $, args>;
24
+ def : keyKind extends "spread" ? def extends validateInnerDefinition<def, $, args> ? inferDefinition<def, $, args> extends object ? def : ErrorType<writeInvalidSpreadTypeMessage<typeToString<inferDefinition<def, $, args>>>> : validateInnerDefinition<def, $, args> : keyKind extends "undeclared" ? UndeclaredKeyBehavior : keyKind extends "required" ? validateInnerDefinition<def, $, args> : def extends OptionalPropertyDefinition ? ErrorMessage<invalidOptionalKeyKindMessage> : isDefaultable<def, $, args> extends true ? ErrorMessage<invalidDefaultableKeyKindMessage> : validateInnerDefinition<def, $, args>;
25
25
  export type isDefaultable<def, $, args> = def extends DefaultablePropertyTuple ? true : def extends PossibleDefaultableStringDefinition ? parseString<def, $, args> extends DefaultablePropertyTuple ? true : false : false;
26
- type validateSpread<def, inferredProperty, $, args> = inferredProperty extends object ? validateInnerDefinition<def, $, args> : ErrorType<writeInvalidSpreadTypeMessage<typeToString<inferredProperty>>>;
27
26
  export type OptionalPropertyDefinition<baseDef = unknown> = OptionalPropertyTuple<baseDef> | OptionalPropertyString<baseDef & string>;
28
27
  export type OptionalPropertyString<baseDef extends string = string> = `${baseDef}?`;
29
28
  export type OptionalPropertyTuple<baseDef = unknown> = readonly [baseDef, "?"];
@@ -33,4 +32,3 @@ export declare const invalidOptionalKeyKindMessage = "Only required keys may mak
33
32
  export type invalidOptionalKeyKindMessage = typeof invalidOptionalKeyKindMessage;
34
33
  export declare const invalidDefaultableKeyKindMessage = "Only required keys may specify default values, e.g. { value: 'number = 0' }";
35
34
  export type invalidDefaultableKeyKindMessage = typeof invalidDefaultableKeyKindMessage;
36
- export {};
@@ -32,7 +32,7 @@ export declare namespace ArkTypeScanner {
32
32
  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;
33
33
  type TerminatingChar = keyof typeof ArkTypeScanner.terminatingChars;
34
34
  type FinalizingLookahead = keyof typeof ArkTypeScanner.finalizingLookaheads;
35
- type InfixToken = Comparator | "|" | "&" | "%" | ":" | "=>" | "#" | "@" | "=";
35
+ type InfixToken = Comparator | "|" | "&" | "%" | ":" | "=>" | "|>" | "#" | "@" | "=";
36
36
  type PostfixToken = "[]" | "?";
37
37
  type OperatorToken = InfixToken | PostfixToken;
38
38
  type shift<lookahead extends string, unscanned extends string> = `${lookahead}${unscanned}`;
@@ -1,6 +1,7 @@
1
- import { type BaseParseContext, type BaseRoot, type MetaSchema, type Morph, type Predicate, type unwrapDefault } from "@ark/schema";
1
+ import { type BaseParseContext, type BaseRoot, type Morph, type Predicate, type unwrapDefault } from "@ark/schema";
2
2
  import { type array, type BuiltinObjectKind, type Constructor, type Domain, type show } from "@ark/util";
3
- import type { defaultFor, distill, inferIntersection, inferMorphOut, inferPredicate, Out, withDefault } from "../attributes.ts";
3
+ import type { defaultFor, distill, inferIntersection, inferMorphOut, inferPipe, inferPredicate, Out, withDefault } from "../attributes.ts";
4
+ import type { TypeMetaInput } from "../config.ts";
4
5
  import type { type } from "../keywords/keywords.ts";
5
6
  import type { inferDefinition, validateDefinition } from "./definition.ts";
6
7
  import { writeMissingRightOperandMessage } from "./shift/operand/unenclosed.ts";
@@ -11,38 +12,73 @@ export type maybeValidateTupleExpression<def extends array, $, args> = def exten
11
12
  def[0] extends "" ? BaseCompletions<$, args, IndexZeroOperator | "..."> : def[0],
12
13
  def[1] extends "" ? BaseCompletions<$, args, IndexOneOperator | "..."> : def[1]
13
14
  ] : null;
14
- export type inferTupleExpression<def extends TupleExpression, $, args> = def[1] extends "[]" ? inferDefinition<def[0], $, args>[] : def[1] extends "?" ? inferDefinition<def[0], $, args> : def[1] extends "&" ? inferIntersection<inferDefinition<def[0], $, args>, inferDefinition<def[2], $, args>> : def[1] extends "|" ? inferDefinition<def[0], $, args> | inferDefinition<def[2], $, args> : def[1] extends ":" ? inferPredicate<inferDefinition<def[0], $, args>, def[2]> : def[1] extends "=>" ? parseMorph<def[0], def[2], $, args> : def[1] extends "=" ? withDefault<inferDefinition<def[0], $, args>, unwrapDefault<def[2]>> : def[1] extends "@" ? inferDefinition<def[0], $, args> : def extends readonly ["===", ...infer values] ? values[number] : def extends (readonly ["instanceof", ...infer constructors extends Constructor[]]) ? InstanceType<constructors[number]> : def[0] extends "keyof" ? inferKeyOfExpression<def[1], $, args> : never;
15
+ export type inferTupleExpression<def extends TupleExpression, $, args> = def[1] extends "[]" ? inferDefinition<def[0], $, args>[] : def[1] extends "?" ? inferDefinition<def[0], $, args> : def[1] extends "&" ? inferIntersection<inferDefinition<def[0], $, args>, inferDefinition<def[2], $, args>> : def[1] extends "|" ? inferDefinition<def[0], $, args> | inferDefinition<def[2], $, args> : def[1] extends ":" ? inferPredicate<inferDefinition<def[0], $, args>, def[2]> : def[1] extends "=>" ? parseMorph<def[0], def[2], $, args> : def[1] extends "|>" ? parseTo<def[0], def[2], $, args> : def[1] extends "=" ? withDefault<inferDefinition<def[0], $, args>, unwrapDefault<def[2]>> : def[1] extends "@" ? inferDefinition<def[0], $, args> : def extends readonly ["===", ...infer values] ? values[number] : def extends (readonly ["instanceof", ...infer constructors extends Constructor[]]) ? InstanceType<constructors[number]> : def[0] extends "keyof" ? inferKeyOfExpression<def[1], $, args> : never;
15
16
  export type validatePrefixExpression<def extends IndexZeroExpression, $, args> = def["length"] extends 1 ? readonly [writeMissingRightOperandMessage<def[0]>] : def[0] extends "keyof" ? readonly [def[0], validateDefinition<def[1], $, args>] : def[0] extends "===" ? readonly [def[0], ...unknown[]] : def[0] extends "instanceof" ? readonly [def[0], ...Constructor[]] : never;
16
17
  export type validateIndexOneExpression<def extends IndexOneExpression, $, args> = def[1] extends TuplePostfixOperator ? readonly [validateDefinition<def[0], $, args>, def[1]] : readonly [
17
18
  validateDefinition<def[0], $, args>,
18
19
  def["length"] extends 2 ? writeMissingRightOperandMessage<def[1]> : def[1],
19
- 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 "=" ? defaultFor<type.infer.In<def[0], $, args>> : def[1] extends "@" ? MetaSchema : validateDefinition<def[2], $, args>
20
+ 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 "@" ? TypeMetaInput : validateDefinition<def[2], $, args>
20
21
  ];
21
22
  export type UnparsedTupleExpressionInput = {
22
23
  instanceof: Constructor;
23
24
  "===": unknown;
24
25
  };
25
26
  export type UnparsedTupleOperator = show<keyof UnparsedTupleExpressionInput>;
26
- export declare const parseKeyOfTuple: PrefixParser<"keyof">;
27
+ export declare const parseKeyOfTuple: IndexZeroParser<"keyof">;
27
28
  export type inferKeyOfExpression<operandDef, $, args> = show<keyof inferDefinition<operandDef, $, args>>;
28
- export type IndexOneParser<token extends IndexOneOperator> = (def: IndexOneExpression<token>, ctx: BaseParseContext) => BaseRoot;
29
- export type PrefixParser<token extends IndexZeroOperator> = (def: IndexZeroExpression<token>, ctx: BaseParseContext) => BaseRoot;
30
29
  export type TupleExpression = IndexZeroExpression | IndexOneExpression;
31
30
  export type TupleExpressionOperator = IndexZeroOperator | IndexOneOperator;
32
- export type IndexOneOperator = TuplePostfixOperator | TupleInfixOperator;
33
31
  export type ArgTwoOperator = Exclude<IndexOneOperator, "?" | "=">;
34
- export type TuplePostfixOperator = "[]" | "?";
35
- export type TupleInfixOperator = "&" | "|" | "=>" | "=" | ":" | "@";
36
- export type IndexOneExpression<token extends IndexOneOperator = IndexOneOperator> = readonly [unknown, token, ...unknown[]];
37
32
  export declare const parseMorphTuple: IndexOneParser<"=>">;
38
- export declare const writeMalformedFunctionalExpressionMessage: (operator: ":" | "=>", value: unknown) => string;
33
+ export declare const parseToTuple: IndexOneParser<"|>">;
34
+ export declare const writeMalformedFunctionalExpressionMessage: (operator: ":" | "=>" | "|>", value: unknown) => string;
35
+ export type parseTo<inDef, outDef, $, args> = inferPipe<inferDefinition<inDef, $, args>, inferDefinition<outDef, $, args>>;
39
36
  export type parseMorph<inDef, morph, $, args> = morph extends Morph ? inferMorphOut<morph> extends infer out ? (In: distill.In<inferDefinition<inDef, $, args>>) => Out<out> : never : never;
40
37
  export declare const parseNarrowTuple: IndexOneParser<":">;
41
- export type IndexZeroOperator = "keyof" | "instanceof" | "===";
42
- export type IndexZeroExpression<token extends IndexZeroOperator = IndexZeroOperator> = readonly [token, ...unknown[]];
38
+ export type IndexOneExpression<token extends string = IndexOneOperator> = readonly [unknown, token, ...unknown[]];
39
+ type IndexOneParser<token extends string> = (def: IndexOneExpression<token>, ctx: BaseParseContext) => BaseRoot;
40
+ declare const postfixParsers: {
41
+ "?": IndexOneParser<"?">;
42
+ "[]": IndexOneParser<"[]">;
43
+ };
44
+ export type TuplePostfixOperator = keyof typeof postfixParsers;
45
+ declare const infixParsers: {
46
+ "=": IndexOneParser<"=">;
47
+ "|": IndexOneParser<"|">;
48
+ "&": IndexOneParser<"&">;
49
+ ":": IndexOneParser<":">;
50
+ "=>": IndexOneParser<"=>">;
51
+ "|>": IndexOneParser<"|>">;
52
+ "@": IndexOneParser<"@">;
53
+ };
54
+ export type TupleInfixOperator = keyof typeof infixParsers;
55
+ declare const indexOneParsers: {
56
+ "=": IndexOneParser<"=">;
57
+ "|": IndexOneParser<"|">;
58
+ "&": IndexOneParser<"&">;
59
+ ":": IndexOneParser<":">;
60
+ "=>": IndexOneParser<"=>">;
61
+ "|>": IndexOneParser<"|>">;
62
+ "@": IndexOneParser<"@">;
63
+ "?": IndexOneParser<"?">;
64
+ "[]": IndexOneParser<"[]">;
65
+ };
66
+ export type IndexOneOperator = keyof typeof indexOneParsers;
43
67
  export type InfixExpression = readonly [
44
68
  unknown,
45
69
  ArkTypeScanner.InfixToken,
46
70
  ...unknown[]
47
71
  ];
72
+ type IndexZeroParser<token extends string> = (def: IndexZeroExpression<token>, ctx: BaseParseContext) => BaseRoot;
73
+ type IndexZeroExpression<token extends string = IndexZeroOperator> = readonly [
74
+ token,
75
+ ...unknown[]
76
+ ];
77
+ declare const indexZeroParsers: {
78
+ keyof: IndexZeroParser<"keyof">;
79
+ instanceof: IndexZeroParser<"instanceof">;
80
+ "===": IndexZeroParser<"===">;
81
+ };
82
+ export type IndexZeroOperator = keyof typeof indexZeroParsers;
48
83
  export declare const writeInvalidConstructorMessage: <actual extends Domain | BuiltinObjectKind>(actual: actual) => string;
84
+ export {};
@@ -2,7 +2,7 @@ import { Disjoint, intersectNodesRoot } from "@ark/schema";
2
2
  import { objectKindOrDomainOf, throwParseError } from "@ark/util";
3
3
  import { shallowDefaultableMessage, shallowOptionalMessage } from "./ast/validate.js";
4
4
  import { writeMissingRightOperandMessage } from "./shift/operand/unenclosed.js";
5
- export const maybeParseTupleExpression = (def, ctx) => isIndexZeroExpression(def) ? prefixParsers[def[0]](def, ctx)
5
+ export const maybeParseTupleExpression = (def, ctx) => isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx)
6
6
  : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx)
7
7
  : null;
8
8
  export const parseKeyOfTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[1], ctx).keyof();
@@ -19,13 +19,17 @@ const parseBranchTuple = (def, ctx) => {
19
19
  return result;
20
20
  };
21
21
  const parseArrayTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).array();
22
- const isIndexOneExpression = (def) => indexOneParsers[def[1]] !== undefined;
23
22
  export const parseMorphTuple = (def, ctx) => {
24
23
  if (typeof def[2] !== "function") {
25
24
  return throwParseError(writeMalformedFunctionalExpressionMessage("=>", def[2]));
26
25
  }
27
26
  return ctx.$.parseOwnDefinitionFormat(def[0], ctx).pipe(def[2]);
28
27
  };
28
+ export const parseToTuple = (def, ctx) => {
29
+ const node = ctx.$.parseOwnDefinitionFormat(def[0], ctx);
30
+ const outputValidator = ctx.$.parseOwnDefinitionFormat(def[2], ctx);
31
+ return node.to(outputValidator);
32
+ };
29
33
  export const writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value})`;
30
34
  export const parseNarrowTuple = (def, ctx) => {
31
35
  if (typeof def[2] !== "function") {
@@ -34,19 +38,26 @@ export const parseNarrowTuple = (def, ctx) => {
34
38
  return ctx.$.parseOwnDefinitionFormat(def[0], ctx).constrain("predicate", def[2]);
35
39
  };
36
40
  const parseAttributeTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configureShallowDescendants(def[2]);
37
- const indexOneParsers = {
41
+ const defineIndexOneParsers = (parsers) => parsers;
42
+ const postfixParsers = defineIndexOneParsers({
38
43
  "[]": parseArrayTuple,
44
+ "?": () => throwParseError(shallowOptionalMessage)
45
+ });
46
+ const infixParsers = defineIndexOneParsers({
39
47
  "|": parseBranchTuple,
40
48
  "&": parseBranchTuple,
41
49
  ":": parseNarrowTuple,
42
50
  "=>": parseMorphTuple,
51
+ "|>": parseToTuple,
43
52
  "@": parseAttributeTuple,
44
53
  // since object and tuple literals parse there via `parseProperty`,
45
54
  // they must be shallow if parsed directly as a tuple expression
46
- "=": () => throwParseError(shallowDefaultableMessage),
47
- "?": () => throwParseError(shallowOptionalMessage)
48
- };
49
- const prefixParsers = {
55
+ "=": () => throwParseError(shallowDefaultableMessage)
56
+ });
57
+ const indexOneParsers = { ...postfixParsers, ...infixParsers };
58
+ const isIndexOneExpression = (def) => indexOneParsers[def[1]] !== undefined;
59
+ const defineIndexZeroParsers = (parsers) => parsers;
60
+ const indexZeroParsers = defineIndexZeroParsers({
50
61
  keyof: parseKeyOfTuple,
51
62
  instanceof: (def, ctx) => {
52
63
  if (typeof def[1] !== "function") {
@@ -62,6 +73,6 @@ const prefixParsers = {
62
73
  : ctx.$.node("union", { branches });
63
74
  },
64
75
  "===": (def, ctx) => ctx.$.units(def.slice(1))
65
- };
66
- const isIndexZeroExpression = (def) => prefixParsers[def[0]] !== undefined;
76
+ });
77
+ const isIndexZeroExpression = (def) => indexZeroParsers[def[0]] !== undefined;
67
78
  export const writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`;
package/out/scope.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { BaseScope, type AliasDefEntry, type ArkScopeConfig, 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";
1
+ 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 ResolvedScopeConfig, type RootKind, type RootSchema, type arkKind, type exportedNameOf, type nodeOfKind, type reducibleKindOf, type toInternalScope, type writeDuplicateAliasError } from "@ark/schema";
2
2
  import { type Brand, type ErrorType, type JsonStructure, type anyOrNever, type array, type flattenListable, type noSuggest } from "@ark/util";
3
- import type { ArkSchemaRegistry } from "./config.ts";
3
+ import type { TypeMetaInput } from "./config.ts";
4
4
  import { type GenericDeclaration, type GenericParser, type ParameterString, type baseGenericConstraints, type parseGenericParams, type parseValidGenericParams } from "./generic.ts";
5
5
  import type { Ark, type } from "./keywords/keywords.ts";
6
- import type { BoundModule, Module, Submodule, instantiateExport } from "./module.ts";
6
+ import { InternalMatchParser, type MatchParser } from "./match.ts";
7
+ import type { BoundModule, Module, Submodule, exportScope, instantiateExport } from "./module.ts";
7
8
  import type { DefAst, InferredAst } from "./parser/ast/infer.ts";
8
9
  import { type inferDefinition } from "./parser/definition.ts";
9
10
  import type { ParsedOptionalProperty } from "./parser/property.ts";
@@ -11,6 +12,8 @@ import type { ParsedDefaultableProperty } from "./parser/shift/operator/default.
11
12
  import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type EnumeratedTypeParser, type InstanceOfTypeParser, type SchemaParser, type TypeParser, type UnitTypeParser } from "./type.ts";
12
13
  /** The convenience properties attached to `scope` */
13
14
  export type ScopeParserAttachments = Omit<ScopeParser, never>;
15
+ export interface ArkScopeConfig extends ArkSchemaScopeConfig {
16
+ }
14
17
  export interface ScopeParser {
15
18
  <const def>(def: scope.validate<def>, config?: ArkScopeConfig): Scope<scope.infer<def>>;
16
19
  define: <const def>(def: scope.validate<def>) => def;
@@ -59,14 +62,19 @@ export type moduleKeyOf<$> = {
59
62
  }[keyof $];
60
63
  export interface ArkTypeRegistry extends ArkSchemaRegistry {
61
64
  typeAttachments?: Ark.boundTypeAttachments<any>;
65
+ ambient: exportScope<Ark>;
62
66
  }
63
67
  export declare const $arkTypeRegistry: ArkTypeRegistry;
64
68
  export interface InternalScope {
65
69
  constructor: typeof InternalScope;
66
70
  }
71
+ interface ResolvedTypeScopeConfig extends ResolvedScopeConfig {
72
+ keywords?: Record<string, TypeMetaInput>;
73
+ }
67
74
  export declare class InternalScope<$ extends {} = {}> extends BaseScope<$> {
75
+ resolvedConfig: ResolvedTypeScopeConfig;
68
76
  get ambientAttachments(): Ark.boundTypeAttachments<$> | undefined;
69
- protected preparseOwnAliasEntry(k: string, v: unknown): AliasDefEntry;
77
+ protected preparseOwnAliasEntry(alias: string, def: unknown): AliasDefEntry;
70
78
  parseGenericParams(def: string, opts: BaseParseOptions): array<GenericParamDef>;
71
79
  protected normalizeRootScopeValue(resolution: unknown): unknown;
72
80
  protected preparseOwnDefinitionFormat(def: unknown, opts: BaseParseOptions): BaseRoot | BaseParseContextInput;
@@ -74,11 +82,12 @@ export declare class InternalScope<$ extends {} = {}> extends BaseScope<$> {
74
82
  unit: UnitTypeParser<$>;
75
83
  enumerated: EnumeratedTypeParser<$>;
76
84
  instanceOf: InstanceOfTypeParser<$>;
77
- type: InternalTypeParser;
85
+ match: InternalMatchParser;
78
86
  declare: () => {
79
87
  type: InternalTypeParser;
80
88
  };
81
89
  define<def>(def: def): def;
90
+ type: InternalTypeParser;
82
91
  static scope: ScopeParser;
83
92
  static module: ModuleParser;
84
93
  }
@@ -105,6 +114,7 @@ export interface Scope<$ = {}> {
105
114
  unit: UnitTypeParser<$>;
106
115
  enumerated: EnumeratedTypeParser<$>;
107
116
  type: TypeParser<$>;
117
+ match: MatchParser<$>;
108
118
  declare: DeclarationParser<$>;
109
119
  define: DefinitionParser<$>;
110
120
  generic: GenericParser<$>;
package/out/scope.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { $ark, BaseScope, hasArkKind, parseGeneric } from "@ark/schema";
2
2
  import { flatMorph, isArray, isThunk, throwParseError } from "@ark/util";
3
3
  import { parseGenericParamName } from "./generic.js";
4
+ import { InternalMatchParser } from "./match.js";
4
5
  import { shallowDefaultableMessage, shallowOptionalMessage } from "./parser/ast/validate.js";
5
6
  import { parseInnerDefinition } from "./parser/definition.js";
6
7
  import { ArkTypeScanner } from "./parser/shift/scanner.js";
@@ -15,22 +16,31 @@ export class InternalScope extends BaseScope {
15
16
  this.bindReference(v)
16
17
  ]));
17
18
  }
18
- preparseOwnAliasEntry(k, v) {
19
- const firstParamIndex = k.indexOf("<");
20
- if (firstParamIndex === -1)
21
- return [k, v];
22
- if (k.at(-1) !== ">") {
19
+ preparseOwnAliasEntry(alias, def) {
20
+ const firstParamIndex = alias.indexOf("<");
21
+ if (firstParamIndex === -1) {
22
+ if (hasArkKind(def, "module") || hasArkKind(def, "generic"))
23
+ return [alias, def];
24
+ const qualifiedName = this.name === "ark" ? alias
25
+ : alias === "root" ? this.name
26
+ : `${this.name}.${alias}`;
27
+ const config = this.resolvedConfig.keywords?.[qualifiedName];
28
+ if (config)
29
+ def = [def, "@", config];
30
+ return [alias, def];
31
+ }
32
+ if (alias.at(-1) !== ">") {
23
33
  throwParseError(`'>' must be the last character of a generic declaration in a scope`);
24
34
  }
25
- const name = k.slice(0, firstParamIndex);
26
- const paramString = k.slice(firstParamIndex + 1, -1);
35
+ const name = alias.slice(0, firstParamIndex);
36
+ const paramString = alias.slice(firstParamIndex + 1, -1);
27
37
  return [
28
38
  name,
29
39
  // use a thunk definition for the generic so that we can parse
30
40
  // constraints within the current scope
31
41
  () => {
32
42
  const params = this.parseGenericParams(paramString, { alias: name });
33
- const generic = parseGeneric(params, v, this);
43
+ const generic = parseGeneric(params, def, this);
34
44
  return generic;
35
45
  }
36
46
  ];
@@ -73,13 +83,14 @@ export class InternalScope extends BaseScope {
73
83
  unit = value => this.units([value]);
74
84
  enumerated = (...values) => this.units(values);
75
85
  instanceOf = ctor => this.node("proto", { proto: ctor }, { prereduced: true });
76
- type = new InternalTypeParser(this);
86
+ match = new InternalMatchParser(this);
77
87
  declare = () => ({
78
88
  type: this.type
79
89
  });
80
90
  define(def) {
81
91
  return def;
82
92
  }
93
+ type = new InternalTypeParser(this);
83
94
  static scope = ((def, config = {}) => new InternalScope(def, config));
84
95
  static module = ((def, config = {}) => this.scope(def, config).export());
85
96
  }
package/out/type.d.ts CHANGED
@@ -1,8 +1,10 @@
1
- import { ArkErrors, BaseRoot, type BaseParseOptions, type MetaSchema, type Morph, type Predicate, type RootSchema } from "@ark/schema";
1
+ import { ArkErrors, BaseRoot, type BaseParseOptions, type Morph, type Predicate, type RootSchema } from "@ark/schema";
2
2
  import { Callable, Hkt, type Constructor, type array, type conform } from "@ark/util";
3
3
  import type { distill } from "./attributes.ts";
4
+ import type { TypeMetaInput } from "./config.ts";
4
5
  import type { Generic, GenericParser, ParameterString, baseGenericConstraints, parseValidGenericParams, validateParameterString } from "./generic.ts";
5
6
  import type { Ark, keywords, type } from "./keywords/keywords.ts";
7
+ import type { MatchParser } from "./match.ts";
6
8
  import type { BaseType } from "./methods/base.ts";
7
9
  import type { instantiateType } from "./methods/instantiate.ts";
8
10
  import type { validateDeclared } from "./parser/definition.ts";
@@ -16,7 +18,7 @@ export interface TypeParser<$ = {}> extends Ark.boundTypeAttachments<$> {
16
18
  *
17
19
  * @example const person = type({ name: "string" })
18
20
  */
19
- <const def, r = Type<type.infer<def, $>, $>>(def: type.validate<def, $>): r;
21
+ <const def, r = type.instantiate<def, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
20
22
  /**
21
23
  * Create a {@link Generic} from a parameter string and body definition.
22
24
  *
@@ -29,14 +31,14 @@ export interface TypeParser<$ = {}> extends Ark.boundTypeAttachments<$> {
29
31
  *
30
32
  * @example const boxOf = type("<t extends string | number>", { contents: "t" })
31
33
  */
32
- <const params extends ParameterString, const def>(params: validateParameterString<params, $>, def: type.validate<def, $, baseGenericConstraints<parseValidGenericParams<params, $>>>): Generic<parseValidGenericParams<params, $>, def, $>;
34
+ <const params extends ParameterString, const def, r = Generic<parseValidGenericParams<params, $>, def, $>>(params: validateParameterString<params, $>, def: type.validate<def, $, baseGenericConstraints<parseValidGenericParams<params, $>>>): r extends infer _ ? _ : never;
33
35
  /**
34
36
  * Create a {@link Type} from a [tuple expression](http://localhost:3000/docs/expressions)
35
37
  * spread as this function's arguments.
36
38
  *
37
39
  * @example type("string", "|", { foo: "number" })
38
40
  */
39
- <const zero, const one, const rest extends array, r = Type<type.infer<[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 "@" ? [MetaSchema] : [type.validate<rest[0], $>] : []): r;
41
+ <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 "@" ? [TypeMetaInput] : [type.validate<rest[0], $>] : []): r extends infer _ ? _ : never;
40
42
  /**
41
43
  * An alias of the {@link ArkErrors} class, an instance of which is returned when a {@link Type}
42
44
  * is invoked with invalid input.
@@ -64,6 +66,7 @@ export interface TypeParser<$ = {}> extends Ark.boundTypeAttachments<$> {
64
66
  scope: ScopeParser;
65
67
  define: DefinitionParser<$>;
66
68
  generic: GenericParser<$>;
69
+ match: MatchParser<$>;
67
70
  schema: SchemaParser<$>;
68
71
  /**
69
72
  * Create a {@link Type} that is satisfied only by a value strictly equal (`===`) to the argument passed to this function.
package/out/type.js CHANGED
@@ -10,6 +10,7 @@ export class InternalTypeParser extends Callable {
10
10
  module: $.constructor.module,
11
11
  scope: $.constructor.scope,
12
12
  define: $.define,
13
+ match: $.match,
13
14
  generic: $.generic,
14
15
  schema: $.schema,
15
16
  // this won't be defined during bootstrapping, but externally always will be
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "arktype",
3
- "description": "TypeScript's 1:1 validator, optimized from editor to runtime",
4
- "version": "2.0.3",
3
+ "description": "Optimized runtime validation for TypeScript syntax",
4
+ "version": "2.1.0",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -34,14 +34,18 @@
34
34
  "out"
35
35
  ],
36
36
  "dependencies": {
37
- "@ark/schema": "0.38.0",
38
- "@ark/util": "0.38.0"
37
+ "@ark/util": "0.40.0",
38
+ "@ark/schema": "0.40.0"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"
42
42
  },
43
43
  "scripts": {
44
44
  "build": "ts ../repo/build.ts",
45
- "test": "ts ../repo/testPackage.ts"
45
+ "test": "ts ../repo/testPackage.ts; pnpm testIntegration",
46
+ "testIntegration": "pnpm testSimpleConfig && pnpm testAllConfig && pnpm testOnFailConfig",
47
+ "testSimpleConfig": "ts ./__tests__/integration/testSimpleConfig.ts",
48
+ "testAllConfig": "ts ./__tests__/integration/testAllConfig.ts",
49
+ "testOnFailConfig": "ts ./__tests__/integration/testOnFailConfig.ts"
46
50
  }
47
51
  }
@@ -1,12 +0,0 @@
1
- import type { inferPipe } from "../attributes.ts";
2
- import type { type } from "../keywords/keywords.ts";
3
- import type { BaseType } from "./base.ts";
4
- /** @ts-ignore cast variance */
5
- interface Type<out t = unknown, $ = {}> extends BaseType<t, $> {
6
- /**
7
- * Append extra validation shape on the pipe output
8
- * @example type({codes: 'string.numeric[]'}).pipe(obj => obj.codes).to('string.numeric.parse[]')
9
- */
10
- to<const def, r = type.infer<def, $>>(def: type.validate<def, $>): Type<inferPipe<t, r>, $>;
11
- }
12
- export type { Type as MorphType };
@@ -1 +0,0 @@
1
- export {};