arktype 2.0.0-rc.4 → 2.0.0-rc.5

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.
Files changed (79) hide show
  1. package/out/generic.js +1 -1
  2. package/out/index.d.ts +1 -1
  3. package/out/index.js +1 -1
  4. package/out/keywords/ark.d.ts +17 -1
  5. package/out/keywords/ast.d.ts +94 -101
  6. package/out/keywords/constructors/Array.d.ts +1 -1
  7. package/out/keywords/constructors/Array.js +2 -2
  8. package/out/keywords/constructors/Date.d.ts +31 -0
  9. package/out/keywords/constructors/FormData.d.ts +1 -1
  10. package/out/keywords/constructors/FormData.js +1 -1
  11. package/out/keywords/number/epoch.d.ts +1 -2
  12. package/out/keywords/number/number.d.ts +23 -6
  13. package/out/keywords/number/number.js +1 -1
  14. package/out/keywords/string/capitalize.d.ts +1 -1
  15. package/out/keywords/string/capitalize.js +1 -1
  16. package/out/keywords/string/date.d.ts +3 -3
  17. package/out/keywords/string/date.js +7 -7
  18. package/out/keywords/string/integer.d.ts +1 -1
  19. package/out/keywords/string/integer.js +3 -3
  20. package/out/keywords/string/ip.d.ts +1 -1
  21. package/out/keywords/string/ip.js +1 -1
  22. package/out/keywords/string/json.d.ts +1 -1
  23. package/out/keywords/string/json.js +2 -2
  24. package/out/keywords/string/lower.d.ts +1 -1
  25. package/out/keywords/string/lower.js +1 -1
  26. package/out/keywords/string/normalize.d.ts +14 -14
  27. package/out/keywords/string/normalize.js +5 -5
  28. package/out/keywords/string/numeric.d.ts +1 -1
  29. package/out/keywords/string/numeric.js +3 -3
  30. package/out/keywords/string/string.d.ts +17 -18
  31. package/out/keywords/string/string.js +1 -1
  32. package/out/keywords/string/trim.d.ts +1 -1
  33. package/out/keywords/string/trim.js +1 -1
  34. package/out/keywords/string/upper.d.ts +1 -1
  35. package/out/keywords/string/upper.js +1 -1
  36. package/out/keywords/string/url.d.ts +1 -1
  37. package/out/keywords/string/url.js +3 -3
  38. package/out/keywords/string/uuid.d.ts +2 -2
  39. package/out/keywords/string/uuid.js +1 -1
  40. package/out/{subtypes → methods}/array.d.ts +6 -6
  41. package/out/{subtypes → methods}/base.d.ts +17 -15
  42. package/out/{subtypes → methods}/date.d.ts +5 -5
  43. package/out/{subtypes → methods}/morph.d.ts +2 -2
  44. package/out/{subtypes → methods}/number.d.ts +6 -6
  45. package/out/{subtypes → methods}/string.d.ts +7 -7
  46. package/out/{subtypes → methods}/validator.d.ts +2 -2
  47. package/out/methods/validator.js +1 -0
  48. package/out/module.d.ts +2 -2
  49. package/out/parser/objectLiteral.d.ts +5 -30
  50. package/out/parser/objectLiteral.js +18 -21
  51. package/out/parser/semantic/default.d.ts +1 -2
  52. package/out/parser/semantic/default.js +1 -1
  53. package/out/parser/semantic/infer.d.ts +7 -6
  54. package/out/parser/semantic/validate.d.ts +2 -2
  55. package/out/parser/string/reduce/dynamic.d.ts +1 -2
  56. package/out/parser/string/reduce/dynamic.js +2 -4
  57. package/out/parser/string/shift/operand/date.d.ts +2 -0
  58. package/out/parser/string/shift/operand/enclosed.d.ts +2 -1
  59. package/out/parser/string/shift/operator/default.d.ts +2 -5
  60. package/out/parser/string/shift/operator/default.js +1 -6
  61. package/out/parser/string/string.d.ts +2 -3
  62. package/out/parser/tuple.d.ts +6 -5
  63. package/out/parser/tuple.js +3 -1
  64. package/out/scope.d.ts +8 -5
  65. package/out/scope.js +7 -6
  66. package/out/type.d.ts +8 -4
  67. package/out/type.js +3 -1
  68. package/package.json +3 -3
  69. /package/out/{subtypes/array.js → keywords/constructors/Date.js} +0 -0
  70. /package/out/{subtypes/base.js → methods/array.js} +0 -0
  71. /package/out/{subtypes/date.js → methods/base.js} +0 -0
  72. /package/out/{subtypes/instantiate.js → methods/date.js} +0 -0
  73. /package/out/{subtypes → methods}/instantiate.d.ts +0 -0
  74. /package/out/{subtypes/morph.js → methods/instantiate.js} +0 -0
  75. /package/out/{subtypes/number.js → methods/morph.js} +0 -0
  76. /package/out/{subtypes/object.js → methods/number.js} +0 -0
  77. /package/out/{subtypes → methods}/object.d.ts +0 -0
  78. /package/out/{subtypes/string.js → methods/object.js} +0 -0
  79. /package/out/{subtypes/validator.js → methods/string.js} +0 -0
@@ -1,6 +1,5 @@
1
- import { ArkErrors, normalizeIndex } from "@ark/schema";
2
- import { append, escapeToken, isArray, printable, stringAndSymbolicEntriesOf, throwParseError } from "@ark/util";
3
- import { writeUnassignableDefaultValueMessage } from "./semantic/default.js";
1
+ import { normalizeIndex } from "@ark/schema";
2
+ import { append, escapeToken, printable, stringAndSymbolicEntriesOf, throwParseError } from "@ark/util";
4
3
  export const parseObjectLiteral = (def, ctx) => {
5
4
  let spread;
6
5
  const structure = {};
@@ -45,22 +44,7 @@ export const parseEntry = (key, value, ctx) => {
45
44
  }
46
45
  if (parsedKey.kind === "...")
47
46
  return { kind: "spread", node: ctx.$.parse(value, ctx) };
48
- const parsedValue = isArray(value) && value[1] === "=" ?
49
- [ctx.$.parse(value[0], ctx), "=", value[2]]
50
- : ctx.$.parse(value, ctx, true);
51
- if (isArray(parsedValue)) {
52
- if (parsedKey.kind !== "required")
53
- throwParseError(invalidDefaultKeyKindMessage);
54
- const out = parsedValue[0].traverse(parsedValue[2]);
55
- if (out instanceof ArkErrors) {
56
- throwParseError(writeUnassignableDefaultValueMessage(printable(parsedKey.key), out.message));
57
- }
58
- return ctx.$.node("optional", {
59
- key: parsedKey.key,
60
- value: parsedValue[0],
61
- default: parsedValue[2]
62
- });
63
- }
47
+ const parsedValue = ctx.$.parse(value, ctx);
64
48
  if (parsedKey.kind === "index") {
65
49
  const signature = ctx.$.parse(parsedKey.key, ctx);
66
50
  const normalized = normalizeIndex(signature, parsedValue, ctx.$);
@@ -70,13 +54,26 @@ export const parseEntry = (key, value, ctx) => {
70
54
  : normalized.index
71
55
  : (normalized.required ?? []));
72
56
  }
57
+ if (parsedValue.meta) {
58
+ if ("default" in parsedValue.meta) {
59
+ return ctx.$.node("optional", {
60
+ key: parsedKey.key,
61
+ value: parsedValue,
62
+ default: parsedValue.meta.default
63
+ });
64
+ }
65
+ if (parsedValue.meta.optional) {
66
+ return ctx.$.node("optional", {
67
+ key: parsedKey.key,
68
+ value: parsedValue
69
+ });
70
+ }
71
+ }
73
72
  return ctx.$.node(parsedKey.kind, {
74
73
  key: parsedKey.key,
75
74
  value: parsedValue
76
75
  });
77
76
  };
78
- // single quote use here is better for TypeScript's inlined error to avoid escapes
79
- export const invalidDefaultKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`;
80
77
  const parseKey = (key) => typeof key === "symbol" ? { kind: "required", key }
81
78
  : key.at(-1) === "?" ?
82
79
  key.at(-2) === escapeToken ?
@@ -1,3 +1,4 @@
1
+ import type { writeUnassignableDefaultValueMessage } from "@ark/schema";
1
2
  import type { ErrorMessage } from "@ark/util";
2
3
  import type { inferAmbient } from "../../type.ts";
3
4
  import type { UnitLiteral } from "../string/shift/operator/default.ts";
@@ -5,5 +6,3 @@ import type { inferAstOut } from "./infer.ts";
5
6
  import type { astToString } from "./utils.ts";
6
7
  import type { validateAst } from "./validate.ts";
7
8
  export type validateDefault<baseAst, unitLiteral extends UnitLiteral, $, args> = validateAst<baseAst, $, args> extends infer e extends ErrorMessage ? e : inferAmbient<unitLiteral> extends inferAstOut<baseAst, $, args> ? undefined : ErrorMessage<writeUnassignableDefaultValueMessage<astToString<baseAst>, unitLiteral>>;
8
- export declare const writeUnassignableDefaultValueMessage: <key extends string, message extends string>(key: key, message: message) => string;
9
- export type writeUnassignableDefaultValueMessage<baseDef extends string, defaultValue extends string> = `Default value ${defaultValue} is not assignable to ${baseDef}`;
@@ -1 +1 @@
1
- export const writeUnassignableDefaultValueMessage = (key, message) => `Default value at ${key} ${message}`;
1
+ export {};
@@ -1,14 +1,15 @@
1
1
  import type { GenericAst } from "@ark/schema";
2
2
  import type { Hkt, array } from "@ark/util";
3
3
  import type { inferIntersection } from "../../intersect.ts";
4
- import type { Date, Default, LimitLiteral, applyConstraint, distillIn, distillOut, normalizeLimit } from "../../keywords/ast.ts";
4
+ import type { Default, LimitLiteral, applyConstraintSchema, distill, normalizeLimit } from "../../keywords/ast.ts";
5
+ import type { Date } from "../../keywords/constructors/Date.ts";
5
6
  import type { UnparsedScope } from "../../scope.ts";
6
7
  import type { inferAmbient } from "../../type.ts";
7
8
  import type { inferDefinition } from "../definition.ts";
8
9
  import type { Comparator, MinComparator } from "../string/reduce/shared.ts";
9
10
  export type inferAstRoot<ast, $, args> = ast extends array ? inferExpression<ast, $, args> : never;
10
- export type inferAstIn<ast, $, args> = distillIn<inferAstRoot<ast, $, args>>;
11
- export type inferAstOut<ast, $, args> = distillOut<inferAstRoot<ast, $, args>>;
11
+ export type inferAstIn<ast, $, args> = distill.In<inferAstRoot<ast, $, args>>;
12
+ export type inferAstOut<ast, $, args> = distill.Out<inferAstRoot<ast, $, args>>;
12
13
  export type DefAst<def = unknown, alias extends string = string> = [
13
14
  def,
14
15
  "def",
@@ -25,8 +26,8 @@ export type inferExpression<ast, $, args> = ast extends array ? ast extends Infe
25
26
  [i in keyof argAsts]: inferExpression<argAsts[i], $, args>;
26
27
  }> : inferDefinition<g["bodyDef"], resolveScope<g["$"], $>, {
27
28
  [i in keyof g["names"] & `${number}` as g["names"][i]]: inferExpression<argAsts[i & keyof argAsts], resolveScope<g["arg$"], $>, args>;
28
- }> : 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 "=" ? inferAmbient<ast[2]> extends infer defaultValue ? (In?: inferExpression<ast[0], $, args>) => Default<defaultValue> : never : ast[1] extends Comparator ? ast[0] extends LimitLiteral ? constrainBound<inferExpression<ast[2], $, args>, ast[1], ast[0]> : constrainBound<inferExpression<ast[0], $, args>, ast[1], ast[2] & LimitLiteral> : ast[1] extends "%" ? applyConstraint<inferExpression<ast[0], $, args>, "divisor", ast[2] & number> : ast[0] extends "keyof" ? keyof inferExpression<ast[1], $, args> : never : never;
29
- export type constrainBound<constrainableIn, comparator extends Comparator, limit extends LimitLiteral> = distillIn<constrainableIn> extends infer In ? comparator extends "==" ? In extends number ? limit : In extends Date ? Date.literal<normalizeLimit<limit>> : applyConstraint<constrainableIn, "exactLength", limit & number> : applyConstraint<constrainableIn, In extends number ? comparator extends MinComparator ? "min" : "max" : In extends string | array ? comparator extends MinComparator ? "minLength" : "maxLength" : comparator extends MinComparator ? "after" : "before", {
29
+ }> : 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 "=" ? inferAmbient<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" ? keyof inferExpression<ast[1], $, args> : never : never;
30
+ 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", {
30
31
  rule: normalizeLimit<limit>;
31
32
  exclusive: comparator extends ">" | "<" ? true : false;
32
33
  }> : never;
@@ -34,6 +35,6 @@ export type PrefixOperator = "keyof" | "instanceof" | "===" | "node";
34
35
  export type PrefixExpression<operator extends PrefixOperator = PrefixOperator, operand = unknown> = [operator, operand];
35
36
  export type PostfixOperator = "[]";
36
37
  export type PostfixExpression<operator extends PostfixOperator = PostfixOperator, operand = unknown> = readonly [operand, operator];
37
- export type InfixOperator = "|" | "&" | Comparator | "%" | ":" | "=>" | "@";
38
+ export type InfixOperator = "|" | "&" | Comparator | "%" | ":" | "=>" | "@" | "=";
38
39
  export type InfixExpression<operator extends InfixOperator = InfixOperator, l = unknown, r = unknown> = [l, operator, r];
39
40
  export {};
@@ -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> : undefined : ast extends [infer baseAst, "=", infer unitLiteral extends UnitLiteral] ? validateDefault<baseAst, unitLiteral, $, args> : 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> : 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}`;
@@ -20,7 +20,7 @@ export declare const writePrefixedPrivateReferenceMessage: <def extends PrivateD
20
20
  export type writePrefixedPrivateReferenceMessage<def extends PrivateDeclaration> = `Private type references should not include '#'. Use '${charsAfterFirst<def>}' instead.`;
21
21
  type validateInferredAst<inferred, def extends string> = def extends NumberLiteral ? number extends inferred ? ErrorMessage<writeMalformedNumericLiteralMessage<def, "number">> : undefined : def extends BigintLiteral ? bigint extends inferred ? ErrorMessage<writeMalformedNumericLiteralMessage<def, "bigint">> : undefined : [inferred] extends [anyOrNever] ? undefined : def extends PrivateDeclaration ? ErrorMessage<writePrefixedPrivateReferenceMessage<def>> : inferred extends Generic ? ErrorMessage<writeInvalidGenericArgCountMessage<def, inferred["names"], []>> : inferred extends {
22
22
  [arkKind]: "module";
23
- } ? "$root" extends keyof inferred ? undefined : ErrorMessage<writeMissingSubmoduleAccessMessage<def>> : def extends ErrorMessage ? def : undefined;
23
+ } ? "root" extends keyof inferred ? undefined : ErrorMessage<writeMissingSubmoduleAccessMessage<def>> : def extends ErrorMessage ? def : undefined;
24
24
  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;
25
25
  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;
26
26
  export {};
@@ -19,8 +19,7 @@ export declare class DynamicState {
19
19
  groups: BranchState[];
20
20
  scanner: Scanner;
21
21
  ctx: ParseContext;
22
- defaultable: boolean;
23
- constructor(scanner: Scanner, ctx: ParseContext, defaultable: boolean);
22
+ constructor(scanner: Scanner, ctx: ParseContext);
24
23
  error(message: string): never;
25
24
  hasRoot(): this is DynamicStateWithRoot;
26
25
  setRoot(root: BaseRoot): void;
@@ -16,11 +16,9 @@ export class DynamicState {
16
16
  groups = [];
17
17
  scanner;
18
18
  ctx;
19
- defaultable;
20
- constructor(scanner, ctx, defaultable) {
19
+ constructor(scanner, ctx) {
21
20
  this.scanner = scanner;
22
21
  this.ctx = ctx;
23
- this.defaultable = defaultable;
24
22
  }
25
23
  error(message) {
26
24
  return throwParseError(message);
@@ -103,7 +101,7 @@ export class DynamicState {
103
101
  this.root = undefined;
104
102
  }
105
103
  parseUntilFinalizer() {
106
- return parseUntilFinalizer(new DynamicState(this.scanner, this.ctx, false));
104
+ return parseUntilFinalizer(new DynamicState(this.scanner, this.ctx));
107
105
  }
108
106
  parseOperator() {
109
107
  return parseOperator(this);
@@ -2,8 +2,10 @@ import type { DateLiteral } from "../../../../keywords/ast.ts";
2
2
  export declare const isDateLiteral: (value: unknown) => value is DateLiteral;
3
3
  export declare const isValidDate: (d: Date) => boolean;
4
4
  export declare const extractDateLiteralSource: <literal extends DateLiteral>(literal: literal) => extractDateLiteralSource<literal>;
5
+ type extractDateLiteralSource<literal extends DateLiteral> = literal extends DateLiteral<infer source> ? source : never;
5
6
  export declare const writeInvalidDateMessage: <source extends string>(source: source) => writeInvalidDateMessage<source>;
6
7
  export type writeInvalidDateMessage<source extends string> = `'${source}' could not be parsed by the Date constructor`;
7
8
  export type DateInput = ConstructorParameters<typeof Date>[0];
8
9
  export type DateParseResult<errorOnFail extends boolean | string = boolean | string> = Date | (errorOnFail extends true | string ? never : undefined);
9
10
  export declare const tryParseDate: <errorOnFail extends boolean | string>(source: string, errorOnFail?: errorOnFail) => DateParseResult<errorOnFail>;
11
+ export {};
@@ -1,4 +1,5 @@
1
- import type { Date, string } from "../../../../keywords/ast.ts";
1
+ import type { string } from "../../../../keywords/ast.ts";
2
+ import type { Date } from "../../../../keywords/constructors/Date.ts";
2
3
  import type { InferredAst } from "../../../semantic/infer.ts";
3
4
  import type { DynamicState } from "../../reduce/dynamic.ts";
4
5
  import type { StaticState, state } from "../../reduce/static.ts";
@@ -1,12 +1,11 @@
1
1
  import type { BaseRoot } from "@ark/schema";
2
- import { type BigintLiteral, type ErrorMessage, type NumberLiteral, type trim } from "@ark/util";
2
+ import type { BigintLiteral, ErrorMessage, NumberLiteral, trim } from "@ark/util";
3
3
  import type { DateLiteral } from "../../../../keywords/ast.ts";
4
4
  import type { DynamicStateWithRoot } from "../../reduce/dynamic.ts";
5
5
  import type { StringLiteral } from "../operand/enclosed.ts";
6
6
  type UnitLiteralKeyword = "null" | "undefined" | "true" | "false";
7
7
  export type UnitLiteral = StringLiteral | BigintLiteral | NumberLiteral | DateLiteral | UnitLiteralKeyword;
8
- export type ParsedDefault = [BaseRoot, "=", unknown];
9
- export declare const parseDefault: (s: DynamicStateWithRoot) => ParsedDefault;
8
+ export declare const parseDefault: (s: DynamicStateWithRoot) => BaseRoot;
10
9
  export type parseDefault<root, unscanned extends string> = trim<unscanned> extends infer defaultValue extends UnitLiteral ? [
11
10
  root,
12
11
  "=",
@@ -14,6 +13,4 @@ export type parseDefault<root, unscanned extends string> = trim<unscanned> exten
14
13
  ] : ErrorMessage<writeNonLiteralDefaultMessage<trim<unscanned>>>;
15
14
  export declare const writeNonLiteralDefaultMessage: <defaultDef extends string>(defaultDef: defaultDef) => writeNonLiteralDefaultMessage<defaultDef>;
16
15
  export type writeNonLiteralDefaultMessage<defaultDef extends string> = `Default value '${defaultDef}' must a literal value`;
17
- export declare const shallowDefaultMessage = "Default values must be specified on objects like { isAdmin: 'boolean = false' }";
18
- export type shallowDefaultMessage = typeof shallowDefaultMessage;
19
16
  export {};
@@ -1,7 +1,4 @@
1
- import { throwParseError } from "@ark/util";
2
1
  export const parseDefault = (s) => {
3
- if (!s.defaultable)
4
- return throwParseError(shallowDefaultMessage);
5
2
  // store the node that will be bounded
6
3
  const baseNode = s.unsetRoot();
7
4
  s.parseOperand();
@@ -10,8 +7,6 @@ export const parseDefault = (s) => {
10
7
  // token from which it was parsed
11
8
  if (!defaultNode.hasKind("unit"))
12
9
  return s.error(writeNonLiteralDefaultMessage(defaultNode.expression));
13
- // assignability is checked in parseEntries
14
- return [baseNode, "=", defaultNode.unit];
10
+ return baseNode.default(defaultNode.unit);
15
11
  };
16
12
  export const writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must a literal value`;
17
- export const shallowDefaultMessage = `Default values must be specified on objects like { isAdmin: 'boolean = false' }`;
@@ -7,7 +7,7 @@ import type { DynamicState, DynamicStateWithRoot } from "./reduce/dynamic.ts";
7
7
  import type { StringifiablePrefixOperator } from "./reduce/shared.ts";
8
8
  import type { state, StaticState } from "./reduce/static.ts";
9
9
  import type { parseOperand } from "./shift/operand/operand.ts";
10
- import { parseDefault, type ParsedDefault } from "./shift/operator/default.ts";
10
+ import { parseDefault } from "./shift/operator/default.ts";
11
11
  import { writeUnexpectedCharacterMessage, type parseOperator } from "./shift/operator/operator.ts";
12
12
  /**
13
13
  * Try to parse the definition from right to left using the most common syntax.
@@ -19,8 +19,7 @@ export type parseString<def extends string, $, args> = def extends keyof $ ? res
19
19
  ] : fullStringParse<state.initialize<def>, $, args> : fullStringParse<state.initialize<def>, $, args>;
20
20
  export type inferString<def extends string, $, args> = inferAstRoot<parseString<def, $, args>, $, args>;
21
21
  export type BaseCompletions<$, args, otherSuggestions extends string = never> = resolvableReferenceIn<$> | resolvableReferenceIn<ArkAmbient.$> | (keyof args & string) | StringifiablePrefixOperator | otherSuggestions;
22
- export type StringParseResult = BaseRoot | ParsedDefault;
23
- export declare const fullStringParse: (s: DynamicState) => StringParseResult;
22
+ export declare const fullStringParse: (s: DynamicState) => BaseRoot;
24
23
  type fullStringParse<s extends StaticState, $, args> = extractFinalizedResult<parseUntilFinalizer<s, $, args>>;
25
24
  export declare const parseUntilFinalizer: (s: DynamicState) => DynamicStateWithRoot;
26
25
  export type parseUntilFinalizer<s extends StaticState, $, args> = s["finalizer"] extends undefined ? parseUntilFinalizer<next<s, $, args>, $, args> : s;
@@ -1,7 +1,8 @@
1
1
  import { type BaseRoot, type MetaSchema, type Morph, type Predicate } from "@ark/schema";
2
2
  import { 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
- import type { distillConstrainableIn, distillOut, inferMorphOut, inferPredicate, Out } from "../keywords/ast.ts";
4
+ import type { type } from "../keywords/ark.ts";
5
+ import type { Default, distill, inferMorphOut, inferPredicate, Out } from "../keywords/ast.ts";
5
6
  import type { ParseContext } from "../scope.ts";
6
7
  import type { inferDefinition, validateDefinition } from "./definition.ts";
7
8
  import type { InfixOperator, PostfixExpression } from "./semantic/infer.ts";
@@ -99,13 +100,13 @@ type optionalPostVariadicMessage = typeof optionalPostVariadicMessage;
99
100
  export declare const spreadOptionalMessage = "A spread element cannot be optional";
100
101
  type spreadOptionalMessage = typeof optionalPostVariadicMessage;
101
102
  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 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
+ 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;
103
104
  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
105
  export type validatePostfixExpression<def extends PostfixExpression, $, args> = conform<def, readonly [validateDefinition<def[0], $, args>, "[]"]>;
105
106
  export type validateInfixExpression<def extends InfixExpression, $, args> = def["length"] extends 2 ? readonly [def[0], writeMissingRightOperandMessage<def[1]>] : readonly [
106
107
  validateDefinition<def[0], $, args>,
107
108
  def[1],
108
- def[1] extends "|" ? validateDefinition<def[2], $, args> : def[1] extends "&" ? validateDefinition<def[2], $, args> : def[1] extends ":" ? Predicate<distillOut<inferDefinition<def[0], $, args>>> : def[1] extends "=>" ? Morph<distillOut<inferDefinition<def[0], $, args>>, unknown> : def[1] extends "@" ? MetaSchema : validateDefinition<def[2], $, args>
109
+ 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 "@" ? MetaSchema : def[1] extends "=" ? type.infer.Out<def[0], $, args> : validateDefinition<def[2], $, args>
109
110
  ];
110
111
  export type UnparsedTupleExpressionInput = {
111
112
  instanceof: Constructor;
@@ -120,11 +121,11 @@ export type TupleExpression = IndexZeroExpression | IndexOneExpression;
120
121
  export type TupleExpressionOperator = IndexZeroOperator | IndexOneOperator;
121
122
  export type IndexOneOperator = TuplePostfixOperator | TupleInfixOperator;
122
123
  export type TuplePostfixOperator = "[]";
123
- export type TupleInfixOperator = "&" | "|" | "=>" | ":" | "@";
124
+ export type TupleInfixOperator = "&" | "|" | "=>" | ":" | "@" | "=";
124
125
  export type IndexOneExpression<token extends IndexOneOperator = IndexOneOperator> = readonly [unknown, token, ...unknown[]];
125
126
  export declare const parseMorphTuple: PostfixParser<"=>">;
126
127
  export declare const writeMalformedFunctionalExpressionMessage: (operator: ":" | "=>", value: unknown) => string;
127
- export type parseMorph<inDef, morph, $, args> = morph extends Morph ? inferMorphOut<morph> extends infer out ? (In: distillConstrainableIn<inferDefinition<inDef, $, args>>) => Out<out> : never : never;
128
+ 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
129
  export declare const parseNarrowTuple: PostfixParser<":">;
129
130
  export type IndexZeroOperator = "keyof" | "instanceof" | "===";
130
131
  export type IndexZeroExpression<token extends IndexZeroOperator = IndexZeroOperator> = readonly [token, ...unknown[]];
@@ -129,13 +129,15 @@ export const parseNarrowTuple = (def, ctx) => {
129
129
  return ctx.$.parse(def[0], ctx).constrain("predicate", def[2]);
130
130
  };
131
131
  const parseAttributeTuple = (def, ctx) => ctx.$.parse(def[0], ctx).configureShallowDescendants(def[2]);
132
+ const parseDefaultTuple = (def, ctx) => ctx.$.parse(def[0], ctx).default(def[2]);
132
133
  const indexOneParsers = {
133
134
  "|": parseBranchTuple,
134
135
  "&": parseBranchTuple,
135
136
  "[]": parseArrayTuple,
136
137
  ":": parseNarrowTuple,
137
138
  "=>": parseMorphTuple,
138
- "@": parseAttributeTuple
139
+ "@": parseAttributeTuple,
140
+ "=": parseDefaultTuple
139
141
  };
140
142
  const prefixParsers = {
141
143
  keyof: parseKeyOfTuple,
package/out/scope.d.ts CHANGED
@@ -6,8 +6,7 @@ import type { Ark } 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 type { ParsedDefault } from "./parser/string/shift/operator/default.ts";
10
- import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type Type, type TypeParser } from "./type.ts";
9
+ import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type EnumeratedTypeParser, type Type, type TypeParser, type UnitTypeParser } from "./type.ts";
11
10
  export type ScopeParser = <const def>(def: validateScope<def>, config?: ArkScopeConfig) => Scope<inferScope<def>>;
12
11
  export type ModuleParser = <const def>(def: validateScope<def>, config?: ArkScopeConfig) => inferScope<def> extends infer $ ? Module<{
13
12
  [k in exportedNameOf<$>]: $[k];
@@ -44,7 +43,7 @@ export type resolutionToAst<alias extends string, resolution> = [
44
43
  resolution
45
44
  ] extends [anyOrNever] ? InferredAst<resolution, alias> : resolution extends Def<infer def> ? DefAst<def, alias> : resolution extends {
46
45
  [arkKind]: "module";
47
- $root: infer root;
46
+ root: infer root;
48
47
  } ? InferredAst<root, alias> : resolution extends GenericAst ? resolution : InferredAst<resolution, alias>;
49
48
  export type moduleKeyOf<$> = {
50
49
  [k in keyof $]: $[k] extends {
@@ -72,9 +71,11 @@ export declare class InternalScope<$ extends {} = {}> extends BaseScope<$> {
72
71
  protected cacheGetter<name extends keyof this>(name: name, value: this[name]): this[name];
73
72
  preparseRoot(def: unknown): unknown;
74
73
  get ambientAttachments(): Ark.boundTypeAttachments<$> | undefined;
75
- parse<defaultable extends boolean = false>(def: unknown, ctx: ParseContext, defaultable?: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
76
- parseString<defaultable extends boolean>(def: string, ctx: ParseContext, defaultable: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
74
+ parse(def: unknown, ctx: ParseContext): BaseRoot;
75
+ parseString(def: string, ctx: ParseContext): BaseRoot;
77
76
  parseRoot: (def: unknown, opts?: TypeParseOptions) => BaseRoot;
77
+ unit: UnitTypeParser<$>;
78
+ enumerated: EnumeratedTypeParser<$>;
78
79
  type: InternalTypeParser;
79
80
  declare: () => {
80
81
  type: InternalTypeParser;
@@ -99,6 +100,8 @@ export interface Scope<$ = {}> {
99
100
  defineSchema<const def extends RootSchema>(schema: def): def;
100
101
  schema(schema: RootSchema, opts?: NodeParseOptions): BaseRoot;
101
102
  node<kinds extends NodeKind | array<RootKind>>(kinds: kinds, schema: NodeSchema<flattenListable<kinds>>, opts?: NodeParseOptions): nodeOfKind<reducibleKindOf<flattenListable<kinds>>>;
103
+ unit: UnitTypeParser<$>;
104
+ enumerated: EnumeratedTypeParser<$>;
102
105
  type: TypeParser<$>;
103
106
  declare: DeclarationParser<$>;
104
107
  define: DefinitionParser<$>;
package/out/scope.js CHANGED
@@ -50,21 +50,20 @@ export class InternalScope extends BaseScope {
50
50
  v.bindScope(this)
51
51
  ]));
52
52
  }
53
- parse(def, ctx, defaultable = false) {
53
+ parse(def, ctx) {
54
54
  if (typeof def === "string") {
55
55
  if (ctx.args && Object.keys(ctx.args).some(k => def.includes(k))) {
56
56
  // we can only rely on the cache if there are no contextual
57
57
  // resolutions like "this" or generic args
58
- return this.parseString(def, ctx, defaultable);
58
+ return this.parseString(def, ctx);
59
59
  }
60
- const contextKey = `${def}${defaultable}`;
61
- return (this.parseCache[contextKey] ??= this.parseString(def, ctx, defaultable));
60
+ return (this.parseCache[def] ??= this.parseString(def, ctx));
62
61
  }
63
62
  return hasDomain(def, "object") ?
64
63
  parseObject(def, ctx)
65
64
  : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)));
66
65
  }
67
- parseString(def, ctx, defaultable) {
66
+ parseString(def, ctx) {
68
67
  const aliasResolution = this.maybeResolveRoot(def);
69
68
  if (aliasResolution)
70
69
  return aliasResolution;
@@ -73,7 +72,7 @@ export class InternalScope extends BaseScope {
73
72
  : undefined;
74
73
  if (aliasArrayResolution)
75
74
  return aliasArrayResolution;
76
- const s = new DynamicState(new Scanner(def), ctx, defaultable);
75
+ const s = new DynamicState(new Scanner(def), ctx);
77
76
  const node = fullStringParse(s);
78
77
  if (s.finalizer === ">")
79
78
  throwParseError(writeUnexpectedCharacterMessage(">"));
@@ -83,6 +82,8 @@ export class InternalScope extends BaseScope {
83
82
  const node = this.parse(def, Object.assign(this.finalizeRootArgs(opts, () => node), { $: this })).bindScope(this);
84
83
  return node;
85
84
  };
85
+ unit = value => this.units([value]);
86
+ enumerated = (...values) => this.units(values);
86
87
  type = new InternalTypeParser(this);
87
88
  declare = () => ({
88
89
  type: this.type
package/out/type.d.ts CHANGED
@@ -2,24 +2,26 @@ import { ArkErrors, BaseRoot, type MetaSchema, type Morph, type Predicate } from
2
2
  import { Callable, type Constructor, type array, type conform } from "@ark/util";
3
3
  import { type Generic, type GenericParser, type ParameterString, type baseGenericConstraints, type parseValidGenericParams, type validateParameterString } from "./generic.ts";
4
4
  import type { Ark, ark } from "./keywords/ark.ts";
5
- import type { distillIn, distillOut } from "./keywords/ast.ts";
5
+ import type { distill } from "./keywords/ast.ts";
6
+ import type { BaseType } from "./methods/base.ts";
7
+ import type { instantiateType } from "./methods/instantiate.ts";
6
8
  import type { inferDefinition, validateDeclared, validateDefinition } from "./parser/definition.ts";
7
9
  import type { IndexOneOperator, IndexZeroOperator, TupleInfixOperator } from "./parser/tuple.ts";
8
10
  import type { InternalScope, ModuleParser, Scope, ScopeParser, bindThis } from "./scope.ts";
9
- import type { BaseType } from "./subtypes/base.ts";
10
- import type { instantiateType } from "./subtypes/instantiate.ts";
11
11
  /** The convenience properties attached to `type` */
12
12
  export type TypeParserAttachments = Omit<TypeParser, never>;
13
13
  export interface TypeParser<$ = {}> extends Ark.boundTypeAttachments<$> {
14
14
  <const def, r = Type<inferTypeRoot<def, $>, $>>(def: validateTypeRoot<def, $>): r;
15
15
  <params extends ParameterString, const def>(params: validateParameterString<params, $>, def: validateDefinition<def, $, baseGenericConstraints<parseValidGenericParams<params, $>>>): Generic<parseValidGenericParams<params, $>, def, $>;
16
- <const zero, const one, const rest extends array, r = Type<inferTypeRoot<[zero, one, ...rest], $>, $>>(_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 "@" ? [MetaSchema] : [validateTypeRoot<rest[0], $>] : []): r;
16
+ <const zero, const one, const rest extends array, r = Type<inferTypeRoot<[zero, one, ...rest], $>, $>>(_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<distill.In<inferTypeRoot<zero, $>>>] : one extends "=>" ? [Morph<distill.Out<inferTypeRoot<zero, $>>, unknown>] : one extends "@" ? [MetaSchema] : [validateTypeRoot<rest[0], $>] : []): r;
17
17
  raw(def: unknown): BaseType<any, $>;
18
18
  errors: typeof ArkErrors;
19
19
  module: ModuleParser;
20
20
  scope: ScopeParser;
21
21
  generic: GenericParser<$>;
22
22
  ark: typeof ark;
23
+ unit: UnitTypeParser<$>;
24
+ enumerated: EnumeratedTypeParser<$>;
23
25
  }
24
26
  export declare class InternalTypeParser extends Callable<(...args: unknown[]) => BaseRoot | Generic, TypeParserAttachments> {
25
27
  constructor($: InternalScope);
@@ -27,6 +29,8 @@ export declare class InternalTypeParser extends Callable<(...args: unknown[]) =>
27
29
  export type DeclarationParser<$> = <preinferred>() => {
28
30
  type: <const def>(def: validateDeclared<preinferred, def, $, bindThis<def>>) => Type<preinferred, $>;
29
31
  };
32
+ export type UnitTypeParser<$> = <const t>(value: t) => Type<t, $>;
33
+ export type EnumeratedTypeParser<$> = <const values extends readonly unknown[]>(...values: values) => Type<values[number], $>;
30
34
  export type DefinitionParser<$> = <def>(def: validateTypeRoot<def, $>) => def;
31
35
  export type validateTypeRoot<def, $ = {}> = validateDefinition<def, $, bindThis<def>>;
32
36
  export type inferTypeRoot<def, $> = inferDefinition<def, $, bindThis<def>>;
package/out/type.js CHANGED
@@ -10,7 +10,9 @@ export class InternalTypeParser extends Callable {
10
10
  scope: $.constructor.scope,
11
11
  generic: $.generic,
12
12
  // this won't be defined during bootstrapping, but externally always will be
13
- ark: $.ambient
13
+ ark: $.ambient,
14
+ unit: $.unit,
15
+ enumerated: $.enumerated
14
16
  },
15
17
  // also won't be defined during bootstrapping
16
18
  $.ambientAttachments);
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.4",
4
+ "version": "2.0.0-rc.5",
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.6.0",
38
- "@ark/schema": "0.6.0"
37
+ "@ark/schema": "0.7.0",
38
+ "@ark/util": "0.7.0"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes