UNPKG

dilswer

Version:

Blazingly fast data validation library with TypeScript integration.

78 lines (76 loc) 2.46 kB
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/string-matching.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 StringMetadata = class extends TypeMetadata { /** * Sets the metadata for the TypeScript pattern. This is used * for generating appropriate TypeScript declarations (via * `toTsType()`). * * This value must use the same syntax as the type literal * types in TypeScript. * * @example * const type = * DataType.StringMatching<`${string}.${string}`>( * /^.+\..+$/ * ).setTsPattern("${string}.${string}"); */ tsPattern(name) { this.container.tsPattern = name; return this.type; } }; var _a, _b; var StringMatchingType = class extends (_b = BaseType, _a = MetadataSymbol, _b) { constructor(pattern) { super(); __publicField(this, "pattern", pattern); __publicField(this, _a, {}); __publicField(this, "meta", new StringMetadata(this, this[MetadataSymbol])); __publicField(this, "kind", "stringMatching"); Object.freeze(this); } /** @internal */ static getOriginalMetadata(dt) { return dt[MetadataSymbol]; } /** @internal */ _acceptVisitor(visitor, depth = 1) { return visitor.visit(this, void 0, depth); } setTsPattern(tsPattern) { this[MetadataSymbol].tsPattern = tsPattern; return this; } get ["~standard"]() { return getStandardSchemaProps(this); } ["~validate"](path, value) { if (typeof value !== "string") { throw new ValidationError(path, this, value, "not a string"); } if (!this.pattern.test(value)) { throw new ValidationError( path, this, value, "does not match the pattern" ); } } ["~matches"](value) { return typeof value === "string" && this.pattern.test(value); } toString() { return `PrimitiveSchema[ string (/${this.pattern.source}/${this.pattern.flags}) ]`; } }; export { StringMatchingType, StringMetadata };