arktype 2.0.0-rc.7 → 2.0.0-rc.8

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/out/generic.d.ts CHANGED
@@ -16,9 +16,9 @@ export type validateGenericArg<arg, param extends GenericParamAst, $> = type.inf
16
16
  export type GenericInstantiator<params extends array<GenericParamAst>, def, $, args$> = params["length"] extends 1 ? {
17
17
  <const a, r = instantiateGeneric<def, params, [a], $, args$>>(a: type.validate<a, args$> & validateGenericArg<a, params[0], args$>): r;
18
18
  } : params["length"] extends 2 ? {
19
- <const a, const b, r = instantiateGeneric<def, params, [a, b], $, args$>>(...args: [type.validate<a, args$>, type.validate<b, args$>] & [
20
- validateGenericArg<a, params[0], args$>,
21
- validateGenericArg<b, params[1], args$>
19
+ <const a, const b, r = instantiateGeneric<def, params, [a, b], $, args$>>(...args: [
20
+ type.validate<a, args$> & validateGenericArg<a, params[0], args$>,
21
+ type.validate<b, args$> & validateGenericArg<b, params[1], args$>
22
22
  ]): r;
23
23
  } : params["length"] extends 3 ? {
24
24
  <const a, const b, const c, r = instantiateGeneric<def, params, [a, b, c], $, args$>>(...args: [
@@ -1,6 +1,7 @@
1
1
  import type { ArkErrors, arkKind } from "@ark/schema";
2
2
  import type { inferred } from "@ark/util";
3
3
  import type { GenericParser } from "../generic.ts";
4
+ import type { BaseType } from "../methods/base.ts";
4
5
  import type { BoundModule, Module } from "../module.ts";
5
6
  import type { inferDefinition, validateDefinition } from "../parser/definition.ts";
6
7
  import { type bindThis, type Scope } from "../scope.ts";
@@ -36,6 +37,9 @@ export declare namespace type {
36
37
  [inferred]?: t;
37
38
  };
38
39
  type errors = ArkErrors;
40
+ /** @ts-ignore cast variance */
41
+ interface Any<out t = any> extends BaseType<t, any> {
42
+ }
39
43
  type infer<def, $ = {}, args = bindThis<def>> = inferDefinition<def, $, args>;
40
44
  namespace infer {
41
45
  type In<def, $ = {}, args = {}> = distill.In<inferDefinition<def, $, args>>;
@@ -47,7 +47,7 @@ const parsableDate = rootSchema({
47
47
  predicate: isParsableDate
48
48
  }
49
49
  }).assertHasKind("intersection");
50
- const epochroot = integer.root.internal
50
+ const epochRoot = integer.root.internal
51
51
  .narrow((s, ctx) => {
52
52
  // we know this is safe since it has already
53
53
  // been validated as an integer string
@@ -64,18 +64,18 @@ const epochroot = integer.root.internal
64
64
  })
65
65
  .assertHasKind("intersection");
66
66
  const epoch = arkModule({
67
- root: epochroot,
67
+ root: epochRoot,
68
68
  parse: rootSchema({
69
- in: epochroot,
69
+ in: epochRoot,
70
70
  morphs: (s) => new Date(s),
71
71
  declaredOut: intrinsic.Date
72
72
  })
73
73
  });
74
- const isoroot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection");
74
+ const isoRoot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection");
75
75
  const iso = arkModule({
76
- root: isoroot,
76
+ root: isoRoot,
77
77
  parse: rootSchema({
78
- in: isoroot,
78
+ in: isoRoot,
79
79
  morphs: (s) => new Date(s),
80
80
  declaredOut: intrinsic.Date
81
81
  })
@@ -3,6 +3,7 @@ import type { Branded, To, constrain } from "../ast.ts";
3
3
  declare namespace string {
4
4
  type json = constrain<string, Branded<"json">>;
5
5
  }
6
+ export declare const writeJsonSyntaxErrorProblem: (error: unknown) => string;
6
7
  export declare const json: stringJson.module;
7
8
  export declare namespace stringJson {
8
9
  type module = Module<submodule>;
@@ -1,20 +1,28 @@
1
1
  import { intrinsic, rootSchema } from "@ark/schema";
2
2
  import { arkModule } from "../utils.js";
3
3
  const jsonStringDescription = "a JSON string";
4
- const isParsableJson = (s) => {
5
- try {
6
- JSON.parse(s);
7
- return true;
8
- }
9
- catch {
10
- return false;
11
- }
4
+ export const writeJsonSyntaxErrorProblem = (error) => {
5
+ if (!(error instanceof SyntaxError))
6
+ throw error;
7
+ return `must be ${jsonStringDescription} (${error})`;
12
8
  };
13
9
  const root = rootSchema({
14
10
  domain: "string",
15
11
  predicate: {
16
12
  meta: jsonStringDescription,
17
- predicate: isParsableJson
13
+ predicate: (s, ctx) => {
14
+ try {
15
+ JSON.parse(s);
16
+ return true;
17
+ }
18
+ catch (e) {
19
+ return ctx.reject({
20
+ code: "predicate",
21
+ expected: jsonStringDescription,
22
+ problem: writeJsonSyntaxErrorProblem(e)
23
+ });
24
+ }
25
+ }
18
26
  }
19
27
  });
20
28
  export const json = arkModule({
@@ -36,7 +44,7 @@ export const json = arkModule({
36
44
  return ctx.error({
37
45
  code: "predicate",
38
46
  expected: jsonStringDescription,
39
- problem: `must be ${jsonStringDescription} (${e})`
47
+ problem: writeJsonSyntaxErrorProblem(e)
40
48
  });
41
49
  }
42
50
  },
@@ -42,11 +42,13 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
42
42
  or<const def, r = type.infer<def, $>>(def: type.validate<def, $>): instantiateType<t | r, $>;
43
43
  array(): ArrayType<t[], $>;
44
44
  pipe: ChainedPipes<t, $>;
45
- equals<def>(def: type.validate<def, $>): this is instantiateType<type.infer<def, $>, $>;
46
- extract<def>(r: type.validate<def, $>): instantiateType<Extract<t, type.infer<def, $>>, $>;
47
- exclude<def>(r: type.validate<def, $>): instantiateType<Exclude<t, type.infer<def, $>>, $>;
48
- extends<def>(other: type.validate<def, $>): this is instantiateType<type.infer<def, $>, $>;
49
- overlaps<def>(r: type.validate<def, $>): boolean;
45
+ equals<const def>(def: type.validate<def, $>): boolean;
46
+ ifEquals<const def>(def: type.validate<def, $>): instantiateType<type.infer<def, $>, $> | undefined;
47
+ extends<const def>(other: type.validate<def, $>): this is instantiateType<type.infer<def, $>, $>;
48
+ ifExtends<const def>(other: type.validate<def, $>): instantiateType<type.infer<def, $>, $> | undefined;
49
+ overlaps<const def>(r: type.validate<def, $>): boolean;
50
+ extract<const def>(r: type.validate<def, $>): instantiateType<Extract<t, type.infer<def, $>>, $>;
51
+ exclude<const def>(r: type.validate<def, $>): instantiateType<Exclude<t, type.infer<def, $>>, $>;
50
52
  distribute<mapOut, reduceOut = mapOut[]>(mapBranch: (branch: Type, i: number, branches: array<Type>) => mapOut, reduceMapped?: (mappedBranches: mapOut[]) => reduceOut): reduceOut;
51
53
  /** @deprecated */
52
54
  apply: Function["apply"];
@@ -1,6 +1,7 @@
1
1
  import type { anyOrNever, array } from "@ark/util";
2
2
  import type { MorphAst } from "../keywords/ast.ts";
3
3
  import type { ArrayType } from "./array.ts";
4
+ import type { BaseType } from "./base.ts";
4
5
  import type { DateType } from "./date.ts";
5
6
  import type { MorphType } from "./morph.ts";
6
7
  import type { NumberType } from "./number.ts";
@@ -11,6 +12,6 @@ export type instantiateType<t, $> = [
11
12
  Extract<t, MorphAst>
12
13
  ] extends [anyOrNever] ? [
13
14
  t
14
- ] extends [string] ? StringType<t, $> : [t] extends [number] ? NumberType<t, $> : [t] extends [object] ? [
15
+ ] extends [anyOrNever] ? BaseType<t, $> : [t] extends [string] ? StringType<t, $> : [t] extends [number] ? NumberType<t, $> : [t] extends [object] ? [
15
16
  t
16
17
  ] extends [array] ? ArrayType<t, $> : [t] extends [Date] ? DateType<t, $> : ObjectType<t, $> : ValidatorType<t, $> : MorphType<t, $>;
@@ -10,7 +10,7 @@ export declare const parseObject: (def: object, ctx: BaseParseContext) => BaseRo
10
10
  export type inferDefinition<def, $, args> = [
11
11
  def
12
12
  ] extends [anyOrNever] ? def : def extends type.cast<infer t> ? ifEmptyObjectLiteral<def, object, t> : def extends ThunkCast<infer t> ? t : def extends string ? inferString<def, $, args> : def extends array ? inferTuple<def, $, args> : def extends RegExp ? string.matching<string> : def extends object ? inferObjectLiteral<def, $, args> : never;
13
- export type validateDefinition<def, $, args> = null extends undefined ? ErrorMessage<`'strict' or 'strictNullChecks' must be set to true in your tsconfig's 'compilerOptions'`> : [def] extends [Terminal] ? def : def extends string ? validateString<def, $, args> : def extends array ? validateTuple<def, $, args> : def extends BadDefinitionType ? ErrorMessage<writeBadDefinitionTypeMessage<objectKindOrDomainOf<def>>> : unknown extends def ? BaseCompletions<$, args> | {} : validateObjectLiteral<def, $, args>;
13
+ export type validateDefinition<def, $, args> = null extends undefined ? ErrorMessage<`'strict' or 'strictNullChecks' must be set to true in your tsconfig's 'compilerOptions'`> : [def] extends [Terminal] ? def : def extends string ? validateString<def, $, args> : def extends array ? validateTuple<def, $, args> : def extends BadDefinitionType ? ErrorMessage<writeBadDefinitionTypeMessage<objectKindOrDomainOf<def>>> : unknown extends def ? BaseCompletions<$, args> | {} : RegExp extends def ? def : validateObjectLiteral<def, $, args>;
14
14
  export type validateDeclared<declared, def, $, args> = def extends validateDefinition<def, $, args> ? validateInference<def, declared, $, args> : validateDefinition<def, $, args>;
15
15
  type validateInference<def, declared, $, args> = def extends RegExp | type.cast<unknown> | ThunkCast | TupleExpression ? validateShallowInference<def, declared, $, args> : def extends array ? declared extends array ? {
16
16
  [i in keyof declared]: i extends keyof def ? validateInference<def[i], declared[i], $, args> : declared[i];
@@ -24,7 +24,7 @@ type declarationMismatch<def, declared, $, args> = {
24
24
  declared: declared;
25
25
  inferred: inferDefinition<def, $, args>;
26
26
  };
27
- type Terminal = RegExp | type.cast<unknown> | Fn;
27
+ type Terminal = type.cast<unknown> | Fn;
28
28
  export type ThunkCast<t = unknown> = () => type.cast<t>;
29
29
  type BadDefinitionType = Exclude<Primitive, string>;
30
30
  export declare const writeBadDefinitionTypeMessage: <actual extends string>(actual: actual) => writeBadDefinitionTypeMessage<actual>;
@@ -3,7 +3,7 @@ import type { Hkt, array } from "@ark/util";
3
3
  import type { inferIntersection } from "../../intersect.ts";
4
4
  import type { arkKeyOf } from "../../keys.ts";
5
5
  import type { type } from "../../keywords/ark.ts";
6
- import type { Default, LimitLiteral, applyConstraintSchema, distill, normalizeLimit } from "../../keywords/ast.ts";
6
+ import type { Default, LimitLiteral, Optional, applyConstraint, applyConstraintSchema, distill, normalizeLimit } from "../../keywords/ast.ts";
7
7
  import type { Date } from "../../keywords/constructors/Date.ts";
8
8
  import type { UnparsedScope } from "../../scope.ts";
9
9
  import type { inferDefinition } from "../definition.ts";
@@ -27,14 +27,14 @@ export type inferExpression<ast, $, args> = ast extends array ? ast extends Infe
27
27
  [i in keyof argAsts]: inferExpression<argAsts[i], $, args>;
28
28
  }> : inferDefinition<g["bodyDef"], resolveScope<g["$"], $>, {
29
29
  [i in keyof g["names"] & `${number}` as g["names"][i]]: inferExpression<argAsts[i & keyof argAsts], resolveScope<g["arg$"], $>, args>;
30
- }> : ast[1] extends "[]" ? inferExpression<ast[0], $, args>[] : ast[1] extends "|" ? inferExpression<ast[0], $, args> | inferExpression<ast[2], $, args> : ast[1] extends "&" ? inferIntersection<inferExpression<ast[0], $, args>, inferExpression<ast[2], $, args>> : ast[1] extends "=" ? type.infer<ast[2]> extends infer defaultValue ? (In?: inferExpression<ast[0], $, args>) => Default<defaultValue> : never : ast[1] extends Comparator ? ast[0] extends LimitLiteral ? brandBound<inferExpression<ast[2], $, args>, ast[1], ast[0]> : brandBound<inferExpression<ast[0], $, args>, ast[1], ast[2] & LimitLiteral> : ast[1] extends "%" ? applyConstraintSchema<inferExpression<ast[0], $, args>, "divisor", ast[2] & number> : ast[0] extends "keyof" ? arkKeyOf<inferExpression<ast[1], $, args>> : never : never;
30
+ }> : ast[1] extends "[]" ? inferExpression<ast[0], $, args>[] : ast[1] extends "|" ? inferExpression<ast[0], $, args> | inferExpression<ast[2], $, args> : ast[1] extends "&" ? inferIntersection<inferExpression<ast[0], $, args>, inferExpression<ast[2], $, args>> : ast[1] extends "=" ? type.infer<ast[2]> extends infer defaultValue ? (In?: inferExpression<ast[0], $, args>) => Default<defaultValue> : never : ast[1] extends Comparator ? ast[0] extends LimitLiteral ? brandBound<inferExpression<ast[2], $, args>, ast[1], ast[0]> : brandBound<inferExpression<ast[0], $, args>, ast[1], ast[2] & LimitLiteral> : ast[1] extends "%" ? applyConstraintSchema<inferExpression<ast[0], $, args>, "divisor", ast[2] & number> : ast[1] extends "?" ? applyConstraint<inferExpression<ast[0], $, args>, Optional> : ast[0] extends "keyof" ? arkKeyOf<inferExpression<ast[1], $, args>> : never : never;
31
31
  export type brandBound<brandableIn, comparator extends Comparator, limit extends LimitLiteral> = distill.In<brandableIn> extends infer In ? comparator extends "==" ? In extends number ? limit : In extends Date ? Date.literal<normalizeLimit<limit>> : applyConstraintSchema<brandableIn, "exactLength", limit & number> : applyConstraintSchema<brandableIn, In extends number ? comparator extends MinComparator ? "min" : "max" : In extends string | array ? comparator extends MinComparator ? "minLength" : "maxLength" : comparator extends MinComparator ? "after" : "before", {
32
32
  rule: normalizeLimit<limit>;
33
33
  exclusive: comparator extends ">" | "<" ? true : false;
34
34
  }> : never;
35
35
  export type PrefixOperator = "keyof" | "instanceof" | "===" | "node";
36
36
  export type PrefixExpression<operator extends PrefixOperator = PrefixOperator, operand = unknown> = [operator, operand];
37
- export type PostfixOperator = "[]";
37
+ export type PostfixOperator = "[]" | "?";
38
38
  export type PostfixExpression<operator extends PostfixOperator = PostfixOperator, operand = unknown> = readonly [operand, operator];
39
39
  export type InfixOperator = "|" | "&" | Comparator | "%" | ":" | "=>" | "@" | "=";
40
40
  export type InfixExpression<operator extends InfixOperator = InfixOperator, l = unknown, r = unknown> = [l, operator, r];
@@ -11,7 +11,7 @@ import type { validateDivisor } from "./divisor.ts";
11
11
  import type { DefAst, GenericInstantiationAst, inferAstRoot, InferredAst, InfixExpression, PostfixExpression } from "./infer.ts";
12
12
  import type { validateKeyof } from "./keyof.ts";
13
13
  import type { astToString } from "./utils.ts";
14
- export type validateAst<ast, $, args> = ast extends ErrorMessage ? ast : ast extends InferredAst ? validateInferredAst<ast[0], ast[2]> : ast extends DefAst ? ast[2] extends PrivateDeclaration ? ErrorMessage<writePrefixedPrivateReferenceMessage<ast[2]>> : undefined : ast extends PostfixExpression<infer operator, infer operand> ? operator extends "[]" ? validateAst<operand, $, args> : never : ast extends InfixExpression<infer operator, infer l, infer r> ? operator extends "&" | "|" ? validateInfix<ast, $, args> : operator extends Comparator ? validateRange<l, operator, r, $, args> : operator extends "%" ? validateDivisor<l, $, args> : operator extends "=" ? validateDefault<l, r & UnitLiteral, $, args> : never : ast extends ["keyof", infer operand] ? validateKeyof<operand, $, args> : ast extends GenericInstantiationAst<infer g, infer argAsts> ? validateGenericArgs<g["paramsAst"], argAsts, $, args, []> : ErrorMessage<writeUnexpectedExpressionMessage<astToString<ast>>> & {
14
+ export type validateAst<ast, $, args> = ast extends ErrorMessage ? ast : ast extends InferredAst ? validateInferredAst<ast[0], ast[2]> : ast extends DefAst ? ast[2] extends PrivateDeclaration ? ErrorMessage<writePrefixedPrivateReferenceMessage<ast[2]>> : undefined : ast extends PostfixExpression<infer operator, infer operand> ? operator extends "[]" ? validateAst<operand, $, args> : operator extends "?" ? validateAst<operand, $, args> : never : ast extends InfixExpression<infer operator, infer l, infer r> ? operator extends "&" | "|" ? validateInfix<ast, $, args> : operator extends Comparator ? validateRange<l, operator, r, $, args> : operator extends "%" ? validateDivisor<l, $, args> : operator extends "=" ? validateDefault<l, r & UnitLiteral, $, args> : never : ast extends ["keyof", infer operand] ? validateKeyof<operand, $, args> : ast extends GenericInstantiationAst<infer g, infer argAsts> ? validateGenericArgs<g["paramsAst"], argAsts, $, args, []> : ErrorMessage<writeUnexpectedExpressionMessage<astToString<ast>>> & {
15
15
  ast: ast;
16
16
  };
17
17
  type writeUnexpectedExpressionMessage<expression extends string> = `Unexpectedly failed to parse the expression resulting from ${expression}`;
@@ -34,19 +34,21 @@ export declare class Scanner<lookahead extends string = string> {
34
34
  readonly "%": true;
35
35
  readonly ",": true;
36
36
  readonly ":": true;
37
+ readonly "?": true;
37
38
  };
38
39
  static finalizingLookaheads: {
39
40
  readonly ">": true;
40
41
  readonly ",": true;
41
42
  readonly "": true;
42
43
  readonly "=": true;
44
+ readonly "?": true;
43
45
  };
44
46
  static lookaheadIsTerminator: Scanner.UntilCondition;
45
47
  static lookaheadIsNotWhitespace: Scanner.UntilCondition;
46
48
  static lookaheadIsFinalizing: (lookahead: string, unscanned: string) => lookahead is ">" | "," | "=";
47
49
  }
48
50
  export declare namespace Scanner {
49
- 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;
51
+ 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;
50
52
  type UntilCondition = (scanner: Scanner, shifted: string) => boolean;
51
53
  type OnInputEndFn = (scanner: Scanner, shifted: string) => string;
52
54
  type ShiftUntilOptions = {
@@ -74,13 +74,15 @@ export class Scanner {
74
74
  "%": true,
75
75
  ",": true,
76
76
  ":": true,
77
+ "?": true,
77
78
  ...whiteSpaceTokens
78
79
  };
79
80
  static finalizingLookaheads = {
80
81
  ">": true,
81
82
  ",": true,
82
83
  "": true,
83
- "=": true
84
+ "=": true,
85
+ "?": true
84
86
  };
85
87
  static lookaheadIsTerminator = (scanner) => scanner.lookahead in this.terminatingChars;
86
88
  static lookaheadIsNotWhitespace = (scanner) => !(scanner.lookahead in whiteSpaceTokens);
@@ -95,6 +97,6 @@ export class Scanner {
95
97
  // "=" is a finalizer on its own (representing a default value),
96
98
  // but not with a second "=" (an equality comparator)
97
99
  : lookahead === "=" ? unscanned[0] !== "="
98
- // ","" is unambiguously a finalizer
99
- : lookahead === ",";
100
+ // "," and "?" are unambiguously finalizers
101
+ : lookahead === "," || lookahead === "?";
100
102
  }
@@ -25,5 +25,5 @@ export declare const parseUntilFinalizer: (s: DynamicState) => DynamicStateWithR
25
25
  export type parseUntilFinalizer<s extends StaticState, $, args> = s["finalizer"] extends undefined ? parseUntilFinalizer<next<s, $, args>, $, args> : s;
26
26
  declare const next: (s: DynamicState) => void;
27
27
  type next<s extends StaticState, $, args> = s["root"] extends undefined ? parseOperand<s, $, args> : parseOperator<s, $, args>;
28
- export type extractFinalizedResult<s extends StaticState> = s["finalizer"] extends "" ? s["root"] : s["finalizer"] extends ErrorMessage ? s["finalizer"] : s["finalizer"] extends "=" ? parseDefault<s["root"], s["unscanned"]> : state.error<writeUnexpectedCharacterMessage<`${s["finalizer"]}`>>;
28
+ 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"]> : state.error<writeUnexpectedCharacterMessage<`${s["finalizer"]}`>>;
29
29
  export {};
@@ -9,6 +9,8 @@ export const fullStringParse = (s) => {
9
9
  }
10
10
  if (s.finalizer === "=")
11
11
  result = parseDefault(s);
12
+ else if (s.finalizer === "?")
13
+ result = result.optional();
12
14
  s.scanner.shiftUntilNonWhitespace();
13
15
  if (s.scanner.lookahead) {
14
16
  // throw a parse error if non-whitespace characters made it here without being parsed
@@ -1,8 +1,8 @@
1
1
  import { type BaseParseContext, type BaseRoot, type MetaSchema, type Morph, type Predicate } from "@ark/schema";
2
- import { type array, type BuiltinObjectKind, type conform, type Constructor, type Domain, type ErrorMessage, type show } from "@ark/util";
2
+ import { type anyOrNever, type array, type BuiltinObjectKind, type conform, type Constructor, type Domain, type ErrorMessage, type show } from "@ark/util";
3
3
  import type { inferIntersection } from "../intersect.ts";
4
4
  import type { type } from "../keywords/ark.ts";
5
- import type { Default, distill, inferMorphOut, inferPredicate, Out } from "../keywords/ast.ts";
5
+ import type { applyConstraint, Default, distill, inferMorphOut, inferPredicate, Optional, OptionalAst, Out } from "../keywords/ast.ts";
6
6
  import type { inferDefinition, validateDefinition } from "./definition.ts";
7
7
  import type { InfixOperator, PostfixExpression } from "./semantic/infer.ts";
8
8
  import { writeMissingRightOperandMessage } from "./string/shift/operand/unenclosed.ts";
@@ -12,7 +12,7 @@ export declare const parseTupleLiteral: (def: array, ctx: BaseParseContext) => B
12
12
  type InfixExpression = readonly [unknown, InfixOperator, ...unknown[]];
13
13
  export type validateTuple<def extends array, $, args> = def extends IndexZeroExpression ? validatePrefixExpression<def, $, args> : def extends PostfixExpression ? validatePostfixExpression<def, $, args> : def extends InfixExpression ? validateInfixExpression<def, $, args> : def extends (readonly ["", ...unknown[]] | readonly [unknown, "", ...unknown[]]) ? readonly [
14
14
  def[0] extends "" ? BaseCompletions<$, args, IndexZeroOperator | "..."> : def[0],
15
- def[1] extends "" ? BaseCompletions<$, args, IndexOneOperator | "..." | "?"> : def[1]
15
+ def[1] extends "" ? BaseCompletions<$, args, IndexOneOperator | "..."> : def[1]
16
16
  ] : validateTupleLiteral<def, $, args>;
17
17
  export type validateTupleLiteral<def extends array, $, args> = parseSequence<def, $, args> extends infer s extends SequenceParseState ? Readonly<s["validated"]> : never;
18
18
  type inferTupleLiteral<def extends array, $, args> = parseSequence<def, $, args> extends infer s extends SequenceParseState ? s["inferred"] : never;
@@ -20,55 +20,75 @@ type SequenceParseState = {
20
20
  unscanned: array;
21
21
  inferred: array;
22
22
  validated: array;
23
+ includesOptional: boolean;
23
24
  };
24
25
  type parseSequence<def extends array, $, args> = parseNextElement<{
25
26
  unscanned: def;
26
27
  inferred: [];
27
28
  validated: [];
29
+ includesOptional: false;
28
30
  }, $, args>;
29
31
  type PreparsedElement = {
30
32
  head: unknown;
31
33
  tail: array;
34
+ inferred: unknown;
32
35
  optional: boolean;
33
36
  spread: boolean;
34
37
  };
35
38
  declare namespace PreparsedElement {
36
39
  type from<result extends PreparsedElement> = result;
37
40
  }
38
- type preparseNextElement<s extends SequenceParseState> = s["unscanned"] extends readonly ["...", infer head, ...infer tail] ? tail extends readonly ["?", ...infer postOptionalTail] ? PreparsedElement.from<{
41
+ type preparseNextElement<s extends SequenceParseState, $, args> = s["unscanned"] extends readonly ["...", infer head, ...infer tail] ? inferDefinition<head, $, args> extends infer t ? [
42
+ t
43
+ ] extends [anyOrNever] ? PreparsedElement.from<{
39
44
  head: head;
40
- tail: postOptionalTail;
45
+ tail: tail;
46
+ inferred: t;
47
+ optional: false;
48
+ spread: true;
49
+ }> : [t] extends [OptionalAst<infer base>] ? PreparsedElement.from<{
50
+ head: head;
51
+ tail: tail;
52
+ inferred: base;
41
53
  optional: true;
42
54
  spread: true;
43
55
  }> : PreparsedElement.from<{
44
56
  head: head;
45
57
  tail: tail;
58
+ inferred: t;
46
59
  optional: false;
47
60
  spread: true;
48
- }> : s["unscanned"] extends readonly [infer head, "?", ...infer tail] ? PreparsedElement.from<{
61
+ }> : never : s["unscanned"] extends readonly [infer head, ...infer tail] ? inferDefinition<head, $, args> extends infer t ? [
62
+ t
63
+ ] extends [anyOrNever] ? PreparsedElement.from<{
49
64
  head: head;
50
65
  tail: tail;
66
+ inferred: t;
67
+ optional: false;
68
+ spread: false;
69
+ }> : [t] extends [OptionalAst<infer base>] ? PreparsedElement.from<{
70
+ head: head;
71
+ tail: tail;
72
+ inferred: base;
51
73
  optional: true;
52
74
  spread: false;
53
- }> : s["unscanned"] extends readonly [infer head, ...infer tail] ? PreparsedElement.from<{
75
+ }> : PreparsedElement.from<{
54
76
  head: head;
55
77
  tail: tail;
78
+ inferred: t;
56
79
  optional: false;
57
80
  spread: false;
58
- }> : null;
59
- type parseNextElement<s extends SequenceParseState, $, args> = preparseNextElement<s> extends infer next extends PreparsedElement ? parseNextElement<{
81
+ }> : never : null;
82
+ type parseNextElement<s extends SequenceParseState, $, args> = preparseNextElement<s, $, args> extends infer next extends PreparsedElement ? parseNextElement<{
60
83
  unscanned: next["tail"];
61
84
  inferred: next["spread"] extends true ? [
62
85
  ...s["inferred"],
63
- ...conform<inferDefinition<next["head"], $, args>, array>
64
- ] : next["optional"] extends true ? [
65
- ...s["inferred"],
66
- inferDefinition<next["head"], $, args>?
67
- ] : [...s["inferred"], inferDefinition<next["head"], $, args>];
86
+ ...conform<next["inferred"], array>
87
+ ] : next["optional"] extends true ? [...s["inferred"], next["inferred"]?] : [...s["inferred"], next["inferred"]];
68
88
  validated: [
69
89
  ...s["validated"],
70
90
  ...(next["spread"] extends true ? [
71
- inferDefinition<next["head"], $, args> extends (infer spreadOperand extends array) ? [
91
+ next["inferred"] extends infer spreadOperand extends array ? [
72
92
  number,
73
93
  number
74
94
  ] extends ([
@@ -76,17 +96,9 @@ type parseNextElement<s extends SequenceParseState, $, args> = preparseNextEleme
76
96
  spreadOperand["length"]
77
97
  ]) ? ErrorMessage<multipleVariadicMessage> : "..." : ErrorMessage<writeNonArraySpreadMessage<next["head"]>>
78
98
  ] : []),
79
- [
80
- next["optional"] | next["spread"],
81
- "?"
82
- ] extends ([
83
- false,
84
- s["validated"][number]
85
- ]) ? ErrorMessage<requiredPostOptionalMessage> : validateDefinition<next["head"], $, args>,
86
- ...(next["optional"] extends true ? [
87
- next["spread"] extends true ? ErrorMessage<spreadOptionalMessage> : number extends s["inferred"]["length"] ? ErrorMessage<optionalPostVariadicMessage> : "?"
88
- ] : [])
99
+ next["optional"] extends true ? next["spread"] extends true ? ErrorMessage<spreadOptionalMessage> : number extends s["inferred"]["length"] ? ErrorMessage<optionalPostVariadicMessage> : validateDefinition<next["head"], $, args> : [s["includesOptional"], next["spread"]] extends [true, false] ? ErrorMessage<requiredPostOptionalMessage> : validateDefinition<next["head"], $, args>
89
100
  ];
101
+ includesOptional: s["includesOptional"] | next["optional"] extends (false) ? false : true;
90
102
  }, $, args> : s;
91
103
  export declare const writeNonArraySpreadMessage: <operand extends string>(operand: operand) => writeNonArraySpreadMessage<operand>;
92
104
  type writeNonArraySpreadMessage<operand> = `Spread element must be an array${operand extends string ? ` (was ${operand})` : ""}`;
@@ -99,9 +111,9 @@ type optionalPostVariadicMessage = typeof optionalPostVariadicMessage;
99
111
  export declare const spreadOptionalMessage = "A spread element cannot be optional";
100
112
  type spreadOptionalMessage = typeof optionalPostVariadicMessage;
101
113
  export type inferTuple<def extends array, $, args> = def extends TupleExpression ? inferTupleExpression<def, $, args> : inferTupleLiteral<def, $, args>;
102
- export type inferTupleExpression<def extends TupleExpression, $, 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 "@" ? inferDefinition<def[0], $, args> : def[1] extends "=" ? (In?: inferDefinition<def[0], $, args>) => Default<def[2]> : 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;
114
+ export type inferTupleExpression<def extends TupleExpression, $, 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 "@" ? inferDefinition<def[0], $, args> : def[1] extends "=" ? (In?: inferDefinition<def[0], $, args>) => Default<def[2]> : def[1] extends "?" ? applyConstraint<inferDefinition<def[0], $, args>, Optional> : 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;
103
115
  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;
104
- export type validatePostfixExpression<def extends PostfixExpression, $, args> = conform<def, readonly [validateDefinition<def[0], $, args>, "[]"]>;
116
+ export type validatePostfixExpression<def extends PostfixExpression, $, args> = conform<def, readonly [validateDefinition<def[0], $, args>, "[]" | "?"]>;
105
117
  export type validateInfixExpression<def extends InfixExpression, $, args> = def["length"] extends 2 ? readonly [def[0], writeMissingRightOperandMessage<def[1]>] : readonly [
106
118
  validateDefinition<def[0], $, args>,
107
119
  def[1],
@@ -114,18 +126,18 @@ export type UnparsedTupleExpressionInput = {
114
126
  export type UnparsedTupleOperator = show<keyof UnparsedTupleExpressionInput>;
115
127
  export declare const parseKeyOfTuple: PrefixParser<"keyof">;
116
128
  export type inferKeyOfExpression<operandDef, $, args> = show<keyof inferDefinition<operandDef, $, args>>;
117
- export type PostfixParser<token extends IndexOneOperator> = (def: IndexOneExpression<token>, ctx: BaseParseContext) => BaseRoot;
129
+ export type IndexOneParser<token extends IndexOneOperator> = (def: IndexOneExpression<token>, ctx: BaseParseContext) => BaseRoot;
118
130
  export type PrefixParser<token extends IndexZeroOperator> = (def: IndexZeroExpression<token>, ctx: BaseParseContext) => BaseRoot;
119
131
  export type TupleExpression = IndexZeroExpression | IndexOneExpression;
120
132
  export type TupleExpressionOperator = IndexZeroOperator | IndexOneOperator;
121
133
  export type IndexOneOperator = TuplePostfixOperator | TupleInfixOperator;
122
- export type TuplePostfixOperator = "[]";
134
+ export type TuplePostfixOperator = "[]" | "?";
123
135
  export type TupleInfixOperator = "&" | "|" | "=>" | ":" | "@" | "=";
124
136
  export type IndexOneExpression<token extends IndexOneOperator = IndexOneOperator> = readonly [unknown, token, ...unknown[]];
125
- export declare const parseMorphTuple: PostfixParser<"=>">;
137
+ export declare const parseMorphTuple: IndexOneParser<"=>">;
126
138
  export declare const writeMalformedFunctionalExpressionMessage: (operator: ":" | "=>", value: unknown) => string;
127
139
  export type parseMorph<inDef, morph, $, args> = morph extends Morph ? inferMorphOut<morph> extends infer out ? (In: distill.brandable.In<inferDefinition<inDef, $, args>>) => Out<out> : never : never;
128
- export declare const parseNarrowTuple: PostfixParser<":">;
140
+ export declare const parseNarrowTuple: IndexOneParser<":">;
129
141
  export type IndexZeroOperator = "keyof" | "instanceof" | "===";
130
142
  export type IndexZeroExpression<token extends IndexZeroOperator = IndexZeroOperator> = readonly [token, ...unknown[]];
131
143
  export declare const writeInvalidConstructorMessage: <actual extends Domain | BuiltinObjectKind>(actual: actual) => string;
@@ -7,19 +7,12 @@ export const parseTupleLiteral = (def, ctx) => {
7
7
  let i = 0;
8
8
  while (i < def.length) {
9
9
  let spread = false;
10
- let optional = false;
11
10
  if (def[i] === "..." && i < def.length - 1) {
12
11
  spread = true;
13
12
  i++;
14
13
  }
15
14
  const element = ctx.$.parseOwnDefinitionFormat(def[i], ctx);
16
15
  i++;
17
- if (def[i] === "?") {
18
- if (spread)
19
- return throwParseError(spreadOptionalMessage);
20
- optional = true;
21
- i++;
22
- }
23
16
  if (spread) {
24
17
  if (!element.extends($ark.intrinsic.Array))
25
18
  return throwParseError(writeNonArraySpreadMessage(element.expression));
@@ -31,7 +24,7 @@ export const parseTupleLiteral = (def, ctx) => {
31
24
  element.distribute(branch => appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)));
32
25
  }
33
26
  else {
34
- sequences = sequences.map(base => appendElement(base, optional ? "optional" : "required", element));
27
+ sequences = sequences.map(base => appendElement(base, element.meta.optional ? "optional" : "required", element));
35
28
  }
36
29
  }
37
30
  return ctx.$.parseSchema(sequences.map(sequence => isEmptyObject(sequence) ?
@@ -139,10 +132,12 @@ export const parseNarrowTuple = (def, ctx) => {
139
132
  };
140
133
  const parseAttributeTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configureShallowDescendants(def[2]);
141
134
  const parseDefaultTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).default(def[2]);
135
+ const parseOptionalTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).optional();
142
136
  const indexOneParsers = {
137
+ "[]": parseArrayTuple,
138
+ "?": parseOptionalTuple,
143
139
  "|": parseBranchTuple,
144
140
  "&": parseBranchTuple,
145
- "[]": parseArrayTuple,
146
141
  ":": parseNarrowTuple,
147
142
  "=>": parseMorphTuple,
148
143
  "@": parseAttributeTuple,
package/out/scope.d.ts CHANGED
@@ -2,11 +2,11 @@ import { BaseScope, type AliasDefEntry, type ArkScopeConfig, type BaseNode, type
2
2
  import { type ErrorType, type Json, type anyOrNever, type array, type flattenListable, type noSuggest, type nominal } from "@ark/util";
3
3
  import type { ArkSchemaRegistry } from "./config.ts";
4
4
  import { type GenericDeclaration, type GenericParser, type ParameterString, type baseGenericConstraints, type parseGenericParams, type parseValidGenericParams } from "./generic.ts";
5
- import type { Ark } from "./keywords/ark.ts";
5
+ import type { Ark, type } from "./keywords/ark.ts";
6
6
  import type { BoundModule, Module, Submodule, instantiateExport } from "./module.ts";
7
7
  import { type inferDefinition, type validateDefinition } from "./parser/definition.ts";
8
8
  import type { DefAst, InferredAst } from "./parser/semantic/infer.ts";
9
- import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type EnumeratedTypeParser, type SchemaParser, type Type, type TypeParser, type UnitTypeParser } from "./type.ts";
9
+ import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type EnumeratedTypeParser, type SchemaParser, type TypeParser, type UnitTypeParser } from "./type.ts";
10
10
  export type ScopeParser = <const def>(def: scope.validate<def>, config?: ArkScopeConfig) => Scope<scope.infer<def>>;
11
11
  export type ModuleParser = <const def>(def: scope.validate<def>, config?: ArkScopeConfig) => scope.infer<def> extends infer $ ? Module<{
12
12
  [k in exportedNameOf<$>]: $[k];
@@ -80,7 +80,7 @@ export declare class InternalScope<$ extends {} = {}> extends BaseScope<$> {
80
80
  export declare const scope: ScopeParser;
81
81
  export declare namespace scope {
82
82
  type validate<def> = {
83
- [k in keyof def]: k extends noSuggest ? unknown : parseScopeKey<k, def>["params"] extends infer params ? params extends array<GenericParamAst> ? params["length"] extends 0 ? def[k] extends Type.Any | 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;
83
+ [k in keyof def]: k extends noSuggest ? unknown : parseScopeKey<k, def>["params"] extends infer params ? params extends array<GenericParamAst> ? params["length"] extends 0 ? def[k] extends type.Any | 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;
84
84
  };
85
85
  type infer<def> = inferBootstrapped<bootstrapAliases<def>>;
86
86
  }
package/out/type.d.ts CHANGED
@@ -12,17 +12,18 @@ import type { InternalScope, ModuleParser, Scope, ScopeParser, bindThis } from "
12
12
  export type TypeParserAttachments = Omit<TypeParser, never>;
13
13
  export interface TypeParser<$ = {}> extends Ark.boundTypeAttachments<$> {
14
14
  <const def, r = Type<type.infer<def, $>, $>>(def: type.validate<def, $>): r;
15
- <params extends ParameterString, const def>(params: validateParameterString<params, $>, def: validateDefinition<def, $, baseGenericConstraints<parseValidGenericParams<params, $>>>): Generic<parseValidGenericParams<params, $>, def, $>;
15
+ <const params extends ParameterString, const def>(params: validateParameterString<params, $>, def: validateDefinition<def, $, baseGenericConstraints<parseValidGenericParams<params, $>>>): Generic<parseValidGenericParams<params, $>, def, $>;
16
16
  <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, IndexOneOperator>, ..._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;
17
17
  $: Scope<$>;
18
18
  raw(def: unknown): BaseType<any, $>;
19
19
  errors: typeof ArkErrors;
20
20
  hkt: typeof Hkt;
21
+ ark: typeof ark;
21
22
  module: ModuleParser;
22
23
  scope: ScopeParser;
24
+ define: DefinitionParser<$>;
23
25
  generic: GenericParser<$>;
24
26
  schema: SchemaParser<$>;
25
- ark: typeof ark;
26
27
  unit: UnitTypeParser<$>;
27
28
  enumerated: EnumeratedTypeParser<$>;
28
29
  }
@@ -34,11 +35,8 @@ export type DeclarationParser<$> = <preinferred>() => {
34
35
  };
35
36
  export type UnitTypeParser<$> = <const t>(value: t) => Type<t, $>;
36
37
  export type EnumeratedTypeParser<$> = <const values extends readonly unknown[]>(...values: values) => Type<values[number], $>;
37
- export type DefinitionParser<$> = <def>(def: type.validate<def, $>) => def;
38
+ export type DefinitionParser<$> = <const def>(def: type.validate<def, $>) => def;
38
39
  export type SchemaParser<$> = (schema: RootSchema, opts?: BaseParseOptions) => Type<unknown, $>;
39
40
  export type Type<t = unknown, $ = {}> = instantiateType<t, $>;
40
- export declare namespace Type {
41
- type Any<t = any> = BaseType<t, any>;
42
- }
43
41
  export type TypeConstructor<t = unknown, $ = {}> = new (def: unknown, $: Scope<$>) => Type<t, $>;
44
42
  export declare const Type: TypeConstructor;
package/out/type.js CHANGED
@@ -9,6 +9,7 @@ export class InternalTypeParser extends Callable {
9
9
  raw: $.parse,
10
10
  module: $.constructor.module,
11
11
  scope: $.constructor.scope,
12
+ define: $.define,
12
13
  generic: $.generic,
13
14
  schema: $.schema,
14
15
  // 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
3
  "description": "TypeScript's 1:1 validator, optimized from editor to runtime",
4
- "version": "2.0.0-rc.7",
4
+ "version": "2.0.0-rc.8",
5
5
  "license": "MIT",
6
6
  "author": {
7
7
  "name": "David Blass",
@@ -34,8 +34,8 @@
34
34
  "out"
35
35
  ],
36
36
  "dependencies": {
37
- "@ark/util": "0.9.0",
38
- "@ark/schema": "0.9.0"
37
+ "@ark/schema": "0.10.0",
38
+ "@ark/util": "0.10.0"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"