arktype 2.0.0-dev.1 → 2.0.0-dev.2

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 (47) hide show
  1. package/__tests__/array.test.ts +42 -4
  2. package/__tests__/config.test.ts +75 -166
  3. package/__tests__/declared.test.ts +5 -4
  4. package/__tests__/keyTraversal.test.ts +71 -70
  5. package/__tests__/match.bench.ts +31 -0
  6. package/__tests__/match.test.ts +216 -26
  7. package/__tests__/narrow.test.ts +3 -3
  8. package/__tests__/objectLiteral.test.ts +19 -18
  9. package/match.ts +206 -79
  10. package/out/match.d.ts +60 -31
  11. package/out/match.d.ts.map +1 -1
  12. package/out/match.js +52 -10
  13. package/out/match.js.map +1 -1
  14. package/out/parser/definition.d.ts +6 -4
  15. package/out/parser/definition.d.ts.map +1 -1
  16. package/out/parser/definition.js.map +1 -1
  17. package/out/parser/objectLiteral.js +2 -2
  18. package/out/parser/objectLiteral.js.map +1 -1
  19. package/out/parser/semantic/semantic.d.ts +3 -3
  20. package/out/parser/semantic/semantic.d.ts.map +1 -1
  21. package/out/parser/shared.d.ts +4 -2
  22. package/out/parser/shared.d.ts.map +1 -1
  23. package/out/parser/shared.js +8 -0
  24. package/out/parser/shared.js.map +1 -1
  25. package/out/parser/string/reduce/static.d.ts +1 -1
  26. package/out/parser/string/reduce/static.d.ts.map +1 -1
  27. package/out/parser/tuple.d.ts +2 -2
  28. package/out/parser/tuple.d.ts.map +1 -1
  29. package/out/parser/tuple.js +14 -15
  30. package/out/parser/tuple.js.map +1 -1
  31. package/out/scope.d.ts +6 -11
  32. package/out/scope.d.ts.map +1 -1
  33. package/out/scope.js +0 -21
  34. package/out/scope.js.map +1 -1
  35. package/out/type.d.ts +5 -8
  36. package/out/type.d.ts.map +1 -1
  37. package/out/type.js +12 -8
  38. package/out/type.js.map +1 -1
  39. package/package.json +3 -3
  40. package/parser/definition.ts +7 -7
  41. package/parser/objectLiteral.ts +6 -6
  42. package/parser/semantic/semantic.ts +3 -4
  43. package/parser/shared.ts +19 -4
  44. package/parser/string/reduce/static.ts +2 -2
  45. package/parser/tuple.ts +18 -17
  46. package/scope.ts +5 -31
  47. package/type.ts +16 -14
@@ -1,34 +1,224 @@
1
- // import { match } from "arktype"
1
+ import { attest } from "@arktype/attest"
2
+ import { match } from "arktype"
3
+ import { scope } from "../ark.js"
2
4
 
3
- // const matcher = match({
4
- // boolean: (b) => !b,
5
- // semver: (s) => s.length
6
- // }).when({ condition: "true" }, (data) => {
7
- // return data.condition
8
- // })
5
+ describe("match", () => {
6
+ it("properly infers types of inputs/outputs", () => {
7
+ const matcher = match({ string: (s) => s, number: (n) => n })
8
+ .when("boolean", (b) => b)
9
+ .orThrow()
9
10
 
10
- // const greeting = match({
11
- // "integer<12": () => "Good morning",
12
- // "integer<18": () => "Good afternoon",
13
- // default: () => "Good evening"
14
- // })
11
+ // properly infers the type of the output based on the input
12
+ attest<string>(matcher("abc")).equals("abc")
13
+ attest<number>(matcher(4)).equals(4)
14
+ attest<boolean>(matcher(true)).equals(true)
15
15
 
16
- // const result = greeting(5)
16
+ // and properly handles unions in the input type
17
+ attest<string | number>(matcher(0 as string | number))
18
+ })
17
19
 
18
- // const base = matcher({} as unknown) //=>?
20
+ it("`.when` errors on redundant cases", () => {
21
+ const matcher = match().when("string", (s) => s)
19
22
 
20
- // const oneResult = matcher({} as object) //=>?
23
+ // @ts-expect-error
24
+ attest(() => matcher.when("string", (s) => s)).throwsAndHasTypeError(
25
+ "This branch is redundant and will never be reached" // TODO: rewrite error message
26
+ )
27
+ })
21
28
 
22
- // const twoResults = matcher({} as boolean | string) //=>?
29
+ it("errors on cases redundant to a previous `cases` block", () => {
30
+ const matcher = match({ string: (s) => s })
23
31
 
24
- // const validMatcher = match({
25
- // // ^?
26
- // number: (data) => data,
27
- // "string|unknown[]": (data) => data.length
28
- // })
32
+ // @ts-expect-error
33
+ attest(() => matcher.cases({ string: (s) => s })).throwsAndHasTypeError(
34
+ "This branch is redundant and will never be reached"
35
+ )
36
+ })
29
37
 
30
- // const invalidMatcher = match({
31
- // // ^?
32
- // "string|numbr": (data) => data,
33
- // "1<boolean<5": (data) => data
34
- // })
38
+ describe("constraint handling", () => {
39
+ it("properly considers constrained types as different from their base", () => {
40
+ const matcher = match
41
+ .only<number>()
42
+ .when("number>2", (n) => {
43
+ attest<number>(n)
44
+ return n
45
+ })
46
+ .when("number", (n) => n)
47
+ .finalize()
48
+
49
+ // for assertions
50
+ matcher(5)
51
+ })
52
+ })
53
+
54
+ describe('"finalizations"', () => {
55
+ it(".orThrow()", () => {
56
+ const matcher = match()
57
+ .when("string", (s) => s)
58
+ .orThrow()
59
+
60
+ // properly returns the `never` type and throws given a guaranteed-to-be-invalid input
61
+ attest<never>(matcher(4))
62
+
63
+ attest(() => matcher(4)).throws("TODO: what's the error message?") // TODO
64
+ })
65
+
66
+ describe(".default", () => {
67
+ it("chained, given a callback", () => {
68
+ const matcher = match()
69
+ .when("string", (s) => s)
70
+ .default((_) => 0)
71
+
72
+ attest<string>(matcher("abc")).equals("abc")
73
+ attest<number>(matcher(4)).equals(0)
74
+
75
+ attest<string | number>(matcher(0 as unknown))
76
+ })
77
+
78
+ it("chained, given a value", () => {
79
+ const matcher = match()
80
+ .when("string", (s) => s)
81
+ .default(0)
82
+
83
+ attest<string>(matcher("abc")).equals("abc")
84
+ attest<number>(matcher(4)).equals(0)
85
+
86
+ attest<string | number>(matcher(0 as unknown))
87
+ })
88
+
89
+ it("in `cases`, given a callback", () => {
90
+ const matcher = match({ string: (s) => s, default: (_) => 0 })
91
+
92
+ attest<string>(matcher("abc")).equals("abc")
93
+ attest<number>(matcher(4)).equals(0)
94
+
95
+ attest<string | number>(matcher(0 as unknown))
96
+ })
97
+ })
98
+
99
+ it("errors when attempting to `.finalize()` a non-exhaustive matcher", () => {
100
+ const matcher = match().when("string", (s) => s)
101
+
102
+ // @ts-expect-error
103
+ attest(() => matcher.finalize()).throwsAndHasTypeError(
104
+ "Cannot manually finalize a non-exhaustive matcher: consider adding a `.default` case, using one of the `.orX` methods, or using `match.only<T>`" // TODO: rewrite message
105
+ )
106
+ })
107
+
108
+ it("considers `unknown` exhaustive", () => {
109
+ const matcher = match()
110
+ .when("unknown", (x) => x)
111
+ .finalize()
112
+
113
+ attest(matcher(4)).equals(4)
114
+ })
115
+ })
116
+
117
+ describe(".only<T>", () => {
118
+ it("does not accept invalid inputs at a type-level", () => {
119
+ const matcher = match
120
+ .only<string | number>()
121
+ .when("string", (s) => s)
122
+ .when("number", (n) => n)
123
+ .finalize()
124
+
125
+ // @ts-expect-error
126
+ attest(() => matcher(true)).throwsAndHasTypeError(
127
+ "Argument of type 'true' is not assignable to parameter of type 'string | number'"
128
+ ) // TODO: what's the runtime error?
129
+ })
130
+
131
+ it("errors when attempting to `.finalize()` a non-exhaustive matcher", () => {
132
+ const matcher = match.only<string | number>().when("string", (s) => s)
133
+
134
+ // @ts-expect-error
135
+ attest(() => matcher.finalize()).throwsAndHasTypeError(
136
+ "Cannot manually finalize a non-exhaustive matcher: consider adding a `.default` case, using one of the `.orX` methods, or handling the cases explicitly" // TODO: rewrite message. at runtime can we even show a counterexample (serialize the cases not handled)?
137
+ )
138
+ })
139
+
140
+ it("allows finalizing exhaustive matchers", (_) => {
141
+ const matcher = match
142
+ .only<string | number>()
143
+ .when("string", (s) => s)
144
+ .when("number", (n) => n)
145
+ .finalize()
146
+
147
+ attest<string>(matcher("abc")).equals("abc")
148
+ attest<number>(matcher(4)).equals(4)
149
+
150
+ attest<string | number>(matcher(0 as string | number))
151
+ })
152
+
153
+ it("infers the parameter to chained .default as the remaining cases", () => {
154
+ const matcher = match
155
+ .only<string | number | boolean>()
156
+ .when("string", (s) => s)
157
+ .default((n) => {
158
+ attest<number | boolean>(n)
159
+ return n
160
+ })
161
+
162
+ // for assertions
163
+ matcher(4)
164
+ })
165
+
166
+ it("infers the parameter to in-cases .default", () => {
167
+ const matcher = match.only<string | number | boolean>().cases({
168
+ string: (s) => s,
169
+ default: (n) => {
170
+ // TS doesn't understand sequentiality in cases, so it's inferred as the in-type
171
+ attest<string | number | boolean>(n)
172
+ return n
173
+ }
174
+ })
175
+
176
+ // for assertions
177
+ matcher(4)
178
+ })
179
+
180
+ it("returns `never` on only the specific cases handled by `.orThrow`", () => {
181
+ const matcher = match
182
+ .only<string | number>()
183
+ .when("string", (s) => s)
184
+ .orThrow()
185
+
186
+ attest<never>(matcher(4))
187
+ })
188
+ })
189
+
190
+ it("within scope", () => {
191
+ const threeSixtyNoScope = scope({ three: "3", sixty: "60", no: "'no'" })
192
+
193
+ const matcher = threeSixtyNoScope
194
+ .match({
195
+ three: (three) => {
196
+ attest<3>(three)
197
+ return 3
198
+ }
199
+ })
200
+ .when("sixty", (sixty) => {
201
+ attest<60>(sixty)
202
+ return 60
203
+ })
204
+ .orThrow()
205
+
206
+ // for assertions
207
+ matcher(3)
208
+ matcher(60)
209
+ })
210
+
211
+ it("properly propagates errors from invalid type definitions in `when`", () => {
212
+ // @ts-expect-error
213
+ attest(() => match().when("strong", (s) => s)).type.errors(
214
+ "'strong' is unresolvable"
215
+ )
216
+ })
217
+
218
+ it("properly propagates errors from invalid type definitions in `cases`", () => {
219
+ // @ts-expect-error
220
+ attest(() => match({ strong: (s) => s })).type.errors(
221
+ "'strong' is unresolvable"
222
+ )
223
+ })
224
+ })
@@ -1,5 +1,5 @@
1
1
  import { attest } from "@arktype/attest"
2
- import type { Out } from "@arktype/schema"
2
+ import type { Out, is } from "@arktype/schema"
3
3
  import type { equals } from "@arktype/util"
4
4
  import { type, type Type } from "arktype"
5
5
 
@@ -52,7 +52,7 @@ describe("narrow", () => {
52
52
  // })
53
53
  it("functional predicate", () => {
54
54
  const one = type(["number", ":", (n): n is 1 => n === 1])
55
- attest<Type<1>>(one)
55
+ attest<1>(one.infer)
56
56
  })
57
57
  it("functional parameter inference", () => {
58
58
  type Expected = number | boolean[]
@@ -88,7 +88,7 @@ describe("narrow", () => {
88
88
  const t = type("string")
89
89
  .morph((s) => s.length)
90
90
  .narrow((n): n is 5 => n === 5)
91
- attest<Type<(In: string) => Out<5>>>(t)
91
+ attest<Type<(In: string) => Out<is<5, { anonymousPredicate: true }>>>>(t)
92
92
  attest(t.json).snap({ domain: "string" })
93
93
  })
94
94
  it("expression", () => {
@@ -1,6 +1,5 @@
1
1
  import { attest } from "@arktype/attest"
2
- import { registry } from "@arktype/schema"
3
- import { printable } from "@arktype/util"
2
+ import { printable, reference } from "@arktype/util"
4
3
  import { scope, type } from "arktype"
5
4
  import {
6
5
  writeInvalidPropertyKeyMessage,
@@ -36,7 +35,7 @@ describe("object literal", () => {
36
35
  })
37
36
  it("symbol key", () => {
38
37
  const s = Symbol()
39
- const name = registry.register(s)
38
+ const name = reference(s)
40
39
  const t = type({
41
40
  [s]: "string"
42
41
  })
@@ -48,7 +47,7 @@ describe("object literal", () => {
48
47
  })
49
48
  it("optional symbol", () => {
50
49
  const s = Symbol()
51
- const name = registry.register(s)
50
+ const name = reference(s)
52
51
  const t = type({
53
52
  [s]: "number?"
54
53
  })
@@ -269,12 +268,13 @@ describe("object literal", () => {
269
268
  attest(abc.json).equals(type({ ...a, ...b, ...c }).json)
270
269
  attest(abc.json).equals(type([[a, "&", b], "&", c]).json)
271
270
  })
272
- it("traverse optional", () => {
273
- const o = type({ "a?": "string" }).configure({ keys: "strict" })
274
- attest(o({ a: "a" }).out).snap({ a: "a" })
275
- attest(o({}).out).snap({})
276
- attest(o({ a: 1 }).errors?.summary).snap("a must be a string (was number)")
277
- })
271
+ // TODO: reenable
272
+ // it("traverse optional", () => {
273
+ // const o = type({ "a?": "string" }).configure({ keys: "strict" })
274
+ // attest(o({ a: "a" }).out).snap({ a: "a" })
275
+ // attest(o({}).out).snap({})
276
+ // attest(o({ a: 1 }).errors?.summary).snap("a must be a string (was number)")
277
+ // })
278
278
  it("intersection", () => {
279
279
  const t = type({ a: "number" }).and({ b: "boolean" })
280
280
  // Should be simplified from {a: number} & {b: boolean} to {a: number, b: boolean}
@@ -289,12 +289,13 @@ describe("object literal", () => {
289
289
  const o = type({ "\\[string]": "string" })
290
290
  attest<{ "[string]": string }>(o.infer)
291
291
  })
292
- it("multiple bad strict", () => {
293
- const t = type({ a: "string", b: "boolean" }).configure({
294
- keys: "strict"
295
- })
296
- attest(t({ a: 1, b: 2 }).errors?.summary).snap(
297
- "a must be a string (was number)\nb must be boolean (was number)"
298
- )
299
- })
292
+ // TODO: reenable
293
+ // it("multiple bad strict", () => {
294
+ // const t = type({ a: "string", b: "boolean" }).configure({
295
+ // keys: "strict"
296
+ // })
297
+ // attest(t({ a: 1, b: 2 }).errors?.summary).snap(
298
+ // "a must be a string (was number)\nb must be boolean (was number)"
299
+ // )
300
+ // })
300
301
  })
package/match.ts CHANGED
@@ -1,116 +1,243 @@
1
- import type { Morph } from "@arktype/schema"
2
1
  import type {
3
- Fn,
2
+ AnonymousRefinementKey,
3
+ Morph,
4
+ distill,
5
+ intersectConstrainables,
6
+ is
7
+ } from "@arktype/schema"
8
+ import type {
9
+ ErrorMessage,
10
+ UnknownUnion,
4
11
  isDisjoint,
12
+ numericStringKeyOf,
5
13
  replaceKey,
6
- returnOf,
7
14
  unionToTuple,
8
15
  valueOf
9
16
  } from "@arktype/util"
10
17
  import type { Scope } from "./scope.js"
11
18
  import { Type, type inferTypeRoot, type validateTypeRoot } from "./type.js"
12
19
 
13
- type MatchContext = {
14
- inConstraint: unknown
15
- outConstraint: unknown
16
- thens: readonly Fn[]
20
+ type MatchParserContext = {
21
+ thens: readonly ((In: unknown) => unknown)[]
17
22
  $: unknown
23
+ exhaustiveOver: unknown
24
+ }
25
+
26
+ export type MatchParser<$> = CaseMatchParser<{
27
+ thens: []
28
+ // "match()" is the same as "match.only<unknown>()"
29
+ exhaustiveOver: unknown
30
+ $: $
31
+ }> & {
32
+ (): ChainableMatchParser<{
33
+ thens: []
34
+ // "match()" is the same as "match.only<unknown>()"
35
+ exhaustiveOver: unknown
36
+ $: $
37
+ }>
38
+ only: <inputs>() => ChainableMatchParser<{
39
+ thens: []
40
+ exhaustiveOver: inputs
41
+ $: $
42
+ }>
43
+ }
44
+
45
+ type matcherInputs<ctx extends MatchParserContext> = Parameters<
46
+ ctx["thens"][number]
47
+ >[0]
48
+
49
+ type AnonymouslyRefined = {
50
+ [k in AnonymousRefinementKey]: { [_ in k]: true }
51
+ }[AnonymousRefinementKey]
52
+
53
+ type getHandledBranches<ctx extends MatchParserContext> = Exclude<
54
+ matcherInputs<ctx>,
55
+ is<unknown, AnonymouslyRefined>
56
+ >
57
+ type getUnhandledBranches<ctx extends MatchParserContext> = Exclude<
58
+ unknown extends ctx["exhaustiveOver"] ? UnknownUnion : ctx["exhaustiveOver"],
59
+ getHandledBranches<ctx>
60
+ >
61
+ type addBranches<
62
+ ctx extends MatchParserContext,
63
+ branches extends unknown[]
64
+ > = replaceKey<ctx, "thens", [...ctx["thens"], ...branches]>
65
+
66
+ type validateWhenDefinition<
67
+ def,
68
+ ctx extends MatchParserContext
69
+ > = def extends validateTypeRoot<def, ctx["$"]>
70
+ ? inferMatchBranch<def, ctx> extends getHandledBranches<ctx>
71
+ ? ErrorMessage<"This branch is redundant and will never be reached">
72
+ : def
73
+ : validateTypeRoot<def, ctx["$"]>
74
+
75
+ // infer the types handled by a match branch, which is identical to `inferTypeRoot` while properly
76
+ // excluding cases that are already handled by other branches
77
+ type inferMatchBranch<
78
+ def,
79
+ ctx extends MatchParserContext
80
+ > = intersectConstrainables<
81
+ getUnhandledBranches<ctx>,
82
+ inferTypeRoot<def, ctx["$"]>
83
+ >
84
+
85
+ export type ChainableMatchParser<ctx extends MatchParserContext> = {
86
+ // chainable methods
87
+ when: <def, ret>(
88
+ when: validateWhenDefinition<def, ctx>,
89
+ then: (In: distill<inferMatchBranch<def, ctx>>) => ret
90
+ ) => ChainableMatchParser<
91
+ addBranches<ctx, [(In: inferMatchBranch<def, ctx>) => ret]>
92
+ >
93
+ cases: CaseMatchParser<ctx>
94
+
95
+ // finalizing methods
96
+ orThrow: () => finalizeMatchParser<
97
+ addBranches<ctx, [(In: getHandledBranches<ctx>) => never]>
98
+ >
99
+ default: MatchParserDefaultInvocation<ctx>
100
+ finalize: (
101
+ this: getUnhandledBranches<ctx> extends never
102
+ ? ChainableMatchParser<ctx>
103
+ : ErrorMessage<"Cannot manually finalize a non-exhaustive matcher: consider adding a `.default` case, using one of the `.orX` methods, or using `match.only<T>`">
104
+ ) => finalizeMatchParser<ctx>
18
105
  }
19
106
 
20
- type validateCases<cases, ctx extends MatchContext> = {
21
- [k in keyof cases | keyof ctx["$"] | "default"]?: k extends "default"
22
- ? (In: ctx["inConstraint"]) => ctx["outConstraint"]
23
- : k extends validateTypeRoot<k, ctx["$"]>
24
- ? (
25
- In: ctx["inConstraint"] & inferTypeRoot<k, ctx["$"]>
26
- ) => ctx["outConstraint"]
27
- : validateTypeRoot<k, ctx["$"]>
107
+ type MatchParserDefaultInvocation<ctx extends MatchParserContext> = {
108
+ <f extends (In: getUnhandledBranches<ctx>) => unknown>(
109
+ f: f
110
+ ): finalizeWithDefault<ctx, ReturnType<f>>
111
+ <const value>(value: value): finalizeWithDefault<ctx, value>
28
112
  }
29
113
 
30
- type errorCases<cases, ctx extends MatchContext> = {
31
- [k in keyof cases]?: k extends "default"
32
- ? (In: ctx["inConstraint"]) => ctx["outConstraint"]
33
- : k extends validateTypeRoot<k, ctx["$"]>
34
- ? (
35
- In: ctx["inConstraint"] & inferTypeRoot<k, ctx["$"]>
36
- ) => ctx["outConstraint"]
37
- : validateTypeRoot<k, ctx["$"]>
114
+ type validateCases<cases, ctx extends MatchParserContext> = {
115
+ [def in keyof cases | keyof ctx["$"] | "default"]?: def extends "default"
116
+ ? (In: distill<getUnhandledBranches<ctx>>) => unknown
117
+ : def extends validateWhenDefinition<def, ctx>
118
+ ? (In: distill<inferMatchBranch<def, ctx>>) => unknown
119
+ : validateWhenDefinition<def, ctx>
120
+ }
121
+
122
+ type errorCases<cases, ctx extends MatchParserContext> = {
123
+ [def in keyof cases]?: def extends "default"
124
+ ? (In: distill<getUnhandledBranches<ctx>>) => unknown
125
+ : def extends validateWhenDefinition<def, ctx>
126
+ ? (In: distill<inferMatchBranch<def, ctx>>) => unknown
127
+ : validateWhenDefinition<def, ctx>
38
128
  } & {
39
129
  [k in Exclude<keyof ctx["$"], keyof cases>]?: (
40
- In: ctx["inConstraint"] & ctx["$"][k]
41
- ) => ctx["outConstraint"]
130
+ In: distill<intersectConstrainables<getUnhandledBranches<ctx>, ctx["$"][k]>>
131
+ ) => unknown
42
132
  } & {
43
- default?: (In: ctx["inConstraint"]) => ctx["outConstraint"]
133
+ default?: (In: distill<getUnhandledBranches<ctx>>) => unknown
44
134
  }
45
135
 
46
- export type CaseMatchParser<ctx extends MatchContext> = {
136
+ export type CaseMatchParser<ctx extends MatchParserContext> = {
47
137
  <cases>(
48
138
  def: cases extends validateCases<cases, ctx>
49
139
  ? cases
50
140
  : errorCases<cases, ctx>
51
- ): ChainableMatchParser<
52
- replaceKey<ctx, "thens", [...ctx["thens"], ...unionToTuple<valueOf<cases>>]>
53
- >
141
+ ): cases extends { default: (...args: never[]) => infer defaultReturn }
142
+ ? finalizeWithDefault<
143
+ addBranches<ctx, unionToTuple<cases[Exclude<keyof cases, "default">]>>,
144
+ defaultReturn
145
+ >
146
+ : ChainableMatchParser<addBranches<ctx, unionToTuple<valueOf<cases>>>>
54
147
  }
55
148
 
56
- export type MatchParser<$> = CaseMatchParser<{
57
- inConstraint: unknown
58
- outConstraint: unknown
59
- thens: []
60
- $: $
61
- }> & {
62
- <In = unknown, Out = unknown>(): ChainableMatchParser<{
63
- inConstraint: In
64
- outConstraint: Out
65
- thens: []
66
- $: $
67
- }>
68
- }
149
+ type finalizeWithDefault<
150
+ ctx extends MatchParserContext,
151
+ defaultReturn
152
+ > = finalizeMatchParser<
153
+ addBranches<ctx, [(_: getUnhandledBranches<ctx>) => defaultReturn]>
154
+ >
69
155
 
70
- export type WhenMatchParser<ctx extends MatchContext> = <
71
- def,
72
- then extends (
73
- In: ctx["inConstraint"] & inferTypeRoot<def, ctx["$"]>
74
- ) => ctx["outConstraint"]
75
- >(
76
- when: validateTypeRoot<def, ctx["$"]>,
77
- then: then
78
- ) => ChainableMatchParser<replaceKey<ctx, "thens", [...ctx["thens"], then]>>
156
+ type finalizeMatchParser<ctx extends MatchParserContext> = MatchInvocation<{
157
+ thens: ctx["thens"]
158
+ initialInputs: ctx["exhaustiveOver"]
159
+ }>
79
160
 
80
- export type MatchInvocation<ctx extends MatchContext> = <
81
- data extends ctx["inConstraint"]
161
+ type MatchInvocationContext = {
162
+ thens: readonly ((...args: never[]) => unknown)[]
163
+ initialInputs: unknown
164
+ }
165
+
166
+ export type MatchInvocation<ctx extends MatchInvocationContext> = <
167
+ data extends ctx["initialInputs"]
82
168
  >(
83
169
  data: data
84
170
  ) => {
85
- [i in Extract<keyof ctx["thens"], `${number}`>]: ctx["thens"][i] extends Fn<
86
- [infer In],
87
- infer Out
88
- >
89
- ? isDisjoint<data, In> extends true
90
- ? never
91
- : Out
92
- : returnOf<ctx["thens"][i]>
93
- }[Extract<keyof ctx["thens"], `${number}`>]
94
-
95
- export type ChainableMatchParser<ctx extends MatchContext> =
96
- MatchInvocation<ctx> & {
97
- cases: CaseMatchParser<ctx>
98
- when: WhenMatchParser<ctx>
99
- }
171
+ [i in numericStringKeyOf<ctx["thens"]>]: isDisjoint<
172
+ data,
173
+ Parameters<ctx["thens"][i]>[0]
174
+ > extends true
175
+ ? never
176
+ : ReturnType<ctx["thens"][i]>
177
+ }[numericStringKeyOf<ctx["thens"]>]
100
178
 
101
179
  export const createMatchParser = <$>(scope: Scope): MatchParser<$> => {
102
- const parser = (cases: Record<string, Morph>) => {
103
- const caseArray = Object.entries(cases).map(([def, morph]) => ({
104
- when: new Type(def, scope).allows,
105
- then: morph
106
- }))
107
- return (data: unknown) => {
108
- for (const c of caseArray) {
109
- if (c.when(data)) {
110
- return c.then(data, {} as never)
180
+ const matchParser = (isRestricted: boolean) => {
181
+ const handledCases: { when: Type; then: Morph }[] = []
182
+ let defaultCase: ((x: unknown) => unknown) | null = null
183
+
184
+ const parser = {
185
+ when: (when: unknown, then: Morph) => {
186
+ handledCases.push({ when: new Type(when, scope), then })
187
+
188
+ return parser
189
+ },
190
+
191
+ finalize: () => {
192
+ // TODO: exhaustiveness checking
193
+ // const branches = handledCases.flatMap(({ when, then }) => {
194
+ // if (when.root.kind === "union") {
195
+ // return when.root.branches.map((branch) => ({
196
+ // in: branch,
197
+ // morph: then
198
+ // }))
199
+ // }
200
+ // if (when.root.kind === "morph") {
201
+ // return [{ in: when, morph: [when.root.morph, then] }]
202
+ // }
203
+ // return [{ in: when.root, morph: then }]
204
+ // })
205
+ // if (defaultCase) {
206
+ // branches.push({ in: new Type("unknown", scope), morph: defaultCase })
207
+ // }
208
+ // const matchers = schema.union({
209
+ // branches,
210
+ // ordered: true
211
+ // })
212
+ // return (data: unknown) => {
213
+ // const result = matchers.apply(data)
214
+ // if (result.errors) {
215
+ // throw result.errors
216
+ // }
217
+ // return result.out
218
+ // }
219
+ },
220
+
221
+ orThrow: () => {
222
+ // implicitly finalize, we don't need to do anything else because we throw either way
223
+ return parser.finalize()
224
+ },
225
+
226
+ default: (x: unknown) => {
227
+ if (x instanceof Function) {
228
+ defaultCase = x as never
229
+ } else {
230
+ defaultCase = () => x
111
231
  }
232
+
233
+ return parser.finalize()
112
234
  }
113
235
  }
236
+
237
+ return parser
114
238
  }
115
- return parser as never
239
+
240
+ return Object.assign(() => matchParser(false), {
241
+ only: () => matchParser(true)
242
+ }) as never
116
243
  }