/** * Hook function executed after a response is received, but before its body is parsed. * It can modify the `Response` object (e.g., to transform headers or status). * @param response - The raw `Response` object received from the fetch call. * @param options - The `RequestInit` object used for the fetch call. * @returns The (potentially modified) `Response` object, or a Promise resolving to it. */ export declare type AfterHook = (response: Response, options: RequestInit) => Response | Promise; /** * Hook function executed before a request is made. * It can modify `RequestInit` options or the URL. * @param url - The URL to `fetch`. * @param query - SearchParam in the URL to `fetch`. * @param options - The `RequestInit` object that will be passed to `fetch`. * @returns The (potentially modified) `RequestInit` object, or a Promise resolving to it. */ export declare type BeforeHook = (params: BeforeHookParams) => void | Promise; /** * Interface for the parameters passed to the beforeHook. * This encapsulates all the mutable parts of the request to allow * the hook to modify them. */ export declare interface BeforeHookParams { query?: QueryParams; headers?: HeadersInit; } /** * Basic cache decorator for functions with single string/number parameter * * @template T The return type of the cached function * @param fn Function to cache * @returns Cached version of the function */ export declare const cache: (fn: (key: string | number) => T) => (key: string | number) => T; /** * Cache decorator that handles multiple parameters using JSON serialization * Multi-Parameter JSON-Serialized Version * @template T The return type of the cached function * @template Args The argument types of the cached function * @param fn Function to cache * @returns Cached version of the function */ export declare const cacheJSON: (fn: (this: unknown, ...args: Args) => T) => (...args: Args) => T; /** * Advanced cache decorator using WeakMap for object keys * @template T The return type of the cached function * @template Args The argument types of the cached function * @param fn Function to cache * @returns Cached version of the function */ export declare function cacheWeak(fn: (this: unknown, ...args: Args) => T): (...args: Args) => T; /** * Capitalizes the first letter of a single text/word. * Unicode-safe and locale-aware. * * @param text The text to capitalize. * @returns The text with the first letter capitalized. */ export declare const capitalize: (text: string) => string; /** * Joins class names together, filtering out falsy values. * @param {...(string | boolean | number | null | undefined)} classes - Class names or conditional expressions * @returns {string} Combined class names as a single string, or undefined (to prevent class="" not render in node). * @example * cn('btn', isActive && 'active', hasError && 'error'); * // Returns: "btn active" (when isActive is true and hasError is false) */ export declare const cn: (...classes: (string | boolean | number | null | undefined)[]) => string | undefined; /** * Copy styles from parent doc to child doc. * * @param source Document to get styles source. * @param target Document target to apply copied styles. */ export declare const copyStyles: (source: Document, target: Document) => void; /** * Copies text to the clipboard using the modern Clipboard API, * with a robust fallback for older browsers/insecure contexts. * * @param text - The text to copy. * @returns `true` if the copy succeeded, `false` otherwise. */ export declare const copyToClipboard: (text: string) => Promise; /** * @param color string CSS Color * @returns 'dark' | 'light' */ export declare const darkOrLight: (key: string | number) => "light" | "dark"; /** * Creates a debounce function that delays execution of the given function * until after the specified delay has passed since the last call. * * @template T - A function type that accepts any parameters and returns void. * @param {T} func - The function to be debounced. * @param {number} wait - The delay time in milliseconds. * @returns {(...args: Parameters) => void} - A new function with debouncing behavior. */ export declare const debounce: void>(func: T, wait?: number) => (...args: Parameters) => void; /** * Ultra-optimized debounce with cancel, flush, and pending status * @template T - Function type to debounce * @param func - Target function * @param wait - Delay in ms (default: 300) * @param options - { leading?: boolean, trailing?: boolean } * @returns Debounced function with control methods */ export declare const debounceAdvanced: void>(func: T, wait?: number, { leading, trailing }?: DebounceAdvancedOptions) => { (...args: Parameters): void; cancel(): void; flush(): void; pending(): boolean; } & { cancel: () => void; flush: () => void; pending: () => boolean; }; declare interface DebounceAdvancedOptions { leading?: boolean; trailing?: boolean; } /** * Initiates a file download from a given Blob or File in modern browsers. * Automatically handles Safari compatibility and revokes the object URL after use. * * @param {Blob | File} data - The binary data to download. * @param {DownloadOptions} [options] - Optional configuration for the download. * @param {string} [options.name=""] - Suggested filename for the downloaded file. * @param {number} [options.timeout=500] - Delay before revoking the object URL (in milliseconds). * @returns {Promise} Resolves after the object URL is revoked; rejects if data is invalid. */ export declare const download: (data: downloadData, { name, timeout, }?: DownloadOptions) => Promise; export declare type downloadData = Blob | File; export declare type DownloadOptions = { name?: string; timeout?: number; }; /** * Represents the progress of a download. */ export declare interface DownloadProgress { /** Bytes loaded so far. */ loaded: number; /** Total bytes to load, if available (e.g., from Content-Length header). */ total: number | undefined; /** Progress percentage (0-1), calculated as loaded / total. Undefined if total is unknown. */ progress: number | undefined; } /** * Options specific to a single fetch request. * These extend the standard `RequestInit` interface and add custom functionalities. */ export declare interface FetchOptions extends Omit { /** The request payload (body). Can be an object (for JSON), FormData, etc. */ body?: RequestBody; /** * An external `AbortSignal` to control the request lifecycle. * If provided, your internal timeout will not use this signal; it will create its own * `AbortController` if `timeout` is also set. */ signal?: AbortSignal; /** * You explicitly destructure headers and use `new Headers(headers)`. * `HeadersInit` allows string[][], Record, or Headers. */ headers?: HeadersInit; /** Query parameters to append to the URL. */ query?: QueryParams; /** * The desired format for the response body. If provided, the function returns the parsed data. * If not provided, the function returns the raw Response object. */ responseType?: ResponseType_2; /** * Request timeout in milliseconds. If the request takes longer than this, it will be aborted * and an `AbortError` will be thrown. A value of `0` or `undefined` means no timeout. */ timeout?: number; /** * A hook function executed before this specific request is made. * Can modify request options. */ beforeHook?: BeforeHook; /** * A hook function executed after the response for this specific request is received, * but before its body is parsed. Can modify the response. */ afterHook?: AfterHook; /** * Callback function for download progress updates. * This is active only if the response has a `Content-Length` header. */ onProgress?: OnProgressCallback; } /** * Get initial name * @param name string * @returns 'Initial Name' */ export declare const getInitials: (name: string) => string; /** * Defines the supported HTTP methods. * @NOTES : It is strongly recommended to consistently use uppercase HTTP methods. */ export declare type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'; /** * Ultra-fast deep comparison * - Supports objects/arrays. * - No Date/Map/Set support. * - Can be significantly faster than Lodash's `_.isEqual()` in most cases, * while still handling all the same edge cases. * - ~15% faster than react-fast-compare in benchmarks. */ export declare const isEqual: (a: T, b: T) => boolean; /** * Strictly checks if a value is a negative number (including -0 and negative BigInt) * @param value - The value to check * @returns true if the value is a negative number or bigint */ export declare const isNegative: (value: unknown) => boolean; /** * Check value is number or not * @param value number - The value to check * @returns boolean - true if the value is a finite number or bigint */ export declare const isNumber: (value: unknown) => value is number | bigint; export declare interface KeyValuePair { key: K; value: V; } /** * Sorts an array using a "map callback" (like Python's `key` argument in `sorted`) * before comparing. This allows you to sort by a derived value instead of the item itself. * * - Items mapped to `undefined` are always moved to the end. * - If `compareFn` is not provided, values are compared as strings using `localeCompare`. * - Sorting is stable: items with equal mapped values preserve their original order. * * @typeParam T - The type of elements in the input array. * @typeParam U - The type of the mapped "sortable" values. * * @param list - The array to sort. * @param mapFn - A function that maps each element to a sortable value. * If it returns `undefined`, that element will be placed at the end. * @param compareFn - Optional comparison function for the mapped values. * Defaults to lexicographic string comparison. * * @returns A new array of the original items, sorted by their mapped values. * * @example * ```ts * // Sort numbers by their absolute value * const result = mapSort([-5, 3, -2, 8], n => Math.abs(n)); * // => [-2, 3, -5, 8] * * // Sort objects by a field * const users = [ * { name: "Alice", age: 30 }, * { name: "Bob", age: 25 }, * { name: "Charlie", age: 25 }, * ]; * * const sorted = mapSort(users, u => u.age); * // => Bob (25), Charlie (25), Alice (30) * ``` */ export declare const mapSort: (list: T[], mapFn?: (item: T, index: number, array: T[]) => U | undefined, compareFn?: (a: U, b: U) => number) => T[]; /** * Generates a unique, sequentially incremented string ID with an optional prefix. * Each call increments an internal counter to ensure uniqueness. * @param prefix - An optional string prefix for the ID (defaults to 'q'). * @returns A unique string ID (e.g., 'q1', 'q2', 'customPrefix123'). */ export declare const nextId: (prefix?: string) => string; /** * Converts a plain object to FormData * @param obj The object to convert * @returns FormData containing all enumerable properties of the input object */ export declare const obj2FormData: (obj: Record) => FormData; /** * Callback function for download progress updates. * @param progress - An object containing loaded, total, and progress percentage. */ export declare type OnProgressCallback = (progress: DownloadProgress) => void; /** * Adds leading zeros to a number or string to reach a specified length, * while handling null/undefined values gracefully. * @param num * @param targetLength * @returns Type: string e.g., "5" → "05" or empty string if falsy */ export declare const padWithLeadingZeros: (num: number | string | null | undefined, targetLength?: number) => string; export declare type Primitive = string | number | boolean | symbol | bigint | undefined | null; /** * Type for query parameters. Supports a plain object where keys are strings * and values can be strings, numbers, booleans, or arrays of strings. */ export declare type QueryParams = Record; /** * A highly configurable fetch wrapper that simplifies making HTTP requests. * It supports query parameters, a request timeout, and a flexible hook system. * The function can either return the parsed response data directly or the raw Response object, * depending on the 'responseType' option. * * @param {string} url The URL of the resource to fetch. * @param {FetchOptions} [options={}] An object containing custom and standard fetch options. * @param {object} [options.headers={}] Headers to be included in the request. * @param {AbortSignal} [options.signal] An AbortSignal instance for canceling the request. * @param {ResponseType} [options.responseType] The desired format for the response body. If omitted, returns the raw Response object. * @param {object} [options.query={}] Query parameters to be appended to the URL. * @param {number} [options.timeout] The request timeout in milliseconds. * @param {BeforeHook} [options.beforeHook] A hook executed before the request is made. * @param {OnProgressCallback} [options.onProgress] A callback for monitoring download progress. * @param {object} options.body The request body. * @param {string} options.method The request method. * @returns {Promise} A Promise that resolves to the parsed response data if `responseType` is provided, * otherwise, it resolves to the raw `Response` object. * @throws {FetchError} Throws a `FetchError` for HTTP status codes outside of the 200-299 range, * or for network failures. The error object includes status and parsed error data. */ export declare const request: (url: string, { signal: externalSignal, headers, query, responseType, timeout, beforeHook, afterHook, onProgress, ...options }?: FetchOptions) => Promise; /** * Type for request payload (body). * It can be an object (for JSON), FormData, URLSearchParams, binary data (Blob, ArrayBuffer), * or a plain string. */ export declare type RequestBody = object | FormData | URLSearchParams | Blob | ArrayBuffer | string | null | undefined; /** * Represents the different types of response parsing methods. * This is used to automatically parse the response body. */ declare type ResponseType_2 = 'json' | 'text' | 'blob' | 'formData' | 'arrayBuffer'; export { ResponseType_2 as ResponseType } /** * Executes an asynchronous action with retry support, exponential backoff, * optional jitter, per-attempt timeout, and {@link AbortController} cancellation. * * The action receives the current attempt index and an {@link AbortSignal}. * The signal should be passed to APIs that support cancellation (e.g. `fetch`, * `axios`, or custom logic). * * @typeParam T - The resolved value type of the action. * * @param action - Asynchronous function to execute. * Receives an object containing: * - `attempt`: Zero-based attempt index. * - `signal`: Abort signal for the current attempt. * * @param options - Optional retry configuration. * * @returns A promise that resolves with the successful result of `action`, * or rejects if all retries fail, retry conditions are not met, * or the operation is aborted. * * @throws {DOMException} * Throws an `AbortError` if the operation is aborted via `AbortController`. * ``` */ export declare const retryAsync: (action: (ctx: { attempt: number; signal: AbortSignal; }) => Promise, { max, delay, maxDelay, jitter, timeout, shouldRetry, signal: externalSignal, }?: RetryOptions) => Promise; /** * Configuration options for {@link retryAsync}. */ declare type RetryOptions = { /** * Maximum number of retry attempts. * * - `0` means no retries (only the initial attempt). * - Default: `2` */ max?: number; /** * Base delay in milliseconds before the first retry. * * Subsequent retries use exponential backoff: * `delay * 2^(attempt - 1)` * * Default: `300` */ delay?: number; /** * Maximum delay in milliseconds between retries. * * Prevents exponential backoff from growing indefinitely. * * Default: `5000` */ maxDelay?: number; /** * Adds random jitter to retry delays to avoid synchronized retries. * * When enabled, the final delay is multiplied by a random factor * between `0.5` and `1.5`. * * Default: `true` */ jitter?: boolean; /** * Per-attempt timeout in milliseconds. * * If the timeout is reached, the current attempt is aborted * via {@link AbortController}. This does NOT cancel underlying * operations that do not support `AbortSignal` (e.g. IndexedDB). * * Default: `undefined` (no timeout) */ timeout?: number; /** * Predicate function that determines whether a failed attempt * should be retried. * * Returning `false` immediately stops retries and rethrows the error. * * @param error - The error thrown by the previous attempt. * @returns `true` to retry, `false` to stop. * * Default: always retry */ shouldRetry?: (error: unknown) => boolean; /** * External {@link AbortSignal} used to cancel all attempts and retries. * * - Aborting this signal stops retries immediately. * - The signal is combined with a per-attempt abort signal. * - Aborting does NOT cancel operations that do not support AbortSignal. */ signal?: AbortSignal; }; /** * Reverses the keys and values of an object. * * Creates a new object where each original value becomes a key * and each original key becomes its corresponding value. * * This function is fully type-safe and preserves literal types * when used with `as const` objects or enums. * * @template T - An object type whose keys and values are valid property keys. * @param obj - The source object to reverse. * @returns A new object with keys and values swapped. * * @example * ```ts * const roles = { * student: "1", * admin: "2", * } as const; * * const reversed = reverseObject(roles); * // => { "1": "student", "2": "admin" } * ``` */ export declare const reverseObject: >(obj: T) => ReverseRecord; export declare type ReverseRecord> = { [K in keyof T as T[K]]: K; }; declare type Reviver = (this: any, key: string, value: any, context?: { source: string; }) => any; /** * Deeply clones a value while safely handling circular references. * Safely deep clone JSON-like data with circular references, and don’t crash. * * - Uses native `structuredClone` when available (fast & spec-compliant) * - Falls back to a custom deep clone implementation for older environments * * Supports: * - Objects, Arrays, Date * - Circular & shared references * * ❌ Fallback clone does NOT support: * - Map / Set * - RegExp, Error * - Functions, DOM nodes * * @typeParam T - Type of the value being cloned * @param value - The value to deep clone * @returns A deep clone of the input value * * @example * ```ts * const obj: any = { a: 1 }; * obj.self = obj; * * const cloned = safeDeepClone(obj); * cloned !== obj; // true * cloned.self === cloned; // true * ``` */ export declare const safeDeepClone: (value: T) => T; /** * Safely parses a JSON string and returns a fallback value on failure. * * This helper is designed for untrusted sources such as `localStorage`, * query params, or API responses. It never throws and guarantees a value * of type `T` is returned. * * Parsing rules: * - If `data` is `null`, `undefined`, or an empty string → returns `fallback` * - If `JSON.parse` throws → returns `fallback` * - If parsed result is `null` or `undefined` → returns `fallback` * * @template T * @param {string | null | undefined} data - The JSON string to parse. * @param {Function(key, value, context)} reviver https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#reviver * @param {T} [ fallback = {} ] - Value returned when parsing fails or result is nullish. Default `{}`. * @returns {T} The parsed JSON value or the fallback. * * @example * safeJsonParse<{ a: number }>('{"a":1}') * // => { a: 1 } * * @example * safeJsonParse('invalid json', {}) * // => {} * * @example * safeJsonParse(null, []) * // => [] * * @example * safeJsonParse('null', { foo: 'bar' }) * // => { foo: 'bar' } * * @example * const bigJSON = '{"gross_gdp": 12345678901234567890}'; * const bigObj = safeJsonParse( * bigJSON, * {}, * (key, value, context) => { * if (key === "gross_gdp" && context) { * return BigInt(context.source); * } * return value; * } * ); * * console.log(bigObj.gross_gdp); // 12345678901234567890n (BigInt) */ export declare const safeJsonParse: >(data: string | null | undefined, fallback?: T, reviver?: Reviver) => T; /** * Safely serializes a data to JSON, handling circular references. * * Circular object references are replaced with the string `"[Circular]"` * instead of throwing a `TypeError`. * * @template T * @param {T} data - The data to stringify. * @param {number} [space] - Number of spaces for pretty-printing (passed to `JSON.stringify`). * @returns {string} A JSON string representation of the data. * * @example * const obj: any = {}; * obj.self = obj; * * safeStringify(obj); * // → '{"self":"[Circular]"}' * * @example * safeStringify({ a: 1 }, 2); * // → '{\n "a": 1\n}' */ export declare const safeStringify: (data: T, space?: number) => string; /** * Shapes an object by picking or omitting specified keys, * with TypeScript inferring exact key types. * * @template T - Original object type. * @template K - Keys to include or exclude (exact literals inferred). * @param obj - Object to shape. * @param keys - Array of keys (use `as const` for smart typing). * @param action - Determines pick or omit, truthy to omit or falsy to pick (default: undefined = pick). * @returns A Partial object with exact types. */ export declare const shape: , K extends keyof T>(obj: T, keys: readonly K[], action?: boolean | number | string | null | undefined) => Partial> | Partial>; /** * Shares a link using the Web Share API (if supported) with a fallback. * Provides callbacks for success and error handling. * * @param data - The share data (title, text, url). * @param options - Configuration and callbacks. * @returns A promise that resolves when the operation completes. */ export declare const shareLink: (data: { title?: string; text?: string; url: string; }, { fallback, onSuccess, onError }?: ShareOptions) => Promise; export declare type shareMethod = 'webShare' | 'copy' | 'window'; /** * Options for the shareLink function. */ export declare interface ShareOptions { /** * Fallback behavior when Web Share API is unsupported or fails. * - 'copy': copy the URL to clipboard (default) * - 'window': open the URL in a new tab */ fallback?: 'copy' | 'window'; /** * Called on successful sharing via any method. * @param method - Which method succeeded ('webShare', 'copy', or 'window') */ onSuccess?: (method: shareMethod) => void; /** * Called when an error occurs. * Note: user cancellation (AbortError) is ignored and does NOT trigger this. * @param error - The error object * @param method - The method that failed ('webShare' or the fallback method) */ onError?: (error: unknown, method: shareMethod) => void; } /** * Simulates an asynchronous operation with configurable delay and failure mode * @param delay Delay in milliseconds (default: 1000ms) * @param isFail Whether to simulate failure (default: false) * @param signal AbortSignal for cancellation * @returns Promise that resolves with 1 or rejects with 0/AbortError */ export declare const simulateAsync: ({ delay, isFail, signal }?: SimulateAsyncOptions) => Promise<1 | 0>; declare interface SimulateAsyncOptions { delay?: number; isFail?: boolean; signal?: AbortSignal; } /** * String (e.g name, username, nickname, fullname) to hexa * @param str string * @returns 'Hexa string' | undefined */ export declare const str2Hex: (str: string) => string | undefined; /** * Creates a throttled function that invokes `func` at most once per `wait` milliseconds. * * @template T - The type of the function to throttle. * @param {T} func - The function to throttle. * @param {number} [wait=300] - The throttle interval in milliseconds. * @returns {(...args: Parameters) => void} - The throttled function. */ export declare const throttle: void>(func: T, wait?: number) => ((...args: Parameters) => void); /** * Throttled function with leading, trailing, and cancellation support. * * @template T - Function type to throttle * @param func - Target function * @param wait - Throttle interval in ms (default: 300) * @param options - { leading?: boolean, trailing?: boolean } * @returns Throttled function with cancel() and flush() methods. */ export declare const throttleAdvanced: void>(func: T, wait?: number, { leading, trailing }?: ThrottleAdvancedOptions) => { (...args: Parameters): void; cancel(): void; flush(): void; pending(): boolean; } & { cancel: () => void; flush: () => void; pending: () => boolean; }; declare interface ThrottleAdvancedOptions { leading?: boolean; trailing?: boolean; } export declare type UUIDv7 = string & { readonly __brand: unique symbol; }; /** * Generate a UUIDv7 (time-ordered, monotonic). * RFC 9562: https://www.rfc-editor.org/rfc/rfc9562.html */ export declare const uuidv7: () => UUIDv7; export { }