arktype 2.0.4 → 2.1.1

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.
@@ -22,10 +22,14 @@ export const stringInteger = Scope.module({
22
22
  },
23
23
  declaredOut: intrinsic.integer
24
24
  })
25
+ }, {
26
+ name: "string.integer"
25
27
  });
26
28
  const base64 = Scope.module({
27
29
  root: regexStringNode(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/, "base64-encoded"),
28
30
  url: regexStringNode(/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}(?:==|%3D%3D)?|[A-Za-z0-9_-]{3}(?:=|%3D)?)?$/, "base64url-encoded")
31
+ }, {
32
+ name: "string.base64"
29
33
  });
30
34
  const preformattedCapitalize = regexStringNode(/^[A-Z].*$/, "capitalized");
31
35
  export const capitalize = Scope.module({
@@ -35,6 +39,8 @@ export const capitalize = Scope.module({
35
39
  declaredOut: preformattedCapitalize
36
40
  }),
37
41
  preformatted: preformattedCapitalize
42
+ }, {
43
+ name: "string.capitalize"
38
44
  });
39
45
  // https://github.com/validatorjs/validator.js/blob/master/src/lib/isLuhnNumber.js
40
46
  export const isLuhnValid = (creditCardInput) => {
@@ -139,6 +145,8 @@ const epoch = Scope.module({
139
145
  morphs: (s) => new Date(s),
140
146
  declaredOut: intrinsic.Date
141
147
  })
148
+ }, {
149
+ name: "string.date.epoch"
142
150
  });
143
151
  const isoRoot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection");
144
152
  const iso = Scope.module({
@@ -148,6 +156,8 @@ const iso = Scope.module({
148
156
  morphs: (s) => new Date(s),
149
157
  declaredOut: intrinsic.Date
150
158
  })
159
+ }, {
160
+ name: "string.date.iso"
151
161
  });
152
162
  export const stringDate = Scope.module({
153
163
  root: parsableDate,
@@ -164,6 +174,8 @@ export const stringDate = Scope.module({
164
174
  }),
165
175
  iso,
166
176
  epoch
177
+ }, {
178
+ name: "string.date"
167
179
  });
168
180
  const email = regexStringNode(
169
181
  // https://www.regular-expressions.info/email.html
@@ -188,6 +200,8 @@ export const ip = Scope.module({
188
200
  root: ["v4 | v6", "@", "an IP address"],
189
201
  v4: regexStringNode(ipv4Matcher, "an IPv4 address"),
190
202
  v6: regexStringNode(ipv6Matcher, "an IPv6 address")
203
+ }, {
204
+ name: "string.ip"
191
205
  });
192
206
  const jsonStringDescription = "a JSON string";
193
207
  export const writeJsonSyntaxErrorProblem = (error) => {
@@ -196,6 +210,7 @@ export const writeJsonSyntaxErrorProblem = (error) => {
196
210
  return `must be ${jsonStringDescription} (${error})`;
197
211
  };
198
212
  const jsonRoot = rootSchema({
213
+ meta: jsonStringDescription,
199
214
  domain: "string",
200
215
  predicate: {
201
216
  meta: jsonStringDescription,
@@ -236,10 +251,13 @@ const parseJson = (s, ctx) => {
236
251
  export const json = Scope.module({
237
252
  root: jsonRoot,
238
253
  parse: rootSchema({
254
+ meta: "safe JSON string parser",
239
255
  in: "string",
240
256
  morphs: parseJson,
241
- declaredOut: intrinsic.json
257
+ declaredOut: intrinsic.jsonObject
242
258
  })
259
+ }, {
260
+ name: "string.json"
243
261
  });
244
262
  const preformattedLower = regexStringNode(/^[a-z]*$/, "only lowercase letters");
245
263
  const lower = Scope.module({
@@ -249,6 +267,8 @@ const lower = Scope.module({
249
267
  declaredOut: preformattedLower
250
268
  }),
251
269
  preformatted: preformattedLower
270
+ }, {
271
+ name: "string.lower"
252
272
  });
253
273
  export const normalizedForms = ["NFC", "NFD", "NFKC", "NFKD"];
254
274
  const preformattedNodes = flatMorph(normalizedForms, (i, form) => [
@@ -270,18 +290,26 @@ const normalizeNodes = flatMorph(normalizedForms, (i, form) => [
270
290
  export const NFC = Scope.module({
271
291
  root: normalizeNodes.NFC,
272
292
  preformatted: preformattedNodes.NFC
293
+ }, {
294
+ name: "string.normalize.NFC"
273
295
  });
274
296
  export const NFD = Scope.module({
275
297
  root: normalizeNodes.NFD,
276
298
  preformatted: preformattedNodes.NFD
299
+ }, {
300
+ name: "string.normalize.NFD"
277
301
  });
278
302
  export const NFKC = Scope.module({
279
303
  root: normalizeNodes.NFKC,
280
304
  preformatted: preformattedNodes.NFKC
305
+ }, {
306
+ name: "string.normalize.NFKC"
281
307
  });
282
308
  export const NFKD = Scope.module({
283
309
  root: normalizeNodes.NFKD,
284
310
  preformatted: preformattedNodes.NFKD
311
+ }, {
312
+ name: "string.normalize.NFKD"
285
313
  });
286
314
  export const normalize = Scope.module({
287
315
  root: "NFC",
@@ -289,6 +317,8 @@ export const normalize = Scope.module({
289
317
  NFD,
290
318
  NFKC,
291
319
  NFKD
320
+ }, {
321
+ name: "string.normalize"
292
322
  });
293
323
  const numericRoot = regexStringNode(numericStringMatcher, "a well-formed numeric string");
294
324
  export const numeric = Scope.module({
@@ -298,6 +328,8 @@ export const numeric = Scope.module({
298
328
  morphs: (s) => Number.parseFloat(s),
299
329
  declaredOut: intrinsic.number
300
330
  })
331
+ }, {
332
+ name: "string.numeric"
301
333
  });
302
334
  // https://semver.org/
303
335
  const semverMatcher = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
@@ -312,6 +344,8 @@ const trim = Scope.module({
312
344
  declaredOut: preformattedTrim
313
345
  }),
314
346
  preformatted: preformattedTrim
347
+ }, {
348
+ name: "string.trim"
315
349
  });
316
350
  const preformattedUpper = regexStringNode(/^[A-Z]*$/, "only uppercase letters");
317
351
  const upper = Scope.module({
@@ -321,6 +355,8 @@ const upper = Scope.module({
321
355
  declaredOut: preformattedUpper
322
356
  }),
323
357
  preformatted: preformattedUpper
358
+ }, {
359
+ name: "string.upper"
324
360
  });
325
361
  const isParsableUrl = (s) => {
326
362
  if (URL.canParse)
@@ -356,6 +392,8 @@ export const url = Scope.module({
356
392
  },
357
393
  declaredOut: rootSchema(URL)
358
394
  })
395
+ }, {
396
+ name: "string.url"
359
397
  });
360
398
  // Based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isUUID.js
361
399
  export const uuid = Scope.module({
@@ -373,6 +411,8 @@ export const uuid = Scope.module({
373
411
  v6: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv6"),
374
412
  v7: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv7"),
375
413
  v8: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv8")
414
+ }, {
415
+ name: "string.uuid"
376
416
  });
377
417
  export const string = Scope.module({
378
418
  root: intrinsic.string,
@@ -395,4 +435,6 @@ export const string = Scope.module({
395
435
  upper,
396
436
  url,
397
437
  uuid
438
+ }, {
439
+ name: "string"
398
440
  });
@@ -18,18 +18,24 @@ export const arkTsKeywords = Scope.module({
18
18
  export const unknown = Scope.module({
19
19
  root: intrinsic.unknown,
20
20
  any: intrinsic.unknown
21
+ }, {
22
+ name: "unknown"
21
23
  });
22
24
  export const json = Scope.module({
23
- root: intrinsic.json,
25
+ root: intrinsic.jsonObject,
24
26
  stringify: node("morph", {
25
- in: intrinsic.json,
27
+ in: intrinsic.jsonObject,
26
28
  morphs: (data) => JSON.stringify(data),
27
29
  declaredOut: intrinsic.string
28
30
  })
31
+ }, {
32
+ name: "object.json"
29
33
  });
30
34
  export const object = Scope.module({
31
35
  root: intrinsic.object,
32
36
  json
37
+ }, {
38
+ name: "object"
33
39
  });
34
40
  class RecordHkt extends Hkt {
35
41
  description = "a generic type that instantiates an object from a single index signature and corresponding value type";
package/out/match.d.ts CHANGED
@@ -1,72 +1,119 @@
1
- import { type BaseRoot } from "@ark/schema";
2
- import { Callable, type array, type Fn, type isDisjoint, type numericStringKeyOf, type propValueOf, type unionToTuple } from "@ark/util";
3
- import type { distill, inferIntersection } from "./attributes.ts";
1
+ import { type ArkErrors, type BaseRoot, type Morph } from "@ark/schema";
2
+ import { Callable, type conform, type ErrorMessage, type ErrorType, type isDisjoint, type Key, type numericStringKeyOf, type propValueOf, type unionToTuple } from "@ark/util";
3
+ import type { distill, Out } from "./attributes.ts";
4
4
  import type { type } from "./keywords/keywords.ts";
5
+ import type { Inferred } from "./methods/base.ts";
6
+ import type { BaseCompletions } from "./parser/string.ts";
5
7
  import type { InternalScope } from "./scope.ts";
6
- type Thens = array<(In: any) => unknown>;
7
- type MatchParserContext = {
8
- thens: Thens;
8
+ type MatchParserContext<input = unknown> = {
9
+ cases: Morph[];
9
10
  $: unknown;
10
- input: unknown;
11
+ input: input;
12
+ key: PropertyKey | null;
11
13
  };
12
- export type MatchParser<$> = CaseMatchParser<{
13
- thens: [];
14
- $: $;
15
- input: unknown;
16
- }> & {
17
- (): ChainableMatchParser<{
18
- thens: [];
14
+ declare namespace ctx {
15
+ type from<ctx extends MatchParserContext> = ctx;
16
+ type init<$, input = unknown> = from<{
17
+ cases: [];
19
18
  $: $;
20
- input: unknown;
19
+ input: input;
20
+ key: null;
21
21
  }>;
22
- from<typedInput>(): ChainableMatchParser<{
23
- thens: [];
24
- $: $;
25
- input: typedInput;
22
+ type atKey<ctx extends MatchParserContext, key extends string> = from<{
23
+ cases: ctx["cases"];
24
+ $: ctx["$"];
25
+ input: ctx["input"];
26
+ key: key;
26
27
  }>;
27
- };
28
- type addBranches<ctx extends MatchParserContext, branches extends readonly unknown[]> = branches extends Thens ? {
28
+ }
29
+ export interface MatchParser<$> extends CaseMatchParser<ctx.init<$>> {
30
+ in<const def>(def: type.validate<def, $>): ChainableMatchParser<ctx.init<$, type.infer<def, $>>>;
31
+ in<const typedInput = never>(...args: [typedInput] extends [never] ? [
32
+ ErrorMessage<"from requires a definition or type argument (from('string') or from<string>())">
33
+ ] : []): ChainableMatchParser<ctx.init<$, typedInput>>;
34
+ in<const def>(def: type.validate<def, $>): ChainableMatchParser<ctx.init<$, type.infer<def, $>>>;
35
+ case: CaseParser<ctx.init<$>>;
36
+ at: AtParser<ctx.init<$>>;
37
+ }
38
+ type addCasesToContext<ctx extends MatchParserContext, cases extends unknown[]> = cases extends Morph[] ? ctx.from<{
29
39
  $: ctx["$"];
30
40
  input: ctx["input"];
31
- thens: [...ctx["thens"], ...branches];
32
- } : never;
33
- type inferMatchBranch<def, ctx extends MatchParserContext> = distill.Out<inferIntersection<ctx["input"], type.infer<def, ctx["$"]>>>;
34
- type ChainableMatchParser<ctx extends MatchParserContext> = {
35
- when: <def, ret>(when: type.validate<def, ctx["$"]>, then: (In: inferMatchBranch<def, ctx>) => ret) => ChainableMatchParser<addBranches<ctx, [(In: inferMatchBranch<def, ctx>) => ret]>>;
36
- cases: CaseMatchParser<ctx>;
37
- orThrow: () => finalizeMatchParser<addBranches<ctx, [(In: ctx["input"]) => never]>>;
38
- default: MatchParserDefaultInvocation<ctx>;
39
- };
40
- type MatchParserDefaultInvocation<ctx extends MatchParserContext> = {
41
- <f extends (In: ctx["input"]) => unknown>(f: f): finalizeWithDefault<ctx, ReturnType<f>>;
42
- <const value>(value: value): finalizeWithDefault<ctx, value>;
43
- };
41
+ cases: [...ctx["cases"], ...cases];
42
+ key: ctx["key"];
43
+ }> : never;
44
+ type addDefaultToContext<ctx extends MatchParserContext, defaultCase extends DefaultCase<ctx>> = ctx.from<{
45
+ $: ctx["$"];
46
+ input: defaultCase extends "never" ? Morph.In<ctx["cases"][number]> : ctx["input"];
47
+ cases: defaultCase extends Morph ? [...ctx["cases"], defaultCase] : defaultCase extends "never" | "assert" ? ctx["cases"] : [...ctx["cases"], (In: ctx["input"]) => ArkErrors];
48
+ key: ctx["key"];
49
+ }>;
50
+ type casesToMorphTuple<cases, ctx extends MatchParserContext> = unionToTuple<propValueOf<{
51
+ [def in Exclude<keyof cases, "default">]: cases[def] extends (Morph<never, infer o>) ? (In: inferCaseArg<def extends number ? `${number}` : def, ctx, "in">) => o : never;
52
+ }>>;
53
+ type addCasesToParser<cases, ctx extends MatchParserContext> = cases extends {
54
+ default: infer defaultDef extends DefaultCase<ctx>;
55
+ } ? finalizeMatchParser<addCasesToContext<ctx, casesToMorphTuple<cases, ctx>>, defaultDef> : ChainableMatchParser<addCasesToContext<ctx, casesToMorphTuple<cases, ctx>>>;
56
+ type inferCaseArg<def, ctx extends MatchParserContext, endpoint extends "in" | "out"> = _finalizeCaseArg<ctx["key"] extends PropertyKey ? {
57
+ [k in ctx["key"]]: type.infer<def, ctx["$"]>;
58
+ } : type.infer<def, ctx["$"]>, ctx, endpoint>;
59
+ type _finalizeCaseArg<t, ctx extends MatchParserContext, endpoint extends "in" | "out"> = [
60
+ distill<t, "in">,
61
+ distill<t, endpoint>
62
+ ] extends [infer i, infer result] ? i extends ctx["input"] ? result : Extract<ctx["input"], i> extends never ? result : Extract<ctx["input"], result> : never;
63
+ type CaseParser<ctx extends MatchParserContext> = <const def, ret>(def: type.validate<def, ctx["$"]>, resolve: (In: inferCaseArg<def, ctx, "out">) => ret) => ChainableMatchParser<addCasesToContext<ctx, [(In: inferCaseArg<def, ctx, "in">) => ret]>>;
64
+ type validateKey<key extends Key, ctx extends MatchParserContext> = ctx["key"] extends Key ? ErrorMessage<doubleAtMessage> : ctx["cases"]["length"] extends 0 ? keyof ctx["input"] extends never ? key : conform<key, keyof ctx["input"]> : ErrorMessage<chainedAtMessage>;
65
+ interface AtParser<ctx extends MatchParserContext> {
66
+ <const key extends string>(key: validateKey<key, ctx>): ChainableMatchParser<ctx.atKey<ctx, key>>;
67
+ <const key extends string, const cases, ctxAtKey extends MatchParserContext = ctx.atKey<ctx, key>>(key: validateKey<key, ctx>, cases: cases extends validateCases<cases, ctxAtKey> ? cases : errorCases<cases, ctxAtKey>): addCasesToParser<cases, ctxAtKey>;
68
+ }
69
+ interface ChainableMatchParser<ctx extends MatchParserContext> {
70
+ case: CaseParser<ctx>;
71
+ match: CaseMatchParser<ctx>;
72
+ default: DefaultMethod<ctx>;
73
+ at: AtParser<ctx>;
74
+ }
75
+ export type DefaultCaseKeyword = "never" | "assert" | "reject";
76
+ type DefaultCase<ctx extends MatchParserContext = MatchParserContext<any>> = DefaultCaseKeyword | Morph<ctx["input"]>;
77
+ type DefaultMethod<ctx extends MatchParserContext> = <const def extends DefaultCase<ctx>>(def: def) => finalizeMatchParser<ctx, def>;
44
78
  type validateCases<cases, ctx extends MatchParserContext> = {
45
- [def in keyof cases | keyof ctx["$"] | "default"]?: def extends "default" ? (In: ctx["input"]) => unknown : def extends type.validate<def, ctx["$"]> ? (In: inferMatchBranch<def, ctx>) => unknown : type.validate<def, ctx["$"]>;
79
+ [def in keyof cases | BaseCompletions<ctx["$"], {}, "default">]?: def extends "default" ? DefaultCase<ctx> : def extends number ? (In: inferCaseArg<`${def}`, ctx, "out">) => unknown : def extends type.validate<def, ctx["$"]> ? (In: inferCaseArg<def, ctx, "out">) => unknown : type.validate<def, ctx["$"]>;
46
80
  };
47
81
  type errorCases<cases, ctx extends MatchParserContext> = {
48
- [def in keyof cases]?: def extends "default" ? (In: ctx["input"]) => unknown : def extends type.validate<def, ctx["$"]> ? (In: inferMatchBranch<def, ctx>) => unknown : type.validate<def, ctx["$"]>;
82
+ [def in keyof cases]?: def extends "default" ? DefaultCase<ctx> : def extends number ? (In: inferCaseArg<`${def}`, ctx, "out">) => unknown : def extends type.validate<def, ctx["$"]> ? (In: inferCaseArg<def, ctx, "out">) => unknown : ErrorType<type.validate<def, ctx["$"]>>;
49
83
  } & {
50
- [k in Exclude<keyof ctx["$"], keyof cases>]?: (In: distill.Out<inferIntersection<ctx["input"], ctx["$"][k]>>) => unknown;
84
+ [k in BaseCompletions<ctx["$"], {}>]?: (In: inferCaseArg<k, ctx, "out">) => unknown;
51
85
  } & {
52
- default?: (In: ctx["input"]) => unknown;
53
- };
54
- export type CaseMatchParser<ctx extends MatchParserContext> = <cases>(def: cases extends validateCases<cases, ctx> ? cases : errorCases<cases, ctx>) => cases extends {
55
- default: (...args: never[]) => infer defaultReturn;
56
- } ? finalizeWithDefault<addBranches<ctx, unionToTuple<cases[Exclude<keyof cases, "default">]>>, defaultReturn> : ChainableMatchParser<addBranches<ctx, unionToTuple<propValueOf<cases>>>>;
57
- type finalizeWithDefault<ctx extends MatchParserContext, defaultReturn> = finalizeMatchParser<addBranches<ctx, [(_: ctx["input"]) => defaultReturn]>>;
58
- type finalizeMatchParser<ctx extends MatchParserContext> = MatchInvocation<{
59
- thens: ctx["thens"];
60
- input: ctx["input"];
61
- }>;
62
- type MatchInvocationContext = {
63
- thens: readonly Fn[];
64
- input: unknown;
86
+ default?: DefaultCase<ctx>;
65
87
  };
66
- export type MatchInvocation<ctx extends MatchInvocationContext> = <const data extends ctx["input"]>(data: data) => {
67
- [i in numericStringKeyOf<ctx["thens"]>]: isDisjoint<data, Parameters<ctx["thens"][i]>[0]> extends true ? never : ReturnType<ctx["thens"][i]>;
68
- }[numericStringKeyOf<ctx["thens"]>];
69
- export declare class InternalMatchParser extends Callable<(...args: unknown[]) => BaseRoot> {
88
+ export type CaseMatchParser<ctx extends MatchParserContext> = <const cases>(def: cases extends validateCases<cases, ctx> ? cases : errorCases<cases, ctx>) => addCasesToParser<cases, ctx>;
89
+ type finalizeMatchParser<ctx extends MatchParserContext, defaultCase extends DefaultCase<ctx>> = addDefaultToContext<ctx, defaultCase> extends (infer ctx extends MatchParserContext) ? Match<ctx["input"], ctx["cases"]> : never;
90
+ export interface Match<In = any, cases extends Morph[] = Morph[]> extends Inferred<(In: Morph.In<cases[number]>) => Out<ReturnType<cases[number]>>> {
91
+ <const data extends In>(data: data): {
92
+ [i in numericStringKeyOf<cases>]: isDisjoint<data, Morph.In<cases[i]>> extends true ? never : Morph.Out<cases[i]>;
93
+ }[numericStringKeyOf<cases>];
94
+ }
95
+ export declare class InternalMatchParser extends Callable<InternalCaseParserFn> {
96
+ $: InternalScope;
97
+ constructor($: InternalScope);
98
+ in(): InternalChainedMatchParser;
99
+ at(key: Key, cases?: InternalCases): InternalChainedMatchParser | Match;
100
+ case(when: unknown, then: Morph): InternalChainedMatchParser;
101
+ }
102
+ type InternalCases = Record<string, Morph | DefaultCase>;
103
+ type InternalCaseParserFn = (cases: InternalCases) => InternalChainedMatchParser | Match;
104
+ export declare class InternalChainedMatchParser extends Callable<InternalCaseParserFn> {
105
+ $: InternalScope;
106
+ protected key: Key | undefined;
107
+ protected branches: BaseRoot[];
70
108
  constructor($: InternalScope);
109
+ at(key: Key, cases?: InternalCases): InternalChainedMatchParser | Match;
110
+ case(def: unknown, resolver: Morph): InternalChainedMatchParser;
111
+ match(cases: InternalCases): InternalChainedMatchParser | Match;
112
+ default(defaultCase: DefaultCase): Match;
71
113
  }
114
+ export declare const throwOnDefault: ArkErrors.Handler;
115
+ export declare const chainedAtMessage = "A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')";
116
+ export type chainedAtMessage = typeof chainedAtMessage;
117
+ export declare const doubleAtMessage = "At most one key matcher may be specified per expression";
118
+ export type doubleAtMessage = typeof doubleAtMessage;
72
119
  export {};
package/out/match.js CHANGED
@@ -1,57 +1,77 @@
1
1
  import { intrinsic } from "@ark/schema";
2
- import { Callable } from "@ark/util";
2
+ import { Callable, domainOf, throwParseError } from "@ark/util";
3
3
  export class InternalMatchParser extends Callable {
4
+ $;
4
5
  constructor($) {
5
- super(() => {
6
- const matchParser = () => {
7
- const handledCases = [];
8
- let defaultCase = null;
9
- const parser = {
10
- when: (when, then) => {
11
- handledCases.push({
12
- when: $.parse(when),
13
- then
14
- });
15
- return parser;
16
- },
17
- finalize: () => {
18
- const branches = handledCases.flatMap(({ when, then }) => {
19
- if (when.kind === "union") {
20
- return when.branches.map(branch => ({
21
- in: branch,
22
- morphs: [then]
23
- }));
24
- }
25
- if (when.hasKind("morph"))
26
- return [{ in: when, morphs: [...when.morphs, then] }];
27
- return [{ in: when, morphs: [then] }];
28
- });
29
- if (defaultCase)
30
- branches.push({ in: intrinsic.unknown, morphs: [defaultCase] });
31
- const matchers = $.node("union", {
32
- branches,
33
- ordered: true
34
- });
35
- return matchers.assert;
36
- },
37
- orThrow: () =>
38
- // implicitly finalize, we don't need to do anything else because we throw either way
39
- parser.finalize(),
40
- default: (x) => {
41
- if (x instanceof Function)
42
- defaultCase = x;
43
- else
44
- defaultCase = () => x;
45
- return parser.finalize();
46
- }
47
- };
48
- return parser;
49
- };
50
- return Object.assign(() => matchParser(), {
51
- only: () => matchParser()
52
- });
53
- }, {
6
+ super((...args) => new InternalChainedMatchParser($)(...args), {
54
7
  bind: $
55
8
  });
9
+ this.$ = $;
10
+ }
11
+ in() {
12
+ return new InternalChainedMatchParser(this.$);
13
+ }
14
+ at(key, cases) {
15
+ return new InternalChainedMatchParser(this.$).at(key, cases);
16
+ }
17
+ case(when, then) {
18
+ return new InternalChainedMatchParser(this.$).case(when, then);
19
+ }
20
+ }
21
+ export class InternalChainedMatchParser extends Callable {
22
+ $;
23
+ key;
24
+ branches = [];
25
+ constructor($) {
26
+ super(cases => {
27
+ const entries = Object.entries(cases);
28
+ for (let i = 0; i < entries.length; i++) {
29
+ const [k, v] = entries[i];
30
+ if (k === "default") {
31
+ if (i !== entries.length - 1) {
32
+ throwParseError(`default may only be specified as the last key of a switch definition`);
33
+ }
34
+ return this.default(v);
35
+ }
36
+ if (typeof v !== "function") {
37
+ return throwParseError(`Value for case "${k}" must be a function (was ${domainOf(v)})`);
38
+ }
39
+ this.case(k, v);
40
+ }
41
+ return this;
42
+ });
43
+ this.$ = $;
44
+ }
45
+ at(key, cases) {
46
+ if (this.key)
47
+ throwParseError(doubleAtMessage);
48
+ if (this.branches.length)
49
+ throwParseError(chainedAtMessage);
50
+ this.key = key;
51
+ return cases ? this.match(cases) : this;
52
+ }
53
+ case(def, resolver) {
54
+ const wrappableDef = this.key ? { [this.key]: def } : def;
55
+ const branch = this.$.parse(wrappableDef).pipe(resolver);
56
+ this.branches.push(branch);
57
+ return this;
58
+ }
59
+ match(cases) {
60
+ return this(cases);
61
+ }
62
+ default(defaultCase) {
63
+ if (typeof defaultCase === "function")
64
+ this.case(intrinsic.unknown, defaultCase);
65
+ const schema = {
66
+ branches: this.branches,
67
+ ordered: true
68
+ };
69
+ if (defaultCase === "never" || defaultCase === "assert")
70
+ schema.meta = { onFail: throwOnDefault };
71
+ const matcher = this.$.finalize(this.$.node("union", schema));
72
+ return matcher;
56
73
  }
57
74
  }
75
+ export const throwOnDefault = errors => errors.throw();
76
+ export const chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`;
77
+ export const doubleAtMessage = `At most one key matcher may be specified per expression`;