mazey 4.13.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -143,7 +143,7 @@ type SingleValueUrlParams = {
143
143
 
144
144
  type ThrottleFunc<T extends (...args: any[]) => any> = (...args: Parameters<T>) => ReturnType<T> | null;
145
145
 
146
- type DebounceFunc<T extends (...args: any[]) => any> = (...args: Parameters<T>) => ReturnType<T>;
146
+ type DebounceFunc<T extends (...args: any[]) => any> = (...args: Parameters<T>) => ReturnType<T> | null;
147
147
 
148
148
  interface IsNumberOptions {
149
149
  isNaNAsNumber?: boolean;
@@ -170,7 +170,7 @@ interface RepeatUntilOptions {
170
170
  args?: Array<any>;
171
171
  }
172
172
 
173
- type LoadScriptReturns = Promise<boolean | string | Error | void>;
173
+ type LoadScriptReturns = Promise<string>;
174
174
 
175
175
  type SimpleType = string | number | boolean | null | undefined;
176
176
 
@@ -203,6 +203,9 @@ interface OnURLChangeOptions {
203
203
  /**
204
204
  * Copy/Clone Object deeply.
205
205
  *
206
+ * Custom class instances are copied as plain objects containing their own
207
+ * properties. Unsupported native instances are preserved by reference.
208
+ *
206
209
  * Usage:
207
210
  *
208
211
  * ```javascript
@@ -226,6 +229,38 @@ interface OnURLChangeOptions {
226
229
  * @category Util
227
230
  */
228
231
  declare function deepCopy<T>(obj: T): T;
232
+ /**
233
+ * Recursively freeze an object and its nested enumerable values.
234
+ *
235
+ * Primitive values and objects that are already frozen are returned unchanged.
236
+ *
237
+ * Usage:
238
+ *
239
+ * ```javascript
240
+ * import { deepFreeze } from "mazey";
241
+ *
242
+ * const config = deepFreeze({
243
+ * api: {
244
+ * timeout: 5000,
245
+ * },
246
+ * });
247
+ *
248
+ * console.log(Object.isFrozen(config));
249
+ * console.log(Object.isFrozen(config.api));
250
+ * ```
251
+ *
252
+ * Output:
253
+ *
254
+ * ```text
255
+ * true
256
+ * true
257
+ * ```
258
+ *
259
+ * @param value The value to freeze.
260
+ * @returns The original value with its nested enumerable values frozen.
261
+ * @category Util
262
+ */
263
+ declare function deepFreeze<T>(value: T): T;
229
264
  /**
230
265
  * Alias of `deepCopy`.
231
266
  *
@@ -546,7 +581,7 @@ declare function floatToPercent(num: number, fixSize?: number): string;
546
581
  *
547
582
  * @category Util
548
583
  */
549
- declare function floatFixed(num: string, size?: number): string;
584
+ declare function floatFixed(num: number | string, size?: number): string;
550
585
  /**
551
586
  * EN: Throttle, used to limit the frequency of function execution over time.
552
587
  *
@@ -589,37 +624,56 @@ declare function throttle<T extends (...args: MazeyFnParams) => MazeyFnReturn>(f
589
624
  */
590
625
  declare function debounce<T extends (...args: MazeyFnParams) => MazeyFnReturn>(func: T, wait: number, immediate?: boolean): DebounceFunc<T>;
591
626
  /**
592
- * EN: Get interval time.
627
+ * Calculate the interval between two dates or timestamps.
593
628
  *
594
- * ZH: 获取间隔时间。
629
+ * The default `d` type returns the number of whole days. The `text` type
630
+ * returns an English duration using days, hours, minutes, and seconds while
631
+ * omitting zero-valued units. A zero interval returns `"0 seconds"`. Any other
632
+ * type returns the number of whole seconds. Negative intervals and invalid
633
+ * dates return an empty string.
595
634
  *
596
635
  * Usage:
597
636
  *
598
637
  * ```javascript
599
- * import { getFriendlyInterval } from "mazey";
638
+ * import { getDateDifference } from "mazey";
600
639
  *
601
- * const ret1 = getFriendlyInterval(new Date("2020-03-28 00:09:27"), new Date("2023-04-18 10:54:00"), { type: "d" });
602
- * const ret2 = getFriendlyInterval(1585325367000, 1681786440000, { type: "text" });
603
- * const ret3 = getFriendlyInterval("2020-03-28 00:09:27", "2023-04-18 10:54:00", { type: "text" });
604
- * console.log(ret1);
605
- * console.log(ret2);
606
- * console.log(ret3);
640
+ * const days = getDateDifference(0, 90061000);
641
+ * const text = getDateDifference(0, 90061000, { type: "text" });
642
+ * const compactText = getDateDifference(0, 90060000, { type: "text" });
643
+ * const dateStringDays = getDateDifference(
644
+ * "2020-03-28 00:09:27",
645
+ * "2023-04-18 10:54:00"
646
+ * );
647
+ * console.log(days);
648
+ * console.log(text);
649
+ * console.log(compactText);
650
+ * console.log(dateStringDays);
607
651
  * ```
608
652
  *
609
653
  * Output:
610
654
  *
611
655
  * ```text
656
+ * 1
657
+ * 1 day 1 hour 1 minute 1 second
658
+ * 1 day 1 hour 1 minute
612
659
  * 1116
613
- * 1116 天 10 时 44 分 33 秒
614
- * 1116 天 10 时 44 分 33 秒
615
660
  * ```
616
661
  *
617
- * @param {number/Date} start 开始时间戳 1585325367122
618
- * @param {number/Date} end 结束时间戳 1585325367122
619
- * @param {string} options.type 返回类型 d: 2(天) text: 2 天 4 时...
620
- * @returns {string/number} 取决于 type
662
+ * @param start Start date or timestamp.
663
+ * @param end End date or timestamp.
664
+ * @param options Formatting options. Use `d` for whole days or `text` for an English duration.
665
+ * @returns Whole days, whole seconds, an English duration, or an empty string for a negative or invalid interval.
666
+ * @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.
621
667
  * @category Util
622
668
  */
669
+ declare function getDateDifference(start?: number | string | Date, end?: number | string | Date, options?: {
670
+ type?: string;
671
+ }): number | string;
672
+ /**
673
+ * Alias of `getDateDifference`.
674
+ *
675
+ * @hidden
676
+ */
623
677
  declare function getFriendlyInterval(start?: number | string | Date, end?: number | string | Date, options?: {
624
678
  type?: string;
625
679
  }): number | string;
@@ -672,8 +726,7 @@ declare function formatDurationFromMs(durationMs: number): string;
672
726
  * ```
673
727
  *
674
728
  * @param {*} num 被判断的值
675
- * @param {boolean} options.isNaNAsNumber 是否 NaN 算数字(默认不算)
676
- * @param {boolean} options.isInfinityAsNumber 是否 无限 算数字(默认不算)
729
+ * @param options Controls whether `NaN`, `Infinity`, or other non-finite values count as numbers.
677
730
  * @returns {boolean} true 是数字
678
731
  * @category Util
679
732
  */
@@ -696,13 +749,13 @@ declare function isNumber(num: unknown, options?: IsNumberOptions): boolean;
696
749
  * @param {function} fn 等待被执行的未知是否有效的函数
697
750
  * @category Util
698
751
  */
699
- declare function invokeFn(fn: MazeyFunction, ...params: Parameters<MazeyFunction>): ReturnType<MazeyFunction> | null;
752
+ declare function invokeFn(fn: MazeyFunction | null | undefined, ...params: Parameters<MazeyFunction>): ReturnType<MazeyFunction> | null;
700
753
  /**
701
754
  * Alias of `invokeFn`.
702
755
  *
703
756
  * @hidden
704
757
  */
705
- declare function doFn(fn: MazeyFunction, ...params: Parameters<MazeyFunction>): ReturnType<MazeyFunction> | null;
758
+ declare function doFn(fn: MazeyFunction | null | undefined, ...params: Parameters<MazeyFunction>): ReturnType<MazeyFunction> | null;
706
759
  /**
707
760
  * Verify the validity of a non-empty array.
708
761
  *
@@ -1067,7 +1120,7 @@ declare function unsanitize(str: string): string;
1067
1120
  * @returns {string} 返回截取后的字符串
1068
1121
  * @category Util
1069
1122
  */
1070
- declare function cutZHString(str: string, len: number, options?: {
1123
+ declare function cutZHString(str: string | null | undefined, len: number, options?: {
1071
1124
  hasDot?: boolean;
1072
1125
  dotText?: string;
1073
1126
  }): string;
@@ -1094,13 +1147,13 @@ declare function cutZHString(str: string, len: number, options?: {
1094
1147
  * @returns {string} 返回截取后的字符串
1095
1148
  * @hidden
1096
1149
  */
1097
- declare function truncateZHString(str: string, len: number, hasDot?: boolean): string;
1150
+ declare function truncateZHString(str: string | null | undefined, len: number, hasDot?: boolean): string;
1098
1151
  /**
1099
1152
  * Alias of `truncateZHString`.
1100
1153
  *
1101
1154
  * @hidden
1102
1155
  */
1103
- declare function cutCHSString(str: string, len: number, hasDot?: boolean): string;
1156
+ declare function cutCHSString(str: string | null | undefined, len: number, hasDot?: boolean): string;
1104
1157
  /**
1105
1158
  * Verify the validity of axios response.
1106
1159
  *
@@ -1109,7 +1162,7 @@ declare function cutCHSString(str: string, len: number, hasDot?: boolean): strin
1109
1162
  * @category Util
1110
1163
  * @hidden
1111
1164
  */
1112
- declare function zAxiosIsValidRes(res: ZResResponse | undefined, options?: ZResIsValidResOptions): boolean;
1165
+ declare function zAxiosIsValidRes(res: ZResResponse | undefined, options?: ZResIsValidResOptions | null): boolean;
1113
1166
  /**
1114
1167
  * Determine the validity of the data.
1115
1168
  *
@@ -1194,6 +1247,42 @@ declare function getFileSize(size: number): string;
1194
1247
  * @category Util
1195
1248
  */
1196
1249
  declare function genHashCode(str: string): number;
1250
+ /**
1251
+ * Check whether an unknown value represents a valid date.
1252
+ *
1253
+ * Valid inputs include `Date` instances, finite millisecond timestamps,
1254
+ * structured local date strings, and ISO 8601 strings with `Z` or a numeric
1255
+ * timezone offset. Structured strings are parsed into numeric components and
1256
+ * validated strictly, so invalid calendar dates are not normalized.
1257
+ *
1258
+ * Supported string forms are `YYYY-MM-DD`, `YYYY-MM-DD HH:mm[:ss]`,
1259
+ * `YYYY-MM-DDTHH:mm[:ss]`, and the same `T`-separated date-time with `Z` or
1260
+ * a `+HH:mm`/`-HH:mm` offset. Zoned strings may include 1-3 millisecond digits.
1261
+ *
1262
+ * Usage:
1263
+ *
1264
+ * ```javascript
1265
+ * import { isValidDate } from "mazey";
1266
+ *
1267
+ * const ret1 = isValidDate(1577877720000);
1268
+ * const ret2 = isValidDate("2020-01-01 11:22");
1269
+ * const ret3 = isValidDate("2020-02-30");
1270
+ * const ret4 = isValidDate(new Date("invalid"));
1271
+ *
1272
+ * console.log(ret1, ret2, ret3, ret4);
1273
+ * ```
1274
+ *
1275
+ * Output:
1276
+ *
1277
+ * ```text
1278
+ * true true false false
1279
+ * ```
1280
+ *
1281
+ * @param value A `Date`, millisecond timestamp, or supported structured date string.
1282
+ * @returns Whether the value represents a valid date.
1283
+ * @category Util
1284
+ */
1285
+ declare function isValidDate(value: unknown): boolean;
1197
1286
  /**
1198
1287
  * Return the formatted date string in the given format.
1199
1288
  *
@@ -1224,11 +1313,12 @@ declare function genHashCode(str: string): number;
1224
1313
  * @param {MazeyDate} dateIns Original Date
1225
1314
  * @param {string} format Format String
1226
1315
  * @returns {string} Return the formatted date string.
1316
+ * @throws {RangeError} If `dateIns` is not a valid date.
1227
1317
  * @category Util
1228
1318
  */
1229
1319
  declare function formatDate(dateIns?: MazeyDate, format?: string): string;
1230
1320
  /**
1231
- * Generate a Calendar Versioning string from a date.
1321
+ * Generate a local-time Calendar Versioning string from a date.
1232
1322
  *
1233
1323
  * The conceptual format is `yyyy.MMdd.HHmmss`. Leading zeroes are removed
1234
1324
  * from each segment to keep numeric Semantic Versioning identifiers valid.
@@ -1250,6 +1340,7 @@ declare function formatDate(dateIns?: MazeyDate, format?: string): string;
1250
1340
  *
1251
1341
  * @param {MazeyDate} dateIns Original date. Defaults to the current date.
1252
1342
  * @returns {string} Return the generated calendar version.
1343
+ * @throws {RangeError} If `dateIns` is not a valid date.
1253
1344
  * @category Util
1254
1345
  */
1255
1346
  declare function generateCalendarVersion(dateIns?: MazeyDate): string;
@@ -1359,11 +1450,7 @@ declare function getCurrentVersion(): string;
1359
1450
  * ```
1360
1451
  *
1361
1452
  * @param callback The callback function to fire.
1362
- * @param options An object containing the options for the function.
1363
- * @param options.interval The interval between each firing of the callback function, in milliseconds. Defaults to 1000.
1364
- * @param options.times The maximum number of times to fire the callback function. Defaults to 10.
1365
- * @param options.context The context to use when calling the callback function. Defaults to null.
1366
- * @param options.args An array of arguments to pass to the callback function.
1453
+ * @param options Controls the interval, maximum invocation count, callback context, and callback arguments.
1367
1454
  * @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.
1368
1455
  * @category Util
1369
1456
  */
@@ -2182,7 +2269,7 @@ declare function fireEvent(type: string, params?: MazeyObject): void;
2182
2269
  *
2183
2270
  * @hidden
2184
2271
  */
2185
- declare function invokeEvent(type: string): void;
2272
+ declare function invokeEvent(type: string, params?: MazeyObject): void;
2186
2273
  /**
2187
2274
  * Remove event.
2188
2275
  *
@@ -2198,7 +2285,7 @@ declare function invokeEvent(type: string): void;
2198
2285
  * @param fn
2199
2286
  * @category Event
2200
2287
  */
2201
- declare function removeEvent(type: string, fn: MazeyFn): void;
2288
+ declare function removeEvent(type: string, fn?: MazeyFn): void;
2202
2289
 
2203
2290
  /**
2204
2291
  * EN: Handle Storage (Keep fit for JSON, it can transfer format automatically).
@@ -2471,7 +2558,7 @@ declare function delCookie(name: string): void;
2471
2558
  */
2472
2559
  declare function loadCSS(url: string, options?: {
2473
2560
  id?: string;
2474
- }): Promise<unknown>;
2561
+ }): Promise<string>;
2475
2562
  /**
2476
2563
  * EN: Load a JavaScript file from the server and execute it.
2477
2564
  *
@@ -2558,7 +2645,7 @@ declare function loadScript(url: string, options?: {
2558
2645
  * @returns {Promise<string>} document is loaded? "complete" "load" / "timeout"
2559
2646
  * @category Load
2560
2647
  */
2561
- declare function windowLoaded(timeout?: number): Promise<string | Error>;
2648
+ declare function windowLoaded(timeout?: number): Promise<string>;
2562
2649
  /**
2563
2650
  * Load an image from the given URL.
2564
2651
  *
@@ -2783,7 +2870,6 @@ declare function getTTFB(): Promise<number>;
2783
2870
  * @remarks
2784
2871
  * This function uses the [`PerformanceNavigationTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming) API to get page load time data.
2785
2872
  * The `PerformanceNavigationTiming` API provides more accurate and detailed information about page load time than the deprecated [`PerformanceTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming) API.
2786
- * If you are using an older browser that does not support `PerformanceNavigationTiming`, you can still use the `PerformanceTiming` API by using the previous version of this library ([`v3.9.7`](https://github.com/chengchuu/mazey/releases/tag/v3.9.7)).
2787
2873
  *
2788
2874
  * Usage:
2789
2875
  *
@@ -2825,7 +2911,7 @@ declare function getTTFB(): Promise<number>;
2825
2911
  * @returns {Promise<object>} 加载数据
2826
2912
  * @category Perf
2827
2913
  */
2828
- declare function getPerformance(camelCase?: boolean): Promise<WebPerformance | Error>;
2914
+ declare function getPerformance(camelCase?: boolean): Promise<WebPerformance>;
2829
2915
 
2830
2916
  /**
2831
2917
  * Detect whether the current browser document provides the minimum
@@ -2854,7 +2940,7 @@ declare function getPerformance(camelCase?: boolean): Promise<WebPerformance | E
2854
2940
  * true
2855
2941
  * ```
2856
2942
  *
2857
- * @environment Browser
2943
+ * @remarks Browser only.
2858
2944
  * @returns Whether the detectable minimum PWA prerequisites are satisfied.
2859
2945
  * @category Browser Information
2860
2946
  */
@@ -2901,7 +2987,7 @@ declare function isSafePWAEnv(): boolean;
2901
2987
  * const isMobileQQ = ["android", "ios"].includes(system) && ["qq_browser", "qq_app"].includes(shell);
2902
2988
  * ```
2903
2989
  *
2904
- * @environment Browser
2990
+ * @remarks Browser only.
2905
2991
  * @returns Browser information
2906
2992
  * @category Browser Information
2907
2993
  */
@@ -2926,7 +3012,7 @@ declare function getBrowserInfo(): BrowserInfo;
2926
3012
  * ["windows", "desktop", "webkit", "chrome"]
2927
3013
  * ```
2928
3014
  *
2929
- * @environment Browser
3015
+ * @remarks Browser only.
2930
3016
  * @param {string} prefix
2931
3017
  * @returns {array} Browser attributes
2932
3018
  * @category Browser Information
@@ -3031,4 +3117,4 @@ declare const mazeyCon: Console;
3031
3117
  */
3032
3118
  declare const timeCon: Console;
3033
3119
 
3034
- export { addClass, addEvent, addStyle, calLongestCommonSubsequence, calLongestCommonSubstring, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHTML, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, convertHttpToHttps, convertKebabToCamel, convertObjectToQuery, convertToHtmlBreaks, convertUnderToCamel, cutCHSString, cutZHString, debounce, deepCopy, deepCopyObject, delCookie, doFn, fireEvent, floatFixed, floatToPercent, formatDate, formatDurationFromMs, genBrowserAttrs, genCustomConsole, genHashCode, genRndNumString, genStyleString, genUniqueNumString, generateCalendarVersion, generateRndNum, generateUniqueNum, getAllQueryParams, getBrowserInfo, getCLS, getCookie, getCurrentVersion, getDefineListeners, getDomain, getFCP, getFID, getFP, getFileSize, getFriendlyInterval, getHashQueryParam, getLCP, getLocalStorage, getPageMeta, getPerformance, getQueryParam, getScriptQueryParam, getSessionStorage, getTTFB, getUrlFileType, getUrlHost, getUrlParam, getUrlPath, hasClass, inRate, invokeEvent, invokeFn, isArray, isBool, isBoolean, isBrowser, isFunction, isHit, isJSONString, isJsonString, isNonEmptyArray, isNonEmptyObject, isNumber, isPureObject, isSafePWAEnv, isString, isSupportWebp, isSupportedEntryType, isUdfOrNul, isValidData, isValidEmail, isValidHttpUrl, isValidPhoneNumber, isValidUrl, loadCSS, loadImage, loadScript, loadScriptIfUndefined, longestComSubsequence, longestComSubstring, mNow, mTrim, mazeyCon, newLine, onURLChange, removeClass, removeCookie, removeEvent, removeHTML, removeHtml, repeatUntilConditionMet, replaceHttp, sanitizeInput, setClass, setCookie, setImgSizeBySrc, setImgWidHeiBySrc, setLocalStorage, setSessionStorage, sleep, throttle, timeCon, truncateZHString, unsanitize, unsanitizeInput, updateQueryParam, waitTime, windowLoaded, zAxiosIsValidRes };
3120
+ export { addClass, addEvent, addStyle, calLongestCommonSubsequence, calLongestCommonSubstring, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHTML, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, convertHttpToHttps, convertKebabToCamel, convertObjectToQuery, convertToHtmlBreaks, convertUnderToCamel, cutCHSString, cutZHString, debounce, deepCopy, deepCopyObject, deepFreeze, delCookie, doFn, fireEvent, floatFixed, floatToPercent, formatDate, formatDurationFromMs, genBrowserAttrs, genCustomConsole, genHashCode, genRndNumString, genStyleString, genUniqueNumString, generateCalendarVersion, generateRndNum, generateUniqueNum, getAllQueryParams, getBrowserInfo, getCLS, getCookie, getCurrentVersion, getDateDifference, getDefineListeners, getDomain, getFCP, getFID, getFP, getFileSize, getFriendlyInterval, getHashQueryParam, getLCP, getLocalStorage, getPageMeta, getPerformance, getQueryParam, getScriptQueryParam, getSessionStorage, getTTFB, getUrlFileType, getUrlHost, getUrlParam, getUrlPath, hasClass, inRate, invokeEvent, invokeFn, isArray, isBool, isBoolean, isBrowser, isFunction, isHit, isJSONString, isJsonString, isNonEmptyArray, isNonEmptyObject, isNumber, isPureObject, isSafePWAEnv, isString, isSupportWebp, isSupportedEntryType, isUdfOrNul, isValidData, isValidDate, isValidEmail, isValidHttpUrl, isValidPhoneNumber, isValidUrl, loadCSS, loadImage, loadScript, loadScriptIfUndefined, longestComSubsequence, longestComSubstring, mNow, mTrim, mazeyCon, newLine, onURLChange, removeClass, removeCookie, removeEvent, removeHTML, removeHtml, repeatUntilConditionMet, replaceHttp, sanitizeInput, setClass, setCookie, setImgSizeBySrc, setImgWidHeiBySrc, setLocalStorage, setSessionStorage, sleep, throttle, timeCon, truncateZHString, unsanitize, unsanitizeInput, updateQueryParam, waitTime, windowLoaded, zAxiosIsValidRes };