Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@d3vtool/utils

ks9611839.0.0TypeScript support: included

A collection of utility functions designed to simplify common tasks in your application.

Utility Functions, Helper Functions, General-purpose utilities, Cross-framework utilities, JavaScript utilities, TypeScript utils, Reusable functions, Common tasks, Toolkit, Functional programming helpers, Code simplification, App development utilities, Application helpers, Framework-agnostic utilities, Cross-platform utilities, Data manipulation utilities, String, Date, Math functions, Modular utilities, Lightweight utilities, JavaScript toolkit, TypeScript helper functions

readme

DevTool Utils

A collection of utility functions designed to simplify common tasks in your application

Installation

You can install the package using npm or yarn:

npm

npm install @d3vtool/utils

yarn

yarn add @d3vtool/utils

Validator Examples

1. String Validation

import { Validator, ValidationError, type VInfer } from "@d3vtool/utils";

const usernameSchema = Validator.string().minLength(5);

type Username = VInfer<typeof usernameSchema>;

const username: Username = "popHero83";

const errors = usernameSchema.validateSafely(username)

console.log(errors);

// or

try {
  usernameSchema.validate(username);
} catch(err: unknown) {
  if(err instanceof ValidationError) {
    // do something with it
    console.log(err);
  }
}

2. Number Validation

import { Validator, ValidationError, type VInfer } from "@d3vtool/utils";

const phoneSchema = Validator.number().requiredLength(10);

type Phone = VInfer<typeof phoneSchema>;

const phone: Phone = 1234567890;

const errors = phoneSchema.validateSafely(phone)

console.log(errors);

// or

try {
  phoneSchema.validate(phone);
} catch(err: unknown) {
  if(err instanceof ValidationError) {
    // do something with it
    console.log(err);
  }
}

3. Boolean Validation

import { Validator, ValidationError, type VInfer } from "@d3vtool/utils";

const vSchema = Validator.boolean(
  "Custom error message" // Optional argument for a custom error message.
);

type vSchema = VInfer<typeof vSchema>;

// Performs strict type validation to ensure the value is a boolean.
// If strict mode is not enabled, any truthy value will be considered true.
vSchema.strict();

const errors = vSchema.validateSafely("string"); // false
console.log(errors);

// or

try {
  vSchema.validate(phone);
} catch(err: unknown) {
  if(err instanceof ValidationError) {
    // do something with it
    console.log(err);
  }
}

4. Array Validation

import { Validator, ValidationError, type VInfer } from "@d3vtool/utils";

const arraySchema = Validator.array<string[]>() // type must be provided for type inference later.
  .minLength(2)
  .maxLength(5)
  .requiredLength(3)
  .notEmpty()
  .includes([1, 2, 3]);

type ArrayType = VInfer<typeof arraySchema>;

const myArray: ArrayType = [1, 2, 3];

const errors = arraySchema.validateSafely(myArray);

console.log(errors);

// or

try {
  arraySchema.validate(myArray);
} catch (err: unknown) {
  if (err instanceof ValidationError) {
    // do something with it
    console.log(err);
  }
}

Methods

minLength(length: number, error: string)

Ensures the array has a minimum length.

  • Arguments:
    • length - The minimum length the array must have.
    • error - The error message to return if validation fails (default: 'The length of the array passed does not have min-length: '${length}'.').

maxLength(length: number, error: string)

Ensures the array has a maximum length.

  • Arguments:
    • length - The maximum length the array can have.
    • error - The error message to return if validation fails (default: 'The length of the array passed does not have max-length: '${length}'.').

requiredLength(length: number, error: string)

Ensures the array has an exact length.

  • Arguments:
    • length - The exact length the array must have.
    • error - The error message to return if validation fails (default: 'The length of the array passed does not have required-length: '${length}'.').

notEmpty(error: string)

Ensures the array is not empty.

  • Arguments:
    • error - The error message to return if validation fails (default: 'Array passed in is empty').

transform<F>(fn: transformerFn<T[], F>)

Transforms the array before validation.

  • Arguments:
    • fn - The transformer function to apply to the array.
    • Returns: The updated array validator.

includes(oneOfvalue: T | T[], strict: boolean, error: string)

Ensures the array includes a specified value or values.

  • Arguments:
    • oneOfvalue - A single value or an array of values to check for inclusion.
    • strict - If true, all values must be included (every); if false, only one must be included (some).
    • error - The error message to return if validation fails (default: 'The provided value is not present in the one-of-value/s: '${oneOfvalue}'.').

optional()

Makes the array optional.

  • Returns: The updated array validator.

ref(propertyName: string, error: string)

References another property for validation.

  • Arguments:
    • propertyName - The name of the property to reference.
    • error - The error message to return if validation fails (default: 'The provided value is invalid or does not meet the expected criteria.').

custom(fn: ValidatorFn, error: string)

Adds a custom validation function.

  • Arguments:
    • fn - The custom validation function which passes a value and must return boolean.
    • error - The error message to return if validation fails.

5. Simple Object Validation

import { Validator, ObjectValidationError, type VInfer } from "@d3vtool/utils";

const schema = Validator.object({
  name: Validator.string().minLength(5),
  email: Validator.string().email(),
});

type schema = VInfer<typeof schema>;

const schemaObj: schema = {
  name: "Sudhanshu",
  email: "email@email.abc"
}

const errors = schema.validateSafely(schemaObj);
console.log(errors);

// or

try {
  schema.validate(schemaObj);
} catch(err: unknown) {
  if(err instanceof ObjectValidationError) {
    // do something with it
    console.log(err);
  }
}

6. Tuple Validator

The Validator.tuple() function is used to validate a tuple, ensuring that each element of the tuple meets the specified schema. This is useful when you want to validate a structured collection of values with specific rules for each element.

Usage Example

import { Validator, ValidationError } from "@d3vtool/utils";

// Define a tuple schema with two elements: a string and a number.
const tupleV = Validator.tuple([
  Validator.string().minLength(5),   // First element: String with a minimum length of 5
  Validator.number().lessThanOrEqual(101)  // Second element: Number less than or equal to 101
]);

// Validate a tuple with the correct values
const errors = tupleV.validateSafely(["hello", 100]);
console.log(errors);  // Outputs: [] (no errors)

// Validate a tuple with incorrect values
const errors2 = tupleV.validateSafely(["hi", 102]);
console.log(errors2);  // Outputs: [Error Msg From respective validation fn, Error Msg From respective validation fn]

Validation Behavior

  1. Valid Tuple: If the tuple matches the schema (correct length, correct types, and correct values), no errors will be (returned or thrown).
  2. Invalid Tuple: If the tuple does not meet the validation criteria (e.g., wrong length, type mismatch, or invalid value), an error is (returned or thrown).

Example of Error Scenarios

  1. Incorrect Tuple Length:
    When the tuple schema expects a specific number of elements (e.g., 1 element), providing more or fewer elements results in an error.

    Example:

    const tupleV = Validator.tuple([Validator.string().minLength(5)]);
    const errors = tupleV.validateSafely(["hello", 100]);
    console.log(errors);  // Outputs: ["Provided tuple 'value' length is equivalent to 'validator-tuple'"]
  2. Invalid Values Inside Tuple:
    If the values inside the tuple don't meet the validation rules, such as a string being too short or a number exceeding the specified range, an error is returned.

    Example:

    const tupleV = Validator.tuple([
      Validator.string().minLength(5),
      Validator.number().lessThanOrEqual(101)
    ]);
    const errors = tupleV.validateSafely(["hi", 102]);
    console.log(errors);  // Outputs: [Error Msg From respective validation fn, Error Msg From respective validation fn]
  3. Invalid Type (Not a Tuple):
    If the value provided is not an array or tuple, an error is raised indicating that the provided value is not a tuple.

    Example:

    const tupleV = Validator.tuple([
      Validator.string().minLength(5)
    ]);
    const errors = tupleV.validateSafely("not a tuple");
    console.log(errors);  // Outputs: ["Provided 'value' is not tuple"]
  4. Edge Case Handling (undefined, null, NaN):
    If the value is undefined, null, or NaN, validation will throw an error indicating that the provided value is not a valid tuple.

    Example:

    const tupleV = Validator.tuple([Validator.string().minLength(5)]);
    const errors = tupleV.validateSafely(undefined);
    console.log(errors);  // Outputs: ["Provided 'value' is not tuple"]

Methods

  • optional(): To skip validation checks, as 'value' might be undefined or null.
  • validateSafely(value: any): Returns an array of errors if the value is invalid or an empty array if the value is valid.
  • validate(value: any): Throws a ValidationError if the value is invalid, otherwise, it passes silently.

7. optional()

import { Validator, ObjectValidationError, type VInfer } from "@d3vtool/utils";

const schema = Validator.object({
  name: Validator.string().minLength(5), // name is required with a minimum length of 5
  email: Validator.string().email().optional(), // email is optional
});

type schema = VInfer<typeof schema>;

const schemaObj: schema = {
  name: "Sudhanshu",
  email: "email@email.abc", // This is valid, but email can also be omitted
};

const errors = schema.validateSafely(schemaObj);
console.log(errors); // Should show no errors

// or
try {
  schema.validate(schemaObj);
} catch(err: unknown) {
  if(err instanceof ObjectValidationError) {
    // do something with it
    console.log(err);
  }
}

// Example with email missing
const schemaObjWithoutEmail: schema = {
  name: "Sudhanshu",
  // email is omitted, which is allowed because it's optional
};

const errorsWithoutEmail = schema.validateSafely(schemaObjWithoutEmail);
console.log(errorsWithoutEmail); // Should show no errors as email is optional

// or 

try {
  schema.validate(schemaObjWithoutEmail);
} catch(err: unknown) {
  if(err instanceof ObjectValidationError) {
    // do something with it
    console.log(err);
  }
}

Explanation:

  1. name field: This field is required, and it must be a string with a minimum length of 5 characters.
  2. email field: This field is optional due to .optional(). If it's provided, it must be a valid email address; if not, the validation will still pass without errors.

Example Behavior:

  1. If both name and email are provided, the validation will pass.
  2. If only name is provided and email is omitted, the validation will still pass because email is marked as optional.

8. .custom(fn) Function [ string | number | array ] validators

import { Validator, ObjectValidationError, type VInfer } from "@d3vtool/utils";

const schema = Validator.object({
  name: Validator.string().custom((value: string) => {
    return value.length >= 5
  }, "minimum length of 5 required"), // name is required with a minimum length of 5
  email: Validator.string().email()
});

type schema = VInfer<typeof schema>;

const schemaObj: schema = {
  name: "Sudhanshu",
  email: "email@email.abc", // This is valid, but email can also be omitted
};

const errors = schema.validateSafely(schemaObj);
console.log(errors); // Should show no errors

// or
try {
  schema.validate(schemaObj);
} catch(err: unknown) {
  if(err instanceof ObjectValidationError) {
    // do something with it
    console.log(err);
  }
}

Explanation:

  1. name field: This field is required, and it must be a string with a minimum length of 5 characters, the .custom(fn) fn takes a 'function' as an arg and should return boolean value.

9. Object Validation with Optional, Custom Fn and Self-Referencing Fields.

import { Validator, ObjectValidationError, type VInfer } from "@d3vtool/utils";

const schema = Validator.object({
  name: Validator.number().custom((value: string) => {
    return value.length >= 5
  }, "minimum length of 5 required"),
  email: Validator.string().email(),
  password: Validator.string().password().minLength(8),
  confirmPassword: Validator.string().optional().ref("password"),
});

type schema = VInfer<typeof schema>;

const schemaObj: schema = {
  name: 12345,
  email: "email@email.abc",
  password: "securepassword123",
  confirmPassword: "securepassword123", // Optional, but must match password if provided
}

const errors = schema.validateSafely(schemaObj);

// or

try {
  schema.validate(schemaObj);
} catch(err: unknown) {
  if(err instanceof ObjectValidationError) {
    // do something with it
    console.log(err);
  }
}

Explanation:

  • name: The name field must be a number and have a minimum value of 5.
  • email: The email field must be a valid email address.
  • password: The password field must be at least 8 characters long and a valid password format.
  • confirmPassword: The confirmPassword field is optional but, if provided, must match the value of the password field (using ref("password")).

In this example, the validateSafely function will check the provided schemaObj and return any validation errors, ensuring that confirmPassword (if present) matches password.


StringUtils Examples

1. toTitleCase(input: string): string

Converts the input string to title case (each word starts with an uppercase letter and the rest are lowercase).

import { StringUtils } from "@d3vtool/utils";

const input = "hello world from chatgpt";
const titleCase = StringUtils.toTitleCase(input);

console.log(titleCase); // "Hello World From Chatgpt"

2. toCamelCase(input: string): string

Converts the input string to camelCase (first word in lowercase and each subsequent word capitalized).

import { StringUtils } from "@d3vtool/utils";

const input = "hello world from chatgpt";
const camelCase = StringUtils.toCamelCase(input);

console.log(camelCase); // "helloWorldFromChatgpt"

3. toPascalCase(input: string): string

Converts the input string to PascalCase (each word capitalized without spaces).

import { StringUtils } from "@d3vtool/utils";

const input = "hello world from chatgpt";
const pascalCase = StringUtils.toPascalCase(input);

console.log(pascalCase); // "HelloWorldFromChatgpt"

4. toKebabCase(input: string): string

Converts the input string to kebab-case (words separated by hyphens with lowercase letters).

import { StringUtils } from "@d3vtool/utils";

const input = "hello world from chatgpt";
const kebabCase = StringUtils.toKebabCase(input);

console.log(kebabCase); // "hello-world-from-chatgpt"

5. isUpperCase(input: string): boolean

Checks if the input string is entirely in uppercase.

import { StringUtils } from "@d3vtool/utils";

const input1 = "HELLO WORLD";
const input2 = "Hello World";

const isUpper1 = StringUtils.isUpperCase(input1);
const isUpper2 = StringUtils.isUpperCase(input2);

console.log(isUpper1); // true
console.log(isUpper2); // false

6. isLowerCase(input: string): boolean

Checks if the input string is entirely in lowercase.

import { StringUtils } from "@d3vtool/utils";

const input1 = "hello world";
const input2 = "Hello World";

const isLower1 = StringUtils.isLowerCase(input1);
const isLower2 = StringUtils.isLowerCase(input2);

console.log(isLower1); // true
console.log(isLower2); // false

7. toAlternateCasing(input: string): string

Converts the input string to alternate casing, where the characters alternate between uppercase and lowercase.

import { StringUtils } from "@d3vtool/utils";

const input = "hello world";
const alternateCasing = StringUtils.toAlternateCasing(input);

console.log(alternateCasing); // "HeLlO wOrLd"

JWT Utility Examples

1. signJwt

Signs a JWT (JSON Web Token) with the provided claims, custom claims, secret key, and options.

Example Usage

import { signJwt, createIssueAt, createExpiry } from "@d3vtool/utils";

const claims = {
    aud: "http://localhost:4000",
    iat: createIssueAt(new Date(Date.now())),
    exp: createExpiry("1h"),
    iss: "server-x",
    sub: "user123"
};

const customClaims = {
    role: "admin",
    name: "John Doe"
};

const secret = "itsasecret";

// Sign the JWT with default algorithm (HS256)
const token = await signJwt(claims, customClaims, secret);

console.log(token); // Signed JWT token as a string

Supported Algorithms for JWT Signing

The following signing algorithms are supported by the signJwt function:

  • HS256 (default): HMAC using SHA-256.
  • HS384: HMAC using SHA-384.
  • HS512: HMAC using SHA-512.

You can specify which algorithm to use by passing the alg option when calling signJwt.

Example Usage with Custom Signing Algorithm

import { signJwt, createIssueAt, createExpiry } from "@d3vtool/utils";

const claims = {
    aud: "http://localhost:4000",
    iat: createIssueAt(new Date()),
    exp: createExpiry("2h"), // 2hr from now
    iss: "server-x",
    sub: "user123"
};

const customClaims = {
    role: "admin",
    name: "John Doe"
};

const secret = "itsasecret";

// Sign the JWT with HS384 algorithm
const token = await signJwt(claims, customClaims, secret, { alg: "HS384" });

console.log(token); // Signed JWT token using HS384

Error Handling

When using a custom algorithm, ensure that the algorithm is one of the supported ones: HS256, HS384, or HS512. If an unsupported algorithm is passed, an error will be thrown:

import { signJwt, createIssueAt, createExpiry } from "@d3vtool/utils";

const secret = "itsasecret";
const claims = {
    aud: "http://localhost:4000",
    iat: createIssueAt(new Date()),
    exp: createExpiry('1m'),  
    iss: "server-x",
    sub: "testing"
}

try {
    const token = await signJwt(claims, { name: "John Doe" }, secret, { alg: "RS256" }); // Unsupported algorithm
} catch (error) {
    if (error instanceof BadJwtHeader) {
        console.error("Error: Unsupported signing algorithm.");
    } else {
        console.error("Unexpected error:", error);
    }
}

2. verifyJwt

Verifies a JWT and decodes its claims, including both standard JWT claims (like iat, exp, iss) and any custom claims included in the token.

Example Usage

import { verifyJwt } from "@d3vtool/utils";

// Example token (replace with a real token)
const jwt = "your.jwt.token";
const secret = "itsasecret";

// Verify the JWT
const verifiedClaims = await verifyJwt(jwt, secret);
console.log(verifiedClaims); // Decoded claims, including standard and custom claims

Error Handling

The verifyJwt function may throw the following errors:

  1. DirtyJwtSignature: If the JWT signature doesn't match or is invalid.
  2. ExpiredJwt: If the token has expired (based on the exp claim).
  3. InvalidJwt: If the token is malformed or cannot be decoded properly.
import { verifyJwt } from "@d3vtool/utils";

const jwt = "your.jwt.token";
const secret = "itsasecret";

try {
    const verifiedClaims = await verifyJwt(jwt, secret);
    console.log(verifiedClaims);
} catch (error) {
    if (error instanceof DirtyJwtSignature) {
        console.error("Error: JWT signature is invalid or has been tampered with.");
    } else if (error instanceof ExpiredJwt) {
        console.error("Error: JWT has expired.");
    } else if (error instanceof InvalidJwt) {
        console.error("Error: JWT is malformed or cannot be decoded.");
    } else {
        console.error("Unexpected error:", error);
    }
}

MIME Type Utility Examples

1. getMimeType

Retrieves the MIME type for a given file extension.

Example Usage

import { getMimeType } from "@d3vtool/utils";

const extension1 = "html"; // Example file extension
const extension2 = "jpg";  // Example file extension
const extension3 = "md";   // Example file extension

// Get MIME type for the given file extensions
const mimeType1 = getMimeType(extension1); // Returns the MIME type for HTML, e.g. "text/html"
const mimeType2 = getMimeType(extension2); // Returns the MIME type for JPG, e.g. "image/jpeg"
const mimeType3 = getMimeType(extension3); // Returns the MIME type for Markdown, e.g. "text/markdown"

// Fallback to default MIME type for unsupported extensions
const unknownMimeType = getMimeType("unknown"); // Returns the default MIME type "text/plain"

console.log(mimeType1); // "text/html"
console.log(mimeType2); // "image/jpeg"
console.log(mimeType3); // "text/markdown"
console.log(unknownMimeType); // "text/plain"

This package is open-source and licensed under the MIT License.