arktype 2.0.0-rc.5 → 2.0.0-rc.7

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 (58) hide show
  1. package/out/generic.d.ts +39 -42
  2. package/out/generic.js +3 -5
  3. package/out/index.d.ts +2 -2
  4. package/out/intersect.d.ts +2 -4
  5. package/out/keys.d.ts +5 -3
  6. package/out/keywords/ark.d.ts +8 -6
  7. package/out/keywords/ark.js +4 -2
  8. package/out/keywords/ast.d.ts +33 -21
  9. package/out/keywords/builtins.js +2 -2
  10. package/out/keywords/constructors/Array.js +5 -5
  11. package/out/keywords/constructors/FormData.js +7 -7
  12. package/out/keywords/constructors/TypedArray.js +2 -2
  13. package/out/keywords/constructors/constructors.d.ts +0 -1
  14. package/out/keywords/constructors/constructors.js +2 -2
  15. package/out/keywords/number/epoch.js +2 -2
  16. package/out/keywords/number/integer.js +2 -2
  17. package/out/keywords/number/number.d.ts +8 -0
  18. package/out/keywords/number/number.js +16 -4
  19. package/out/keywords/string/capitalize.js +4 -4
  20. package/out/keywords/string/creditCard.js +2 -2
  21. package/out/keywords/string/date.d.ts +0 -4
  22. package/out/keywords/string/date.js +9 -9
  23. package/out/keywords/string/integer.js +4 -4
  24. package/out/keywords/string/ip.js +4 -4
  25. package/out/keywords/string/json.js +5 -5
  26. package/out/keywords/string/lower.js +4 -4
  27. package/out/keywords/string/normalize.d.ts +0 -4
  28. package/out/keywords/string/normalize.js +9 -9
  29. package/out/keywords/string/numeric.js +4 -4
  30. package/out/keywords/string/string.d.ts +2 -5
  31. package/out/keywords/string/string.js +2 -2
  32. package/out/keywords/string/trim.js +4 -4
  33. package/out/keywords/string/upper.js +4 -4
  34. package/out/keywords/string/url.js +6 -6
  35. package/out/keywords/string/uuid.js +2 -2
  36. package/out/keywords/ts.d.ts +11 -0
  37. package/out/keywords/ts.js +7 -3
  38. package/out/keywords/utils.d.ts +1 -1
  39. package/out/keywords/utils.js +1 -1
  40. package/out/methods/base.d.ts +18 -15
  41. package/out/methods/morph.d.ts +3 -3
  42. package/out/methods/object.d.ts +32 -8
  43. package/out/parser/definition.d.ts +2 -3
  44. package/out/parser/objectLiteral.d.ts +4 -5
  45. package/out/parser/objectLiteral.js +4 -4
  46. package/out/parser/semantic/default.d.ts +2 -2
  47. package/out/parser/semantic/infer.d.ts +3 -2
  48. package/out/parser/string/reduce/dynamic.d.ts +3 -4
  49. package/out/parser/string/reduce/dynamic.js +3 -2
  50. package/out/parser/string/shift/operand/enclosed.js +7 -3
  51. package/out/parser/string/shift/operand/unenclosed.js +6 -2
  52. package/out/parser/tuple.d.ts +5 -6
  53. package/out/parser/tuple.js +29 -20
  54. package/out/scope.d.ts +21 -23
  55. package/out/scope.js +33 -26
  56. package/out/type.d.ts +12 -12
  57. package/out/type.js +9 -9
  58. package/package.json +3 -3
@@ -1,10 +1,11 @@
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 { arkKeyOf } from "../../keys.ts";
5
+ import type { type } from "../../keywords/ark.ts";
4
6
  import type { Default, LimitLiteral, applyConstraintSchema, distill, normalizeLimit } from "../../keywords/ast.ts";
5
7
  import type { Date } from "../../keywords/constructors/Date.ts";
6
8
  import type { UnparsedScope } from "../../scope.ts";
7
- import type { inferAmbient } from "../../type.ts";
8
9
  import type { inferDefinition } from "../definition.ts";
9
10
  import type { Comparator, MinComparator } from "../string/reduce/shared.ts";
10
11
  export type inferAstRoot<ast, $, args> = ast extends array ? inferExpression<ast, $, args> : never;
@@ -26,7 +27,7 @@ export type inferExpression<ast, $, args> = ast extends array ? ast extends Infe
26
27
  [i in keyof argAsts]: inferExpression<argAsts[i], $, args>;
27
28
  }> : inferDefinition<g["bodyDef"], resolveScope<g["$"], $>, {
28
29
  [i in keyof g["names"] & `${number}` as g["names"][i]]: inferExpression<argAsts[i & keyof argAsts], resolveScope<g["arg$"], $>, args>;
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
+ }> : 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
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", {
31
32
  rule: normalizeLimit<limit>;
32
33
  exclusive: comparator extends ">" | "<" ? true : false;
@@ -1,7 +1,6 @@
1
- import type { BaseRoot } from "@ark/schema";
1
+ import type { BaseParseContext, BaseRoot } from "@ark/schema";
2
2
  import { type requireKeys } from "@ark/util";
3
3
  import type { LimitLiteral } from "../../../keywords/ast.ts";
4
- import type { ParseContext } from "../../../scope.ts";
5
4
  import type { InfixOperator } from "../../semantic/infer.ts";
6
5
  import type { Scanner } from "../shift/scanner.ts";
7
6
  import { type Comparator, type MinComparator, type OpenLeftBound, type StringifiablePrefixOperator } from "./shared.ts";
@@ -18,8 +17,8 @@ export declare class DynamicState {
18
17
  finalizer: Scanner.FinalizingLookahead | undefined;
19
18
  groups: BranchState[];
20
19
  scanner: Scanner;
21
- ctx: ParseContext;
22
- constructor(scanner: Scanner, ctx: ParseContext);
20
+ ctx: BaseParseContext;
21
+ constructor(scanner: Scanner, ctx: BaseParseContext);
23
22
  error(message: string): never;
24
23
  hasRoot(): this is DynamicStateWithRoot;
25
24
  setRoot(root: BaseRoot): void;
@@ -91,10 +91,11 @@ export class DynamicState {
91
91
  this.assertRangeUnset();
92
92
  this.applyPrefixes();
93
93
  const root = this.root;
94
- this.branches.intersection = this.branches.intersection?.and(root) ?? root;
94
+ this.branches.intersection =
95
+ this.branches.intersection?.rawAnd(root) ?? root;
95
96
  if (token === "|") {
96
97
  this.branches.union =
97
- this.branches.union?.or(this.branches.intersection) ??
98
+ this.branches.union?.rawOr(this.branches.intersection) ??
98
99
  this.branches.intersection;
99
100
  this.branches.intersection = null;
100
101
  }
@@ -1,4 +1,4 @@
1
- import { isKeyOf } from "@ark/util";
1
+ import { isKeyOf, throwParseError } from "@ark/util";
2
2
  import { tryParseDate, writeInvalidDateMessage } from "./date.js";
3
3
  export const parseEnclosed = (s, enclosing) => {
4
4
  const enclosed = s.scanner.shiftUntil(untilLookaheadIsClosing[enclosingTokens[enclosing]]);
@@ -7,8 +7,12 @@ export const parseEnclosed = (s, enclosing) => {
7
7
  // Shift the scanner one additional time for the second enclosing token
8
8
  s.scanner.shift();
9
9
  if (enclosing === "/") {
10
- // fail parsing if the regex is invalid
11
- new RegExp(enclosed);
10
+ try {
11
+ new RegExp(enclosed);
12
+ }
13
+ catch (e) {
14
+ throwParseError(String(e));
15
+ }
12
16
  s.root = s.ctx.$.node("intersection", {
13
17
  domain: "string",
14
18
  pattern: enclosed
@@ -24,8 +24,12 @@ const unenclosedToNode = (s, token) => maybeParseReference(s, token) ??
24
24
  writePrefixedPrivateReferenceMessage(token)
25
25
  : writeUnresolvableMessage(token));
26
26
  const maybeParseReference = (s, token) => {
27
- if (s.ctx.args?.[token])
28
- return s.ctx.args[token].internal;
27
+ if (s.ctx.args?.[token]) {
28
+ const arg = s.ctx.args[token];
29
+ if (typeof arg !== "string")
30
+ return arg;
31
+ return s.ctx.$.node("alias", { reference: arg }, { prereduced: true });
32
+ }
29
33
  const resolution = s.ctx.$.maybeResolve(token);
30
34
  if (hasArkKind(resolution, "root"))
31
35
  return resolution;
@@ -1,15 +1,14 @@
1
- import { type BaseRoot, type MetaSchema, type Morph, type Predicate } from "@ark/schema";
1
+ import { type BaseParseContext, 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
4
  import type { type } from "../keywords/ark.ts";
5
5
  import type { Default, distill, inferMorphOut, inferPredicate, Out } from "../keywords/ast.ts";
6
- import type { ParseContext } from "../scope.ts";
7
6
  import type { inferDefinition, validateDefinition } from "./definition.ts";
8
7
  import type { InfixOperator, PostfixExpression } from "./semantic/infer.ts";
9
8
  import { writeMissingRightOperandMessage } from "./string/shift/operand/unenclosed.ts";
10
9
  import type { BaseCompletions } from "./string/string.ts";
11
- export declare const parseTuple: (def: array, ctx: ParseContext) => BaseRoot;
12
- export declare const parseTupleLiteral: (def: array, ctx: ParseContext) => BaseRoot;
10
+ export declare const parseTuple: (def: array, ctx: BaseParseContext) => BaseRoot;
11
+ export declare const parseTupleLiteral: (def: array, ctx: BaseParseContext) => BaseRoot;
13
12
  type InfixExpression = readonly [unknown, InfixOperator, ...unknown[]];
14
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 [
15
14
  def[0] extends "" ? BaseCompletions<$, args, IndexZeroOperator | "..."> : def[0],
@@ -115,8 +114,8 @@ export type UnparsedTupleExpressionInput = {
115
114
  export type UnparsedTupleOperator = show<keyof UnparsedTupleExpressionInput>;
116
115
  export declare const parseKeyOfTuple: PrefixParser<"keyof">;
117
116
  export type inferKeyOfExpression<operandDef, $, args> = show<keyof inferDefinition<operandDef, $, args>>;
118
- export type PostfixParser<token extends IndexOneOperator> = (def: IndexOneExpression<token>, ctx: ParseContext) => BaseRoot;
119
- export type PrefixParser<token extends IndexZeroOperator> = (def: IndexZeroExpression<token>, ctx: ParseContext) => BaseRoot;
117
+ export type PostfixParser<token extends IndexOneOperator> = (def: IndexOneExpression<token>, ctx: BaseParseContext) => BaseRoot;
118
+ export type PrefixParser<token extends IndexZeroOperator> = (def: IndexZeroExpression<token>, ctx: BaseParseContext) => BaseRoot;
120
119
  export type TupleExpression = IndexZeroExpression | IndexOneExpression;
121
120
  export type TupleExpressionOperator = IndexZeroOperator | IndexOneOperator;
122
121
  export type IndexOneOperator = TuplePostfixOperator | TupleInfixOperator;
@@ -1,5 +1,5 @@
1
- import { $ark, makeRootAndArrayPropertiesMutable } from "@ark/schema";
2
- import { append, objectKindOrDomainOf, throwParseError } from "@ark/util";
1
+ import { $ark, Disjoint, intersectNodesRoot, makeRootAndArrayPropertiesMutable } from "@ark/schema";
2
+ import { append, isEmptyObject, objectKindOrDomainOf, throwParseError } from "@ark/util";
3
3
  import { writeMissingRightOperandMessage } from "./string/shift/operand/unenclosed.js";
4
4
  export const parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx);
5
5
  export const parseTupleLiteral = (def, ctx) => {
@@ -12,7 +12,7 @@ export const parseTupleLiteral = (def, ctx) => {
12
12
  spread = true;
13
13
  i++;
14
14
  }
15
- const element = ctx.$.parse(def[i], ctx);
15
+ const element = ctx.$.parseOwnDefinitionFormat(def[i], ctx);
16
16
  i++;
17
17
  if (def[i] === "?") {
18
18
  if (spread)
@@ -34,10 +34,15 @@ export const parseTupleLiteral = (def, ctx) => {
34
34
  sequences = sequences.map(base => appendElement(base, optional ? "optional" : "required", element));
35
35
  }
36
36
  }
37
- return ctx.$.internal.rootNode(sequences.map(sequence => ({
38
- proto: Array,
39
- sequence
40
- })));
37
+ return ctx.$.parseSchema(sequences.map(sequence => isEmptyObject(sequence) ?
38
+ {
39
+ proto: Array,
40
+ exactLength: 0
41
+ }
42
+ : {
43
+ proto: Array,
44
+ sequence
45
+ }));
41
46
  };
42
47
  const appendElement = (base, kind, element) => {
43
48
  switch (kind) {
@@ -86,11 +91,11 @@ const appendSpreadBranch = (base, branch) => {
86
91
  // the only array with no sequence reference is unknown[]
87
92
  return appendElement(base, "variadic", $ark.intrinsic.unknown);
88
93
  }
89
- spread.prefix.forEach(node => appendElement(base, "required", node));
90
- spread.optionals.forEach(node => appendElement(base, "optional", node));
94
+ spread.prefix?.forEach(node => appendElement(base, "required", node));
95
+ spread.optionals?.forEach(node => appendElement(base, "optional", node));
91
96
  if (spread.variadic)
92
97
  appendElement(base, "variadic", spread.variadic);
93
- spread.postfix.forEach(node => appendElement(base, "required", node));
98
+ spread.postfix?.forEach(node => appendElement(base, "required", node));
94
99
  return base;
95
100
  };
96
101
  const maybeParseTupleExpression = (def, ctx) => {
@@ -104,32 +109,36 @@ export const multipleVariadicMesage = "A tuple may have at most one variadic ele
104
109
  export const requiredPostOptionalMessage = "A required element may not follow an optional element";
105
110
  export const optionalPostVariadicMessage = "An optional element may not follow a variadic element";
106
111
  export const spreadOptionalMessage = "A spread element cannot be optional";
107
- export const parseKeyOfTuple = (def, ctx) => ctx.$.parse(def[1], ctx).keyof();
112
+ export const parseKeyOfTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[1], ctx).keyof();
108
113
  const parseBranchTuple = (def, ctx) => {
109
114
  if (def[2] === undefined)
110
115
  return throwParseError(writeMissingRightOperandMessage(def[1], ""));
111
- const l = ctx.$.parse(def[0], ctx);
112
- const r = ctx.$.parse(def[2], ctx);
113
- return def[1] === "&" ? l.and(r) : l.or(r);
116
+ const l = ctx.$.parseOwnDefinitionFormat(def[0], ctx);
117
+ const r = ctx.$.parseOwnDefinitionFormat(def[2], ctx);
118
+ if (def[1] === "|")
119
+ return ctx.$.node("union", { branches: [l, r] });
120
+ const result = intersectNodesRoot(l, r, ctx.$);
121
+ if (result instanceof Disjoint)
122
+ return result.throw();
123
+ return result;
114
124
  };
115
- const parseArrayTuple = (def, ctx) => ctx.$.parse(def[0], ctx).array();
125
+ const parseArrayTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).array();
116
126
  const isIndexOneExpression = (def) => indexOneParsers[def[1]] !== undefined;
117
127
  export const parseMorphTuple = (def, ctx) => {
118
128
  if (typeof def[2] !== "function") {
119
129
  return throwParseError(writeMalformedFunctionalExpressionMessage("=>", def[2]));
120
130
  }
121
- // TODO: nested morphs?
122
- return ctx.$.parse(def[0], ctx).pipe(def[2]);
131
+ return ctx.$.parseOwnDefinitionFormat(def[0], ctx).pipe(def[2]);
123
132
  };
124
133
  export const writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value})`;
125
134
  export const parseNarrowTuple = (def, ctx) => {
126
135
  if (typeof def[2] !== "function") {
127
136
  return throwParseError(writeMalformedFunctionalExpressionMessage(":", def[2]));
128
137
  }
129
- return ctx.$.parse(def[0], ctx).constrain("predicate", def[2]);
138
+ return ctx.$.parseOwnDefinitionFormat(def[0], ctx).constrain("predicate", def[2]);
130
139
  };
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]);
140
+ const parseAttributeTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configureShallowDescendants(def[2]);
141
+ const parseDefaultTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).default(def[2]);
133
142
  const indexOneParsers = {
134
143
  "|": parseBranchTuple,
135
144
  "&": parseBranchTuple,
package/out/scope.d.ts CHANGED
@@ -1,21 +1,19 @@
1
- import { BaseScope, type AliasDefEntry, type ArkScopeConfig, type BaseNode, type BaseRoot, type GenericArgResolutions, type GenericAst, type GenericParamAst, type NodeKind, type NodeParseOptions, 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 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";
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
- import { parseGenericParams, type GenericDeclaration, type GenericParser, type ParameterString, type baseGenericConstraints, type parseValidGenericParams } from "./generic.ts";
4
+ import { type GenericDeclaration, type GenericParser, type ParameterString, type baseGenericConstraints, type parseGenericParams, type parseValidGenericParams } from "./generic.ts";
5
5
  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 { InternalTypeParser, type DeclarationParser, type DefinitionParser, type EnumeratedTypeParser, type Type, type TypeParser, type UnitTypeParser } from "./type.ts";
10
- export type ScopeParser = <const def>(def: validateScope<def>, config?: ArkScopeConfig) => Scope<inferScope<def>>;
11
- export type ModuleParser = <const def>(def: validateScope<def>, config?: ArkScopeConfig) => inferScope<def> extends infer $ ? Module<{
9
+ import { InternalTypeParser, type DeclarationParser, type DefinitionParser, type EnumeratedTypeParser, type SchemaParser, type Type, type TypeParser, type UnitTypeParser } from "./type.ts";
10
+ export type ScopeParser = <const def>(def: scope.validate<def>, config?: ArkScopeConfig) => Scope<scope.infer<def>>;
11
+ export type ModuleParser = <const def>(def: scope.validate<def>, config?: ArkScopeConfig) => scope.infer<def> extends infer $ ? Module<{
12
12
  [k in exportedNameOf<$>]: $[k];
13
13
  }> : never;
14
- export type validateScope<def> = {
15
- [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;
14
+ export type bindThis<def> = {
15
+ this: Def<def>;
16
16
  };
17
- export type inferScope<def> = inferBootstrapped<bootstrapAliases<def>>;
18
- export type bindThis<def> = {};
19
17
  /** nominal type for an unparsed definition used during scope bootstrapping */
20
18
  type Def<def = {}> = nominal<def, "unparsed">;
21
19
  /** sentinel indicating a scope that will be associated with a generic has not yet been parsed */
@@ -56,24 +54,19 @@ export interface ArkTypeRegistry extends ArkSchemaRegistry {
56
54
  typeAttachments?: Ark.boundTypeAttachments<any>;
57
55
  }
58
56
  export declare const $arkTypeRegistry: ArkTypeRegistry;
59
- export interface ParseContext extends TypeParseOptions {
60
- $: InternalScope;
61
- }
62
- export interface TypeParseOptions {
63
- args?: GenericArgResolutions;
64
- }
65
57
  export interface InternalScope {
66
58
  constructor: typeof InternalScope;
67
59
  }
68
60
  export declare class InternalScope<$ extends {} = {}> extends BaseScope<$> {
69
61
  private parseCache;
70
- preparseAlias(k: string, v: unknown): AliasDefEntry;
71
62
  protected cacheGetter<name extends keyof this>(name: name, value: this[name]): this[name];
72
- preparseRoot(def: unknown): unknown;
73
63
  get ambientAttachments(): Ark.boundTypeAttachments<$> | undefined;
74
- parse(def: unknown, ctx: ParseContext): BaseRoot;
75
- parseString(def: string, ctx: ParseContext): BaseRoot;
76
- parseRoot: (def: unknown, opts?: TypeParseOptions) => BaseRoot;
64
+ protected preparseOwnAliasEntry(k: string, v: unknown): AliasDefEntry;
65
+ parseGenericParams(def: string, opts: BaseParseOptions): array<GenericParamDef>;
66
+ protected normalizeRootScopeValue(resolution: unknown): unknown;
67
+ protected preparseOwnDefinitionFormat(def: unknown, opts: BaseParseOptions): BaseRoot | BaseParseContextInput;
68
+ parseOwnDefinitionFormat(def: unknown, ctx: BaseParseContext): BaseRoot;
69
+ parseString(def: string, ctx: BaseParseContext): BaseRoot;
77
70
  unit: UnitTypeParser<$>;
78
71
  enumerated: EnumeratedTypeParser<$>;
79
72
  type: InternalTypeParser;
@@ -85,6 +78,12 @@ export declare class InternalScope<$ extends {} = {}> extends BaseScope<$> {
85
78
  static module: ModuleParser;
86
79
  }
87
80
  export declare const scope: ScopeParser;
81
+ export declare namespace scope {
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;
84
+ };
85
+ type infer<def> = inferBootstrapped<bootstrapAliases<def>>;
86
+ }
88
87
  export declare const module: ModuleParser;
89
88
  export interface Scope<$ = {}> {
90
89
  t: $;
@@ -98,14 +97,14 @@ export interface Scope<$ = {}> {
98
97
  aliases: Record<string, unknown>;
99
98
  internal: toInternalScope<$>;
100
99
  defineSchema<const def extends RootSchema>(schema: def): def;
101
- schema(schema: RootSchema, opts?: NodeParseOptions): BaseRoot;
102
- node<kinds extends NodeKind | array<RootKind>>(kinds: kinds, schema: NodeSchema<flattenListable<kinds>>, opts?: NodeParseOptions): nodeOfKind<reducibleKindOf<flattenListable<kinds>>>;
100
+ node<kinds extends NodeKind | array<RootKind>>(kinds: kinds, schema: NodeSchema<flattenListable<kinds>>, opts?: BaseParseOptions): nodeOfKind<reducibleKindOf<flattenListable<kinds>>>;
103
101
  unit: UnitTypeParser<$>;
104
102
  enumerated: EnumeratedTypeParser<$>;
105
103
  type: TypeParser<$>;
106
104
  declare: DeclarationParser<$>;
107
105
  define: DefinitionParser<$>;
108
106
  generic: GenericParser<$>;
107
+ schema: SchemaParser<$>;
109
108
  import(): Module<{
110
109
  [k in exportedNameOf<$> as PrivateDeclaration<k>]: $[k];
111
110
  }>;
@@ -126,7 +125,6 @@ export interface ScopeConstructor {
126
125
  module: ModuleParser;
127
126
  }
128
127
  export declare const Scope: ScopeConstructor;
129
- export declare const writeShallowCycleErrorMessage: (name: string, seen: string[]) => string;
130
128
  export type parseScopeKey<k, def> = k extends `${infer name}<${infer params}>` ? parseGenericScopeKey<name, params, def> : {
131
129
  name: k;
132
130
  params: [];
package/out/scope.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { $ark, BaseScope, hasArkKind, parseGeneric } from "@ark/schema";
2
2
  import { domainOf, flatMorph, hasDomain, isThunk, throwParseError } from "@ark/util";
3
- import { parseGenericParams } from "./generic.js";
3
+ import { parseGenericParamName } from "./generic.js";
4
4
  import { parseObject, writeBadDefinitionTypeMessage } from "./parser/definition.js";
5
5
  import { DynamicState } from "./parser/string/reduce/dynamic.js";
6
6
  import { writeUnexpectedCharacterMessage } from "./parser/string/shift/operator/operator.js";
@@ -10,7 +10,19 @@ import { InternalTypeParser } from "./type.js";
10
10
  export const $arkTypeRegistry = $ark;
11
11
  export class InternalScope extends BaseScope {
12
12
  parseCache = {};
13
- preparseAlias(k, v) {
13
+ cacheGetter(name, value) {
14
+ Object.defineProperty(this, name, { value });
15
+ return value;
16
+ }
17
+ get ambientAttachments() {
18
+ if (!$arkTypeRegistry.typeAttachments)
19
+ return;
20
+ return this.cacheGetter("ambientAttachments", flatMorph($arkTypeRegistry.typeAttachments, (k, v) => [
21
+ k,
22
+ this.bindReference(v)
23
+ ]));
24
+ }
25
+ preparseOwnAliasEntry(k, v) {
14
26
  const firstParamIndex = k.indexOf("<");
15
27
  if (firstParamIndex === -1)
16
28
  return [k, v];
@@ -24,33 +36,33 @@ export class InternalScope extends BaseScope {
24
36
  // use a thunk definition for the generic so that we can parse
25
37
  // constraints within the current scope
26
38
  () => {
27
- const params = parseGenericParams(paramString, {
28
- $: this,
29
- args: {}
30
- });
39
+ const params = this.parseGenericParams(paramString, { alias: name });
31
40
  const generic = parseGeneric(params, v, this);
32
41
  return generic;
33
42
  }
34
43
  ];
35
44
  }
36
- cacheGetter(name, value) {
37
- Object.defineProperty(this, name, { value });
38
- return value;
45
+ parseGenericParams(def, opts) {
46
+ return parseGenericParamName(new Scanner(def), [], this.createParseContext({ ...opts, def, prefix: "generic" }));
39
47
  }
40
- preparseRoot(def) {
41
- if (isThunk(def) && !hasArkKind(def, "generic"))
42
- return def();
43
- return def;
48
+ normalizeRootScopeValue(resolution) {
49
+ if (isThunk(resolution) && !hasArkKind(resolution, "generic"))
50
+ return resolution();
51
+ return resolution;
44
52
  }
45
- get ambientAttachments() {
46
- if (!$arkTypeRegistry.typeAttachments)
47
- return;
48
- return this.cacheGetter("ambientAttachments", flatMorph($arkTypeRegistry.typeAttachments, (k, v) => [
49
- k,
50
- v.bindScope(this)
51
- ]));
53
+ preparseOwnDefinitionFormat(def, opts) {
54
+ return {
55
+ ...opts,
56
+ def,
57
+ prefix: opts.alias ?? "type"
58
+ };
52
59
  }
53
- parse(def, ctx) {
60
+ parseOwnDefinitionFormat(def, ctx) {
61
+ const isScopeAlias = ctx.alias && ctx.alias in this.aliases;
62
+ // if the definition being parsed is not a scope alias and is not a
63
+ // generic instantiation (i.e. opts don't include args), add this as a resolution.
64
+ if (!isScopeAlias && !ctx.args)
65
+ ctx.args = { this: ctx.id };
54
66
  if (typeof def === "string") {
55
67
  if (ctx.args && Object.keys(ctx.args).some(k => def.includes(k))) {
56
68
  // we can only rely on the cache if there are no contextual
@@ -78,10 +90,6 @@ export class InternalScope extends BaseScope {
78
90
  throwParseError(writeUnexpectedCharacterMessage(">"));
79
91
  return node;
80
92
  }
81
- parseRoot = (def, opts = {}) => {
82
- const node = this.parse(def, Object.assign(this.finalizeRootArgs(opts, () => node), { $: this })).bindScope(this);
83
- return node;
84
- };
85
93
  unit = value => this.units([value]);
86
94
  enumerated = (...values) => this.units(values);
87
95
  type = new InternalTypeParser(this);
@@ -95,4 +103,3 @@ export class InternalScope extends BaseScope {
95
103
  export const scope = InternalScope.scope;
96
104
  export const module = InternalScope.module;
97
105
  export const Scope = InternalScope;
98
- export const writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join(":")}`;
package/out/type.d.ts CHANGED
@@ -1,24 +1,27 @@
1
- import { ArkErrors, BaseRoot, type MetaSchema, type Morph, type Predicate } from "@ark/schema";
2
- import { Callable, type Constructor, type array, type conform } from "@ark/util";
3
- import { type Generic, type GenericParser, type ParameterString, type baseGenericConstraints, type parseValidGenericParams, type validateParameterString } from "./generic.ts";
4
- import type { Ark, ark } from "./keywords/ark.ts";
1
+ import { ArkErrors, BaseRoot, type BaseParseOptions, type MetaSchema, type Morph, type Predicate, type RootSchema } from "@ark/schema";
2
+ import { Callable, Hkt, type Constructor, type array, type conform } from "@ark/util";
3
+ import type { Generic, GenericParser, ParameterString, baseGenericConstraints, parseValidGenericParams, validateParameterString } from "./generic.ts";
4
+ import type { Ark, ark, type } from "./keywords/ark.ts";
5
5
  import type { distill } from "./keywords/ast.ts";
6
6
  import type { BaseType } from "./methods/base.ts";
7
7
  import type { instantiateType } from "./methods/instantiate.ts";
8
- import type { inferDefinition, validateDeclared, validateDefinition } from "./parser/definition.ts";
8
+ import type { validateDeclared, validateDefinition } from "./parser/definition.ts";
9
9
  import type { IndexOneOperator, IndexZeroOperator, TupleInfixOperator } from "./parser/tuple.ts";
10
10
  import type { InternalScope, ModuleParser, Scope, ScopeParser, bindThis } from "./scope.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
- <const def, r = Type<inferTypeRoot<def, $>, $>>(def: validateTypeRoot<def, $>): r;
14
+ <const def, r = Type<type.infer<def, $>, $>>(def: type.validate<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<distill.In<inferTypeRoot<zero, $>>>] : one extends "=>" ? [Morph<distill.Out<inferTypeRoot<zero, $>>, unknown>] : one extends "@" ? [MetaSchema] : [validateTypeRoot<rest[0], $>] : []): r;
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
+ $: Scope<$>;
17
18
  raw(def: unknown): BaseType<any, $>;
18
19
  errors: typeof ArkErrors;
20
+ hkt: typeof Hkt;
19
21
  module: ModuleParser;
20
22
  scope: ScopeParser;
21
23
  generic: GenericParser<$>;
24
+ schema: SchemaParser<$>;
22
25
  ark: typeof ark;
23
26
  unit: UnitTypeParser<$>;
24
27
  enumerated: EnumeratedTypeParser<$>;
@@ -31,11 +34,8 @@ export type DeclarationParser<$> = <preinferred>() => {
31
34
  };
32
35
  export type UnitTypeParser<$> = <const t>(value: t) => Type<t, $>;
33
36
  export type EnumeratedTypeParser<$> = <const values extends readonly unknown[]>(...values: values) => Type<values[number], $>;
34
- export type DefinitionParser<$> = <def>(def: validateTypeRoot<def, $>) => def;
35
- export type validateTypeRoot<def, $ = {}> = validateDefinition<def, $, bindThis<def>>;
36
- export type inferTypeRoot<def, $> = inferDefinition<def, $, bindThis<def>>;
37
- export type validateAmbient<def> = validateTypeRoot<def, {}>;
38
- export type inferAmbient<def> = inferTypeRoot<def, {}>;
37
+ export type DefinitionParser<$> = <def>(def: type.validate<def, $>) => def;
38
+ export type SchemaParser<$> = (schema: RootSchema, opts?: BaseParseOptions) => Type<unknown, $>;
39
39
  export type Type<t = unknown, $ = {}> = instantiateType<t, $>;
40
40
  export declare namespace Type {
41
41
  type Any<t = any> = BaseType<t, any>;
package/out/type.js CHANGED
@@ -1,14 +1,16 @@
1
1
  import { ArkErrors, BaseRoot, GenericRoot } from "@ark/schema";
2
- import { Callable } from "@ark/util";
3
- import { parseGenericParams } from "./generic.js";
2
+ import { Callable, Hkt } from "@ark/util";
4
3
  export class InternalTypeParser extends Callable {
5
4
  constructor($) {
6
5
  const attach = Object.assign({
7
6
  errors: ArkErrors,
8
- raw: $.parseRoot,
7
+ hkt: Hkt,
8
+ $: $,
9
+ raw: $.parse,
9
10
  module: $.constructor.module,
10
11
  scope: $.constructor.scope,
11
12
  generic: $.generic,
13
+ schema: $.schema,
12
14
  // this won't be defined during bootstrapping, but externally always will be
13
15
  ark: $.ambient,
14
16
  unit: $.unit,
@@ -19,7 +21,7 @@ export class InternalTypeParser extends Callable {
19
21
  super((...args) => {
20
22
  if (args.length === 1) {
21
23
  // treat as a simple definition
22
- return $.parseRoot(args[0]);
24
+ return $.parse(args[0]);
23
25
  }
24
26
  if (args.length === 2 &&
25
27
  typeof args[0] === "string" &&
@@ -27,16 +29,14 @@ export class InternalTypeParser extends Callable {
27
29
  args[0].at(-1) === ">") {
28
30
  // if there are exactly two args, the first of which looks like <${string}>,
29
31
  // treat as a generic
30
- const params = parseGenericParams(args[0].slice(1, -1), {
31
- $,
32
- args: {}
33
- });
32
+ const paramString = args[0].slice(1, -1);
33
+ const params = $.parseGenericParams(paramString, {});
34
34
  return new GenericRoot(params, args[1], $, $);
35
35
  }
36
36
  // otherwise, treat as a tuple expression. technically, this also allows
37
37
  // non-expression tuple definitions to be parsed, but it's not a supported
38
38
  // part of the API as specified by the associated types
39
- return $.parseRoot(args);
39
+ return $.parse(args);
40
40
  }, {
41
41
  bind: $,
42
42
  attach
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.5",
4
+ "version": "2.0.0-rc.7",
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/schema": "0.7.0",
38
- "@ark/util": "0.7.0"
37
+ "@ark/util": "0.9.0",
38
+ "@ark/schema": "0.9.0"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"