arktype 2.0.0-dev.0 → 2.0.0-dev.10

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 (219) hide show
  1. package/__tests__/array.test.ts +270 -151
  2. package/__tests__/badDefinitionType.test.ts +10 -3
  3. package/__tests__/basis.test.ts +6 -2
  4. package/__tests__/bounds.test.ts +282 -352
  5. package/__tests__/cast.test.ts +7 -2
  6. package/__tests__/completions.test.ts +8 -3
  7. package/__tests__/config.test.ts +95 -167
  8. package/__tests__/dateLiteral.test.ts +8 -4
  9. package/__tests__/declared.test.ts +7 -6
  10. package/__tests__/discrimination.test.ts +1 -1
  11. package/__tests__/divisor.test.ts +46 -22
  12. package/__tests__/enclosed.test.ts +39 -25
  13. package/__tests__/examples.test.ts +56 -56
  14. package/__tests__/expressions.test.ts +184 -112
  15. package/__tests__/generic.test.ts +307 -288
  16. package/__tests__/group.test.ts +67 -54
  17. package/__tests__/imports.test.ts +62 -49
  18. package/__tests__/instanceof.test.ts +25 -23
  19. package/__tests__/intersection.test.ts +52 -48
  20. package/__tests__/keyTraversal.test.ts +77 -73
  21. package/__tests__/keyof.test.ts +68 -52
  22. package/__tests__/keywords.test.ts +164 -138
  23. package/__tests__/literal.test.ts +60 -21
  24. package/__tests__/match.bench.ts +31 -0
  25. package/__tests__/match.test.ts +222 -22
  26. package/__tests__/narrow.test.ts +52 -54
  27. package/__tests__/objectLiteral.test.ts +347 -205
  28. package/__tests__/operator.bench.ts +4 -4
  29. package/__tests__/pipe.test.ts +501 -0
  30. package/__tests__/realWorld.test.ts +63 -0
  31. package/__tests__/regex.test.ts +17 -7
  32. package/__tests__/scope.bench.ts +1 -1
  33. package/__tests__/scope.test.ts +257 -23
  34. package/__tests__/serialization.test.ts +19 -0
  35. package/__tests__/string.test.ts +11 -7
  36. package/__tests__/submodule.test.ts +26 -39
  37. package/__tests__/this.test.ts +83 -57
  38. package/__tests__/thunk.test.ts +13 -7
  39. package/__tests__/traverse.test.ts +76 -54
  40. package/__tests__/tsGenerics.test.ts +12 -12
  41. package/__tests__/type.test.ts +36 -0
  42. package/__tests__/typeReference.test.ts +7 -7
  43. package/__tests__/unenclosed.test.ts +116 -100
  44. package/__tests__/union.test.ts +171 -104
  45. package/ark.ts +21 -65
  46. package/generic.ts +69 -0
  47. package/main.ts +6 -18
  48. package/match.ts +195 -93
  49. package/module.ts +15 -0
  50. package/out/ark.d.ts +15 -39
  51. package/out/ark.js +9 -18
  52. package/out/ark.js.map +1 -1
  53. package/out/generic.d.ts +21 -0
  54. package/out/generic.js +24 -0
  55. package/out/generic.js.map +1 -0
  56. package/out/main.d.ts +6 -7
  57. package/out/main.js +4 -3
  58. package/out/main.js.map +1 -1
  59. package/out/match.d.ts +57 -34
  60. package/out/match.js +51 -17
  61. package/out/match.js.map +1 -1
  62. package/out/module.d.ts +10 -0
  63. package/out/module.js +3 -0
  64. package/out/module.js.map +1 -0
  65. package/out/parser/definition.d.ts +11 -13
  66. package/out/parser/definition.js +10 -13
  67. package/out/parser/definition.js.map +1 -1
  68. package/out/parser/generic.d.ts +5 -7
  69. package/out/parser/generic.js +7 -11
  70. package/out/parser/generic.js.map +1 -1
  71. package/out/parser/objectLiteral.d.ts +45 -14
  72. package/out/parser/objectLiteral.js +61 -52
  73. package/out/parser/objectLiteral.js.map +1 -1
  74. package/out/parser/semantic/bounds.d.ts +10 -8
  75. package/out/parser/semantic/bounds.js +0 -1
  76. package/out/parser/semantic/bounds.js.map +1 -1
  77. package/out/parser/semantic/divisor.d.ts +5 -7
  78. package/out/parser/semantic/divisor.js +0 -1
  79. package/out/parser/semantic/infer.d.ts +24 -0
  80. package/out/parser/semantic/infer.js +1 -0
  81. package/out/parser/semantic/infer.js.map +1 -0
  82. package/out/parser/semantic/utils.d.ts +3 -7
  83. package/out/parser/semantic/utils.js +0 -1
  84. package/out/parser/semantic/validate.d.ts +15 -14
  85. package/out/parser/semantic/validate.js +1 -1
  86. package/out/parser/semantic/validate.js.map +1 -1
  87. package/out/parser/string/reduce/dynamic.d.ts +13 -13
  88. package/out/parser/string/reduce/dynamic.js +31 -26
  89. package/out/parser/string/reduce/dynamic.js.map +1 -1
  90. package/out/parser/string/reduce/shared.d.ts +6 -20
  91. package/out/parser/string/reduce/shared.js +0 -1
  92. package/out/parser/string/reduce/shared.js.map +1 -1
  93. package/out/parser/string/reduce/static.d.ts +27 -24
  94. package/out/parser/string/reduce/static.js +0 -1
  95. package/out/parser/string/shift/operand/date.d.ts +3 -3
  96. package/out/parser/string/shift/operand/date.js +4 -7
  97. package/out/parser/string/shift/operand/date.js.map +1 -1
  98. package/out/parser/string/shift/operand/enclosed.d.ts +4 -19
  99. package/out/parser/string/shift/operand/enclosed.js +12 -13
  100. package/out/parser/string/shift/operand/enclosed.js.map +1 -1
  101. package/out/parser/string/shift/operand/genericArgs.d.ts +9 -10
  102. package/out/parser/string/shift/operand/genericArgs.js +6 -10
  103. package/out/parser/string/shift/operand/genericArgs.js.map +1 -1
  104. package/out/parser/string/shift/operand/operand.d.ts +3 -4
  105. package/out/parser/string/shift/operand/operand.js +8 -12
  106. package/out/parser/string/shift/operand/operand.js.map +1 -1
  107. package/out/parser/string/shift/operand/unenclosed.d.ts +15 -22
  108. package/out/parser/string/shift/operand/unenclosed.js +24 -36
  109. package/out/parser/string/shift/operand/unenclosed.js.map +1 -1
  110. package/out/parser/string/shift/operator/bounds.d.ts +9 -13
  111. package/out/parser/string/shift/operator/bounds.js +43 -54
  112. package/out/parser/string/shift/operator/bounds.js.map +1 -1
  113. package/out/parser/string/shift/operator/divisor.d.ts +2 -4
  114. package/out/parser/string/shift/operator/divisor.js +1 -3
  115. package/out/parser/string/shift/operator/divisor.js.map +1 -1
  116. package/out/parser/string/shift/operator/operator.d.ts +2 -3
  117. package/out/parser/string/shift/operator/operator.js +12 -19
  118. package/out/parser/string/shift/operator/operator.js.map +1 -1
  119. package/out/parser/string/shift/scanner.d.ts +2 -2
  120. package/out/parser/string/shift/scanner.js +14 -16
  121. package/out/parser/string/shift/scanner.js.map +1 -1
  122. package/out/parser/string/string.d.ts +8 -6
  123. package/out/parser/string/string.js +1 -3
  124. package/out/parser/string/string.js.map +1 -1
  125. package/out/parser/tuple.d.ts +102 -43
  126. package/out/parser/tuple.js +119 -87
  127. package/out/parser/tuple.js.map +1 -1
  128. package/out/scope.d.ts +43 -120
  129. package/out/scope.js +39 -209
  130. package/out/scope.js.map +1 -1
  131. package/out/type.d.ts +43 -64
  132. package/out/type.js +30 -131
  133. package/out/type.js.map +1 -1
  134. package/package.json +7 -3
  135. package/parser/definition.ts +77 -93
  136. package/parser/generic.ts +38 -40
  137. package/parser/objectLiteral.ts +172 -136
  138. package/parser/semantic/bounds.ts +33 -32
  139. package/parser/semantic/divisor.ts +8 -10
  140. package/parser/semantic/infer.ts +141 -0
  141. package/parser/semantic/utils.ts +12 -23
  142. package/parser/semantic/validate.ts +81 -73
  143. package/parser/string/reduce/dynamic.ts +67 -55
  144. package/parser/string/reduce/shared.ts +1 -3
  145. package/parser/string/reduce/static.ts +67 -69
  146. package/parser/string/shift/operand/date.ts +15 -14
  147. package/parser/string/shift/operand/enclosed.ts +30 -25
  148. package/parser/string/shift/operand/genericArgs.ts +46 -45
  149. package/parser/string/shift/operand/operand.ts +32 -38
  150. package/parser/string/shift/operand/unenclosed.ts +107 -158
  151. package/parser/string/shift/operator/bounds.ts +118 -112
  152. package/parser/string/shift/operator/divisor.ts +14 -17
  153. package/parser/string/shift/operator/operator.ts +35 -46
  154. package/parser/string/shift/scanner.ts +51 -50
  155. package/parser/string/string.ts +30 -35
  156. package/parser/tuple.ts +375 -307
  157. package/scope.ts +170 -453
  158. package/type.ts +193 -274
  159. package/__tests__/astUtils.test.ts +0 -17
  160. package/__tests__/cyclic.test.ts +0 -144
  161. package/__tests__/jsdoc.test.ts +0 -64
  162. package/__tests__/morph.test.ts +0 -409
  163. package/__tests__/nodeDefinitions.test.ts +0 -190
  164. package/__tests__/typeMethods.test.ts +0 -69
  165. package/out/ark.d.ts.map +0 -1
  166. package/out/arkConfig.d.ts +0 -2
  167. package/out/arkConfig.d.ts.map +0 -1
  168. package/out/arkConfig.js +0 -10
  169. package/out/arkConfig.js.map +0 -1
  170. package/out/main.d.ts.map +0 -1
  171. package/out/match.d.ts.map +0 -1
  172. package/out/parser/definition.d.ts.map +0 -1
  173. package/out/parser/generic.d.ts.map +0 -1
  174. package/out/parser/objectLiteral.d.ts.map +0 -1
  175. package/out/parser/semantic/bounds.d.ts.map +0 -1
  176. package/out/parser/semantic/divisor.d.ts.map +0 -1
  177. package/out/parser/semantic/intersections.d.ts +0 -14
  178. package/out/parser/semantic/intersections.d.ts.map +0 -1
  179. package/out/parser/semantic/intersections.js +0 -2
  180. package/out/parser/semantic/intersections.js.map +0 -1
  181. package/out/parser/semantic/semantic.d.ts +0 -33
  182. package/out/parser/semantic/semantic.d.ts.map +0 -1
  183. package/out/parser/semantic/semantic.js +0 -2
  184. package/out/parser/semantic/semantic.js.map +0 -1
  185. package/out/parser/semantic/utils.d.ts.map +0 -1
  186. package/out/parser/semantic/validate.d.ts.map +0 -1
  187. package/out/parser/shared.d.ts +0 -54
  188. package/out/parser/shared.d.ts.map +0 -1
  189. package/out/parser/shared.js +0 -47
  190. package/out/parser/shared.js.map +0 -1
  191. package/out/parser/string/reduce/dynamic.d.ts.map +0 -1
  192. package/out/parser/string/reduce/shared.d.ts.map +0 -1
  193. package/out/parser/string/reduce/static.d.ts.map +0 -1
  194. package/out/parser/string/shift/operand/date.d.ts.map +0 -1
  195. package/out/parser/string/shift/operand/enclosed.d.ts.map +0 -1
  196. package/out/parser/string/shift/operand/genericArgs.d.ts.map +0 -1
  197. package/out/parser/string/shift/operand/operand.d.ts.map +0 -1
  198. package/out/parser/string/shift/operand/unenclosed.d.ts.map +0 -1
  199. package/out/parser/string/shift/operator/bounds.d.ts.map +0 -1
  200. package/out/parser/string/shift/operator/divisor.d.ts.map +0 -1
  201. package/out/parser/string/shift/operator/operator.d.ts.map +0 -1
  202. package/out/parser/string/shift/scanner.d.ts.map +0 -1
  203. package/out/parser/string/string.d.ts.map +0 -1
  204. package/out/parser/tuple.d.ts.map +0 -1
  205. package/out/scope.d.ts.map +0 -1
  206. package/out/test.d.ts +0 -2
  207. package/out/test.d.ts.map +0 -1
  208. package/out/test.js +0 -7
  209. package/out/test.js.map +0 -1
  210. package/out/tsconfig.build.tsbuildinfo +0 -1
  211. package/out/type.d.ts.map +0 -1
  212. package/out/util.d.ts +0 -19
  213. package/out/util.d.ts.map +0 -1
  214. package/out/util.js +0 -7
  215. package/out/util.js.map +0 -1
  216. package/parser/semantic/intersections.ts +0 -46
  217. package/parser/semantic/semantic.ts +0 -144
  218. package/parser/shared.ts +0 -152
  219. package/util.ts +0 -36
package/out/match.d.ts CHANGED
@@ -1,48 +1,71 @@
1
- import type { Fn, isDisjoint, replaceKey, returnOf, unionToTuple, valueOf } from "@arktype/util";
1
+ import type { Narrowed, distillOut, inferIntersection } from "@arktype/schema";
2
+ import type { ErrorMessage, isDisjoint, numericStringKeyOf, override, propValueOf, unionToTuple } from "@arktype/util";
2
3
  import type { Scope } from "./scope.js";
3
- import { type inferTypeRoot, type validateTypeRoot } from "./type.js";
4
- type MatchContext = {
5
- inConstraint: unknown;
6
- outConstraint: unknown;
7
- thens: readonly Fn[];
4
+ import type { inferTypeRoot, validateTypeRoot } from "./type.js";
5
+ type MatchParserContext = {
6
+ thens: readonly ((In: unknown) => unknown)[];
8
7
  $: unknown;
9
- };
10
- type validateCases<cases, ctx extends MatchContext> = {
11
- [k in keyof cases | keyof ctx["$"] | "default"]?: k extends "default" ? (In: ctx["inConstraint"]) => ctx["outConstraint"] : k extends validateTypeRoot<k, ctx["$"]> ? (In: ctx["inConstraint"] & inferTypeRoot<k, ctx["$"]>) => ctx["outConstraint"] : validateTypeRoot<k, ctx["$"]>;
12
- };
13
- type errorCases<cases, ctx extends MatchContext> = {
14
- [k in keyof cases]?: k extends "default" ? (In: ctx["inConstraint"]) => ctx["outConstraint"] : k extends validateTypeRoot<k, ctx["$"]> ? (In: ctx["inConstraint"] & inferTypeRoot<k, ctx["$"]>) => ctx["outConstraint"] : validateTypeRoot<k, ctx["$"]>;
15
- } & {
16
- [k in Exclude<keyof ctx["$"], keyof cases>]?: (In: ctx["inConstraint"] & ctx["$"][k]) => ctx["outConstraint"];
17
- } & {
18
- default?: (In: ctx["inConstraint"]) => ctx["outConstraint"];
19
- };
20
- export type CaseMatchParser<ctx extends MatchContext> = {
21
- <cases>(def: cases extends validateCases<cases, ctx> ? cases : errorCases<cases, ctx>): ChainableMatchParser<replaceKey<ctx, "thens", [...ctx["thens"], ...unionToTuple<valueOf<cases>>]>>;
8
+ exhaustiveOver: unknown;
22
9
  };
23
10
  export type MatchParser<$> = CaseMatchParser<{
24
- inConstraint: unknown;
25
- outConstraint: unknown;
26
11
  thens: [];
12
+ exhaustiveOver: unknown;
27
13
  $: $;
28
14
  }> & {
29
- <In = unknown, Out = unknown>(): ChainableMatchParser<{
30
- inConstraint: In;
31
- outConstraint: Out;
15
+ (): ChainableMatchParser<{
16
+ thens: [];
17
+ exhaustiveOver: unknown;
18
+ $: $;
19
+ }>;
20
+ only: <inputs>() => ChainableMatchParser<{
32
21
  thens: [];
22
+ exhaustiveOver: inputs;
33
23
  $: $;
34
24
  }>;
35
25
  };
36
- export type WhenMatchParser<ctx extends MatchContext> = <def, then extends (In: ctx["inConstraint"] & inferTypeRoot<def, ctx["$"]>) => ctx["outConstraint"]>(when: validateTypeRoot<def, ctx["$"]>, then: then) => ChainableMatchParser<replaceKey<ctx, "thens", [...ctx["thens"], then]>>;
37
- export type MatchInvocation<ctx extends MatchContext> = <data extends ctx["inConstraint"]>(data: data) => {
38
- [i in Extract<keyof ctx["thens"], `${number}`>]: ctx["thens"][i] extends Fn<[
39
- infer In
40
- ], infer Out> ? isDisjoint<data, In> extends true ? never : Out : returnOf<ctx["thens"][i]>;
41
- }[Extract<keyof ctx["thens"], `${number}`>];
42
- export type ChainableMatchParser<ctx extends MatchContext> = MatchInvocation<ctx> & {
26
+ type matcherInputs<ctx extends MatchParserContext> = Parameters<ctx["thens"][number]>[0];
27
+ type getHandledBranches<ctx extends MatchParserContext> = Exclude<matcherInputs<ctx>, Narrowed>;
28
+ type getUnhandledBranches<ctx extends MatchParserContext> = distillOut<Exclude<ctx["exhaustiveOver"], getHandledBranches<ctx>>>;
29
+ type addBranches<ctx extends MatchParserContext, branches extends unknown[]> = override<ctx, {
30
+ thens: [...ctx["thens"], ...branches];
31
+ }>;
32
+ type validateWhenDefinition<def, ctx extends MatchParserContext> = def extends validateTypeRoot<def, ctx["$"]> ? inferMatchBranch<def, ctx> extends getHandledBranches<ctx> ? ErrorMessage<"This branch is redundant and will never be reached"> : def : validateTypeRoot<def, ctx["$"]>;
33
+ type inferMatchBranch<def, ctx extends MatchParserContext> = distillOut<inferIntersection<getUnhandledBranches<ctx>, inferTypeRoot<def, ctx["$"]>>>;
34
+ export type ChainableMatchParser<ctx extends MatchParserContext> = {
35
+ when: <def, ret>(when: validateWhenDefinition<def, ctx>, then: (In: inferMatchBranch<def, ctx>) => ret) => ChainableMatchParser<addBranches<ctx, [(In: inferMatchBranch<def, ctx>) => ret]>>;
43
36
  cases: CaseMatchParser<ctx>;
44
- when: WhenMatchParser<ctx>;
37
+ orThrow: () => finalizeMatchParser<addBranches<ctx, [(In: getHandledBranches<ctx>) => never]>>;
38
+ default: MatchParserDefaultInvocation<ctx>;
39
+ finalize: (this: getUnhandledBranches<ctx> extends never ? ChainableMatchParser<ctx> : ErrorMessage<"Cannot manually finalize a non-exhaustive matcher: consider adding a `.default` case, using one of the `.orX` methods, or using `match.only<T>`">) => finalizeMatchParser<ctx>;
40
+ };
41
+ type MatchParserDefaultInvocation<ctx extends MatchParserContext> = {
42
+ <f extends (In: getUnhandledBranches<ctx>) => unknown>(f: f): finalizeWithDefault<ctx, ReturnType<f>>;
43
+ <const value>(value: value): finalizeWithDefault<ctx, value>;
44
+ };
45
+ type validateCases<cases, ctx extends MatchParserContext> = {
46
+ [def in keyof cases | keyof ctx["$"] | "default"]?: def extends "default" ? (In: getUnhandledBranches<ctx>) => unknown : def extends validateWhenDefinition<def, ctx> ? (In: inferMatchBranch<def, ctx>) => unknown : validateWhenDefinition<def, ctx>;
47
+ };
48
+ type errorCases<cases, ctx extends MatchParserContext> = {
49
+ [def in keyof cases]?: def extends "default" ? (In: getUnhandledBranches<ctx>) => unknown : def extends validateWhenDefinition<def, ctx> ? (In: inferMatchBranch<def, ctx>) => unknown : validateWhenDefinition<def, ctx>;
50
+ } & {
51
+ [k in Exclude<keyof ctx["$"], keyof cases>]?: (In: distillOut<inferIntersection<getUnhandledBranches<ctx>, ctx["$"][k]>>) => unknown;
52
+ } & {
53
+ default?: (In: getUnhandledBranches<ctx>) => unknown;
54
+ };
55
+ export type CaseMatchParser<ctx extends MatchParserContext> = <cases>(def: cases extends validateCases<cases, ctx> ? cases : errorCases<cases, ctx>) => cases extends {
56
+ default: (...args: never[]) => infer defaultReturn;
57
+ } ? finalizeWithDefault<addBranches<ctx, unionToTuple<cases[Exclude<keyof cases, "default">]>>, defaultReturn> : ChainableMatchParser<addBranches<ctx, unionToTuple<propValueOf<cases>>>>;
58
+ type finalizeWithDefault<ctx extends MatchParserContext, defaultReturn> = finalizeMatchParser<addBranches<ctx, [(_: getUnhandledBranches<ctx>) => defaultReturn]>>;
59
+ type finalizeMatchParser<ctx extends MatchParserContext> = MatchInvocation<{
60
+ thens: ctx["thens"];
61
+ initialInputs: ctx["exhaustiveOver"];
62
+ }>;
63
+ type MatchInvocationContext = {
64
+ thens: readonly ((...args: never[]) => unknown)[];
65
+ initialInputs: unknown;
45
66
  };
46
- export declare const createMatchParser: <$>(scope: Scope) => MatchParser<$>;
67
+ export type MatchInvocation<ctx extends MatchInvocationContext> = <data extends ctx["initialInputs"]>(data: data) => {
68
+ [i in numericStringKeyOf<ctx["thens"]>]: isDisjoint<data, Parameters<ctx["thens"][i]>[0]> extends true ? never : ReturnType<ctx["thens"][i]>;
69
+ }[numericStringKeyOf<ctx["thens"]>];
70
+ export declare const createMatchParser: <$>($: Scope) => MatchParser<$>;
47
71
  export {};
48
- //# sourceMappingURL=match.d.ts.map
package/out/match.js CHANGED
@@ -1,18 +1,52 @@
1
- import { Type } from "./type.js";
2
- export const createMatchParser = (scope) => {
3
- const parser = (cases) => {
4
- const caseArray = Object.entries(cases).map(([def, morph]) => ({
5
- when: new Type(def, scope).allows,
6
- then: morph
7
- }));
8
- return (data) => {
9
- for (const c of caseArray) {
10
- if (c.when(data)) {
11
- return c.then(data, {});
12
- }
13
- }
14
- };
15
- };
16
- return parser;
1
+ export const createMatchParser = ($) => {
2
+ return (() => { }).bind($);
3
+ // const matchParser = (isRestricted: boolean) => {
4
+ // const handledCases: { when: RawSchema; then: Morph }[] = []
5
+ // let defaultCase: ((x: unknown) => unknown) | null = null
6
+ // const parser = {
7
+ // when: (when: unknown, then: Morph) => {
8
+ // handledCases.push({ when: $.parseRoot(when, {}), then })
9
+ // return parser
10
+ // },
11
+ // finalize: () => {
12
+ // // TODO: exhaustiveness checking
13
+ // const branches = handledCases.flatMap(({ when, then }) => {
14
+ // if (when.kind === "union") {
15
+ // return when.branches.map((branch) => ({
16
+ // from: branch,
17
+ // morph: then
18
+ // }))
19
+ // }
20
+ // if (when.kind === "morph") {
21
+ // return [{ from: when, morph: [when.morph, then] }]
22
+ // }
23
+ // return [{ from: when, morph: then }]
24
+ // })
25
+ // if (defaultCase) {
26
+ // branches.push({ from: keywordNodes.unknown, morph: defaultCase })
27
+ // }
28
+ // const matchers = $.node("union", {
29
+ // branches,
30
+ // ordered: true
31
+ // })
32
+ // return matchers.assert
33
+ // },
34
+ // orThrow: () => {
35
+ // // implicitly finalize, we don't need to do anything else because we throw either way
36
+ // return parser.finalize()
37
+ // },
38
+ // default: (x: unknown) => {
39
+ // if (x instanceof Function) {
40
+ // defaultCase = x as never
41
+ // } else {
42
+ // defaultCase = () => x
43
+ // }
44
+ // return parser.finalize()
45
+ // }
46
+ // }
47
+ // return parser
48
+ // }
49
+ // return Object.assign(() => matchParser(false), {
50
+ // only: () => matchParser(true)
51
+ // }) as never
17
52
  };
18
- //# sourceMappingURL=match.js.map
package/out/match.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"match.js","sourceRoot":"","sources":["../match.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,IAAI,EAA6C,MAAM,WAAW,CAAA;AA0F3E,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAI,KAAY,EAAkB,EAAE;IACpE,MAAM,MAAM,GAAG,CAAC,KAA4B,EAAE,EAAE;QAC/C,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;YAC9D,IAAI,EAAE,IAAI,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,MAAM;YACjC,IAAI,EAAE,KAAK;SACX,CAAC,CAAC,CAAA;QACH,OAAO,CAAC,IAAa,EAAE,EAAE;YACxB,KAAK,MAAM,CAAC,IAAI,SAAS,EAAE,CAAC;gBAC3B,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;oBAClB,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,EAAW,CAAC,CAAA;gBACjC,CAAC;YACF,CAAC;QACF,CAAC,CAAA;IACF,CAAC,CAAA;IACD,OAAO,MAAe,CAAA;AACvB,CAAC,CAAA"}
1
+ {"version":3,"file":"match.js","sourceRoot":"","sources":["../match.ts"],"names":[],"mappings":"AA8JA,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAI,CAAQ,EAAkB,EAAE;IAChE,OAAO,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAU,CAAA;IAClC,mDAAmD;IACnD,+DAA+D;IAC/D,4DAA4D;IAE5D,oBAAoB;IACpB,4CAA4C;IAC5C,8DAA8D;IAE9D,mBAAmB;IACnB,OAAO;IAEP,sBAAsB;IACtB,sCAAsC;IACtC,iEAAiE;IACjE,mCAAmC;IACnC,+CAA+C;IAC/C,sBAAsB;IACtB,oBAAoB;IACpB,WAAW;IACX,QAAQ;IACR,mCAAmC;IACnC,0DAA0D;IAC1D,QAAQ;IACR,2CAA2C;IAC3C,QAAQ;IACR,wBAAwB;IACxB,wEAAwE;IACxE,OAAO;IACP,wCAAwC;IACxC,gBAAgB;IAChB,oBAAoB;IACpB,QAAQ;IACR,4BAA4B;IAC5B,OAAO;IAEP,qBAAqB;IACrB,2FAA2F;IAC3F,8BAA8B;IAC9B,OAAO;IAEP,+BAA+B;IAC/B,kCAAkC;IAClC,+BAA+B;IAC/B,cAAc;IACd,4BAA4B;IAC5B,OAAO;IAEP,8BAA8B;IAC9B,MAAM;IACN,KAAK;IAEL,iBAAiB;IACjB,IAAI;IAEJ,mDAAmD;IACnD,iCAAiC;IACjC,cAAc;AACf,CAAC,CAAA"}
@@ -0,0 +1,10 @@
1
+ import type { PreparsedNodeResolution, arkKind } from "@arktype/schema";
2
+ import { DynamicBase, type isAnyOrNever } from "@arktype/util";
3
+ import type { Type } from "./type.js";
4
+ type exportScope<$> = {
5
+ [k in keyof $]: $[k] extends PreparsedNodeResolution ? isAnyOrNever<$[k]> extends true ? Type<$[k], $> : $[k] : Type<$[k], $>;
6
+ };
7
+ export declare class Module<$ = any> extends DynamicBase<exportScope<$>> {
8
+ readonly [arkKind]: "module";
9
+ }
10
+ export {};
package/out/module.js ADDED
@@ -0,0 +1,3 @@
1
+ import { DynamicBase } from "@arktype/util";
2
+ export class Module extends DynamicBase {
3
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.js","sourceRoot":"","sources":["../module.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAqB,MAAM,eAAe,CAAA;AAW9D,MAAM,OAAO,MAAgB,SAAQ,WAA2B;CAE/D"}
@@ -1,24 +1,23 @@
1
- import { type TypeNode } from "@arktype/schema";
2
- import { type defined, type equals, type ErrorMessage, type evaluate, type isAny, type isUnknown, type objectKindOrDomainOf, type optionalKeyOf, type Primitive, type requiredKeyOf } from "@arktype/util";
1
+ import { type RawSchema, type string } from "@arktype/schema";
2
+ import { type ErrorMessage, type Primitive, type array, type defined, type equals, type isAny, type isUnknown, type objectKindOrDomainOf, type optionalKeyOf, type requiredKeyOf, type show } from "@arktype/util";
3
3
  import type { type } from "../ark.js";
4
4
  import type { ParseContext } from "../scope.js";
5
5
  import { type inferObjectLiteral, type validateObjectLiteral } from "./objectLiteral.js";
6
6
  import type { validateString } from "./semantic/validate.js";
7
7
  import type { BaseCompletions, inferString } from "./string/string.js";
8
- import { type inferTuple, type TupleExpression, type validateTuple } from "./tuple.js";
9
- export declare const parseObject: (def: object, ctx: ParseContext) => TypeNode;
10
- export type inferDefinition<def, $, args> = isAny<def> extends true ? never : def extends type.cast<infer t> | ThunkCast<infer t> ? t : def extends string ? inferString<def, $, args> : def extends readonly unknown[] ? inferTuple<def, $, args> : def extends RegExp ? string : def extends object ? inferObjectLiteral<def, $, args> : never;
11
- export type validateDefinition<def, $, args> = null extends undefined ? ErrorMessage<`'strict' or 'strictNullChecks' must be set to true in your tsconfig's 'compilerOptions'`> : [def] extends [Terminal] ? unknown extends def ? never : def : def extends string ? validateString<def, $, args> : def extends readonly unknown[] ? validateTuple<def, $, args> : def extends BadDefinitionType ? writeBadDefinitionTypeMessage<objectKindOrDomainOf<def>> : isUnknown<def> extends true ? // this allows the initial list of autocompletions to be populated when a user writes "type()",
12
- BaseCompletions<$, args> | {} : validateObjectLiteral<def, $, args>;
8
+ import { type TupleExpression, type inferTuple, type validateTuple } from "./tuple.js";
9
+ export declare const parseObject: (def: object, ctx: ParseContext) => RawSchema;
10
+ export type inferDefinition<def, $, args> = isAny<def> extends true ? never : def extends type.cast<infer t> | 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;
11
+ export type validateDefinition<def, $, args> = null extends undefined ? ErrorMessage<`'strict' or 'strictNullChecks' must be set to true in your tsconfig's 'compilerOptions'`> : [def] extends [Terminal] ? def : def extends string ? validateString<def, $, args> : def extends array ? validateTuple<def, $, args> : def extends BadDefinitionType ? writeBadDefinitionTypeMessage<objectKindOrDomainOf<def>> : isUnknown<def> extends true ? BaseCompletions<$, args> | {} : validateObjectLiteral<def, $, args>;
13
12
  export type validateDeclared<declared, def, $, args> = def extends validateDefinition<def, $, args> ? validateInference<def, declared, $, args> : validateDefinition<def, $, args>;
14
- type validateInference<def, declared, $, args> = def extends RegExp | type.cast<unknown> | ThunkCast | TupleExpression ? validateShallowInference<def, declared, $, args> : def extends readonly unknown[] ? declared extends readonly unknown[] ? {
13
+ type validateInference<def, declared, $, args> = def extends RegExp | type.cast<unknown> | ThunkCast | TupleExpression ? validateShallowInference<def, declared, $, args> : def extends array ? declared extends array ? {
15
14
  [i in keyof declared]: i extends keyof def ? validateInference<def[i], declared[i], $, args> : unknown;
16
- } : evaluate<declarationMismatch<def, declared, $, args>> : def extends object ? evaluate<{
15
+ } : show<declarationMismatch<def, declared, $, args>> : def extends object ? show<{
17
16
  [k in requiredKeyOf<declared>]: k extends keyof def ? validateInference<def[k], declared[k], $, args> : unknown;
18
17
  } & {
19
- [k in optionalKeyOf<declared> & string as `${k}?`]: `${k}?` extends keyof def ? validateInference<def[`${k}?`], defined<declared[k]>, $, args> : unknown;
18
+ [k in optionalKeyOf<declared> & string as `${k}?`]: `${k}?` extends (keyof def) ? validateInference<def[`${k}?`], defined<declared[k]>, $, args> : unknown;
20
19
  }> : validateShallowInference<def, declared, $, args>;
21
- type validateShallowInference<def, declared, $, args> = equals<inferDefinition<def, $, args>, declared> extends true ? def : evaluate<declarationMismatch<def, declared, $, args>>;
20
+ type validateShallowInference<def, declared, $, args> = equals<inferDefinition<def, $, args>, declared> extends true ? def : show<declarationMismatch<def, declared, $, args>>;
22
21
  type declarationMismatch<def, declared, $, args> = {
23
22
  declared: declared;
24
23
  inferred: inferDefinition<def, $, args>;
@@ -26,7 +25,6 @@ type declarationMismatch<def, declared, $, args> = {
26
25
  type Terminal = RegExp | type.cast<unknown> | ((...args: never[]) => unknown);
27
26
  export type ThunkCast<t = unknown> = () => type.cast<t>;
28
27
  type BadDefinitionType = Exclude<Primitive, string>;
29
- export declare const writeBadDefinitionTypeMessage: <actual extends string>(actual: actual) => `Type definitions must be strings or objects (was ${actual})`;
28
+ export declare const writeBadDefinitionTypeMessage: <actual extends string>(actual: actual) => writeBadDefinitionTypeMessage<actual>;
30
29
  type writeBadDefinitionTypeMessage<actual extends string> = `Type definitions must be strings or objects (was ${actual})`;
31
30
  export {};
32
- //# sourceMappingURL=definition.d.ts.map
@@ -1,32 +1,29 @@
1
- import { isNode, schema } from "@arktype/schema";
1
+ import { hasArkKind } from "@arktype/schema";
2
2
  import { isThunk, objectKindOf, printable, throwParseError } from "@arktype/util";
3
- import { Type } from "../type.js";
4
3
  import { parseObjectLiteral } from "./objectLiteral.js";
5
4
  import { parseTuple } from "./tuple.js";
6
5
  export const parseObject = (def, ctx) => {
7
6
  const objectKind = objectKindOf(def);
8
7
  switch (objectKind) {
9
8
  case undefined:
10
- if (def instanceof Type) {
11
- return def.root;
12
- }
13
- if (isNode(def) && def.isType()) {
9
+ if (hasArkKind(def, "schema"))
14
10
  return def;
15
- }
16
11
  return parseObjectLiteral(def, ctx);
17
12
  case "Array":
18
13
  return parseTuple(def, ctx);
19
14
  case "RegExp":
20
- return schema({ basis: "string", pattern: def });
21
- case "Function":
15
+ return ctx.$.node("intersection", {
16
+ domain: "string",
17
+ regex: def
18
+ }, { prereduced: true });
19
+ case "Function": {
22
20
  const resolvedDef = isThunk(def) ? def() : def;
23
- if (resolvedDef instanceof Type) {
24
- return resolvedDef.root;
25
- }
21
+ if (hasArkKind(resolvedDef, "schema"))
22
+ return resolvedDef;
26
23
  return throwParseError(writeBadDefinitionTypeMessage("Function"));
24
+ }
27
25
  default:
28
26
  return throwParseError(writeBadDefinitionTypeMessage(objectKind ?? printable(def)));
29
27
  }
30
28
  };
31
29
  export const writeBadDefinitionTypeMessage = (actual) => `Type definitions must be strings or objects (was ${actual})`;
32
- //# sourceMappingURL=definition.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"definition.js","sourceRoot":"","sources":["../../parser/definition.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAiB,MAAM,iBAAiB,CAAA;AAC/D,OAAO,EACN,OAAO,EACP,YAAY,EACZ,SAAS,EACT,eAAe,EAaf,MAAM,eAAe,CAAA;AAGtB,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AACjC,OAAO,EACN,kBAAkB,EAGlB,MAAM,oBAAoB,CAAA;AAG3B,OAAO,EACN,UAAU,EAIV,MAAM,YAAY,CAAA;AAEnB,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,GAAW,EAAE,GAAiB,EAAY,EAAE;IACvE,MAAM,UAAU,GAAG,YAAY,CAAC,GAAG,CAAC,CAAA;IACpC,QAAQ,UAAU,EAAE,CAAC;QACpB,KAAK,SAAS;YACb,IAAI,GAAG,YAAY,IAAI,EAAE,CAAC;gBACzB,OAAO,GAAG,CAAC,IAAI,CAAA;YAChB,CAAC;YACD,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,EAAE,EAAE,CAAC;gBACjC,OAAO,GAAG,CAAA;YACX,CAAC;YACD,OAAO,kBAAkB,CAAC,GAAW,EAAE,GAAG,CAAC,CAAA;QAC5C,KAAK,OAAO;YACX,OAAO,UAAU,CAAC,GAAW,EAAE,GAAG,CAAC,CAAA;QACpC,KAAK,QAAQ;YACZ,OAAO,MAAM,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAa,EAAE,CAAC,CAAA;QAC3D,KAAK,UAAU;YACd,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAA;YAC9C,IAAI,WAAW,YAAY,IAAI,EAAE,CAAC;gBACjC,OAAO,WAAW,CAAC,IAAI,CAAA;YACxB,CAAC;YACD,OAAO,eAAe,CAAC,6BAA6B,CAAC,UAAU,CAAC,CAAC,CAAA;QAClE;YACC,OAAO,eAAe,CACrB,6BAA6B,CAAC,UAAU,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAC3D,CAAA;IACH,CAAC;AACF,CAAC,CAAA;AA0FD,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAC5C,MAAc,EAC0B,EAAE,CAC1C,oDAAoD,MAAM,GAAG,CAAA"}
1
+ {"version":3,"file":"definition.js","sourceRoot":"","sources":["../../parser/definition.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,UAAU,EAAe,MAAM,iBAAiB,CAAA;AACzE,OAAO,EAQN,OAAO,EAEP,YAAY,EAGZ,SAAS,EAGT,eAAe,EACf,MAAM,eAAe,CAAA;AAGtB,OAAO,EAEN,kBAAkB,EAElB,MAAM,oBAAoB,CAAA;AAG3B,OAAO,EAGN,UAAU,EAEV,MAAM,YAAY,CAAA;AAEnB,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,GAAW,EAAE,GAAiB,EAAa,EAAE;IACxE,MAAM,UAAU,GAAG,YAAY,CAAC,GAAG,CAAC,CAAA;IACpC,QAAQ,UAAU,EAAE,CAAC;QACpB,KAAK,SAAS;YACb,IAAI,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC;gBAAE,OAAO,GAAG,CAAA;YACzC,OAAO,kBAAkB,CAAC,GAAW,EAAE,GAAG,CAAC,CAAA;QAC5C,KAAK,OAAO;YACX,OAAO,UAAU,CAAC,GAAY,EAAE,GAAG,CAAC,CAAA;QACrC,KAAK,QAAQ;YACZ,OAAO,GAAG,CAAC,CAAC,CAAC,IAAI,CAChB,cAAc,EACd;gBACC,MAAM,EAAE,QAAQ;gBAChB,KAAK,EAAE,GAAa;aACpB,EACD,EAAE,UAAU,EAAE,IAAI,EAAE,CACpB,CAAA;QACF,KAAK,UAAU,CAAC,CAAC,CAAC;YACjB,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAA;YAC9C,IAAI,UAAU,CAAC,WAAW,EAAE,QAAQ,CAAC;gBAAE,OAAO,WAAW,CAAA;YACzD,OAAO,eAAe,CAAC,6BAA6B,CAAC,UAAU,CAAC,CAAC,CAAA;QAClE,CAAC;QACD;YACC,OAAO,eAAe,CACrB,6BAA6B,CAAC,UAAU,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAC3D,CAAA;IACH,CAAC;AACF,CAAC,CAAA;AA0ED,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAC5C,MAAc,EAC0B,EAAE,CAC1C,oDAAoD,MAAM,GAAG,CAAA"}
@@ -1,18 +1,16 @@
1
- import { type nominal } from "@arktype/util";
1
+ import { type keyError } from "@arktype/util";
2
2
  import { writeUnexpectedCharacterMessage } from "./string/shift/operator/operator.js";
3
3
  import { Scanner } from "./string/shift/scanner.js";
4
4
  export type GenericDeclaration<name extends string = string, params extends string = string> = `${name}<${params}>`;
5
5
  export type GenericParamsParseError<message extends string = string> = [
6
- nominal<message, "InvalidGenericParameters">
6
+ keyError<message>
7
7
  ];
8
8
  export declare const parseGenericParams: (def: string) => string[];
9
- export type parseGenericParams<def extends string> = parseParamsRecurse<def, "", [
10
- ]> extends infer result extends string[] ? "" extends result[number] ? GenericParamsParseError<emptyGenericParameterMessage> : result : never;
9
+ export type parseGenericParams<def extends string> = _parseParams<def, "", []> extends infer result extends string[] ? "" extends result[number] ? GenericParamsParseError<emptyGenericParameterMessage> : result : never;
11
10
  export declare const emptyGenericParameterMessage = "An empty string is not a valid generic parameter name";
12
11
  export type emptyGenericParameterMessage = typeof emptyGenericParameterMessage;
13
- type parseParamsRecurse<unscanned extends string, param extends string, result extends string[]> = unscanned extends `${infer lookahead}${infer nextUnscanned}` ? lookahead extends "," ? parseParamsRecurse<nextUnscanned, "", [...result, param]> : lookahead extends Scanner.WhiteSpaceToken ? param extends "" ? parseParamsRecurse<Scanner.skipWhitespace<nextUnscanned>, "", result> : Scanner.skipWhitespace<nextUnscanned> extends `${infer nextNonWhitespace}${infer rest}` ? nextNonWhitespace extends "," ? parseParamsRecurse<rest, "", [...result, param]> : GenericParamsParseError<writeUnexpectedCharacterMessage<nextNonWhitespace, ",">> : [
12
+ type _parseParams<unscanned extends string, param extends string, result extends string[]> = unscanned extends `${infer lookahead}${infer nextUnscanned}` ? lookahead extends "," ? _parseParams<nextUnscanned, "", [...result, param]> : lookahead extends Scanner.WhiteSpaceToken ? param extends "" ? _parseParams<Scanner.skipWhitespace<nextUnscanned>, "", result> : Scanner.skipWhitespace<nextUnscanned> extends (`${infer nextNonWhitespace}${infer rest}`) ? nextNonWhitespace extends "," ? _parseParams<rest, "", [...result, param]> : GenericParamsParseError<writeUnexpectedCharacterMessage<nextNonWhitespace, ",">> : [
14
13
  ...result,
15
14
  param
16
- ] : parseParamsRecurse<nextUnscanned, `${param}${lookahead}`, result> : param extends "" ? result : [...result, param];
15
+ ] : _parseParams<nextUnscanned, `${param}${lookahead}`, result> : param extends "" ? result : [...result, param];
17
16
  export {};
18
- //# sourceMappingURL=generic.d.ts.map
@@ -1,19 +1,15 @@
1
1
  import { throwParseError } from "@arktype/util";
2
2
  import { writeUnexpectedCharacterMessage } from "./string/shift/operator/operator.js";
3
3
  import { Scanner } from "./string/shift/scanner.js";
4
- export const parseGenericParams = (def) => parseGenericParamsRecurse(new Scanner(def));
5
- export const emptyGenericParameterMessage = `An empty string is not a valid generic parameter name`;
6
- const parseGenericParamsRecurse = (scanner) => {
4
+ export const parseGenericParams = (def) => _parseGenericParams(new Scanner(def));
5
+ export const emptyGenericParameterMessage = "An empty string is not a valid generic parameter name";
6
+ const _parseGenericParams = (scanner) => {
7
7
  const param = scanner.shiftUntilNextTerminator();
8
- if (param === "") {
8
+ if (param === "")
9
9
  throwParseError(emptyGenericParameterMessage);
10
- }
11
10
  scanner.shiftUntilNonWhitespace();
12
11
  const nextNonWhitespace = scanner.shift();
13
- return nextNonWhitespace === ""
14
- ? [param]
15
- : nextNonWhitespace === ","
16
- ? [param, ...parseGenericParamsRecurse(scanner)]
17
- : throwParseError(writeUnexpectedCharacterMessage(nextNonWhitespace, ","));
12
+ return (nextNonWhitespace === "" ? [param]
13
+ : nextNonWhitespace === "," ? [param, ..._parseGenericParams(scanner)]
14
+ : throwParseError(writeUnexpectedCharacterMessage(nextNonWhitespace, ",")));
18
15
  };
19
- //# sourceMappingURL=generic.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generic.js","sourceRoot":"","sources":["../../parser/generic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAgB,MAAM,eAAe,CAAA;AAC7D,OAAO,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAA;AACrF,OAAO,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAA;AAYnD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,GAAW,EAAE,EAAE,CACjD,yBAAyB,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAY5C,MAAM,CAAC,MAAM,4BAA4B,GAAG,uDAAuD,CAAA;AAInG,MAAM,yBAAyB,GAAG,CAAC,OAAgB,EAAY,EAAE;IAChE,MAAM,KAAK,GAAG,OAAO,CAAC,wBAAwB,EAAE,CAAA;IAChD,IAAI,KAAK,KAAK,EAAE,EAAE,CAAC;QAClB,eAAe,CAAC,4BAA4B,CAAC,CAAA;IAC9C,CAAC;IACD,OAAO,CAAC,uBAAuB,EAAE,CAAA;IACjC,MAAM,iBAAiB,GAAG,OAAO,CAAC,KAAK,EAAE,CAAA;IACzC,OAAO,iBAAiB,KAAK,EAAE;QAC9B,CAAC,CAAC,CAAC,KAAK,CAAC;QACT,CAAC,CAAC,iBAAiB,KAAK,GAAG;YAC3B,CAAC,CAAC,CAAC,KAAK,EAAE,GAAG,yBAAyB,CAAC,OAAO,CAAC,CAAC;YAChD,CAAC,CAAC,eAAe,CAAC,+BAA+B,CAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC,CAAA;AAC5E,CAAC,CAAA"}
1
+ {"version":3,"file":"generic.js","sourceRoot":"","sources":["../../parser/generic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,eAAe,EAAE,MAAM,eAAe,CAAA;AAC9D,OAAO,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAA;AACrF,OAAO,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAA;AAYnD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,GAAW,EAAY,EAAE,CAC3D,mBAAmB,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAStC,MAAM,CAAC,MAAM,4BAA4B,GACxC,uDAAuD,CAAA;AAIxD,MAAM,mBAAmB,GAAG,CAAC,OAAgB,EAAY,EAAE;IAC1D,MAAM,KAAK,GAAG,OAAO,CAAC,wBAAwB,EAAE,CAAA;IAChD,IAAI,KAAK,KAAK,EAAE;QAAE,eAAe,CAAC,4BAA4B,CAAC,CAAA;IAE/D,OAAO,CAAC,uBAAuB,EAAE,CAAA;IACjC,MAAM,iBAAiB,GAAG,OAAO,CAAC,KAAK,EAAE,CAAA;IACzC,OAAO,CACN,iBAAiB,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;QAClC,CAAC,CAAC,iBAAiB,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;YACtE,CAAC,CAAC,eAAe,CAAC,+BAA+B,CAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC,CAC1E,CAAA;AACF,CAAC,CAAA"}
@@ -1,33 +1,64 @@
1
- import { type TypeNode } from "@arktype/schema";
2
- import { type Dict, type ErrorMessage, type evaluate, type merge } from "@arktype/util";
1
+ import { type RawSchema, type writeInvalidPropertyKeyMessage } from "@arktype/schema";
2
+ import { type Dict, type ErrorMessage, type Key, type merge, 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 { astToString } from "./semantic/utils.js";
6
6
  import type { validateString } from "./semantic/validate.js";
7
- import { parseEntry, type EntryParseResult, type IndexedKey, type OptionalValue, type validateObjectValue } from "./shared.js";
8
- export declare const parseObjectLiteral: (def: Dict, ctx: ParseContext) => TypeNode;
7
+ import { Scanner } from "./string/shift/scanner.js";
8
+ export declare const parseObjectLiteral: (def: Dict, ctx: ParseContext) => RawSchema;
9
+ export declare const nonLeadingSpreadError = "Spread operator may only be used as the first key in an object";
9
10
  /**
10
11
  * Infers the contents of an object literal, ignoring a spread definition
11
12
  * You probably want to use {@link inferObjectLiteral} instead.
12
13
  */
13
14
  type inferObjectLiteralInner<def extends object, $, args> = {
14
- -readonly [k in keyof def as nonOptionalKeyFrom<k, def[k], $, args>]: inferDefinition<def[k], $, args>;
15
+ -readonly [k in keyof def as nonOptionalKeyFrom<k, $, args>]: inferDefinition<def[k], $, args>;
15
16
  } & {
16
- -readonly [k in keyof def as optionalKeyFrom<k, def[k]>]?: inferDefinition<def[k] extends OptionalValue<infer inner> ? inner : def[k], $, args>;
17
+ -readonly [k in keyof def as optionalKeyFrom<k>]?: inferDefinition<def[k], $, args>;
17
18
  };
18
- export type inferObjectLiteral<def extends object, $, args> = evaluate<"..." extends keyof def ? merge<inferDefinition<def["..."], $, args>, inferObjectLiteralInner<def, $, args>> : inferObjectLiteralInner<def, $, args>>;
19
+ export type inferObjectLiteral<def extends object, $, args> = show<"..." extends keyof def ? merge<inferDefinition<def["..."], $, args>, inferObjectLiteralInner<def, $, args>> : inferObjectLiteralInner<def, $, args>>;
19
20
  export type validateObjectLiteral<def, $, args> = {
20
- [k in keyof def]: k extends IndexedKey<infer indexDef> ? validateString<indexDef, $, args> extends ErrorMessage<infer message> ? indexParseError<message> : inferDefinition<indexDef, $, args> extends PropertyKey ? validateDefinition<def[k], $, args> : indexParseError<writeInvalidPropertyKeyMessage<indexDef>> : k extends "..." ? inferDefinition<def[k], $, args> extends object ? validateDefinition<def[k], $, args> : indexParseError<writeInvalidSpreadTypeMessage<astToString<def[k]>>> : validateObjectValue<def[k], $, args>;
21
+ [k in keyof def]: k extends IndexKey<infer indexDef> ? validateString<indexDef, $, args> extends ErrorMessage<infer message> ? indexParseError<message> : inferDefinition<indexDef, $, args> extends PropertyKey ? validateDefinition<def[k], $, args> : indexParseError<writeInvalidPropertyKeyMessage<indexDef>> : k extends "..." ? inferDefinition<def[k], $, args> extends object ? validateDefinition<def[k], $, args> : indexParseError<writeInvalidSpreadTypeMessage<astToString<def[k]>>> : validateDefinition<def[k], $, args>;
21
22
  };
22
- type nonOptionalKeyFrom<k extends PropertyKey, valueDef, $, args> = parseEntry<k, valueDef> extends infer result extends EntryParseResult ? result["kind"] extends "required" ? result["innerKey"] : result["kind"] extends "indexed" ? inferDefinition<result["innerKey"], $, args> & PropertyKey : never : never;
23
- type optionalKeyFrom<k extends PropertyKey, valueDef> = parseEntry<k, valueDef> extends infer result extends EntryParseResult<"optional"> ? result["innerKey"] : never;
23
+ type nonOptionalKeyFrom<k, $, args> = parseKey<k> extends PreparsedKey<"required", infer inner> ? inner : parseKey<k> extends PreparsedKey<"index", infer inner> ? inferDefinition<inner, $, args> & Key : never;
24
+ type optionalKeyFrom<k> = parseKey<k> extends PreparsedKey<"optional", infer inner> ? inner : never;
25
+ type PreparsedKey<kind extends ParsedKeyKind = ParsedKeyKind, inner extends Key = Key> = {
26
+ kind: kind;
27
+ inner: inner;
28
+ };
29
+ declare namespace PreparsedKey {
30
+ type from<t extends PreparsedKey> = t;
31
+ }
32
+ type ParsedKeyKind = "required" | "optional" | "index" | "spread";
33
+ export type IndexKey<def extends string = string> = `[${def}]`;
34
+ type PreparsedEntry = PreparsedKey & {
35
+ value: unknown;
36
+ };
37
+ export declare const parseEntry: (entry: readonly [Key, unknown]) => PreparsedEntry;
38
+ declare const parseKey: (key: Key) => PreparsedKey<ParsedKeyKind, Key>;
39
+ type parseKey<k> = k extends `${infer inner}?` ? inner extends `${infer baseName}${Scanner.EscapeToken}` ? PreparsedKey.from<{
40
+ kind: "required";
41
+ inner: `${baseName}?`;
42
+ }> : PreparsedKey.from<{
43
+ kind: "optional";
44
+ inner: inner;
45
+ }> : k extends "..." ? PreparsedKey.from<{
46
+ kind: "spread";
47
+ inner: "...";
48
+ }> : k extends `${Scanner.EscapeToken}...` ? PreparsedKey.from<{
49
+ kind: "required";
50
+ inner: "...";
51
+ }> : k extends IndexKey<infer def> ? PreparsedKey.from<{
52
+ kind: "index";
53
+ inner: def;
54
+ }> : PreparsedKey.from<{
55
+ kind: "required";
56
+ inner: k extends (`${Scanner.EscapeToken}${infer escapedIndexKey extends IndexKey}`) ? escapedIndexKey : k extends Key ? k : `${k & number}`;
57
+ }>;
24
58
  declare const indexParseSymbol: unique symbol;
25
59
  export type indexParseError<message extends string = string> = {
26
60
  [indexParseSymbol]: message;
27
61
  };
28
- export declare const writeInvalidPropertyKeyMessage: <indexDef extends string>(indexDef: indexDef) => `Indexed key definition '${indexDef}' must be a string, number or symbol`;
29
- type writeInvalidPropertyKeyMessage<indexDef extends string> = `Indexed key definition '${indexDef}' must be a string, number or symbol`;
30
- export declare const writeInvalidSpreadTypeMessage: <def extends string>(def: def) => `Spread operand must resolve to an object literal type (was ${def})`;
62
+ export declare const writeInvalidSpreadTypeMessage: <def extends string>(def: def) => writeInvalidSpreadTypeMessage<def>;
31
63
  type writeInvalidSpreadTypeMessage<def extends string> = `Spread operand must resolve to an object literal type (was ${def})`;
32
64
  export {};
33
- //# sourceMappingURL=objectLiteral.d.ts.map
@@ -1,66 +1,75 @@
1
- import { keywords, schema } from "@arktype/schema";
2
- import { printable, throwParseError } from "@arktype/util";
3
- import { parseEntry } from "./shared.js";
4
- const stringAndSymbolicEntriesOf = (o) => [
5
- ...Object.entries(o),
6
- ...Object.getOwnPropertySymbols(o).map((k) => [k, o[k]])
7
- ];
1
+ import { tsKeywords } from "@arktype/schema";
2
+ import { printable, spliterate, stringAndSymbolicEntriesOf, throwParseError } from "@arktype/util";
3
+ import { Scanner } from "./string/shift/scanner.js";
8
4
  export const parseObjectLiteral = (def, ctx) => {
9
- const required = [];
10
- const optional = [];
5
+ const propNodes = [];
6
+ const indexNodes = [];
11
7
  // We only allow a spread operator to be used as the first key in an object
12
8
  // because to match JS behavior any keys before the spread are overwritten
13
9
  // by the values in the target object, so there'd be no useful purpose in having it
14
10
  // anywhere except for the beginning.
15
- // Discussion in ArkType Discord:
16
- // https://discord.com/channels/957797212103016458/1103023445035462678/1182814502471860334
17
- let hasSeenFirstKey = false;
18
- const entries = stringAndSymbolicEntriesOf(def);
19
- for (const entry of entries) {
20
- const result = parseEntry(entry);
21
- if (result.kind === "spread") {
22
- if (hasSeenFirstKey) {
23
- return throwParseError("Spread operator may only be used as the first key in an object");
24
- }
25
- const spreadNode = ctx.scope.parse(result.innerValue, ctx);
26
- if (spreadNode.kind !== "intersection" ||
27
- !spreadNode.extends(keywords.object)) {
28
- return throwParseError(writeInvalidSpreadTypeMessage(printable(result.innerValue)));
29
- }
30
- // For each key on spreadNode, add it to our object.
31
- // We filter out keys from the spreadNode that will be defined later on this same object
32
- // because the currently parsed definition will overwrite them.
33
- const requiredEntriesFromSpread = (spreadNode.required ?? []).filter((e) => !entries.some(([k]) => k === e.key));
34
- const optionalEntriesFromSpread = (spreadNode.optional ?? []).filter((e) => !entries.some(([k]) => k === e.key));
35
- required.push(...requiredEntriesFromSpread);
36
- optional.push(...optionalEntriesFromSpread);
37
- continue;
11
+ const parsedEntries = stringAndSymbolicEntriesOf(def).map(parseEntry);
12
+ if (parsedEntries[0]?.kind === "spread") {
13
+ // remove the spread entry so we can iterate over the remaining entries
14
+ // expecting non-spread entries
15
+ const spreadEntry = parsedEntries.shift();
16
+ const spreadNode = ctx.$.parse(spreadEntry.value, ctx);
17
+ if (!spreadNode.hasKind("intersection") ||
18
+ !spreadNode.extends(tsKeywords.object)) {
19
+ return throwParseError(writeInvalidSpreadTypeMessage(printable(spreadEntry.value)));
38
20
  }
39
- ctx.path.push(`${typeof result.innerKey === "symbol"
40
- ? `[${printable(result.innerKey)}]`
41
- : result.innerKey}`);
42
- const valueNode = ctx.scope.parse(result.innerValue, ctx);
43
- if (result.kind === "optional") {
44
- optional.push({
45
- key: result.innerKey,
46
- value: valueNode
47
- });
21
+ // TODO: move to props group merge in schema
22
+ // For each key on spreadNode, add it to our object.
23
+ // We filter out keys from the spreadNode that will be defined later on this same object
24
+ // because the currently parsed definition will overwrite them.
25
+ spreadNode.prop?.forEach(spreadRequired => !parsedEntries.some(({ inner: innerKey }) => innerKey === spreadRequired.key) && propNodes.push(spreadRequired));
26
+ }
27
+ for (const entry of parsedEntries) {
28
+ if (entry.kind === "spread")
29
+ return throwParseError(nonLeadingSpreadError);
30
+ if (entry.kind === "index") {
31
+ // handle key parsing first to match type behavior
32
+ const key = ctx.$.parse(entry.inner, ctx);
33
+ const value = ctx.$.parse(entry.value, ctx);
34
+ // extract enumerable named props from the index signature
35
+ const [enumerable, nonEnumerable] = spliterate(key.branches, k => k.hasKind("unit"));
36
+ if (enumerable.length) {
37
+ propNodes.push(...enumerable.map(k => ctx.$.node("prop", { key: k.unit, value })));
38
+ if (nonEnumerable.length)
39
+ indexNodes.push(ctx.$.node("index", { key: nonEnumerable, value }));
40
+ }
41
+ else
42
+ indexNodes.push(ctx.$.node("index", { key, value }));
48
43
  }
49
44
  else {
50
- required.push({
51
- key: result.innerKey,
52
- value: valueNode
45
+ const value = ctx.$.parse(entry.value, ctx);
46
+ propNodes.push({
47
+ key: entry.inner,
48
+ value,
49
+ optional: entry.kind === "optional"
53
50
  });
54
51
  }
55
- ctx.path.pop();
56
- hasSeenFirstKey ||= true;
57
52
  }
58
- return schema({
59
- basis: "object",
60
- required,
61
- optional
53
+ return ctx.$.schema({
54
+ domain: "object",
55
+ prop: propNodes,
56
+ index: indexNodes
62
57
  });
63
58
  };
64
- export const writeInvalidPropertyKeyMessage = (indexDef) => `Indexed key definition '${indexDef}' must be a string, number or symbol`;
59
+ export const nonLeadingSpreadError = "Spread operator may only be used as the first key in an object";
60
+ export const parseEntry = (entry) => Object.assign(parseKey(entry[0]), { value: entry[1] });
61
+ const parseKey = (key) => typeof key === "symbol" ? { inner: key, kind: "required" }
62
+ : key.at(-1) === "?" ?
63
+ key.at(-2) === Scanner.escapeToken ?
64
+ { inner: `${key.slice(0, -2)}?`, kind: "required" }
65
+ : {
66
+ inner: key.slice(0, -1),
67
+ kind: "optional"
68
+ }
69
+ : key[0] === "[" && key.at(-1) === "]" ?
70
+ { inner: key.slice(1, -1), kind: "index" }
71
+ : key[0] === Scanner.escapeToken && key[1] === "[" && key.at(-1) === "]" ?
72
+ { inner: key.slice(1), kind: "required" }
73
+ : key === "..." ? { inner: "...", kind: "spread" }
74
+ : { inner: key === "\\..." ? "..." : key, kind: "required" };
65
75
  export const writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`;
66
- //# sourceMappingURL=objectLiteral.js.map