/** * @author Cheng */ interface BrowserInfo { engine: string; // webkit gecko presto trident engineVs: string; platform: string; // desktop mobile supporter: string; // chrome safari firefox opera iexplore edge supporterVs: string; system: string; // windows macos linux android ios systemVs: string; shell: string; // wechat qq uc 360 2345 sougou liebao maxthon shellVs: string; appleType: string; colorScheme: string; } /** * A resolved preference value and its human-readable label. * * @category Browser Information */ interface PreferenceResult { /** Machine-readable value used by application logic. */ value: T; /** Human-readable label suitable for display. */ label: string; } interface DefineListeners { [key: string]: any; } type SingleValueUrlParams = { [key: string]: string; }; type ThrottleFunc any> = (...args: Parameters) => ReturnType | null; type DebounceFunc any> = (...args: Parameters) => ReturnType | null; interface IsNumberOptions { isNaNAsNumber?: boolean; isInfinityAsNumber?: boolean; isUnFiniteAsNumber?: boolean; } interface ZResResponse { status: number; data: { code: number; }; } interface ZResIsValidResOptions { validStatusRange?: [number, number]; validCode?: number[]; } interface RepeatUntilOptions { interval?: number; times?: number; context?: any; args?: Array; } type LoadScriptReturns = Promise; type SimpleType = string | number | boolean | null | undefined; type MazeyObject = any; type MazeyFnParams = any[]; type MazeyFnReturn = any; type MazeyFunction = (...args: any[]) => any; type MazeyFn = (...args: MazeyFnParams) => MazeyFnReturn; interface WebPerformance { [key: string]: string | number; } type MazeyElement = HTMLElement | null; type MazeyDate = Date | string | number; type URLChangeTrigger = "load" | "popstate" | "hashchange" | "pushState" | "replaceState"; interface URLChangeInfo { url: string; oldUrl: string; trigger: URLChangeTrigger; } interface OnURLChangeOptions { fireOnInit?: boolean; } type InvestmentReturnRate = number | string; /** * Calculate an investment's Compound Annual Growth Rate (CAGR). * * Numeric total returns use decimal ratios. For example, `0.202` represents * `20.2%`. String total returns use percentage values, so `"20.2%"` and * `"20.2"` both represent `20.2%`. A trailing percent sign is optional, and * the complete trimmed string must be a finite JavaScript number. Scientific * notation such as `"2.02e1%"` is accepted. * * The returned CAGR is a decimal ratio and is not rounded. The calculation * uses: * * `CAGR = (1 + totalReturn)^(365 / durationInDays) - 1` * * Usage: * * ```typescript * import { * calculateCAGR, * floatToPercent, * } from "mazey"; * * const cagr = calculateCAGR( * "2022-04-01", * "2025-10-01", * "20.2%" * ); * const equivalentCagr = calculateCAGR( * "2022-04-01", * "2025-10-01", * 0.202 * ); * const negativeCagr = calculateCAGR( * "2022-04-01", * "2025-10-01", * "-15.5%" * ); * * console.log({ * cagr, * equivalentCagr, * negativeCagr, * percentage: floatToPercent(cagr, 2), * }); * ``` * * Possible output: * * ```text * { * cagr: 0.053908..., * equivalentCagr: 0.053908..., * negativeCagr: -0.046926..., * percentage: "5.39%" * } * ``` * * @param startDate Start date as a supported structured string, millisecond timestamp, or `Date`. * @param endDate End date in the same accepted forms. It must be strictly later than `startDate`. * @param totalReturnRate Total period return. Numbers are decimal ratios; strings are percentage values. * @returns The unrounded CAGR as a decimal ratio. * @throws {TypeError} If either date or the total return is invalid. * @throws {RangeError} If the dates are not increasing, the total return is at most `-1`, or the result is not finite. * @remarks Duration uses the exact elapsed milliseconds, including time of day, converted to fractional days. A financial year is always fixed at 365 days. Input `Date` objects are copied and never mutated. * @category Calculate and Formula */ declare function calculateCAGR(startDate: MazeyDate, endDate: MazeyDate, totalReturnRate: InvestmentReturnRate): number; /** * Compute the length of the longest common substring of two strings. * * Usage: * * ```javascript * import { longestComSubstring } from "mazey"; * * const ret = longestComSubstring("fish", "finish"); * console.log(ret); * ``` * * Output: * * ```text * 3 * ``` * * @param {string} aStr String * @param {string} bStr String * @returns {number} Length * @category Calculate and Formula */ declare function longestComSubstring(aStr: string, bStr: string): number; /** * Alias of `longestComSubstring`. * * @hidden */ declare function calLongestCommonSubstring(aStr: string, bStr: string): number; /** * Compute the length of the longest common subsequence of two strings. * * Usage: * * ```javascript * import { longestComSubsequence } from "mazey"; * * const ret = longestComSubsequence("fish", "finish"); * console.log(ret); * ``` * * Output: * * ```text * 4 * ``` * * @param {string} aStr The first string. * @param {string} bStr The second string. * @returns {number} The length of the longest common subsequence. * @category Calculate and Formula */ declare function longestComSubsequence(aStr: string, bStr: string): number; /** * Alias of `longestComSubsequence`. * * @hidden */ declare function calLongestCommonSubsequence(aStr: string, bStr: string): number; /** * Return whether a random value falls within the given probability. * * Usage: * * ```javascript * import { isHit } from "mazey"; * * const ret = isHit(0.5); // A 50% chance of returning true. * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * Example: Test the precision. * * ```javascript * let trueCount = 0; * let falseCount = 0; * new Array(1000000).fill(0).forEach(() => { * if (isHit(0.5)) { * trueCount++; * } else { * falseCount++; * } * }); * console.log(trueCount, falseCount); * ``` * * Output: * * ```text * 499994 500006 * ``` * * @param {number} rate Probability expressed as a value from 0 to 1. * @returns {boolean} Whether the random value is less than the probability. * @category Calculate and Formula */ declare function isHit(rate: number): boolean; /** * Alias of `isHit`. * * @hidden */ declare function inRate(rate: number): boolean; /** * Precision used by `formatLocalDateTime`. * * @category Util */ type LocalDateTimePrecision = "minute" | "second" | "millisecond"; /** * Parse an HTML `datetime-local` value into a local `Date`. * * Accepted normalized values use a year with at least four digits followed by * `-MM-DDTHH:mm`, with optional seconds and 1-3 fractional-second digits. * Components are validated strictly, so impossible dates and times return * `null` instead of being normalized by `Date`. * * Usage: * * ```javascript * import { parseLocalDateTime } from "mazey"; * * const date = parseLocalDateTime("2026-07-21T14:30:45.123"); * console.log(date?.getFullYear()); * console.log(date?.getHours()); * console.log(date?.getMilliseconds()); * ``` * * Output: * * ```text * 2026 * 14 * 123 * ``` * * @param value A normalized HTML `datetime-local` value without a timezone. * @returns A local `Date`, or `null` when the value is malformed or represents an impossible local date and time. * @remarks The value is interpreted using the runtime's local timezone. Timezone suffixes, surrounding whitespace, and date-only values are rejected. * @category Util */ declare function parseLocalDateTime(value: string): Date | null; /** * Format a `Date` as an HTML `datetime-local` value using local fields. * * | Precision | Output shape | * | ------------- | ----------------------------- | * | `minute` | `YYYY-MM-DDTHH:mm` | * | `second` | `YYYY-MM-DDTHH:mm:ss` | * | `millisecond` | `YYYY-MM-DDTHH:mm:ss.SSS` | * * Usage: * * ```javascript * import { formatLocalDateTime } from "mazey"; * * const date = new Date(2026, 6, 21, 14, 30, 45, 123); * const minutes = formatLocalDateTime(date); * const seconds = formatLocalDateTime(date, { precision: "second" }); * const milliseconds = formatLocalDateTime(date, { * precision: "millisecond", * }); * console.log(minutes); * console.log(seconds); * console.log(milliseconds); * ``` * * Output: * * ```text * 2026-07-21T14:30 * 2026-07-21T14:30:45 * 2026-07-21T14:30:45.123 * ``` * * @param date A valid `Date` to format. * @param options Formatting options. Precision defaults to `minute`. * @returns A normalized HTML `datetime-local` value containing local calendar fields. The year is padded to at least four digits. * @throws {TypeError} If `date` is not a `Date` or `precision` is unsupported. * @throws {RangeError} If `date` is invalid or its local year is earlier than 1. * @remarks This function does not call `toISOString()` and does not convert the value to UTC. It does not mutate the supplied `Date`. * @category Util */ declare function formatLocalDateTime(date: Date, options?: { precision?: LocalDateTimePrecision; }): string; /** * Get the current timestamp in milliseconds. * * Usage: * * ```javascript * import { mNow } from "mazey"; * * const ret = mNow(); * console.log(ret); * ``` * * Output: * * ```text * 1585325367122 * ``` * * @returns {number} The current timestamp in milliseconds. * @category Util */ declare function mNow(): number; /** * Calculate the interval between two dates or timestamps. * * The default `d` type returns the number of whole days. The `text` type * returns an English duration using days, hours, minutes, and seconds while * omitting zero-valued units. A zero interval returns `"0 seconds"`. Any other * type returns the number of whole seconds. Negative intervals and invalid * dates return an empty string. * * Usage: * * ```javascript * import { getDateDifference } from "mazey"; * * const days = getDateDifference(0, 90061000); * const text = getDateDifference(0, 90061000, { type: "text" }); * const compactText = getDateDifference(0, 90060000, { type: "text" }); * const dateStringDays = getDateDifference( * "2020-03-28 00:09:27", * "2023-04-18 10:54:00" * ); * console.log(days); * console.log(text); * console.log(compactText); * console.log(dateStringDays); * ``` * * Output: * * ```text * 1 * 1 day 1 hour 1 minute 1 second * 1 day 1 hour 1 minute * 1116 * ``` * * @param start Start date or timestamp. * @param end End date or timestamp. * @param options Formatting options. Use `d` for whole days or `text` for an English duration. * @returns Whole days, whole seconds, an English duration, or an empty string for a negative or invalid interval. * @remarks Strings in `YYYY-MM-DD HH:mm:ss` format are normalized and parsed as local time. Other date strings use the runtime's native `Date` parser; use timestamps or ISO strings with an explicit timezone when parsing must be portable. * @category Util */ declare function getDateDifference(start?: number | string | Date, end?: number | string | Date, options?: { type?: string; }): number | string; /** * Alias of `getDateDifference`. * * @hidden */ declare function getFriendlyInterval(start?: number | string | Date, end?: number | string | Date, options?: { type?: string; }): number | string; /** * Format a duration in milliseconds using its largest applicable English unit. * * Values are rounded to at most one decimal place. Negative durations are * clamped to zero, and non-finite values return `"0 seconds"`. * * Usage: * * ```javascript * import { formatDurationFromMs } from "mazey"; * * formatDurationFromMs(500); // "0.5 seconds" * formatDurationFromMs(90000); // "1.5 minutes" * formatDurationFromMs(3600000); // "1 hour" * formatDurationFromMs(129600000); // "1.5 days" * ``` * * @param {number} durationMs Duration in milliseconds. * @returns {string} Concise duration using seconds, minutes, hours, or days. * @category Util */ declare function formatDurationFromMs(durationMs: number): string; /** * Check whether an unknown value represents a valid date. * * Valid inputs include `Date` instances, finite millisecond timestamps, * structured local date strings, and ISO 8601 strings with `Z` or a numeric * timezone offset. Structured strings are parsed into numeric components and * validated strictly, so invalid calendar dates are not normalized. * * Supported string forms are `YYYY-MM-DD`, `YYYY-MM-DD HH:mm[:ss]`, * `YYYY-MM-DDTHH:mm[:ss]`, and the same `T`-separated date-time with `Z` or * a `+HH:mm`/`-HH:mm` offset. Zoned strings may include 1-3 millisecond digits. * * Usage: * * ```javascript * import { isValidDate } from "mazey"; * * const ret1 = isValidDate(1577877720000); * const ret2 = isValidDate("2020-01-01 11:22"); * const ret3 = isValidDate("2020-02-30"); * const ret4 = isValidDate(new Date("invalid")); * * console.log(ret1, ret2, ret3, ret4); * ``` * * Output: * * ```text * true true false false * ``` * * @param value A `Date`, millisecond timestamp, or supported structured date string. * @returns Whether the value represents a valid date. * @category Util */ declare function isValidDate(value: unknown): boolean; /** * Check whether a date is today in the runtime's local timezone. * * Usage: * * ```javascript * import { isToday } from "mazey"; * * const ret = isToday(new Date()); * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * @param date A `Date`, millisecond timestamp, or string accepted by `isValidDate`. * @returns Whether the value has the current local year, month, and day. Invalid input returns `false`. * @remarks Hours, minutes, seconds, and milliseconds are ignored. Results depend on the runtime's local timezone. * @category Util */ declare function isToday(date: MazeyDate): boolean; /** * Check whether a date is in the current local calendar year. * * Usage: * * ```javascript * import { isThisYear } from "mazey"; * * const ret = isThisYear(new Date()); * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * @param date A `Date`, millisecond timestamp, or string accepted by `isValidDate`. * @returns Whether the value has the current local year. Invalid input returns `false`. * @remarks Results depend on the runtime's local timezone. * @category Util */ declare function isThisYear(date: MazeyDate): boolean; /** * Check whether a date is in the current local calendar month and year. * * Usage: * * ```javascript * import { isThisMonth } from "mazey"; * * const ret = isThisMonth(new Date()); * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * @param date A `Date`, millisecond timestamp, or string accepted by `isValidDate`. * @returns Whether the value has the current local year and month. Invalid input returns `false`. * @remarks Results depend on the runtime's local timezone. * @category Util */ declare function isThisMonth(date: MazeyDate): boolean; /** * Check whether a date is in the current Monday-first local calendar week. * * Usage: * * ```javascript * import { isThisWeek } from "mazey"; * * const ret = isThisWeek(new Date()); * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * @param date A `Date`, millisecond timestamp, or string accepted by `isValidDate`. * @returns Whether the value is in the current local week. Invalid input returns `false`. * @remarks The week begins on Monday and ends before the following Monday. Boundaries use local time and a half-open range. * @category Util */ declare function isThisWeek(date: MazeyDate): boolean; /** * Check whether a date is within the current local clock hour. * * Usage: * * ```javascript * import { isThisHour } from "mazey"; * * const ret = isThisHour(new Date()); * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * @param date A `Date`, millisecond timestamp, or string accepted by `isValidDate`. * @returns Whether the value has the current local year, month, day, and hour. Invalid input returns `false`. * @remarks Minutes, seconds, and milliseconds are ignored. Results depend on the runtime's local timezone. * @category Util */ declare function isThisHour(date: MazeyDate): boolean; /** * Format the absolute distance from a date to now in concise English words. * * Usage: * * ```javascript * import { formatDistanceToNow } from "mazey"; * * const ret = formatDistanceToNow(new Date(Date.now() - 60 * 60 * 1000)); * console.log(ret); * ``` * * Output: * * ```text * about 1 hour * ``` * * @param date A `Date`, millisecond timestamp, or string accepted by `isValidDate`. * @returns The absolute approximate distance phrase, or an empty string for invalid input. * @remarks Past and future dates use the same wording without `ago` or `in`. Months and years use fixed approximate durations of 30 and 365 days. * @category Util */ declare function formatDistanceToNow(date: MazeyDate): string; /** * Return the formatted date string in the given format. * * Supported format tokens: * * | Token | Meaning | Range or example | * | ------ | -------------------------------------- | ---------------- | * | `yyyy` | Four-digit year | `2022` | * | `MM` | Two-digit month | `01`–`12` | * | `dd` | Two-digit day of the month | `01`–`31` | * | `HH` | Two-digit hour using the 24-hour clock | `00`–`23` | * | `hh` | Two-digit hour using the 12-hour clock | `01`–`12` | * | `mm` | Two-digit minute | `00`–`59` | * | `ss` | Two-digit second | `00`–`59` | * | `a` | Uppercase meridiem indicator | `AM` or `PM` | * * The function creates a native `Date` and reads its local date and time * fields. Timestamp output can therefore differ between runtime time zones. * * Usage: * * ```javascript * import { formatDate } from "mazey"; * * const ret1 = formatDate(); * const ret2 = formatDate("Tue Jan 11 2022 14:12:26 GMT+0800 (China Standard Time)", "yyyy-MM-dd hh:mm:ss a"); * const ret3 = formatDate(1641881235000, "yyyy-MM-dd hh:mm:ss a"); * const ret4 = formatDate(new Date(2014, 1, 11), "MM/dd/yyyy"); * console.log("Default formatDate value:", ret1); * console.log("String formatDate value:", ret2); * console.log("Number formatDate value:", ret3); * console.log("Date formatDate value:", ret4); * ``` * * Output: * * ```text * Default formatDate value: 2023-01-11 * String formatDate value: 2022-01-11 02:12:26 PM * Number formatDate value: 2022-01-11 02:07:15 PM * Date formatDate value: 02/11/2014 * ``` * * @param {MazeyDate} dateIns Original date value. Defaults to the current date and time. * @param {string} format Format string composed of supported format tokens. Defaults to `yyyy-MM-dd`. * @returns {string} The formatted date string. * @throws {RangeError} If `dateIns` is not a valid date. * @category Util */ declare function formatDate(dateIns?: MazeyDate, format?: string): string; /** * Generate a local-time Calendar Versioning string from a date. * * The conceptual format is `yyyy.MMdd.HHmmss`. Leading zeroes are removed * from each segment to keep numeric Semantic Versioning identifiers valid. * * Usage: * * ```javascript * import { generateCalendarVersion } from "mazey"; * * const ret = generateCalendarVersion(new Date(2026, 6, 11, 7, 40, 35)); * console.log(ret); * ``` * * Output: * * ```text * 2026.711.74035 * ``` * * @param {MazeyDate} dateIns Original date. Defaults to the current date. * @returns {string} Return the generated calendar version. * @throws {RangeError} If `dateIns` is not a valid date. * @category Util */ declare function generateCalendarVersion(dateIns?: MazeyDate): string; /** * Copy/Clone Object deeply. * * Custom class instances are copied as plain objects containing their own * properties. Unsupported native instances are preserved by reference. * * Usage: * * ```javascript * import { deepCopy } from "mazey"; * * const ret1 = deepCopy(["a", "b", "c"]); * const ret2 = deepCopy("abc"); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * ["a", "b", "c"] * abc * ``` * * @param {object} obj The value to clone. * @returns {object} Returns the deep cloned value. * @category Util */ declare function deepCopy(obj: T): T; /** * Recursively freeze an object and its nested enumerable values. * * Primitive values and objects that are already frozen are returned unchanged. * * Usage: * * ```javascript * import { deepFreeze } from "mazey"; * * const config = deepFreeze({ * api: { * timeout: 5000, * }, * }); * * console.log(Object.isFrozen(config)); * console.log(Object.isFrozen(config.api)); * ``` * * Output: * * ```text * true * true * ``` * * @param value The value to freeze. * @returns The original value with its nested enumerable values frozen. * @category Util */ declare function deepFreeze(value: T): T; /** * Shallowly assign defined properties from one or more sources. * * The target is mutated. Only own enumerable string-keyed properties are * considered, and `undefined` values are skipped. Other falsy values such as * `null`, an empty string, `0`, and `false` are assigned. * * Usage: * * ```javascript * import { assignDefined } from "mazey"; * * const options = assignDefined( * { retries: 3, verbose: true }, * { retries: undefined, verbose: false }, * ); * * console.log(options); * ``` * * Output: * * ```text * { retries: 3, verbose: false } * ``` * * @param target The object to mutate. * @param sources Sources applied from left to right. * @returns The mutated target. * @category Util */ declare function assignDefined(target: T, ...sources: ReadonlyArray | undefined>): T; /** * Alias of `deepCopy`. * * @hidden */ declare function deepCopyObject(obj: T): T; /** * Convert CamelCase to KebabCase. * * Usage: * * ```javascript * import { convertCamelToKebab } from "mazey"; * * const ret1 = convertCamelToKebab("ABC"); * const ret2 = convertCamelToKebab("aBC"); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * a-b-c * a-b-c * ``` * * @param {string} camelCase "aBC" or "ABC" * @returns {string} "a-b-c" * @category Util */ declare function convertCamelToKebab(camelCase: string): string; /** * Convert KebabCase to CamelCase. * * Usage: * * ```javascript * import { convertKebabToCamel } from "mazey"; * * const ret1 = convertKebabToCamel("a-b-c"); * const ret2 = convertKebabToCamel("a-bb-cc"); * console.log(ret1, ret2); * ``` * * Output: * * ```text * aBC aBbCc * ``` * * @param {string} kebabCase "a-bb-cc" * @returns {string} "aBbCc" * @category Util */ declare function convertKebabToCamel(kebabCase: string): string; /** * Alias of `convertCamelToKebab`. * * @hidden */ declare function camelCaseToKebabCase(camelCase: string): string; /** * Convert CamelCase to Underscore. * * Usage: * * ```javascript * import { convertCamelToUnder } from "mazey"; * * const ret1 = convertCamelToUnder("ABC"); * const ret2 = convertCamelToUnder("aBC"); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * a_b_c * a_b_c * ``` * * @param {string} camelCase "aBC" or "ABC" * @returns {string} "a_b_c" * @category Util */ declare function convertCamelToUnder(camelCase: string): string; /** * Convert Underscore to CamelCase. * * Usage: * * ```javascript * import { convertUnderToCamel } from "mazey"; * * const ret1 = convertUnderToCamel("a_b_c"); * const ret2 = convertUnderToCamel("a_bb_cc"); * console.log(ret1, ret2); * ``` * * Output: * * ```text * aBC aBbCc * ``` * * @param {string} underCase "a_bb_cc" * @returns {string} "aBbCc" * @category Util */ declare function convertUnderToCamel(underCase: string): string; /** * Alias of `convertCamelToUnder`. * * @hidden */ declare function camelCase2Underscore(camelCase: string): string; /** * Convert text to a deterministic uppercase ASCII JavaScript identifier. * * Characters outside `A-Z`, `a-z`, `0-9`, `_`, and `$` become `_`. A result * beginning with a digit is prefixed with `_`; an empty input therefore returns `_`. * * Usage: * * ```javascript * import { toJavaScriptGlobalName } from "mazey"; * * const globalName = toJavaScriptGlobalName("@scope/my-library"); * console.log(globalName); * ``` * * Output: * * ```text * _SCOPE_MY_LIBRARY * ``` * * @param value Text such as a package name or bundle filename. * @returns An uppercase identifier suitable for an IIFE global name. * @throws TypeError when `value` is not a string. * @category Util */ declare function toJavaScriptGlobalName(value: string): string; /** * Remove leading and trailing whitespace or specified characters from string. * * Note: This method is used to replace the native `String.prototype.trim()`. But it is not necessary to use it in modern browsers. * * Usage: * * ```javascript * import { mTrim } from "mazey"; * * const ret1 = mTrim(" 1 2 3 "); * const ret2 = mTrim("abc "); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * 1 2 3 * abc * ``` * * @param {string} str The string to trim. * @returns {string} Trimmed string. * @category Util * @hidden */ declare function mTrim(str: string): string; /** * Check whether it is a valid JSON string. * * Usage: * * ```javascript * import { isJSONString } from "mazey"; * * const ret1 = isJSONString(`['a', 'b', 'c']`); * const ret2 = isJSONString(`["a", "b", "c"]`); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * false * true * ``` * * @param {string} str The string to check. * @returns {boolean} Return the result of checking. * @category Util */ declare function isJSONString(str: string): boolean; /** * Alias of `isJSONString`. * * @hidden */ declare function isJsonString(str: string): boolean; /** * Parse a JSON string and return a caller-defined fallback when parsing fails. * * Usage: * * ```javascript * import { parseJsonSafe } from "mazey"; * * const data = parseJsonSafe('{"enabled":true}'); * const fallback = parseJsonSafe("invalid", {}); * ``` * * @param value JSON string to parse. * @param fallback Value returned when parsing fails. Defaults to `null`. * @returns The parsed JSON value or the supplied fallback. * @category Util */ declare function parseJsonSafe(value: string, fallback?: F): T | F; /** * Generate a random string of number, `genRndNumString(7)` => "7658495". * * Usage: * * ```javascript * import { genRndNumString } from "mazey"; * * const ret1 = genRndNumString(4); * const ret2 = genRndNumString(7); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * 9730 * 2262490 * ``` * * @param {number} n Length * @returns {string} Return the random string. * @category Util */ declare function genRndNumString(n?: number): string; /** * Alias of `genRndNumString`. * * @hidden */ declare function generateRndNum(n?: number): string; /** * Generate a numeric identifier by combining the current timestamp with a * random numeric suffix. * * Usage: * * ```javascript * import { genUniqueNumString } from "mazey"; * * const ret1 = genUniqueNumString(); * const ret2 = genUniqueNumString(3); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * 1538324722364123 * 1538324722364123 * ``` * * @param {number} n Length of the random numeric suffix. * @returns {string} A timestamp-based numeric identifier. * @category Util */ declare function genUniqueNumString(n?: number): string; /** * Alias of `genUniqueNumString`. * * @hidden */ declare function generateUniqueNum(n?: number): string; /** * Convert a floating-point ratio to a percentage string. * * Usage: * * ```javascript * import { floatToPercent } from "mazey"; * * const ret1 = floatToPercent(0.2); * const ret2 = floatToPercent(0.2, 2); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * 20% * 20.00% * ``` * * @param {number} num Floating-point ratio to convert. * @param {number} fixSize Number of decimal places in the percentage. * @returns {string} The percentage string. * @category Util */ declare function floatToPercent(num: number, fixSize?: number): string; /** * Format a number with a fixed number of decimal places. * * Usage: * * ```javascript * import { floatFixed } from "mazey"; * * const ret1 = floatFixed(0.2); * const ret2 = floatFixed(0.2, 2); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * 0 * 0.20 * ``` * * @param num Number or numeric string to format. * @param size Number of decimal places. * @returns The fixed-point string. * @category Util */ declare function floatFixed(num: number | string, size?: number): string; /** * Limit how frequently a function can be invoked over time. * * Usage: * * ```javascript * import { throttle } from "mazey"; * * const foo = throttle(() => { * console.log("The function will be invoked at most once per every wait 1000 milliseconds."); * }, 1000, { leading: true }); * ``` * * Reference: [Lodash](https://lodash.com/docs/4.17.15#throttle) * * @param func Function to throttle. * @param wait Minimum interval between invocations, in milliseconds. * @param options.leading Whether to invoke on the leading edge. * @param options.trailing Whether to invoke on the trailing edge. * @returns The throttled function. * @category Util */ declare function throttle MazeyFnReturn>(func: T, wait: number, options?: { leading?: boolean; trailing?: boolean; }): ThrottleFunc; /** * Delay function execution until the specified time has passed since the last * invocation. * * Usage: * * ```javascript * import { debounce } from "mazey"; * * const foo = debounce(() => { * console.log("The debounced function will only be invoked in 1000 milliseconds, the other invoking will disappear during the wait time."); * }, 1000, true); * ``` * * @param func Function to debounce. * @param wait Delay after the last invocation, in milliseconds. * @param immediate Whether to invoke on the leading edge instead. * @returns The debounced function. * @category Util */ declare function debounce MazeyFnReturn>(func: T, wait: number, immediate?: boolean): DebounceFunc; /** * Check whether a value is a number allowed by the supplied options. * * Usage: * * ```javascript * import { isNumber } from "mazey"; * * const ret1 = isNumber(123); * const ret2 = isNumber("123"); * // Default: NaN, Infinity is not Number * const ret3 = isNumber(Infinity); * const ret4 = isNumber(Infinity, { isInfinityAsNumber: true }); * const ret5 = isNumber(NaN); * const ret6 = isNumber(NaN, { isNaNAsNumber: true, isInfinityAsNumber: true }); * console.log(ret1, ret2, ret3, ret4, ret5, ret6); * ``` * * Output: * * ```text * true false false true false true * ``` * * @param {*} num Value to check. * @param options Controls whether `NaN`, `Infinity`, or other non-finite values count as numbers. * @returns {boolean} Whether the value is an allowed number. * @category Util */ declare function isNumber(num: unknown, options?: IsNumberOptions): boolean; /** * Invoke a value only when it is a function. * * Usage: * * ```javascript * import { invokeFn } from "mazey"; * * const ret = invokeFn(() => { * console.log("invokeFn"); * }); * ``` * * @param {function} fn Potential function to invoke. * @param params Arguments passed to the function. * @returns The function result, or `null` when `fn` is not callable. * @category Util */ declare function invokeFn(fn: MazeyFunction | null | undefined, ...params: Parameters): ReturnType | null; /** * Alias of `invokeFn`. * * @hidden */ declare function doFn(fn: MazeyFunction | null | undefined, ...params: Parameters): ReturnType | null; /** * Verify the validity of a non-empty array. * * Usage: * * ```javascript * import { isNonEmptyArray } from "mazey"; * * const ret = isNonEmptyArray([1, 2, 3]); * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * @category Util */ declare function isNonEmptyArray(arr: Array): boolean; /** * Verify the validity of a pure object. * * Usage: * * ```javascript * import { isPureObject } from "mazey"; * * const ret1 = isPureObject({ a: 1 }); * const ret2 = isPureObject("abc"); * const ret3 = isPureObject(null); * const ret4 = isPureObject([]); * * console.log(ret1, ret2, ret3, ret4); * ``` * * Output: * * ```text * true false false false * ``` * * @param {MazeyObject} obj The object to verify. * @returns {boolean} Return TRUE if the object is a pure object. * @category Util */ declare function isPureObject(obj: MazeyObject): boolean; /** * Verify the validity of a function. * * Usage: * * ```javascript * import { isFunction } from "mazey"; * * const ret1 = isFunction(() => {}); * const ret2 = isFunction("abc"); * const ret3 = isFunction(null); * console.log(ret1, ret2, ret3); * ``` * * Output: * * ```text * true false false * ``` * * @param {MazeyObject} fn The function to verify. * @returns {boolean} Return TRUE if the object is a function. * @category Util */ declare function isFunction(fn: MazeyObject): boolean; /** * Verify the validity of a string. * * Usage: * * ```javascript * import { isString } from "mazey"; * * const ret1 = isString("abc"); * const ret2 = isString({ a: 1 }); * const ret3 = isString(null); * console.log(ret1, ret2, ret3); * ``` * * Output: * * ```text * true false false * ``` * * @param {MazeyObject} str The string to verify. * @returns {boolean} Return TRUE if the object is a string. * @category Util */ declare function isString(str: MazeyObject): boolean; /** * Verify the validity of a boolean. * * Usage: * * ```javascript * import { isBool } from "mazey"; * * const ret1 = isBool(true); * const ret2 = isBool({ a: 1 }); * const ret3 = isBool("abc"); * const ret4 = isBool(null); * console.log(ret1, ret2, ret3, ret4); * ``` * * Output: * * ```text * true false false false * ``` * * @param {MazeyObject} bool The boolean to verify. * @returns {boolean} Return TRUE if the object is a boolean. * @category Util */ declare function isBool(bool: MazeyObject): boolean; /** * Alias of `isBool`. */ declare function isBoolean(bool: MazeyObject): boolean; /** * Verify the validity of a value. * * Usage: * * ```javascript * import { isUdfOrNul } from "mazey"; * * const ret1 = isUdfOrNul(undefined); * const ret2 = isUdfOrNul(null); * const ret3 = isUdfOrNul("abc"); * console.log(ret1, ret2, ret3); * ``` * * Output: * * ```text * true true false * ``` * * @param {MazeyObject} val The value to verify. * @returns {boolean} Return TRUE if the object is undefined or null. * @category Util */ declare function isUdfOrNul(val: MazeyObject): boolean; /** * Verify the validity of an array. * * Usage: * * ```javascript * import { isArray } from "mazey"; * * const ret1 = isArray([1, 2, 3]); * const ret2 = isArray({ a: 1 }); * const ret3 = isArray("abc"); * const ret4 = isArray(null); * console.log(ret1, ret2, ret3, ret4); * ``` * * Output: * * ```text * true false false false * ``` * * @param {MazeyObject} obj The object to verify. * @returns {boolean} Return TRUE if the object is an array. * @category Util */ declare function isArray(obj: MazeyObject): boolean; /** * Verify the validity of a non-empty object. * * Usage: * * ```javascript * import { isNonEmptyObject } from "mazey"; * * const ret1 = isNonEmptyObject({ a: 1 }); * const ret2 = isNonEmptyObject({}); * const ret3 = isNonEmptyObject("abc"); * const ret4 = isNonEmptyObject(null); * console.log(ret1, ret2, ret3, ret4); * ``` * * Output: * * ```text * true false false false * ``` * * @param obj * @returns */ declare function isNonEmptyObject(obj: MazeyObject): boolean; /** * Convert newline characters `\n` into HTML line breaks `
`. * * Usage: * * ```javascript * import { convertToHtmlBreaks } from "mazey"; * * const ret1 = convertToHtmlBreaks("a\nb\nc"); * const ret2 = convertToHtmlBreaks("a\n\nbc"); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * a
b
c * a

bc * ``` * * @param {string} str The string to make a new line. * @returns {string} A newline with `br`. * @category Util */ declare function convertToHtmlBreaks(str: string): string; /** * Alias of `convertToHtmlBreaks`. * * @hidden */ declare function newLine(str: string): string; /** * Remove HTML tags from a string, and optionally newline characters. * * Usage: * * ```javascript * import { removeHTML } from "mazey"; * * const ret = removeHTML("
hello world
"); * console.log(ret); * ``` * * Output: * * ```text * hello world * ``` * * @param {string} str A string that may contain HTML tags. * @returns {string} The string with HTML tags removed. * @category Util */ declare function removeHTML(str: string, options?: { removeNewLine?: boolean; }): string; /** * Alias of `removeHTML`. * * @hidden */ declare function removeHtml(str: string, options?: { removeNewLine?: boolean; }): string; /** * Alias of `removeHTML`. * * @hidden */ declare function clearHTML(str: string, options?: { removeNewLine?: boolean; }): string; /** * Alias of `removeHTML`. * * @hidden */ declare function clearHtml(str: string, options?: { removeNewLine?: boolean; }): string; /** * Sanitizes user input to prevent XSS attacks. * * Usage: * * ```javascript * import { sanitizeInput } from "mazey"; * * const ret = sanitizeInput("
hello world
"); * console.log(ret); * ``` * * Output: * * ```text * <div>hello world</div> * ``` * * @param input - The input string to sanitize * @returns The sanitized input string * @category Util */ declare function sanitizeInput(input: string): string; /** * Reverses the sanitization done by the `sanitizeInput` function. * * Usage: * * ```javascript * import { unsanitizeInput } from "mazey"; * * const ret = unsanitizeInput("<div>hello world</div>"); * console.log(ret); * ``` * * Output: * * ```text *
hello world
* ``` * * @param input - The input string to unsanitize * @returns The unsanitized input string * @category Util */ declare function unsanitizeInput(input: string): string; /** * Alias of `unsanitizeInput`. * * @hidden */ declare function unsanitize(str: string): string; /** * Truncate a string by weighted length, counting non-ASCII characters as two * units. * * Usage: * * ```javascript * import { cutZHString } from "mazey"; * * const ret = cutZHString("hello world", 5); * console.log(ret); * ``` * * Output: * * ```text * hello * ``` * * @param {string} str String to truncate. * @param {number} len Maximum weighted length. * @param {boolean} options.hasDot Whether to append truncation text. * @param {string} options.dotText Text appended when truncation occurs. * @returns {string} The truncated string. * @category Util */ declare function cutZHString(str: string | null | undefined, len: number, options?: { hasDot?: boolean; dotText?: string; }): string; /** * Alias of `cutZHString`. * * Usage: * * ```javascript * import { truncateZHString } from "mazey"; * * const ret = truncateZHString("hello world", 5); * console.log(ret); * ``` * * Output: * * ```text * hello * ``` * * @param {string} str String to truncate. * @param {number} len Maximum weighted length. * @param {boolean} hasDot Whether to append the default truncation text. * @returns {string} The truncated string. * @hidden */ declare function truncateZHString(str: string | null | undefined, len: number, hasDot?: boolean): string; /** * Alias of `truncateZHString`. * * @hidden */ declare function cutCHSString(str: string | null | undefined, len: number, hasDot?: boolean): string; /** * Verify the validity of axios response. * * Reference: [Handling Errors](https://axios-http.com/docs/handling_errors) * * @category Util * @hidden */ declare function zAxiosIsValidRes(res: ZResResponse | undefined, options?: ZResIsValidResOptions | null): boolean; /** * Determine the validity of the data. * * Usage: * * ```javascript * import { isValidData } from "mazey"; * * const validData = { * a: { * b: { * c: 413 * } * } * }; * const isValidDataResA = isValidData(validData, ["a", "b", "c"], 2333); * const isValidDataResB = isValidData(validData, ["a", "b", "c"], 413); * const isValidDataResC = isValidData(validData, ["d", "d"], 413); * console.log("isValidDataResA:", isValidDataResA); * console.log("isValidDataResB:", isValidDataResB); * console.log("isValidDataResC:", isValidDataResC); * ``` * * Output: * * ```text * isValidDataResA: false * isValidDataResB: true * isValidDataResC: false * ``` * * @param {any} data Original Data * @param {string[]} attributes Data Attributes * @param {any} validValue Given Value for verifying. * @returns {boolean} Return TRUE if the data is valid. * @category Util */ declare function isValidData(data: MazeyObject, attributes: string[], validValue: SimpleType): boolean; /** * Options for formatting a byte count. * * @category Util */ interface FormatByteSizeOptions { /** Unit scale. Defaults to `1024`. */ base?: 1000 | 1024; /** Decimal places for rounded values. Must be an integer from 0 to 20. Defaults to `1`. */ fractionDigits?: number; /** Returned for negative, non-finite, or otherwise invalid input. Defaults to an empty string. */ invalidValue?: string; } /** * Format a non-negative byte count using `B`, `KB`, `MB`, `GB`, or `TB`. * * Scaling defaults to 1024 with one fractional digit. Byte values omit * insignificant trailing zeroes, while scaled values retain the requested * number of fractional digits. Values beyond terabytes remain expressed in * `TB`. * * Usage: * * ```javascript * import { formatByteSize } from "mazey"; * * formatByteSize(0); // "0 B" * formatByteSize(1536); // "1.5 KB" * formatByteSize(1500000, { base: 1000, fractionDigits: 2 }); // "1.50 MB" * ``` * * @param bytes Byte count to format. * @param options Formatting options. * @returns A formatted byte-size string, or `invalidValue` for invalid input. * @category Util */ declare function formatByteSize(bytes: number, options?: FormatByteSizeOptions): string; /** * Deprecated alias of `formatByteSize`. * * @deprecated Use `formatByteSize` instead. * @param size Byte count to format. * @param options Formatting options. * @returns The result of `formatByteSize`. * @category Util */ declare function getFileSize(size: number, options?: FormatByteSizeOptions): string; /** * Generate a Hash Code from a string. * * Usage: * * ```javascript * import { genHashCode } from "mazey"; * * const ret = genHashCode("hello world"); * console.log(ret); * ``` * * Output: * * ```text * 1794106052 * ``` * * Reference: [Generate a Hash from string in Javascript](https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery) * * @category Util */ declare function genHashCode(str: string): number; /** * Generate a lowercase SHA-256 hexadecimal digest with the Web Crypto API. * * Usage: * * ```javascript * import { sha256Hex } from "mazey"; * * const digest = await sha256Hex("hello world"); * console.log(digest); * ``` * * Output: * * ```text * b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 * ``` * * @remarks Requires Web Crypto. String input also requires `TextEncoder`. * @param input Text or binary data to hash. * @returns A promise that resolves to the lowercase hexadecimal digest. * @throws When the required platform API is unavailable. Digest failures are propagated. * @category Util */ declare function sha256Hex(input: string | BufferSource): Promise; /** * Check if the given string is a mobile phone number. * * Usage: * * ```javascript * import { isMobile } from "mazey"; * * const ret1 = isMobile("13800138000"); * const ret2 = isMobile("1380013800"); * const ret3 = isMobile("138001380000"); * const ret4 = isMobile("1380013800a"); * console.log(ret1, ret2, ret3, ret4); * ``` * * Output: * * ```text * true false false false * ``` * * @param mobile * @returns {boolean} Return true if the given string is a mobile phone number. * @category Util */ declare function isValidPhoneNumber(mobile: string): boolean; /** * Check if the given string is a valid email. * * Usage: * * ```javascript * import { isValidEmail } from "mazey"; * * const ret = isValidEmail("mazeyqian@gmail.com"); * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * @param email * @returns {boolean} Return true if the given string is a valid email. * @category Util */ declare function isValidEmail(email: string): boolean; /** * Convert a given 10-hex number to a lowercase 26-hex string. * * Usage: * * ```javascript * import { convert10To26 } from "mazey"; * * const ret1 = convert10To26(1); * const ret2 = convert10To26(26); * const ret3 = convert10To26(27); * const ret4 = convert10To26(52); * const ret5 = convert10To26(53); * console.log(ret1, ret2, ret3, ret4, ret5); * ``` * * Output: * * ```text * a z aa az ba * ``` * * @param {number} num * @returns {string} Return a lowercase 26-hex string. * @category Util */ declare function convert10To26(num: number): string; /** * Get the current version. * * @hidden */ declare function getCurrentVersion(): string; /** * Repeatedly fires a callback function with a certain interval until a specified condition is met. * * Usage: * * ```javascript * import { repeatUntilConditionMet } from "mazey"; * * repeatUntilConditionMet( * () => { * console.log("repeatUntilConditionMet"); * return true; * }, { * interval: 1000, * times: 10, * context: null, * args: [], * }, (result) => { * return result === true; * } * ); * ``` * * @param callback The callback function to fire. * @param options Controls the interval, maximum invocation count, callback context, and callback arguments. * @param condition A function that takes the result of the callback function as its argument and returns a boolean value indicating whether the condition has been met. Defaults to a function that always returns true. * @category Util */ declare function repeatUntilConditionMet MazeyFnReturn>(callback: T, options?: RepeatUntilOptions, condition?: (result: ReturnType) => boolean): void; /** * Wait for a specified amount of time. * * Usage: * * ```javascript * import { waitTime } from "mazey"; * * waitTime(1000).then((time) => { * console.log("waitTime:", time); * }); * ``` * * Output: * * ```text * waitTime: 1000 * ``` * * @param time The amount of time to wait, in milliseconds. * @returns A Promise that resolves after the specified time has elapsed. * @category Util */ declare function waitTime(time: number): Promise; /** * Alias of `waitTime`. * * @hidden */ declare function sleep(time: number): Promise; /** * Determine if it is a browser environment. * * Usage: * * ```javascript * import { isBrowser } from "mazey"; * * const ret = isBrowser(); * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * @returns {boolean} true Yes * @category Browser Information */ declare function isBrowser(): boolean; /** * Canonical identity fields returned by {@link parseGitHubRepository}. * * @category URL */ interface GitHubRepositoryDetails { owner: string; name: string; slug: string; url: string; } /** * Parse a GitHub repository shorthand or transport URL. * * Accepted values include `owner/name`, `github:owner/name`, SCP-style SSH, * and `git`, `ssh`, `http`, or `https` GitHub URLs with an optional `git+` * prefix and terminal `.git` suffix. Owner and repository names intentionally * use a strict subset of GitHub's ASCII naming rules, including documented * length bounds, and percent-encoded input is rejected. * * Usage: * * ```javascript * import { parseGitHubRepository } from "mazey"; * * const repository = parseGitHubRepository("git@github.com:acme/widget.git"); * console.log(repository.slug, repository.url); * ``` * * Output: * * ```text * acme/widget https://github.com/acme/widget * ``` * * @param value A GitHub `owner/name` shorthand, SCP form, or supported Git URL. * @returns Canonical owner, repository name, slug, and HTTPS URL. * @throws TypeError when `value` is not a string. * @throws Error when the value is malformed or does not identify one GitHub repository. * @category URL */ declare function parseGitHubRepository(value: string): GitHubRepositoryDetails; /** * Get the query param's value of the current Web URL(`location.search`). * * Usage: * * ```javascript * import { getQueryParam } from "mazey"; * * // http://example.com/?t1=1&t2=2&t3=3&t4=4#2333 * // ?t1=1&t2=2&t3=3&t4=4 * const p1 = getQueryParam("t3"); * const p2 = getQueryParam("t4"); * console.log(p1, p2); * ``` * * Output: * * ```text * 3 4 * ``` * * @param {string} param Query param. * @returns {string} value * @category URL */ declare function getQueryParam(param: string): string; /** * Get the all query params of the current Web URL(`location.search`). * * Usage: * * ```javascript * import { getAllQueryParams } from "mazey"; * * // http://example.com/?t1=1&t2=2&t3=3&t4=4#2333 * // ?t1=1&t2=2&t3=3&t4=4 * const ret = getAllQueryParams(); * console.log(ret); * ``` * * Output: * * ```text * { t1: "1", t2: "2", t3: "3", t4: "4" } * ``` * * @param {string} url Optional, The URL string. * @returns {object} The query params object. * @category URL */ declare function getAllQueryParams(url?: string): SingleValueUrlParams; /** * Returns the value of the specified query parameter in the input URL. * * Usage: * * ```javascript * import { getUrlParam } from "mazey"; * * const p1 = getUrlParam("http://example.com/?t1=1&t2=2&t3=3&t4=4", "t3"); * const p2 = getUrlParam("http://example.com/?t1=1&t2=2&t3=3&t4=4", "t4"); * console.log(p1, p2); * ``` * * Output: * * ```text * 3 4 * ``` * * @param {string} url The URL string. * @param {string} param The query parameter to retrieve the value for. * @param {object} options The options object. * @param {boolean} options.returnArray Whether to return an array of values for the specified query parameter. Default is false. * @returns {string|string[]} The value of the specified query parameter, or an empty string if the parameter is not found. * @category URL */ declare function getUrlParam(url: string, param: string, options?: { returnArray?: boolean; }): string | string[] | null; /** * Update the query param's value of the input URL. * * Usage: * * ```javascript * import { updateQueryParam } from "mazey"; * * const ret1 = updateQueryParam("http://example.com/?t1=1&t2=2&t3=3&t4=4", "t3", "three"); * const ret2 = updateQueryParam("http://example.com/?t1=1&t2=2&t3=3&t4=4", "t4", "four"); * console.log(ret1); * console.log(ret2); * ``` * * Output: * * ```text * http://example.com/?t1=1&t2=2&t3=three&t4=4 * http://example.com/?t1=1&t2=2&t3=3&t4=four * ``` * * @param {string} url URL string. * @param {string} param Query param. * @param {string} value Param's value. * @returns {string} URL. * @category URL */ declare function updateQueryParam(url: string, param: string, value: string): string; /** * Get the hash query param's value of the current Web URL(`location.hash`). * * Usage: * * ```javascript * import { getHashQueryParam } from "mazey"; * * // http://example.com/?#2333?t1=1&t2=2&t3=3&t4=4 * // #2333?t1=1&t2=2&t3=3&t4=4 * const p1 = getHashQueryParam("t3"); * const p2 = getHashQueryParam("t4"); * console.log(p1, p2); * ``` * * Output: * * ```text * 3 4 * ``` * * @param {string} param Query param. * @returns {string} value * @category URL */ declare function getHashQueryParam(param: string): string; /** * Get the domain of URL, and other params. * * Usage: * * ```javascript * import { getDomain } from "mazey"; * * const ret1 = getDomain("http://example.com/?t1=1&t2=2&t3=3&t4=4"); * const ret2 = getDomain("http://example.com/test/thanks?t1=1&t2=2&t3=3&t4=4", ["hostname", "pathname"]); * const ret3 = getDomain("http://example.com:7890/test/thanks", ["hostname"]); * const ret4 = getDomain("http://example.com:7890/test/thanks", ["host"]); // With Port * const ret5 = getDomain("http://example.com:7890/test/thanks", ["origin"]); * const ret6 = getDomain("http://example.com:7890/test/thanks?id=1", ["origin", "pathname", "search"]); * console.log(ret1); * console.log(ret2); * console.log(ret3); * console.log(ret4); * console.log(ret5); * console.log(ret6); * ``` * * Output: * * ```text * example.com * example.com/test/thanks * example.com * example.com:7890 * http://example.com:7890 * http://example.com:7890/test/thanks?id=1 * ``` * * @param {string} url * @param {array} rules Object.keys(location), ["href", "origin", "protocol", "host", "hostname", "port", "pathname", "search", "hash"], ["hostname", "pathname"] = "km.mazey.net/plugins/servlet/mobile" * @category URL */ declare function getDomain(url: string, rules?: string[]): string; /** * Checks if the given string is a valid URL, including **scheme URLs**. * * Usage: * * ```javascript * import { isValidUrl } from "mazey"; * * const ret1 = isValidUrl("https://www.example.com"); * const ret2 = isValidUrl("http://example.com/path/exx/ss"); * const ret3 = isValidUrl("https://www.example.com/?q=hello&age=24#world"); * const ret4 = isValidUrl("http://www.example.com/#world?id=9"); * const ret5 = isValidUrl("ftp://example.com"); * console.log(ret1, ret2, ret3, ret4, ret5); * ``` * * Output: * * ```text * true true true true true * ``` * * @remarks * If you are specifically checking for HTTP/HTTPS URLs, it is recommended to use the `isValidHttpUrl` function instead. * The `isValidUrl` function matches all scheme URLs, including FTP and other non-HTTP schemes. * * @param url - The URL to check. * @returns Returns `true` if the given string is a valid URL, else `false`. * @category URL */ declare function isValidUrl(url: string): boolean; /** * Check if the given string is a valid HTTP/HTTPS URL. * * Usage: * * ```javascript * import { isValidHttpUrl } from "mazey"; * * const ret1 = isValidHttpUrl("https://www.example.com"); * const ret2 = isValidHttpUrl("http://example.com/path/exx/ss"); * const ret3 = isValidHttpUrl("https://www.example.com/?q=hello&age=24#world"); * const ret4 = isValidHttpUrl("http://www.example.com/#world?id=9"); * const ret5 = isValidHttpUrl("//example.com/a/b/c?q=1", { strict: false }); * const ret6 = isValidHttpUrl("ftp://example.com"); * console.log(ret1, ret2, ret3, ret4, ret5, ret6); * ``` * * Output: * * ```text * true true true true true false * ``` * * @param url * @param options.strict - If `true`, the function only matches standard HTTP/HTTPS URLs. Default is `true`. If `false`, the function also matches protocol-relative URLs, such as `//example.com`. * @returns {boolean} Return true if the given string is a valid HTTP/HTTPS URL. * @category URL */ declare function isValidHttpUrl(url: string, options?: { strict: boolean; }): boolean; /** * Get the file extension from a URL or path. * * Usage: * * ```javascript * import { getUrlFileType } from "mazey"; * * const ret1 = getUrlFileType("https://example.com/a/b/c.png"); * const ret2 = getUrlFileType("https://example.com/a/b/c.jpg"); * const ret3 = getUrlFileType("https://example.com/a/b/c.jpeg"); * const ret4 = getUrlFileType("/a/b/c.jpeg"); * const ret5 = getUrlFileType("https://example.com/a/b/c.v/a"); * console.log(ret1, ret2, ret3, ret4, ret5); * ``` * * Output: * * ```text * png jpg jpeg jpeg "" * ``` * * @param url * @returns * @category URL */ declare function getUrlFileType(url: string): boolean | string; /** * Retrieve a query parameter from a script URL in the browser. * * Usage: * * ```html * * ``` * * ```javascript * import { getScriptQueryParam } from "mazey"; * * const ret = getScriptQueryParam("test", "https://example.com/example.js"); * console.log(ret); * ``` * * Output: * * ```text * hello * ``` * * @param param - The name of the query parameter to retrieve. * @param matchString - An optional substring to match in the script URL. * If not provided, defaults to matching the ".js" substring. * @returns The decoded value of the specified query parameter, or an empty string if no matching parameter is found. * @category URL */ declare function getScriptQueryParam(param: string, matchString?: string): string; /** * Convert an object to a query string. * * Usage: * * ```javascript * import { convertObjectToQuery } from "mazey"; * * const ret = convertObjectToQuery({ t1: "1", t2: "2", t3: "3", t4: "4" }); * console.log(ret); * ``` * * Output: * * ```text * ?t1=1&t2=2&t3=3&t4=4 * ``` * * @param obj - The object to convert to a query string. * @returns The query string. * @category URL */ declare function convertObjectToQuery(obj: { [key: string]: string; }): string; /** * Convert an HTTP URL to an HTTPS URL. * * Usage: * * ```javascript * import { convertHttpToHttps } from "mazey"; * * const ret = convertHttpToHttps("http://example.com"); * console.log(ret); * ``` * * Output: * * ```text * https://example.com * ``` * * @param url - The HTTP URL to convert to HTTPS. * @returns The HTTPS URL. * @category URL */ declare function convertHttpToHttps(url: string): string; /** * Alias of `convertHttpToHttps`. * * @hidden */ declare function replaceHttp(url: string): string; /** * Get the host of the URL. * * Usage: * * ```javascript * import { getUrlHost } from "mazey"; * * const ret = getUrlHost("https://example.com/path/to/page"); * console.log(ret); * ``` * * Output: * * ```text * example.com * ``` * * @param url - The URL to get the host from. * @returns The host of the URL. * @category URL */ declare function getUrlHost(url: string): string; /** * Get the path of the URL. * * Usage: * * ```javascript * import { getUrlPath } from "mazey"; * * const ret = getUrlPath("https://example.com/path/to/page"); * console.log(ret); * ``` * * Output: * * ```text * /path/to/page * ``` * * @param url - The URL to get the path from. * @returns The path of the URL. * @category URL */ declare function getUrlPath(url: string): string; /** * Listen to URL changes from: * - back/forward navigation * - hash changes * - history.pushState / history.replaceState * * @param callback - Called with current URL, previous URL, and trigger source. * @param options - { fireOnInit?: boolean } default true. * @returns unsubscribe function * * @category URL */ declare function onURLChange(callback: (info: URLChangeInfo) => void, options?: OnURLChangeOptions): () => void; /** * Modify `class`: determine `class`. * * Usage: * * ```javascript * import { hasClass, addClass, removeClass } from "mazey"; * * const dom = document.querySelector("#box"); * // Determine `class` * hasClass(dom, "test"); * // Add `class` * addClass(dom, "test"); * // Remove `class` * removeClass(dom, "test"); * ``` * * @category DOM */ declare function hasClass(obj: MazeyElement, cls: string): boolean; /** * Add `class` to the element. The second parameter can be a single class name or an array of class names. * * Basic Usage: * * ```javascript * import { addClass } from "mazey"; * * const ele = document.querySelector("#box"); * addClass(ele, "test"); * ``` * * Output: * * ```html *
* ``` * * Advanced Usage: * * ```javascript * import { addClass, genBrowserAttrs } from "mazey"; * * const ele = document.querySelector("html"); * addClass(ele, genBrowserAttrs()); * ``` * * Output: * * ```html * * ``` * * @category DOM */ declare function addClass(ele: MazeyElement, cls: string | string[]): void; /** * Alias of `addClass`. * * @hidden */ declare function setClass(ele: HTMLElement, cls: string): void; /** * Modify `class`: remove `class`. * * Usage: * * ```javascript * import { hasClass, addClass, removeClass } from "mazey"; * * const dom = document.querySelector("#box"); * // Determine `class` * hasClass(dom, "test"); * // Add `class` * addClass(dom, "test"); * // Remove `class` * removeClass(dom, "test"); * ``` * * @category DOM */ declare function removeClass(obj: MazeyElement, cls: string): void; /** * Add a ` * ``` * * Example 2: Add the ` * ``` * * Example 3: Combine `genStyleString` and `addStyle` to add multiple styles at once. * * ```javascript * import { genStyleString, addStyle } from "mazey"; * * const xStyle = genStyleString( * ".footer>.x-wish>a:first-child" + * ",div.wish-flex>a[href^='https://github.com/chengchuu']" + * ",.m-hide", * [ "display: none" ] * ); * const yStyle = genStyleString( * ".footer>.y-wish:before", * [ * `content: 'Copyright (c) chengchuu'`, * "color: inherit", * "padding-inline-start: var(--y-wish-1_5)", * "padding-inline-end: var(--y-wish-1_5)", * "padding-top: var(--y-wish-1)", * "padding-bottom: var(--y-wish-1)", * ] * ); * addStyle(xStyle + yStyle, { id: "z-style" }); * ``` * * Output: * * ```html * * ``` * * @param style CSS text to add to the document. * @param options.id Optional ` * ``` * * @param {string} selector * @param {array} styleArray * @returns {string} The inline style string. * @category DOM */ declare function genStyleString(selector: string, styleArray: Array): string; /** * Get the value of the meta tag by the given name. * * Usage: * * ```html * * ``` * * ```javascript * import { getPageMeta } from "mazey"; * * const keywords = getPageMeta("keywords"); * console.log(keywords); * ``` * * Output: * * ```text * mazey,web,frontend * ``` * * @param {string} name - The name of the meta tag. * @returns {string} The content of the meta tag. * @category DOM */ declare function getPageMeta(name: string): string; /** * Check whether a value is a CSS selector supported by the supplied query * root without allowing selector syntax errors to escape. * * Usage: * * ```javascript * import { isValidCssSelector } from "mazey"; * * isValidCssSelector(".message > img"); // true * isValidCssSelector("["); // false * isValidCssSelector("", { allowEmpty: true }); // true * ``` * * @remarks Browser only unless a compatible `ParentNode` is supplied. * @param selector Value to validate as a CSS selector. * @param options.allowEmpty Whether an empty or whitespace-only string is accepted. Defaults to `false`. * @param options.root Query root used to validate browser support. Defaults to `document` when available. * @returns Whether the selector is accepted by the query root. * @category DOM */ declare function isValidCssSelector(selector: unknown, options?: { allowEmpty?: boolean; root?: ParentNode; }): boolean; /** * Extract text from a cloned element without modifying the original DOM. * Images can be replaced by their `alt` text, selected descendants can be * removed, and whitespace can be normalized before returning the text. * * Invalid exclusion selectors are ignored. * * Usage: * * ```javascript * import { extractElementText } from "mazey"; * * const element = document.querySelector(".message"); * const text = extractElementText(element, { * excludeSelector: ".message-actions", * }); * ``` * * @remarks Browser only. * @param element Element whose cloned contents are read. * @param options.excludeSelector Selector for descendants to remove from the clone. * @param options.replaceImagesWithAlt Whether images with an `alt` attribute are replaced by that text. Defaults to `true`. * @param options.normalizeWhitespace Whether whitespace is collapsed and trimmed. Defaults to `true`. * @returns Extracted text from the cloned element. * @category DOM */ declare function extractElementText(element: Element, options?: { excludeSelector?: string; replaceImagesWithAlt?: boolean; normalizeWhitespace?: boolean; }): string; /** * Prevent bubbling. * * Usage: * * ```javascript * import { cancelBubble } from "mazey"; * * const ret1 = cancelBubble(e); * ``` * * @category Event */ declare function cancelBubble(e: Event): void; /** * Get the defined listeners. * * Usage: * * ```javascript * import { getDefineListeners } from "mazey"; * * const ret = getDefineListeners(); * console.log(ret); * ``` * * Output: * * ```text * {} * ``` * * @category Event * @hidden */ declare function getDefineListeners(): DefineListeners; /** * Add event. * * Usage: * * ```javascript * import { addEvent } from "mazey"; * * addEvent("test", (e) => { * console.log("test event:", e); * }); * fireEvent("test"); * ``` * * Output: * * ```javascript * test event: { type: "test" } * ``` * * @param type * @param fn * @category Event */ declare function addEvent(type: string, fn: MazeyFn): void; /** * Fire/Invoke event. * * Usage: * * ```javascript * import { fireEvent } from "mazey"; * * fireEvent("test"); * ``` * * @param type The event type. * @param params The event parameters. * @category Event */ declare function fireEvent(type: string, params?: MazeyObject): void; /** * Alias of `fireEvent`. * * @hidden */ declare function invokeEvent(type: string, params?: MazeyObject): void; /** * Remove event. * * Usage: * * ```javascript * import { removeEvent } from "mazey"; * * removeEvent("test"); * ``` * * @param type * @param fn * @category Event */ declare function removeEvent(type: string, fn?: MazeyFn): void; /** * Serialize a value as JSON and store it in `sessionStorage`. * * Usage: * * ```javascript * import { setSessionStorage, getSessionStorage, setLocalStorage, getLocalStorage } from "mazey"; * * setSessionStorage("test", "123"); * const ret1 = getSessionStorage("test"); * setLocalStorage("test", "123"); * const ret2 = getLocalStorage("test"); * console.log(ret1, ret2); * * // Wrap the helpers with a project-specific key prefix. * const projectName = "mazey"; * function mSetLocalStorage (key, value) { * return setLocalStorage(`${projectName}_${key}`, value); * } * * function mGetLocalStorage (key) { * return getLocalStorage(`${projectName}_${key}`); * } * ``` * * Output: * * ```text * 123 123 * ``` * * @param {string} key Storage key. * @param value Value to serialize and store. * @returns {void} This function does not return a value. * @category Store */ declare function setSessionStorage(key: string, value?: T | null): void; /** * Read a value from `sessionStorage`, parsing JSON when possible. * * Usage: * * ```javascript * import { setSessionStorage, getSessionStorage, setLocalStorage, getLocalStorage } from "mazey"; * * setSessionStorage("test", "123"); * const ret1 = getSessionStorage("test"); * setLocalStorage("test", "123"); * const ret2 = getLocalStorage("test"); * console.log(ret1, ret2); * * // Wrap the helpers with a project-specific key prefix. * const projectName = "mazey"; * function mSetLocalStorage (key, value) { * return setLocalStorage(`${projectName}_${key}`, value); * } * * function mGetLocalStorage (key) { * return getLocalStorage(`${projectName}_${key}`); * } * ``` * * Output: * * ```text * 123 123 * ``` * * @param {string} key Storage key. * @returns The parsed value, raw stored value, or `null` when no value exists. * @category Store */ declare function getSessionStorage(key: string): T | null; /** * Serialize a value as JSON and store it in `localStorage`. * * Usage: * * ```javascript * import { setSessionStorage, getSessionStorage, setLocalStorage, getLocalStorage } from "mazey"; * * setSessionStorage("test", "123"); * const ret1 = getSessionStorage("test"); * setLocalStorage("test", "123"); * const ret2 = getLocalStorage("test"); * console.log(ret1, ret2); * * // Wrap the helpers with a project-specific key prefix. * const projectName = "mazey"; * function mSetLocalStorage (key, value) { * return setLocalStorage(`${projectName}_${key}`, value); * } * * function mGetLocalStorage (key) { * return getLocalStorage(`${projectName}_${key}`); * } * ``` * * Output: * * ```text * 123 123 * ``` * * @param {string} key Storage key. * @param value Value to serialize and store. * @returns {void} This function does not return a value. * @category Store */ declare function setLocalStorage(key: string, value?: T | null): void; /** * Read a value from `localStorage`, parsing JSON when possible. * * Usage: * * ```javascript * import { setSessionStorage, getSessionStorage, setLocalStorage, getLocalStorage } from "mazey"; * * setSessionStorage("test", "123"); * const ret1 = getSessionStorage("test"); * setLocalStorage("test", "123"); * const ret2 = getLocalStorage("test"); * console.log(ret1, ret2); * * // Wrap the helpers with a project-specific key prefix. * const projectName = "mazey"; * function mSetLocalStorage (key, value) { * return setLocalStorage(`${projectName}_${key}`, value); * } * * function mGetLocalStorage (key) { * return getLocalStorage(`${projectName}_${key}`); * } * ``` * * Output: * * ```text * 123 123 * ``` * * @param {string} key Storage key. * @returns The parsed value, raw stored value, or `null` when no value exists. * @category Store */ declare function getLocalStorage(key: string): T | null; /** * Get a cookie value by name. * * Usage: * * ```javascript * import { setCookie, getCookie } from "mazey"; * * setCookie("test", "123", 30, "example.com"); // name, value, days, domain * const ret = getCookie("test"); * console.log(ret); * ``` * * Output: * * ```text * 123 * ``` * * @param name Cookie name. * @returns The cookie value, or an empty string when the cookie does not exist. * @category Store */ declare function getCookie(name: string): string; /** * Set a cookie value. * * Usage: * * ```javascript * import { setCookie, getCookie } from "mazey"; * * setCookie("test", "123", 30, "example.com"); // name, value, days, domain * const ret = getCookie("test"); * console.log(ret); * ``` * * Output: * * ```text * 123 * ``` * * @param name Cookie name. * @param value Cookie value. * @param days Number of days until expiration. Omit for a session cookie. * @param domain Optional cookie domain. * @returns {void} This function does not return a value. * @category Store */ declare function setCookie(name: string, value: string, days?: number, domain?: string): void; /** * Delete a cookie by name. * * Usage: * * ```javascript * import { removeCookie } from "mazey"; * * const ret = removeCookie("test"); * console.log(ret); * ``` * * Output: * * ```text * true * ``` * * @param name - The name of the cookie to delete. * @returns `true` if the cookie was deleted successfully, `false` otherwise. * @category Store */ declare function removeCookie(name: string): boolean; /** * Alias of `removeCookie`. * * @hidden */ declare function delCookie(name: string): void; /** * Load a CSS file dynamically. * * Usage: * * ```javascript * import { loadCSS } from "mazey"; * * loadCSS( * "http://example.com/path/example.css", * { * id: "iamid", // Optional, link ID, default none * } * ) * .then( * res => { * console.log(`Load CSS Success: ${res}`); * } * ) * .catch( * err => { * console.error(`Load CSS Fail: ${err.message}`) * } * ); * ``` * * Output: * * ```text * Load CSS Success: loaded * ``` * * @param {string} url URL of the CSS resource. * @param {string} options.id Optional ID for the `` element. * @returns {Promise} A promise that resolves to `"loaded"` after the stylesheet loads. * @category Load */ declare function loadCSS(url: string, options?: { id?: string; }): Promise; /** * Load and execute a JavaScript file dynamically. * * Usage: * * ```javascript * import { loadScript } from "mazey"; * * loadScript( * "http://example.com/static/js/plugin-2.1.1.min.js", * { * id: "iamid", // (Optional) script ID, default none * timeout: 5000, // (Optional) timeout, default `5000` * } * ) * .then( * res => { * console.log(`Load JavaScript script: ${res}`); * } * ) * .catch( * err => { * console.error(`Load JavaScript script: ${err.message}`); * } * ); * ``` * * Output: * * ```text * Load JavaScript script: loaded * ``` * * @param {string} url URL of the JavaScript resource. * @param {string} options.id Optional ID for the `