UNPKG

defuss-runtime

Version:

Isomorphic JS runtime API enhancements, relevant for Defuss packages.

575 lines (519 loc) 24.8 kB
declare const _BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; declare let _base64LookupMap: Record<string, number> | null; declare function _getBase64LookupMap(): Record<string, number>; declare function binaryToBase64(buffer: ArrayBufferLike): string; declare function base64ToBinary(base64: string): ArrayBufferLike; declare const _HEX_PREFIX = "hex:"; declare function binaryToHex(buffer: ArrayBufferLike): string; declare function hexToBinary(hexString: string): ArrayBufferLike; declare function textToBinary(text: string): ArrayBufferLike; declare function binaryToText(buffer: ArrayBufferLike): string; declare const getAllKeysFromPath: (path: string) => Array<string | number>; declare const ensureKey: (obj: Record<string, any>, key: string | number, nextKey?: string | number) => void; declare const getByPath: (obj: any, path: string) => any; declare const setByPath: (obj: any, path: string, value: any) => any; /** * Return a new array with unique values from the input array. * @param a - The array to dedupe * @returns Array of unique values */ declare function unique<T>(a: readonly T[]): T[]; /** * Pick specific keys from an object. * @param o - The source object * @param keys - Array of keys to pick * @returns New object with only the picked keys */ declare function pick<T extends object, K extends keyof T>(o: T, keys: readonly K[]): Pick<T, K>; /** * Omit specific keys from an object. * @param o - The source object * @param keys - Array of keys to omit * @returns New object without the omitted keys */ declare function omit<T extends object, K extends keyof T>(o: T, keys: readonly K[]): Omit<T, K>; /** * Check deep equality of two values via JSON serialization. * Non-serializable values (functions, undefined) are omitted. * @param a - First value to compare * @param b - Second value to compare * @returns True if the serialized values are identical, false otherwise */ declare function equalsJSON<T>(a: T, b: T): boolean; /** * Unique symbol to identify path accessor objects */ declare const PATH_ACCESSOR_SYMBOL: unique symbol; /** * Type helper for access accessor that returns string paths * This type allows chaining property access while maintaining type safety * and ultimately returning a string representation of the access */ type PathAccessor<T> = T extends object ? { [K in keyof T]: T[K] extends object ? PathAccessor<T[K]> & string : string; } & { [K in number]: T extends readonly (infer U)[] ? PathAccessor<U> & string : T extends Record<number, infer U> ? PathAccessor<U> & string : PathAccessor<Dynamic> & string; } & string : string; /** * Dynamic type for untyped object property access * Use this with access<Dynamic>() to enable arbitrary property access */ type Dynamic = { [key: string]: Dynamic; [key: number]: Dynamic; }; /** * Creates a type-safe access accessor that returns string representations of property paths * * @example * ```typescript * interface User { * profile: { * preferences: { * theme: string; * }; * }; * } * * const themePath = access<User>().profile.preferences.theme; * console.log(String(themePath)); // "profile.preferences.theme" * * // For dynamic usage without types: * const dynamicPath = access<Dynamic>().some.dynamic.path; * console.log(String(dynamicPath)); // "some.dynamic.path" * ``` */ declare const access: <T = any>() => PathAccessor<T>; /** * Checks if an object is a path accessor created by the access() function * * @param obj - The object to check * @returns True if the object is a path accessor, false otherwise * * @example * ```typescript * const path = access<User>().profile.theme; * const regularString = "profile.theme"; * * console.log(isPathAccessor(path)); // true * console.log(isPathAccessor(regularString)); // false * ``` */ declare const isPathAccessor: (obj: any) => obj is PathAccessor<any>; /** * Debounce a function: delays invoking `fn` until after `wait` ms have elapsed * since the last time the debounced function was called. * @param fn - The function to debounce * @param wait - Milliseconds to wait * @returns Debounced function */ declare function debounce<F extends (...args: any[]) => any>(fn: F, wait: number): (...args: Parameters<F>) => void; /** * Throttle a function: ensures that `fn` is called at most once every `wait` ms. * @param fn - The function to throttle * @param wait - Milliseconds to wait * @returns Throttled function */ declare function throttle<F extends (...args: any[]) => any>(fn: F, wait: number): (...args: Parameters<F>) => void; /** * Wait for a specified amount of time. * @param ms - Milliseconds to wait * @returns A promise that resolves after the specified time */ declare function wait(ms: number): Promise<void>; declare function createTimeoutPromise<T>(timeoutMs: number, operation: () => Promise<T> | T, timeoutCallback?: (ms: number) => void): Promise<T>; declare function waitForWithPolling<T>(check: () => T | null | undefined, timeout: number, interval?: number): Promise<T>; declare function waitForRef<T>(ref: { current: T | null; }, timeout: number): Promise<T>; type TransformerFn<T extends any[] = any[]> = (...args: T) => any; /** * Converts a value to a string representation. * Handles various types including null, undefined, numbers, booleans, dates, regexes, arrays, and objects. * * @param value - The value to convert to a string. * @returns The string representation of the value. */ declare const asString: TransformerFn; /** * Converts a value to a number representation. * Handles various types including strings, dates, and numbers. * * @param value - The value to convert to a number. * @returns The numeric representation of the value, or 0 if conversion fails. */ declare const asNumber: TransformerFn; /** * Converts a value to a boolean representation. * Handles various types including strings, numbers, and existing booleans. * * @param value - The value to convert to a boolean. * @returns The boolean representation of the value. */ declare const asBoolean: TransformerFn; /** * Converts a value to an array representation. * If the value is already an array, it applies a transformer function to each element. * If the value is null or undefined, it returns an empty array. * Otherwise, it applies the transformer function to the value and returns it as a single-element array. * * @param value - The value to convert to an array. * @param transformerFn - A function to transform each element of the array. * @returns An array representation of the value. */ declare const asArray: TransformerFn; /** * Converts a value to a Date object. * Handles various types including null, undefined, strings, numbers, and existing Date objects. * * @param value - The value to convert to a Date. * @returns The Date representation of the value, or an invalid Date if conversion fails. */ declare const asDate: TransformerFn; /** * Converts a value to an integer representation. * Handles various types including strings, numbers, and objects. * * @param value - The value to convert to an integer. * @returns The integer representation of the value, or 0 if conversion fails. */ declare const asInteger: TransformerFn; type ValidationMessage = string | number | boolean | null | undefined; type ValidationFnResult = true | ValidationMessage; type ValidatorPrimitiveFn<T = unknown> = (value: T, message?: string) => boolean | string | Promise<boolean | string>; interface SingleValidationResult { message?: ValidationMessage; isValid: boolean; } type ValidatorFn<T extends any[] = any[]> = (...args: T) => boolean | string; type ValidationStep<T extends any[] = any[]> = { fn: ValidatorFn<T>; args: T; }; /** * Checks if the given value is a date and is after a specified minimum date. * @param value - The date value to check. * @param minDate - The minimum date to compare against. * @param inclusive - If true, the value can be equal to the minDate. * @param message - Optional error message to return when validation fails. * @returns True if the value is a Date and is after the minDate, the message if validation fails and message is provided, false otherwise. */ declare const isAfter: ValidatorFn; /** * Checks if the given value is an array. * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is an array, the message if validation fails and message is provided, false otherwise. */ declare const isArray: ValidatorPrimitiveFn; /** * Checks if the given value is a date and is before a specified maximum date. * @param value - The date value to check. * @param maxDate - The maximum date to compare against. * @param inclusive - If true, the value can be equal to the maxDate. * @param message - Optional error message to return when validation fails. * @returns True if the value is a Date and is before the maxDate, the message if validation fails and message is provided, false otherwise. */ declare const isBefore: ValidatorFn; /** * Checks if the given value is a boolean. * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is a boolean, the message if validation fails and message is provided, false otherwise. */ declare const isBoolean: ValidatorPrimitiveFn; /** * Checks if the given value is a Date object. * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is a Date object, the message if validation fails and message is provided, false otherwise. */ declare const isDate: ValidatorPrimitiveFn; /** * Checks if the given value is defined (not `undefined`). * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is defined, the message if validation fails and message is provided, false otherwise. */ declare const isDefined: ValidatorPrimitiveFn; /** * Checks if the given value is a valid email address. * Implements RFC 5322 official, @see https://emailregex.com/ * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is a valid email address, the message if validation fails and message is provided, false otherwise. */ declare const isEmail: ValidatorPrimitiveFn; /** * Checks if the given value is empty. * An empty value is defined as: * - `null` or `undefined` * - an empty string * - an empty array * - an object with no own properties * - a Date object (not considered empty) * * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is empty, the message if validation fails and message is provided, false otherwise. */ declare const isEmpty: ValidatorPrimitiveFn; /** * Checks if the given value is equal to another value. * @param value - The first value to compare. * @param valueB - The second value to compare. * @param message - Optional error message to return when validation fails. * @returns True if the values are equal, the message if validation fails and message is provided, false otherwise. */ declare const is: ValidatorFn; /** * Checks if the given value is greater than a specified minimum value. * Optionally includes equality in the comparison. * * @param value - The value to check. * @param minValue - The minimum value to compare against. * @param includeEqual - Whether to include equality in the comparison (default: false). * @param message - Optional error message to return when validation fails. * @returns True if the value is greater than (or equal to, if `includeEqual` is true) the minimum value, the message if validation fails and message is provided, false otherwise. */ declare const isGreaterThan: ValidatorFn; /** * Checks if a value is a safe number (not NaN and finite). * @param value - The value to check * @param message - Optional error message to return when validation fails. * @returns True if the value is a safe number, the message if validation fails and message is provided, false otherwise */ declare const isSafeNumber: ValidatorPrimitiveFn; /** * Checks if a value (number or string) is a numeric and a safe number. * @param value - The value to check * @param message - Optional error message to return when validation fails. * @returns True if the value is numeric, the message if validation fails and message is provided, false otherwise */ declare const isSafeNumeric: ValidatorPrimitiveFn; /** * Checks if the provided value is an object. * An object is defined as a non-null value that is of type 'object' and not an array. * * @param value - The value to check if it is an object. * @param message - Optional error message to return when validation fails. * @returns True if the value is an object, the message if validation fails and message is provided, false otherwise. */ declare const isObject: ValidatorPrimitiveFn; /** * Checks if the given value is one of the specified options. * This function checks if the value is included in the provided array of options. * * @param value - The value to check. * @param options - An array of strings or numbers to check against. * @param message - Optional error message to return when validation fails. * @returns True if the value is one of the options, the message if validation fails and message is provided, false otherwise. */ declare const isOneOf: ValidatorFn; /** * Validates if the provided value is a valid phone number. * The phone number must be a string that matches the E.164 format. * * @param value - The value to validate as a phone number. * @param message - Optional error message to return when validation fails. * @returns True if the value is a valid phone number, the message if validation fails and message is provided, false otherwise. */ declare const isPhoneNumber: ValidatorPrimitiveFn; /** * Checks if the provided value is required. * This function checks if the value is truthy, meaning it is not null, undefined, or an empty string. * * @param value - The value to check if it is required. * @param message - Optional error message to return when validation fails. * @returns True if the value is required (truthy), the message if validation fails and message is provided, false otherwise. */ declare const isRequired: ValidatorPrimitiveFn; /** * Validates if the provided value is a valid slug. * A slug is a string that consists of lowercase letters, numbers, and hyphens. * It does not allow spaces or special characters. * * @param value - The value to validate as a slug. * @param message - Optional error message to return when validation fails. * @returns True if the value is a valid slug, the message if validation fails and message is provided, false otherwise. */ declare const isSlug: ValidatorPrimitiveFn; /** * Checks if the given value is less than a specified maximum value. * Optionally includes equality in the comparison. * * @param value - The value to check. * @param maxValue - The maximum value to compare against. * @param includeEqual - Whether to include equality in the comparison (default: false). * @param message - Optional error message to return when validation fails. * @returns True if the value is less than (or equal to, if `includeEqual` is true) the maximum value, the message if validation fails and message is provided, false otherwise. */ declare const isLessThan: ValidatorFn; /** * Validates if the provided value is a string. * This function checks if the value is of type string. * * @param value - The value to validate as a string. * @param message - Optional error message to return when validation fails. * @returns True if the value is a string, the message if validation fails and message is provided, false otherwise. */ declare const isString: ValidatorPrimitiveFn; /** * Validates if the provided value is a valid URL. * The URL must be a string that can be parsed by the URL constructor. * * @param value - The value to validate as a URL. * @param message - Optional error message to return when validation fails. * @returns True if the value is a valid URL, the message if validation fails and message is provided, false otherwise. */ declare const isUrl: ValidatorPrimitiveFn; /** * Validates if the provided value is a valid URL path. * A URL path consists of lowercase letters, numbers, hyphens, underscores, and slashes. * It does not allow spaces or special characters. * * @param value - The value to validate as a URL path. * @param message - Optional error message to return when validation fails. * @returns True if the value is a valid URL path, the message if validation fails and message is provided, false otherwise. */ declare const isUrlPath: ValidatorPrimitiveFn; interface DateValue { month: number; year: number; date: number; hour: number; minute: number; second: number; millisecond: number; } /** * Converts a Date object into a DateValue object. * @param date - The Date object to convert. * @returns A DateValue object containing the year, month, date, hour, minute, second, and millisecond. */ declare const getDateValue: (date: Date) => DateValue; /** * Checks if the given value is a string and its length is longer than a specified minimum length. * Optionally, it can include equality in the comparison. * * @param value - The value to check. * @param minLength - The minimum length to compare against. * @param includeEqual - Whether to include equality in the comparison (default: false). * @param message - Optional error message to return when validation fails. * @returns True if the value is a string and its length is longer than the specified minimum length, * the message if validation fails and message is provided, false otherwise. */ declare const isLongerThan: ValidatorFn; /** * Checks if the given value is shorter than a specified maximum length. * Optionally includes equality in the comparison. * * @param value - The value to check, expected to be a string. * @param maxLength - The maximum length to compare against. * @param includeEqual - If true, includes equality in the comparison (default is false). * @param message - Optional error message to return when validation fails. * @returns True if the value's length is shorter than (or equal to, if includeEqual is true) the maxLength, the message if validation fails and message is provided, false otherwise. */ declare const isShorterThan: ValidatorFn; /** * Checks if the given value matches a specified pattern. * @param value - The value to check. * @param pattern - The regular expression pattern to match against. * @param message - Optional error message to return when validation fails. * @returns True if the value matches the pattern, the message if validation fails and message is provided, false otherwise. */ declare const hasPattern: ValidatorFn; /** * Checks if the given value is a valid/parsable date format. * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is a valid date format, the message if validation fails and message is provided, false otherwise. */ declare const hasDateFormat: ValidatorFn; /** * Checks if the given value is an integer. * An integer is a number without a fractional part. * * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is an integer, the message if validation fails and message is provided, false otherwise. */ declare const isInteger: ValidatorPrimitiveFn; /** * Compares two values for equality using a deep comparison. * This function checks if the two values are equal in terms of their JSON representation. * * @param value - The first value to compare. * @param valueB - The second value to compare. * @param message - Optional error message to return when validation fails. * @returns True if the values are equal, the message if validation fails and message is provided, false otherwise. */ declare const isEqual: ValidatorFn; /** * Transformer that checks if a value is strictly true. * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is strictly true, the message if validation fails and message is provided, false otherwise. */ declare const isTrue: ValidatorFn; /** * Transformer that checks if a value is strictly false. * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is strictly false, the message if validation fails and message is provided, false otherwise. */ declare const isFalse: ValidatorFn; /** * Transformer that checks if a value is truthy. * Returns true for all truthy values (non-zero numbers, non-empty strings, objects, etc.) * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is truthy, the message if validation fails and message is provided, false otherwise. */ declare const isTruthy: ValidatorFn; /** * Transformer that checks if a value is falsy. * Returns true for all falsy values (false, 0, "", null, undefined, NaN) * @param value - The value to check. * @param message - Optional error message to return when validation fails. * @returns True if the value is falsy, the message if validation fails and message is provided, false otherwise. */ declare const isFalsy: ValidatorFn; /** * Checks if the given value is an instance of a specified constructor function. * This function verifies that the value is an instance of the provided constructor * and that its constructor matches the specified constructor. * * @param value - The value to check. * @param someConstructorFunction - The constructor function to check against. * @param message - Optional error message to return when validation fails. * @returns True if the value is an instance of the constructor, the message if validation fails and message is provided, false otherwise. * @throws TypeError if `someConstructorFunction` is not a function. */ declare const isInstanceOf: ValidatorFn; /** * Checks if the provided value is of a specific type. * This function checks if the value matches the specified type, which can be one of: * - "string" * - "number" * - "boolean" * - "object" * - "function" * - "undefined" * * @param value - The value to check its type. * @param type - The type to check against. * @param message - Optional error message to return when validation fails. * @returns True if the value is of the specified type, the message if validation fails and message is provided, false otherwise. */ declare const isTypeOf: ValidatorFn; /** * Checks if the provided value is null. * @param value any - The value to check if it is null. * @param message - Optional error message to return when validation fails. * @returns boolean | string - Returns true if the value is null, the message if validation fails and message is provided, false otherwise. */ declare const isNull: ValidatorPrimitiveFn; type PreloadAs = "image" | "script" | "style" | "fetch" | "track" | "font"; declare function preload(url: string | string[], as?: PreloadAs): void; export { type DateValue, type Dynamic, PATH_ACCESSOR_SYMBOL, type PathAccessor, type PreloadAs, type SingleValidationResult, type ValidationFnResult, type ValidationMessage, type ValidationStep, type ValidatorFn, type ValidatorPrimitiveFn, _BASE64_CHARS, _HEX_PREFIX, _base64LookupMap, _getBase64LookupMap, access, asArray, asBoolean, asDate, asInteger, asNumber, asString, base64ToBinary, binaryToBase64, binaryToHex, binaryToText, createTimeoutPromise, debounce, ensureKey, equalsJSON, getAllKeysFromPath, getByPath, getDateValue, hasDateFormat, hasPattern, hexToBinary, is, isAfter, isArray, isBefore, isBoolean, isDate, isDefined, isEmail, isEmpty, isEqual, isFalse, isFalsy, isGreaterThan, isInstanceOf, isInteger, isLessThan, isLongerThan, isNull, isObject, isOneOf, isPathAccessor, isPhoneNumber, isRequired, isSafeNumber, isSafeNumeric, isShorterThan, isSlug, isString, isTrue, isTruthy, isTypeOf, isUrl, isUrlPath, omit, pick, preload, setByPath, textToBinary, throttle, unique, wait, waitForRef, waitForWithPolling };