Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add gt lt #4

Merged
merged 15 commits into from
Sep 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:

strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
node-version: [20.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
Expand Down
2 changes: 1 addition & 1 deletion japaFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { configure } = require("japa");

configure({
files: [
// "tests/compiler.spec.ts"
// "tests/validators/number-validators.spec.ts"
"tests/*.spec.ts",
"tests/*/**/*.spec.ts"
]
Expand Down
25 changes: 11 additions & 14 deletions others/yup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,32 @@ import * as Yup from "yup";
import type { TypeOfAbolishOrInstance } from "../src/Abolish";
import type { AbolishValidator } from "../src/types";
import { AddValidatorToClassOrInstance } from "./index";
import type { ValidateOptions } from "yup/es/types";
import type { ValidateOptions, AnySchema } from "yup";

export type YupSchemaOption<T extends Yup.BaseSchema> = { schema: T; options?: ValidateOptions };
export type YupSchemaOption<T extends Yup.AnySchema> = { schema: T; options?: ValidateOptions };
type YupHelper<T> = (y: typeof Yup) => T;

declare module "../src/validator" {
module AvailableValidators {
interface Options {
$yup: Yup.BaseSchema | YupSchemaOption<any>;
$yupAsync: Yup.BaseSchema | YupSchemaOption<any>;
$yup: Yup.AnySchema | YupSchemaOption<any>;
$yupAsync: Yup.AnySchema | YupSchemaOption<any>;
}
}
}

/**
* $yup Schema Helper
*/
export function $yup<T extends Yup.BaseSchema>(
export function $yup<T extends Yup.AnySchema>(
schema: YupHelper<T>,
options?: ValidateOptions
): Record<"$yup", YupSchemaOption<T>>;
export function $yup<T extends Yup.BaseSchema>(
export function $yup<T extends Yup.AnySchema>(
schema: T,
options?: ValidateOptions
): Record<"$yup", YupSchemaOption<T>>;
export function $yup<T extends Yup.BaseSchema>(
schema: T | YupHelper<T>,
options?: ValidateOptions
) {
export function $yup<T extends Yup.AnySchema>(schema: T | YupHelper<T>, options?: ValidateOptions) {
// if input is a function, call it
if (typeof schema === "function") {
schema = schema(Yup) as T;
Expand All @@ -42,15 +39,15 @@ export function $yup<T extends Yup.BaseSchema>(
/**
* $yup Async Helper
*/
export function $yupAsync<T extends Yup.BaseSchema>(
export function $yupAsync<T extends Yup.AnySchema>(
schema: YupHelper<T>,
options?: ValidateOptions
): Record<"$yupAsync", YupSchemaOption<T>>;
export function $yupAsync<T extends Yup.BaseSchema>(
export function $yupAsync<T extends Yup.AnySchema>(
schema: T,
options?: ValidateOptions
): Record<"$yupAsync", YupSchemaOption<T>>;
export function $yupAsync<T extends Yup.BaseSchema>(
export function $yupAsync<T extends Yup.AnySchema>(
schema: T | YupHelper<T>,
options?: ValidateOptions
) {
Expand All @@ -65,7 +62,7 @@ export function $yupAsync<T extends Yup.BaseSchema>(
* Check if this is a yup input option
* @param schema
*/
function isSchemaOption(schema: Yup.BaseSchema | YupSchemaOption<Yup.BaseSchema>) {
function isSchemaOption(schema: Yup.AnySchema | YupSchemaOption<Yup.AnySchema>) {
const keys = Object.keys(schema);
return keys.includes("schema");
}
Expand Down
27 changes: 14 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "abolish",
"version": "6.5.3",
"version": "6.7.2",
"description": "A javascript object validator.",
"main": "index.js",
"module": "index.esm.js",
Expand All @@ -20,29 +20,30 @@
"bundle": "node bundle.js",
"prepublishOnly": "npm run test",
"watch": "npx tsc --watch",
"play": "npx ts-node-dev --respawn dev/play.ts",
"play": "npx tsx watch dev/play.ts",
"play:dev": "npx nodemon dev/play.js",
"test-browser": "npx vite --host",
"test": "npm run build && node japaFile.js",
"test-dev": "npx nodemon japaFile.js --watch '*/**' --ext 'ts'",
"test-dev": "npx nodemon japaFile.js --watch '*/* *' --ext 'ts'",
"benchmark": "node benchmarks"
},
"dependencies": {
"lodash": "^4.17.21"
"lodash": "^4.17.21",
"tsx": "^4.15.5"
},
"devDependencies": {
"@trapcode/benchmark": "^0.1.3",
"@types/lodash": "^4.14.191",
"@types/node": "^18.11.18",
"esbuild": "^0.17.2",
"@types/lodash": "^4.17.5",
"@types/node": "^20.14.2",
"esbuild": "^0.21.5",
"japa": "^4.0.0",
"joi": "^17.7.0",
"joi": "^17.13.1",
"lodash-es": "^4.17.21",
"prettier": "^2.8.3",
"ts-node": "^10.9.1",
"prettier": "^3.3.2",
"ts-node": "^10.9.2",
"ts-node-dev": "^2.0.0",
"typescript": "^4.9.4",
"yup": "^0.32.11"
"typescript": "^5.4.5",
"yup": "^1.4.0"
},
"keywords": [
"abolish",
Expand All @@ -51,4 +52,4 @@
"object-validator",
"async-object-validator"
]
}
}
75 changes: 67 additions & 8 deletions src/Abolish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
CompiledValidator
} from "./Compiler";
import { assertType } from "./types-checker";
import { string } from "joi";

type Job = {
$name: string | false;
Expand Down Expand Up @@ -68,7 +69,7 @@ export class AttemptError extends Error {
*/
export const SuperKeys = Object.freeze({
Wildcards: new Set(["*", "$"]),
Fields: new Set(["*", "$", "$include"]),
Fields: new Set(["*", "$", "$include", "$strict"]),
Rules: new Set(["$name", "$skip", "$error", "$errors"])
});

Expand Down Expand Up @@ -294,10 +295,42 @@ class Abolish {
if (!Array.isArray(includeKeys)) throw new Error(`$include has to be an array!`);
}

let keysToBeValidated = Object.keys(rules);

// remove SUPER_RULES from keysToBeValidated
keysToBeValidated = keysToBeValidated.filter((key) => !SuperKeys.Fields.has(key));
let keysToBeValidated = Object.keys(rules).filter((key) => !SuperKeys.Fields.has(key));

let allowedKeys: string[] | undefined = undefined;

if (rules.hasOwnProperty("$strict")) {
if (rules["$strict"] === true) {
allowedKeys = keysToBeValidated;
} else if (Array.isArray(rules["$strict"])) {
// if strict is an array, then append it to allowedKeys
allowedKeys = keysToBeValidated.concat(rules["$strict"] as string[]);
} else {
throw new Error(`$strict must be a boolean or an array of allowed keys.`);
}

// add $include keys to allowedKeys
allowedKeys = Array.from(new Set(allowedKeys.concat(includeKeys)));

// check if all keys in object are allowed
const objectKeys = Object.keys(validated);
const unknownKeys = objectKeys.filter((key) => !allowedKeys!.includes(key));

if (unknownKeys.length > 0) {
return [
{
code: "object.unknown",
type: "internal",
key: "$strict",
validator: "$strict",
message: "Data contains unknown fields!",
data: { unknown: unknownKeys }
},
{} as R
];
}
}

// Loop through defined rules
for (const rule of keysToBeValidated) {
Expand Down Expand Up @@ -903,10 +936,12 @@ class Abolish {

const compiled = new AbolishCompiled(Schema(schema));

let internalWildcardRules: AbolishRule | undefined;
let internalWildcardRules: AbolishRule | boolean | undefined;
let includeFields: string[] = [];
let allowedKeys: string[] | undefined = undefined;
let schemaEntries = Object.entries(schema);

for (const [field, rules] of Object.entries(schema)) {
for (const [field, rules] of schemaEntries) {
/**
* Check for wildcard rules (*, $)
*/
Expand All @@ -919,15 +954,27 @@ class Abolish {
*/
if (typeof internalWildcardRules === "string")
internalWildcardRules = StringToRules(internalWildcardRules);
} else if (field === "$include") {
}

if (field === "$include") {
includeFields = rules as string[];
}

if (field === "$strict") {
if (rules === true) {
allowedKeys = Object.keys(schema);
} else if (Array.isArray(rules)) {
allowedKeys = rules as string[];
} else {
throw new Error(`$strict must be a boolean or an array of allowed keys.`);
}
}
}

/**
* Loop Through each field and rule
*/
for (const [field, rules] of Object.entries(schema)) {
for (const [field, rules] of schemaEntries) {
if (SuperKeys.Fields.has(field)) continue;

const compiledRule: CompiledRule = { validators: {} };
Expand Down Expand Up @@ -1104,6 +1151,18 @@ class Abolish {
// Check if any field has dot notation
compiled.fieldsHasDotNotation = compiled.fields.some(hasDotNotation);

// add allowedKeys
if (allowedKeys) {
// add $include keys to allowedKeys
allowedKeys = compiled.fields.concat(includeFields).concat(allowedKeys);

// remove SUPER_RULES from allowedKeys
allowedKeys = allowedKeys.filter((key) => !SuperKeys.Fields.has(key));

// make sure allowedKeys are unique
compiled.allowedFields = Array.from(new Set(allowedKeys));
}

return compiled as AbolishCompiledObject;
}

Expand Down
49 changes: 46 additions & 3 deletions src/Compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,12 @@ export class AbolishCompiled {
/**
* Fields included
*/
public includedFields: string[] = [];
public includedFields?: string[];

/**
* Allowed Fields when $strict rule is used
*/
public allowedFields?: string[];

/**
* If fields has any dot notation set to true
Expand Down Expand Up @@ -113,6 +118,25 @@ export class AbolishCompiled {
*/
const validated: Record<string, any> = { ...data };

if (this.allowedFields) {
const objKeys = Object.keys(validated);
const unknownKeys = objKeys.filter((key) => !this.allowedFields!.includes(key));

if (unknownKeys.length) {
return [
{
code: "object.unknown",
type: "internal",
key: "$strict",
validator: "$strict",
message: "Data contains unknown fields!",
data: { unknown: unknownKeys }
},
{} as R
];
}
}

/**
* Hold current fields
* This will be used in the skip section to remove fields that are not included in the input
Expand All @@ -139,7 +163,7 @@ export class AbolishCompiled {

if ($skip) {
// if field is not in included fields, remove it from fields
if (!this.includedFields.includes(field)) {
if (this.includedFields && !this.includedFields.includes(field)) {
fields = fields.filter((f) => f !== field);
}

Expand Down Expand Up @@ -216,6 +240,25 @@ export class AbolishCompiled {
*/
const validated: Record<string, any> = { ...data };

if (this.allowedFields) {
const objKeys = Object.keys(validated);
const unknownKeys = objKeys.filter((key) => !this.allowedFields!.includes(key));

if (unknownKeys.length) {
return [
{
code: "object.unknown",
type: "internal",
key: "$strict",
validator: "$strict",
message: "Data contains unknown fields!",
data: { unknown: unknownKeys }
},
{} as R
];
}
}

/**
* Hold current fields
* This will be used in the skip section to remove fields that are not included in the input
Expand All @@ -242,7 +285,7 @@ export class AbolishCompiled {

if ($skip) {
// if field is not in included fields, remove it from fields
if (!this.includedFields.includes(field)) {
if (this.includedFields && !this.includedFields.includes(field)) {
fields = fields.filter((f) => f !== field);
}

Expand Down
5 changes: 4 additions & 1 deletion src/ValidatorHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export function registerAllValidators<T extends typeof Abolish>(abolish: T) {
registerValidators(abolish, "object");
registerValidators(abolish, "string");
registerValidators(abolish, "utils");
registerValidators(abolish, "number");

return abolish;
}
Expand All @@ -21,7 +22,7 @@ export function registerAllValidators<T extends typeof Abolish>(abolish: T) {
*/
export function registerValidators<T extends typeof Abolish>(
abolish: T,
validators: "string" | "array" | "utils" | "object" | "date"
validators: "string" | "array" | "utils" | "object" | "date" | "number"
) {
switch (validators) {
case "string":
Expand All @@ -34,5 +35,7 @@ export function registerValidators<T extends typeof Abolish>(
return abolish.addGlobalValidators(require("../validators/utils"));
case "object":
return abolish.addGlobalValidators(require("../validators/object"));
case "number":
return abolish.addGlobalValidators(require("../validators/number"));
}
}
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,5 @@ export type AbolishRule = string | string[] | Record<string, any> | AbolishRule[
// >;
export type AbolishSchema<Keys extends Record<string, any> = Record<string, any>> = Record<
keyof Keys | string,
AbolishRule
AbolishRule | boolean
>;
Loading
Loading