New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

abolish

Package Overview
Dependencies
Maintainers
1
Versions
148
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

abolish - npm Package Compare versions

Comparing version 0.0.1 to 0.0.2

types/index.d.ts

4

index.ts
import Abolish from "./src/Abolish";
import {Rule} from "./src/Functions";
export {Abolish}
// Export Abolish and Rule generator
export {Abolish, Rule}

@@ -8,1 +8,3 @@ "use strict";

exports.Abolish = Abolish_1.default;
const Functions_1 = require("./src/Functions");
exports.Rule = Functions_1.Rule;
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -92,3 +101,29 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

*/
validate(object, rules) {
static validate(object, rules) {
return (new this).validate(object, rules);
}
/**
* Validate Async
*
* Waits for all validation defined
* @param object
* @param rules
* @return {Promise<ValidationResult>}
*/
static validateAsync(object, rules) {
return (new this).validateAsync(object, rules);
}
/**
* Validate
* @description
* Validates given object with rules defined on Abolish instance
* @param {object} object
* @param {object} rules
* @param {boolean} isAsync
*/
validate(object, rules, isAsync = false) {
let asyncData = {
validated: {},
jobs: []
};
/**

@@ -125,38 +160,174 @@ * Check for wildcard rules (*, **)

/**
* Convert ruleData to object if string
* Using StringToRules function
* if ruleData has property of $skip then check
*/
if (typeof ruleData === "string")
ruleData = StringToRules_1.default(ruleData);
let $skip = false;
if (ruleData.hasOwnProperty('$skip')) {
$skip = ruleData['$skip'];
if (typeof $skip === 'function') {
$skip = $skip(validated[rule]);
}
if (typeof $skip !== 'boolean') {
throw new Error(`$skip value or resolved function value must be a BOOLEAN in RuleFor: (${rule})`);
}
}
/**
* Append internal Wildcard data
* Run validation if not $skip
*/
ruleData = Object.assign(Object.assign({}, internalWildcardRules), ruleData);
/**
* Loop through ruleData to check if validators defined exists
*/
for (const validatorName of Object.keys(ruleData)) {
if (!$skip) {
/**
* Throw Error if validator is not defined in global or local validators
* Convert ruleData to object if string
* Using StringToRules function
*/
if (!this.validators.hasOwnProperty(validatorName) && !GlobalValidators_1.default.hasOwnProperty(validatorName)) {
throw new Error(`Validator: {${validatorName}} does not exists but defined in rules`);
}
if (typeof ruleData === "string")
ruleData = StringToRules_1.default(ruleData);
/**
* The value of the validator set in rules
* e.g {must: true}
* where "true" is validationOption
* Append internal Wildcard data
*/
const validatorOption = ruleData[validatorName];
ruleData = Object.assign(Object.assign({}, internalWildcardRules), ruleData);
/**
* Value of key being validated in object
* Loop through ruleData to check if validators defined exists
*/
const objectValue = object[rule];
for (const validatorName of Object.keys(ruleData)) {
/**
* Throw Error if validator is not defined in global or local validators
*/
if (!this.validators.hasOwnProperty(validatorName) && !GlobalValidators_1.default.hasOwnProperty(validatorName)) {
throw new Error(`Validator: {${validatorName}} does not exists but defined in rules`);
}
/**
* Validator of rule defined in rules.
*/
const validator = (this.validators[validatorName] || GlobalValidators_1.default[validatorName]);
if (!isAsync && validator.isAsync) {
throw new Error(`Validator: {${validatorName}} is async, use validateAsync method instead.`);
}
/**
* The value of the validator set in rules
* e.g {must: true}
* where "true" is validationOption
*/
const validatorOption = ruleData[validatorName];
/**
* Value of key being validated in object
*/
const objectValue = validated[rule];
/**
* If is async push needed data to asyncData
*/
if (isAsync) {
asyncData.jobs.push({ rule, validator, validatorName, validatorOption });
}
else {
/**
* Try running validator
*/
let validationResult = false;
try {
/**
* Run Validation
* Passing required helpers
*/
validationResult = validator.validator(objectValue, validatorOption, {
error: (message, data) => new AbolishError_1.default(message, data),
modifier: new ObjectModifier_1.default(validated, rule)
});
}
catch (e) {
/**
* If error when running defined function
* Send error as validationResult with type as 'internal'
*/
return {
error: {
key: rule,
type: 'internal',
validator: validatorName,
message: e.message,
data: e.stack
}
};
}
if (validationResult instanceof AbolishError_1.default) {
return {
error: {
key: rule,
type: 'validator',
validator: validatorName,
message: validationResult.message,
data: validationResult.data
}
};
}
else if (!validationResult) {
/**
* Check if option is stringable
* This is required because a rule option could an array or an object
* and these cannot be converted to string
*
* Only strings and numbers can be parsed as :option
*/
const optionIsStringable = typeof validatorOption === "string" || typeof validatorOption === "number";
/**
* Replace :param with rule converted to upperCase
* and if option is stringable, replace :option with validatorOption
*/
let message = validator.error.replace(':param', Functions_1.UpperFirst(rule));
if (optionIsStringable)
message = message.replace(':option', validatorOption);
// Return Error using the ValidationResult format
return {
error: {
key: rule,
type: 'validator',
validator: validatorName,
message,
data: null
}
};
}
}
}
}
}
if (isAsync) {
asyncData.validated = validated;
return asyncData;
}
// Pick only keys in rules
validated = pick_1.default(validated, keysToBeValidated);
return {
error: false,
validated
};
}
/**
* Validate Async
*
* Waits for all validation defined
* @param object
* @param rules
* @return {Promise<ValidationResult>}
*/
validateAsync(object, rules) {
/**
* Get asyncData
*/
const asyncData = this.validate(object, rules, true);
/**
* Destruct values in async data
*/
const { validated, jobs } = asyncData;
/**
* Return a promise
*/
return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
/**
* Loop through jobs and run their validators
*/
for (const job of jobs) {
const { rule, validator, validatorName, validatorOption } = job;
/**
* Validator of rule defined in rules.
* Value of key being validated in object
*/
const validator = (this.validators[validatorName] || GlobalValidators_1.default[validatorName]);
/**
* Try running
*/
const objectValue = validated[rule];
let validationResult = false;

@@ -168,3 +339,3 @@ try {

*/
validationResult = validator.validator(objectValue, validatorOption, {
validationResult = yield validator.validator(objectValue, validatorOption, {
error: (message, data) => new AbolishError_1.default(message, data),

@@ -179,3 +350,3 @@ modifier: new ObjectModifier_1.default(validated, rule)

*/
return {
return resolve({
error: {

@@ -188,6 +359,6 @@ key: rule,

}
};
});
}
if (validationResult instanceof AbolishError_1.default) {
return {
return resolve({
error: {

@@ -200,3 +371,3 @@ key: rule,

}
};
});
}

@@ -216,7 +387,7 @@ else if (!validationResult) {

*/
let message = validator.error.replace(':param', Functions_1.upperFirst(rule));
let message = validator.error.replace(':param', Functions_1.UpperFirst(rule));
if (optionIsStringable)
message = message.replace(':option', validatorOption);
// Return Error using the ValidationResult format
return {
return resolve({
error: {

@@ -229,14 +400,12 @@ key: rule,

}
};
});
}
}
}
// Pick only keys in rules
validated = pick_1.default(validated, keysToBeValidated);
return {
error: null,
validated
};
return resolve({
error: false,
validated
});
}));
}
}
module.exports = Abolish;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
function upperFirst(str) {
const StringToRules_1 = __importDefault(require("./StringToRules"));
/**
* Change to string to upperFirst
* @param str
* @constructor
*/
function UpperFirst(str) {
return str[0].toUpperCase() + str.substr(1);
}
exports.upperFirst = upperFirst;
exports.UpperFirst = UpperFirst;
/**
* Converts an array of rules (string | object)[] to one object rule
* @example
* const rule = Rule(['must', {min: 10, max: 20}, '!exact'])
* // will return
* { must: true, min: 10, max: 20, exact: false }
*
* @param rules
* @constructor
*/
function Rule(rules) {
/**
* Convert to array if not array.
*/
if (!Array.isArray(rules)) {
rules = [rules];
}
/**
* Stores generated rules
*/
let generatedRule = {};
/**
* Loop Through each rule
*
* 1. convert to object if string
* 2. add rule to generatedRule object
*/
for (let rule of rules) {
if (typeof rule === "string")
rule = StringToRules_1.default(rule);
generatedRule = Object.assign(Object.assign({}, generatedRule), rule);
}
return generatedRule;
}
exports.Rule = Rule;

@@ -27,6 +27,11 @@ "use strict";

},
typeOf: {
name: 'typeOf',
typeof: {
name: 'typeof',
error: ':param is not typeOf :option',
validator: (value, option) => {
/**
* If typeof is false then we don't validate this
*/
if (option === false)
return true;
option = option.toLowerCase();

@@ -33,0 +38,0 @@ if (option === 'array')

{
"name": "abolish",
"version": "0.0.1",
"version": "0.0.2",
"description": "A javascript object validator.",

@@ -19,2 +19,3 @@ "main": "js/index.js",

"@types/node": "^13.9.1",
"axios": "^0.19.2",
"ts-node-dev": "^1.0.0-pre.44",

@@ -21,0 +22,0 @@ "typescript": "^3.8.3"

import {Validator, ValidationResult, ObjectType} from "./Types"
import StringToRules from "./StringToRules";
import GlobalValidators from "./GlobalValidators";
import {upperFirst} from "./Functions";
import {UpperFirst} from "./Functions";
import AbolishError from "./AbolishError";

@@ -99,4 +99,33 @@ import ObjectModifier from "./ObjectModifier";

*/
validate(object: ObjectType, rules: ObjectType): ValidationResult {
static validate(object: ObjectType, rules: ObjectType): ValidationResult {
return (new this).validate(object, rules);
}
/**
* Validate Async
*
* Waits for all validation defined
* @param object
* @param rules
* @return {Promise<ValidationResult>}
*/
static validateAsync(object: ObjectType, rules: ObjectType): Promise<ValidationResult> {
return (new this).validateAsync(object, rules)
}
/**
* Validate
* @description
* Validates given object with rules defined on Abolish instance
* @param {object} object
* @param {object} rules
* @param {boolean} isAsync
*/
validate(object: ObjectType, rules: ObjectType, isAsync = false): ValidationResult {
let asyncData = {
validated: {} as any,
jobs: [] as any
};
/**

@@ -139,48 +168,200 @@ * Check for wildcard rules (*, **)

/**
* Convert ruleData to object if string
* Using StringToRules function
* if ruleData has property of $skip then check
*/
if (typeof ruleData === "string")
ruleData = StringToRules(ruleData);
let $skip: any = false;
/**
* Append internal Wildcard data
*/
ruleData = {...internalWildcardRules, ...ruleData};
if (ruleData.hasOwnProperty('$skip')) {
$skip = ruleData['$skip'];
if (typeof $skip === 'function') {
$skip = $skip(validated[rule])
}
if (typeof $skip !== 'boolean') {
throw new Error(`$skip value or resolved function value must be a BOOLEAN in RuleFor: (${rule})`);
}
}
/**
* Loop through ruleData to check if validators defined exists
* Run validation if not $skip
*/
for (const validatorName of Object.keys(ruleData)) {
if (!$skip) {
/**
* Throw Error if validator is not defined in global or local validators
* Convert ruleData to object if string
* Using StringToRules function
*/
if (!this.validators.hasOwnProperty(validatorName) && !GlobalValidators.hasOwnProperty(validatorName)) {
throw new Error(`Validator: {${validatorName}} does not exists but defined in rules`)
}
if (typeof ruleData === "string")
ruleData = StringToRules(ruleData);
/**
* The value of the validator set in rules
* e.g {must: true}
* where "true" is validationOption
* Append internal Wildcard data
*/
const validatorOption = ruleData[validatorName];
ruleData = {...internalWildcardRules, ...ruleData};
/**
* Value of key being validated in object
* Loop through ruleData to check if validators defined exists
*/
const objectValue = object[rule];
for (const validatorName of Object.keys(ruleData)) {
/**
* Throw Error if validator is not defined in global or local validators
*/
if (!this.validators.hasOwnProperty(validatorName) && !GlobalValidators.hasOwnProperty(validatorName)) {
throw new Error(`Validator: {${validatorName}} does not exists but defined in rules`)
}
/**
* Validator of rule defined in rules.
*/
const validator = (this.validators[validatorName] || GlobalValidators[validatorName]) as Validator;
if (!isAsync && validator.isAsync) {
throw new Error(`Validator: {${validatorName}} is async, use validateAsync method instead.`)
}
/**
* The value of the validator set in rules
* e.g {must: true}
* where "true" is validationOption
*/
const validatorOption = ruleData[validatorName];
/**
* Value of key being validated in object
*/
const objectValue = validated[rule];
/**
* If is async push needed data to asyncData
*/
if (isAsync) {
asyncData.jobs.push({rule, validator, validatorName, validatorOption})
} else {
/**
* Try running validator
*/
let validationResult: any = false;
try {
/**
* Run Validation
* Passing required helpers
*/
validationResult = validator.validator(objectValue, validatorOption, {
error: (message: string, data?: any) => new AbolishError(message, data),
modifier: new ObjectModifier(validated, rule)
});
} catch (e) {
/**
* If error when running defined function
* Send error as validationResult with type as 'internal'
*/
return {
error: {
key: rule,
type: 'internal',
validator: validatorName,
message: e.message,
data: e.stack
}
}
}
if (validationResult instanceof AbolishError) {
return {
error: {
key: rule,
type: 'validator',
validator: validatorName,
message: validationResult.message,
data: validationResult.data
}
}
} else if (!validationResult) {
/**
* Check if option is stringable
* This is required because a rule option could an array or an object
* and these cannot be converted to string
*
* Only strings and numbers can be parsed as :option
*/
const optionIsStringable = typeof validatorOption === "string" || typeof validatorOption === "number";
/**
* Replace :param with rule converted to upperCase
* and if option is stringable, replace :option with validatorOption
*/
let message = validator.error!.replace(':param', UpperFirst(rule));
if (optionIsStringable)
message = message.replace(':option', validatorOption);
// Return Error using the ValidationResult format
return {
error: {
key: rule,
type: 'validator',
validator: validatorName,
message,
data: null
}
}
}
}
}
}
}
if (isAsync) {
asyncData.validated = validated;
return asyncData as any;
}
// Pick only keys in rules
validated = pick(validated, keysToBeValidated);
return {
error: false,
validated
}
}
/**
* Validate Async
*
* Waits for all validation defined
* @param object
* @param rules
* @return {Promise<ValidationResult>}
*/
validateAsync(object: ObjectType, rules: ObjectType): Promise<ValidationResult> {
/**
* Get asyncData
*/
const asyncData: any = this.validate(object, rules, true);
/**
* Destruct values in async data
*/
const {validated, jobs} = asyncData;
/**
* Return a promise
*/
return new Promise<ValidationResult>(async (resolve) => {
/**
* Loop through jobs and run their validators
*/
for (const job of jobs) {
const {rule, validator, validatorName, validatorOption} = job;
/**
* Validator of rule defined in rules.
* Value of key being validated in object
*/
const validator = (this.validators[validatorName] || GlobalValidators[validatorName]) as Validator;
const objectValue = validated[rule];
/**
* Try running
*/
let validationResult: any = false;

@@ -192,3 +373,3 @@ try {

*/
validationResult = validator.validator(objectValue, validatorOption, {
validationResult = await validator.validator(objectValue, validatorOption, {
error: (message: string, data?: any) => new AbolishError(message, data),

@@ -203,3 +384,3 @@ modifier: new ObjectModifier(validated, rule)

*/
return {
return resolve({
error: {

@@ -212,3 +393,3 @@ key: rule,

}
}
})
}

@@ -218,3 +399,3 @@

if (validationResult instanceof AbolishError) {
return {
return resolve({
error: {

@@ -227,3 +408,3 @@ key: rule,

}
}
})
} else if (!validationResult) {

@@ -243,3 +424,3 @@ /**

*/
let message = validator.error!.replace(':param', upperFirst(rule));
let message = validator.error!.replace(':param', UpperFirst(rule));
if (optionIsStringable)

@@ -249,3 +430,3 @@ message = message.replace(':option', validatorOption);

// Return Error using the ValidationResult format
return {
return resolve({
error: {

@@ -258,14 +439,11 @@ key: rule,

}
}
})
}
}
}
// Pick only keys in rules
validated = pick(validated, keysToBeValidated);
return {
error: null,
validated
}
return resolve({
error: false,
validated
})
});
}

@@ -272,0 +450,0 @@ }

@@ -1,3 +0,50 @@

export function upperFirst(str: string): string {
import StringToRules from "./StringToRules";
/**
* Change to string to upperFirst
* @param str
* @constructor
*/
export function UpperFirst(str: string): string {
return str[0].toUpperCase() + str.substr(1)
}
/**
* Converts an array of rules (string | object)[] to one object rule
* @example
* const rule = Rule(['must', {min: 10, max: 20}, '!exact'])
* // will return
* { must: true, min: 10, max: 20, exact: false }
*
* @param rules
* @constructor
*/
export function Rule(rules: any[]): any {
/**
* Convert to array if not array.
*/
if (!Array.isArray(rules)) {
rules = [rules];
}
/**
* Stores generated rules
*/
let generatedRule = {};
/**
* Loop Through each rule
*
* 1. convert to object if string
* 2. add rule to generatedRule object
*/
for (let rule of rules) {
if (typeof rule as string === "string")
rule = StringToRules(rule);
generatedRule = {...generatedRule, ...rule}
}
return generatedRule;
}

@@ -32,6 +32,12 @@ /**

typeOf: {
name: 'typeOf',
typeof: {
name: 'typeof',
error: ':param is not typeOf :option',
validator: (value: any, option: string): boolean => {
validator: (value: any, option: string | false): boolean => {
/**
* If typeof is false then we don't validate this
*/
if (option === false) return true;
option = option.toLowerCase();

@@ -38,0 +44,0 @@ if (option === 'array')

import AbolishError from "./AbolishError";
import ObjectModifier from "./ObjectModifier";
/**
* ValidationError
* @description
* Result returned by the validate object
*/
export type ValidationError = {
key: string
type: 'internal' | 'validator'
message: string
validator: string
data: any
};
/**
* ValidationResult

@@ -10,10 +24,4 @@ * @description

export type ValidationResult = {
error: null | {
key: string
type: 'internal' | 'validator'
message: string
validator: string
data: any
},
validated?: object
error: ValidationError | false,
validated?: any
}

@@ -28,3 +36,3 @@

}
) => boolean | AbolishError
) => boolean | AbolishError | Promise<boolean | AbolishError>

@@ -31,0 +39,0 @@ /**

@@ -5,16 +5,23 @@ {

// "incremental": true, /* Enable incremental compilation */
"target": "ES2016", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": [
"dom",
"es2016"
], /* Specify library files to be included in the compilation. */
"target": "ES2016",
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs",
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": [
"dom",
"es2016"
],
/* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
"declaration": true,
/* Generates corresponding '.d.ts' file. */
"declarationDir": "types",
/* Declaration file directory*/
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "js", /* Redirect output structure to the directory. */
"outDir": "js",
/* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */

@@ -30,3 +37,4 @@ // "composite": true, /* Enable project compilation */

/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"strict": true,
/* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */

@@ -47,3 +55,4 @@ // "strictNullChecks": true, /* Enable strict null checks. */

/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"moduleResolution": "node",
/* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */

@@ -55,3 +64,4 @@ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */

// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"esModuleInterop": true,
/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */

@@ -71,8 +81,9 @@ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
"forceConsistentCasingInFileNames": true
/* Disallow inconsistently-cased references to the same file. */
},
"exclude": [
"play.ts"
"play.ts",
"types"
]
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc