dilswer
Version:
Blazingly fast data validation library with TypeScript integration.
83 lines (81 loc) • 2.6 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/enum.ts
import { BaseType, MetadataSymbol, TypeMetadata } from "../base-type.mjs";
import { getStandardSchemaProps } from "../generate-standard-schema.mjs";
import { ValidationError } from "../../validation-algorithms/validation-error/validation-error.mjs";
var EnumMetadata = class extends TypeMetadata {
/**
* Sets the metadata for the enum name. This is used for
* generating appropriate TypeScript declarations (via
* `toTsType()`).
*/
enumName(name) {
this.container.enumName = name;
return this.type;
}
};
var _a, _b;
var EnumType = class extends (_b = BaseType, _a = MetadataSymbol, _b) {
constructor(enumInstance) {
super();
__publicField(this, _a, {});
__publicField(this, "kind", "enumUnion");
__publicField(this, "enumInstance");
__publicField(this, "memberNames");
__publicField(this, "meta", new EnumMetadata(this, this[MetadataSymbol]));
this.enumInstance = enumInstance;
this.memberNames = Object.keys(enumInstance).filter(
(name) => Number.isNaN(Number(name))
);
Object.freeze(this);
}
/** @internal */
static getOriginalMetadata(dt) {
return dt[MetadataSymbol];
}
/**
* Sets the metadata for the enum name. This is used for
* generating appropriate TypeScript declarations (via
* `toTsType()`).
*/
setEnumName(name) {
this[MetadataSymbol].enumName = name;
return this;
}
/** @internal */
_acceptVisitor(visitor, depth = 1) {
return visitor.visit(this, void 0, depth);
}
get ["~standard"]() {
return getStandardSchemaProps(this);
}
["~validate"](path, value) {
for (let i = 0; i < this.memberNames.length; i++) {
const name = this.memberNames[i];
const member = this.enumInstance[name];
if (member === value) {
return;
}
}
throw new ValidationError(path, this, value, "not a valid enum value");
}
["~matches"](value) {
for (let i = 0; i < this.memberNames.length; i++) {
const name = this.memberNames[i];
const member = this.enumInstance[name];
if (member === value) {
return true;
}
}
return false;
}
toString() {
return `EnumSchema[ ${this.memberNames.join(" | ")} ]`;
}
};
export {
EnumMetadata,
EnumType
};