Suite of AT Protocol TypeScript libraries built on web standards
1import {
2 Schema,
3 type ValidationResult,
4 type Validator,
5 type ValidatorContext,
6} from "../validation.ts";
7
8export type RefSchemaGetter<V> = () => Validator<V>;
9
10export class RefSchema<V = any> extends Schema<V> {
11 #getter: RefSchemaGetter<V>;
12
13 constructor(getter: RefSchemaGetter<V>) {
14 super();
15 this.#getter = getter;
16 }
17
18 get schema(): Validator<V> {
19 const value = this.#getter.call(null);
20
21 this.#getter = throwAlreadyCalled;
22
23 Object.defineProperty(this, "schema", {
24 value,
25 writable: false,
26 enumerable: false,
27 configurable: true,
28 });
29
30 return value;
31 }
32
33 validateInContext(
34 input: unknown,
35 ctx: ValidatorContext,
36 ): ValidationResult<V> {
37 return ctx.validate(input, this.schema);
38 }
39}
40
41function throwAlreadyCalled(): never {
42 throw new Error("RefSchema getter called multiple times");
43}