@catbee/utils
Version:
A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.
224 lines (221 loc) • 8.52 kB
TypeScript
/*
* The MIT License
*
* Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Appends query parameters to a given URL.
*
* @param {string} url - The base URL to which query parameters will be appended.
* @param {Record<string, string | number>} params - Key-value pairs to add as query parameters.
* @returns {string} The new URL string with query parameters appended.
*
* @example
* appendQueryParams('https://example.com', { page: 1, limit: 10 });
* // -> 'https://example.com/?page=1&limit=10'
*/
declare function appendQueryParams(url: string, params: Record<string, string | number>): string;
/**
* Parses a query string into a key-value object.
*
* @param {string} query - The query string (with or without leading '?').
* @returns {Record<string, string>} Object representing parsed query parameters.
*
* @example
* parseQueryString('?page=1&limit=10');
* // -> { page: '1', limit: '10' }
*/
declare function parseQueryString(query: string): Record<string, string>;
/**
* Validates if a string is a valid URL.
*
* @param {string} url - The URL string to validate.
* @param {boolean} [requireHttps=false] - If true, requires the URL to use HTTPS.
* @returns {boolean} True if the URL is valid, false otherwise.
*/
declare function isValidUrl(url: string, requireHttps?: boolean): boolean;
/**
* Extracts the domain name from a URL.
*
* @param {string} url - The URL to extract the domain from.
* @param {boolean} [removeSubdomains=false] - If true, removes subdomains (returns root domain only).
* @returns {string} The domain name.
*
* @example
* getDomain('https://api.example.com/path');
* // -> 'api.example.com'
*
* getDomain('https://api.example.com/path', true);
* // -> 'example.com'
*/
declare function getDomain(url: string, removeSubdomains?: boolean): string;
/**
* Joins URL paths properly handling slashes.
*
* @param {...string[]} segments - URL path segments to join.
* @returns {string} Joined URL path.
*
* @example
* joinPaths('https://example.com/', '/api/', '/users');
* // -> 'https://example.com/api/users'
*/
declare function joinPaths(...segments: string[]): string;
/**
* Normalizes a URL by resolving relative paths, handling protocol-relative URLs, etc.
*
* @param {string} url - The URL to normalize.
* @param {string} [base] - Optional base URL for resolving relative URLs.
* @returns {string} Normalized URL.
*
* @example
* normalizeUrl('HTTP://Example.COM/foo/../bar');
* // -> 'http://example.com/bar'
*/
declare function normalizeUrl(url: string, base?: string): string;
/**
* Updates or sets a single query parameter in a URL.
*
* @param {string} url - The source URL.
* @param {string} key - Parameter key.
* @param {string | number} value - Parameter value.
* @returns {string} URL with updated parameter.
*
* @example
* updateQueryParam('https://example.com?page=1', 'page', 2); // 'https://example.com?page=2'
*/
declare function updateQueryParam(url: string, key: string, value: string | number): string;
/**
* Creates a URL builder for constructing URLs with a base URL.
*
* @param {string} baseUrl - The base URL to build upon.
* @returns {Object} URL builder methods.
*
* @example
* const api = createUrlBuilder('https://api.example.com');
* api.path('/users', { active: true });
* // -> 'https://api.example.com/users?active=true'
*/
declare function createUrlBuilder(baseUrl: string): {
/**
* Creates a full URL with the given path and query parameters.
*
* @param {string} path - The path to append to the base URL.
* @param {Record<string, any>} [params] - Query parameters to add.
* @returns {string} The complete URL.
*/
path(path: string, params?: Record<string, any>): string;
/**
* Creates a full URL with query parameters but no additional path.
*
* @param {Record<string, any>} params - Query parameters to add.
* @returns {string} The complete URL with query parameters.
*/
query(params: Record<string, any>): string;
};
/**
* Extracts specific query parameters from a URL.
*
* @param {string} url - The URL to extract parameters from.
* @param {string[]} paramNames - Names of parameters to extract.
* @returns {Record<string, string>} Object containing the extracted parameters.
*/
declare function extractQueryParams(url: string, paramNames: string[]): Record<string, string>;
/**
* Removes specified query parameters from a URL.
*
* @param {string} url - The URL to modify.
* @param {string[]} paramsToRemove - Names of parameters to remove.
* @returns {string} URL with parameters removed.
*/
declare function removeQueryParams(url: string, paramsToRemove: string[]): string;
/**
* Gets the file extension from a URL path.
*
* @param {string} url - The URL to examine.
* @returns {string} The file extension (without dot) or empty string if none found.
*
* @example
* getExtension('https://example.com/document.pdf?v=1');
* // -> 'pdf'
*/
declare function getExtension(url: string): string;
/**
* Parses URL query parameters into a strongly-typed object.
*
* @template T Expected type of the query parameters
* @param {string} url - The URL to parse.
* @param {Record<keyof T, (val: string) => any>} [converters] - Type converters for params.
* @returns {Partial<T>} Typed query parameters.
*
* @example
* parseTypedQueryParams<{page: number, q: string}>('https://example.com?page=2&q=test', {
* page: Number,
* q: String
* });
* // -> { page: 2, q: 'test' }
*/
declare function parseTypedQueryParams<T extends Record<string, any>>(url: string, converters?: Record<keyof T, (val: string) => any>): Partial<T>;
/**
* Extracts the subdomain from a URL.
*
* @param {string} url - The URL.
* @returns {string} Subdomain or empty string.
*
* @example
* getSubdomain('https://api.example.com'); // 'api'
* getSubdomain('https://www.blog.example.com'); // 'www.blog'
*/
declare function getSubdomain(url: string): string;
/**
* Checks if a URL is relative (not absolute).
*
* @param {string} url - The URL to check.
* @returns {boolean} True if relative.
*
* @example
* isRelativeUrl('/path/to/page'); // true
* isRelativeUrl('https://example.com/page'); // false
*/
declare function isRelativeUrl(url: string): boolean;
/**
* Converts a relative URL to an absolute URL using a base URL.
*
* @param {string} relativeUrl - The relative URL.
* @param {string} baseUrl - The base URL.
* @returns {string} Absolute URL.
*
* @example
* toAbsoluteUrl('/api/users', 'https://example.com'); // 'https://example.com/api/users'
*/
declare function toAbsoluteUrl(relativeUrl: string, baseUrl: string): string;
/**
* Sanitizes a URL by removing dangerous protocols and normalizing.
*
* @param {string} url - The URL to sanitize.
* @param {string[]} [allowedProtocols=['http', 'https']] - Allowed protocols.
* @returns {string | null} Sanitized URL or null if unsafe.
*
* @example
* sanitizeUrl('javascript:alert(1)'); // null
* sanitizeUrl('https://example.com'); // 'https://example.com/'
*/
declare function sanitizeUrl(url: string, allowedProtocols?: string[]): string | null;
export { appendQueryParams, createUrlBuilder, extractQueryParams, getDomain, getExtension, getSubdomain, isRelativeUrl, isValidUrl, joinPaths, normalizeUrl, parseQueryString, parseTypedQueryParams, removeQueryParams, sanitizeUrl, toAbsoluteUrl, updateQueryParam };