@lntvow/utils 4.0.16 → 4.0.18

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.
@@ -1,732 +1,2 @@
1
1
  /* @ts-self-types="./esm-bundler.d.ts" */
2
-
3
- // src/lang/isObject.ts
4
- function isObject(value) {
5
- const type = typeof value;
6
- return value !== null && (type === "object" || type === "function");
7
- }
8
-
9
- // src/lang/isObjectLike.ts
10
- function isObjectLike(value) {
11
- return value !== null && typeof value === "object";
12
- }
13
-
14
- // src/lang/type.ts
15
- var objectToString = Object.prototype.toString;
16
- var toTypeString = (value) => objectToString.call(value);
17
- var toTypeValue = (value) => toTypeString(value).slice(8, -1);
18
- var isString = (val) => typeof val === "string";
19
- var isNumber = (val) => typeof val === "number" && Number.isFinite(val);
20
- var isBoolean = (val) => typeof val === "boolean";
21
- var isNull = (val) => val === null;
22
- var isUndefined = (val) => val === void 0;
23
- var isSymbol = (val) => typeof val === "symbol";
24
- var isArray = Array.isArray;
25
- var isFunction = (val) => typeof val === "function";
26
- var isMap = (val) => toTypeString(val) === "[object Map]";
27
- var isSet = (val) => toTypeString(val) === "[object Set]";
28
- var isDate = (val) => toTypeString(val) === "[object Date]";
29
- var isRegExp = (val) => toTypeString(val) === "[object RegExp]";
30
- var isPromise = (val) => isObjectLike(val) && isFunction(val?.then) && isFunction(val?.catch);
31
- var isUndef = (val) => val === void 0 || val === null;
32
- var isDef = (val) => val !== void 0 && val !== null;
33
- var hasChanged = (oldValue, newValue) => oldValue !== newValue;
34
-
35
- // src/lang/isPlainObject.ts
36
- function isPlainObject(value) {
37
- return toTypeString(value) === "[object Object]";
38
- }
39
-
40
- // src/array/castArray.ts
41
- function castArray(target) {
42
- return isArray(target) ? target : [target];
43
- }
44
-
45
- // src/utils/code.ts
46
- function decimalToBinary(decNumber) {
47
- const stack = [];
48
- let remainder;
49
- let binaryString = "";
50
- while (decNumber > 0) {
51
- remainder = Math.floor(decNumber % 2);
52
- stack.push(remainder);
53
- decNumber = Math.floor(decNumber / 2);
54
- }
55
- while (stack.length > 0) {
56
- binaryString += stack.pop().toString();
57
- }
58
- return binaryString;
59
- }
60
- var BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
61
- function base64Encode(str) {
62
- let result = "";
63
- let bin = "";
64
- for (let i = 0; i < str.length; i++) {
65
- bin += str[i].charCodeAt(0).toString(2).padStart(8, "0");
66
- }
67
- for (let i = 0; i < bin.length; i += 6) {
68
- result += BASE64_CHARS[parseInt(bin.slice(i, i + 6).padEnd(6, "0"), 2)];
69
- }
70
- const padding = result.length % 4;
71
- if (padding !== 0) result += "=".repeat(4 - padding);
72
- return result;
73
- }
74
- function base64Decode(str) {
75
- let result = "";
76
- let bin = "";
77
- for (let i = 0; i < str.length; i++) {
78
- if (str[i] === "=") break;
79
- bin += BASE64_CHARS.indexOf(str[i]).toString(2).padStart(6, "0");
80
- }
81
- for (let i = 0; i < bin.length; i += 8) {
82
- const binary = parseInt(bin.slice(i, i + 8), 2);
83
- if (binary) {
84
- result += String.fromCharCode(binary);
85
- }
86
- }
87
- return result;
88
- }
89
-
90
- // src/utils/compose.ts
91
- function compose(...fns) {
92
- return fns.reduce(
93
- (previous, current) => function(...args) {
94
- return current(previous(...args));
95
- }
96
- );
97
- }
98
- function composeRight(...fns) {
99
- return fns.reduce(
100
- (previous, current) => function(...args) {
101
- return previous(current(...args));
102
- }
103
- );
104
- }
105
-
106
- // src/utils/debounce.ts
107
- function debounce(target, wait = 500) {
108
- let timer = null;
109
- return function(...args) {
110
- if (timer) clearTimeout(timer);
111
- timer = setTimeout(() => {
112
- target.apply(this, args);
113
- }, wait);
114
- };
115
- }
116
-
117
- // src/utils/deepClone.ts
118
- function deepClone(target) {
119
- const map = /* @__PURE__ */ new WeakMap();
120
- function _deepClone(value) {
121
- if (!isObjectLike(value)) return value;
122
- if (isDate(value)) return new Date(value);
123
- if (isRegExp(value)) return new RegExp(value);
124
- if (isPromise(value)) return value;
125
- if (map.has(value)) return map.get(value);
126
- if (isMap(value)) {
127
- const cloned2 = /* @__PURE__ */ new Map();
128
- map.set(value, cloned2);
129
- value.forEach((val, key) => cloned2.set(_deepClone(key), _deepClone(val)));
130
- return cloned2;
131
- }
132
- if (isSet(value)) {
133
- const cloned2 = /* @__PURE__ */ new Set();
134
- map.set(value, cloned2);
135
- value.forEach((val) => cloned2.add(_deepClone(val)));
136
- return cloned2;
137
- }
138
- const cloned = isArray(value) ? Object.setPrototypeOf([], Object.getPrototypeOf(value)) : Object.create(Object.getPrototypeOf(value));
139
- map.set(value, cloned);
140
- const descriptors = Object.getOwnPropertyDescriptors(value);
141
- for (const key of Reflect.ownKeys(descriptors)) {
142
- const descriptor = descriptors[key];
143
- if (descriptor.get || descriptor.set) {
144
- Object.defineProperty(cloned, key, descriptor);
145
- } else {
146
- Object.defineProperty(cloned, key, { ...descriptor, value: _deepClone(descriptor.value) });
147
- }
148
- }
149
- return cloned;
150
- }
151
- return _deepClone(target);
152
- }
153
-
154
- // src/utils/deepMerge.ts
155
- function deepMerge(template, source, options = {}) {
156
- return _deepMerge(clone(template, options), clone(source, options), options);
157
- }
158
- function _deepMerge(template, source, options) {
159
- return isArray(template) ? arrayMerge(template, source, options) : mergeObject(template, source, options);
160
- }
161
- function mergeObject(template, source, options) {
162
- if (!isPlainObject(source)) return source;
163
- const descriptors = Object.getOwnPropertyDescriptors(source);
164
- Reflect.ownKeys(source).forEach((key) => {
165
- if ((isPlainObject(template[key]) || isArray(template[key])) && (isPlainObject(source[key]) || isArray(source[key]))) {
166
- template[key] = _deepMerge(template[key], source[key], options);
167
- } else {
168
- Object.defineProperty(template, key, descriptors[key]);
169
- }
170
- });
171
- return template;
172
- }
173
- function arrayMerge(template, source, options) {
174
- const { mergeStrategy = "replace" } = options;
175
- if (isArray(source)) {
176
- switch (mergeStrategy) {
177
- case "merge":
178
- return template.concat(source);
179
- case "replace":
180
- return source;
181
- default:
182
- return source;
183
- }
184
- }
185
- return source;
186
- }
187
- function clone(source, options) {
188
- const { deepClone: _deepClone = true } = options;
189
- return _deepClone ? deepClone(source) : source;
190
- }
191
-
192
- // src/utils/error.ts
193
- var UtilsError = class extends Error {
194
- constructor(m, name = "Utils") {
195
- super(m);
196
- this.name = name;
197
- }
198
- };
199
- function throwError(scope, message) {
200
- throw new UtilsError(`[${scope}] ${message}`);
201
- }
202
- function debugWarn(scope, message) {
203
- const error2 = isString(scope) ? new UtilsError(`[${scope}] ${message}`, "UtilsWarn") : scope;
204
- console.warn(error2);
205
- }
206
- function warn(...args) {
207
- console.warn(...args);
208
- }
209
- function error(...args) {
210
- console.error(...args);
211
- }
212
- var deprecated = ({
213
- from,
214
- replacement,
215
- version,
216
- type = "API"
217
- }) => {
218
- debugWarn(`${type}`, `${from} is about to be deprecated in version ${version}, please use ${replacement} instead.`);
219
- };
220
- function throwErrorInvalidTypeMessage(scope, key, type, value) {
221
- const message = `Invalid params: type check failed for params "${key}". Expected ${type}, got ${toTypeValue(value)} with value ${value}.`;
222
- throwError(scope, message);
223
- }
224
- function debugWarnInvalidTypeMessage(scope, key, type, value) {
225
- const message = `Invalid params: type check failed for params "${key}". Expected ${type}, got ${toTypeValue(value)} with value ${value}.`;
226
- debugWarn(scope, message);
227
- }
228
-
229
- // src/utils/log.ts
230
- var baseConsole = (type, name, ...arg) => {
231
- if (!name) return;
232
- const context = arg.length === 0 ? "" : arg.length === 1 ? arg[0] : arg;
233
- console[type](`[Log] ${name}:`, context);
234
- };
235
- var log = (name, ...arg) => {
236
- baseConsole("info", name, ...arg);
237
- };
238
- log.info = (name, ...arg) => {
239
- baseConsole("info", name, ...arg);
240
- };
241
- log.error = (name, ...arg) => {
242
- baseConsole("error", name, ...arg);
243
- };
244
- log.warn = (name, ...arg) => {
245
- baseConsole("warn", name, ...arg);
246
- };
247
- if (typeof globalThis !== "undefined") {
248
- globalThis.log = log;
249
- }
250
-
251
- // src/utils/qs.ts
252
- function parse(str, options) {
253
- const { decode = true } = options || {};
254
- const result = {};
255
- str.startsWith("?") && (str = str.slice(1));
256
- str.includes("?") && (str = str.slice(str.indexOf("?") + 1));
257
- const pairs = str.split("&").filter(Boolean);
258
- for (const pair of pairs) {
259
- const [key, value] = pair.split("=");
260
- result[key] = decode ? decodeURIComponent(value) : value;
261
- }
262
- return result;
263
- }
264
- function stringify(obj, options) {
265
- const { encode = true } = options || {};
266
- const pairs = [];
267
- for (const key in obj) {
268
- const value = obj[key];
269
- pairs.push(`${key}=${encode ? encodeURIComponent(value) : value}`);
270
- }
271
- return pairs.join("&");
272
- }
273
- function appendQueryString(url, obj, options) {
274
- const stringifyOptions = deepMerge({ encode: true }, { ...options });
275
- const query = stringify(obj, stringifyOptions);
276
- if (url.includes("?")) {
277
- return url.endsWith("?") || url.endsWith("&") ? `${url}${query}` : `${url}&${query}`;
278
- }
279
- return `${url}?${query}`;
280
- }
281
- var qs = {
282
- parse,
283
- stringify,
284
- appendQueryString
285
- };
286
-
287
- // src/utils/throttle.ts
288
- function throttle(target, wait = 500) {
289
- let timer = null;
290
- return function(...args) {
291
- if (isUndef(timer)) {
292
- timer = Date.now();
293
- return target.apply(this, args);
294
- }
295
- const now = Date.now();
296
- if (now - timer >= wait) {
297
- timer = now;
298
- return target.apply(this, args);
299
- }
300
- };
301
- }
302
-
303
- // src/utils/validator.ts
304
- function validatorChineseOrEnglishOrNumber(value) {
305
- return !isUndef(value) && /^[\dA-Z\u4E00-\u9FA5]+$/i.test(value);
306
- }
307
- function validatorChineseOrEnglish(value) {
308
- return !isUndef(value) && /^[A-Z\u4E00-\u9FA5]+$/i.test(value);
309
- }
310
- function validatorUppercaseOrNumbersOrSpecial(value) {
311
- return !isUndef(value) && /^[\d!"#$%&'()*+,./:;<=>?@A-Z[\\\]^_`{|}~]+$/.test(value);
312
- }
313
- function validatorUppercaseOrNumbersOrUnderline(value) {
314
- return /^[\dA-Z_]+$/.test(value);
315
- }
316
-
317
- // src/object/pick.ts
318
- function pick(target, properties, options = {}) {
319
- const { includeProto = false, includeSymbols = true, includeNonEnum = false } = options;
320
- const cloned = {};
321
- if (!isPlainObject(target)) return cloned;
322
- const propsToPick = castArray(properties);
323
- propsToPick.forEach((key) => {
324
- if (isSymbol(key) && !includeSymbols) return;
325
- const exists = includeProto ? key in target : Object.hasOwn(target, key);
326
- if (!exists) return;
327
- if (!includeNonEnum) {
328
- const descriptor = includeProto ? findPropertyDescriptor(target, key) : Object.getOwnPropertyDescriptor(target, key);
329
- if (descriptor?.enumerable === false) return;
330
- }
331
- cloned[key] = deepClone(target[key]);
332
- });
333
- return cloned;
334
- }
335
- function findPropertyDescriptor(obj, key) {
336
- let current = obj;
337
- while (current !== null) {
338
- const descriptor = Object.getOwnPropertyDescriptor(current, key);
339
- if (descriptor) return descriptor;
340
- current = Object.getPrototypeOf(current);
341
- }
342
- }
343
-
344
- // src/object/omit.ts
345
- function omit(target, properties) {
346
- if (!isPlainObject(target)) return {};
347
- const cloned = deepClone(target);
348
- const propsToOmit = castArray(properties);
349
- const keysToPick = Object.keys(cloned).filter(
350
- (key) => !propsToOmit.includes(key)
351
- );
352
- return pick(cloned, keysToPick);
353
- }
354
-
355
- // src/random/generateRandomArray.ts
356
- function generateRandomArray(num, cb) {
357
- if (!isNumber(num) || num <= 0) {
358
- throwError("generateRandomArray", "num \u5FC5\u987B\u5927\u4E8E0");
359
- }
360
- if (!isFunction(cb)) {
361
- throwError("generateRandomArray", "cb \u5FC5\u987B\u662F\u51FD\u6570");
362
- }
363
- return Array.from({ length: num }).fill(0).map((e, i) => cb(e, i));
364
- }
365
-
366
- // src/random/generateRandomColor.ts
367
- function generateRandomColor() {
368
- return `#${Math.random().toString(16).slice(2, 8).padEnd(6, "0")}`;
369
- }
370
-
371
- // src/random/generateRandomDate.ts
372
- import dayjs, { extend } from "dayjs";
373
- import customParseFormat from "dayjs/plugin/customParseFormat";
374
-
375
- // src/random/getRandomItem.ts
376
- function getRandomItem(list) {
377
- return list[Math.floor(Math.random() * list.length)];
378
- }
379
-
380
- // src/random/getRandomInt.ts
381
- function getRandomInt(options = {}) {
382
- if (isNumber(options)) options = { max: options };
383
- const { min = 1, max = getRandomItem(getMaxSafeIntegerList()) } = options;
384
- validateOptions(min, max);
385
- const effectiveMin = Math.ceil(min);
386
- const effectiveMax = Math.floor(max);
387
- return Math.floor(Math.random() * (effectiveMax - effectiveMin + 1) + effectiveMin);
388
- }
389
- function validateOptions(min, max) {
390
- const effectiveMin = Math.ceil(min);
391
- const effectiveMax = Math.floor(max);
392
- if (!Number.isSafeInteger(effectiveMin)) {
393
- throwError("getRandomInt", `The minimum value Math.ceil(${min}) should be a safe integer`);
394
- }
395
- if (!Number.isSafeInteger(effectiveMax)) {
396
- throwError("getRandomInt", `The maximum value Math.floor(${max}) should be a safe integer`);
397
- }
398
- if (effectiveMax < effectiveMin) {
399
- if (max >= min) {
400
- throwError("getRandomInt", `No integer value found between ${min} and ${max}`);
401
- }
402
- throwError("getRandomInt", `The maximum value ${max} should be greater than the minimum value ${min}`);
403
- }
404
- }
405
- function getMaxSafeIntegerList() {
406
- return Array.from({ length: Number.MAX_SAFE_INTEGER.toString().length }).map((_, i) => {
407
- const max = Number.MAX_SAFE_INTEGER.toString().slice(0, i + 1);
408
- return Number(max);
409
- });
410
- }
411
-
412
- // src/random/generateRandomDate.ts
413
- extend(customParseFormat);
414
- function generateRandomDate(options = {}) {
415
- const {
416
- start = "1800-01-01 00:00:00",
417
- end = dayjs().format("YYYY-MM-DD HH:mm:ss"),
418
- format = "YYYY-MM-DD HH:mm:ss"
419
- } = options;
420
- if (!dayjs(start).isValid() || !dayjs(end).isValid()) {
421
- throwError("generateRandomDate", "start end \u53C2\u6570\u5FC5\u987B\u662F\u5408\u6CD5\u7684\u65F6\u95F4\u683C\u5F0F");
422
- }
423
- const startYear = dayjs(start).year();
424
- const endYear = dayjs(end).year();
425
- const randomYear = getRandomInt({ min: startYear, max: endYear });
426
- const randomMonth = getRandomInt({ min: 1, max: 12 });
427
- const randomDay = getRandomInt({ min: 1, max: 31 });
428
- const randomHour = getRandomInt(23);
429
- const randomMinute = getRandomInt(59);
430
- const randomSecond = getRandomInt(59);
431
- const result = dayjs(`${randomYear}-${randomMonth}-${randomDay} ${randomHour}:${randomMinute}:${randomSecond}`);
432
- if (result.isBefore(dayjs(start)) || result.isAfter(dayjs(end))) {
433
- return generateRandomDate(options);
434
- }
435
- return result.format(format);
436
- }
437
-
438
- // src/random/getRandomString.ts
439
- function getRandomString(options = {}) {
440
- const normalizedOptions = normalizeOptions(options);
441
- const characters = buildCharacterSet(normalizedOptions);
442
- validateLengthCharacters(characters);
443
- const { length } = normalizedOptions;
444
- validateLength(length.min, length.max);
445
- const len = getRandomInt(length);
446
- let result = normalizedOptions.prefix || "";
447
- for (let i = 0; i < len; i++) {
448
- result += characters.charAt(Math.floor(Math.random() * characters.length));
449
- }
450
- return result + (normalizedOptions.suffix || "");
451
- }
452
- var DEFAULT_MAX = 16;
453
- var DEFAULT_MIN = 1;
454
- function normalizeOptions(options) {
455
- const simple = isNumber(options);
456
- return {
457
- lowerCase: true,
458
- upperCase: true,
459
- number: true,
460
- ...simple ? {} : options,
461
- length: simple ? { max: options, min: options } : isNumber(options.length) ? { max: options.length, min: options.length } : { max: DEFAULT_MAX, min: DEFAULT_MIN, ...options.length },
462
- extra: simple ? [] : [...new Set(castArray(options.extra || []))]
463
- };
464
- }
465
- function buildCharacterSet(options) {
466
- let characters = "";
467
- if (options.lowerCase) characters += "abcdefghijklmnopqrstuvwxyz";
468
- if (options.upperCase) characters += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
469
- if (options.number) characters += "0123456789";
470
- characters += castArray(options.extra).join("");
471
- return characters;
472
- }
473
- function validateLengthCharacters(characters) {
474
- if (characters.length === 0) {
475
- throwError(
476
- "getRandomString",
477
- "At least one character set (lowercase, uppercase, number) must be enabled or extra characters provided"
478
- );
479
- }
480
- }
481
- function validateLength(min, max) {
482
- if (!Number.isInteger(min)) throwError("getRandomString", "min must be an integer");
483
- if (!Number.isInteger(max)) throwError("getRandomString", "max must be an integer");
484
- if (min < DEFAULT_MIN) throwError("getRandomString", `Minimum length cannot be less than ${DEFAULT_MIN}`);
485
- if (max < min) throwError("getRandomString", `Maximum length cannot be less than minimum length`);
486
- }
487
-
488
- // src/random/generateRandomEmail.ts
489
- function generateRandomEmail() {
490
- const emailProviders = ["gmail.com", "outlook.com.cn", "example.com", "qq.com", "163.com", "test.com.cn"];
491
- const result = `${getRandomString(1)}${getRandomString({
492
- length: getRandomInt({ max: 30, min: 1 })
493
- })}${getRandomString(1)}@${getRandomItem(emailProviders)}`;
494
- if (/\.{2,}/.test(result)) {
495
- return generateRandomEmail();
496
- }
497
- return result;
498
- }
499
-
500
- // src/random/generateRandomFloat.ts
501
- function generateRandomFloat(options = {}) {
502
- if (isNumber(options)) {
503
- options = { max: options };
504
- }
505
- const { min = 0, max = 1, fractionDigits = 2 } = options;
506
- if (min === max) {
507
- return min;
508
- }
509
- if (min > max) {
510
- throw new Error(`\u6700\u5927\u503C ${max} \u5E94\u5927\u4E8E\u6700\u5C0F\u503C ${min}`);
511
- }
512
- return Math.random() * (max - min) + min;
513
- }
514
-
515
- // src/random/generateRandomStringFromSource.ts
516
- function generateRandomStringFromSource(num, source) {
517
- if (!isNumber(num) || num <= 0) {
518
- throwError("generateRandomStringFromSource", "num \u5FC5\u987B\u5927\u4E8E0");
519
- }
520
- if (!isArray(source) || source.length === 0) {
521
- throwError("generateRandomStringFromSource", "source \u4E0D\u80FD\u4E3A\u7A7A\u6570\u7EC4");
522
- }
523
- let result = "";
524
- for (let i = 0; i < num; i++) {
525
- result += getRandomItem(source);
526
- }
527
- return result;
528
- }
529
-
530
- // src/random/generateRandomIdCard.ts
531
- function generateRandomIdCard() {
532
- const prefix = getRandomInt({ min: 1e5, max: 999999 });
533
- const zeroToNine = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
534
- return [
535
- prefix,
536
- generateRandomDate({ format: "YYYYMMDD" }),
537
- generateRandomStringFromSource(3, zeroToNine),
538
- generateRandomStringFromSource(1, [...zeroToNine, "X", "x"])
539
- ].join("");
540
- }
541
-
542
- // src/random/generateRandomMobilePhone.ts
543
- function generateRandomMobilePhone() {
544
- return getRandomItem(["13", "14", "15", "16", "17", "18", "19"]) + getRandomInt(999999999).toString().padEnd(9, "0");
545
- }
546
-
547
- // src/random/getRandomUrl.ts
548
- function getRandomUrl() {
549
- const urlPrefix = ["http://", "https://"];
550
- const domainSuffix = [".com", ".net", ".org", ".cn", ".top"];
551
- const parameters = [
552
- `?name=${getRandomString({ length: { min: 4, max: 8 } })}`,
553
- `?id=${getRandomInt()}`,
554
- `?page=${getRandomString({ length: { min: 2, max: 4 } })}`,
555
- `?query=${getRandomString({ length: { min: 5, max: 6 } })}`,
556
- `?search=${getRandomString({ length: { min: 1, max: 4 } })}`,
557
- `?token=${getRandomString({ length: { min: 16, max: 16 } })}`
558
- ];
559
- return `${getRandomItem(urlPrefix)}${getRandomString({ length: { min: 5, max: 25 } })}${getRandomItem(domainSuffix)}${getRandomItem(parameters)}`;
560
- }
561
-
562
- // src/validator/aphabet.ts
563
- function isNumberOrNumberString(val) {
564
- return /^\d+$/.test(val);
565
- }
566
- function isEnglishAphabet(val) {
567
- return /^[A-Z]+$/i.test(val);
568
- }
569
- function isUpperCase(val) {
570
- return /^[A-Z]+$/.test(val);
571
- }
572
- function isUpperCaseAndNumber(val) {
573
- return /^[\dA-Z]+$/.test(val);
574
- }
575
- function isUpperCaseAndNumberAndChinese(val) {
576
- return /^[\dA-Z\u4E00-\u9FA5]+$/.test(val);
577
- }
578
- function isLowerCase(val) {
579
- return /^[a-z]+$/.test(val);
580
- }
581
- function isLowerCaseAndNumber(val) {
582
- return /^[\da-z]+$/.test(val);
583
- }
584
- function isLowerCaseAndNumberAndChinese(val) {
585
- return /^[\da-z\u4E00-\u9FA5]+$/.test(val);
586
- }
587
- function isChineseString(val) {
588
- return /^[\u4E00-\u9FA5]+$/.test(val);
589
- }
590
-
591
- // src/validator/float.ts
592
- function isFloat(val) {
593
- return /^-?(?:0|[1-9]\d*)\.\d+$/.test(val);
594
- }
595
- function isPositiveFloat(val) {
596
- return /^(?:0\.0*[1-9]\d*|[1-9]\d*\.\d+)$/.test(val);
597
- }
598
- function isNonNegativeFloat(val) {
599
- return /^(?:0|[1-9]\d*)\.\d+$/.test(val);
600
- }
601
- function isNegativeFloat(val) {
602
- return /^-(?:0\.0*[1-9]\d*|[1-9]\d*\.\d+)$/.test(val);
603
- }
604
- function isNonPositiveFloat(val) {
605
- return /^-(?:0|[1-9]\d*)\.\d+$/.test(val);
606
- }
607
-
608
- // src/validator/integer.ts
609
- function isInteger(val) {
610
- return /^-?(?:0|[1-9]\d*)$/.test(val);
611
- }
612
- function isPositiveInteger(val) {
613
- return /^[1-9]\d*$/.test(val);
614
- }
615
- function isNonNegativeInteger(val) {
616
- return /^(?:0|[1-9]\d*)$/.test(val) && !Object.is(val, -0);
617
- }
618
- function isNegativeInteger(val) {
619
- return /^-[1-9]\d*$/.test(val);
620
- }
621
- function isNonPositiveInteger(val) {
622
- return /^-(?:0|[1-9]\d*)$/.test(val) || Object.is(val, -0);
623
- }
624
-
625
- // src/validator/utils.ts
626
- import dayjs2, { extend as extend2 } from "dayjs";
627
- import customParseFormat2 from "dayjs/plugin/customParseFormat";
628
- function isMobilePhone(val) {
629
- return /^1[3-9]\d{9}$/.test(val);
630
- }
631
- function isUrl(val) {
632
- return /^https?:\/\/\S+$/i.test(val);
633
- }
634
- function isEmail(val) {
635
- return /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(val);
636
- }
637
- function isEmptyString(val) {
638
- return val === "";
639
- }
640
- function isDateString(val, format = "YYYY-MM-DD HH:mm:ss") {
641
- extend2(customParseFormat2);
642
- return dayjs2(val, format, true).isValid();
643
- }
644
- function isIdCard(val) {
645
- const flag = /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dX]$/i.test(val) && isDateString(val.slice(6, 14), "YYYYMMDD");
646
- return flag;
647
- }
648
- export {
649
- base64Decode,
650
- base64Encode,
651
- castArray,
652
- compose,
653
- composeRight,
654
- debounce,
655
- debugWarn,
656
- debugWarnInvalidTypeMessage,
657
- decimalToBinary,
658
- deepClone,
659
- deepMerge,
660
- deprecated,
661
- error,
662
- generateRandomArray,
663
- generateRandomColor,
664
- generateRandomDate,
665
- generateRandomEmail,
666
- generateRandomFloat,
667
- generateRandomIdCard,
668
- generateRandomMobilePhone,
669
- generateRandomStringFromSource,
670
- getRandomInt,
671
- getRandomItem,
672
- getRandomString,
673
- getRandomUrl,
674
- hasChanged,
675
- isArray,
676
- isBoolean,
677
- isChineseString,
678
- isDate,
679
- isDateString,
680
- isDef,
681
- isEmail,
682
- isEmptyString,
683
- isEnglishAphabet,
684
- isFloat,
685
- isFunction,
686
- isIdCard,
687
- isInteger,
688
- isLowerCase,
689
- isLowerCaseAndNumber,
690
- isLowerCaseAndNumberAndChinese,
691
- isMap,
692
- isMobilePhone,
693
- isNegativeFloat,
694
- isNegativeInteger,
695
- isNonNegativeFloat,
696
- isNonNegativeInteger,
697
- isNonPositiveFloat,
698
- isNonPositiveInteger,
699
- isNull,
700
- isNumber,
701
- isNumberOrNumberString,
702
- isObject,
703
- isObjectLike,
704
- isPlainObject,
705
- isPositiveFloat,
706
- isPositiveInteger,
707
- isPromise,
708
- isRegExp,
709
- isSet,
710
- isString,
711
- isSymbol,
712
- isUndef,
713
- isUndefined,
714
- isUpperCase,
715
- isUpperCaseAndNumber,
716
- isUpperCaseAndNumberAndChinese,
717
- isUrl,
718
- objectToString,
719
- omit,
720
- pick,
721
- qs,
722
- throttle,
723
- throwError,
724
- throwErrorInvalidTypeMessage,
725
- toTypeString,
726
- toTypeValue,
727
- validatorChineseOrEnglish,
728
- validatorChineseOrEnglishOrNumber,
729
- validatorUppercaseOrNumbersOrSpecial,
730
- validatorUppercaseOrNumbersOrUnderline,
731
- warn
732
- };
2
+ function ft(t){let e=typeof t;return t!==null&&(e==="object"||e==="function")}function w(t){return t!==null&&typeof t=="object"}var q=Object.prototype.toString,b=t=>q.call(t),R=t=>b(t).slice(8,-1),P=t=>typeof t=="string",u=t=>typeof t=="number"&&Number.isFinite(t),dt=t=>typeof t=="boolean",xt=t=>t===null,bt=t=>t===void 0,N=t=>typeof t=="symbol",g=Array.isArray,$=t=>typeof t=="function",C=t=>b(t)==="[object Map]",F=t=>b(t)==="[object Set]",v=t=>b(t)==="[object Date]",Y=t=>b(t)==="[object RegExp]",U=t=>w(t)&&$(t?.then)&&$(t?.catch),h=t=>t==null,yt=t=>t!=null,ht=(t,e)=>t!==e;function x(t){return b(t)==="[object Object]"}function y(t){return g(t)?t:[t]}function It(t){let e=[],n,r="";for(;t>0;)n=Math.floor(t%2),e.push(n),t=Math.floor(t/2);for(;e.length>0;)r+=e.pop().toString();return r}var _="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Pt(t){let e="",n="";for(let o=0;o<t.length;o++)n+=t[o].charCodeAt(0).toString(2).padStart(8,"0");for(let o=0;o<n.length;o+=6)e+=_[parseInt(n.slice(o,o+6).padEnd(6,"0"),2)];let r=e.length%4;return r!==0&&(e+="=".repeat(4-r)),e}function Nt(t){let e="",n="";for(let r=0;r<t.length&&t[r]!=="=";r++)n+=_.indexOf(t[r]).toString(2).padStart(6,"0");for(let r=0;r<n.length;r+=8){let o=parseInt(n.slice(r,r+8),2);o&&(e+=String.fromCharCode(o))}return e}function Ft(...t){return t.reduce((e,n)=>function(...r){return n(e(...r))})}function vt(...t){return t.reduce((e,n)=>function(...r){return e(n(...r))})}function Ut(t,e=500){let n=null;return function(...r){n&&clearTimeout(n),n=setTimeout(()=>{t.apply(this,r)},e)}}function O(t){let e=new WeakMap;function n(r){if(!w(r))return r;if(v(r))return new Date(r);if(Y(r))return new RegExp(r);if(U(r))return r;if(e.has(r))return e.get(r);if(C(r)){let i=new Map;return e.set(r,i),r.forEach((c,f)=>i.set(n(f),n(c))),i}if(F(r)){let i=new Set;return e.set(r,i),r.forEach(c=>i.add(n(c))),i}let o=g(r)?Object.setPrototypeOf([],Object.getPrototypeOf(r)):Object.create(Object.getPrototypeOf(r));e.set(r,o);let m=Object.getOwnPropertyDescriptors(r);for(let i of Reflect.ownKeys(m)){let c=m[i];c.get||c.set?Object.defineProperty(o,i,c):Object.defineProperty(o,i,{...c,value:n(c.value)})}return o}return n(t)}function K(t,e,n={}){return z(L(t,n),L(e,n),n)}function z(t,e,n){return g(t)?V(t,e,n):B(t,e,n)}function B(t,e,n){if(!x(e))return e;let r=Object.getOwnPropertyDescriptors(e);return Reflect.ownKeys(e).forEach(o=>{(x(t[o])||g(t[o]))&&(x(e[o])||g(e[o]))?t[o]=z(t[o],e[o],n):Object.defineProperty(t,o,r[o])}),t}function V(t,e,n){let{mergeStrategy:r="replace"}=n;if(g(e))switch(r){case"merge":return t.concat(e);case"replace":return e;default:return e}return e}function L(t,e){let{deepClone:n=!0}=e;return n?O(t):t}var A=class extends Error{constructor(e,n="Utils"){super(e),this.name=n}};function s(t,e){throw new A(`[${t}] ${e}`)}function W(t,e){let n=P(t)?new A(`[${t}] ${e}`,"UtilsWarn"):t;console.warn(n)}function Gt(...t){console.warn(...t)}function qt(...t){console.error(...t)}var Bt=({from:t,replacement:e,version:n,type:r="API"})=>{W(`${r}`,`${t} is about to be deprecated in version ${n}, please use ${e} instead.`)};function Vt(t,e,n,r){let o=`Invalid params: type check failed for params "${e}". Expected ${n}, got ${R(r)} with value ${r}.`;s(t,o)}function Xt(t,e,n,r){let o=`Invalid params: type check failed for params "${e}". Expected ${n}, got ${R(r)} with value ${r}.`;W(t,o)}var S=(t,e,...n)=>{if(!e)return;let r=n.length===0?"":n.length===1?n[0]:n;console[t](`[Log] ${e}:`,r)},j=(t,...e)=>{S("info",t,...e)};j.info=(t,...e)=>{S("info",t,...e)};j.error=(t,...e)=>{S("error",t,...e)};j.warn=(t,...e)=>{S("warn",t,...e)};typeof globalThis<"u"&&(globalThis.log=j);function X(t,e){let{decode:n=!0}=e||{},r={};t.startsWith("?")&&(t=t.slice(1)),t.includes("?")&&(t=t.slice(t.indexOf("?")+1));let o=t.split("&").filter(Boolean);for(let m of o){let[i,c]=m.split("=");r[i]=n?decodeURIComponent(c):c}return r}function H(t,e){let{encode:n=!0}=e||{},r=[];for(let o in t){let m=t[o];r.push(`${o}=${n?encodeURIComponent(m):m}`)}return r.join("&")}function Q(t,e,n){let r=K({encode:!0},{...n}),o=H(e,r);return t.includes("?")?t.endsWith("?")||t.endsWith("&")?`${t}${o}`:`${t}&${o}`:`${t}?${o}`}var te={parse:X,stringify:H,appendQueryString:Q};function re(t,e=500){let n=null;return function(...r){if(h(n))return n=Date.now(),t.apply(this,r);let o=Date.now();if(o-n>=e)return n=o,t.apply(this,r)}}function se(t){return!h(t)&&/^[\dA-Z\u4E00-\u9FA5]+$/i.test(t)}function ae(t){return!h(t)&&/^[A-Z\u4E00-\u9FA5]+$/i.test(t)}function me(t){return!h(t)&&/^[\d!"#$%&'()*+,./:;<=>?@A-Z[\\\]^_`{|}~]+$/.test(t)}function ce(t){return/^[\dA-Z_]+$/.test(t)}function Z(t,e,n={}){let{includeProto:r=!1,includeSymbols:o=!0,includeNonEnum:m=!1}=n,i={};return x(t)&&y(e).forEach(f=>{N(f)&&!o||!(r?f in t:Object.hasOwn(t,f))||!m&&(r?J(t,f):Object.getOwnPropertyDescriptor(t,f))?.enumerable===!1||(i[f]=O(t[f]))}),i}function J(t,e){let n=t;for(;n!==null;){let r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=Object.getPrototypeOf(n)}}function Ee(t,e){if(!x(t))return{};let n=O(t),r=y(e),o=Object.keys(n).filter(m=>!r.includes(m));return Z(n,o)}function ve(t,e){return(!u(t)||t<=0)&&s("generateRandomArray","num \u5FC5\u987B\u5927\u4E8E0"),$(e)||s("generateRandomArray","cb \u5FC5\u987B\u662F\u51FD\u6570"),Array.from({length:t}).fill(0).map((n,r)=>e(n,r))}function Ue(){return`#${Math.random().toString(16).slice(2,8).padEnd(6,"0")}`}import d from"dayjs";import nt from"dayjs/plugin/customParseFormat.js";function p(t){return t[Math.floor(Math.random()*t.length)]}function a(t={}){u(t)&&(t={max:t});let{min:e=1,max:n=p(et())}=t;tt(e,n);let r=Math.ceil(e),o=Math.floor(n);return Math.floor(Math.random()*(o-r+1)+r)}function tt(t,e){let n=Math.ceil(t),r=Math.floor(e);Number.isSafeInteger(n)||s("getRandomInt",`The minimum value Math.ceil(${t}) should be a safe integer`),Number.isSafeInteger(r)||s("getRandomInt",`The maximum value Math.floor(${e}) should be a safe integer`),r<n&&(e>=t&&s("getRandomInt",`No integer value found between ${t} and ${e}`),s("getRandomInt",`The maximum value ${e} should be greater than the minimum value ${t}`))}function et(){return Array.from({length:Number.MAX_SAFE_INTEGER.toString().length}).map((t,e)=>{let n=Number.MAX_SAFE_INTEGER.toString().slice(0,e+1);return Number(n)})}d.extend(nt);function T(t={}){let{start:e="1800-01-01 00:00:00",end:n=d().format("YYYY-MM-DD HH:mm:ss"),format:r="YYYY-MM-DD HH:mm:ss"}=t;(!d(e).isValid()||!d(n).isValid())&&s("generateRandomDate","start end \u53C2\u6570\u5FC5\u987B\u662F\u5408\u6CD5\u7684\u65F6\u95F4\u683C\u5F0F");let o=d(e).year(),m=d(n).year(),i=a({min:o,max:m}),c=a({min:1,max:12}),f=a({min:1,max:31}),D=a(23),I=a(59),G=a(59),M=d(`${i}-${c}-${f} ${D}:${I}:${G}`);return M.isBefore(d(e))||M.isAfter(d(n))?T(t):M.format(r)}function l(t={}){let e=ot(t),n=it(e);st(n);let{length:r}=e;at(r.min,r.max);let o=a(r),m=e.prefix||"";for(let i=0;i<o;i++)m+=n.charAt(Math.floor(Math.random()*n.length));return m+(e.suffix||"")}var rt=16,k=1;function ot(t){let e=u(t);return{lowerCase:!0,upperCase:!0,number:!0,...e?{}:t,length:e?{max:t,min:t}:u(t.length)?{max:t.length,min:t.length}:{max:rt,min:k,...t.length},extra:e?[]:[...new Set(y(t.extra||[]))]}}function it(t){let e="";return t.lowerCase&&(e+="abcdefghijklmnopqrstuvwxyz"),t.upperCase&&(e+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"),t.number&&(e+="0123456789"),e+=y(t.extra).join(""),e}function st(t){t.length===0&&s("getRandomString","At least one character set (lowercase, uppercase, number) must be enabled or extra characters provided")}function at(t,e){Number.isInteger(t)||s("getRandomString","min must be an integer"),Number.isInteger(e)||s("getRandomString","max must be an integer"),t<k&&s("getRandomString",`Minimum length cannot be less than ${k}`),e<t&&s("getRandomString","Maximum length cannot be less than minimum length")}function mt(){let t=["gmail.com","outlook.com.cn","example.com","qq.com","163.com","test.com.cn"],e=`${l(1)}${l({length:a({max:30,min:1})})}${l(1)}@${p(t)}`;return/\.{2,}/.test(e)?mt():e}function mn(t={}){u(t)&&(t={max:t});let{min:e=0,max:n=1,fractionDigits:r=2}=t;if(e===n)return e;if(e>n)throw new Error(`\u6700\u5927\u503C ${n} \u5E94\u5927\u4E8E\u6700\u5C0F\u503C ${e}`);return Math.random()*(n-e)+e}function E(t,e){(!u(t)||t<=0)&&s("generateRandomStringFromSource","num \u5FC5\u987B\u5927\u4E8E0"),(!g(e)||e.length===0)&&s("generateRandomStringFromSource","source \u4E0D\u80FD\u4E3A\u7A7A\u6570\u7EC4");let n="";for(let r=0;r<t;r++)n+=p(e);return n}function bn(){let t=a({min:1e5,max:999999}),e=[0,1,2,3,4,5,6,7,8,9];return[t,T({format:"YYYYMMDD"}),E(3,e),E(1,[...e,"X","x"])].join("")}function wn(){return p(["13","14","15","16","17","18","19"])+a(999999999).toString().padEnd(9,"0")}function Mn(){let t=["http://","https://"],e=[".com",".net",".org",".cn",".top"],n=[`?name=${l({length:{min:4,max:8}})}`,`?id=${a()}`,`?page=${l({length:{min:2,max:4}})}`,`?query=${l({length:{min:5,max:6}})}`,`?search=${l({length:{min:1,max:4}})}`,`?token=${l({length:{min:16,max:16}})}`];return`${p(t)}${l({length:{min:5,max:25}})}${p(e)}${p(n)}`}function Kn(t){return/^\d+$/.test(t)}function zn(t){return/^[A-Z]+$/i.test(t)}function Wn(t){return/^[A-Z]+$/.test(t)}function Hn(t){return/^[\dA-Z]+$/.test(t)}function Zn(t){return/^[\dA-Z\u4E00-\u9FA5]+$/.test(t)}function Gn(t){return/^[a-z]+$/.test(t)}function qn(t){return/^[\da-z]+$/.test(t)}function Bn(t){return/^[\da-z\u4E00-\u9FA5]+$/.test(t)}function Vn(t){return/^[\u4E00-\u9FA5]+$/.test(t)}function Qn(t){return/^-?(?:0|[1-9]\d*)\.\d+$/.test(t)}function Jn(t){return/^(?:0\.0*[1-9]\d*|[1-9]\d*\.\d+)$/.test(t)}function tr(t){return/^(?:0|[1-9]\d*)\.\d+$/.test(t)}function er(t){return/^-(?:0\.0*[1-9]\d*|[1-9]\d*\.\d+)$/.test(t)}function nr(t){return/^-(?:0|[1-9]\d*)\.\d+$/.test(t)}function or(t){return/^-?(?:0|[1-9]\d*)$/.test(t)}function ir(t){return/^[1-9]\d*$/.test(t)}function sr(t){return/^(?:0|[1-9]\d*)$/.test(t)&&!Object.is(t,-0)}function ar(t){return/^-[1-9]\d*$/.test(t)}function mr(t){return/^-(?:0|[1-9]\d*)$/.test(t)||Object.is(t,-0)}import ct from"dayjs";function fr(t){return/^1[3-9]\d{9}$/.test(t)}function ur(t){return/^https?:\/\/\S+$/i.test(t)}function gr(t){return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(t)}function lr(t){return t===""}function pt(t,e="YYYY-MM-DD HH:mm:ss"){return ct(t,e,!0).isValid()}function dr(t){return/^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dX]$/i.test(t)&&pt(t.slice(6,14),"YYYYMMDD")}export{Nt as base64Decode,Pt as base64Encode,y as castArray,Ft as compose,vt as composeRight,Ut as debounce,W as debugWarn,Xt as debugWarnInvalidTypeMessage,It as decimalToBinary,O as deepClone,K as deepMerge,Bt as deprecated,qt as error,ve as generateRandomArray,Ue as generateRandomColor,T as generateRandomDate,mt as generateRandomEmail,mn as generateRandomFloat,bn as generateRandomIdCard,wn as generateRandomMobilePhone,E as generateRandomStringFromSource,a as getRandomInt,p as getRandomItem,l as getRandomString,Mn as getRandomUrl,ht as hasChanged,g as isArray,dt as isBoolean,Vn as isChineseString,v as isDate,pt as isDateString,yt as isDef,gr as isEmail,lr as isEmptyString,zn as isEnglishAphabet,Qn as isFloat,$ as isFunction,dr as isIdCard,or as isInteger,Gn as isLowerCase,qn as isLowerCaseAndNumber,Bn as isLowerCaseAndNumberAndChinese,C as isMap,fr as isMobilePhone,er as isNegativeFloat,ar as isNegativeInteger,tr as isNonNegativeFloat,sr as isNonNegativeInteger,nr as isNonPositiveFloat,mr as isNonPositiveInteger,xt as isNull,u as isNumber,Kn as isNumberOrNumberString,ft as isObject,w as isObjectLike,x as isPlainObject,Jn as isPositiveFloat,ir as isPositiveInteger,U as isPromise,Y as isRegExp,F as isSet,P as isString,N as isSymbol,h as isUndef,bt as isUndefined,Wn as isUpperCase,Hn as isUpperCaseAndNumber,Zn as isUpperCaseAndNumberAndChinese,ur as isUrl,q as objectToString,Ee as omit,Z as pick,te as qs,re as throttle,s as throwError,Vt as throwErrorInvalidTypeMessage,b as toTypeString,R as toTypeValue,ae as validatorChineseOrEnglish,se as validatorChineseOrEnglishOrNumber,me as validatorUppercaseOrNumbersOrSpecial,ce as validatorUppercaseOrNumbersOrUnderline,Gt as warn};