UNPKG

runtyp

Version:

Lightning-fast, zero-dependency runtime validation for TS/JS. 25x faster than zod with a cleaner API.

48 lines 1.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.object = void 0; function object(schema, options) { if (typeof schema !== 'object') throw new Error('invalid schema, must be object'); return (value) => { if (typeof value !== 'object' || !value) { return { isValid: false, errors: { root: `must be an object with keys ${Object.keys(schema).join(', ')}` } }; } // go through each key in the schema const errors = Object.entries(schema) .reduce((acc, [key, predicate]) => { const result = predicate(value[key]); if (!result.isValid && Object.keys(result.errors).length === 1 && result.errors.root) { // root error acc[key] = result.errors.root; } else if (!result.isValid) { // nested errors Object.entries(result.errors).forEach(([subKey, subMessage]) => { acc[`${key}.${subKey}`] = subMessage; }); } return acc; }, {}); // go through each key in the value if (!options?.allowUnknownKeys) { Object.keys(value).forEach((key) => { if (!schema[key]) { errors[key] = 'unknown key'; } }); } if (Object.keys(errors).length > 0) { return { isValid: false, errors, }; } return { isValid: true, value: value, }; }; } exports.object = object; //# sourceMappingURL=object.js.map