veffect
Version:
powerful TypeScript validation library built on the robust foundation of Effect combining exceptional type safety, high performance, and developer experience. Taking inspiration from Effect's functional principles, VEffect delivers a balanced approach tha
183 lines (182 loc) • 8.06 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.oneOf = void 0;
exports.union = union;
/**
* Union schema implementation
*/
const E = __importStar(require("../internal/effect"));
const EffectMod = __importStar(require("effect/Effect"));
const Function_1 = require("effect/Function");
const validator_1 = require("../validator");
const errors_1 = require("../errors");
/**
* Create a union schema
*/
function union(schemas) {
const validations = [];
const schema = {
_tag: 'UnionSchema',
schemas,
// refinement implementation
refine: (refinement, message) => {
validations.push((input, options) => refinement(input)
? E.succeed(input)
: E.fail(new errors_1.UnionValidationError(typeof message === 'function'
? message(input)
: message || 'Failed refinement', [], options === null || options === void 0 ? void 0 : options.path)));
return schema;
},
// transformation implementation
transform: (transformer) => {
return {
_tag: 'TransformedSchema',
toValidator: () => (0, validator_1.createEffectValidator)((input, options) => {
return E.pipe(schema.toValidator().validate(input, options), E.map(value => transformer(value)));
})
};
},
// default value implementation
default: (defaultValue) => {
const defaultSchema = {
...schema,
_tag: 'UnionSchema',
schemas,
toValidator: () => (0, validator_1.createEffectValidator)((input, options) => {
if (input === undefined) {
const value = typeof defaultValue === 'function'
? defaultValue()
: defaultValue;
return E.succeed(value);
}
return schema.toValidator().validate(input, options);
})
};
return defaultSchema;
},
// nullable implementation
nullable: () => {
return {
...schema,
_tag: 'NullableSchema',
toValidator: () => (0, validator_1.createEffectValidator)((input, options) => {
if (input === null) {
return E.succeed(null);
}
return schema.toValidator().validate(input, options);
})
};
},
// optional implementation
optional: () => {
return {
_tag: 'OptionalSchema',
toValidator: () => (0, validator_1.createEffectValidator)((input, options) => {
if (input === undefined) {
return E.succeed(undefined);
}
return schema.toValidator().validate(input, options);
})
};
},
// nullish implementation
nullish: () => {
return {
_tag: 'NullishSchema',
toValidator: () => (0, validator_1.createEffectValidator)((input, options) => {
if (input === null || input === undefined) {
return E.succeed(input);
}
return schema.toValidator().validate(input, options);
})
};
},
// catch-all implementation
catchAll: (fallback) => {
return {
_tag: 'CatchAllSchema',
toValidator: () => (0, validator_1.createEffectValidator)((input, options) => {
return (0, Function_1.pipe)(schema.toValidator().validate(input, options), EffectMod.catchAll((error) => {
const fallbackValue = typeof fallback === 'function'
? fallback(error)
: fallback;
return E.succeed(fallbackValue);
}));
})
};
},
toValidator: () => (0, validator_1.createEffectValidator)((input, options) => {
// Reject null and undefined by default
if (input === null || input === undefined) {
return E.fail(new errors_1.UnionValidationError(`Expected a valid value but received ${input === null ? 'null' : 'undefined'}`, [], options === null || options === void 0 ? void 0 : options.path));
}
// Special handling for empty objects that won't match any schema
if (typeof input === 'object' && !Array.isArray(input) &&
Object.keys(input).length === 0 &&
!schemas.some(s => s._tag === 'EmptyObjectSchema')) {
return E.fail(new errors_1.UnionValidationError(`Empty object doesn't match any schema in the union`, [], options === null || options === void 0 ? void 0 : options.path));
}
// Try to validate with each schema
const schemaValidations = schemas.map(s => {
const validator = s.toValidator();
return E.either(validator.validate(input, options));
});
// If any schema validates successfully, use that result
const result = (0, Function_1.pipe)(E.forEach(schemaValidations, (validation) => validation), E.map((results) => {
// Find the first successful validation
const successResult = results.find(r => E.isRight(r));
if (successResult && E.isRight(successResult)) {
// Return the successful validation result
return successResult.right;
}
// If all validations failed, collect all errors
const errors = results
.filter(r => E.isLeft(r))
.map(r => E.isLeft(r) ? r.left : null)
.filter(Boolean);
// Return union validation error with all schema errors
return E.fail(new errors_1.UnionValidationError('Input failed to match any schema in the union', errors, options === null || options === void 0 ? void 0 : options.path));
}));
// Apply any additional validations
return validations.reduce((acc, validation) => E.flatMap(acc, val => validation(val, options)), result);
})
};
return schema;
}
/**
* Alias for union - Creates a schema that accepts any of the given schemas
*/
exports.oneOf = union;