n4s
Version:
Assertion library for form validations
85 lines (74 loc) • 2.66 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('n4s'), require('vest-utils')) :
typeof define === 'function' && define.amd ? define(['exports', 'n4s', 'vest-utils'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.schema = {}, global.n4s, global["vest-utils"]));
})(this, (function (exports, n4s, vestUtils) { 'use strict';
function ruleReturn(pass, message) {
const output = { pass };
return output;
}
function failing() {
return ruleReturn(false);
}
function passing() {
return ruleReturn(true);
}
function defaultToPassing(callback) {
return vestUtils.defaultTo(callback, passing());
}
function runLazyRule(lazyRule, currentValue) {
try {
return lazyRule.run(currentValue);
}
catch (_a) {
return failing();
}
}
function isArrayOf(inputArray, currentRule) {
return defaultToPassing(vestUtils.mapFirst(inputArray, (currentValue, breakout, index) => {
const res = n4s.ctx.run({ value: currentValue, set: true, meta: { index } }, () => runLazyRule(currentRule, currentValue));
breakout(!res.pass, res);
}));
}
function loose(inputObject, shapeObject) {
for (const key in shapeObject) {
const currentValue = inputObject[key];
const currentRule = shapeObject[key];
const res = n4s.ctx.run({ value: currentValue, set: true, meta: { key } }, () => runLazyRule(currentRule, currentValue));
if (!res.pass) {
return res;
}
}
return passing();
}
function optional(value, ruleChain) {
if (vestUtils.isNullish(value)) {
return passing();
}
return runLazyRule(ruleChain, value);
}
function shape(inputObject, shapeObject) {
const baseRes = loose(inputObject, shapeObject);
if (!baseRes.pass) {
return baseRes;
}
for (const key in inputObject) {
if (!vestUtils.hasOwnProperty(shapeObject, key)) {
return failing();
}
}
return passing();
}
// Help needed improving the typings of this file.
// Ideally, we'd be able to extend ShapeObject, but that's not possible.
function partial(shapeObject) {
const output = {};
for (const key in shapeObject) {
output[key] = n4s.enforce.optional(shapeObject[key]);
}
return output;
}
n4s.enforce.extend({ isArrayOf, loose, optional, shape });
exports.partial = partial;
}));
//# sourceMappingURL=schema.development.js.map