arktype 2.0.0-dev.24 → 2.0.0-dev.26

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 (38) hide show
  1. package/out/ark.d.ts +1 -1
  2. package/out/ark.js +1 -2
  3. package/out/parser/definition.d.ts +1 -1
  4. package/out/parser/generic.d.ts +2 -2
  5. package/out/parser/objectLiteral.d.ts +38 -25
  6. package/out/parser/objectLiteral.js +55 -62
  7. package/out/parser/semantic/bounds.d.ts +1 -1
  8. package/out/parser/semantic/default.d.ts +8 -0
  9. package/out/parser/semantic/default.js +1 -0
  10. package/out/parser/semantic/infer.d.ts +4 -3
  11. package/out/parser/semantic/validate.d.ts +5 -3
  12. package/out/parser/string/reduce/dynamic.d.ts +2 -1
  13. package/out/parser/string/reduce/dynamic.js +4 -2
  14. package/out/parser/string/reduce/shared.d.ts +5 -5
  15. package/out/parser/string/shift/operand/date.d.ts +2 -4
  16. package/out/parser/string/shift/operand/enclosed.d.ts +1 -11
  17. package/out/parser/string/shift/operand/genericArgs.d.ts +1 -1
  18. package/out/parser/string/shift/operand/operand.d.ts +3 -2
  19. package/out/parser/string/shift/operand/operand.js +2 -3
  20. package/out/parser/string/shift/operand/unenclosed.d.ts +4 -4
  21. package/out/parser/string/shift/operand/unenclosed.js +6 -5
  22. package/out/parser/string/shift/operator/bounds.d.ts +3 -5
  23. package/out/parser/string/shift/operator/bounds.js +5 -6
  24. package/out/parser/string/shift/operator/default.d.ts +24 -0
  25. package/out/parser/string/shift/operator/default.js +23 -0
  26. package/out/parser/string/shift/operator/divisor.d.ts +1 -1
  27. package/out/parser/string/shift/operator/operator.d.ts +3 -2
  28. package/out/parser/string/shift/scanner.d.ts +4 -11
  29. package/out/parser/string/shift/scanner.js +10 -12
  30. package/out/parser/string/string.d.ts +7 -5
  31. package/out/parser/string/string.js +4 -1
  32. package/out/parser/tuple.d.ts +4 -4
  33. package/out/parser/tuple.js +3 -3
  34. package/out/scope.d.ts +5 -4
  35. package/out/scope.js +104 -54
  36. package/out/type.d.ts +7 -5
  37. package/out/type.js +7 -4
  38. package/package.json +3 -3
@@ -1,5 +1,5 @@
1
1
  import { BaseRoot, hasArkKind, writeUnresolvableMessage } from "@arktype/schema";
2
- import { printable, throwParseError, tryParseNumber, tryParseWellFormedBigint } from "@arktype/util";
2
+ import { printable, throwParseError, tryParseWellFormedBigint, tryParseWellFormedNumber } from "@arktype/util";
3
3
  import { writePrefixedPrivateReferenceMessage } from "../../../semantic/validate.js";
4
4
  import { parseGenericArgs, writeInvalidGenericArgsMessage } from "./genericArgs.js";
5
5
  export const parseUnenclosed = (s) => {
@@ -28,18 +28,19 @@ const unenclosedToNode = (s, token) => maybeParseReference(s, token) ??
28
28
  : writeUnresolvableMessage(token));
29
29
  const maybeParseReference = (s, token) => {
30
30
  if (s.ctx.args?.[token])
31
- return s.ctx.args[token].raw;
31
+ return s.ctx.args[token].internal;
32
32
  const resolution = s.ctx.$.maybeResolve(token);
33
33
  if (resolution instanceof BaseRoot)
34
34
  return resolution;
35
35
  if (resolution === undefined)
36
36
  return;
37
- if (hasArkKind(resolution, "generic"))
38
- return parseGenericInstantiation(token, resolution, s);
37
+ if (hasArkKind(resolution, "generic")) {
38
+ return parseGenericInstantiation(token, throwParseError("Generics unsupported"), s);
39
+ }
39
40
  return throwParseError(`Unexpected resolution ${printable(resolution)}`);
40
41
  };
41
42
  const maybeParseUnenclosedLiteral = (s, token) => {
42
- const maybeNumber = tryParseNumber(token, { strict: true });
43
+ const maybeNumber = tryParseWellFormedNumber(token);
43
44
  if (maybeNumber !== undefined)
44
45
  return s.ctx.$.node("unit", { unit: maybeNumber });
45
46
  const maybeBigint = tryParseWellFormedBigint(token);
@@ -2,7 +2,7 @@ import { type BaseRoot, type BoundKind, type LimitLiteral } from "@arktype/schem
2
2
  import { type keySet } from "@arktype/util";
3
3
  import type { astToString } from "../../../semantic/utils.js";
4
4
  import type { DynamicState, DynamicStateWithRoot } from "../../reduce/dynamic.js";
5
- import { type Comparator, type InvertedComparators, type MaxComparator, writeUnpairableComparatorMessage } from "../../reduce/shared.js";
5
+ import { writeUnpairableComparatorMessage, type Comparator, type InvertedComparators, type MaxComparator } from "../../reduce/shared.js";
6
6
  import type { StaticState, state } from "../../reduce/static.js";
7
7
  import type { parseOperand } from "../operand/operand.js";
8
8
  import type { Scanner } from "../scanner.js";
@@ -16,14 +16,12 @@ type OneCharComparator = keyof typeof oneCharComparators;
16
16
  export type ComparatorStartChar = Comparator extends `${infer char}${string}` ? char : never;
17
17
  export declare const comparatorStartChars: keySet<ComparatorStartChar>;
18
18
  declare const shiftComparator: (s: DynamicState, start: ComparatorStartChar) => Comparator;
19
- type shiftComparator<start extends ComparatorStartChar, unscanned extends string> = unscanned extends `=${infer nextUnscanned}` ? [`${start}=`, nextUnscanned] : start extends OneCharComparator ? [start, unscanned] : state.error<singleEqualsMessage>;
19
+ type shiftComparator<start extends ComparatorStartChar, unscanned extends string> = unscanned extends `=${infer nextUnscanned}` ? [`${start}=`, nextUnscanned] : [start & OneCharComparator, unscanned];
20
20
  export declare const writeIncompatibleRangeMessage: (l: BoundKind, r: BoundKind) => string;
21
21
  export declare const getBoundKinds: (comparator: Comparator, limit: LimitLiteral, root: BaseRoot, boundKind: BoundExpressionKind) => BoundKind[];
22
- export declare const singleEqualsMessage = "= is not a valid comparator. Use == to check for equality";
23
- type singleEqualsMessage = typeof singleEqualsMessage;
24
22
  export declare const parseRightBound: (s: DynamicStateWithRoot, comparator: Comparator) => void;
25
23
  export type parseRightBound<s extends StaticState, comparator extends Comparator, $, args> = parseOperand<s, $, args> extends infer nextState extends StaticState ? nextState["root"] extends `${infer limit extends LimitLiteral}` ? s["branches"]["leftBound"] extends {} ? comparator extends MaxComparator ? state.reduceRange<s, s["branches"]["leftBound"]["limit"], s["branches"]["leftBound"]["comparator"], comparator, limit, nextState["unscanned"]> : state.error<writeUnpairableComparatorMessage<comparator>> : state.reduceSingleBound<s, comparator, limit, nextState["unscanned"]> : state.error<writeInvalidLimitMessage<comparator, astToString<nextState["root"]>, "right">> : never;
26
- export declare const writeInvalidLimitMessage: <comparator extends ">" | "<" | ">=" | "<=" | "==", limit extends string | number, boundKind extends BoundExpressionKind>(comparator: comparator, limit: limit, boundKind: boundKind) => `Comparator ${boundKind extends "left" ? InvertedComparators[comparator] : comparator} must be ${boundKind extends "left" ? "preceded" : "followed"} by a corresponding literal (was ${limit})`;
24
+ export declare const writeInvalidLimitMessage: <comparator extends Comparator, limit extends string | number, boundKind extends BoundExpressionKind>(comparator: comparator, limit: limit, boundKind: boundKind) => writeInvalidLimitMessage<comparator, limit, boundKind>;
27
25
  export type writeInvalidLimitMessage<comparator extends Comparator, limit extends string | number, boundKind extends BoundExpressionKind> = `Comparator ${boundKind extends "left" ? InvertedComparators[comparator] : comparator} must be ${boundKind extends "left" ? "preceded" : "followed"} by a corresponding literal (was ${limit})`;
28
26
  export type BoundExpressionKind = "left" | "right";
29
27
  export {};
@@ -1,4 +1,4 @@
1
- import { internalKeywords, jsObjects, tsKeywords, writeUnboundableMessage } from "@arktype/schema";
1
+ import { internal, jsObjects, tsKeywords, writeUnboundableMessage } from "@arktype/schema";
2
2
  import { isKeyOf, throwParseError } from "@arktype/util";
3
3
  import { invertedComparators, maxComparators, writeUnpairableComparatorMessage } from "../../reduce/shared.js";
4
4
  import { extractDateLiteralSource, isDateLiteral } from "../operand/date.js";
@@ -28,9 +28,9 @@ export const comparatorStartChars = {
28
28
  ">": 1,
29
29
  "=": 1
30
30
  };
31
- const shiftComparator = (s, start) => s.scanner.lookaheadIs("=") ? `${start}${s.scanner.shift()}`
32
- : isKeyOf(start, oneCharComparators) ? start
33
- : s.error(singleEqualsMessage);
31
+ const shiftComparator = (s, start) => s.scanner.lookaheadIs("=") ?
32
+ `${start}${s.scanner.shift()}`
33
+ : start;
34
34
  export const writeIncompatibleRangeMessage = (l, r) => `Bound kinds ${l} and ${r} are incompatible`;
35
35
  export const getBoundKinds = (comparator, limit, root, boundKind) => {
36
36
  if (root.extends(tsKeywords.number)) {
@@ -41,7 +41,7 @@ export const getBoundKinds = (comparator, limit, root, boundKind) => {
41
41
  : comparator[0] === ">" ? ["min"]
42
42
  : ["max"]);
43
43
  }
44
- if (root.extends(internalKeywords.lengthBoundable)) {
44
+ if (root.extends(internal.lengthBoundable)) {
45
45
  if (typeof limit !== "number") {
46
46
  return throwParseError(writeInvalidLimitMessage(comparator, limit, boundKind));
47
47
  }
@@ -57,7 +57,6 @@ export const getBoundKinds = (comparator, limit, root, boundKind) => {
57
57
  }
58
58
  return throwParseError(writeUnboundableMessage(root.expression));
59
59
  };
60
- export const singleEqualsMessage = "= is not a valid comparator. Use == to check for equality";
61
60
  const openLeftBoundToRoot = (leftBound) => ({
62
61
  rule: isDateLiteral(leftBound.limit) ?
63
62
  extractDateLiteralSource(leftBound.limit)
@@ -0,0 +1,24 @@
1
+ import type { BaseRoot, DateLiteral } from "@arktype/schema";
2
+ import { type BigintLiteral, type ErrorMessage, type NumberLiteral, type trim } from "@arktype/util";
3
+ import type { DynamicStateWithRoot } from "../../reduce/dynamic.js";
4
+ import type { StringLiteral } from "../operand/enclosed.js";
5
+ declare const unitLiteralKeywords: {
6
+ readonly null: null;
7
+ readonly undefined: undefined;
8
+ readonly true: true;
9
+ readonly false: false;
10
+ };
11
+ type UnitLiteralKeyword = keyof typeof unitLiteralKeywords;
12
+ export type UnitLiteral = StringLiteral | BigintLiteral | NumberLiteral | DateLiteral | UnitLiteralKeyword;
13
+ export type ParsedDefault = [BaseRoot, "=", unknown];
14
+ export declare const parseDefault: (s: DynamicStateWithRoot) => ParsedDefault;
15
+ export type parseDefault<root, unscanned extends string> = trim<unscanned> extends infer defaultValue extends UnitLiteral ? [
16
+ root,
17
+ "=",
18
+ defaultValue
19
+ ] : ErrorMessage<writeNonLiteralDefaultMessage<trim<unscanned>>>;
20
+ export declare const writeNonLiteralDefaultMessage: <defaultDef extends string>(defaultDef: defaultDef) => writeNonLiteralDefaultMessage<defaultDef>;
21
+ export type writeNonLiteralDefaultMessage<defaultDef extends string> = `Default value '${defaultDef}' must a literal value`;
22
+ export declare const shallowDefaultMessage = "Default values must be specified on objects like { isAdmin: 'boolean = false' }";
23
+ export type shallowDefaultMessage = typeof shallowDefaultMessage;
24
+ export {};
@@ -0,0 +1,23 @@
1
+ import { throwParseError } from "@arktype/util";
2
+ const unitLiteralKeywords = {
3
+ null: null,
4
+ undefined,
5
+ true: true,
6
+ false: false
7
+ };
8
+ export const parseDefault = (s) => {
9
+ if (!s.defaultable)
10
+ return throwParseError(shallowDefaultMessage);
11
+ // store the node that will be bounded
12
+ const baseNode = s.unsetRoot();
13
+ s.parseOperand();
14
+ const defaultNode = s.unsetRoot();
15
+ // after parsing the next operand, use the locations to get the
16
+ // token from which it was parsed
17
+ if (!defaultNode.hasKind("unit"))
18
+ return s.error(writeNonLiteralDefaultMessage(defaultNode.expression));
19
+ // assignability is checked in parseEntries
20
+ return [baseNode, "=", defaultNode.unit];
21
+ };
22
+ export const writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must a literal value`;
23
+ export const shallowDefaultMessage = `Default values must be specified on objects like { isAdmin: 'boolean = false' }`;
@@ -3,5 +3,5 @@ import type { StaticState, state } from "../../reduce/static.js";
3
3
  import type { Scanner } from "../scanner.js";
4
4
  export declare const parseDivisor: (s: DynamicStateWithRoot) => void;
5
5
  export type parseDivisor<s extends StaticState, unscanned extends string> = Scanner.shiftUntilNextTerminator<Scanner.skipWhitespace<unscanned>> extends (Scanner.shiftResult<infer scanned, infer nextUnscanned>) ? scanned extends `${infer divisor extends number}` ? divisor extends 0 ? state.error<writeInvalidDivisorMessage<0>> : state.setRoot<s, [s["root"], "%", divisor], nextUnscanned> : state.error<writeInvalidDivisorMessage<scanned>> : never;
6
- export declare const writeInvalidDivisorMessage: <divisor extends string | number>(divisor: divisor) => `% operator must be followed by a non-zero integer literal (was ${divisor})`;
6
+ export declare const writeInvalidDivisorMessage: <divisor extends string | number>(divisor: divisor) => writeInvalidDivisorMessage<divisor>;
7
7
  export type writeInvalidDivisorMessage<divisor extends string | number> = `% operator must be followed by a non-zero integer literal (was ${divisor})`;
@@ -1,11 +1,12 @@
1
+ import { type WhiteSpaceToken } from "@arktype/util";
1
2
  import type { DynamicStateWithRoot } from "../../reduce/dynamic.js";
2
3
  import type { StaticState, state } from "../../reduce/static.js";
3
4
  import { Scanner } from "../scanner.js";
4
5
  import { parseBound, type ComparatorStartChar } from "./bounds.js";
5
6
  import { parseDivisor } from "./divisor.js";
6
7
  export declare const parseOperator: (s: DynamicStateWithRoot) => void;
7
- export type parseOperator<s extends StaticState, $, args> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "[" ? unscanned extends Scanner.shift<"]", infer nextUnscanned> ? state.setRoot<s, [s["root"], "[]"], nextUnscanned> : state.error<incompleteArrayTokenMessage> : lookahead extends "|" | "&" ? state.reduceBranch<s, lookahead, unscanned> : lookahead extends ")" ? state.finalizeGroup<s, unscanned> : Scanner.lookaheadIsFinalizing<lookahead, unscanned> extends true ? state.finalize<state.scanTo<s, unscanned>, lookahead & Scanner.FinalizingLookahead> : lookahead extends ComparatorStartChar ? parseBound<s, lookahead, unscanned, $, args> : lookahead extends "%" ? parseDivisor<s, unscanned> : lookahead extends Scanner.WhiteSpaceToken ? parseOperator<state.scanTo<s, unscanned>, $, args> : state.error<writeUnexpectedCharacterMessage<lookahead>> : state.finalize<s, "">;
8
- export declare const writeUnexpectedCharacterMessage: <char extends string, shouldBe extends string>(char: char, shouldBe?: shouldBe) => `'${char}' is not allowed here${shouldBe extends "" ? "" : ` (should be ${shouldBe})`}`;
8
+ export type parseOperator<s extends StaticState, $, args> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "[" ? unscanned extends Scanner.shift<"]", infer nextUnscanned> ? state.setRoot<s, [s["root"], "[]"], nextUnscanned> : state.error<incompleteArrayTokenMessage> : lookahead extends "|" | "&" ? state.reduceBranch<s, lookahead, unscanned> : lookahead extends ")" ? state.finalizeGroup<s, unscanned> : Scanner.lookaheadIsFinalizing<lookahead, unscanned> extends true ? state.finalize<state.scanTo<s, unscanned>, lookahead & Scanner.FinalizingLookahead> : lookahead extends ComparatorStartChar ? parseBound<s, lookahead, unscanned, $, args> : lookahead extends "%" ? parseDivisor<s, unscanned> : lookahead extends WhiteSpaceToken ? parseOperator<state.scanTo<s, unscanned>, $, args> : state.error<writeUnexpectedCharacterMessage<lookahead>> : state.finalize<s, "">;
9
+ export declare const writeUnexpectedCharacterMessage: <char extends string, shouldBe extends string>(char: char, shouldBe?: shouldBe) => writeUnexpectedCharacterMessage<char, shouldBe>;
9
10
  export type writeUnexpectedCharacterMessage<char extends string, shouldBe extends string = ""> = `'${char}' is not allowed here${shouldBe extends "" ? "" : ` (should be ${shouldBe})`}`;
10
11
  export declare const incompleteArrayTokenMessage = "Missing expected ']'";
11
12
  type incompleteArrayTokenMessage = typeof incompleteArrayTokenMessage;
@@ -1,4 +1,4 @@
1
- import { type Dict } from "@arktype/util";
1
+ import { type Dict, type EscapeToken, type WhiteSpaceToken } from "@arktype/util";
2
2
  import type { Comparator } from "../reduce/shared.js";
3
3
  export declare class Scanner<lookahead extends string = string> {
4
4
  private chars;
@@ -45,21 +45,14 @@ export declare namespace Scanner {
45
45
  readonly ">": true;
46
46
  readonly ",": true;
47
47
  readonly "": true;
48
+ readonly "=": true;
48
49
  };
49
50
  type FinalizingLookahead = keyof typeof finalizingLookaheads;
50
51
  type InfixToken = Comparator | "|" | "&" | "%" | ":" | "=>";
51
52
  type PostfixToken = "[]";
52
53
  type OperatorToken = InfixToken | PostfixToken;
53
- const escapeToken = "\\";
54
- type EscapeToken = typeof escapeToken;
55
- const whiteSpaceTokens: {
56
- readonly " ": true;
57
- readonly "\n": true;
58
- readonly "\t": true;
59
- };
60
- type WhiteSpaceToken = keyof typeof whiteSpaceTokens;
61
- const lookaheadIsFinalizing: (lookahead: string, unscanned: string) => lookahead is ">" | ",";
62
- type lookaheadIsFinalizing<lookahead extends string, unscanned extends string> = lookahead extends ">" ? unscanned extends `=${infer nextUnscanned}` ? nextUnscanned extends `=${string}` ? true : false : Scanner.skipWhitespace<unscanned> extends ("" | `${TerminatingChar}${string}`) ? true : false : lookahead extends "," ? true : false;
54
+ const lookaheadIsFinalizing: (lookahead: string, unscanned: string) => lookahead is ">" | "," | "=";
55
+ type lookaheadIsFinalizing<lookahead extends string, unscanned extends string> = lookahead extends ">" ? unscanned extends `=${infer nextUnscanned}` ? nextUnscanned extends `=${string}` ? true : false : Scanner.skipWhitespace<unscanned> extends ("" | `${TerminatingChar}${string}`) ? true : false : lookahead extends "=" ? unscanned extends `=${string}` ? false : true : lookahead extends "," ? true : false;
63
56
  type shift<lookahead extends string, unscanned extends string> = `${lookahead}${unscanned}`;
64
57
  type shiftUntil<unscanned extends string, terminator extends string, scanned extends string = ""> = unscanned extends shift<infer lookahead, infer nextUnscanned> ? lookahead extends terminator ? scanned extends `${infer base}${EscapeToken}` ? shiftUntil<nextUnscanned, terminator, `${base}${lookahead}`> : [scanned, unscanned] : shiftUntil<nextUnscanned, terminator, `${scanned}${lookahead}`> : [scanned, ""];
65
58
  type shiftUntilNot<unscanned extends string, nonTerminator extends string, scanned extends string = ""> = unscanned extends shift<infer lookahead, infer nextUnscanned> ? lookahead extends nonTerminator ? shiftUntilNot<nextUnscanned, nonTerminator, `${scanned}${lookahead}`> : [scanned, unscanned] : [scanned, ""];
@@ -1,4 +1,4 @@
1
- import { isKeyOf } from "@arktype/util";
1
+ import { escapeToken, isKeyOf, whiteSpaceTokens } from "@arktype/util";
2
2
  export class Scanner {
3
3
  chars;
4
4
  i;
@@ -23,7 +23,7 @@ export class Scanner {
23
23
  let shifted = "";
24
24
  while (this.lookahead) {
25
25
  if (condition(this, shifted)) {
26
- if (shifted[shifted.length - 1] === Scanner.escapeToken)
26
+ if (shifted[shifted.length - 1] === escapeToken)
27
27
  shifted = shifted.slice(0, -1);
28
28
  else
29
29
  break;
@@ -63,7 +63,7 @@ export class Scanner {
63
63
  }
64
64
  (function (Scanner) {
65
65
  Scanner.lookaheadIsTerminator = (scanner) => scanner.lookahead in Scanner.terminatingChars;
66
- Scanner.lookaheadIsNotWhitespace = (scanner) => !(scanner.lookahead in Scanner.whiteSpaceTokens);
66
+ Scanner.lookaheadIsNotWhitespace = (scanner) => !(scanner.lookahead in whiteSpaceTokens);
67
67
  Scanner.terminatingChars = {
68
68
  "<": true,
69
69
  ">": true,
@@ -79,13 +79,8 @@ export class Scanner {
79
79
  Scanner.finalizingLookaheads = {
80
80
  ">": true,
81
81
  ",": true,
82
- "": true
83
- };
84
- Scanner.escapeToken = "\\";
85
- Scanner.whiteSpaceTokens = {
86
- " ": true,
87
- "\n": true,
88
- "\t": true
82
+ "": true,
83
+ "=": true
89
84
  };
90
85
  Scanner.lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">" ?
91
86
  unscanned[0] === "=" ?
@@ -95,6 +90,9 @@ export class Scanner {
95
90
  // if > is the end of a generic instantiation, the next token will be an operator or the end of the string
96
91
  : unscanned.trimStart() === "" ||
97
92
  isKeyOf(unscanned.trimStart()[0], Scanner.terminatingChars)
98
- // if the lookahead is a finalizing token but not >, it's unambiguously a finalizer (currently just ",")
99
- : lookahead === ",";
93
+ // "=" is a finalizer on its own (representing a default value),
94
+ // but not with a second "=" (an equality comparator)
95
+ : lookahead === "=" ? unscanned[0] !== "="
96
+ // ","" is unambiguously a finalizer
97
+ : lookahead === ",";
100
98
  })(Scanner || (Scanner = {}));
@@ -1,11 +1,12 @@
1
- import type { ambient, BaseRoot, resolvableReferenceIn } from "@arktype/schema";
1
+ import type { BaseRoot, resolvableReferenceIn } from "@arktype/schema";
2
2
  import { type ErrorMessage } from "@arktype/util";
3
3
  import type { inferAstRoot } from "../semantic/infer.js";
4
4
  import type { DynamicState, DynamicStateWithRoot } from "./reduce/dynamic.js";
5
5
  import type { StringifiablePrefixOperator } from "./reduce/shared.js";
6
6
  import type { state, StaticState } from "./reduce/static.js";
7
7
  import type { parseOperand } from "./shift/operand/operand.js";
8
- import { type parseOperator, writeUnexpectedCharacterMessage } from "./shift/operator/operator.js";
8
+ import { parseDefault, type ParsedDefault } from "./shift/operator/default.js";
9
+ import { writeUnexpectedCharacterMessage, type parseOperator } from "./shift/operator/operator.js";
9
10
  /**
10
11
  * Try to parse the definition from right to left using the most common syntax.
11
12
  * This can be much more efficient for simple definitions.
@@ -15,12 +16,13 @@ export type parseString<def extends string, $, args> = def extends keyof $ ? def
15
16
  "[]"
16
17
  ] : fullStringParse<state.initialize<def>, $, args> : fullStringParse<state.initialize<def>, $, args>;
17
18
  export type inferString<def extends string, $, args> = inferAstRoot<parseString<def, $, args>, $, args>;
18
- export type BaseCompletions<$, args, otherSuggestions extends string = never> = resolvableReferenceIn<$> | resolvableReferenceIn<ambient> | (keyof args & string) | StringifiablePrefixOperator | otherSuggestions;
19
- export declare const fullStringParse: (s: DynamicState) => BaseRoot;
19
+ export type BaseCompletions<$, args, otherSuggestions extends string = never> = resolvableReferenceIn<$> | resolvableReferenceIn<ArkEnv.$> | (keyof args & string) | StringifiablePrefixOperator | otherSuggestions;
20
+ export type StringParseResult = BaseRoot | ParsedDefault;
21
+ export declare const fullStringParse: (s: DynamicState) => StringParseResult;
20
22
  type fullStringParse<s extends StaticState, $, args> = extractFinalizedResult<parseUntilFinalizer<s, $, args>>;
21
23
  export declare const parseUntilFinalizer: (s: DynamicState) => DynamicStateWithRoot;
22
24
  export type parseUntilFinalizer<s extends StaticState, $, args> = s["finalizer"] extends undefined ? parseUntilFinalizer<next<s, $, args>, $, args> : s;
23
25
  declare const next: (s: DynamicState) => void;
24
26
  type next<s extends StaticState, $, args> = s["root"] extends undefined ? parseOperand<s, $, args> : parseOperator<s, $, args>;
25
- export type extractFinalizedResult<s extends StaticState> = s["finalizer"] extends ErrorMessage ? s["finalizer"] : s["finalizer"] extends "" ? s["root"] : state.error<writeUnexpectedCharacterMessage<`${s["finalizer"]}`>>;
27
+ export type extractFinalizedResult<s extends StaticState> = s["finalizer"] extends "" ? s["root"] : s["finalizer"] extends ErrorMessage ? s["finalizer"] : s["finalizer"] extends "=" ? parseDefault<s["root"], s["unscanned"]> : state.error<writeUnexpectedCharacterMessage<`${s["finalizer"]}`>>;
26
28
  export {};
@@ -1,11 +1,14 @@
1
1
  import { throwInternalError, throwParseError } from "@arktype/util";
2
+ import { parseDefault } from "./shift/operator/default.js";
2
3
  import { writeUnexpectedCharacterMessage } from "./shift/operator/operator.js";
3
4
  export const fullStringParse = (s) => {
4
5
  s.parseOperand();
5
- const result = parseUntilFinalizer(s).root;
6
+ let result = parseUntilFinalizer(s).root;
6
7
  if (!result) {
7
8
  return throwInternalError(`Root was unexpectedly unset after parsing string '${s.scanner.scanned}'`);
8
9
  }
10
+ if (s.finalizer === "=")
11
+ result = parseDefault(s);
9
12
  s.scanner.shiftUntilNonWhitespace();
10
13
  if (s.scanner.lookahead) {
11
14
  // throw a parse error if non-whitespace characters made it here without being parsed
@@ -1,5 +1,5 @@
1
1
  import { type BaseMeta, type BaseRoot, type Morph, type Out, type Predicate, type distillConstrainableIn, type distillOut, type inferIntersection, type inferMorphOut, type inferPredicate } from "@arktype/schema";
2
- import { type Constructor, type Domain, type ErrorMessage, type array, type conform, type show } from "@arktype/util";
2
+ import { type BuiltinObjectKind, type Constructor, type Domain, type ErrorMessage, type array, type conform, type show } from "@arktype/util";
3
3
  import type { ParseContext } from "../scope.js";
4
4
  import type { inferDefinition, validateDefinition } from "./definition.js";
5
5
  import type { InfixOperator, PostfixExpression } from "./semantic/infer.js";
@@ -86,7 +86,7 @@ type parseNextElement<s extends SequenceParseState, $, args> = preparseNextEleme
86
86
  ] : [])
87
87
  ];
88
88
  }, $, args> : s;
89
- export declare const writeNonArraySpreadMessage: <operand extends string>(operand: operand) => `Spread element must be an array${operand extends string ? ` (was ${operand})` : ""}`;
89
+ export declare const writeNonArraySpreadMessage: <operand extends string>(operand: operand) => writeNonArraySpreadMessage<operand>;
90
90
  type writeNonArraySpreadMessage<operand> = `Spread element must be an array${operand extends string ? ` (was ${operand})` : ""}`;
91
91
  export declare const multipleVariadicMesage = "A tuple may have at most one variadic element";
92
92
  type multipleVariadicMessage = typeof multipleVariadicMesage;
@@ -122,9 +122,9 @@ export type TupleInfixOperator = "&" | "|" | "=>" | ":" | "@";
122
122
  export type IndexOneExpression<token extends IndexOneOperator = IndexOneOperator> = readonly [unknown, token, ...unknown[]];
123
123
  export declare const parseMorphTuple: PostfixParser<"=>">;
124
124
  export declare const writeMalformedFunctionalExpressionMessage: (operator: ":" | "=>", value: unknown) => string;
125
- export type parseMorph<inDef, morph, $, args> = morph extends Morph ? (In: distillConstrainableIn<inferDefinition<inDef, $, args>>) => Out<inferMorphOut<morph>> : never;
125
+ export type parseMorph<inDef, morph, $, args> = morph extends Morph ? inferMorphOut<morph> extends infer out ? (In: distillConstrainableIn<inferDefinition<inDef, $, args>>) => Out<out> : never : never;
126
126
  export declare const parseNarrowTuple: PostfixParser<":">;
127
127
  export type IndexZeroOperator = "keyof" | "instanceof" | "===";
128
128
  export type IndexZeroExpression<token extends IndexZeroOperator = IndexZeroOperator> = readonly [token, ...unknown[]];
129
- export declare const writeInvalidConstructorMessage: <actual extends Domain | keyof import("@arktype/util").builtinConstructors>(actual: actual) => string;
129
+ export declare const writeInvalidConstructorMessage: <actual extends Domain | BuiltinObjectKind>(actual: actual) => string;
130
130
  export {};
@@ -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.$.raw.schema(sequences.map(sequence => ({
37
+ return ctx.$.internal.schema(sequences.map(sequence => ({
38
38
  proto: Array,
39
39
  sequence
40
40
  })));
@@ -75,7 +75,7 @@ const appendElement = (base, kind, element) => {
75
75
  }
76
76
  else {
77
77
  // e.g. [string, ...number[]]
78
- base.variadic = element.raw;
78
+ base.variadic = element.internal;
79
79
  }
80
80
  return base;
81
81
  }
@@ -84,7 +84,7 @@ const appendSpreadBranch = (base, branch) => {
84
84
  const spread = branch.firstReferenceOfKind("sequence");
85
85
  if (!spread) {
86
86
  // the only array with no sequence reference is unknown[]
87
- return appendElement(base, "variadic", tsKeywords.unknown);
87
+ return appendElement(base, "variadic", tsKeywords.unknown.internal);
88
88
  }
89
89
  spread.prefix.forEach(node => appendElement(base, "required", node));
90
90
  spread.optionals.forEach(node => appendElement(base, "optional", node));
package/out/scope.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { RawRootScope, type ArkConfig, type BaseRoot, type GenericProps, type PreparsedNodeResolution, type PrivateDeclaration, type RawRootResolutions, type RootScope, type UnknownRoot, type ambient, type arkKind, type destructuredExportContext, type destructuredImportContext, type exportedNameOf, type writeDuplicateAliasError } from "@arktype/schema";
1
+ import { RawRootScope, type ArkConfig, type BaseRoot, type GenericProps, type PreparsedNodeResolution, type PrivateDeclaration, type RawRootResolutions, type RootScope, type UnknownRoot, type arkKind, type destructuredExportContext, type destructuredImportContext, type exportedNameOf, type writeDuplicateAliasError } from "@arktype/schema";
2
2
  import { type anyOrNever, type keyError, type nominal, type show } from "@arktype/util";
3
3
  import { Generic } from "./generic.js";
4
4
  import { type MatchParser } from "./match.js";
5
5
  import type { Module } from "./module.js";
6
6
  import { type inferDefinition, type validateDefinition } from "./parser/definition.js";
7
7
  import { parseGenericParams, type GenericDeclaration, type GenericParamsParseError } from "./parser/generic.js";
8
+ import type { ParsedDefault } from "./parser/string/shift/operator/default.js";
8
9
  import { RawTypeParser, type DeclarationParser, type DefinitionParser, type Type, type TypeParser } from "./type.js";
9
10
  export type ScopeParser = <const def>(def: validateScope<def>, config?: ArkConfig) => Scope<inferScope<def>>;
10
11
  export type validateScope<def> = {
@@ -40,7 +41,7 @@ export type moduleKeyOf<$> = {
40
41
  [arkKind]: "module";
41
42
  } ? k & string : never;
42
43
  }[keyof $];
43
- export type tryInferSubmoduleReference<$, token> = token extends `${infer submodule extends moduleKeyOf<$>}.${infer subalias}` ? subalias extends keyof $[submodule] ? $[submodule][subalias] : never : token extends (`${infer submodule extends moduleKeyOf<ambient>}.${infer subalias}`) ? subalias extends keyof ambient[submodule] ? ambient[submodule][subalias] : never : never;
44
+ export type tryInferSubmoduleReference<$, token> = token extends `${infer submodule extends moduleKeyOf<$>}.${infer subalias}` ? subalias extends keyof $[submodule] ? $[submodule][subalias] : never : token extends `${infer submodule}.${infer subalias}` ? submodule extends moduleKeyOf<ArkEnv.$> ? subalias extends keyof ArkEnv.$[submodule] ? ArkEnv.$[submodule][subalias] : never : never : never;
44
45
  export interface ParseContext {
45
46
  $: RawScope;
46
47
  args?: Record<string, UnknownRoot>;
@@ -65,8 +66,8 @@ export declare class RawScope<$ extends RawRootResolutions = RawRootResolutions>
65
66
  define: (def: unknown) => unknown;
66
67
  preparseRoot(def: unknown): unknown;
67
68
  parseRoot(def: unknown): BaseRoot;
68
- parse(def: unknown, ctx: ParseContext): BaseRoot;
69
- parseString(def: string, ctx: ParseContext): BaseRoot;
69
+ parse<defaultable extends boolean = false>(def: unknown, ctx: ParseContext, defaultable?: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
70
+ parseString<defaultable extends boolean>(def: string, ctx: ParseContext, defaultable: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
70
71
  }
71
72
  export declare const writeShallowCycleErrorMessage: (name: string, seen: string[]) => string;
72
73
  export type ParsedScopeKey = {
package/out/scope.js CHANGED
@@ -1,5 +1,39 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
1
35
  import { RawRootScope, hasArkKind } from "@arktype/schema";
2
- import { domainOf, hasDomain, isThunk, throwParseError } from "@arktype/util";
36
+ import { bound, domainOf, hasDomain, isThunk, throwParseError } from "@arktype/util";
3
37
  import { Generic } from "./generic.js";
4
38
  import { createMatchParser } from "./match.js";
5
39
  import { parseObject, writeBadDefinitionTypeMessage } from "./parser/definition.js";
@@ -8,62 +42,78 @@ import { DynamicState } from "./parser/string/reduce/dynamic.js";
8
42
  import { fullStringParse } from "./parser/string/string.js";
9
43
  import { RawTypeParser } from "./type.js";
10
44
  export const scope = ((def, config = {}) => new RawScope(def, config));
11
- export class RawScope extends RawRootScope {
12
- parseCache = {};
13
- constructor(def, config) {
14
- const aliases = {};
15
- for (const k in def) {
16
- const parsedKey = parseScopeKey(k);
17
- aliases[parsedKey.name] =
18
- parsedKey.params.length ?
19
- // TODO: this
20
- new Generic(parsedKey.params, def[k], {})
21
- : def[k];
45
+ let RawScope = (() => {
46
+ let _classSuper = RawRootScope;
47
+ let _instanceExtraInitializers = [];
48
+ let _parseRoot_decorators;
49
+ return class RawScope extends _classSuper {
50
+ static {
51
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
52
+ _parseRoot_decorators = [bound];
53
+ __esDecorate(this, null, _parseRoot_decorators, { kind: "method", name: "parseRoot", static: false, private: false, access: { has: obj => "parseRoot" in obj, get: obj => obj.parseRoot }, metadata: _metadata }, null, _instanceExtraInitializers);
54
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
22
55
  }
23
- super(aliases, config);
24
- }
25
- type = new RawTypeParser(this);
26
- match = createMatchParser(this);
27
- declare = (() => ({
28
- type: this.type
29
- })).bind(this);
30
- define = ((def) => def).bind(this);
31
- preparseRoot(def) {
32
- if (isThunk(def) && !hasArkKind(def, "generic"))
33
- return def();
34
- return def;
35
- }
36
- parseRoot(def) {
37
- // args: { this: {} as RawRoot },
38
- return this.parse(def, {
39
- $: this,
40
- args: {}
41
- // type parsing can bypass nodes if it hits the cache,
42
- // so bind it directly (could be optimized)
43
- }).bindScope(this);
44
- }
45
- parse(def, ctx) {
46
- if (typeof def === "string") {
47
- if (ctx.args && Object.keys(ctx.args).every(k => !def.includes(k))) {
48
- // we can only rely on the cache if there are no contextual
49
- // resolutions like "this" or generic args
50
- return this.parseString(def, ctx);
56
+ parseCache = (__runInitializers(this, _instanceExtraInitializers), {});
57
+ constructor(def, config) {
58
+ const aliases = {};
59
+ for (const k in def) {
60
+ const parsedKey = parseScopeKey(k);
61
+ aliases[parsedKey.name] =
62
+ parsedKey.params.length ?
63
+ // TODO: this
64
+ new Generic(parsedKey.params, def[k], {})
65
+ : def[k];
51
66
  }
52
- if (!this.parseCache[def])
53
- this.parseCache[def] = this.parseString(def, ctx);
54
- return this.parseCache[def];
67
+ super(aliases, config);
55
68
  }
56
- return hasDomain(def, "object") ?
57
- parseObject(def, ctx)
58
- : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)));
59
- }
60
- parseString(def, ctx) {
61
- return (this.maybeResolveRoot(def) ??
62
- ((def.endsWith("[]") &&
63
- this.maybeResolveRoot(def.slice(0, -2))?.array()) ||
64
- fullStringParse(new DynamicState(def, ctx))));
65
- }
66
- }
69
+ type = new RawTypeParser(this);
70
+ match = createMatchParser(this);
71
+ declare = (() => ({
72
+ type: this.type
73
+ })).bind(this);
74
+ define = ((def) => def).bind(this);
75
+ preparseRoot(def) {
76
+ if (isThunk(def) && !hasArkKind(def, "generic"))
77
+ return def();
78
+ return def;
79
+ }
80
+ parseRoot(def) {
81
+ return this.parse(def, {
82
+ $: this,
83
+ // args: { this: {} as RawRoot },
84
+ args: {}
85
+ }).bindScope(this);
86
+ }
87
+ parse(def, ctx, defaultable = false) {
88
+ if (typeof def === "string") {
89
+ if (ctx.args && Object.keys(ctx.args).every(k => !def.includes(k))) {
90
+ // we can only rely on the cache if there are no contextual
91
+ // resolutions like "this" or generic args
92
+ return this.parseString(def, ctx, defaultable);
93
+ }
94
+ const contextKey = `${def}${defaultable}`;
95
+ if (!this.parseCache[contextKey])
96
+ this.parseCache[contextKey] = this.parseString(def, ctx, defaultable);
97
+ return this.parseCache[contextKey];
98
+ }
99
+ return hasDomain(def, "object") ?
100
+ parseObject(def, ctx)
101
+ : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)));
102
+ }
103
+ parseString(def, ctx, defaultable) {
104
+ const aliasResolution = this.maybeResolveRoot(def);
105
+ if (aliasResolution)
106
+ return aliasResolution;
107
+ const aliasArrayResolution = def.endsWith("[]") ?
108
+ this.maybeResolveRoot(def.slice(0, -2))?.array()
109
+ : undefined;
110
+ if (aliasArrayResolution)
111
+ return aliasArrayResolution;
112
+ return fullStringParse(new DynamicState(def, ctx, defaultable));
113
+ }
114
+ };
115
+ })();
116
+ export { RawScope };
67
117
  export const writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join(":")}`;
68
118
  export const parseScopeKey = (k) => {
69
119
  const firstParamIndex = k.indexOf("<");