arktype 2.0.0-rc.6 → 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 (42) hide show
  1. package/out/generic.d.ts +5 -6
  2. package/out/generic.js +3 -5
  3. package/out/index.d.ts +1 -1
  4. package/out/keys.d.ts +5 -3
  5. package/out/keywords/ark.d.ts +2 -1
  6. package/out/keywords/ark.js +1 -0
  7. package/out/keywords/ast.d.ts +27 -17
  8. package/out/keywords/constructors/Array.js +3 -3
  9. package/out/keywords/constructors/FormData.js +5 -5
  10. package/out/keywords/constructors/constructors.d.ts +0 -1
  11. package/out/keywords/number/epoch.js +2 -2
  12. package/out/keywords/number/integer.js +2 -2
  13. package/out/keywords/number/number.js +2 -2
  14. package/out/keywords/string/capitalize.js +2 -2
  15. package/out/keywords/string/creditCard.js +2 -2
  16. package/out/keywords/string/date.js +5 -5
  17. package/out/keywords/string/integer.js +2 -2
  18. package/out/keywords/string/ip.js +2 -2
  19. package/out/keywords/string/json.js +3 -3
  20. package/out/keywords/string/lower.js +2 -2
  21. package/out/keywords/string/normalize.js +3 -3
  22. package/out/keywords/string/numeric.js +2 -2
  23. package/out/keywords/string/string.d.ts +1 -1
  24. package/out/keywords/string/trim.js +2 -2
  25. package/out/keywords/string/upper.js +2 -2
  26. package/out/keywords/string/url.js +4 -4
  27. package/out/methods/base.d.ts +3 -0
  28. package/out/methods/object.d.ts +31 -6
  29. package/out/parser/definition.d.ts +2 -3
  30. package/out/parser/objectLiteral.d.ts +4 -5
  31. package/out/parser/objectLiteral.js +4 -4
  32. package/out/parser/semantic/infer.d.ts +2 -1
  33. package/out/parser/string/reduce/dynamic.d.ts +3 -4
  34. package/out/parser/string/reduce/dynamic.js +3 -2
  35. package/out/parser/string/shift/operand/unenclosed.js +6 -2
  36. package/out/parser/tuple.d.ts +5 -6
  37. package/out/parser/tuple.js +20 -16
  38. package/out/scope.d.ts +21 -24
  39. package/out/scope.js +33 -29
  40. package/out/type.d.ts +6 -3
  41. package/out/type.js +8 -9
  42. package/package.json +3 -3
package/out/generic.d.ts CHANGED
@@ -1,13 +1,13 @@
1
- import { GenericRoot, type arkKind, type GenericAst, type GenericParamAst, type GenericParamDef, type genericParamNames, type LazyGenericBody } from "@ark/schema";
1
+ import { GenericRoot, type arkKind, type BaseParseContext, type GenericAst, type GenericParamAst, type GenericParamDef, type genericParamNames, type LazyGenericBody } from "@ark/schema";
2
2
  import { type array, type Callable, type conform, type ErrorMessage, type ErrorType, type Hkt, type Json, type WhiteSpaceToken } from "@ark/util";
3
3
  import type { type } from "./keywords/ark.ts";
4
4
  import type { inferDefinition, validateDefinition } from "./parser/definition.ts";
5
5
  import type { inferAstRoot } from "./parser/semantic/infer.ts";
6
6
  import type { validateAst } from "./parser/semantic/validate.ts";
7
7
  import type { state, StaticState } from "./parser/string/reduce/static.ts";
8
- import { Scanner } from "./parser/string/shift/scanner.ts";
8
+ import type { Scanner } from "./parser/string/shift/scanner.ts";
9
9
  import { parseUntilFinalizer } from "./parser/string/string.ts";
10
- import type { ParseContext, Scope } from "./scope.ts";
10
+ import type { Scope } from "./scope.ts";
11
11
  import type { Type } from "./type.ts";
12
12
  export type ParameterString<params extends string = string> = `<${params}>`;
13
13
  export type extractParams<s extends ParameterString> = s extends ParameterString<infer params> ? params : never;
@@ -127,16 +127,15 @@ export type GenericDeclaration<name extends string = string, params extends Para
127
127
  export type parseValidGenericParams<def extends ParameterString, $> = conform<parseGenericParams<extractParams<def>, $>, array<GenericParamAst>>;
128
128
  export declare const emptyGenericParameterMessage = "An empty string is not a valid generic parameter name";
129
129
  export type emptyGenericParameterMessage = typeof emptyGenericParameterMessage;
130
- export declare const parseGenericParams: (def: string, ctx: ParseContext) => array<GenericParamDef>;
131
130
  export type parseGenericParams<def extends string, $> = parseNextNameChar<Scanner.skipWhitespace<def>, "", [
132
131
  ], $>;
133
132
  type ParamsTerminator = WhiteSpaceToken | ",";
134
- declare const parseName: (scanner: Scanner, result: GenericParamDef[], ctx: ParseContext) => GenericParamDef[];
133
+ export declare const parseGenericParamName: (scanner: Scanner, result: GenericParamDef[], ctx: BaseParseContext) => GenericParamDef[];
135
134
  type parseName<unscanned extends string, result extends array<GenericParamAst>, $> = parseNextNameChar<Scanner.skipWhitespace<unscanned>, "", result, $>;
136
135
  type parseNextNameChar<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = unscanned extends `${infer lookahead}${infer nextUnscanned}` ? lookahead extends ParamsTerminator ? name extends "" ? ErrorMessage<emptyGenericParameterMessage> : lookahead extends "," ? parseName<nextUnscanned, [...result, [name, unknown]], $> : lookahead extends WhiteSpaceToken ? _parseOptionalConstraint<nextUnscanned, name, result, $> : never : parseNextNameChar<nextUnscanned, `${name}${lookahead}`, result, $> : name extends "" ? result : [...result, [name, unknown]];
137
136
  declare const extendsToken = "extends ";
138
137
  type extendsToken = typeof extendsToken;
139
- declare const _parseOptionalConstraint: (scanner: Scanner, name: string, result: GenericParamDef[], ctx: ParseContext) => GenericParamDef[];
138
+ declare const _parseOptionalConstraint: (scanner: Scanner, name: string, result: GenericParamDef[], ctx: BaseParseContext) => GenericParamDef[];
140
139
  type _parseOptionalConstraint<unscanned extends string, name extends string, result extends array<GenericParamAst>, $> = Scanner.skipWhitespace<unscanned> extends (`${extendsToken}${infer nextUnscanned}`) ? parseUntilFinalizer<state.initialize<nextUnscanned>, $, {}> extends (infer finalArgState extends StaticState) ? validateAst<finalArgState["root"], $, {}> extends (infer e extends ErrorMessage) ? e : parseName<finalArgState["unscanned"], [
141
140
  ...result,
142
141
  [name, inferAstRoot<finalArgState["root"], $, {}>]
package/out/generic.js CHANGED
@@ -1,12 +1,10 @@
1
1
  import { GenericRoot } from "@ark/schema";
2
2
  import { throwParseError } from "@ark/util";
3
3
  import { DynamicState } from "./parser/string/reduce/dynamic.js";
4
- import { Scanner } from "./parser/string/shift/scanner.js";
5
4
  import { parseUntilFinalizer } from "./parser/string/string.js";
6
5
  export const Generic = GenericRoot;
7
6
  export const emptyGenericParameterMessage = "An empty string is not a valid generic parameter name";
8
- export const parseGenericParams = (def, ctx) => parseName(new Scanner(def), [], ctx);
9
- const parseName = (scanner, result, ctx) => {
7
+ export const parseGenericParamName = (scanner, result, ctx) => {
10
8
  scanner.shiftUntilNonWhitespace();
11
9
  const name = scanner.shiftUntilNextTerminator();
12
10
  if (name === "") {
@@ -30,9 +28,9 @@ const _parseOptionalConstraint = (scanner, name, result, ctx) => {
30
28
  if (scanner.lookahead === ",")
31
29
  scanner.shift();
32
30
  result.push(name);
33
- return parseName(scanner, result, ctx);
31
+ return parseGenericParamName(scanner, result, ctx);
34
32
  }
35
33
  const s = parseUntilFinalizer(new DynamicState(scanner, ctx));
36
34
  result.push([name, s.root]);
37
- return parseName(scanner, result, ctx);
35
+ return parseGenericParamName(scanner, result, ctx);
38
36
  };
package/out/index.d.ts CHANGED
@@ -3,5 +3,5 @@ export { Hkt, inferred } from "@ark/util";
3
3
  export { Generic } from "./generic.ts";
4
4
  export { ambient, ark, declare, define, generic, type, type Ark } from "./keywords/ark.ts";
5
5
  export { Module, type BoundModule, type Submodule } from "./module.ts";
6
- export { module, scope, type Scope, type inferScope, type validateScope } from "./scope.ts";
6
+ export { module, scope, type Scope } from "./scope.ts";
7
7
  export { Type } from "./type.ts";
package/out/keys.d.ts CHANGED
@@ -5,12 +5,14 @@ export type toArkKey<o, k extends keyof o> = k extends number ? [
5
5
  o,
6
6
  number
7
7
  ] extends [array, k] ? NonNegativeIntegerLiteral : `${k}` : k;
8
- export type arkKeyOf<o> = o extends array ? (number extends o["length"] ? NonNegativeIntegerLiteral : never) | {
8
+ export type arkKeyOf<o> = [
9
+ o
10
+ ] extends [array] ? (number extends o["length"] ? NonNegativeIntegerLiteral : never) | {
9
11
  [k in keyof o]-?: k extends `${infer index extends number}` ? index | k : never;
10
12
  }[keyof o & `${number}`] : {
11
- [k in keyof o]: k extends number ? k | `${k}` : k;
13
+ [k in keyof o]-?: k extends number ? k | `${k}` : k;
12
14
  }[keyof o];
13
- export type getArkKey<o, k extends arkKeyOf<o>> = o[Extract<k extends NonNegativeIntegerLiteral ? number : k, keyof o>];
15
+ export type arkGet<o, k extends arkKeyOf<o>> = o[Extract<k extends NonNegativeIntegerLiteral ? number : k, keyof o>];
14
16
  export type TypeKey = termOrType<Key>;
15
17
  export type typeKeyToString<k extends TypeKey> = typeToString<k extends type.cast<infer t> ? t : k>;
16
18
  export type writeInvalidKeysMessage<o extends string, keys extends array<string>> = `Key${keys["length"] extends 1 ? "" : "s"} ${join<keys, ", ">} ${keys["length"] extends 1 ? "does" : "do"} not exist on ${o}`;
@@ -4,7 +4,7 @@ import type { GenericParser } from "../generic.ts";
4
4
  import type { BoundModule, Module } from "../module.ts";
5
5
  import type { inferDefinition, validateDefinition } from "../parser/definition.ts";
6
6
  import { type bindThis, type Scope } from "../scope.ts";
7
- import type { DeclarationParser, DefinitionParser, Type, TypeParser } from "../type.ts";
7
+ import type { DeclarationParser, DefinitionParser, SchemaParser, Type, TypeParser } from "../type.ts";
8
8
  import type { distill } from "./ast.ts";
9
9
  import { arkBuiltins } from "./builtins.ts";
10
10
  import { arkPrototypes } from "./constructors/constructors.ts";
@@ -52,5 +52,6 @@ export declare namespace type {
52
52
  }
53
53
  export type type<t = unknown, $ = {}> = Type<t, $>;
54
54
  export declare const generic: GenericParser<{}>;
55
+ export declare const schema: SchemaParser<{}>;
55
56
  export declare const define: DefinitionParser<{}>;
56
57
  export declare const declare: DeclarationParser<{}>;
@@ -21,5 +21,6 @@ export const ambient = scope({
21
21
  export const ark = ambient.export();
22
22
  export const type = ambient.type;
23
23
  export const generic = ambient.generic;
24
+ export const schema = ambient.schema;
24
25
  export const define = ambient.define;
25
26
  export const declare = ambient.declare;
@@ -1,5 +1,5 @@
1
1
  import type { ArkError, ArkErrors, Constraint, constraintKindOf, Morph, NodeSchema } from "@ark/schema";
2
- import { type anyOrNever, type array, type conform, type equals, type leftIfEqual, type Primitive, type show } from "@ark/util";
2
+ import { type anyOrNever, type array, type conform, type equals, type isSafelyMappable, type leftIfEqual, type objectKindOf, type Primitive, type show } from "@ark/util";
3
3
  import type { inferPipe } from "../intersect.ts";
4
4
  import type { Type } from "../type.ts";
5
5
  import type { type } from "./ark.ts";
@@ -71,12 +71,20 @@ export type parseConstraints<t> = t extends constrain<infer base, infer constrai
71
71
  }> extends true ? [
72
72
  string,
73
73
  constraints
74
- ] : equals<t, Date & {
74
+ ] : equals<t, bigint & {
75
75
  [constrained]: constraints;
76
76
  }> extends true ? [
77
- Date,
77
+ bigint,
78
78
  constraints
79
- ] : [base, constraints] : null;
79
+ ] : equals<t, symbol & {
80
+ [constrained]: constraints;
81
+ }> extends true ? [
82
+ symbol,
83
+ constraints
84
+ ] : objectKindOf<t> extends infer kind ? kind extends BuiltinTerminalObjectKind ? [
85
+ arkPrototypes.instanceOf<kind>,
86
+ constraints
87
+ ] : kind extends "Array" ? null : kind extends undefined ? [Omit<base, constrained>, constraints] : [base, constraints] : never : null;
80
88
  export type normalizePrimitiveConstraintRoot<schema extends NodeSchema<Constraint.PrimitiveKind>> = "rule" extends keyof schema ? conform<schema["rule"], PropertyKey> : conform<schema, PropertyKey>;
81
89
  type minLengthSchemaToConstraint<schema, rule> = schema extends {
82
90
  exclusive: true;
@@ -144,17 +152,18 @@ export type includesMorphs<t> = [
144
152
  type _distill<t, opts extends distill.Options> = t extends undefined ? t : [t] extends [anyOrNever] ? t : parseConstraints<t> extends ([
145
153
  infer base,
146
154
  infer constraints extends Constraints
147
- ]) ? opts["branded"] extends true ? constrain<_distill<base, opts>, constraints> : _distill<base, opts> : t extends TerminallyInferredObjectKind | Primitive ? t : unknown extends t ? unknown : t extends MorphAst<infer i, infer o> ? opts["endpoint"] extends "in" ? _distill<i, opts> : opts["endpoint"] extends "out.introspectable" ? o extends To<infer validatedOut> ? _distill<validatedOut, opts> : unknown : opts["endpoint"] extends "out" ? _distill<o[1], opts> : _distill<o[1], opts> extends infer r ? o extends To ? (In: i) => To<r> : (In: i) => Out<r> : never : t extends DefaultedAst<infer t> ? _distill<t, opts> : t extends array ? distillArray<t, opts, []> : t extends Function ? t : {
148
- [k in keyof t]: t[k];
149
- } extends t ? opts["endpoint"] extends "in" ? show<{
150
- [k in keyof t as k extends optionalInputKeyOf<t> ? never : k]: _distill<t[k], opts>;
155
+ ]) ? opts["branded"] extends true ? constrain<_distill<base, opts>, constraints> : _distill<base, opts> : unknown extends t ? unknown : t extends TerminallyInferredObject | Primitive ? t : t extends MorphAst<infer i, infer o> ? opts["branded"] extends true ? distillIo<i, o, opts> : distillUnbrandedIo<t, i, o, opts> : t extends array ? distillArray<t, opts> : t extends DefaultedAst<infer t> ? _distill<t, opts> : t extends Function ? t : isSafelyMappable<t> extends true ? distillMappable<t, opts> : t;
156
+ type distillMappable<o, opts extends distill.Options> = opts["endpoint"] extends "in" ? show<{
157
+ [k in keyof o as k extends optionalInputKeyOf<o> ? never : k]: _distill<o[k], opts>;
151
158
  } & {
152
- [k in optionalInputKeyOf<t>]?: _distill<t[k], opts>;
159
+ [k in optionalInputKeyOf<o>]?: _distill<o[k], opts>;
153
160
  }> : show<{
154
- [k in keyof t as k extends metaOptionalKeyOf<t> ? never : k]: _distill<t[k], opts>;
161
+ [k in keyof o as k extends metaOptionalKeyOf<o> ? never : k]: _distill<o[k], opts>;
155
162
  } & {
156
- [k in keyof t as k extends metaOptionalKeyOf<t> ? k : never]?: _distill<t[k], opts>;
157
- }> : t;
163
+ [k in keyof o as k extends metaOptionalKeyOf<o> ? k : never]?: _distill<o[k], opts>;
164
+ }>;
165
+ type distillUnbrandedIo<t extends MorphAst, i, o extends Out, opts extends distill.Options> = t extends (MorphAst<constrain<infer constrainedIn, any>, Out<constrain<infer constrainedOut, any>>>) ? distillIo<constrainedIn, o extends To ? To<constrainedOut> : Out<constrainedOut>, opts> : t extends MorphAst<constrain<infer constrainedIn, any>> ? distillIo<constrainedIn, o, opts> : t extends MorphAst<any, Out<constrain<infer constrainedOut, any>>> ? distillIo<i, o extends To ? To<constrainedOut> : Out<constrainedOut>, opts> : distillIo<i, o, opts>;
166
+ type distillIo<i, o extends Out, opts extends distill.Options> = opts["endpoint"] extends "in" ? _distill<i, opts> : opts["endpoint"] extends "out.introspectable" ? o extends To<infer validatedOut> ? _distill<validatedOut, opts> : unknown : opts["endpoint"] extends "out" ? _distill<o[1], opts> : _distill<o[1], opts> extends infer r ? o extends To ? (In: i) => To<r> : (In: i) => Out<r> : never;
158
167
  type optionalInputKeyOf<o> = metaDefaultedKeyOf<o> | metaOptionalKeyOf<o>;
159
168
  type metaDefaultedKeyOf<o> = {
160
169
  [k in keyof o]: [o[k]] extends [anyOrNever] ? never : o[k] extends DefaultedAst ? k : never;
@@ -162,16 +171,17 @@ type metaDefaultedKeyOf<o> = {
162
171
  type metaOptionalKeyOf<o> = {
163
172
  [k in keyof o]: [o[k]] extends [anyOrNever] ? never : o[k] extends OptionalAst ? k : never;
164
173
  }[keyof o];
165
- type distillArray<t extends array, opts extends distill.Options, prefix extends array> = _distillArray<t, opts, prefix> extends infer result ? (t extends unknown[] ? result : Readonly<t>) & // re-intersect non-array props for a type like `{ name: string } & string[]`
166
- _distill<{
167
- [k in keyof t as k extends keyof unknown[] ? never : k]: t[k];
168
- }, opts> : never;
174
+ type distillArray<t extends array, opts extends distill.Options> = _distillArray<[...t], opts, []> extends infer result ? distillNonArraykeys<t, t extends unknown[] ? result : Readonly<t>, opts> : never;
175
+ type distillNonArraykeys<originalArray extends array, distilledArray, opts extends distill.Options> = keyof originalArray extends keyof distilledArray | constrained ? distilledArray : distilledArray & _distill<{
176
+ [k in keyof originalArray as k extends (keyof distilledArray | (opts["branded"] extends true ? never : constrained)) ? never : k]: originalArray[k];
177
+ }, opts>;
169
178
  type _distillArray<t extends array, opts extends distill.Options, prefix extends array> = t extends readonly [infer head, ...infer tail] ? _distillArray<tail, opts, [...prefix, _distill<head, opts>]> : [...prefix, ...distillPostfix<t, opts>];
170
179
  type distillPostfix<t extends array, opts extends distill.Options, postfix extends array = []> = t extends readonly [...infer init, infer last] ? distillPostfix<init, opts, [_distill<last, opts>, ...postfix]> : [...{
171
180
  [i in keyof t]: _distill<t[i], opts>;
172
181
  }, ...postfix];
182
+ type BuiltinTerminalObjectKind = Exclude<keyof arkPrototypes.instances, "Array" | "Function">;
173
183
  /** Objects we don't want to expand during inference like Date or Promise */
174
- type TerminallyInferredObjectKind = arkPrototypes.instanceOfExcluding<"Array" | "Function"> | ArkEnv.prototypes;
184
+ type TerminallyInferredObject = arkPrototypes.instanceOf<BuiltinTerminalObjectKind> | ArkEnv.prototypes;
175
185
  export type inferPredicate<t, predicate> = predicate extends (data: any, ...args: any[]) => data is infer narrowed ? t extends constrain<unknown, infer constraints> ? applyConstraintSchema<constrain<narrowed, constraints>, "predicate", any> : applyConstraintSchema<narrowed, "predicate", any> : applyConstraintSchema<t, "predicate", any>;
176
186
  export type constrainWithPredicate<t> = t extends constrain<unknown, infer constraints> ? applyConstraintSchema<constrain<t, constraints>, "predicate", any> : applyConstraintSchema<t, "predicate", any>;
177
187
  export type inferPipes<t, pipes extends Morph[]> = pipes extends [infer head extends Morph, ...infer tail extends Morph[]] ? inferPipes<pipes[0] extends type.cast<infer tPipe> ? inferPipe<t, tPipe> : inferMorphOut<head> extends infer out ? (In: distill.brandable.In<t>) => Out<out> : never, tail> : t;
@@ -1,4 +1,4 @@
1
- import { genericNode, intrinsic, rootNode } from "@ark/schema";
1
+ import { genericNode, intrinsic, rootSchema } from "@ark/schema";
2
2
  import { Hkt, liftArray } from "@ark/util";
3
3
  import { arkModule } from "../utils.js";
4
4
  class liftFromHkt extends Hkt {
@@ -7,9 +7,9 @@ const liftFrom = genericNode("element")(args => {
7
7
  const nonArrayElement = args.element.exclude(intrinsic.Array);
8
8
  const lifted = nonArrayElement.array();
9
9
  return nonArrayElement
10
- .or(lifted)
10
+ .rawOr(lifted)
11
11
  .pipe(liftArray)
12
- .distribute(branch => branch.assertHasKind("morph").declareOut(lifted), rootNode);
12
+ .distribute(branch => branch.assertHasKind("morph").declareOut(lifted), rootSchema);
13
13
  }, liftFromHkt);
14
14
  export const arkArray = arkModule({
15
15
  root: intrinsic.Array,
@@ -1,9 +1,9 @@
1
- import { rootNode } from "@ark/schema";
1
+ import { rootSchema } from "@ark/schema";
2
2
  import { registry } from "@ark/util";
3
3
  import { arkModule } from "../utils.js";
4
- const value = rootNode(["string", registry.FileConstructor]);
5
- const parsedFormDataValue = value.or(value.array());
6
- const parsed = rootNode({
4
+ const value = rootSchema(["string", registry.FileConstructor]);
5
+ const parsedFormDataValue = value.rawOr(value.array());
6
+ const parsed = rootSchema({
7
7
  meta: "an object representing parsed form data",
8
8
  domain: "object",
9
9
  index: {
@@ -15,7 +15,7 @@ export const arkFormData = arkModule({
15
15
  root: ["instanceof", FormData],
16
16
  value,
17
17
  parsed,
18
- parse: rootNode({
18
+ parse: rootSchema({
19
19
  in: FormData,
20
20
  morphs: (data) => {
21
21
  const result = {};
@@ -26,6 +26,5 @@ export declare namespace arkPrototypes {
26
26
  interface instances extends ecmascript, platform {
27
27
  }
28
28
  type instanceOf<name extends keyof instances = keyof instances> = instances[name];
29
- type instanceOfExcluding<name extends keyof instances = keyof instances> = instances[Exclude<keyof instances, name>];
30
29
  }
31
30
  export {};
@@ -1,11 +1,11 @@
1
- import { rootNode } from "@ark/schema";
1
+ import { rootSchema } from "@ark/schema";
2
2
  /**
3
3
  * As per the ECMA-262 specification:
4
4
  * A time value supports a slightly smaller range of -8,640,000,000,000,000 to 8,640,000,000,000,000 milliseconds.
5
5
  *
6
6
  * @see https://262.ecma-international.org/15.0/index.html#sec-time-values-and-time-range
7
7
  */
8
- export const epoch = rootNode({
8
+ export const epoch = rootSchema({
9
9
  domain: {
10
10
  domain: "number",
11
11
  meta: "a number representing a Unix timestamp"
@@ -1,5 +1,5 @@
1
- import { rootNode } from "@ark/schema";
2
- export const integer = rootNode({
1
+ import { rootSchema } from "@ark/schema";
2
+ export const integer = rootSchema({
3
3
  domain: "number",
4
4
  divisor: 1
5
5
  });
@@ -1,4 +1,4 @@
1
- import { intrinsic, rootNode } from "@ark/schema";
1
+ import { intrinsic, rootSchema } from "@ark/schema";
2
2
  import { arkModule } from "../utils.js";
3
3
  import { epoch } from "./epoch.js";
4
4
  import { integer } from "./integer.js";
@@ -6,7 +6,7 @@ export const number = arkModule({
6
6
  root: intrinsic.number,
7
7
  integer,
8
8
  epoch,
9
- safe: rootNode({
9
+ safe: rootSchema({
10
10
  domain: "number",
11
11
  min: Number.MIN_SAFE_INTEGER,
12
12
  max: Number.MAX_SAFE_INTEGER,
@@ -1,9 +1,9 @@
1
- import { rootNode } from "@ark/schema";
1
+ import { rootSchema } from "@ark/schema";
2
2
  import { arkModule } from "../utils.js";
3
3
  import { regexStringNode } from "./utils.js";
4
4
  const preformatted = regexStringNode(/^[A-Z].*$/, "capitalized");
5
5
  export const capitalize = arkModule({
6
- root: rootNode({
6
+ root: rootSchema({
7
7
  in: "string",
8
8
  morphs: (s) => s.charAt(0).toUpperCase() + s.slice(1),
9
9
  declaredOut: preformatted
@@ -1,4 +1,4 @@
1
- import { rootNode } from "@ark/schema";
1
+ import { rootSchema } from "@ark/schema";
2
2
  // https://github.com/validatorjs/validator.js/blob/master/src/lib/isLuhnNumber.js
3
3
  export const isLuhnValid = (creditCardInput) => {
4
4
  const sanitized = creditCardInput.replace(/[- ]+/g, "");
@@ -24,7 +24,7 @@ export const isLuhnValid = (creditCardInput) => {
24
24
  };
25
25
  // https://github.com/validatorjs/validator.js/blob/master/src/lib/isCreditCard.js
26
26
  const creditCardMatcher = /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/;
27
- export const creditCard = rootNode({
27
+ export const creditCard = rootSchema({
28
28
  domain: "string",
29
29
  pattern: {
30
30
  meta: "a credit card number",
@@ -1,4 +1,4 @@
1
- import { ArkErrors, intrinsic, rootNode } from "@ark/schema";
1
+ import { ArkErrors, intrinsic, rootSchema } from "@ark/schema";
2
2
  import { number } from "../number/number.js";
3
3
  import { arkModule } from "../utils.js";
4
4
  import { integer } from "./integer.js";
@@ -40,7 +40,7 @@ export const tryParseDatePattern = (data, opts) => {
40
40
  return writeFormattedExpected(opts.format);
41
41
  };
42
42
  const isParsableDate = (s) => !Number.isNaN(new Date(s).valueOf());
43
- const parsableDate = rootNode({
43
+ const parsableDate = rootSchema({
44
44
  domain: "string",
45
45
  predicate: {
46
46
  meta: "a parsable date",
@@ -65,7 +65,7 @@ const epochroot = integer.root.internal
65
65
  .assertHasKind("intersection");
66
66
  const epoch = arkModule({
67
67
  root: epochroot,
68
- parse: rootNode({
68
+ parse: rootSchema({
69
69
  in: epochroot,
70
70
  morphs: (s) => new Date(s),
71
71
  declaredOut: intrinsic.Date
@@ -74,7 +74,7 @@ const epoch = arkModule({
74
74
  const isoroot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection");
75
75
  const iso = arkModule({
76
76
  root: isoroot,
77
- parse: rootNode({
77
+ parse: rootSchema({
78
78
  in: isoroot,
79
79
  morphs: (s) => new Date(s),
80
80
  declaredOut: intrinsic.Date
@@ -82,7 +82,7 @@ const iso = arkModule({
82
82
  });
83
83
  export const stringDate = arkModule({
84
84
  root: parsableDate,
85
- parse: rootNode({
85
+ parse: rootSchema({
86
86
  declaredIn: parsableDate,
87
87
  in: "string",
88
88
  morphs: (s, ctx) => {
@@ -1,11 +1,11 @@
1
- import { intrinsic, rootNode } from "@ark/schema";
1
+ import { intrinsic, rootSchema } from "@ark/schema";
2
2
  import { wellFormedIntegerMatcher } from "@ark/util";
3
3
  import { arkModule } from "../utils.js";
4
4
  import { regexStringNode } from "./utils.js";
5
5
  const root = regexStringNode(wellFormedIntegerMatcher, "a well-formed integer string");
6
6
  export const integer = arkModule({
7
7
  root,
8
- parse: rootNode({
8
+ parse: rootSchema({
9
9
  in: root,
10
10
  morphs: (s, ctx) => {
11
11
  const parsed = Number.parseInt(s);
@@ -1,6 +1,7 @@
1
1
  import { arkModule } from "../utils.js";
2
2
  import { regexStringNode } from "./utils.js";
3
3
  // Based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isIP.js
4
+ // Adjusted to incorporate unmerged fix in https://github.com/validatorjs/validator.js/pull/2083
4
5
  const ipv4Segment = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
5
6
  const ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`;
6
7
  const ipv4Matcher = new RegExp(`^${ipv4Address}$`);
@@ -14,8 +15,7 @@ const ipv6Matcher = new RegExp("^(" +
14
15
  `(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|` +
15
16
  `(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|` +
16
17
  `(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:))` +
17
- ")(%[0-9a-zA-Z-.:]{1,})?$");
18
- // Based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isUUID.js
18
+ ")(%[0-9a-zA-Z.]{1,})?$");
19
19
  export const ip = arkModule({
20
20
  root: ["v4 | v6", "@", "an IP address"],
21
21
  v4: regexStringNode(ipv4Matcher, "an IPv4 address"),
@@ -1,4 +1,4 @@
1
- import { intrinsic, rootNode } from "@ark/schema";
1
+ import { intrinsic, rootSchema } from "@ark/schema";
2
2
  import { arkModule } from "../utils.js";
3
3
  const jsonStringDescription = "a JSON string";
4
4
  const isParsableJson = (s) => {
@@ -10,7 +10,7 @@ const isParsableJson = (s) => {
10
10
  return false;
11
11
  }
12
12
  };
13
- const root = rootNode({
13
+ const root = rootSchema({
14
14
  domain: "string",
15
15
  predicate: {
16
16
  meta: jsonStringDescription,
@@ -19,7 +19,7 @@ const root = rootNode({
19
19
  });
20
20
  export const json = arkModule({
21
21
  root,
22
- parse: rootNode({
22
+ parse: rootSchema({
23
23
  in: "string",
24
24
  morphs: (s, ctx) => {
25
25
  if (s.length === 0) {
@@ -1,9 +1,9 @@
1
- import { rootNode } from "@ark/schema";
1
+ import { rootSchema } from "@ark/schema";
2
2
  import { arkModule } from "../utils.js";
3
3
  import { regexStringNode } from "./utils.js";
4
4
  const preformatted = regexStringNode(/^[a-z]*$/, "only lowercase letters");
5
5
  export const lower = arkModule({
6
- root: rootNode({
6
+ root: rootSchema({
7
7
  in: "string",
8
8
  morphs: (s) => s.toLowerCase(),
9
9
  declaredOut: preformatted
@@ -1,10 +1,10 @@
1
- import { rootNode } from "@ark/schema";
1
+ import { rootSchema } from "@ark/schema";
2
2
  import { flatMorph } from "@ark/util";
3
3
  import { arkModule } from "../utils.js";
4
4
  export const normalizedForms = ["NFC", "NFD", "NFKC", "NFKD"];
5
5
  const preformattedNodes = flatMorph(normalizedForms, (i, form) => [
6
6
  form,
7
- rootNode({
7
+ rootSchema({
8
8
  domain: "string",
9
9
  predicate: (s) => s.normalize(form) === s,
10
10
  meta: `${form}-normalized unicode`
@@ -12,7 +12,7 @@ const preformattedNodes = flatMorph(normalizedForms, (i, form) => [
12
12
  ]);
13
13
  const normalizeNodes = flatMorph(normalizedForms, (i, form) => [
14
14
  form,
15
- rootNode({
15
+ rootSchema({
16
16
  in: "string",
17
17
  morphs: (s) => s.normalize(form),
18
18
  declaredOut: preformattedNodes[form]
@@ -1,11 +1,11 @@
1
- import { intrinsic, rootNode } from "@ark/schema";
1
+ import { intrinsic, rootSchema } from "@ark/schema";
2
2
  import { wellFormedNumberMatcher } from "@ark/util";
3
3
  import { arkModule } from "../utils.js";
4
4
  import { regexStringNode } from "./utils.js";
5
5
  const root = regexStringNode(wellFormedNumberMatcher, "a well-formed numeric string");
6
6
  export const numeric = arkModule({
7
7
  root,
8
- parse: rootNode({
8
+ parse: rootSchema({
9
9
  in: root,
10
10
  morphs: (s) => Number.parseFloat(s),
11
11
  declaredOut: intrinsic.number
@@ -43,8 +43,8 @@ export declare const string: Module<{
43
43
  date: Submodule<stringDate.submodule>;
44
44
  lower: Submodule<lower.submodule>;
45
45
  upper: Submodule<upper.submodule>;
46
- json: Submodule<stringJson.submodule>;
47
46
  integer: Submodule<stringInteger.submodule>;
47
+ json: Submodule<stringJson.submodule>;
48
48
  alpha: unknown;
49
49
  alphanumeric: unknown;
50
50
  creditCard: unknown;
@@ -1,11 +1,11 @@
1
- import { rootNode } from "@ark/schema";
1
+ import { rootSchema } from "@ark/schema";
2
2
  import { arkModule } from "../utils.js";
3
3
  import { regexStringNode } from "./utils.js";
4
4
  const preformatted = regexStringNode(
5
5
  // no leading or trailing whitespace
6
6
  /^\S.*\S$|^\S?$/, "trimmed");
7
7
  export const trim = arkModule({
8
- root: rootNode({
8
+ root: rootSchema({
9
9
  in: "string",
10
10
  morphs: (s) => s.trim(),
11
11
  declaredOut: preformatted
@@ -1,9 +1,9 @@
1
- import { rootNode } from "@ark/schema";
1
+ import { rootSchema } from "@ark/schema";
2
2
  import { arkModule } from "../utils.js";
3
3
  import { regexStringNode } from "./utils.js";
4
4
  const preformatted = regexStringNode(/^[A-Z]*$/, "only uppercase letters");
5
5
  export const upper = arkModule({
6
- root: rootNode({
6
+ root: rootSchema({
7
7
  in: "string",
8
8
  morphs: (s) => s.toUpperCase(),
9
9
  declaredOut: preformatted
@@ -1,4 +1,4 @@
1
- import { rootNode } from "@ark/schema";
1
+ import { rootSchema } from "@ark/schema";
2
2
  import { arkModule } from "../utils.js";
3
3
  const isParsableUrl = (s) => {
4
4
  if (URL.canParse)
@@ -12,7 +12,7 @@ const isParsableUrl = (s) => {
12
12
  return false;
13
13
  }
14
14
  };
15
- const root = rootNode({
15
+ const root = rootSchema({
16
16
  domain: "string",
17
17
  predicate: {
18
18
  meta: "a URL string",
@@ -21,7 +21,7 @@ const root = rootNode({
21
21
  });
22
22
  export const url = arkModule({
23
23
  root,
24
- parse: rootNode({
24
+ parse: rootSchema({
25
25
  declaredIn: root,
26
26
  in: "string",
27
27
  morphs: (s, ctx) => {
@@ -32,6 +32,6 @@ export const url = arkModule({
32
32
  return ctx.error("a URL string");
33
33
  }
34
34
  },
35
- declaredOut: rootNode(URL)
35
+ declaredOut: rootSchema(URL)
36
36
  })
37
37
  });
@@ -1,5 +1,6 @@
1
1
  import type { ArkErrors, BaseRoot, Disjoint, JsonSchema, MetaSchema, Morph, UndeclaredKeyBehavior } from "@ark/schema";
2
2
  import type { anyOrNever, array, Callable, ErrorMessage, inferred, Json, unset } from "@ark/util";
3
+ import type { ArkAmbient } from "../config.ts";
3
4
  import type { inferIntersection } from "../intersect.ts";
4
5
  import type { type } from "../keywords/ark.ts";
5
6
  import type { applyConstraint, Default, distill, inferMorphOut, inferPipes, Optional } from "../keywords/ast.ts";
@@ -16,6 +17,8 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
16
17
  inferIn: distill.In<t>;
17
18
  [inferred]: t;
18
19
  json: Json;
20
+ meta: ArkAmbient.meta;
21
+ precompilation: string | undefined;
19
22
  toJsonSchema(): JsonSchema;
20
23
  description: string;
21
24
  expression: string;
@@ -1,5 +1,5 @@
1
- import type { array, ErrorType, merge } from "@ark/util";
2
- import type { arkKeyOf, getArkKey, toArkKey } from "../keys.ts";
1
+ import type { array, ErrorType, inferred, intersectUnion, Key, listable, merge, optionalKeyOf, show } from "@ark/util";
2
+ import type { arkGet, arkKeyOf, toArkKey } from "../keys.ts";
3
3
  import type { type } from "../keywords/ark.ts";
4
4
  import type { ArrayType } from "./array.ts";
5
5
  import type { instantiateType } from "./instantiate.ts";
@@ -11,10 +11,10 @@ interface Type<out t extends object = object, $ = {}> extends ValidatorType<t, $
11
11
  }, $> : Type<{
12
12
  readonly [k in keyof t]: t[k];
13
13
  }, $>;
14
- keyof(): instantiateType<keyof t, $>;
15
- get<k1 extends arkKeyOf<t>, r = instantiateType<getArkKey<t, k1>, $>>(k1: k1 | type.cast<k1>): r;
16
- get<k1 extends arkKeyOf<t>, k2 extends arkKeyOf<getArkKey<t, k1>>, r = instantiateType<getArkKey<getArkKey<t, k1>, k2>, $>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>): r;
17
- get<k1 extends arkKeyOf<t>, k2 extends arkKeyOf<getArkKey<t, k1>>, k3 extends arkKeyOf<getArkKey<getArkKey<t, k1>, k2>>, r = instantiateType<getArkKey<getArkKey<getArkKey<t, k1>, k2>, k3>, $>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>, k3: k3 | type.cast<k3>): r;
14
+ keyof(): instantiateType<arkKeyOf<t>, $>;
15
+ get<k1 extends arkKeyOf<t>, r = instantiateType<arkGet<t, k1>, $>>(k1: k1 | type.cast<k1>): r;
16
+ get<k1 extends arkKeyOf<t>, k2 extends arkKeyOf<arkGet<t, k1>>, r = instantiateType<arkGet<arkGet<t, k1>, k2>, $>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>): r;
17
+ get<k1 extends arkKeyOf<t>, k2 extends arkKeyOf<arkGet<t, k1>>, k3 extends arkKeyOf<arkGet<arkGet<t, k1>, k2>>, r = instantiateType<arkGet<arkGet<arkGet<t, k1>, k2>, k3>, $>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>, k3: k3 | type.cast<k3>): r;
18
18
  pick<const key extends arkKeyOf<t> = never>(...keys: (key | type.cast<key>)[]): Type<{
19
19
  [k in keyof t as Extract<toArkKey<t, k>, key>]: t[k];
20
20
  }, $>;
@@ -28,5 +28,30 @@ interface Type<out t extends object = object, $ = {}> extends ValidatorType<t, $
28
28
  partial(): Type<{
29
29
  [k in keyof t]?: t[k];
30
30
  }, $>;
31
+ map<transformed extends listable<MappedTypeEntry<Key, v>>, v = unknown>(flatMapEntry: (entry: typeEntryOf<t, $>) => transformed): Type<constructMapped<t, transformed>, $>;
31
32
  }
33
+ export type MappedTypeEntry<k extends Key = Key, v = unknown> = readonly [
34
+ key: k,
35
+ value: type.cast<v>,
36
+ kind?: "required" | "optional"
37
+ ];
38
+ type TypeEntries = array<MappedTypeEntry>;
39
+ type typeEntryOf<t, $> = {
40
+ [k in keyof t]-?: readonly [
41
+ k,
42
+ instantiateType<t[k] & ({} | null), $>,
43
+ k extends optionalKeyOf<t> ? "optional" : "required"
44
+ ];
45
+ }[keyof t] & unknown;
46
+ type constructMapped<t, transformed extends listable<MappedTypeEntry>> = show<intersectUnion<fromTypeEntries<t, transformed extends TypeEntries ? transformed : [transformed]>>>;
47
+ type fromTypeEntries<t, entries extends TypeEntries> = show<{
48
+ [entry in entries[number] as Extract<applyHomomorphicOptionality<t, entry>, readonly [unknown, unknown, "required"]>[0]]: entry[1][inferred];
49
+ } & {
50
+ [entry in entries[number] as Extract<applyHomomorphicOptionality<t, entry>, readonly [unknown, unknown, "optional"]>[0]]?: entry[1][inferred];
51
+ }>;
52
+ type applyHomomorphicOptionality<t, entry extends MappedTypeEntry> = readonly [
53
+ entry[0],
54
+ entry[1],
55
+ entry[2] extends string ? entry[2] : entry[0] extends optionalKeyOf<t> ? "optional" : "required"
56
+ ];
32
57
  export type { Type as ObjectType };
@@ -1,13 +1,12 @@
1
- import { type BaseRoot } from "@ark/schema";
1
+ import { type BaseParseContext, type BaseRoot } from "@ark/schema";
2
2
  import { type ErrorMessage, type Fn, type Primitive, type anyOrNever, type array, type defined, type equals, type ifEmptyObjectLiteral, type objectKindOrDomainOf, type optionalKeyOf, type requiredKeyOf, type show } from "@ark/util";
3
3
  import type { type } from "../keywords/ark.ts";
4
4
  import type { string } from "../keywords/string/string.ts";
5
- import type { ParseContext } from "../scope.ts";
6
5
  import { type inferObjectLiteral, type validateObjectLiteral } from "./objectLiteral.ts";
7
6
  import type { validateString } from "./semantic/validate.ts";
8
7
  import type { BaseCompletions, inferString } from "./string/string.ts";
9
8
  import { type TupleExpression, type inferTuple, type validateTuple } from "./tuple.ts";
10
- export declare const parseObject: (def: object, ctx: ParseContext) => BaseRoot;
9
+ export declare const parseObject: (def: object, ctx: BaseParseContext) => BaseRoot;
11
10
  export type inferDefinition<def, $, args> = [
12
11
  def
13
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;
@@ -1,11 +1,10 @@
1
- import { type BaseRoot, type Index, type Optional, type Required, type UndeclaredKeyBehavior, type writeInvalidPropertyKeyMessage } from "@ark/schema";
1
+ import { type BaseParseContext, type BaseRoot, type Index, type Optional, type Required, type UndeclaredKeyBehavior, type writeInvalidPropertyKeyMessage } from "@ark/schema";
2
2
  import { type anyOrNever, type Dict, type ErrorMessage, type ErrorType, type EscapeToken, type Key, type listable, type merge, type show } from "@ark/util";
3
3
  import type { constrain } from "../keywords/ast.ts";
4
- import type { ParseContext } from "../scope.ts";
5
4
  import type { inferDefinition, validateDefinition } from "./definition.ts";
6
5
  import type { astToString } from "./semantic/utils.ts";
7
6
  import type { validateString } from "./semantic/validate.ts";
8
- export declare const parseObjectLiteral: (def: Dict, ctx: ParseContext) => BaseRoot;
7
+ export declare const parseObjectLiteral: (def: Dict, ctx: BaseParseContext) => BaseRoot;
9
8
  export declare const writeInvalidUndeclaredBehaviorMessage: (actual: unknown) => string;
10
9
  export declare const nonLeadingSpreadError = "Spread operator may only be used as the first key in an object";
11
10
  export type inferObjectLiteral<def extends object, $, args> = show<"..." extends keyof def ? merge<inferDefinition<def["..."], $, args>, _inferObjectLiteral<def, $, args>> : _inferObjectLiteral<def, $, args>>;
@@ -24,7 +23,7 @@ export type validateObjectLiteral<def, $, args> = {
24
23
  };
25
24
  type nonOptionalKeyFrom<k, $, args> = parseKey<k> extends PreparsedKey<"required", infer inner> ? inner : parseKey<k> extends PreparsedKey<"index", infer inner> ? inferDefinition<inner, $, args> extends infer t extends Key ? t : never : never;
26
25
  type optionalKeyFrom<k> = parseKey<k> extends PreparsedKey<"optional", infer inner> ? inner : never;
27
- type PreparsedKey<kind extends ParsedKeyKind = ParsedKeyKind, key extends Key = Key> = {
26
+ export type PreparsedKey<kind extends ParsedKeyKind = ParsedKeyKind, key extends Key = Key> = {
28
27
  kind: kind;
29
28
  key: key;
30
29
  };
@@ -43,7 +42,7 @@ export type ParsedSpreadEntry = {
43
42
  kind: "spread";
44
43
  node: BaseRoot;
45
44
  };
46
- export declare const parseEntry: (key: Key, value: unknown, ctx: ParseContext) => listable<ParsedEntry>;
45
+ export declare const parseEntry: (key: Key, value: unknown, ctx: BaseParseContext) => listable<ParsedEntry>;
47
46
  declare const parseKey: (key: Key) => PreparsedKey;
48
47
  type parseKey<k> = k extends `${infer inner}?` ? inner extends `${infer baseName}${EscapeToken}` ? PreparsedKey.from<{
49
48
  kind: "required";
@@ -28,7 +28,7 @@ export const parseObjectLiteral = (def, ctx) => {
28
28
  structure[entry.kind] = append(structure[entry.kind], entry);
29
29
  }
30
30
  const structureNode = ctx.$.node("structure", structure);
31
- return ctx.$.rootNode({
31
+ return ctx.$.parseSchema({
32
32
  domain: "object",
33
33
  structure: spread?.merge(structureNode) ?? structureNode
34
34
  });
@@ -43,10 +43,10 @@ export const parseEntry = (key, value, ctx) => {
43
43
  return { kind: "undeclared", behavior: value };
44
44
  }
45
45
  if (parsedKey.kind === "...")
46
- return { kind: "spread", node: ctx.$.parse(value, ctx) };
47
- const parsedValue = ctx.$.parse(value, ctx);
46
+ return { kind: "spread", node: ctx.$.parseOwnDefinitionFormat(value, ctx) };
47
+ const parsedValue = ctx.$.parseOwnDefinitionFormat(value, ctx);
48
48
  if (parsedKey.kind === "index") {
49
- const signature = ctx.$.parse(parsedKey.key, ctx);
49
+ const signature = ctx.$.parseOwnDefinitionFormat(parsedKey.key, ctx);
50
50
  const normalized = normalizeIndex(signature, parsedValue, ctx.$);
51
51
  return (normalized.index ?
52
52
  normalized.required ?
@@ -1,6 +1,7 @@
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";
4
5
  import type { type } from "../../keywords/ark.ts";
5
6
  import type { Default, LimitLiteral, applyConstraintSchema, distill, normalizeLimit } from "../../keywords/ast.ts";
6
7
  import type { Date } from "../../keywords/constructors/Date.ts";
@@ -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 "=" ? 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" ? 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
  }
@@ -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,4 +1,4 @@
1
- import { $ark, makeRootAndArrayPropertiesMutable } from "@ark/schema";
1
+ import { $ark, Disjoint, intersectNodesRoot, makeRootAndArrayPropertiesMutable } from "@ark/schema";
2
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);
@@ -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,7 +34,7 @@ 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 => isEmptyObject(sequence) ?
37
+ return ctx.$.parseSchema(sequences.map(sequence => isEmptyObject(sequence) ?
38
38
  {
39
39
  proto: Array,
40
40
  exactLength: 0
@@ -91,11 +91,11 @@ const appendSpreadBranch = (base, branch) => {
91
91
  // the only array with no sequence reference is unknown[]
92
92
  return appendElement(base, "variadic", $ark.intrinsic.unknown);
93
93
  }
94
- spread.prefix.forEach(node => appendElement(base, "required", node));
95
- 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));
96
96
  if (spread.variadic)
97
97
  appendElement(base, "variadic", spread.variadic);
98
- spread.postfix.forEach(node => appendElement(base, "required", node));
98
+ spread.postfix?.forEach(node => appendElement(base, "required", node));
99
99
  return base;
100
100
  };
101
101
  const maybeParseTupleExpression = (def, ctx) => {
@@ -109,32 +109,36 @@ export const multipleVariadicMesage = "A tuple may have at most one variadic ele
109
109
  export const requiredPostOptionalMessage = "A required element may not follow an optional element";
110
110
  export const optionalPostVariadicMessage = "An optional element may not follow a variadic element";
111
111
  export const spreadOptionalMessage = "A spread element cannot be optional";
112
- export const parseKeyOfTuple = (def, ctx) => ctx.$.parse(def[1], ctx).keyof();
112
+ export const parseKeyOfTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[1], ctx).keyof();
113
113
  const parseBranchTuple = (def, ctx) => {
114
114
  if (def[2] === undefined)
115
115
  return throwParseError(writeMissingRightOperandMessage(def[1], ""));
116
- const l = ctx.$.parse(def[0], ctx);
117
- const r = ctx.$.parse(def[2], ctx);
118
- 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;
119
124
  };
120
- const parseArrayTuple = (def, ctx) => ctx.$.parse(def[0], ctx).array();
125
+ const parseArrayTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).array();
121
126
  const isIndexOneExpression = (def) => indexOneParsers[def[1]] !== undefined;
122
127
  export const parseMorphTuple = (def, ctx) => {
123
128
  if (typeof def[2] !== "function") {
124
129
  return throwParseError(writeMalformedFunctionalExpressionMessage("=>", def[2]));
125
130
  }
126
- // TODO: nested morphs?
127
- return ctx.$.parse(def[0], ctx).pipe(def[2]);
131
+ return ctx.$.parseOwnDefinitionFormat(def[0], ctx).pipe(def[2]);
128
132
  };
129
133
  export const writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value})`;
130
134
  export const parseNarrowTuple = (def, ctx) => {
131
135
  if (typeof def[2] !== "function") {
132
136
  return throwParseError(writeMalformedFunctionalExpressionMessage(":", def[2]));
133
137
  }
134
- return ctx.$.parse(def[0], ctx).constrain("predicate", def[2]);
138
+ return ctx.$.parseOwnDefinitionFormat(def[0], ctx).constrain("predicate", def[2]);
135
139
  };
136
- const parseAttributeTuple = (def, ctx) => ctx.$.parse(def[0], ctx).configureShallowDescendants(def[2]);
137
- 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]);
138
142
  const indexOneParsers = {
139
143
  "|": parseBranchTuple,
140
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,25 +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
- private _parse;
76
- parseString(def: string, ctx: ParseContext): BaseRoot;
77
- 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;
78
70
  unit: UnitTypeParser<$>;
79
71
  enumerated: EnumeratedTypeParser<$>;
80
72
  type: InternalTypeParser;
@@ -86,6 +78,12 @@ export declare class InternalScope<$ extends {} = {}> extends BaseScope<$> {
86
78
  static module: ModuleParser;
87
79
  }
88
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
+ }
89
87
  export declare const module: ModuleParser;
90
88
  export interface Scope<$ = {}> {
91
89
  t: $;
@@ -99,14 +97,14 @@ export interface Scope<$ = {}> {
99
97
  aliases: Record<string, unknown>;
100
98
  internal: toInternalScope<$>;
101
99
  defineSchema<const def extends RootSchema>(schema: def): def;
102
- schema(schema: RootSchema, opts?: NodeParseOptions): BaseRoot;
103
- 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>>>;
104
101
  unit: UnitTypeParser<$>;
105
102
  enumerated: EnumeratedTypeParser<$>;
106
103
  type: TypeParser<$>;
107
104
  declare: DeclarationParser<$>;
108
105
  define: DefinitionParser<$>;
109
106
  generic: GenericParser<$>;
107
+ schema: SchemaParser<$>;
110
108
  import(): Module<{
111
109
  [k in exportedNameOf<$> as PrivateDeclaration<k>]: $[k];
112
110
  }>;
@@ -127,7 +125,6 @@ export interface ScopeConstructor {
127
125
  module: ModuleParser;
128
126
  }
129
127
  export declare const Scope: ScopeConstructor;
130
- export declare const writeShallowCycleErrorMessage: (name: string, seen: string[]) => string;
131
128
  export type parseScopeKey<k, def> = k extends `${infer name}<${infer params}>` ? parseGenericScopeKey<name, params, def> : {
132
129
  name: k;
133
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,36 +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;
44
- }
45
- get ambientAttachments() {
46
- if (!$arkTypeRegistry.typeAttachments)
47
- return;
48
- return this.cacheGetter("ambientAttachments", flatMorph($arkTypeRegistry.typeAttachments, (k, v) => [
49
- k,
50
- this.bindReference(v)
51
- ]));
48
+ normalizeRootScopeValue(resolution) {
49
+ if (isThunk(resolution) && !hasArkKind(resolution, "generic"))
50
+ return resolution();
51
+ return resolution;
52
52
  }
53
- parse(def, ctx) {
54
- return this.bindReference(this._parse(def, ctx));
53
+ preparseOwnDefinitionFormat(def, opts) {
54
+ return {
55
+ ...opts,
56
+ def,
57
+ prefix: opts.alias ?? "type"
58
+ };
55
59
  }
56
- _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 };
57
66
  if (typeof def === "string") {
58
67
  if (ctx.args && Object.keys(ctx.args).some(k => def.includes(k))) {
59
68
  // we can only rely on the cache if there are no contextual
@@ -81,10 +90,6 @@ export class InternalScope extends BaseScope {
81
90
  throwParseError(writeUnexpectedCharacterMessage(">"));
82
91
  return node;
83
92
  }
84
- parseRoot = (def, opts = {}) => {
85
- const node = this.parse(def, Object.assign(this.finalizeRootArgs(opts, () => node), { $: this }));
86
- return node;
87
- };
88
93
  unit = value => this.units([value]);
89
94
  enumerated = (...values) => this.units(values);
90
95
  type = new InternalTypeParser(this);
@@ -98,4 +103,3 @@ export class InternalScope extends BaseScope {
98
103
  export const scope = InternalScope.scope;
99
104
  export const module = InternalScope.module;
100
105
  export const Scope = InternalScope;
101
- export const writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join(":")}`;
package/out/type.d.ts CHANGED
@@ -1,6 +1,6 @@
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";
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
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";
@@ -17,9 +17,11 @@ export interface TypeParser<$ = {}> extends Ark.boundTypeAttachments<$> {
17
17
  $: Scope<$>;
18
18
  raw(def: unknown): BaseType<any, $>;
19
19
  errors: typeof ArkErrors;
20
+ hkt: typeof Hkt;
20
21
  module: ModuleParser;
21
22
  scope: ScopeParser;
22
23
  generic: GenericParser<$>;
24
+ schema: SchemaParser<$>;
23
25
  ark: typeof ark;
24
26
  unit: UnitTypeParser<$>;
25
27
  enumerated: EnumeratedTypeParser<$>;
@@ -33,6 +35,7 @@ export type DeclarationParser<$> = <preinferred>() => {
33
35
  export type UnitTypeParser<$> = <const t>(value: t) => Type<t, $>;
34
36
  export type EnumeratedTypeParser<$> = <const values extends readonly unknown[]>(...values: values) => Type<values[number], $>;
35
37
  export type DefinitionParser<$> = <def>(def: type.validate<def, $>) => def;
38
+ export type SchemaParser<$> = (schema: RootSchema, opts?: BaseParseOptions) => Type<unknown, $>;
36
39
  export type Type<t = unknown, $ = {}> = instantiateType<t, $>;
37
40
  export declare namespace Type {
38
41
  type Any<t = any> = BaseType<t, any>;
package/out/type.js CHANGED
@@ -1,15 +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,
7
+ hkt: Hkt,
8
8
  $: $,
9
- raw: $.parseRoot,
9
+ raw: $.parse,
10
10
  module: $.constructor.module,
11
11
  scope: $.constructor.scope,
12
12
  generic: $.generic,
13
+ schema: $.schema,
13
14
  // this won't be defined during bootstrapping, but externally always will be
14
15
  ark: $.ambient,
15
16
  unit: $.unit,
@@ -20,7 +21,7 @@ export class InternalTypeParser extends Callable {
20
21
  super((...args) => {
21
22
  if (args.length === 1) {
22
23
  // treat as a simple definition
23
- return $.parseRoot(args[0]);
24
+ return $.parse(args[0]);
24
25
  }
25
26
  if (args.length === 2 &&
26
27
  typeof args[0] === "string" &&
@@ -28,16 +29,14 @@ export class InternalTypeParser extends Callable {
28
29
  args[0].at(-1) === ">") {
29
30
  // if there are exactly two args, the first of which looks like <${string}>,
30
31
  // treat as a generic
31
- const params = parseGenericParams(args[0].slice(1, -1), {
32
- $,
33
- args: {}
34
- });
32
+ const paramString = args[0].slice(1, -1);
33
+ const params = $.parseGenericParams(paramString, {});
35
34
  return new GenericRoot(params, args[1], $, $);
36
35
  }
37
36
  // otherwise, treat as a tuple expression. technically, this also allows
38
37
  // non-expression tuple definitions to be parsed, but it's not a supported
39
38
  // part of the API as specified by the associated types
40
- return $.parseRoot(args);
39
+ return $.parse(args);
41
40
  }, {
42
41
  bind: $,
43
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.6",
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/util": "0.8.0",
38
- "@ark/schema": "0.8.0"
37
+ "@ark/util": "0.9.0",
38
+ "@ark/schema": "0.9.0"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"