dilswer
Version:
Blazingly fast data validation library with TypeScript integration.
69 lines (67 loc) • 2.15 kB
JavaScript
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// src/data-types/types/tuple.ts
import { BaseType } from "../base-type.mjs";
import { getStandardSchemaProps } from "../generate-standard-schema.mjs";
import { ValidationError } from "../../validation-algorithms/validation-error/validation-error.mjs";
var TupleType = class extends BaseType {
constructor(tuple) {
super();
__publicField(this, "tuple", tuple);
__publicField(this, "kind", "tuple");
Object.freeze(this.tuple);
Object.freeze(this);
}
/** @internal */
_acceptVisitor(visitor, depth = 1) {
const children = [];
for (let i = 0; i < this.tuple.length; i++) {
children.push(this.tuple[i]._acceptVisitor(visitor, depth + 1));
}
return visitor.visit(this, children, depth);
}
get ["~standard"]() {
return getStandardSchemaProps(this);
}
["~validate"](path, value) {
if (!Array.isArray(value)) {
throw new ValidationError(path, this, value, "not an array");
}
if (value.length !== this.tuple.length) {
throw new ValidationError(
path,
this,
value,
"too many or too few elements in array"
);
}
for (let index = 0; index < this.tuple.length; index++) {
const elem = value[index];
const elemtType = this.tuple[index];
elemtType["~validate"](
path.concat(index),
elem
);
}
}
["~matches"](value) {
if (!Array.isArray(value) || value.length !== this.tuple.length) {
return false;
}
for (let index = 0; index < this.tuple.length; index++) {
const elem = value[index];
const elemtType = this.tuple[index];
if (!elemtType["~matches"](elem)) {
return false;
}
}
return true;
}
toString() {
return `TupleSchema[ ${this.tuple.map((t) => t.toString()).join(", ")} ]`;
}
};
export {
TupleType
};