Suite of AT Protocol TypeScript libraries built on web standards
1import type { Simplify } from "../core/types.ts";
2import {
3 type Infer,
4 Schema,
5 type ValidationResult,
6 type ValidatorContext,
7} from "../validation.ts";
8import type { DictSchema } from "./dict.ts";
9import type { ObjectSchema } from "./object.ts";
10
11export type Intersect<A, B> = B[keyof B] extends never ? A
12 : keyof A & keyof B extends never ? A & B
13 : A & { [K in keyof B]: B[K] | A[keyof A & K] };
14
15export type IntersectionSchemaOutput<
16 Left extends ObjectSchema,
17 Right extends DictSchema,
18> = Simplify<Intersect<Infer<Left>, Infer<Right>>>;
19
20export class IntersectionSchema<
21 const Left extends ObjectSchema = any,
22 const Right extends DictSchema = any,
23> extends Schema<IntersectionSchemaOutput<Left, Right>> {
24 constructor(
25 protected readonly left: Left,
26 protected readonly right: Right,
27 ) {
28 super();
29 }
30
31 validateInContext(
32 input: unknown,
33 ctx: ValidatorContext,
34 ): ValidationResult<IntersectionSchemaOutput<Left, Right>> {
35 const leftResult = ctx.validate(input, this.left);
36 if (!leftResult.success) return leftResult;
37
38 return this.right.validateInContext(leftResult.value, ctx, {
39 ignoredKeys: this.left.validatorsMap,
40 }) as ValidationResult<IntersectionSchemaOutput<Left, Right>>;
41 }
42}