bguard 0.0.4 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/{CommonSchema-DeTBsQhn.d.mts → CommonSchema-BIe85W_A.d.mts} +3 -1
- package/lib/{CommonSchema-DeTBsQhn.d.ts → CommonSchema-BIe85W_A.d.ts} +3 -1
- package/lib/InferType.d.mts +18 -0
- package/lib/InferType.d.ts +18 -0
- package/lib/InferType.js +19 -0
- package/lib/InferType.js.map +1 -0
- package/lib/InferType.mjs +1 -0
- package/lib/InferType.mjs.map +1 -0
- package/lib/__tests__/ArraySchema.test.d.mts +2 -0
- package/lib/__tests__/ArraySchema.test.d.ts +2 -0
- package/lib/__tests__/ArraySchema.test.js +201 -0
- package/lib/__tests__/ArraySchema.test.js.map +1 -0
- package/lib/__tests__/ArraySchema.test.mjs +199 -0
- package/lib/__tests__/ArraySchema.test.mjs.map +1 -0
- package/lib/__tests__/BooleanSchema.test.d.mts +2 -0
- package/lib/__tests__/BooleanSchema.test.d.ts +2 -0
- package/lib/__tests__/BooleanSchema.test.js +219 -0
- package/lib/__tests__/BooleanSchema.test.js.map +1 -0
- package/lib/__tests__/BooleanSchema.test.mjs +217 -0
- package/lib/__tests__/BooleanSchema.test.mjs.map +1 -0
- package/lib/__tests__/CommonSchema.test.d.mts +2 -0
- package/lib/__tests__/CommonSchema.test.d.ts +2 -0
- package/lib/__tests__/CommonSchema.test.js +253 -0
- package/lib/__tests__/CommonSchema.test.js.map +1 -0
- package/lib/__tests__/CommonSchema.test.mjs +251 -0
- package/lib/__tests__/CommonSchema.test.mjs.map +1 -0
- package/lib/__tests__/MixTypes.test.d.mts +2 -0
- package/lib/__tests__/MixTypes.test.d.ts +2 -0
- package/lib/__tests__/MixTypes.test.js +165 -0
- package/lib/__tests__/MixTypes.test.js.map +1 -0
- package/lib/__tests__/MixTypes.test.mjs +163 -0
- package/lib/__tests__/MixTypes.test.mjs.map +1 -0
- package/lib/__tests__/NumberSchema.test.d.mts +2 -0
- package/lib/__tests__/NumberSchema.test.d.ts +2 -0
- package/lib/__tests__/NumberSchema.test.js +253 -0
- package/lib/__tests__/NumberSchema.test.js.map +1 -0
- package/lib/__tests__/NumberSchema.test.mjs +251 -0
- package/lib/__tests__/NumberSchema.test.mjs.map +1 -0
- package/lib/__tests__/ObjectSchema.test.d.mts +2 -0
- package/lib/__tests__/ObjectSchema.test.d.ts +2 -0
- package/lib/__tests__/ObjectSchema.test.js +356 -0
- package/lib/__tests__/ObjectSchema.test.js.map +1 -0
- package/lib/__tests__/ObjectSchema.test.mjs +354 -0
- package/lib/__tests__/ObjectSchema.test.mjs.map +1 -0
- package/lib/__tests__/StringSchema.test.d.mts +2 -0
- package/lib/__tests__/StringSchema.test.d.ts +2 -0
- package/lib/__tests__/StringSchema.test.js +228 -0
- package/lib/__tests__/StringSchema.test.js.map +1 -0
- package/lib/__tests__/StringSchema.test.mjs +226 -0
- package/lib/__tests__/StringSchema.test.mjs.map +1 -0
- package/lib/asserts/array/index.d.mts +18 -2
- package/lib/asserts/array/index.d.ts +18 -2
- package/lib/asserts/boolean/index.d.mts +16 -2
- package/lib/asserts/boolean/index.d.ts +16 -2
- package/lib/asserts/common/equalTo.d.mts +1 -1
- package/lib/asserts/common/equalTo.d.ts +1 -1
- package/lib/asserts/common/index.d.mts +1 -1
- package/lib/asserts/common/index.d.ts +1 -1
- package/lib/asserts/number/index.d.mts +16 -2
- package/lib/asserts/number/index.d.ts +16 -2
- package/lib/asserts/number/max.d.mts +1 -1
- package/lib/asserts/number/max.d.ts +1 -1
- package/lib/asserts/number/maxExcluded.d.mts +1 -1
- package/lib/asserts/number/maxExcluded.d.ts +1 -1
- package/lib/asserts/number/min.d.mts +1 -1
- package/lib/asserts/number/min.d.ts +1 -1
- package/lib/asserts/number/minExcluded.d.mts +1 -1
- package/lib/asserts/number/minExcluded.d.ts +1 -1
- package/lib/asserts/number/negative.d.mts +1 -1
- package/lib/asserts/number/negative.d.ts +1 -1
- package/lib/asserts/number/positive.d.mts +1 -1
- package/lib/asserts/number/positive.d.ts +1 -1
- package/lib/asserts/object/index.d.mts +21 -2
- package/lib/asserts/object/index.d.ts +21 -2
- package/lib/asserts/string/email.d.mts +1 -1
- package/lib/asserts/string/email.d.ts +1 -1
- package/lib/asserts/string/index.d.mts +16 -2
- package/lib/asserts/string/index.d.ts +16 -2
- package/lib/asserts/string/maxLength.d.mts +1 -1
- package/lib/asserts/string/maxLength.d.ts +1 -1
- package/lib/asserts/string/minLength.d.mts +1 -1
- package/lib/asserts/string/minLength.d.ts +1 -1
- package/lib/asserts/string/regExp.d.mts +1 -1
- package/lib/asserts/string/regExp.d.ts +1 -1
- package/lib/core.d.mts +1 -0
- package/lib/core.d.ts +1 -0
- package/lib/core.js +111 -0
- package/lib/core.js.map +1 -0
- package/lib/core.mjs +83 -0
- package/lib/core.mjs.map +1 -0
- package/lib/exceptions.d.mts +12 -0
- package/lib/exceptions.d.ts +12 -0
- package/lib/exceptions.js +52 -0
- package/lib/exceptions.js.map +1 -0
- package/lib/exceptions.mjs +25 -0
- package/lib/exceptions.mjs.map +1 -0
- package/lib/index.d.mts +14 -51
- package/lib/index.d.ts +14 -51
- package/lib/index.js +8 -2
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +4 -1
- package/lib/parseSchema.d.mts +37 -0
- package/lib/parseSchema.d.ts +37 -0
- package/lib/parseSchema.js +119 -0
- package/lib/parseSchema.js.map +1 -0
- package/lib/parseSchema.mjs +92 -0
- package/lib/parseSchema.mjs.map +1 -0
- package/lib/schemas/ArraySchema.d.mts +13 -0
- package/lib/schemas/ArraySchema.d.ts +13 -0
- package/lib/schemas/ArraySchema.js +85 -0
- package/lib/schemas/ArraySchema.js.map +1 -0
- package/lib/schemas/ArraySchema.mjs +58 -0
- package/lib/schemas/ArraySchema.mjs.map +1 -0
- package/lib/{index-nzqBrOHf.d.mts → schemas/BooleanSchema.d.mts} +2 -14
- package/lib/{index-B1yBez0g.d.ts → schemas/BooleanSchema.d.ts} +2 -14
- package/lib/schemas/BooleanSchema.js +113 -0
- package/lib/schemas/BooleanSchema.js.map +1 -0
- package/lib/schemas/BooleanSchema.mjs +86 -0
- package/lib/schemas/BooleanSchema.mjs.map +1 -0
- package/lib/schemas/CommonSchema.d.mts +1 -0
- package/lib/schemas/CommonSchema.d.ts +1 -0
- package/lib/schemas/CommonSchema.js +67 -0
- package/lib/schemas/CommonSchema.js.map +1 -0
- package/lib/schemas/CommonSchema.mjs +40 -0
- package/lib/schemas/CommonSchema.mjs.map +1 -0
- package/lib/{index-B63cXDOm.d.mts → schemas/NumberSchema.d.mts} +2 -14
- package/lib/{index-CK_g_aEC.d.ts → schemas/NumberSchema.d.ts} +2 -14
- package/lib/schemas/NumberSchema.js +107 -0
- package/lib/schemas/NumberSchema.js.map +1 -0
- package/lib/schemas/NumberSchema.mjs +80 -0
- package/lib/schemas/NumberSchema.mjs.map +1 -0
- package/lib/schemas/ObjectSchema.d.mts +12 -0
- package/lib/schemas/ObjectSchema.d.ts +12 -0
- package/lib/schemas/ObjectSchema.js +89 -0
- package/lib/schemas/ObjectSchema.js.map +1 -0
- package/lib/schemas/ObjectSchema.mjs +62 -0
- package/lib/schemas/ObjectSchema.mjs.map +1 -0
- package/lib/{index-aBEYpJdZ.d.mts → schemas/StringSchema.d.mts} +2 -14
- package/lib/{index-BEyBEBSm.d.ts → schemas/StringSchema.d.ts} +2 -14
- package/lib/schemas/StringSchema.js +107 -0
- package/lib/schemas/StringSchema.js.map +1 -0
- package/lib/schemas/StringSchema.mjs +80 -0
- package/lib/schemas/StringSchema.mjs.map +1 -0
- package/package.json +28 -27
- package/lib/index-D3R2euaT.d.mts +0 -29
- package/lib/index-DPkImfCy.d.ts +0 -29
- package/lib/index-DitgsWDO.d.ts +0 -27
- package/lib/index-T3KBmyyn.d.mts +0 -27
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/exceptions.ts","../src/core.ts","../src/parseSchema.ts","../src/asserts/common/equalTo.ts","../src/schemas/CommonSchema.ts","../src/schemas/NumberSchema.ts","../src/asserts/number/index.ts","../src/schemas/StringSchema.ts","../src/asserts/string/index.ts","../src/schemas/BooleanSchema.ts","../src/asserts/boolean/index.ts","../src/schemas/ArraySchema.ts","../src/asserts/array/index.ts","../src/schemas/ObjectSchema.ts","../src/asserts/object/index.ts","../src/asserts/common/index.ts"],"sourcesContent":["export type { InferType } from './InferType';\nexport { parseSchema } from './parseSchema';\nexport { number } from './asserts/number';\nexport { string } from './asserts/string';\nexport { boolean } from './asserts/boolean';\nexport { array } from './asserts/array';\nexport { object } from './asserts/object';\nexport { oneOfTypes } from './asserts/common';\n","export class ValidationError extends Error {\n expected: unknown;\n received: unknown;\n pathToError: string;\n message: string;\n constructor(expected: unknown, received: unknown, pathToError: string, message: string) {\n super();\n this.expected = expected;\n this.received = received;\n this.pathToError = pathToError;\n this.message = message;\n }\n}\n\nexport class BuildSchemaError extends Error {}\n\nexport function throwException(expected: unknown, received: unknown, pathToError: string, message: string): never {\n throw new ValidationError(expected, received, pathToError, message);\n}\n","export const ctxSymbol = Symbol('contextSymbol');\n\nimport { throwException } from './exceptions';\nimport type { CommonSchema } from './schemas/CommonSchema';\n\nexport function innerCheck(schema: CommonSchema, receivedValue: unknown, pathToError: string) {\n const ctx = schema[ctxSymbol];\n if (receivedValue === undefined) {\n if (!ctx.isOptional) throwException('Required', receivedValue, pathToError, 'The required value is missing');\n return receivedValue;\n }\n\n if (receivedValue === null) {\n if (!ctx.isNullable) throwException('Not null', receivedValue, pathToError, 'Value should not be null');\n return receivedValue;\n }\n\n if (ctx.array) {\n if (!Array.isArray(receivedValue))\n throwException('Array', receivedValue, pathToError, 'Expected an array but received a different type');\n const schema = ctx.array;\n\n receivedValue.forEach((elem, i) => {\n innerCheck(schema, elem, `${pathToError}[${i}]`);\n });\n\n return receivedValue;\n }\n\n const typeOfVal = typeof receivedValue;\n\n if (ctx.object) {\n if (typeOfVal !== 'object')\n throwException('Object', receivedValue, pathToError, 'Expected an object but received a different type');\n if (Array.isArray(receivedValue))\n throwException(\n 'Object',\n receivedValue,\n pathToError,\n 'Expected an object but received an array. Invalid type of data',\n );\n const shapeSchema = ctx.object;\n for (const keyPerReceivedValue of Object.keys(receivedValue)) {\n if (shapeSchema[keyPerReceivedValue] === undefined)\n throwException('Not allowed', keyPerReceivedValue, pathToError, 'This key is not allowed in the object');\n }\n\n for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {\n const receivedObjectValuePropery = (receivedValue as Record<string, unknown>)[keyOfSchema];\n if (receivedObjectValuePropery === undefined) {\n if (!valueOfSchema[ctxSymbol].isOptional)\n throwException(\n 'Required',\n receivedObjectValuePropery,\n pathToError,\n 'Missing required property in the object',\n );\n }\n innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);\n }\n\n return receivedValue;\n }\n\n if (ctx.type.length) {\n if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, 'Invalid type of data');\n }\n\n ctx.requiredValidations.forEach((requiredValidation) => {\n requiredValidation(receivedValue, pathToError);\n });\n\n return receivedValue;\n}\n","import { InferType } from './InferType';\nimport { innerCheck } from './core';\nimport { ValidationError } from './exceptions';\nimport { CommonSchema } from './schemas/CommonSchema';\n\n/**\n * Parses and validates a value against the provided schema, returning a type-safe result.\n *\n * This function will throw a `ValidationError` if the value does not conform to the schema.\n * The inferred TypeScript type of the returned value will match the structure defined by the schema.\n *\n * @template T\n * @param {T} schema - The schema to validate the received value against. This schema dictates the expected structure and type of the value.\n * @param {unknown} receivedValue - The value to be validated and parsed according to the schema.\n * @returns {InferType<T>} The validated value, with its TypeScript type inferred from the schema.\n *\n * @throws {ValidationError} If the received value does not match the schema, a `ValidationError` will be thrown.\n * @throws {Error} If an unexpected error occurs during validation, an error will be thrown with a generic message.\n *\n * @example\n * const schema = object({\n * name: string(),\n * age: number(),\n * });\n *\n * const result = parseSchema(schema, { name: 'Alice', age: 30 });\n * // result will be inferred as { name: string; age: number }\n *\n * parseSchema(schema, { name: 'Alice', age: '30' });\n * // Throws ValidationError because 'age' should be a number, not a string.\n */\nexport function parseSchema<T extends CommonSchema>(schema: T, receivedValue: unknown): InferType<T> {\n try {\n return innerCheck(schema, receivedValue, '') as InferType<T>;\n } catch (e) {\n if (e instanceof ValidationError) throw e;\n /* istanbul ignore next */\n throw new Error('Something unexpected happened');\n }\n}\n","import { throwException } from '../../exceptions';\nimport { RequiredValidation } from '../../schemas/CommonSchema';\n\n/**\n * Creates a custom assertion that checks if a value is equal to the expected value.\n *\n * This assertion can be used within a `.custom` method to enforce that a value strictly matches the expected value.\n * It will throw a `ValidationError` if the values are not equal.\n *\n * @param {unknown} expected - The value that the received value is expected to match.\n * @returns {RequiredValidation} A function that takes the received value and the path to the error,\n * and throws a `ValidationError` if the received value does not equal the expected value.\n *\n * @throws {ValidationError} If the received value does not match the expected value.\n *\n * @example\n * import { number, equalTo } from 'bguard';\n *\n * // Define a schema with a custom assertion\n * const schema = number().custom(equalTo(5));\n *\n * // This will pass\n * parseSchema(schema, 5);\n *\n * // This will throw a ValidationError\n * parseSchema(schema, 3);\n */\nexport const equalTo =\n (expected: unknown): RequiredValidation =>\n (received: number, pathToError: string) => {\n if (expected !== received)\n throwException(expected, received, pathToError, 'The received value is not equal to expected');\n };\n","import { ctxSymbol } from '../core';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type RequiredValidation = (received: any, pathToError: string) => void;\nexport type ObjectShapeSchemaType = Record<string, CommonSchema>;\n\nexport type PrimitiveType = 'number' | 'string' | 'boolean' | 'undefined' | 'object' | 'function' | 'symbol' | 'bigint';\nexport interface ValidatorContext {\n type: PrimitiveType[];\n isNullable?: boolean;\n isOptional?: boolean;\n requiredValidations: RequiredValidation[];\n array?: CommonSchema;\n object?: ObjectShapeSchemaType;\n}\n\nexport class CommonSchema {\n [ctxSymbol]: ValidatorContext;\n constructor(ctx: ValidatorContext) {\n this[ctxSymbol] = ctx;\n }\n\n /**\n * @param validators - One or more custom validation functions.\n * @returns {this} The schema instance with the added custom validation.\n */\n custom(...validators: RequiredValidation[]): this {\n this[ctxSymbol].requiredValidations.push(...validators);\n return this;\n }\n\n /**\n * Marks the schema as nullable, allowing the value to be `null`.\n *\n * @returns {WithNull<this>} The schema instance marked as nullable.\n */\n nullable(): WithNull<this> {\n this[ctxSymbol].isNullable = true;\n return this as WithNull<this>;\n }\n\n /**\n * Marks the schema as optional, allowing the value to be `undefined`.\n *\n * @returns {WithUndefined<this>}} The schema instance marked as optional.\n */\n optional(): WithUndefined<this> {\n this[ctxSymbol].isOptional = true;\n return this as WithUndefined<this>;\n }\n}\n\nexport type WithNull<T extends CommonSchema> = T & { validation_null: true };\nexport type WithUndefined<T extends CommonSchema> = T & { validation_undefined: true };\n\ntype TypeMapping = {\n number: number;\n string: string;\n boolean: boolean;\n undefined: undefined;\n object: object;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n function: Function;\n symbol: symbol;\n bigint: bigint;\n};\n\nexport type WithMix<Y = unknown> = CommonSchema & { validation_mix: Y };\nexport type ExtractFromMix<T> = T extends WithMix<infer X> ? X : never;\n\nexport type MapMixTypes<T extends PrimitiveType[]> = T extends (infer U)[]\n ? U extends keyof TypeMapping\n ? TypeMapping[U]\n : never\n : never;\n","import { equalTo } from '../asserts/common/equalTo';\n\nimport { CommonSchema } from './CommonSchema';\n\nexport class NumberSchema extends CommonSchema {\n _number = 1;\n\n /**\n * Restricts the schema to exactly match the specified value and infers the literal value as the TypeScript type.\n *\n * @param expectedValue - The value that the schema must exactly match.\n * @returns - The schema instance restricted to the specified value, with the literal value inferred as the TypeScript type\n *\n * @example - number().equalTo(42); // Infers the type 42\n */\n equalTo<Y extends number>(expectedValue: Y): WithNumber<this, Y> {\n return this.custom(equalTo(expectedValue)) as WithNumber<this, Y>;\n }\n}\n\nexport type WithNumber<T extends NumberSchema, Y = number> = T & { validation_number: Y };\nexport type ExtractFromNumber<T> = T extends WithNumber<NumberSchema, infer Y> ? Y : never;\n","import { NumberSchema } from '../../schemas/NumberSchema';\n\n/**\n * Creates a new schema for validating number values.\n *\n * @returns {NumberSchema} A new instance of `NumberSchema` for validating numbers.\n *\n * @example\n * const schema = number();\n * parseSchema(schema, 42); // Validates successfully\n * parseSchema(schema, '42'); // Throws a validation error\n */\nexport function number(): NumberSchema {\n return new NumberSchema({ type: ['number'], requiredValidations: [] });\n}\n","import { equalTo } from '../asserts/common/equalTo';\nimport { CommonSchema } from './CommonSchema';\n\nexport class StringSchema extends CommonSchema {\n _string = 1;\n\n /**\n * Restricts the schema to exactly match the specified value and infers the literal value as the TypeScript type.\n *\n * @param expectedValue - The value that the schema must exactly match.\n * @returns - The schema instance restricted to the specified value, with the literal value inferred as the TypeScript type\n *\n * @example - string().equalTo('hello'); // Infers the type 'hello'\n */\n equalTo<Y extends string>(expectedValue: Y): WithString<this, Y> {\n return this.custom(equalTo(expectedValue)) as WithString<this, Y>;\n }\n}\n\nexport type WithString<T extends StringSchema, Y = string> = T & { validation_string: Y };\nexport type ExtractFromString<T> = T extends WithString<StringSchema, infer Y> ? Y : never;\n","import { StringSchema } from '../../schemas/StringSchema';\n\n/**\n * Creates a new schema for validating string values.\n *\n * @returns {StringSchema} A new instance of `StringSchema` for validating strings.\n *\n * @example\n * const schema = string();\n * parseSchema(schema, 'hello'); // Validates successfully\n * parseSchema(schema, 123); // Throws a validation error\n */\nexport function string(): StringSchema {\n return new StringSchema({ type: ['string'], requiredValidations: [] });\n}\n","import { CommonSchema } from './CommonSchema';\nimport { throwException } from '../exceptions';\n\nconst isBoolean = (expected: boolean) => (received: boolean, pathToError: string) => {\n if (received !== expected) throwException(expected, received, pathToError, `The received value is not ${expected}`);\n};\n\nexport class BooleanSchema extends CommonSchema {\n _boolean = 1;\n\n /**\n * Restricts the schema to exactly match the boolean value true and infers the true value as the TypeScript type.\n *\n * @returns - The schema instance restricted to the value true, with the true value inferred as the TypeScript type\n *\n * @example - boolean().onlyTrue(); // Infers the type true\n */\n onlyTrue(): WithBoolean<this, true> {\n return this.custom(isBoolean(true)) as WithBoolean<this, true>;\n }\n\n /**\n * Restricts the schema to exactly match the boolean value false and infers the false value as the TypeScript type.\n *\n * @returns - The schema instance restricted to the value false, with the false value inferred as the TypeScript type\n *\n * @example - boolean().onlyFalse(); // Infers the type false\n */\n onlyFalse(): WithBoolean<this, false> {\n return this.custom(isBoolean(false)) as WithBoolean<this, false>;\n }\n}\n\nexport type WithBoolean<T extends BooleanSchema, Y = boolean> = T & { validation_boolean: Y };\nexport type ExtractFromBoolean<T> = T extends WithBoolean<BooleanSchema, infer Y> ? Y : never;\n","import { BooleanSchema } from '../../schemas/BooleanSchema';\n\n/**\n * Creates a new schema for validating boolean values.\n *\n * @returns {BooleanSchema} A new instance of `BooleanSchema` for validating booleans.\n *\n * @example\n * const schema = boolean();\n * parseSchema(schema, true); // Validates successfully\n * parseSchema(schema, 'true'); // Throws a validation error\n */\nexport function boolean(): BooleanSchema {\n return new BooleanSchema({ type: ['boolean'], requiredValidations: [] });\n}\n","import { ctxSymbol } from '../core';\nimport { BuildSchemaError } from '../exceptions';\nimport { CommonSchema, ValidatorContext } from './CommonSchema';\n\nexport class ArraySchema extends CommonSchema {\n _array = 1;\n constructor(ctx: ValidatorContext, arraySchema: CommonSchema) {\n super(ctx);\n this.validateArrayEntry(arraySchema);\n this[ctxSymbol].array = arraySchema;\n }\n\n private validateArrayEntry(arraySchema: CommonSchema) {\n if (!arraySchema) throw new BuildSchemaError('Missing schema in array method');\n if (!(arraySchema instanceof CommonSchema)) throw new BuildSchemaError('Invalid schema in array method');\n }\n}\n\nexport type WithArray<Y extends CommonSchema> = ArraySchema & { validation_array: Y };\nexport type ExtractFromArray<T> = T extends WithArray<infer X> ? X : never;\n","import { ArraySchema, WithArray } from '../../schemas/ArraySchema';\nimport { CommonSchema } from '../../schemas/CommonSchema';\n\n/**\n * Creates a new schema for validating arrays where each element must match the specified schema.\n *\n * @template T\n * @param {T} arraySchema - The schema that each element of the array must match.\n * @returns {WithArray<T>} A new instance of `ArraySchema` for validating arrays of elements that match the specified schema.\n *\n * @example\n * const schema = array(string());\n * parseSchema(schema, ['hello', 'world']); // Validates successfully\n * parseSchema(schema, ['hello', 123]); // Throws a validation error\n */\nexport function array<T extends CommonSchema>(arraySchema: T): WithArray<T> {\n return new ArraySchema({ type: [], requiredValidations: [] }, arraySchema) as WithArray<T>;\n}\n","import { ctxSymbol } from '../core';\nimport { BuildSchemaError } from '../exceptions';\nimport { CommonSchema, ObjectShapeSchemaType, ValidatorContext } from './CommonSchema';\n\nexport class ObjectSchema extends CommonSchema {\n _object = 1;\n constructor(ctx: ValidatorContext, shapeSchema: ObjectShapeSchemaType) {\n super(ctx);\n this.validateObjectEntry(shapeSchema);\n this[ctxSymbol].object = shapeSchema;\n }\n\n private validateObjectEntry(shapeSchema: ObjectShapeSchemaType) {\n if (!shapeSchema) throw new BuildSchemaError('Missing schema in object method');\n if (shapeSchema instanceof CommonSchema) throw new BuildSchemaError('Invalid schema in object');\n for (const [key, value] of Object.entries(shapeSchema)) {\n if (!(value instanceof CommonSchema))\n throw new BuildSchemaError(`Invalid schema in object method for property '${key}'`);\n }\n }\n}\n\nexport type WithObject<Y extends ObjectShapeSchemaType> = ObjectSchema & { validation_object: Y };\n","import { ObjectShapeSchemaType } from '../../schemas/CommonSchema';\nimport { ObjectSchema, WithObject } from '../../schemas/ObjectSchema';\n\n/**\n * Creates a new schema for validating objects where each property must match the specified schema.\n *\n * @template T\n * @param {T} shapeSchema - The schema that each property of the object must match.\n * @returns {WithObject<T>} A new instance of `ObjectSchema` for validating objects with properties matching the specified schema.\n *\n * @example\n * const schema = object({\n * name: string(),\n * age: number()\n * });\n * parseSchema(schema, { name: 'John', age: 30 }); // Validates successfully\n * parseSchema(schema, { name: 'John', age: '30' }); // Throws a validation error\n */\nexport function object<T extends ObjectShapeSchemaType>(shapeSchema: T): WithObject<T> {\n return new ObjectSchema({ type: [], requiredValidations: [] }, shapeSchema) as WithObject<T>;\n}\n","import { CommonSchema, MapMixTypes, PrimitiveType, WithMix } from '../../schemas/CommonSchema';\n\n/**\n * Creates a new schema for validating values that can match any one of the specified primitive types.\n *\n * @template T\n * @param {T} valueTypes - An array of primitive types that the value can match.\n * @returns {WithMix<MapMixTypes<T>>} A new schema for validating values that can match any of the specified types.\n *\n * @example\n * const schema = oneOfTypes(['string', 'number']);\n * parseSchema(schema, 'hello'); // Validates successfully\n * parseSchema(schema, 42); // Validates successfully\n * parseSchema(schema, true); // Throws a validation error\n */\nexport function oneOfTypes<T extends PrimitiveType[]>(valueTypes: T): WithMix<MapMixTypes<T>> {\n return new CommonSchema({ type: valueTypes, requiredValidations: [] }) as WithMix<MapMixTypes<T>>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,UAAmB,UAAmB,aAAqB,SAAiB;AACtF,UAAM;AACN,SAAK,WAAW;AAChB,SAAK,WAAW;AAChB,SAAK,cAAc;AACnB,SAAK,UAAU;AAAA,EACjB;AACF;AAEO,IAAM,mBAAN,cAA+B,MAAM;AAAC;AAEtC,SAAS,eAAe,UAAmB,UAAmB,aAAqB,SAAwB;AAChH,QAAM,IAAI,gBAAgB,UAAU,UAAU,aAAa,OAAO;AACpE;;;AClBO,IAAM,YAAY,OAAO,eAAe;AAKxC,SAAS,WAAW,QAAsB,eAAwB,aAAqB;AAC5F,QAAM,MAAM,OAAO,SAAS;AAC5B,MAAI,kBAAkB,QAAW;AAC/B,QAAI,CAAC,IAAI,WAAY,gBAAe,YAAY,eAAe,aAAa,+BAA+B;AAC3G,WAAO;AAAA,EACT;AAEA,MAAI,kBAAkB,MAAM;AAC1B,QAAI,CAAC,IAAI,WAAY,g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pC,SAAK,SAAS,EAAE,SAAS;AAAA,EAC3B;AAAA,EAEQ,oBAAoB,aAAoC;AAC9D,QAAI,CAAC,YAAa,OAAM,IAAI,iBAAiB,iCAAiC;AAC9E,QAAI,uBAAuB,aAAc,OAAM,IAAI,iBAAiB,0BAA0B;AAC9F,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,WAAW,GAAG;AACtD,UAAI,EAAE,iBAAiB;AACrB,cAAM,IAAI,iBAAiB,iDAAiD,GAAG,GAAG;AAAA,IACtF;AAAA,EACF;AACF;;;ACFO,SAAS,OAAwC,aAA+B;AACrF,SAAO,IAAI,aAAa,EAAE,MAAM,CAAC,GAAG,qBAAqB,CAAC,EAAE,GAAG,WAAW;AAC5E;;;ACLO,SAAS,WAAsC,YAAwC;AAC5F,SAAO,IAAI,aAAa,EAAE,MAAM,YAAY,qBAAqB,CAAC,EAAE,CAAC;AACvE;","names":["schema"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/exceptions.ts","../src/core.ts","../src/parseSchema.ts","../src/asserts/common/equalTo.ts","../src/schemas/CommonSchema.ts","../src/schemas/NumberSchema.ts","../src/asserts/number/index.ts","../src/schemas/StringSchema.ts","../src/asserts/string/index.ts","../src/schemas/BooleanSchema.ts","../src/asserts/boolean/index.ts","../src/schemas/ArraySchema.ts","../src/asserts/array/index.ts","../src/schemas/ObjectSchema.ts","../src/asserts/object/index.ts","../src/asserts/common/index.ts"],"sourcesContent":["export type { InferType } from './InferType';\nexport { parseSchema } from './parseSchema';\nexport { number } from './asserts/number';\nexport { string } from './asserts/string';\nexport { boolean } from './asserts/boolean';\nexport { array } from './asserts/array';\nexport { object } from './asserts/object';\nexport { oneOfTypes } from './asserts/common';\nexport { ValidationError, BuildSchemaError, throwException } from './exceptions';\n","export class ValidationError extends Error {\n expected: unknown;\n received: unknown;\n pathToError: string;\n message: string;\n constructor(expected: unknown, received: unknown, pathToError: string, message: string) {\n super();\n this.expected = expected;\n this.received = received;\n this.pathToError = pathToError;\n this.message = message;\n }\n}\n\nexport class BuildSchemaError extends Error {}\n\nexport function throwException(expected: unknown, received: unknown, pathToError: string, message: string): never {\n throw new ValidationError(expected, received, pathToError, message);\n}\n","export const ctxSymbol = Symbol('contextSymbol');\n\nimport { throwException } from './exceptions';\nimport type { CommonSchema } from './schemas/CommonSchema';\n\nexport function innerCheck(schema: CommonSchema, receivedValue: unknown, pathToError: string) {\n const ctx = schema[ctxSymbol];\n if (receivedValue === undefined) {\n if (!ctx.isOptional) throwException('Required', receivedValue, pathToError, 'The required value is missing');\n return receivedValue;\n }\n\n if (receivedValue === null) {\n if (!ctx.isNullable) throwException('Not null', receivedValue, pathToError, 'Value should not be null');\n return receivedValue;\n }\n\n if (ctx.array) {\n if (!Array.isArray(receivedValue))\n throwException('Array', receivedValue, pathToError, 'Expected an array but received a different type');\n const schema = ctx.array;\n\n receivedValue.forEach((elem, i) => {\n innerCheck(schema, elem, `${pathToError}[${i}]`);\n });\n\n return receivedValue;\n }\n\n const typeOfVal = typeof receivedValue;\n\n if (ctx.object) {\n if (typeOfVal !== 'object')\n throwException('Object', receivedValue, pathToError, 'Expected an object but received a different type');\n if (Array.isArray(receivedValue))\n throwException(\n 'Object',\n receivedValue,\n pathToError,\n 'Expected an object but received an array. Invalid type of data',\n );\n const shapeSchema = ctx.object;\n for (const keyPerReceivedValue of Object.keys(receivedValue)) {\n if (shapeSchema[keyPerReceivedValue] === undefined)\n throwException('Not allowed', keyPerReceivedValue, pathToError, 'This key is not allowed in the object');\n }\n\n for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {\n const receivedObjectValuePropery = (receivedValue as Record<string, unknown>)[keyOfSchema];\n if (receivedObjectValuePropery === undefined) {\n if (!valueOfSchema[ctxSymbol].isOptional)\n throwException(\n 'Required',\n receivedObjectValuePropery,\n pathToError,\n 'Missing required property in the object',\n );\n }\n innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);\n }\n\n return receivedValue;\n }\n\n if (ctx.type.length) {\n if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, 'Invalid type of data');\n }\n\n ctx.requiredValidations.forEach((requiredValidation) => {\n requiredValidation(receivedValue, pathToError);\n });\n\n return receivedValue;\n}\n","import { InferType } from './InferType';\nimport { innerCheck } from './core';\nimport { ValidationError } from './exceptions';\nimport { CommonSchema } from './schemas/CommonSchema';\n\n/**\n * Parses and validates a value against the provided schema, returning a type-safe result.\n *\n * This function will throw a `ValidationError` if the value does not conform to the schema.\n * The inferred TypeScript type of the returned value will match the structure defined by the schema.\n *\n * @template T\n * @param {T} schema - The schema to validate the received value against. This schema dictates the expected structure and type of the value.\n * @param {unknown} receivedValue - The value to be validated and parsed according to the schema.\n * @returns {InferType<T>} The validated value, with its TypeScript type inferred from the schema.\n *\n * @throws {ValidationError} If the received value does not match the schema, a `ValidationError` will be thrown.\n * @throws {Error} If an unexpected error occurs during validation, an error will be thrown with a generic message.\n *\n * @example\n * const schema = object({\n * name: string(),\n * age: number(),\n * });\n *\n * const result = parseSchema(schema, { name: 'Alice', age: 30 });\n * // result will be inferred as { name: string; age: number }\n *\n * parseSchema(schema, { name: 'Alice', age: '30' });\n * // Throws ValidationError because 'age' should be a number, not a string.\n */\nexport function parseSchema<T extends CommonSchema>(schema: T, receivedValue: unknown): InferType<T> {\n try {\n return innerCheck(schema, receivedValue, '') as InferType<T>;\n } catch (e) {\n if (e instanceof ValidationError) throw e;\n /* istanbul ignore next */\n throw new Error('Something unexpected happened');\n }\n}\n","import { throwException } from '../../exceptions';\nimport { RequiredValidation } from '../../schemas/CommonSchema';\n\n/**\n * Creates a custom assertion that checks if a value is equal to the expected value.\n *\n * This assertion can be used within a `.custom` method to enforce that a value strictly matches the expected value.\n * It will throw a `ValidationError` if the values are not equal.\n *\n * @param {unknown} expected - The value that the received value is expected to match.\n * @returns {RequiredValidation} A function that takes the received value and the path to the error,\n * and throws a `ValidationError` if the received value does not equal the expected value.\n *\n * @throws {ValidationError} If the received value does not match the expected value.\n *\n * @example\n * import { number, equalTo } from 'bguard';\n *\n * // Define a schema with a custom assertion\n * const schema = number().custom(equalTo(5));\n *\n * // This will pass\n * parseSchema(schema, 5);\n *\n * // This will throw a ValidationError\n * parseSchema(schema, 3);\n */\nexport const equalTo =\n (expected: unknown): RequiredValidation =>\n (received: number, pathToError: string) => {\n if (expected !== received)\n throwException(expected, received, pathToError, 'The received value is not equal to expected');\n };\n","import { ctxSymbol } from '../core';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type RequiredValidation = (received: any, pathToError: string) => void;\nexport type ObjectShapeSchemaType = Record<string, CommonSchema>;\n\nexport type PrimitiveType = 'number' | 'string' | 'boolean' | 'undefined' | 'object' | 'function' | 'symbol' | 'bigint';\nexport interface ValidatorContext {\n type: PrimitiveType[];\n isNullable?: boolean;\n isOptional?: boolean;\n requiredValidations: RequiredValidation[];\n array?: CommonSchema;\n object?: ObjectShapeSchemaType;\n}\n\nexport class CommonSchema {\n [ctxSymbol]: ValidatorContext;\n constructor(ctx: ValidatorContext) {\n this[ctxSymbol] = ctx;\n }\n\n /**\n * @param validators - One or more custom validation functions.\n * @returns {this} The schema instance with the added custom validation.\n */\n custom(...validators: RequiredValidation[]): this {\n this[ctxSymbol].requiredValidations.push(...validators);\n return this;\n }\n\n /**\n * Marks the schema as nullable, allowing the value to be `null`.\n *\n * @returns {WithNull<this>} The schema instance marked as nullable.\n */\n nullable(): WithNull<this> {\n this[ctxSymbol].isNullable = true;\n return this as WithNull<this>;\n }\n\n /**\n * Marks the schema as optional, allowing the value to be `undefined`.\n *\n * @returns {WithUndefined<this>}} The schema instance marked as optional.\n */\n optional(): WithUndefined<this> {\n this[ctxSymbol].isOptional = true;\n return this as WithUndefined<this>;\n }\n}\n\nexport type WithNull<T extends CommonSchema> = T & { validation_null: true };\nexport type WithUndefined<T extends CommonSchema> = T & { validation_undefined: true };\n\ntype TypeMapping = {\n number: number;\n string: string;\n boolean: boolean;\n undefined: undefined;\n object: object;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n function: Function;\n symbol: symbol;\n bigint: bigint;\n};\n\nexport type WithMix<Y = unknown> = CommonSchema & { validation_mix: Y };\nexport type ExtractFromMix<T> = T extends WithMix<infer X> ? X : never;\n\nexport type MapMixTypes<T extends PrimitiveType[]> = T extends (infer U)[]\n ? U extends keyof TypeMapping\n ? TypeMapping[U]\n : never\n : never;\n","import { equalTo } from '../asserts/common/equalTo';\n\nimport { CommonSchema } from './CommonSchema';\n\nexport class NumberSchema extends CommonSchema {\n _number = 1;\n\n /**\n * Restricts the schema to exactly match the specified value and infers the literal value as the TypeScript type.\n *\n * @param expectedValue - The value that the schema must exactly match.\n * @returns - The schema instance restricted to the specified value, with the literal value inferred as the TypeScript type\n *\n * @example - number().equalTo(42); // Infers the type 42\n */\n equalTo<Y extends number>(expectedValue: Y): WithNumber<this, Y> {\n return this.custom(equalTo(expectedValue)) as WithNumber<this, Y>;\n }\n}\n\nexport type WithNumber<T extends NumberSchema, Y = number> = T & { validation_number: Y };\nexport type ExtractFromNumber<T> = T extends WithNumber<NumberSchema, infer Y> ? Y : never;\n","import { NumberSchema } from '../../schemas/NumberSchema';\n\n/**\n * Creates a new schema for validating number values.\n *\n * @returns {NumberSchema} A new instance of `NumberSchema` for validating numbers.\n *\n * @example\n * const schema = number();\n * parseSchema(schema, 42); // Validates successfully\n * parseSchema(schema, '42'); // Throws a validation error\n */\nexport function number(): NumberSchema {\n return new NumberSchema({ type: ['number'], requiredValidations: [] });\n}\n","import { equalTo } from '../asserts/common/equalTo';\nimport { CommonSchema } from './CommonSchema';\n\nexport class StringSchema extends CommonSchema {\n _string = 1;\n\n /**\n * Restricts the schema to exactly match the specified value and infers the literal value as the TypeScript type.\n *\n * @param expectedValue - The value that the schema must exactly match.\n * @returns - The schema instance restricted to the specified value, with the literal value inferred as the TypeScript type\n *\n * @example - string().equalTo('hello'); // Infers the type 'hello'\n */\n equalTo<Y extends string>(expectedValue: Y): WithString<this, Y> {\n return this.custom(equalTo(expectedValue)) as WithString<this, Y>;\n }\n}\n\nexport type WithString<T extends StringSchema, Y = string> = T & { validation_string: Y };\nexport type ExtractFromString<T> = T extends WithString<StringSchema, infer Y> ? Y : never;\n","import { StringSchema } from '../../schemas/StringSchema';\n\n/**\n * Creates a new schema for validating string values.\n *\n * @returns {StringSchema} A new instance of `StringSchema` for validating strings.\n *\n * @example\n * const schema = string();\n * parseSchema(schema, 'hello'); // Validates successfully\n * parseSchema(schema, 123); // Throws a validation error\n */\nexport function string(): StringSchema {\n return new StringSchema({ type: ['string'], requiredValidations: [] });\n}\n","import { CommonSchema } from './CommonSchema';\nimport { throwException } from '../exceptions';\n\nconst isBoolean = (expected: boolean) => (received: boolean, pathToError: string) => {\n if (received !== expected) throwException(expected, received, pathToError, `The received value is not ${expected}`);\n};\n\nexport class BooleanSchema extends CommonSchema {\n _boolean = 1;\n\n /**\n * Restricts the schema to exactly match the boolean value true and infers the true value as the TypeScript type.\n *\n * @returns - The schema instance restricted to the value true, with the true value inferred as the TypeScript type\n *\n * @example - boolean().onlyTrue(); // Infers the type true\n */\n onlyTrue(): WithBoolean<this, true> {\n return this.custom(isBoolean(true)) as WithBoolean<this, true>;\n }\n\n /**\n * Restricts the schema to exactly match the boolean value false and infers the false value as the TypeScript type.\n *\n * @returns - The schema instance restricted to the value false, with the false value inferred as the TypeScript type\n *\n * @example - boolean().onlyFalse(); // Infers the type false\n */\n onlyFalse(): WithBoolean<this, false> {\n return this.custom(isBoolean(false)) as WithBoolean<this, false>;\n }\n}\n\nexport type WithBoolean<T extends BooleanSchema, Y = boolean> = T & { validation_boolean: Y };\nexport type ExtractFromBoolean<T> = T extends WithBoolean<BooleanSchema, infer Y> ? Y : never;\n","import { BooleanSchema } from '../../schemas/BooleanSchema';\n\n/**\n * Creates a new schema for validating boolean values.\n *\n * @returns {BooleanSchema} A new instance of `BooleanSchema` for validating booleans.\n *\n * @example\n * const schema = boolean();\n * parseSchema(schema, true); // Validates successfully\n * parseSchema(schema, 'true'); // Throws a validation error\n */\nexport function boolean(): BooleanSchema {\n return new BooleanSchema({ type: ['boolean'], requiredValidations: [] });\n}\n","import { ctxSymbol } from '../core';\nimport { BuildSchemaError } from '../exceptions';\nimport { CommonSchema, ValidatorContext } from './CommonSchema';\n\nexport class ArraySchema extends CommonSchema {\n _array = 1;\n constructor(ctx: ValidatorContext, arraySchema: CommonSchema) {\n super(ctx);\n this.validateArrayEntry(arraySchema);\n this[ctxSymbol].array = arraySchema;\n }\n\n private validateArrayEntry(arraySchema: CommonSchema) {\n if (!arraySchema) throw new BuildSchemaError('Missing schema in array method');\n if (!(arraySchema instanceof CommonSchema)) throw new BuildSchemaError('Invalid schema in array method');\n }\n}\n\nexport type WithArray<Y extends CommonSchema> = ArraySchema & { validation_array: Y };\nexport type ExtractFromArray<T> = T extends WithArray<infer X> ? X : never;\n","import { ArraySchema, WithArray } from '../../schemas/ArraySchema';\nimport { CommonSchema } from '../../schemas/CommonSchema';\n\n/**\n * Creates a new schema for validating arrays where each element must match the specified schema.\n *\n * @template T\n * @param {T} arraySchema - The schema that each element of the array must match.\n * @returns {WithArray<T>} A new instance of `ArraySchema` for validating arrays of elements that match the specified schema.\n *\n * @example\n * const schema = array(string());\n * parseSchema(schema, ['hello', 'world']); // Validates successfully\n * parseSchema(schema, ['hello', 123]); // Throws a validation error\n */\nexport function array<T extends CommonSchema>(arraySchema: T): WithArray<T> {\n return new ArraySchema({ type: [], requiredValidations: [] }, arraySchema) as WithArray<T>;\n}\n","import { ctxSymbol } from '../core';\nimport { BuildSchemaError } from '../exceptions';\nimport { CommonSchema, ObjectShapeSchemaType, ValidatorContext } from './CommonSchema';\n\nexport class ObjectSchema extends CommonSchema {\n _object = 1;\n constructor(ctx: ValidatorContext, shapeSchema: ObjectShapeSchemaType) {\n super(ctx);\n this.validateObjectEntry(shapeSchema);\n this[ctxSymbol].object = shapeSchema;\n }\n\n private validateObjectEntry(shapeSchema: ObjectShapeSchemaType) {\n if (!shapeSchema) throw new BuildSchemaError('Missing schema in object method');\n if (shapeSchema instanceof CommonSchema) throw new BuildSchemaError('Invalid schema in object');\n for (const [key, value] of Object.entries(shapeSchema)) {\n if (!(value instanceof CommonSchema))\n throw new BuildSchemaError(`Invalid schema in object method for property '${key}'`);\n }\n }\n}\n\nexport type WithObject<Y extends ObjectShapeSchemaType> = ObjectSchema & { validation_object: Y };\n","import { ObjectShapeSchemaType } from '../../schemas/CommonSchema';\nimport { ObjectSchema, WithObject } from '../../schemas/ObjectSchema';\n\n/**\n * Creates a new schema for validating objects where each property must match the specified schema.\n *\n * @template T\n * @param {T} shapeSchema - The schema that each property of the object must match.\n * @returns {WithObject<T>} A new instance of `ObjectSchema` for validating objects with properties matching the specified schema.\n *\n * @example\n * const schema = object({\n * name: string(),\n * age: number()\n * });\n * parseSchema(schema, { name: 'John', age: 30 }); // Validates successfully\n * parseSchema(schema, { name: 'John', age: '30' }); // Throws a validation error\n */\nexport function object<T extends ObjectShapeSchemaType>(shapeSchema: T): WithObject<T> {\n return new ObjectSchema({ type: [], requiredValidations: [] }, shapeSchema) as WithObject<T>;\n}\n","import { CommonSchema, MapMixTypes, PrimitiveType, WithMix } from '../../schemas/CommonSchema';\n\n/**\n * Creates a new schema for validating values that can match any one of the specified primitive types.\n *\n * @template T\n * @param {T} valueTypes - An array of primitive types that the value can match.\n * @returns {WithMix<MapMixTypes<T>>} A new schema for validating values that can match any of the specified types.\n *\n * @example\n * const schema = oneOfTypes(['string', 'number']);\n * parseSchema(schema, 'hello'); // Validates successfully\n * parseSchema(schema, 42); // Validates successfully\n * parseSchema(schema, true); // Throws a validation error\n */\nexport function oneOfTypes<T extends PrimitiveType[]>(valueTypes: T): WithMix<MapMixTypes<T>> {\n return new CommonSchema({ type: valueTypes, requiredValidations: [] }) as WithMix<MapMixTypes<T>>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AE,CAAC;AACvE;","names":["schema"]}
|
package/lib/index.mjs
CHANGED
|
@@ -251,12 +251,15 @@ function oneOfTypes(valueTypes) {
|
|
|
251
251
|
return new CommonSchema({ type: valueTypes, requiredValidations: [] });
|
|
252
252
|
}
|
|
253
253
|
export {
|
|
254
|
+
BuildSchemaError,
|
|
255
|
+
ValidationError,
|
|
254
256
|
array,
|
|
255
257
|
boolean,
|
|
256
258
|
number,
|
|
257
259
|
object,
|
|
258
260
|
oneOfTypes,
|
|
259
261
|
parseSchema,
|
|
260
|
-
string
|
|
262
|
+
string,
|
|
263
|
+
throwException
|
|
261
264
|
};
|
|
262
265
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { InferType } from './InferType.mjs';
|
|
2
|
+
import { C as CommonSchema } from './CommonSchema-BIe85W_A.mjs';
|
|
3
|
+
import './schemas/ArraySchema.mjs';
|
|
4
|
+
import './schemas/BooleanSchema.mjs';
|
|
5
|
+
import './schemas/NumberSchema.mjs';
|
|
6
|
+
import './schemas/ObjectSchema.mjs';
|
|
7
|
+
import './schemas/StringSchema.mjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Parses and validates a value against the provided schema, returning a type-safe result.
|
|
11
|
+
*
|
|
12
|
+
* This function will throw a `ValidationError` if the value does not conform to the schema.
|
|
13
|
+
* The inferred TypeScript type of the returned value will match the structure defined by the schema.
|
|
14
|
+
*
|
|
15
|
+
* @template T
|
|
16
|
+
* @param {T} schema - The schema to validate the received value against. This schema dictates the expected structure and type of the value.
|
|
17
|
+
* @param {unknown} receivedValue - The value to be validated and parsed according to the schema.
|
|
18
|
+
* @returns {InferType<T>} The validated value, with its TypeScript type inferred from the schema.
|
|
19
|
+
*
|
|
20
|
+
* @throws {ValidationError} If the received value does not match the schema, a `ValidationError` will be thrown.
|
|
21
|
+
* @throws {Error} If an unexpected error occurs during validation, an error will be thrown with a generic message.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* const schema = object({
|
|
25
|
+
* name: string(),
|
|
26
|
+
* age: number(),
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* const result = parseSchema(schema, { name: 'Alice', age: 30 });
|
|
30
|
+
* // result will be inferred as { name: string; age: number }
|
|
31
|
+
*
|
|
32
|
+
* parseSchema(schema, { name: 'Alice', age: '30' });
|
|
33
|
+
* // Throws ValidationError because 'age' should be a number, not a string.
|
|
34
|
+
*/
|
|
35
|
+
declare function parseSchema<T extends CommonSchema>(schema: T, receivedValue: unknown): InferType<T>;
|
|
36
|
+
|
|
37
|
+
export { parseSchema };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { InferType } from './InferType.js';
|
|
2
|
+
import { C as CommonSchema } from './CommonSchema-BIe85W_A.js';
|
|
3
|
+
import './schemas/ArraySchema.js';
|
|
4
|
+
import './schemas/BooleanSchema.js';
|
|
5
|
+
import './schemas/NumberSchema.js';
|
|
6
|
+
import './schemas/ObjectSchema.js';
|
|
7
|
+
import './schemas/StringSchema.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Parses and validates a value against the provided schema, returning a type-safe result.
|
|
11
|
+
*
|
|
12
|
+
* This function will throw a `ValidationError` if the value does not conform to the schema.
|
|
13
|
+
* The inferred TypeScript type of the returned value will match the structure defined by the schema.
|
|
14
|
+
*
|
|
15
|
+
* @template T
|
|
16
|
+
* @param {T} schema - The schema to validate the received value against. This schema dictates the expected structure and type of the value.
|
|
17
|
+
* @param {unknown} receivedValue - The value to be validated and parsed according to the schema.
|
|
18
|
+
* @returns {InferType<T>} The validated value, with its TypeScript type inferred from the schema.
|
|
19
|
+
*
|
|
20
|
+
* @throws {ValidationError} If the received value does not match the schema, a `ValidationError` will be thrown.
|
|
21
|
+
* @throws {Error} If an unexpected error occurs during validation, an error will be thrown with a generic message.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* const schema = object({
|
|
25
|
+
* name: string(),
|
|
26
|
+
* age: number(),
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* const result = parseSchema(schema, { name: 'Alice', age: 30 });
|
|
30
|
+
* // result will be inferred as { name: string; age: number }
|
|
31
|
+
*
|
|
32
|
+
* parseSchema(schema, { name: 'Alice', age: '30' });
|
|
33
|
+
* // Throws ValidationError because 'age' should be a number, not a string.
|
|
34
|
+
*/
|
|
35
|
+
declare function parseSchema<T extends CommonSchema>(schema: T, receivedValue: unknown): InferType<T>;
|
|
36
|
+
|
|
37
|
+
export { parseSchema };
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/parseSchema.ts
|
|
21
|
+
var parseSchema_exports = {};
|
|
22
|
+
__export(parseSchema_exports, {
|
|
23
|
+
parseSchema: () => parseSchema
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(parseSchema_exports);
|
|
26
|
+
|
|
27
|
+
// src/exceptions.ts
|
|
28
|
+
var ValidationError = class extends Error {
|
|
29
|
+
expected;
|
|
30
|
+
received;
|
|
31
|
+
pathToError;
|
|
32
|
+
message;
|
|
33
|
+
constructor(expected, received, pathToError, message) {
|
|
34
|
+
super();
|
|
35
|
+
this.expected = expected;
|
|
36
|
+
this.received = received;
|
|
37
|
+
this.pathToError = pathToError;
|
|
38
|
+
this.message = message;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
function throwException(expected, received, pathToError, message) {
|
|
42
|
+
throw new ValidationError(expected, received, pathToError, message);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/core.ts
|
|
46
|
+
var ctxSymbol = Symbol("contextSymbol");
|
|
47
|
+
function innerCheck(schema, receivedValue, pathToError) {
|
|
48
|
+
const ctx = schema[ctxSymbol];
|
|
49
|
+
if (receivedValue === void 0) {
|
|
50
|
+
if (!ctx.isOptional) throwException("Required", receivedValue, pathToError, "The required value is missing");
|
|
51
|
+
return receivedValue;
|
|
52
|
+
}
|
|
53
|
+
if (receivedValue === null) {
|
|
54
|
+
if (!ctx.isNullable) throwException("Not null", receivedValue, pathToError, "Value should not be null");
|
|
55
|
+
return receivedValue;
|
|
56
|
+
}
|
|
57
|
+
if (ctx.array) {
|
|
58
|
+
if (!Array.isArray(receivedValue))
|
|
59
|
+
throwException("Array", receivedValue, pathToError, "Expected an array but received a different type");
|
|
60
|
+
const schema2 = ctx.array;
|
|
61
|
+
receivedValue.forEach((elem, i) => {
|
|
62
|
+
innerCheck(schema2, elem, `${pathToError}[${i}]`);
|
|
63
|
+
});
|
|
64
|
+
return receivedValue;
|
|
65
|
+
}
|
|
66
|
+
const typeOfVal = typeof receivedValue;
|
|
67
|
+
if (ctx.object) {
|
|
68
|
+
if (typeOfVal !== "object")
|
|
69
|
+
throwException("Object", receivedValue, pathToError, "Expected an object but received a different type");
|
|
70
|
+
if (Array.isArray(receivedValue))
|
|
71
|
+
throwException(
|
|
72
|
+
"Object",
|
|
73
|
+
receivedValue,
|
|
74
|
+
pathToError,
|
|
75
|
+
"Expected an object but received an array. Invalid type of data"
|
|
76
|
+
);
|
|
77
|
+
const shapeSchema = ctx.object;
|
|
78
|
+
for (const keyPerReceivedValue of Object.keys(receivedValue)) {
|
|
79
|
+
if (shapeSchema[keyPerReceivedValue] === void 0)
|
|
80
|
+
throwException("Not allowed", keyPerReceivedValue, pathToError, "This key is not allowed in the object");
|
|
81
|
+
}
|
|
82
|
+
for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {
|
|
83
|
+
const receivedObjectValuePropery = receivedValue[keyOfSchema];
|
|
84
|
+
if (receivedObjectValuePropery === void 0) {
|
|
85
|
+
if (!valueOfSchema[ctxSymbol].isOptional)
|
|
86
|
+
throwException(
|
|
87
|
+
"Required",
|
|
88
|
+
receivedObjectValuePropery,
|
|
89
|
+
pathToError,
|
|
90
|
+
"Missing required property in the object"
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);
|
|
94
|
+
}
|
|
95
|
+
return receivedValue;
|
|
96
|
+
}
|
|
97
|
+
if (ctx.type.length) {
|
|
98
|
+
if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, "Invalid type of data");
|
|
99
|
+
}
|
|
100
|
+
ctx.requiredValidations.forEach((requiredValidation) => {
|
|
101
|
+
requiredValidation(receivedValue, pathToError);
|
|
102
|
+
});
|
|
103
|
+
return receivedValue;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// src/parseSchema.ts
|
|
107
|
+
function parseSchema(schema, receivedValue) {
|
|
108
|
+
try {
|
|
109
|
+
return innerCheck(schema, receivedValue, "");
|
|
110
|
+
} catch (e) {
|
|
111
|
+
if (e instanceof ValidationError) throw e;
|
|
112
|
+
throw new Error("Something unexpected happened");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
116
|
+
0 && (module.exports = {
|
|
117
|
+
parseSchema
|
|
118
|
+
});
|
|
119
|
+
//# sourceMappingURL=parseSchema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/parseSchema.ts","../src/exceptions.ts","../src/core.ts"],"sourcesContent":["import { InferType } from './InferType';\nimport { innerCheck } from './core';\nimport { ValidationError } from './exceptions';\nimport { CommonSchema } from './schemas/CommonSchema';\n\n/**\n * Parses and validates a value against the provided schema, returning a type-safe result.\n *\n * This function will throw a `ValidationError` if the value does not conform to the schema.\n * The inferred TypeScript type of the returned value will match the structure defined by the schema.\n *\n * @template T\n * @param {T} schema - The schema to validate the received value against. This schema dictates the expected structure and type of the value.\n * @param {unknown} receivedValue - The value to be validated and parsed according to the schema.\n * @returns {InferType<T>} The validated value, with its TypeScript type inferred from the schema.\n *\n * @throws {ValidationError} If the received value does not match the schema, a `ValidationError` will be thrown.\n * @throws {Error} If an unexpected error occurs during validation, an error will be thrown with a generic message.\n *\n * @example\n * const schema = object({\n * name: string(),\n * age: number(),\n * });\n *\n * const result = parseSchema(schema, { name: 'Alice', age: 30 });\n * // result will be inferred as { name: string; age: number }\n *\n * parseSchema(schema, { name: 'Alice', age: '30' });\n * // Throws ValidationError because 'age' should be a number, not a string.\n */\nexport function parseSchema<T extends CommonSchema>(schema: T, receivedValue: unknown): InferType<T> {\n try {\n return innerCheck(schema, receivedValue, '') as InferType<T>;\n } catch (e) {\n if (e instanceof ValidationError) throw e;\n /* istanbul ignore next */\n throw new Error('Something unexpected happened');\n }\n}\n","export class ValidationError extends Error {\n expected: unknown;\n received: unknown;\n pathToError: string;\n message: string;\n constructor(expected: unknown, received: unknown, pathToError: string, message: string) {\n super();\n this.expected = expected;\n this.received = received;\n this.pathToError = pathToError;\n this.message = message;\n }\n}\n\nexport class BuildSchemaError extends Error {}\n\nexport function throwException(expected: unknown, received: unknown, pathToError: string, message: string): never {\n throw new ValidationError(expected, received, pathToError, message);\n}\n","export const ctxSymbol = Symbol('contextSymbol');\n\nimport { throwException } from './exceptions';\nimport type { CommonSchema } from './schemas/CommonSchema';\n\nexport function innerCheck(schema: CommonSchema, receivedValue: unknown, pathToError: string) {\n const ctx = schema[ctxSymbol];\n if (receivedValue === undefined) {\n if (!ctx.isOptional) throwException('Required', receivedValue, pathToError, 'The required value is missing');\n return receivedValue;\n }\n\n if (receivedValue === null) {\n if (!ctx.isNullable) throwException('Not null', receivedValue, pathToError, 'Value should not be null');\n return receivedValue;\n }\n\n if (ctx.array) {\n if (!Array.isArray(receivedValue))\n throwException('Array', receivedValue, pathToError, 'Expected an array but received a different type');\n const schema = ctx.array;\n\n receivedValue.forEach((elem, i) => {\n innerCheck(schema, elem, `${pathToError}[${i}]`);\n });\n\n return receivedValue;\n }\n\n const typeOfVal = typeof receivedValue;\n\n if (ctx.object) {\n if (typeOfVal !== 'object')\n throwException('Object', receivedValue, pathToError, 'Expected an object but received a different type');\n if (Array.isArray(receivedValue))\n throwException(\n 'Object',\n receivedValue,\n pathToError,\n 'Expected an object but received an array. Invalid type of data',\n );\n const shapeSchema = ctx.object;\n for (const keyPerReceivedValue of Object.keys(receivedValue)) {\n if (shapeSchema[keyPerReceivedValue] === undefined)\n throwException('Not allowed', keyPerReceivedValue, pathToError, 'This key is not allowed in the object');\n }\n\n for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {\n const receivedObjectValuePropery = (receivedValue as Record<string, unknown>)[keyOfSchema];\n if (receivedObjectValuePropery === undefined) {\n if (!valueOfSchema[ctxSymbol].isOptional)\n throwException(\n 'Required',\n receivedObjectValuePropery,\n pathToError,\n 'Missing required property in the object',\n );\n }\n innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);\n }\n\n return receivedValue;\n }\n\n if (ctx.type.length) {\n if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, 'Invalid type of data');\n }\n\n ctx.requiredValidations.forEach((requiredValidation) => {\n requiredValidation(receivedValue, pathToError);\n });\n\n return receivedValue;\n}\n"],"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AO,KAAK,aAAa,GAAG;AAC5D,UAAI,YAAY,mBAAmB,MAAM;AACvC,uBAAe,eAAe,qBAAqB,aAAa,uCAAuC;AAAA,IAC3G;AAEA,eAAW,CAAC,aAAa,aAAa,KAAK,OAAO,QAAQ,WAAW,GAAG;AACtE,YAAM,6BAA8B,cAA0C,WAAW;AACzF,UAAI,+BAA+B,QAAW;AAC5C,YAAI,CAAC,cAAc,SAAS,EAAE;AAC5B;AAAA,YACE;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,MACJ;AACA,iBAAW,eAAe,4BAA4B,GAAG,WAAW,IAAI,WAAW,EAAE;AAAA,IACvF;AAEA,WAAO;AAAA,EACT;AAEA,MAAI,IAAI,KAAK,QAAQ;AACnB,QAAI,CAAC,IAAI,KAAK,SAAS,SAAS,EAAG,gBAAe,IAAI,MAAM,WAAW,aAAa,sBAAsB;AAAA,EAC5G;AAEA,MAAI,oBAAoB,QAAQ,CAAC,uBAAuB;AACtD,uBAAmB,eAAe,WAAW;AAAA,EAC/C,CAAC;AAED,SAAO;AACT;;;AF1CO,SAAS,YAAoC,QAAW,eAAsC;AACnG,MAAI;AACF,WAAO,WAAW,QAAQ,eAAe,EAAE;AAAA,EAC7C,SAAS,GAAG;AACV,QAAI,aAAa,gBAAiB,OAAM;AAExC,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACjD;AACF;","names":["schema"]}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// src/exceptions.ts
|
|
2
|
+
var ValidationError = class extends Error {
|
|
3
|
+
expected;
|
|
4
|
+
received;
|
|
5
|
+
pathToError;
|
|
6
|
+
message;
|
|
7
|
+
constructor(expected, received, pathToError, message) {
|
|
8
|
+
super();
|
|
9
|
+
this.expected = expected;
|
|
10
|
+
this.received = received;
|
|
11
|
+
this.pathToError = pathToError;
|
|
12
|
+
this.message = message;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
function throwException(expected, received, pathToError, message) {
|
|
16
|
+
throw new ValidationError(expected, received, pathToError, message);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// src/core.ts
|
|
20
|
+
var ctxSymbol = Symbol("contextSymbol");
|
|
21
|
+
function innerCheck(schema, receivedValue, pathToError) {
|
|
22
|
+
const ctx = schema[ctxSymbol];
|
|
23
|
+
if (receivedValue === void 0) {
|
|
24
|
+
if (!ctx.isOptional) throwException("Required", receivedValue, pathToError, "The required value is missing");
|
|
25
|
+
return receivedValue;
|
|
26
|
+
}
|
|
27
|
+
if (receivedValue === null) {
|
|
28
|
+
if (!ctx.isNullable) throwException("Not null", receivedValue, pathToError, "Value should not be null");
|
|
29
|
+
return receivedValue;
|
|
30
|
+
}
|
|
31
|
+
if (ctx.array) {
|
|
32
|
+
if (!Array.isArray(receivedValue))
|
|
33
|
+
throwException("Array", receivedValue, pathToError, "Expected an array but received a different type");
|
|
34
|
+
const schema2 = ctx.array;
|
|
35
|
+
receivedValue.forEach((elem, i) => {
|
|
36
|
+
innerCheck(schema2, elem, `${pathToError}[${i}]`);
|
|
37
|
+
});
|
|
38
|
+
return receivedValue;
|
|
39
|
+
}
|
|
40
|
+
const typeOfVal = typeof receivedValue;
|
|
41
|
+
if (ctx.object) {
|
|
42
|
+
if (typeOfVal !== "object")
|
|
43
|
+
throwException("Object", receivedValue, pathToError, "Expected an object but received a different type");
|
|
44
|
+
if (Array.isArray(receivedValue))
|
|
45
|
+
throwException(
|
|
46
|
+
"Object",
|
|
47
|
+
receivedValue,
|
|
48
|
+
pathToError,
|
|
49
|
+
"Expected an object but received an array. Invalid type of data"
|
|
50
|
+
);
|
|
51
|
+
const shapeSchema = ctx.object;
|
|
52
|
+
for (const keyPerReceivedValue of Object.keys(receivedValue)) {
|
|
53
|
+
if (shapeSchema[keyPerReceivedValue] === void 0)
|
|
54
|
+
throwException("Not allowed", keyPerReceivedValue, pathToError, "This key is not allowed in the object");
|
|
55
|
+
}
|
|
56
|
+
for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {
|
|
57
|
+
const receivedObjectValuePropery = receivedValue[keyOfSchema];
|
|
58
|
+
if (receivedObjectValuePropery === void 0) {
|
|
59
|
+
if (!valueOfSchema[ctxSymbol].isOptional)
|
|
60
|
+
throwException(
|
|
61
|
+
"Required",
|
|
62
|
+
receivedObjectValuePropery,
|
|
63
|
+
pathToError,
|
|
64
|
+
"Missing required property in the object"
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);
|
|
68
|
+
}
|
|
69
|
+
return receivedValue;
|
|
70
|
+
}
|
|
71
|
+
if (ctx.type.length) {
|
|
72
|
+
if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, "Invalid type of data");
|
|
73
|
+
}
|
|
74
|
+
ctx.requiredValidations.forEach((requiredValidation) => {
|
|
75
|
+
requiredValidation(receivedValue, pathToError);
|
|
76
|
+
});
|
|
77
|
+
return receivedValue;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// src/parseSchema.ts
|
|
81
|
+
function parseSchema(schema, receivedValue) {
|
|
82
|
+
try {
|
|
83
|
+
return innerCheck(schema, receivedValue, "");
|
|
84
|
+
} catch (e) {
|
|
85
|
+
if (e instanceof ValidationError) throw e;
|
|
86
|
+
throw new Error("Something unexpected happened");
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
export {
|
|
90
|
+
parseSchema
|
|
91
|
+
};
|
|
92
|
+
//# sourceMappingURL=parseSchema.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/exceptions.ts","../src/core.ts","../src/parseSchema.ts"],"sourcesContent":["export class ValidationError extends Error {\n expected: unknown;\n received: unknown;\n pathToError: string;\n message: string;\n constructor(expected: unknown, received: unknown, pathToError: string, message: string) {\n super();\n this.expected = expected;\n this.received = received;\n this.pathToError = pathToError;\n this.message = message;\n }\n}\n\nexport class BuildSchemaError extends Error {}\n\nexport function throwException(expected: unknown, received: unknown, pathToError: string, message: string): never {\n throw new ValidationError(expected, received, pathToError, message);\n}\n","export const ctxSymbol = Symbol('contextSymbol');\n\nimport { throwException } from './exceptions';\nimport type { CommonSchema } from './schemas/CommonSchema';\n\nexport function innerCheck(schema: CommonSchema, receivedValue: unknown, pathToError: string) {\n const ctx = schema[ctxSymbol];\n if (receivedValue === undefined) {\n if (!ctx.isOptional) throwException('Required', receivedValue, pathToError, 'The required value is missing');\n return receivedValue;\n }\n\n if (receivedValue === null) {\n if (!ctx.isNullable) throwException('Not null', receivedValue, pathToError, 'Value should not be null');\n return receivedValue;\n }\n\n if (ctx.array) {\n if (!Array.isArray(receivedValue))\n throwException('Array', receivedValue, pathToError, 'Expected an array but received a different type');\n const schema = ctx.array;\n\n receivedValue.forEach((elem, i) => {\n innerCheck(schema, elem, `${pathToError}[${i}]`);\n });\n\n return receivedValue;\n }\n\n const typeOfVal = typeof receivedValue;\n\n if (ctx.object) {\n if (typeOfVal !== 'object')\n throwException('Object', receivedValue, pathToError, 'Expected an object but received a different type');\n if (Array.isArray(receivedValue))\n throwException(\n 'Object',\n receivedValue,\n pathToError,\n 'Expected an object but received an array. Invalid type of data',\n );\n const shapeSchema = ctx.object;\n for (const keyPerReceivedValue of Object.keys(receivedValue)) {\n if (shapeSchema[keyPerReceivedValue] === undefined)\n throwException('Not allowed', keyPerReceivedValue, pathToError, 'This key is not allowed in the object');\n }\n\n for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {\n const receivedObjectValuePropery = (receivedValue as Record<string, unknown>)[keyOfSchema];\n if (receivedObjectValuePropery === undefined) {\n if (!valueOfSchema[ctxSymbol].isOptional)\n throwException(\n 'Required',\n receivedObjectValuePropery,\n pathToError,\n 'Missing required property in the object',\n );\n }\n innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);\n }\n\n return receivedValue;\n }\n\n if (ctx.type.length) {\n if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, 'Invalid type of data');\n }\n\n ctx.requiredValidations.forEach((requiredValidation) => {\n requiredValidation(receivedValue, pathToError);\n });\n\n return receivedValue;\n}\n","import { InferType } from './InferType';\nimport { innerCheck } from './core';\nimport { ValidationError } from './exceptions';\nimport { CommonSchema } from './schemas/CommonSchema';\n\n/**\n * Parses and validates a value against the provided schema, returning a type-safe result.\n *\n * This function will throw a `ValidationError` if the value does not conform to the schema.\n * The inferred TypeScript type of the returned value will match the structure defined by the schema.\n *\n * @template T\n * @param {T} schema - The schema to validate the received value against. This schema dictates the expected structure and type of the value.\n * @param {unknown} receivedValue - The value to be validated and parsed according to the schema.\n * @returns {InferType<T>} The validated value, with its TypeScript type inferred from the schema.\n *\n * @throws {ValidationError} If the received value does not match the schema, a `ValidationError` will be thrown.\n * @throws {Error} If an unexpected error occurs during validation, an error will be thrown with a generic message.\n *\n * @example\n * const schema = object({\n * name: string(),\n * age: number(),\n * });\n *\n * const result = parseSchema(schema, { name: 'Alice', age: 30 });\n * // result will be inferred as { name: string; age: number }\n *\n * parseSchema(schema, { name: 'Alice', age: '30' });\n * // Throws ValidationError because 'age' should be a number, not a string.\n */\nexport function parseSchema<T extends CommonSchema>(schema: T, receivedValue: unknown): InferType<T> {\n try {\n return innerCheck(schema, receivedValue, '') as InferType<T>;\n } catch (e) {\n if (e instanceof ValidationError) throw e;\n /* istanbul ignore next */\n throw new Error('Something unexpected happened');\n }\n}\n"],"mappings":";AAAO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,UAAmB,UAAmB,aAAqB,SAAiB;AACtF,UAAM;AACN,SAAK,WAAW;AAChB,SAAK,WAAW;AAChB,SAAK,cAAc;AACnB,SAAK,UAAU;AAAA,EACjB;AACF;AAIO,SAAS,eAAe,UAAmB,UAAmB,aAAqB,SAAwB;AAChH,QAAM,IAAI,gBAAgB,UAAU,UAAU,aAAa,OAA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W,IAAI,WAAW,EAAE;AAAA,IACvF;AAEA,WAAO;AAAA,EACT;AAEA,MAAI,IAAI,KAAK,QAAQ;AACnB,QAAI,CAAC,IAAI,KAAK,SAAS,SAAS,EAAG,gBAAe,IAAI,MAAM,WAAW,aAAa,sBAAsB;AAAA,EAC5G;AAEA,MAAI,oBAAoB,QAAQ,CAAC,uBAAuB;AACtD,uBAAmB,eAAe,WAAW;AAAA,EAC/C,CAAC;AAED,SAAO;AACT;;;AC1CO,SAAS,YAAoC,QAAW,eAAsC;AACnG,MAAI;AACF,WAAO,WAAW,QAAQ,eAAe,EAAE;AAAA,EAC7C,SAAS,GAAG;AACV,QAAI,aAAa,gBAAiB,OAAM;AAExC,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACjD;AACF;","names":["schema"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { C as CommonSchema, V as ValidatorContext } from '../CommonSchema-BIe85W_A.mjs';
|
|
2
|
+
|
|
3
|
+
declare class ArraySchema extends CommonSchema {
|
|
4
|
+
_array: number;
|
|
5
|
+
constructor(ctx: ValidatorContext, arraySchema: CommonSchema);
|
|
6
|
+
private validateArrayEntry;
|
|
7
|
+
}
|
|
8
|
+
type WithArray<Y extends CommonSchema> = ArraySchema & {
|
|
9
|
+
validation_array: Y;
|
|
10
|
+
};
|
|
11
|
+
type ExtractFromArray<T> = T extends WithArray<infer X> ? X : never;
|
|
12
|
+
|
|
13
|
+
export { ArraySchema, type ExtractFromArray, type WithArray };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { C as CommonSchema, V as ValidatorContext } from '../CommonSchema-BIe85W_A.js';
|
|
2
|
+
|
|
3
|
+
declare class ArraySchema extends CommonSchema {
|
|
4
|
+
_array: number;
|
|
5
|
+
constructor(ctx: ValidatorContext, arraySchema: CommonSchema);
|
|
6
|
+
private validateArrayEntry;
|
|
7
|
+
}
|
|
8
|
+
type WithArray<Y extends CommonSchema> = ArraySchema & {
|
|
9
|
+
validation_array: Y;
|
|
10
|
+
};
|
|
11
|
+
type ExtractFromArray<T> = T extends WithArray<infer X> ? X : never;
|
|
12
|
+
|
|
13
|
+
export { ArraySchema, type ExtractFromArray, type WithArray };
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/schemas/ArraySchema.ts
|
|
21
|
+
var ArraySchema_exports = {};
|
|
22
|
+
__export(ArraySchema_exports, {
|
|
23
|
+
ArraySchema: () => ArraySchema
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(ArraySchema_exports);
|
|
26
|
+
|
|
27
|
+
// src/exceptions.ts
|
|
28
|
+
var BuildSchemaError = class extends Error {
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// src/core.ts
|
|
32
|
+
var ctxSymbol = Symbol("contextSymbol");
|
|
33
|
+
|
|
34
|
+
// src/schemas/CommonSchema.ts
|
|
35
|
+
var CommonSchema = class {
|
|
36
|
+
[ctxSymbol];
|
|
37
|
+
constructor(ctx) {
|
|
38
|
+
this[ctxSymbol] = ctx;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* @param validators - One or more custom validation functions.
|
|
42
|
+
* @returns {this} The schema instance with the added custom validation.
|
|
43
|
+
*/
|
|
44
|
+
custom(...validators) {
|
|
45
|
+
this[ctxSymbol].requiredValidations.push(...validators);
|
|
46
|
+
return this;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Marks the schema as nullable, allowing the value to be `null`.
|
|
50
|
+
*
|
|
51
|
+
* @returns {WithNull<this>} The schema instance marked as nullable.
|
|
52
|
+
*/
|
|
53
|
+
nullable() {
|
|
54
|
+
this[ctxSymbol].isNullable = true;
|
|
55
|
+
return this;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Marks the schema as optional, allowing the value to be `undefined`.
|
|
59
|
+
*
|
|
60
|
+
* @returns {WithUndefined<this>}} The schema instance marked as optional.
|
|
61
|
+
*/
|
|
62
|
+
optional() {
|
|
63
|
+
this[ctxSymbol].isOptional = true;
|
|
64
|
+
return this;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// src/schemas/ArraySchema.ts
|
|
69
|
+
var ArraySchema = class extends CommonSchema {
|
|
70
|
+
_array = 1;
|
|
71
|
+
constructor(ctx, arraySchema) {
|
|
72
|
+
super(ctx);
|
|
73
|
+
this.validateArrayEntry(arraySchema);
|
|
74
|
+
this[ctxSymbol].array = arraySchema;
|
|
75
|
+
}
|
|
76
|
+
validateArrayEntry(arraySchema) {
|
|
77
|
+
if (!arraySchema) throw new BuildSchemaError("Missing schema in array method");
|
|
78
|
+
if (!(arraySchema instanceof CommonSchema)) throw new BuildSchemaError("Invalid schema in array method");
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
82
|
+
0 && (module.exports = {
|
|
83
|
+
ArraySchema
|
|
84
|
+
});
|
|
85
|
+
//# sourceMappingURL=ArraySchema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/schemas/ArraySchema.ts","../../src/exceptions.ts","../../src/core.ts","../../src/schemas/CommonSchema.ts"],"sourcesContent":["import { ctxSymbol } from '../core';\nimport { BuildSchemaError } from '../exceptions';\nimport { CommonSchema, ValidatorContext } from './CommonSchema';\n\nexport class ArraySchema extends CommonSchema {\n _array = 1;\n constructor(ctx: ValidatorContext, arraySchema: CommonSchema) {\n super(ctx);\n this.validateArrayEntry(arraySchema);\n this[ctxSymbol].array = arraySchema;\n }\n\n private validateArrayEntry(arraySchema: CommonSchema) {\n if (!arraySchema) throw new BuildSchemaError('Missing schema in array method');\n if (!(arraySchema instanceof CommonSchema)) throw new BuildSchemaError('Invalid schema in array method');\n }\n}\n\nexport type WithArray<Y extends CommonSchema> = ArraySchema & { validation_array: Y };\nexport type ExtractFromArray<T> = T extends WithArray<infer X> ? X : never;\n","export class ValidationError extends Error {\n expected: unknown;\n received: unknown;\n pathToError: string;\n message: string;\n constructor(expected: unknown, received: unknown, pathToError: string, message: string) {\n super();\n this.expected = expected;\n this.received = received;\n this.pathToError = pathToError;\n this.message = message;\n }\n}\n\nexport class BuildSchemaError extends Error {}\n\nexport function throwException(expected: unknown, received: unknown, pathToError: string, message: string): never {\n throw new ValidationError(expected, received, pathToError, message);\n}\n","export const ctxSymbol = Symbol('contextSymbol');\n\nimport { throwException } from './exceptions';\nimport type { CommonSchema } from './schemas/CommonSchema';\n\nexport function innerCheck(schema: CommonSchema, receivedValue: unknown, pathToError: string) {\n const ctx = schema[ctxSymbol];\n if (receivedValue === undefined) {\n if (!ctx.isOptional) throwException('Required', receivedValue, pathToError, 'The required value is missing');\n return receivedValue;\n }\n\n if (receivedValue === null) {\n if (!ctx.isNullable) throwException('Not null', receivedValue, pathToError, 'Value should not be null');\n return receivedValue;\n }\n\n if (ctx.array) {\n if (!Array.isArray(receivedValue))\n throwException('Array', receivedValue, pathToError, 'Expected an array but received a different type');\n const schema = ctx.array;\n\n receivedValue.forEach((elem, i) => {\n innerCheck(schema, elem, `${pathToError}[${i}]`);\n });\n\n return receivedValue;\n }\n\n const typeOfVal = typeof receivedValue;\n\n if (ctx.object) {\n if (typeOfVal !== 'object')\n throwException('Object', receivedValue, pathToError, 'Expected an object but received a different type');\n if (Array.isArray(receivedValue))\n throwException(\n 'Object',\n receivedValue,\n pathToError,\n 'Expected an object but received an array. Invalid type of data',\n );\n const shapeSchema = ctx.object;\n for (const keyPerReceivedValue of Object.keys(receivedValue)) {\n if (shapeSchema[keyPerReceivedValue] === undefined)\n throwException('Not allowed', keyPerReceivedValue, pathToError, 'This key is not allowed in the object');\n }\n\n for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {\n const receivedObjectValuePropery = (receivedValue as Record<string, unknown>)[keyOfSchema];\n if (receivedObjectValuePropery === undefined) {\n if (!valueOfSchema[ctxSymbol].isOptional)\n throwException(\n 'Required',\n receivedObjectValuePropery,\n pathToError,\n 'Missing required property in the object',\n );\n }\n innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);\n }\n\n return receivedValue;\n }\n\n if (ctx.type.length) {\n if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, 'Invalid type of data');\n }\n\n ctx.requiredValidations.forEach((requiredValidation) => {\n requiredValidation(receivedValue, pathToError);\n });\n\n return receivedValue;\n}\n","import { ctxSymbol } from '../core';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type RequiredValidation = (received: any, pathToError: string) => void;\nexport type ObjectShapeSchemaType = Record<string, CommonSchema>;\n\nexport type PrimitiveType = 'number' | 'string' | 'boolean' | 'undefined' | 'object' | 'function' | 'symbol' | 'bigint';\nexport interface ValidatorContext {\n type: PrimitiveType[];\n isNullable?: boolean;\n isOptional?: boolean;\n requiredValidations: RequiredValidation[];\n array?: CommonSchema;\n object?: ObjectShapeSchemaType;\n}\n\nexport class CommonSchema {\n [ctxSymbol]: ValidatorContext;\n constructor(ctx: ValidatorContext) {\n this[ctxSymbol] = ctx;\n }\n\n /**\n * @param validators - One or more custom validation functions.\n * @returns {this} The schema instance with the added custom validation.\n */\n custom(...validators: RequiredValidation[]): this {\n this[ctxSymbol].requiredValidations.push(...validators);\n return this;\n }\n\n /**\n * Marks the schema as nullable, allowing the value to be `null`.\n *\n * @returns {WithNull<this>} The schema instance marked as nullable.\n */\n nullable(): WithNull<this> {\n this[ctxSymbol].isNullable = true;\n return this as WithNull<this>;\n }\n\n /**\n * Marks the schema as optional, allowing the value to be `undefined`.\n *\n * @returns {WithUndefined<this>}} The schema instance marked as optional.\n */\n optional(): WithUndefined<this> {\n this[ctxSymbol].isOptional = true;\n return this as WithUndefined<this>;\n }\n}\n\nexport type WithNull<T extends CommonSchema> = T & { validation_null: true };\nexport type WithUndefined<T extends CommonSchema> = T & { validation_undefined: true };\n\ntype TypeMapping = {\n number: number;\n string: string;\n boolean: boolean;\n undefined: undefined;\n object: object;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n function: Function;\n symbol: symbol;\n bigint: bigint;\n};\n\nexport type WithMix<Y = unknown> = CommonSchema & { validation_mix: Y };\nexport type ExtractFromMix<T> = T extends WithMix<infer X> ? X : never;\n\nexport type MapMixTypes<T extends PrimitiveType[]> = T extends (infer U)[]\n ? U extends keyof TypeMapping\n ? TypeMapping[U]\n : never\n : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcO,IAAM,mBAAN,cAA+B,MAAM;AAAC;;;ACdtC,IAAM,YAAY,OAAO,eAAe;;;ACgBxC,IAAM,eAAN,MAAmB;AAAA,EACxB,CAAC,SAAS;AAAA,EACV,YAAY,KAAuB;AACjC,SAAK,SAAS,IAAI;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,UAAU,YAAwC;AAChD,SAAK,SAAS,EAAE,oBAAoB,KAAK,GAAG,UAAU;AACtD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,WAA2B;AACzB,SAAK,SAAS,EAAE,aAAa;AAC7B,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,WAAgC;AAC9B,SAAK,SAAS,EAAE,aAAa;AAC7B,WAAO;AAAA,EACT;AACF;;;AH9CO,IAAM,cAAN,cAA0B,aAAa;AAAA,EAC5C,SAAS;AAAA,EACT,YAAY,KAAuB,aAA2B;AAC5D,UAAM,GAAG;AACT,SAAK,mBAAmB,WAAW;AACnC,SAAK,SAAS,EAAE,QAAQ;AAAA,EAC1B;AAAA,EAEQ,mBAAmB,aAA2B;AACpD,QAAI,CAAC,YAAa,OAAM,IAAI,iBAAiB,gCAAgC;AAC7E,QAAI,EAAE,uBAAuB,cAAe,OAAM,IAAI,iBAAiB,gCAAgC;AAAA,EACzG;AACF;","names":[]}
|