@oipage/core.js 1.0.0 → 1.1.0-alpha.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.
Files changed (84) hide show
  1. package/CHANGELOG +52 -6
  2. package/LICENSE +20 -20
  3. package/README.md +170 -51
  4. package/dist/core.esm.js +2711 -0
  5. package/dist/core.js +2709 -208
  6. package/dist/core.min.js +2 -6
  7. package/package.json +63 -34
  8. package/src/Array/group.js +35 -0
  9. package/src/Array/index.js +21 -0
  10. package/src/Array/list.js +79 -0
  11. package/src/Array/sort.js +40 -0
  12. package/src/Array/tool.js +20 -0
  13. package/src/Array/unique.js +30 -0
  14. package/src/Cache/driver.js +86 -0
  15. package/src/Cache/expire.js +21 -0
  16. package/src/Cache/index.js +33 -0
  17. package/src/Cache/store.js +113 -0
  18. package/src/Color/adjust.js +67 -0
  19. package/src/Color/convert.js +100 -0
  20. package/src/Color/index.js +19 -0
  21. package/src/Color/tool.js +39 -0
  22. package/src/Digits/compare.js +33 -0
  23. package/src/Digits/format.js +55 -0
  24. package/src/Digits/index.js +32 -9
  25. package/src/Digits/math.js +75 -0
  26. package/src/Digits/precise.js +230 -0
  27. package/src/Digits/tool.js +29 -0
  28. package/src/Id/index.js +17 -0
  29. package/src/Id/nanoid.js +24 -0
  30. package/src/Id/random.js +40 -0
  31. package/src/Id/tool.js +38 -0
  32. package/src/Id/uuid.js +21 -0
  33. package/src/Object/check.js +15 -0
  34. package/src/Object/clone.js +66 -0
  35. package/src/Object/equal.js +63 -0
  36. package/src/Object/index.js +25 -0
  37. package/src/Object/merge.js +35 -0
  38. package/src/Object/path.js +58 -0
  39. package/src/Object/pick.js +34 -0
  40. package/src/Query/index.js +14 -0
  41. package/src/Query/parse.js +40 -0
  42. package/src/Query/stringify.js +45 -0
  43. package/src/Query/tool.js +58 -0
  44. package/src/Query/url.js +63 -0
  45. package/src/String/case.js +35 -0
  46. package/src/String/escape.js +40 -0
  47. package/src/String/index.js +28 -0
  48. package/src/String/mask.js +70 -0
  49. package/src/String/pad.js +23 -0
  50. package/src/String/trim.js +10 -0
  51. package/src/String/truncate.js +36 -0
  52. package/src/String/width.js +27 -0
  53. package/src/Time/arithmetic.js +61 -0
  54. package/src/Time/calendar.js +37 -0
  55. package/src/Time/compare.js +28 -0
  56. package/src/Time/field.js +37 -0
  57. package/src/Time/format.js +28 -0
  58. package/src/Time/index.js +97 -74
  59. package/src/Time/tool.js +20 -16
  60. package/src/Validate/contact.js +14 -0
  61. package/src/Validate/identity.js +57 -0
  62. package/src/Validate/index.js +24 -0
  63. package/src/Validate/network.js +59 -0
  64. package/src/Validate/type.js +28 -0
  65. package/src/index.js +10 -2
  66. package/src/shared/date.js +123 -0
  67. package/src/shared/is.js +63 -0
  68. package/src/tool.js +2 -2
  69. package/types/Array.d.ts +33 -0
  70. package/types/Cache.d.ts +51 -0
  71. package/types/Color.d.ts +43 -0
  72. package/types/Digits.d.ts +92 -0
  73. package/types/Id.d.ts +25 -0
  74. package/types/Object.d.ts +45 -0
  75. package/types/Query.d.ts +35 -0
  76. package/types/String.d.ts +62 -0
  77. package/types/Time.d.ts +136 -0
  78. package/types/Validate.d.ts +39 -0
  79. package/types/index.d.ts +30 -5
  80. package/.github/FUNDING.yml +0 -12
  81. package/.mailmap +0 -1
  82. package/AUTHORS.txt +0 -6
  83. package/types/Digits.ts +0 -13
  84. package/types/Time.ts +0 -52
package/dist/core.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @oipage/corejs v1.0.0
2
+ * @oipage/core.js v1.1.0-alpha.0
3
3
  * git+https://github.com/oi-contrib/oipage-corejs.git
4
4
  */
5
5
  (function (global, factory) {
@@ -8,220 +8,2721 @@
8
8
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.corejs = {}));
9
9
  })(this, (function (exports) { 'use strict';
10
10
 
11
- /*!
12
- * format of OIPage v1.4.1
13
- * git+https://github.com/oi-contrib/OIPage.git
14
- */
15
-
16
- function numberFormat(input) {
17
- if (!input && input !== 0) {
18
- return '';
19
- } else {
20
- input = input + "";
21
-
22
- var decimalValue, integerValue;
23
-
24
- var dotIndex = input.indexOf('.');
25
- if (dotIndex == -1) {
26
- decimalValue = ".00";
27
- integerValue = input;
28
- } else {
29
- var temp = input.split(".");
30
- decimalValue = "." + (temp[1] + "0").substring(0, 2);
31
- integerValue = temp[0];
32
- }
33
-
34
- var integerArray = [];
35
- for (var index = integerValue.length; index > 0; index -= 3) {
36
- integerArray.unshift(integerValue.substring(index > 2 ? index - 3 : 0, index));
37
- }
38
-
39
- return integerArray.join(",") + decimalValue;
40
- }
41
- }
42
-
43
- function dateFormat(input, option) {
44
- option = option || option;
45
- var dateObj;
46
-
47
- // 如果无值,就用当前日期
48
- if (!input) {
49
- dateObj = new Date();
50
- }
51
-
52
- // 日期对象
53
- else if (typeof input == 'object' && input.constructor === Date) {
54
- dateObj = input;
55
- }
56
-
57
- // 否则就尝试创建日期对象
58
- else if (!option.inputFormat) {
59
- dateObj = new Date(input);
60
- if (dateObj + "" == "Invalid Date") {
61
- console.error("非法的日期格式:" + input, dateObj);
62
- return "";
63
- }
64
- }
65
-
66
- // 年、月、日、时、分、秒
67
- var single = {
68
- yyyy: 0, MM: 0, dd: 0, HH: 0, mm: 0, ss: 0
69
- };
70
-
71
- // 如果获取了日期实例
72
- if (dateObj) {
73
-
74
- single.yyyy = dateObj.getFullYear();
75
- single.MM = dateObj.getMonth() + 1;
76
- single.dd = dateObj.getDate();
77
-
78
- single.HH = dateObj.getHours();
79
- single.mm = dateObj.getMinutes();
80
- single.ss = dateObj.getSeconds();
81
- }
82
-
83
- // 否则只能借助 inputFormat 来解析
84
- else {
85
- var inputFormat = option.inputFormat + "", valIndex = 0;
86
- for (var index = 0; index < inputFormat.length; index++) {
87
-
88
- // 年
89
- if (inputFormat.substring(index, index + 4) == "yyyy") {
90
- single.yyyy = +input.substring(valIndex, valIndex + 4);
91
-
92
- valIndex += 4;
93
- index += 3;
94
- } else {
95
- var curFlag = inputFormat.substring(index, index + 2);
96
- if (["MM", "dd", "HH", "mm", "ss"].indexOf(curFlag) > -1) {
97
- var valContent = input[valIndex];
98
- if (/\d/.test(input[valIndex + 1])) {
99
- valContent += input[valIndex + 1];
100
- valIndex += 2;
101
- } else {
102
- valIndex += 1;
103
- }
104
-
105
- (single)[curFlag] = +valContent;
106
- index += 1;
107
- } else {
108
- valIndex += 1;
109
- }
110
- }
111
- }
112
- }
113
-
114
- if (single.MM < 10) single.MM = "0" + single.MM;
115
- if (single.dd < 10) single.dd = "0" + single.dd;
116
- if (single.HH < 10) single.HH = "0" + single.HH;
117
- if (single.mm < 10) single.mm = "0" + single.mm;
118
- if (single.ss < 10) single.ss = "0" + single.ss;
119
-
120
- var format = option.format || "yyyy/MM/dd";
121
- return format.replace("yyyy", single.yyyy).replace("MM", single.MM).replace("dd", single.dd).replace("HH", single.HH).replace("mm", single.mm).replace("ss", single.ss);
122
- }
123
-
124
- function is(value, type) {
125
- return Object.prototype.toString.call(value) === '[object ' + type + ']'
126
- }
127
-
128
- // 计算某月多少天
129
- let calcMonthDays = function (year, month) {
130
-
131
- if (month == 2) {
132
-
133
- if ((year % 4 != 0) || (year % 100 == 0 && year % 400 != 0)) {
134
- return 28
135
- } else {
136
- return 29
137
- }
138
-
139
- } else {
140
- return [31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]
141
- }
142
-
11
+ /**
12
+ * 日期相关的纯函数工具
13
+ * 内部使用,不对外导出
14
+ */
15
+
16
+ // 常见的日期格式片段(按最长优先匹配)
17
+ const TOKENS = ["yyyy", "MM", "dd", "HH", "mm", "ss", "yy", "M", "d"];
18
+
19
+ const GROUP_PATTERN = {
20
+ yyyy: "(\\d{4})",
21
+ yy: "(\\d{2})",
22
+ MM: "(\\d{1,2})",
23
+ M: "(\\d{1,2})",
24
+ dd: "(\\d{1,2})",
25
+ d: "(\\d{1,2})",
26
+ HH: "(\\d{1,2})",
27
+ mm: "(\\d{1,2})",
28
+ ss: "(\\d{1,2})"
29
+ };
30
+
31
+ function pad2$1(value) {
32
+ return value < 10 ? "0" + value : "" + value
33
+ }
34
+
35
+ function isLeapYear(year) {
36
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
37
+ }
38
+
39
+ // 某年某月有多少天
40
+ function daysInMonth(year, month) {
41
+ return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]
42
+ }
43
+
44
+ /**
45
+ * 按 format 把年月日格式化为字符串
46
+ * 支持 yyyy、yy、MM、M、dd、d、HH、mm、ss,其中时间部分固定输出 00
47
+ */
48
+ function formatDate(year, month, day, format) {
49
+ return String(format).replace(/yyyy|MM|dd|HH|mm|ss|yy|M|d/g, function (token) {
50
+ switch (token) {
51
+ case "yyyy": return "" + year
52
+ case "yy": return pad2$1(year % 100)
53
+ case "MM": return pad2$1(month)
54
+ case "M": return "" + month
55
+ case "dd": return pad2$1(day)
56
+ case "d": return "" + day
57
+ default: return "00" // HH、mm、ss
58
+ }
59
+ })
60
+ }
61
+
62
+ /**
63
+ * 按 format 解析日期字符串
64
+ * 格式中的非 token 字符按“任意一个非数字字符”处理,因此可以不区分分隔符
65
+ * 解析失败会抛出错误,不接受兜底到“今天”
66
+ */
67
+ function parseDate(input, format) {
68
+ let source = "";
69
+ let tokens = [];
70
+ let index = 0;
71
+
72
+ while (index < format.length) {
73
+ let matched = null;
74
+ for (let i = 0; i < TOKENS.length; i++) {
75
+ if (format.substring(index, index + TOKENS[i].length) === TOKENS[i]) {
76
+ matched = TOKENS[i];
77
+ break
78
+ }
79
+ }
80
+
81
+ if (matched) {
82
+ source += GROUP_PATTERN[matched];
83
+ tokens.push(matched);
84
+ index += matched.length;
85
+ } else {
86
+ source += "[^0-9]?";
87
+ index += 1;
88
+ }
89
+ }
90
+
91
+ let result = new RegExp("^" + source).exec(String(input).trim());
92
+ if (!result) {
93
+ throw new TypeError("无法按格式 " + format + " 解析日期:" + input)
94
+ }
95
+
96
+ let year = null, month = null, day = null;
97
+ for (let i = 0; i < tokens.length; i++) {
98
+ let value = +result[i + 1];
99
+ switch (tokens[i]) {
100
+ case "yyyy": year = value; break
101
+ case "yy": year = value <= 49 ? 2000 + value : 1900 + value; break
102
+ case "MM": case "M": month = value; break
103
+ case "dd": case "d": day = value; break
104
+ }
105
+ }
106
+
107
+ if (year === null || month === null || day === null) {
108
+ throw new TypeError("格式 " + format + " 中缺少年、月、日:" + input)
109
+ }
110
+
111
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
112
+ throw new TypeError("非法的日期:" + input)
113
+ }
114
+
115
+ return { year: year, month: month, day: day }
116
+ }
117
+
118
+ /**
119
+ * 用 setFullYear 构造本地时间零点,避免 new Date(年, ...) 把 0-99 年映射成 1900+
120
+ */
121
+ function toLocalDate(year, month, day) {
122
+ let date = new Date(2000, 0, 1, 0, 0, 0, 0);
123
+ date.setFullYear(year, month - 1, day);
124
+ return date
125
+ }
126
+
127
+ // 是否合法的年月日组合
128
+ function isValidDate(year, month, day) {
129
+ return typeof year === "number" && isFinite(year) && year === Math.floor(year)
130
+ && typeof month === "number" && month === Math.floor(month) && month >= 1 && month <= 12
131
+ && typeof day === "number" && day === Math.floor(day) && day >= 1
132
+ && day <= daysInMonth(year, month)
133
+ }
134
+
135
+ /**
136
+ * 基础类型判断
137
+ * 内部使用的工具函数,不对外导出
138
+ */
139
+ const toString = Object.prototype.toString;
140
+
141
+ function is(value, type) {
142
+ return toString.call(value) === "[object " + type + "]"
143
+ }
144
+
145
+ function isInteger$1(value) {
146
+ return typeof value === "number" && isFinite(value) && Math.floor(value) === value
147
+ }
148
+
149
+ function isDate(value) {
150
+ return is(value, "Date")
151
+ }
152
+
153
+ function isRegExp(value) {
154
+ return is(value, "RegExp")
155
+ }
156
+
157
+ function isMap(value) {
158
+ return is(value, "Map")
159
+ }
160
+
161
+ function isSet(value) {
162
+ return is(value, "Set")
163
+ }
164
+
165
+ function isArrayBuffer(value) {
166
+ return is(value, "ArrayBuffer")
167
+ }
168
+
169
+ const objectToString = Function.prototype.toString.call(Object);
170
+
171
+ function isPlainObject(value) {
172
+ if (!is(value, "Object")) return false
173
+
174
+ let proto = Object.getPrototypeOf(value);
175
+ if (proto === null) return true
176
+
177
+ // 跨 realm(iframe、另一个 window、vm 沙箱)时 proto 不是当前 realm 的 Object.prototype,
178
+ // 改为比较原型上 constructor 的源码,避免把外来普通对象误判成类实例
179
+ let ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
180
+ return typeof ctor === "function" && Function.prototype.toString.call(ctor) === objectToString
181
+ }
182
+
183
+ function isNil(value) {
184
+ return value === null || value === undefined
185
+ }
186
+
187
+ /**
188
+ * Time 字段与转换
189
+ */
190
+
191
+ function useFields(Time) {
192
+ /**
193
+ * 当前维护的日期是否仍然合法(直接修改 year/month/day 后可能非法)
194
+ */
195
+ Time.prototype.isValid = function () {
196
+ return isValidDate(this.year, this.month, this.day)
197
+ };
198
+
199
+ /**
200
+ * 复制一个内容相同、格式相同的新对象
201
+ */
202
+ Time.prototype.clone = function () {
203
+ return new Time(this.getTime(), {
204
+ input: this.inputFormat,
205
+ output: this.outputFormat
206
+ })
207
+ };
208
+
209
+ /**
210
+ * 本地时间零点对应的时间戳
211
+ */
212
+ Time.prototype.getTime = function () {
213
+ return toLocalDate(this.year, this.month, this.day).getTime()
214
+ };
215
+
216
+ /**
217
+ * 转成可以直接使用的 Date 对象(本地时间零点)
218
+ */
219
+ Time.prototype.toDate = function () {
220
+ return toLocalDate(this.year, this.month, this.day)
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Time 格式化输出
226
+ */
227
+
228
+ function useFormat$1(Time) {
229
+ /**
230
+ * 按指定格式返回当前维护的日期,不传时用 outputFormat
231
+ */
232
+ Time.prototype.format = function (format) {
233
+ return formatDate(this.year, this.month, this.day, format || this.outputFormat)
234
+ };
235
+
236
+ /**
237
+ * 按照 outputFormat 格式返回当前维护的日期
238
+ */
239
+ Time.prototype.valueOf = function () {
240
+ return this.format()
241
+ };
242
+
243
+ Time.prototype.toString = function () {
244
+ return this.format()
245
+ };
246
+
247
+ Time.prototype.toJSON = function () {
248
+ return this.format()
249
+ };
250
+ }
251
+
252
+ /**
253
+ * Time 日期加减
254
+ */
255
+
256
+ function useArithmetic(Time) {
257
+ /**
258
+ * 新增 year 年(负数即减少),闰日会自动夹取到当月最后一天
259
+ */
260
+ Time.prototype.addYear = function (year) {
261
+ if (!isInteger$1(year)) throw new TypeError("addYear 需要整数,收到:" + year)
262
+ this.year += year;
263
+
264
+ let totalDay = daysInMonth(this.year, this.month);
265
+ if (totalDay < this.day) this.day = totalDay;
266
+
267
+ return this
268
+ };
269
+
270
+ /**
271
+ * 新增 month 月(负数即减少),月末日期会自动夹取到当月最后一天
272
+ */
273
+ Time.prototype.addMonth = function (month) {
274
+ if (!isInteger$1(month)) throw new TypeError("addMonth 需要整数,收到:" + month)
275
+
276
+ let total = (this.year * 12 + this.month - 1) + month;
277
+ this.year = Math.floor(total / 12);
278
+ this.month = total - this.year * 12 + 1;
279
+
280
+ let totalDay = daysInMonth(this.year, this.month);
281
+ if (totalDay < this.day) this.day = totalDay;
282
+
283
+ return this
284
+ };
285
+
286
+ /**
287
+ * 新增 day 天(负数即减少)
288
+ * 使用本地日历做加减,跨月、跨年、跨夏令时都安全
289
+ */
290
+ Time.prototype.addDay = function (day) {
291
+ if (!isInteger$1(day)) throw new TypeError("addDay 需要整数,收到:" + day)
292
+
293
+ let dateObj = this.toDate();
294
+ dateObj.setDate(dateObj.getDate() + day);
295
+
296
+ this.year = dateObj.getFullYear();
297
+ this.month = dateObj.getMonth() + 1;
298
+ this.day = dateObj.getDate();
299
+
300
+ return this
301
+ };
302
+
303
+ /**
304
+ * 新增 week 周(负数即减少)
305
+ */
306
+ Time.prototype.addWeek = function (week) {
307
+ if (!isInteger$1(week)) throw new TypeError("addWeek 需要整数,收到:" + week)
308
+ return this.addDay(week * 7)
309
+ };
310
+ }
311
+
312
+ /**
313
+ * Time 内部工具
314
+ */
315
+
316
+ function utcStamp(year, month, day) {
317
+ let date = new Date(0);
318
+ date.setUTCFullYear(year, month - 1, day);
319
+ date.setUTCHours(0, 0, 0, 0);
320
+ return date.getTime()
321
+ }
322
+
323
+ function toTime(Time, value, inputFormat) {
324
+ if (value instanceof Time) return value
325
+ if (isDate(value) || typeof value === "number") return new Time(value)
326
+ if (typeof value === "string") {
327
+ return new Time(value, inputFormat ? { input: inputFormat, output: inputFormat } : undefined)
328
+ }
329
+ throw new TypeError("无法转换为 Time 的参数:" + value)
330
+ }
331
+
332
+ /**
333
+ * Time 比较
334
+ */
335
+
336
+ function useCompare$1(Time) {
337
+ /**
338
+ * 与另一个日期相差的天数(this 比 other 晚则为正数)
339
+ */
340
+ Time.prototype.diffDays = function (other) {
341
+ let target = toTime(Time, other, this.inputFormat);
342
+ let selfStamp = utcStamp(this.year, this.month, this.day);
343
+ let targetStamp = utcStamp(target.year, target.month, target.day);
344
+ return Math.round((selfStamp - targetStamp) / 86400000)
345
+ };
346
+
347
+ Time.prototype.isBefore = function (other) {
348
+ return this.diffDays(other) < 0
349
+ };
350
+
351
+ Time.prototype.isAfter = function (other) {
352
+ return this.diffDays(other) > 0
353
+ };
354
+
355
+ Time.prototype.isSame = function (other) {
356
+ return this.diffDays(other) === 0
357
+ };
358
+ }
359
+
360
+ /**
361
+ * Time 月历信息
362
+ */
363
+
364
+ function useCalendar(Time) {
365
+ /**
366
+ * 把日期调整到当月第一天
367
+ */
368
+ Time.prototype.startOfMonth = function () {
369
+ this.day = 1;
370
+ return this
371
+ };
372
+
373
+ /**
374
+ * 把日期调整到当月最后一天
375
+ */
376
+ Time.prototype.endOfMonth = function () {
377
+ this.day = daysInMonth(this.year, this.month);
378
+ return this
379
+ };
380
+
381
+ /**
382
+ * 星期几:0 表示周日,1-6 表示周一至周六
383
+ */
384
+ Time.prototype.getWeekDay = function () {
385
+ return this.toDate().getDay()
386
+ };
387
+
388
+ Time.prototype.isLeapYear = function () {
389
+ return isLeapYear(this.year)
390
+ };
391
+
392
+ Time.prototype.daysInMonth = function () {
393
+ return daysInMonth(this.year, this.month)
394
+ };
395
+ }
396
+
397
+ /**
398
+ * 日期对象:只维护年、月、日
399
+ *
400
+ * @param {string|Date|number} date 日期,可以是字符串、Date 对象或时间戳,默认今天
401
+ * @param {object} format 格式配置
402
+ * @param {string} format.input 字符串输入格式,默认 yyyy/MM/dd
403
+ * @param {string} format.output 输出格式,默认 yyyy/MM/dd
404
+ */
405
+ function Time(date, format) {
406
+ format = format || {};
407
+
408
+ Object.defineProperty(this, "inputFormat", {
409
+ value: format.input || "yyyy/MM/dd",
410
+ writable: true,
411
+ enumerable: false
412
+ });
413
+ Object.defineProperty(this, "outputFormat", {
414
+ value: format.output || "yyyy/MM/dd",
415
+ writable: true,
416
+ enumerable: false
417
+ });
418
+
419
+ let year, month, day;
420
+
421
+ // 空值兜底为今天
422
+ if (date === undefined || date === null || date === "") {
423
+ let now = new Date();
424
+ year = now.getFullYear();
425
+ month = now.getMonth() + 1;
426
+ day = now.getDate();
427
+ }
428
+
429
+ // 字符串
430
+ else if (typeof date === "string") {
431
+ let temp = parseDate(date, this.inputFormat);
432
+ year = temp.year;
433
+ month = temp.month;
434
+ day = temp.day;
435
+ }
436
+
437
+ // 时间戳
438
+ else if (typeof date === "number") {
439
+ if (!isFinite(date)) throw new TypeError("非法的日期时间戳:" + date)
440
+ let dateObj = new Date(date);
441
+ year = dateObj.getFullYear();
442
+ month = dateObj.getMonth() + 1;
443
+ day = dateObj.getDate();
444
+ }
445
+
446
+ // Date 对象
447
+ else if (isDate(date)) {
448
+ if (isNaN(date.getTime())) throw new TypeError("非法的 Date 对象")
449
+ year = date.getFullYear();
450
+ month = date.getMonth() + 1;
451
+ day = date.getDate();
452
+ }
453
+
454
+ else {
455
+ throw new TypeError("Time 只接受字符串、Date 对象或时间戳,收到:" + date)
456
+ }
457
+
458
+ if (!isValidDate(year, month, day)) {
459
+ throw new TypeError("非法的日期:" + date)
460
+ }
461
+
462
+ this.year = year;
463
+ this.month = month;
464
+ this.day = day;
465
+ }
466
+
467
+ useFields(Time);
468
+ useFormat$1(Time);
469
+ useArithmetic(Time);
470
+ useCompare$1(Time);
471
+ useCalendar(Time);
472
+
473
+ /**
474
+ * 今天
475
+ */
476
+ Time.today = function (format) {
477
+ return new Time(undefined, format)
478
+ };
479
+
480
+ /**
481
+ * 按指定格式解析日期字符串
482
+ */
483
+ Time.parse = function (input, format) {
484
+ return new Time(input, { input: format, output: format })
485
+ };
486
+
487
+ /**
488
+ * 十进制高精度运算引擎
489
+ *
490
+ * 内部用 BigInt 保存“整数部分 + 小数位数”({ big, scale },实际值 = big / 10^scale),
491
+ * 全部运算都在整数域完成,不经过浮点,避免 0.1 + 0.2 这类精度问题。
492
+ * 注意:这里一律用 BigInt() 构造而不是 10n 字面量,保证产物不需要提高语法目标。
493
+ */
494
+
495
+ // 部分旧引擎(老版本小程序基础库、iOS 14 以下 Safari)没有 BigInt,
496
+ // 这里不能在模块加载期就调用 BigInt(),否则整个包都会 import 失败
497
+ const HAS_BIGINT = typeof BigInt === "function";
498
+ const TEN = HAS_BIGINT ? BigInt(10) : 10;
499
+ const ZERO = HAS_BIGINT ? BigInt(0) : 0;
500
+ const TWO = HAS_BIGINT ? BigInt(2) : 2;
501
+
502
+ const NUMBER_RE = /^([+-]?)(\d+)?(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
503
+
504
+ const ROUNDINGS = ["half-up", "half-even", "ceil", "floor", "trunc"];
505
+
506
+ function pow10(n) {
507
+ let result = BigInt(1);
508
+ for (let i = 0; i < n; i++) result = result * TEN;
509
+ return result
510
+ }
511
+
512
+ function abs(value) {
513
+ return value < ZERO ? -value : value
514
+ }
515
+
516
+ // 去掉小数末尾多余的 0
517
+ function normalize(big, scale) {
518
+ while (scale > 0 && big % TEN === ZERO) {
519
+ big = big / TEN;
520
+ scale -= 1;
521
+ }
522
+ return { big: big, scale: scale }
523
+ }
524
+
525
+ function checkRounding(rounding) {
526
+ if (ROUNDINGS.indexOf(rounding) === -1) {
527
+ throw new TypeError("不支持的舍入模式:" + rounding + ",可选 " + ROUNDINGS.join("、"))
528
+ }
529
+ return rounding
530
+ }
531
+
532
+ /**
533
+ * 把任意数字形态转成内部十进制表示
534
+ * 支持 number、string(可带千分位和小数)、bigint、以及内部表示
535
+ */
536
+ function toDecimal(value) {
537
+ if (!HAS_BIGINT) {
538
+ throw new TypeError("当前运行环境不支持 BigInt,Digits 无法使用:请升级小程序基础库 / iOS 14+ / Node 10.4+")
539
+ }
540
+
541
+ if (value && typeof value === "object" && typeof value.big === "bigint") {
542
+ return value
543
+ }
544
+
545
+ if (typeof value === "bigint") {
546
+ return { big: value, scale: 0 }
547
+ }
548
+
549
+ let str;
550
+ if (typeof value === "number") {
551
+ if (!isFinite(value)) throw new TypeError("不是合法的数字:" + value)
552
+ str = String(value);
553
+ } else if (typeof value === "string") {
554
+ str = value.trim().replace(/,/g, "");
555
+ } else {
556
+ throw new TypeError("不是合法的数字:" + value)
557
+ }
558
+
559
+ let matched = NUMBER_RE.exec(str);
560
+ if (!matched || (!matched[2] && !matched[3])) {
561
+ throw new TypeError("不是合法的数字:" + value)
562
+ }
563
+
564
+ let negative = matched[1] === "-";
565
+ let integerPart = matched[2] || "";
566
+ let decimalPart = matched[3] || "";
567
+ let exponent = matched[4] ? parseInt(matched[4], 10) : 0;
568
+
569
+ let digits = integerPart + decimalPart;
570
+ let scale = decimalPart.length - exponent;
571
+
572
+ if (scale < 0) {
573
+ digits += "0".repeat(-scale);
574
+ scale = 0;
575
+ }
576
+
577
+ digits = digits.replace(/^0+(?=\d)/, "");
578
+
579
+ let big = BigInt(digits);
580
+ if (negative) big = -big;
581
+
582
+ return normalize(big, scale)
583
+ }
584
+
585
+ // 内部十进制表示转字符串(精确值,不丢精度)
586
+ function toStr(decimal) {
587
+ let negative = decimal.big < ZERO;
588
+ let digits = (negative ? -decimal.big : decimal.big).toString();
589
+ let scale = decimal.scale;
590
+
591
+ if (scale === 0) return (negative ? "-" : "") + digits
592
+
593
+ if (digits.length <= scale) {
594
+ digits = "0".repeat(scale - digits.length + 1) + digits;
595
+ }
596
+
597
+ let cut = digits.length - scale;
598
+ return (negative ? "-" : "") + digits.substring(0, cut) + "." + digits.substring(cut)
599
+ }
600
+
601
+ function toNumber(decimal) {
602
+ return Number(toStr(decimal))
603
+ }
604
+
605
+ function compare(a, b) {
606
+ a = toDecimal(a);
607
+ b = toDecimal(b);
608
+
609
+ let maxScale = Math.max(a.scale, b.scale);
610
+ let left = a.big * pow10(maxScale - a.scale);
611
+ let right = b.big * pow10(maxScale - b.scale);
612
+
613
+ return left === right ? 0 : (left > right ? 1 : -1)
614
+ }
615
+
616
+ function add(a, b) {
617
+ a = toDecimal(a);
618
+ b = toDecimal(b);
619
+
620
+ let maxScale = Math.max(a.scale, b.scale);
621
+ let left = a.big * pow10(maxScale - a.scale);
622
+ let right = b.big * pow10(maxScale - b.scale);
623
+
624
+ return normalize(left + right, maxScale)
625
+ }
626
+
627
+ function subtract(a, b) {
628
+ a = toDecimal(a);
629
+ b = toDecimal(b);
630
+
631
+ let maxScale = Math.max(a.scale, b.scale);
632
+ let left = a.big * pow10(maxScale - a.scale);
633
+ let right = b.big * pow10(maxScale - b.scale);
634
+
635
+ return normalize(left - right, maxScale)
636
+ }
637
+
638
+ function multiply(a, b) {
639
+ a = toDecimal(a);
640
+ b = toDecimal(b);
641
+
642
+ return normalize(a.big * b.big, a.scale + b.scale)
643
+ }
644
+
645
+ /**
646
+ * 在“已截断的商 q 和余数 r”上按指定模式进位,q、denominator 都是非负的绝对值
647
+ */
648
+ function roundQuotient(q, r, denominator, negative, rounding) {
649
+ if (r === ZERO) return q
650
+
651
+ let doubled = r * TWO;
652
+
653
+ switch (rounding) {
654
+ case "half-up":
655
+ if (doubled >= denominator) q += BigInt(1);
656
+ break
657
+ case "half-even":
658
+ if (doubled > denominator || (doubled === denominator && q % TWO !== ZERO)) q += BigInt(1);
659
+ break
660
+ case "ceil":
661
+ if (!negative) q += BigInt(1);
662
+ break
663
+ case "floor":
664
+ if (negative) q += BigInt(1);
665
+ break
666
+ }
667
+
668
+ return q
669
+ }
670
+
671
+ function divide(a, b, scale, rounding) {
672
+ a = toDecimal(a);
673
+ b = toDecimal(b);
674
+
675
+ if (b.big === ZERO) throw new RangeError("除数不能为0")
676
+
677
+ scale = scale === undefined ? 16 : scale;
678
+ rounding = checkRounding(rounding || "half-up");
679
+
680
+ let negative = (a.big < ZERO) !== (b.big < ZERO);
681
+
682
+ let left = abs(a.big) * pow10(b.scale + scale);
683
+ let right = abs(b.big) * pow10(a.scale);
684
+
685
+ let q = left / right;
686
+ let r = left % right;
687
+
688
+ q = roundQuotient(q, r, right, negative, rounding);
689
+
690
+ return normalize(negative ? -q : q, scale)
691
+ }
692
+
693
+ /**
694
+ * 把十进制表示按 scale 位小数舍入
695
+ */
696
+ function round(decimal, scale, rounding) {
697
+ decimal = toDecimal(decimal);
698
+ scale = scale === undefined ? 0 : scale;
699
+ rounding = checkRounding(rounding || "half-up");
700
+
701
+ if (scale < 0) throw new RangeError("scale 不能为负数:" + scale)
702
+
703
+ if (decimal.scale <= scale) {
704
+ return { big: decimal.big * pow10(scale - decimal.scale), scale: scale }
705
+ }
706
+
707
+ let negative = decimal.big < ZERO;
708
+ let drop = pow10(decimal.scale - scale);
709
+
710
+ let q = abs(decimal.big) / drop;
711
+ let r = abs(decimal.big) % drop;
712
+
713
+ q = roundQuotient(q, r, drop, negative, rounding);
714
+
715
+ return normalize(negative ? -q : q, scale)
716
+ }
717
+
718
+ /**
719
+ * Digits 内部工具
720
+ */
721
+
722
+ function fixedString(decimal, scale) {
723
+ let str = toStr(decimal);
724
+ let dotIndex = str.indexOf(".");
725
+
726
+ if (dotIndex === -1) {
727
+ return scale === 0 ? str : str + "." + "0".repeat(scale)
728
+ }
729
+
730
+ let current = str.length - dotIndex - 1;
731
+ if (current >= scale) return str
732
+
733
+ return str + "0".repeat(scale - current)
734
+ }
735
+
736
+ function thousands(str) {
737
+ let negative = str.charAt(0) === "-";
738
+ let body = negative ? str.substring(1) : str;
739
+ let dotIndex = body.indexOf(".");
740
+
741
+ let integerPart = dotIndex === -1 ? body : body.substring(0, dotIndex);
742
+ let decimalPart = dotIndex === -1 ? "" : body.substring(dotIndex);
743
+
744
+ return (negative ? "-" : "") + integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + decimalPart
745
+ }
746
+
747
+ /**
748
+ * Digits 格式化输出
749
+ */
750
+
751
+ function useFormat(Digits) {
752
+ /**
753
+ * 返回格式化后的数字,默认保留 2 位小数、四舍五入、带千分位
754
+ *
755
+ * @param {number} scale 小数位数,默认 2
756
+ * @param {object} options
757
+ * @param {string} options.rounding 舍入模式:half-up、half-even、ceil、floor、trunc,默认 half-up
758
+ * @param {boolean} options.thousands 是否加千分位,默认 true
759
+ */
760
+ Digits.prototype.format = function (scale, options) {
761
+ scale = scale === undefined ? 2 : scale;
762
+ options = options || {};
763
+
764
+ let rounded = round(this._decimal, scale, options.rounding || "half-up");
765
+ let str = fixedString(rounded, scale);
766
+
767
+ return options.thousands === false ? str : thousands(str)
768
+ };
769
+
770
+ /**
771
+ * 当前值的精确字符串表示(不受浮点精度影响)
772
+ */
773
+ Digits.prototype.toString = function () {
774
+ return toStr(this._decimal)
775
+ };
776
+
777
+ Digits.prototype.valueOf = function () {
778
+ return this.value
779
+ };
780
+
781
+ Digits.prototype.toJSON = function () {
782
+ return this.value
783
+ };
784
+
785
+ /**
786
+ * 取当前值(等价于 digits.value)
787
+ */
788
+ Digits.prototype.getValue = function () {
789
+ return this.value
790
+ };
791
+
792
+ /**
793
+ * 返回保留 scale 位小数的字符串
794
+ */
795
+ Digits.prototype.toFixed = function (scale, rounding) {
796
+ scale = scale === undefined ? 2 : scale;
797
+ return fixedString(round(this._decimal, scale, rounding), scale)
798
+ };
799
+ }
800
+
801
+ /**
802
+ * Digits 运算
803
+ */
804
+
805
+ function useMath(Digits) {
806
+ /**
807
+ * 高精度加法
808
+ */
809
+ Digits.prototype.add = function (value) {
810
+ this._decimal = add(this._decimal, value);
811
+ return this
812
+ };
813
+
814
+ /**
815
+ * 高精度减法
816
+ */
817
+ Digits.prototype.subtract = function (value) {
818
+ this._decimal = subtract(this._decimal, value);
819
+ return this
820
+ };
821
+
822
+ /**
823
+ * 高精度乘法
824
+ */
825
+ Digits.prototype.multiply = function (value) {
826
+ this._decimal = multiply(this._decimal, value);
827
+ return this
828
+ };
829
+
830
+ /**
831
+ * 高精度除法
832
+ *
833
+ * @param {number|string} value 除数,为 0 时抛错
834
+ * @param {object} options
835
+ * @param {number} options.scale 结果保留的小数位,默认 16
836
+ * @param {string} options.rounding 舍入模式,默认 half-up
837
+ */
838
+ Digits.prototype.divide = function (value, options) {
839
+ options = options || {};
840
+ this._decimal = divide(
841
+ this._decimal,
842
+ value,
843
+ options.scale === undefined ? 16 : options.scale,
844
+ options.rounding
845
+ );
846
+ return this
847
+ };
848
+
849
+ /**
850
+ * 就地四舍五入到 scale 位小数
851
+ */
852
+ Digits.prototype.round = function (scale, rounding) {
853
+ this._decimal = round(this._decimal, scale, rounding);
854
+ return this
855
+ };
856
+
857
+ /**
858
+ * 取绝对值
859
+ */
860
+ Digits.prototype.abs = function () {
861
+ if (this._decimal.big < BigInt(0)) {
862
+ this._decimal = { big: -this._decimal.big, scale: this._decimal.scale };
863
+ }
864
+ return this
865
+ };
866
+
867
+ /**
868
+ * 取相反数
869
+ */
870
+ Digits.prototype.negate = function () {
871
+ this._decimal = { big: -this._decimal.big, scale: this._decimal.scale };
872
+ return this
873
+ };
874
+ }
875
+
876
+ /**
877
+ * Digits 比较
878
+ */
879
+
880
+ function useCompare(Digits) {
881
+ /**
882
+ * 比较大小:大于返回 1,相等返回 0,小于返回 -1
883
+ */
884
+ Digits.prototype.compare = function (value) {
885
+ return compare(this._decimal, value)
886
+ };
887
+
888
+ Digits.prototype.eq = function (value) {
889
+ return this.compare(value) === 0
890
+ };
891
+
892
+ Digits.prototype.gt = function (value) {
893
+ return this.compare(value) > 0
894
+ };
895
+
896
+ Digits.prototype.gte = function (value) {
897
+ return this.compare(value) >= 0
898
+ };
899
+
900
+ Digits.prototype.lt = function (value) {
901
+ return this.compare(value) < 0
902
+ };
903
+
904
+ Digits.prototype.lte = function (value) {
905
+ return this.compare(value) <= 0
906
+ };
907
+ }
908
+
909
+ /**
910
+ * 数字对象:内部用 BigInt 定点表示,加减乘除都不经过浮点
911
+ *
912
+ * @param {number|string} value 初始值,默认 0
913
+ */
914
+ function Digits(value = 0) {
915
+
916
+ Object.defineProperty(this, "_decimal", {
917
+ value: toDecimal(value),
918
+ writable: true,
919
+ enumerable: false
920
+ });
921
+
922
+ Object.defineProperty(this, "value", {
923
+ enumerable: true,
924
+ get: function () {
925
+ return toNumber(this._decimal)
926
+ },
927
+ set: function (value) {
928
+ this._decimal = toDecimal(value);
929
+ }
930
+ });
931
+ }
932
+
933
+ useFormat(Digits);
934
+ useMath(Digits);
935
+ useCompare(Digits);
936
+
937
+ /**
938
+ * String 宽度与字符
939
+ */
940
+
941
+ const WIDE_RE = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6]/;
942
+
943
+ function toChars(str) {
944
+ return Array.from(String(str))
945
+ }
946
+
947
+ /**
948
+ * 单个字符的显示宽度:中文等宽字符算 2,其余算 1
949
+ */
950
+ function widthOf(char) {
951
+ return WIDE_RE.test(char) ? 2 : 1
952
+ }
953
+
954
+ /**
955
+ * 字符串的显示宽度
956
+ */
957
+ function width(str) {
958
+ let total = 0;
959
+ toChars(str).forEach(function (char) {
960
+ total += widthOf(char);
961
+ });
962
+ return total
963
+ }
964
+
965
+ /**
966
+ * String 命名与反转
967
+ */
968
+
969
+ /**
970
+ * 转为小驼峰:foo-bar、foo_bar、foo bar 都转成 fooBar
971
+ */
972
+ function camelCase(str) {
973
+ let words = String(str).split(/[\s\-_./]+/).filter(Boolean);
974
+ return words.map(function (word, index) {
975
+ let lower = word.toLowerCase();
976
+ if (index === 0) return lower
977
+ return lower.charAt(0).toUpperCase() + lower.substring(1)
978
+ }).join("")
979
+ }
980
+
981
+ /**
982
+ * 转为短横线命名:fooBar 转成 foo-bar
983
+ */
984
+ function kebabCase(str) {
985
+ return String(str)
986
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
987
+ .replace(/[\s_./]+/g, "-")
988
+ .replace(/-+/g, "-")
989
+ .replace(/^-|-$/g, "")
990
+ .toLowerCase()
991
+ }
992
+
993
+ /**
994
+ * 反向字符串(按 Unicode 码位切分,不会拆坏 emoji 等代理对)
995
+ */
996
+ function reverse(str) {
997
+ return toChars(str).reverse().join("")
998
+ }
999
+
1000
+ /**
1001
+ * String HTML 转义
1002
+ */
1003
+
1004
+ const ESCAPE_MAP = {
1005
+ "&": "&amp;",
1006
+ "<": "&lt;",
1007
+ ">": "&gt;",
1008
+ '"': "&quot;",
1009
+ "'": "&#39;"
1010
+ };
1011
+
1012
+ const UNESCAPE_MAP = {
1013
+ "&amp;": "&",
1014
+ "&lt;": "<",
1015
+ "&gt;": ">",
1016
+ "&quot;": '"',
1017
+ "&#39;": "'",
1018
+ "&#x27;": "'"
1019
+ };
1020
+
1021
+ /**
1022
+ * 转义 HTML 特殊字符,用于把用户输入拼进页面
1023
+ */
1024
+ function escapeHTML(str) {
1025
+ return String(str).replace(/[&<>"']/g, function (char) {
1026
+ return ESCAPE_MAP[char]
1027
+ })
1028
+ }
1029
+
1030
+ /**
1031
+ * 还原 HTML 实体
1032
+ */
1033
+ function unescapeHTML(str) {
1034
+ return String(str).replace(/&(amp|lt|gt|quot|#39|#x27);/g, function (entity) {
1035
+ return UNESCAPE_MAP[entity] || entity
1036
+ })
1037
+ }
1038
+
1039
+ // 用命名空间对象导出,避免在本文件内遮蔽原生 String
1040
+
1041
+ /**
1042
+ * String 脱敏
1043
+ */
1044
+
1045
+ /**
1046
+ * 按 head/tail 保留首尾,中间用 char 替代
1047
+ */
1048
+ function maskMiddle(str, head, tail, char) {
1049
+ char = char === undefined ? "*" : String(char);
1050
+ let chars = toChars(str);
1051
+ head = Math.max(0, head || 0);
1052
+ tail = Math.max(0, tail || 0);
1053
+
1054
+ if (chars.length <= head + tail) {
1055
+ return char.repeat(chars.length)
1056
+ }
1057
+
1058
+ return chars.slice(0, head).join("")
1059
+ + char.repeat(chars.length - head - tail)
1060
+ + chars.slice(chars.length - tail).join("")
1061
+ }
1062
+
1063
+ /**
1064
+ * 常用脱敏
1065
+ *
1066
+ * @param {string} type mobile、idcard、bankcard、email、name,或 custom
1067
+ * @param {object} option custom 时的配置:head、tail、char
1068
+ */
1069
+ function mask(str, type, option) {
1070
+ str = String(str === undefined || str === null ? "" : str);
1071
+ if (!str) return ""
1072
+
1073
+ option = option || {};
1074
+ let char = option.char || "*";
1075
+
1076
+ switch (type) {
1077
+ case "mobile":
1078
+ return maskMiddle(str, 3, 4, char)
1079
+
1080
+ case "idcard":
1081
+ return maskMiddle(str, 6, 4, char)
1082
+
1083
+ case "bankcard": {
1084
+ let last = toChars(str).slice(-4).join("");
1085
+ let groups = [];
1086
+ for (let i = 0; i < 3; i++) groups.push(char.repeat(4));
1087
+ return groups.join(" ") + " " + last
1088
+ }
1089
+
1090
+ case "email": {
1091
+ let atIndex = str.indexOf("@");
1092
+ if (atIndex <= 0) return maskMiddle(str, 2, 2, char)
1093
+ let local = str.substring(0, atIndex);
1094
+ let host = str.substring(atIndex);
1095
+ if (local.length <= 2) return char.repeat(local.length) + host
1096
+ return local.substring(0, 2) + char.repeat(3) + host
1097
+ }
1098
+
1099
+ case "name": {
1100
+ let chars = toChars(str);
1101
+ if (chars.length === 1) return char
1102
+ if (chars.length === 2) return chars[0] + char
1103
+ return chars[0] + char.repeat(chars.length - 2) + chars[chars.length - 1]
1104
+ }
1105
+
1106
+ default:
1107
+ return maskMiddle(str, option.head || 0, option.tail || 0, char)
1108
+ }
1109
+ }
1110
+
1111
+ /**
1112
+ * String 补位
1113
+ */
1114
+
1115
+ /**
1116
+ * 补齐到指定显示宽度
1117
+ *
1118
+ * @param {string} position 补在左边用 "start",补在右边用 "end",默认 "end"
1119
+ */
1120
+ function pad(str, length, char, position) {
1121
+ str = String(str);
1122
+ char = char === undefined ? " " : String(char);
1123
+ let current = width(str);
1124
+ if (current >= length) return str
1125
+
1126
+ let fill = "";
1127
+ while (current + width(fill) + width(char) <= length) {
1128
+ fill += char;
1129
+ }
1130
+
1131
+ return position === "start" ? fill + str : str + fill
1132
+ }
1133
+
1134
+ /**
1135
+ * String 去空白
1136
+ */
1137
+
1138
+ /**
1139
+ * 去掉首尾空白,包含全角空格与不换行空格
1140
+ */
1141
+ function trim(str) {
1142
+ return String(str).replace(/^[\s\u00A0\u3000]+|[\s\u00A0\u3000]+$/g, "")
1143
+ }
1144
+
1145
+ /**
1146
+ * String 截断
1147
+ */
1148
+
1149
+ /**
1150
+ * 按字符数截断,超出部分用 suffix 替代
1151
+ */
1152
+ function truncate(str, maxLength, suffix) {
1153
+ suffix = suffix === undefined ? "..." : suffix;
1154
+ let chars = toChars(str);
1155
+ if (chars.length <= maxLength) return String(str)
1156
+ return chars.slice(0, Math.max(0, maxLength - Array.from(String(suffix)).length)).join("") + suffix
1157
+ }
1158
+
1159
+ /**
1160
+ * 按显示宽度截断(中文按 2 个宽度),超出部分用 suffix 替代
1161
+ */
1162
+ function cutByWidth(str, maxWidth, suffix) {
1163
+ suffix = suffix === undefined ? "..." : suffix;
1164
+ let suffixWidth = width(suffix);
1165
+ if (width(str) <= maxWidth) return String(str)
1166
+
1167
+ let total = 0;
1168
+ let result = [];
1169
+ let chars = toChars(str);
1170
+
1171
+ for (let i = 0; i < chars.length; i++) {
1172
+ let current = widthOf(chars[i]);
1173
+ if (total + current > maxWidth - suffixWidth) break
1174
+ total += current;
1175
+ result.push(chars[i]);
1176
+ }
1177
+
1178
+ return result.join("") + suffix
1179
+ }
1180
+
1181
+ /**
1182
+ * String 对外入口
1183
+ */
1184
+
1185
+ const StringUtil = {
1186
+ trim: trim,
1187
+ width: width,
1188
+ widthOf: widthOf,
1189
+ truncate: truncate,
1190
+ cutByWidth: cutByWidth,
1191
+ pad: pad,
1192
+ camelCase: camelCase,
1193
+ kebabCase: kebabCase,
1194
+ reverse: reverse,
1195
+ mask: mask,
1196
+ maskMiddle: maskMiddle,
1197
+ escapeHTML: escapeHTML,
1198
+ unescapeHTML: unescapeHTML
1199
+ };
1200
+
1201
+ /**
1202
+ * Validate 联系方式
1203
+ */
1204
+
1205
+ /**
1206
+ * 中国大陆手机号(含 13-19 号段)
1207
+ */
1208
+ function isMobile(value) {
1209
+ return /^1[3-9]\d{9}$/.test(String(value))
1210
+ }
1211
+
1212
+ function isEmail(value) {
1213
+ return /^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$/.test(String(value))
1214
+ }
1215
+
1216
+ /**
1217
+ * Validate 证件与银行卡
1218
+ */
1219
+
1220
+ /**
1221
+ * 身份证号:15 位或 18 位,会校验出生日期与末位校验码
1222
+ */
1223
+ function isIdCard(value) {
1224
+ let str = String(value);
1225
+
1226
+ if (!/^\d{15}$/.test(str) && !/^\d{17}[\dXx]$/.test(str)) return false
1227
+
1228
+ let year, month, day;
1229
+ if (str.length === 15) {
1230
+ year = 1900 + (+str.substring(6, 8));
1231
+ month = +str.substring(8, 10);
1232
+ day = +str.substring(10, 12);
1233
+ } else {
1234
+ year = +str.substring(6, 10);
1235
+ month = +str.substring(10, 12);
1236
+ day = +str.substring(12, 14);
1237
+ }
1238
+
1239
+ if (!isValidDate(year, month, day)) return false
1240
+ if (str.length === 15) return true
1241
+
1242
+ let weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
1243
+ let codes = "10X98765432";
1244
+ let total = 0;
1245
+
1246
+ for (let i = 0; i < 17; i++) {
1247
+ total += (+str.charAt(i)) * weights[i];
1248
+ }
1249
+
1250
+ return codes.charAt(total % 11) === str.charAt(17).toUpperCase()
1251
+ }
1252
+
1253
+ /**
1254
+ * 银行卡号:12-19 位数字,且通过 Luhn 校验
1255
+ */
1256
+ function isBankCard(value) {
1257
+ let str = String(value).replace(/\s/g, "");
1258
+ if (!/^\d{12,19}$/.test(str)) return false
1259
+
1260
+ let total = 0;
1261
+ for (let i = 0; i < str.length; i++) {
1262
+ let digit = +str.charAt(str.length - 1 - i);
1263
+ if (i % 2 === 1) {
1264
+ digit *= 2;
1265
+ if (digit > 9) digit -= 9;
1266
+ }
1267
+ total += digit;
1268
+ }
1269
+
1270
+ return total % 10 === 0
1271
+ }
1272
+
1273
+ /**
1274
+ * Validate 网络地址
1275
+ */
1276
+
1277
+ function isUrl(value) {
1278
+ return /^((https?|ftp):\/\/)([\w-]+\.)*[\w-]+(:\d+)?(\/[\w\-./?%&=#+~:@!$'()*,;]*)?$/.test(String(value))
1279
+ }
1280
+
1281
+ /**
1282
+ * IPv4,要求每一段都在 0-255 之间
1283
+ */
1284
+ function isIPv4(value) {
1285
+ let parts = String(value).split(".");
1286
+ if (parts.length !== 4) return false
1287
+
1288
+ for (let i = 0; i < parts.length; i++) {
1289
+ if (!/^\d{1,3}$/.test(parts[i])) return false
1290
+ if (+parts[i] > 255) return false
1291
+ }
1292
+
1293
+ return true
1294
+ }
1295
+
1296
+ function isHexGroups(list) {
1297
+ return list.every(function (group) {
1298
+ return /^[0-9a-fA-F]{1,4}$/.test(group)
1299
+ })
1300
+ }
1301
+
1302
+ function isIPv6(value) {
1303
+ let str = String(value);
1304
+ if (!str) return false
1305
+
1306
+ let index = str.indexOf("::");
1307
+
1308
+ // 完整写法:8 组
1309
+ if (index === -1) {
1310
+ let groups = str.split(":");
1311
+ return groups.length === 8 && isHexGroups(groups)
1312
+ }
1313
+
1314
+ // 压缩写法只允许出现一次 ::
1315
+ if (str.indexOf("::", index + 2) !== -1) return false
1316
+
1317
+ let left = str.substring(0, index);
1318
+ let right = str.substring(index + 2);
1319
+
1320
+ let leftGroups = left ? left.split(":") : [];
1321
+ let rightGroups = right ? right.split(":") : [];
1322
+
1323
+ // :: 至少代表一组,因此两侧合计不能超过 7 组
1324
+ if (leftGroups.length + rightGroups.length > 7) return false
1325
+
1326
+ return isHexGroups(leftGroups) && isHexGroups(rightGroups)
1327
+ }
1328
+
1329
+ function isIp(value) {
1330
+ return isIPv4(value) || isIPv6(value)
1331
+ }
1332
+
1333
+ /**
1334
+ * Validate 数字与文本
1335
+ */
1336
+
1337
+ function isInteger(value) {
1338
+ if (typeof value === "number") {
1339
+ return isFinite(value) && Math.floor(value) === value
1340
+ }
1341
+ return /^[+-]?\d+$/.test(String(value).trim())
1342
+ }
1343
+
1344
+ /**
1345
+ * 小数(允许负号,不接受科学计数法)
1346
+ */
1347
+ function isDecimal(value) {
1348
+ return /^[+-]?(\d+\.?\d*|\.\d+)$/.test(String(value))
1349
+ }
1350
+
1351
+ function isChinese(value) {
1352
+ return /^[\u4E00-\u9FA5]+$/.test(String(value))
1353
+ }
1354
+
1355
+ /**
1356
+ * 中国大陆邮编
1357
+ */
1358
+ function isPostCode(value) {
1359
+ return /^[1-9]\d{5}$/.test(String(value))
1360
+ }
1361
+
1362
+ /**
1363
+ * Validate 对外入口
1364
+ */
1365
+
1366
+ const Valid = {
1367
+ isMobile: isMobile,
1368
+ isEmail: isEmail,
1369
+ isIdCard: isIdCard,
1370
+ isUrl: isUrl,
1371
+ isIPv4: isIPv4,
1372
+ isIPv6: isIPv6,
1373
+ isIp: isIp,
1374
+ isBankCard: isBankCard,
1375
+ isInteger: isInteger,
1376
+ isDecimal: isDecimal,
1377
+ isChinese: isChinese,
1378
+ isPostCode: isPostCode
1379
+ };
1380
+
1381
+ /**
1382
+ * Object 判空
1383
+ */
1384
+
1385
+ /**
1386
+ * 是否为空:null、undefined、空字符串、空数组、空 Map/Set、无键对象都算空
1387
+ */
1388
+ function isEmpty(value) {
1389
+ if (isNil(value)) return true
1390
+ if (typeof value === "string" || Array.isArray(value)) return value.length === 0
1391
+ if (isMap(value) || isSet(value)) return value.size === 0
1392
+ if (isPlainObject(value)) return Object.keys(value).length === 0
1393
+ return false
1394
+ }
1395
+
1396
+ /**
1397
+ * Object 路径读写
1398
+ */
1399
+
1400
+ /**
1401
+ * 把 a.b[0].c 这类路径转成键名数组
1402
+ */
1403
+ function toPath(path) {
1404
+ if (Array.isArray(path)) return path.map(String)
1405
+
1406
+ return String(path)
1407
+ .replace(/\[(?:"([^"]*)"|'([^']*)'|(\d+)|(\w+))\]/g, function (matched, dq, sq, index, word) {
1408
+ return "." + (dq || sq || index || word)
1409
+ })
1410
+ .split(".")
1411
+ .filter(function (key) {
1412
+ return key !== ""
1413
+ })
1414
+ }
1415
+
1416
+ /**
1417
+ * 按路径读取,路径不存在时返回 defaultValue
1418
+ */
1419
+ function get(target, path, defaultValue) {
1420
+ let keys = toPath(path);
1421
+ let current = target;
1422
+
1423
+ for (let i = 0; i < keys.length; i++) {
1424
+ if (isNil(current)) return defaultValue
1425
+ current = current[keys[i]];
1426
+ }
1427
+
1428
+ return current === undefined ? defaultValue : current
1429
+ }
1430
+
1431
+ /**
1432
+ * 按路径写入,路径中间不存在时自动创建对象或数组
1433
+ */
1434
+ function set(target, path, value) {
1435
+ if (typeof target !== "object" || target === null) {
1436
+ throw new TypeError("set 的目标必须是对象或数组")
1437
+ }
1438
+
1439
+ let keys = toPath(path);
1440
+ let current = target;
1441
+
1442
+ for (let i = 0; i < keys.length - 1; i++) {
1443
+ let key = keys[i];
1444
+ if (typeof current[key] !== "object" || current[key] === null) {
1445
+ current[key] = /^\d+$/.test(keys[i + 1]) ? [] : {};
1446
+ }
1447
+ current = current[key];
1448
+ }
1449
+
1450
+ current[keys[keys.length - 1]] = value;
1451
+ return target
1452
+ }
1453
+
1454
+ /**
1455
+ * Object 深拷贝
1456
+ */
1457
+
1458
+ /**
1459
+ * 深拷贝,支持 Date、RegExp、Map、Set、ArrayBuffer、普通对象与数组,能处理循环引用
1460
+ * 其它类型(如 DOM 节点、类实例)按引用返回
1461
+ */
1462
+ function deepClone(value, seen) {
1463
+ if (typeof value !== "object" || value === null) return value
1464
+
1465
+ seen = seen || new WeakMap();
1466
+ if (seen.has(value)) return seen.get(value)
1467
+
1468
+ if (isDate(value)) return new Date(value.getTime())
1469
+
1470
+ if (isRegExp(value)) {
1471
+ let reg = new RegExp(value.source, value.flags);
1472
+ reg.lastIndex = value.lastIndex;
1473
+ return reg
1474
+ }
1475
+
1476
+ if (isArrayBuffer(value)) return value.slice(0)
1477
+
1478
+ let result;
1479
+
1480
+ if (isMap(value)) {
1481
+ result = new Map();
1482
+ seen.set(value, result);
1483
+ value.forEach(function (item, key) {
1484
+ result.set(deepClone(key, seen), deepClone(item, seen));
1485
+ });
1486
+ return result
1487
+ }
1488
+
1489
+ if (isSet(value)) {
1490
+ result = new Set();
1491
+ seen.set(value, result);
1492
+ value.forEach(function (item) {
1493
+ result.add(deepClone(item, seen));
1494
+ });
1495
+ return result
1496
+ }
1497
+
1498
+ if (Array.isArray(value)) {
1499
+ result = [];
1500
+ seen.set(value, result);
1501
+ for (let i = 0; i < value.length; i++) {
1502
+ result[i] = deepClone(value[i], seen);
1503
+ }
1504
+ return result
1505
+ }
1506
+
1507
+ if (isPlainObject(value)) {
1508
+ result = Object.create(Object.getPrototypeOf(value));
1509
+ seen.set(value, result);
1510
+ Object.keys(value).forEach(function (key) {
1511
+ result[key] = deepClone(value[key], seen);
1512
+ });
1513
+ return result
1514
+ }
1515
+
1516
+ return value
1517
+ }
1518
+
1519
+ /**
1520
+ * Object 深比较
1521
+ */
1522
+
1523
+ function compareValue$1(a, b, pairs) {
1524
+ if (Object.is(a, b)) return true
1525
+
1526
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false
1527
+
1528
+ for (let i = 0; i < pairs.length; i++) {
1529
+ if (pairs[i][0] === a && pairs[i][1] === b) return true
1530
+ }
1531
+ pairs.push([a, b]);
1532
+
1533
+ if (isDate(a) || isDate(b)) {
1534
+ return isDate(a) && isDate(b) && a.getTime() === b.getTime()
1535
+ }
1536
+
1537
+ if (isRegExp(a) || isRegExp(b)) {
1538
+ return isRegExp(a) && isRegExp(b) && a.toString() === b.toString()
1539
+ }
1540
+
1541
+ if (isMap(a) || isMap(b)) {
1542
+ if (!isMap(a) || !isMap(b) || a.size !== b.size) return false
1543
+ let result = true;
1544
+ a.forEach(function (value, key) {
1545
+ if (!b.has(key) || !compareValue$1(value, b.get(key), pairs)) result = false;
1546
+ });
1547
+ return result
1548
+ }
1549
+
1550
+ if (isSet(a) || isSet(b)) {
1551
+ if (!isSet(a) || !isSet(b) || a.size !== b.size) return false
1552
+ let result = true;
1553
+ a.forEach(function (value) {
1554
+ if (!b.has(value)) result = false;
1555
+ });
1556
+ return result
1557
+ }
1558
+
1559
+ if (Array.isArray(a) !== Array.isArray(b)) return false
1560
+
1561
+ let keysA = Object.keys(a);
1562
+ let keysB = Object.keys(b);
1563
+
1564
+ if (keysA.length !== keysB.length) return false
1565
+
1566
+ for (let i = 0; i < keysA.length; i++) {
1567
+ if (!Object.prototype.hasOwnProperty.call(b, keysA[i])) return false
1568
+ if (!compareValue$1(a[keysA[i]], b[keysA[i]], pairs)) return false
1569
+ }
1570
+
1571
+ return true
1572
+ }
1573
+
1574
+ /**
1575
+ * 深比较
1576
+ */
1577
+ function equal(a, b) {
1578
+ return compareValue$1(a, b, [])
1579
+ }
1580
+
1581
+ /**
1582
+ * Object 深合并
1583
+ */
1584
+
1585
+ function mergeTwo(target, source, options) {
1586
+ Object.keys(source).forEach(function (key) {
1587
+ let sourceValue = source[key];
1588
+ let targetValue = target[key];
1589
+
1590
+ if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
1591
+ target[key] = mergeTwo(deepClone(targetValue), sourceValue, options);
1592
+ } else if (Array.isArray(sourceValue) && Array.isArray(targetValue) && options.array === "concat") {
1593
+ target[key] = targetValue.concat(deepClone(sourceValue));
1594
+ } else {
1595
+ target[key] = deepClone(sourceValue);
1596
+ }
1597
+ });
1598
+
1599
+ return target
1600
+ }
1601
+
1602
+ /**
1603
+ * 深合并,返回合并后的新对象
1604
+ *
1605
+ * @param {object} target 目标对象
1606
+ * @param {object} source 来源对象
1607
+ * @param {object} options
1608
+ * @param {string} options.array 数组合并策略:replace(默认)或 concat
1609
+ */
1610
+ function deepMerge(target, source, options) {
1611
+ options = options || {};
1612
+ return mergeTwo(deepClone(target === undefined ? {} : target), source || {}, options)
1613
+ }
1614
+
1615
+ /**
1616
+ * Object 字段筛选
1617
+ */
1618
+
1619
+ /**
1620
+ * 只保留指定键
1621
+ */
1622
+ function pick(target, keys) {
1623
+ keys = Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments, 1);
1624
+ let result = {};
1625
+
1626
+ keys.forEach(function (key) {
1627
+ if (target !== null && target !== undefined && key in Object(target)) {
1628
+ result[key] = target[key];
1629
+ }
1630
+ });
1631
+
1632
+ return result
1633
+ }
1634
+
1635
+ /**
1636
+ * 排除指定键
1637
+ */
1638
+ function omit(target, keys) {
1639
+ keys = Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments, 1);
1640
+ let result = {};
1641
+ let excluded = keys.map(String);
1642
+
1643
+ Object.keys(Object(target)).forEach(function (key) {
1644
+ if (excluded.indexOf(key) === -1) result[key] = target[key];
1645
+ });
1646
+
1647
+ return result
1648
+ }
1649
+
1650
+ /**
1651
+ * Object 对外入口
1652
+ */
1653
+
1654
+ const ObjectUtil = {
1655
+ deepClone: deepClone,
1656
+ deepMerge: deepMerge,
1657
+ get: get,
1658
+ set: set,
1659
+ toPath: toPath,
1660
+ pick: pick,
1661
+ omit: omit,
1662
+ isEmpty: isEmpty,
1663
+ isPlainObject: isPlainObject,
1664
+ equal: equal
1665
+ };
1666
+
1667
+ /**
1668
+ * Array 内部工具
1669
+ */
1670
+
1671
+ /**
1672
+ * Array:数组处理
1673
+ * 全部返回新数组,不修改入参
1674
+ */
1675
+
1676
+ function toIteratee(iteratee) {
1677
+ if (typeof iteratee === "function") return iteratee
1678
+ if (typeof iteratee === "string" || typeof iteratee === "number") {
1679
+ return function (item) {
1680
+ return item === null || item === undefined ? undefined : item[iteratee]
1681
+ }
1682
+ }
1683
+ return function (item) {
1684
+ return item
1685
+ }
1686
+ }
1687
+
1688
+ /**
1689
+ * Array 分组
1690
+ */
1691
+
1692
+ /**
1693
+ * 分组,返回以分组键为属性的普通对象
1694
+ */
1695
+ function groupBy(list, iteratee) {
1696
+ let fn = toIteratee(iteratee);
1697
+ let result = {};
1698
+
1699
+ list.forEach(function (item) {
1700
+ let key = fn(item);
1701
+ if (!Object.prototype.hasOwnProperty.call(result, key)) result[key] = [];
1702
+ result[key].push(item);
1703
+ });
1704
+
1705
+ return result
1706
+ }
1707
+
1708
+ function normalizeKey(key) {
1709
+ if (typeof key === "function") return { fn: key, desc: false }
1710
+
1711
+ if (Array.isArray(key)) {
1712
+ return { fn: toIteratee(key[0]), desc: String(key[1]).toLowerCase() === "desc" }
1713
+ }
1714
+
1715
+ let str = String(key);
1716
+ if (str.charAt(0) === "-") {
1717
+ return { fn: toIteratee(str.substring(1)), desc: true }
1718
+ }
1719
+
1720
+ return { fn: toIteratee(str), desc: false }
1721
+ }
1722
+
1723
+ /**
1724
+ * Array 结构处理
1725
+ */
1726
+
1727
+ /**
1728
+ * 拍平数组
1729
+ *
1730
+ * @param {number} depth 拍平深度,默认 Infinity
1731
+ */
1732
+ function flatten(list, depth) {
1733
+ depth = depth === undefined ? Infinity : depth;
1734
+
1735
+ let result = [];
1736
+ list.forEach(function (item) {
1737
+ if (Array.isArray(item) && depth > 0) {
1738
+ result = result.concat(flatten(item, depth - 1));
1739
+ } else {
1740
+ result.push(item);
1741
+ }
1742
+ });
1743
+
1744
+ return result
1745
+ }
1746
+
1747
+ /**
1748
+ * 按长度切分
1749
+ */
1750
+ function chunk(list, size) {
1751
+ if (!(size > 0)) throw new TypeError("chunk 的 size 必须大于 0")
1752
+
1753
+ let result = [];
1754
+ for (let i = 0; i < list.length; i += size) {
1755
+ result.push(list.slice(i, i + size));
1756
+ }
1757
+
1758
+ return result
1759
+ }
1760
+
1761
+ /**
1762
+ * 去掉 falsey 值(false、0、""、null、undefined、NaN)
1763
+ */
1764
+ function compact(list) {
1765
+ return list.filter(Boolean)
1766
+ }
1767
+
1768
+ /**
1769
+ * 随机打乱(Fisher-Yates)
1770
+ */
1771
+ function shuffle(list) {
1772
+ let result = list.slice();
1773
+ for (let i = result.length - 1; i > 0; i--) {
1774
+ let index = Math.floor(Math.random() * (i + 1));
1775
+ let temp = result[i];
1776
+ result[i] = result[index];
1777
+ result[index] = temp;
1778
+ }
1779
+ return result
1780
+ }
1781
+
1782
+ /**
1783
+ * 生成数字序列,左闭右开
1784
+ */
1785
+ function range(start, end, step) {
1786
+ if (end === undefined) {
1787
+ end = start;
1788
+ start = 0;
1789
+ }
1790
+ step = step === undefined ? (start <= end ? 1 : -1) : step;
1791
+ if (step === 0) throw new TypeError("range 的 step 不能为 0")
1792
+
1793
+ let result = [];
1794
+ if (step > 0) {
1795
+ for (let i = start; i < end; i += step) result.push(i);
1796
+ } else {
1797
+ for (let i = start; i > end; i += step) result.push(i);
1798
+ }
1799
+
1800
+ return result
1801
+ }
1802
+
1803
+ /**
1804
+ * Array 排序
1805
+ */
1806
+
1807
+ function compareValue(a, b) {
1808
+ let aEmpty = a === null || a === undefined;
1809
+ let bEmpty = b === null || b === undefined;
1810
+
1811
+ if (aEmpty && bEmpty) return 0
1812
+ if (aEmpty) return 1 // 空值统一排后面
1813
+ if (bEmpty) return -1
1814
+
1815
+ if (a instanceof Date) a = a.getTime();
1816
+ if (b instanceof Date) b = b.getTime();
1817
+
1818
+ if (typeof a === "number" && typeof b === "number") return a - b
1819
+
1820
+ a = String(a);
1821
+ b = String(b);
1822
+
1823
+ return a < b ? -1 : (a > b ? 1 : 0)
1824
+ }
1825
+
1826
+ /**
1827
+ * 多字段排序,返回新数组
1828
+ *
1829
+ * @param {Array} keys 排序键,字符串("-" 前缀表示倒序)、函数,或 [键, "desc"]
1830
+ */
1831
+ function sortBy(list, keys) {
1832
+ let rules = (Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments, 1)).map(normalizeKey);
1833
+
1834
+ return list.slice().sort(function (a, b) {
1835
+ for (let i = 0; i < rules.length; i++) {
1836
+ let result = compareValue(rules[i].fn(a), rules[i].fn(b));
1837
+ if (result !== 0) return rules[i].desc ? -result : result
1838
+ }
1839
+ return 0
1840
+ })
1841
+ }
1842
+
1843
+ /**
1844
+ * Array 去重
1845
+ */
1846
+
1847
+ /**
1848
+ * 去重,使用 SameValueZero 语义(NaN 会被正确去重,对象按引用比较)
1849
+ */
1850
+ function unique(list) {
1851
+ return Array.from(new Set(list))
1852
+ }
1853
+
1854
+ /**
1855
+ * 按字段或函数去重,保留第一次出现的元素
1856
+ */
1857
+ function uniqueBy(list, iteratee) {
1858
+ let fn = toIteratee(iteratee);
1859
+ let seen = new Set();
1860
+ let result = [];
1861
+
1862
+ list.forEach(function (item) {
1863
+ let key = fn(item);
1864
+ if (!seen.has(key)) {
1865
+ seen.add(key);
1866
+ result.push(item);
1867
+ }
1868
+ });
1869
+
1870
+ return result
1871
+ }
1872
+
1873
+ /**
1874
+ * Array 对外入口
1875
+ */
1876
+
1877
+ const ArrayUtil = {
1878
+ unique: unique,
1879
+ uniqueBy: uniqueBy,
1880
+ groupBy: groupBy,
1881
+ sortBy: sortBy,
1882
+ flatten: flatten,
1883
+ chunk: chunk,
1884
+ compact: compact,
1885
+ shuffle: shuffle,
1886
+ range: range
1887
+ };
1888
+
1889
+ /**
1890
+ * Query 编解码与内部工具
1891
+ */
1892
+
1893
+ /**
1894
+ * Query:URL 查询参数与地址解析
1895
+ */
1896
+
1897
+ function decode(value) {
1898
+ let str = String(value).replace(/\+/g, " ");
1899
+ try {
1900
+ return decodeURIComponent(str)
1901
+ } catch (error) {
1902
+ return str // 非法转义时保留原样,不抛错
1903
+ }
1904
+ }
1905
+
1906
+ function encode(value) {
1907
+ return encodeURIComponent(String(value)).replace(/%5B/g, "[").replace(/%5D/g, "]")
1908
+ }
1909
+
1910
+ function buildPath(key) {
1911
+ let arrayFlag = /\[\]$/.test(key);
1912
+ let base = arrayFlag ? key.substring(0, key.length - 2) : key;
1913
+ let tokens = base.split(/\[|\]/).filter(function (token) {
1914
+ return token !== ""
1915
+ });
1916
+
1917
+ return { tokens: tokens, arrayFlag: arrayFlag }
1918
+ }
1919
+
1920
+ function assign(target, tokens, value, arrayFlag) {
1921
+ let current = target;
1922
+
1923
+ for (let i = 0; i < tokens.length - 1; i++) {
1924
+ let key = tokens[i];
1925
+ if (typeof current[key] !== "object" || current[key] === null) {
1926
+ current[key] = /^\d+$/.test(tokens[i + 1]) ? [] : {};
1927
+ }
1928
+ current = current[key];
1929
+ }
1930
+
1931
+ let last = tokens[tokens.length - 1];
1932
+
1933
+ if (arrayFlag) {
1934
+ if (!Array.isArray(current[last])) current[last] = [];
1935
+ current[last].push(value);
1936
+ return
1937
+ }
1938
+
1939
+ if (current[last] === undefined) {
1940
+ current[last] = value;
1941
+ } else if (Array.isArray(current[last])) {
1942
+ current[last].push(value);
1943
+ } else {
1944
+ current[last] = [current[last], value];
1945
+ }
1946
+ }
1947
+
1948
+ /**
1949
+ * Query 查询串解析
1950
+ */
1951
+
1952
+ /**
1953
+ * 解析查询字符串,支持 a=1&a=2、a[]=1、a[b]=1 三种写法
1954
+ *
1955
+ * @param {string} query 可以带 ? 前缀,也可以直接是完整 URL
1956
+ */
1957
+ function parseQuery(query) {
1958
+ let result = {};
1959
+ let str = String(query === undefined || query === null ? "" : query);
1960
+
1961
+ let questionIndex = str.indexOf("?");
1962
+ if (questionIndex !== -1) str = str.substring(questionIndex + 1);
1963
+
1964
+ let hashIndex = str.indexOf("#");
1965
+ if (hashIndex !== -1) str = str.substring(0, hashIndex);
1966
+
1967
+ if (!str) return result
1968
+
1969
+ str.split("&").forEach(function (pair) {
1970
+ if (!pair) return
1971
+
1972
+ let equalIndex = pair.indexOf("=");
1973
+ let rawKey = equalIndex === -1 ? pair : pair.substring(0, equalIndex);
1974
+ let rawValue = equalIndex === -1 ? "" : pair.substring(equalIndex + 1);
1975
+
1976
+ let key = decode(rawKey);
1977
+ if (!key) return
1978
+
1979
+ let path = buildPath(key);
1980
+ if (!path.tokens.length) return
1981
+
1982
+ assign(result, path.tokens, decode(rawValue), path.arrayFlag);
1983
+ });
1984
+
1985
+ return result
1986
+ }
1987
+
1988
+ /**
1989
+ * Query 查询串序列化
1990
+ */
1991
+
1992
+ /**
1993
+ * 把对象序列化成查询字符串,与 parseQuery 可逆
1994
+ */
1995
+ function stringifyQuery(target) {
1996
+ let parts = [];
1997
+
1998
+ function walk(value, key) {
1999
+ if (value === undefined) return
2000
+
2001
+ if (value === null) {
2002
+ parts.push(encode(key) + "=");
2003
+ return
2004
+ }
2005
+
2006
+ if (Array.isArray(value)) {
2007
+ value.forEach(function (item) {
2008
+ if (item !== undefined) walk(item, key);
2009
+ });
2010
+ return
2011
+ }
2012
+
2013
+ if (typeof value === "object" && !(value instanceof Date)) {
2014
+ Object.keys(value).forEach(function (childKey) {
2015
+ walk(value[childKey], key + "[" + childKey + "]");
2016
+ });
2017
+ return
2018
+ }
2019
+
2020
+ parts.push(encode(key) + "=" + encode(value));
2021
+ }
2022
+
2023
+ if (target && typeof target === "object") {
2024
+ Object.keys(target).forEach(function (key) {
2025
+ walk(target[key], key);
2026
+ });
2027
+ }
2028
+
2029
+ return parts.join("&")
2030
+ }
2031
+
2032
+ /**
2033
+ * Query URL 解析
2034
+ */
2035
+
2036
+ /**
2037
+ * 解析 URL,返回协议、主机、端口、路径、查询串、hash 与查询参数对象
2038
+ */
2039
+ function parseUrl(url) {
2040
+ let matched = /^([a-zA-Z][a-zA-Z0-9+.\-]*:)?(?:\/\/([^/?#]*))?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(String(url));
2041
+
2042
+ if (!matched) throw new TypeError("非法的 URL:" + url)
2043
+
2044
+ let protocol = matched[1] ? matched[1].substring(0, matched[1].length - 1).toLowerCase() : "";
2045
+ let authority = matched[2] || "";
2046
+
2047
+ let username = "";
2048
+ let password = "";
2049
+ let atIndex = authority.lastIndexOf("@");
2050
+ if (atIndex !== -1) {
2051
+ let userinfo = authority.substring(0, atIndex);
2052
+ authority = authority.substring(atIndex + 1);
2053
+
2054
+ let colonIndex = userinfo.indexOf(":");
2055
+ if (colonIndex === -1) {
2056
+ username = userinfo;
2057
+ } else {
2058
+ username = userinfo.substring(0, colonIndex);
2059
+ password = userinfo.substring(colonIndex + 1);
2060
+ }
2061
+ }
2062
+
2063
+ let hostname = authority;
2064
+ let port = "";
2065
+
2066
+ let portIndex = authority.lastIndexOf(":");
2067
+ if (portIndex !== -1 && portIndex > authority.lastIndexOf("]")) {
2068
+ hostname = authority.substring(0, portIndex);
2069
+ port = authority.substring(portIndex + 1);
2070
+ }
2071
+
2072
+ let query = matched[4] ? matched[4].substring(1) : "";
2073
+ let hash = matched[5] ? matched[5].substring(1) : "";
2074
+
2075
+ let result = {
2076
+ protocol: protocol,
2077
+ host: authority,
2078
+ hostname: hostname,
2079
+ port: port,
2080
+ username: username,
2081
+ password: password,
2082
+ path: matched[3] || "",
2083
+ query: query,
2084
+ hash: hash
2085
+ };
2086
+
2087
+ Object.defineProperty(result, "params", {
2088
+ value: parseQuery(query),
2089
+ enumerable: false
2090
+ });
2091
+
2092
+ return result
2093
+ }
2094
+
2095
+ /**
2096
+ * Query 对外入口
2097
+ */
2098
+
2099
+ const QueryUtil = {
2100
+ parseQuery: parseQuery,
2101
+ stringifyQuery: stringifyQuery,
2102
+ parseUrl: parseUrl
2103
+ };
2104
+
2105
+ /**
2106
+ * Id 随机源
2107
+ */
2108
+
2109
+ /**
2110
+ * Id:随机标识生成
2111
+ * 优先使用 crypto.getRandomValues,环境不支持时退回 Math.random(安全性较弱,仅适合展示类场景)
2112
+ */
2113
+
2114
+ const DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";
2115
+
2116
+ function getCrypto() {
2117
+ if (typeof globalThis !== "undefined" && globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
2118
+ return globalThis.crypto
2119
+ }
2120
+ return null
2121
+ }
2122
+
2123
+ function randomBytes(size) {
2124
+ let bytes = new Array(size);
2125
+ let cryptoObj = getCrypto();
2126
+
2127
+ if (cryptoObj) {
2128
+ let array = new Uint8Array(size);
2129
+ cryptoObj.getRandomValues(array);
2130
+ for (let i = 0; i < size; i++) bytes[i] = array[i];
2131
+ } else {
2132
+ for (let i = 0; i < size; i++) bytes[i] = Math.floor(Math.random() * 256);
2133
+ }
2134
+
2135
+ return bytes
2136
+ }
2137
+
2138
+ // 是否为加密安全随机源
2139
+
2140
+ function isSecure() {
2141
+ return getCrypto() !== null
2142
+ }
2143
+
2144
+ /**
2145
+ * Id 短 ID
2146
+ */
2147
+
2148
+ /**
2149
+ * 生成短 ID,默认 21 位、64 个字符的字母表
2150
+ */
2151
+ function nanoid(size, alphabet) {
2152
+ size = size === undefined ? 21 : size;
2153
+ alphabet = alphabet || DEFAULT_ALPHABET;
2154
+
2155
+ if (!(size > 0)) throw new TypeError("nanoid 的 size 必须大于 0")
2156
+ if (alphabet.length < 2) throw new TypeError("nanoid 的 alphabet 至少需要 2 个字符")
2157
+
2158
+ let bytes = randomBytes(size);
2159
+ let result = "";
2160
+
2161
+ for (let i = 0; i < size; i++) {
2162
+ result += alphabet.charAt(bytes[i] % alphabet.length);
2163
+ }
2164
+
2165
+ return result
2166
+ }
2167
+
2168
+ /**
2169
+ * Id 随机数与随机串
2170
+ */
2171
+
2172
+ /**
2173
+ * 生成 [min, max] 之间的随机整数(含两端)
2174
+ */
2175
+ function randomInt(min, max) {
2176
+ if (max === undefined) {
2177
+ max = min;
2178
+ min = 0;
2179
+ }
2180
+
2181
+ min = Math.ceil(min);
2182
+ max = Math.floor(max);
2183
+
2184
+ if (max < min) throw new TypeError("randomInt 的 max 不能小于 min")
2185
+
2186
+ return min + Math.floor(Math.random() * (max - min + 1))
2187
+ }
2188
+
2189
+ /**
2190
+ * 生成随机字符串
2191
+ */
2192
+ function randomString(size, alphabet) {
2193
+ size = size === undefined ? 8 : size;
2194
+ alphabet = alphabet || DEFAULT_ALPHABET;
2195
+
2196
+ if (!(size > 0)) throw new TypeError("randomString 的 size 必须大于 0")
2197
+
2198
+ let bytes = randomBytes(size);
2199
+ let result = "";
2200
+
2201
+ for (let i = 0; i < size; i++) {
2202
+ result += alphabet.charAt(bytes[i] % alphabet.length);
2203
+ }
2204
+
2205
+ return result
2206
+ }
2207
+
2208
+ /**
2209
+ * Id UUID
2210
+ */
2211
+
2212
+ /**
2213
+ * UUID v4
2214
+ */
2215
+ function uuid() {
2216
+ let bytes = randomBytes(16);
2217
+
2218
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // 版本号 4
2219
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // 变体位 10
2220
+
2221
+ let hex = bytes.map(function (byte) {
2222
+ return (byte + 0x100).toString(16).substring(1)
2223
+ }).join("");
2224
+
2225
+ return hex.substring(0, 8) + "-" + hex.substring(8, 12) + "-" + hex.substring(12, 16)
2226
+ + "-" + hex.substring(16, 20) + "-" + hex.substring(20)
2227
+ }
2228
+
2229
+ /**
2230
+ * Id 对外入口
2231
+ */
2232
+
2233
+ const IdUtil = {
2234
+ uuid: uuid,
2235
+ nanoid: nanoid,
2236
+ randomInt: randomInt,
2237
+ randomString: randomString,
2238
+ isSecure: isSecure
143
2239
  };
144
2240
 
145
- function Time(date, format = {}) {
146
- this.inputFormat = format.input || "yyyy/MM/dd";
147
- this.outputFormat = format.output || "yyyy/MM/dd";
148
-
149
- // 字符串
150
- if (date && typeof date === "string") {
151
- let temp = dateFormat(date, {
152
- inputFormat: this.inputFormat
153
- }).split("/");
154
-
155
- this.year = +temp[0];
156
- this.month = +temp[1];
157
- this.day = +temp[2];
158
- }
159
-
160
- else {
161
- // 不是Date对象
162
- if (!is(date, "Date")) date = new Date();
163
-
164
- this.year = date.getFullYear();
165
- this.month = date.getMonth() + 1;
166
- this.day = date.getDate();
167
- }
168
- }
169
-
170
- Time.prototype.valueOf = function () {
171
- return dateFormat(`${this.year}/${this.month}/${this.day}`, {
172
- format: this.outputFormat
173
- })
174
- };
175
-
176
- Time.prototype.addYear = function (year) {
177
- this.year += year;
178
- return this
179
- };
180
-
181
- Time.prototype.addMonth = function (month) {
182
- let month1 = month % 12; // 零碎的月份
183
- this.year += (month - month1) / 12; // 整齐的年份
184
-
185
- if (month1 > 0) {
186
- let month2 = 12 - this.month; // 新增月份剩余空间
187
- if (month2 >= month1) {
188
- this.month += month1;
189
- } else {
190
- this.year += 1;
191
- this.month = month1 - month2;
192
- }
193
- } else if (month1 < 0) {
194
- if (this.month + month1 > 0) {
195
- this.month += month1;
196
- } else {
197
- this.year -= 1;
198
- this.month += 12 + month1;
199
- }
200
- }
201
-
202
- let totalDay = calcMonthDays(this.year, this.month);
203
- if (totalDay < this.day) this.day = totalDay;
204
-
205
- return this
206
- };
207
-
208
- Time.prototype.addDay = function (day) {
209
- let dateObj = new Date(+new Date(`${this.year}/${this.month}/${this.day}`) + (day * 86400000)); // 86400000 = 24 * 60 * 60 * 1000
210
- this.year = dateObj.getFullYear();
211
- this.month = dateObj.getMonth() + 1;
212
- this.day = dateObj.getDate();
213
- return this
2241
+ /**
2242
+ * Color 内部工具
2243
+ */
2244
+
2245
+ /**
2246
+ * Color:颜色换算与调色
2247
+ * 输入输出统一使用 #rrggbb(必要时带 alpha),内部按 0-255 / 0-360 计算
2248
+ */
2249
+
2250
+ function clamp(value, min, max) {
2251
+ return value < min ? min : (value > max ? max : value)
2252
+ }
2253
+
2254
+ function pad2(value) {
2255
+ let str = Math.round(clamp(value, 0, 255)).toString(16);
2256
+ return str.length === 1 ? "0" + str : str
2257
+ }
2258
+
2259
+ function normalizeHex(hex) {
2260
+ let str = String(hex === undefined || hex === null ? "" : hex).trim().replace(/^#/, "");
2261
+
2262
+ if (/^[0-9a-fA-F]{3}$/.test(str)) {
2263
+ str = str.split("").map(function (char) {
2264
+ return char + char
2265
+ }).join("");
2266
+ }
2267
+
2268
+ if (/^[0-9a-fA-F]{4}$/.test(str)) {
2269
+ str = str.split("").map(function (char) {
2270
+ return char + char
2271
+ }).join("");
2272
+ }
2273
+
2274
+ if (!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(str)) {
2275
+ throw new TypeError("非法的颜色值:" + hex)
2276
+ }
2277
+
2278
+ return "#" + str.toLowerCase()
2279
+ }
2280
+
2281
+ /**
2282
+ * Color 格式互转
2283
+ */
2284
+
2285
+ /**
2286
+ * #rrggbb / #rgb / #rrggbbaa 转 { r, g, b, a }
2287
+ */
2288
+ function hex2rgb(hex) {
2289
+ let str = normalizeHex(hex).substring(1);
2290
+
2291
+ let result = {
2292
+ r: parseInt(str.substring(0, 2), 16),
2293
+ g: parseInt(str.substring(2, 4), 16),
2294
+ b: parseInt(str.substring(4, 6), 16),
2295
+ a: 1
2296
+ };
2297
+
2298
+ if (str.length === 8) {
2299
+ result.a = Math.round(parseInt(str.substring(6, 8), 16) / 255 * 100) / 100;
2300
+ }
2301
+
2302
+ return result
2303
+ }
2304
+
2305
+ /**
2306
+ * { r, g, b, a } 转 #rrggbb,alpha 小于 1 时输出 #rrggbbaa
2307
+ */
2308
+ function rgb2hex(rgb) {
2309
+ if (!rgb || typeof rgb !== "object") throw new TypeError("rgb2hex 需要一个 { r, g, b } 对象")
2310
+
2311
+ let alpha = rgb.a === undefined ? 1 : clamp(rgb.a, 0, 1);
2312
+ let hex = "#" + pad2(rgb.r) + pad2(rgb.g) + pad2(rgb.b);
2313
+
2314
+ return alpha < 1 ? hex + pad2(alpha * 255) : hex
2315
+ }
2316
+
2317
+ /**
2318
+ * { r, g, b } 转 { h, s, l }
2319
+ */
2320
+ function rgb2hsl(rgb) {
2321
+ let r = clamp(rgb.r, 0, 255) / 255;
2322
+ let g = clamp(rgb.g, 0, 255) / 255;
2323
+ let b = clamp(rgb.b, 0, 255) / 255;
2324
+
2325
+ let max = Math.max(r, g, b);
2326
+ let min = Math.min(r, g, b);
2327
+ let delta = max - min;
2328
+ let l = (max + min) / 2;
2329
+
2330
+ let h = 0;
2331
+ let s = 0;
2332
+
2333
+ if (delta !== 0) {
2334
+ s = delta / (1 - Math.abs(2 * l - 1));
2335
+
2336
+ switch (max) {
2337
+ case r: h = ((g - b) / delta) % 6; break
2338
+ case g: h = (b - r) / delta + 2; break
2339
+ default: h = (r - g) / delta + 4;
2340
+ }
2341
+
2342
+ h *= 60;
2343
+ if (h < 0) h += 360;
2344
+ }
2345
+
2346
+ return {
2347
+ h: Math.round(h * 100) / 100,
2348
+ s: Math.round(s * 10000) / 100,
2349
+ l: Math.round(l * 10000) / 100
2350
+ }
2351
+ }
2352
+
2353
+ /**
2354
+ * { h, s, l } 转 { r, g, b },h 单位是度,s/l 单位是百分比
2355
+ */
2356
+ function hsl2rgb(hsl) {
2357
+ let h = ((hsl.h % 360) + 360) % 360;
2358
+ let s = clamp(hsl.s, 0, 100) / 100;
2359
+ let l = clamp(hsl.l, 0, 100) / 100;
2360
+
2361
+ let c = (1 - Math.abs(2 * l - 1)) * s;
2362
+ let x = c * (1 - Math.abs((h / 60) % 2 - 1));
2363
+ let m = l - c / 2;
2364
+
2365
+ let rgb;
2366
+
2367
+ if (h < 60) rgb = [c, x, 0];
2368
+ else if (h < 120) rgb = [x, c, 0];
2369
+ else if (h < 180) rgb = [0, c, x];
2370
+ else if (h < 240) rgb = [0, x, c];
2371
+ else if (h < 300) rgb = [x, 0, c];
2372
+ else rgb = [c, 0, x];
2373
+
2374
+ return {
2375
+ r: Math.round((rgb[0] + m) * 255),
2376
+ g: Math.round((rgb[1] + m) * 255),
2377
+ b: Math.round((rgb[2] + m) * 255)
2378
+ }
2379
+ }
2380
+
2381
+ /**
2382
+ * Color 调色
2383
+ */
2384
+
2385
+ /**
2386
+ * 按权重混合两个颜色
2387
+ *
2388
+ * @param {number} weight 第二个颜色的权重,0-1
2389
+ */
2390
+ function mix(color1, color2, weight) {
2391
+ weight = weight === undefined ? 0.5 : clamp(weight, 0, 1);
2392
+
2393
+ let a = hex2rgb(color1);
2394
+ let b = hex2rgb(color2);
2395
+
2396
+ return rgb2hex({
2397
+ r: Math.round(a.r * (1 - weight) + b.r * weight),
2398
+ g: Math.round(a.g * (1 - weight) + b.g * weight),
2399
+ b: Math.round(a.b * (1 - weight) + b.b * weight)
2400
+ })
2401
+ }
2402
+
2403
+ /**
2404
+ * 变亮:与白色混合
2405
+ *
2406
+ * @param {number} amount 0-1
2407
+ */
2408
+ function lighten(color, amount) {
2409
+ return mix(color, "#ffffff", amount === undefined ? 0.3 : amount)
2410
+ }
2411
+
2412
+ /**
2413
+ * 变暗:与黑色混合
2414
+ *
2415
+ * @param {number} amount 0-1
2416
+ */
2417
+ function darken(color, amount) {
2418
+ return mix(color, "#000000", amount === undefined ? 0.3 : amount)
2419
+ }
2420
+
2421
+ /**
2422
+ * 根据背景色返回可读的前景色(纯黑或纯白)
2423
+ */
2424
+ function contrast(color) {
2425
+ let rgb = hex2rgb(color);
2426
+
2427
+ // W3C 相对亮度
2428
+ let channel = function (value) {
2429
+ let ratio = value / 255;
2430
+ return ratio <= 0.03928 ? ratio / 12.92 : Math.pow((ratio + 0.055) / 1.055, 2.4)
2431
+ };
2432
+
2433
+ let luminance = 0.2126 * channel(rgb.r) + 0.7152 * channel(rgb.g) + 0.0722 * channel(rgb.b);
2434
+
2435
+ return luminance > 0.5 ? "#000000" : "#ffffff"
2436
+ }
2437
+
2438
+ /**
2439
+ * 转成 rgba() 字符串
2440
+ */
2441
+ function toRgba(color, alpha) {
2442
+ let rgb = hex2rgb(color);
2443
+ alpha = alpha === undefined ? 1 : clamp(alpha, 0, 1);
2444
+ return "rgba(" + rgb.r + ", " + rgb.g + ", " + rgb.b + ", " + alpha + ")"
2445
+ }
2446
+
2447
+ /**
2448
+ * Color 对外入口
2449
+ */
2450
+
2451
+ const ColorUtil = {
2452
+ hex2rgb: hex2rgb,
2453
+ rgb2hex: rgb2hex,
2454
+ rgb2hsl: rgb2hsl,
2455
+ hsl2rgb: hsl2rgb,
2456
+ mix: mix,
2457
+ lighten: lighten,
2458
+ darken: darken,
2459
+ contrast: contrast,
2460
+ toRgba: toRgba
214
2461
  };
215
2462
 
216
- function Digits(value = 0) {
217
- this.value = value;
218
- }
219
-
220
- Digits.prototype.format = function () {
221
- return numberFormat(this.value)
2463
+ /**
2464
+ * Cache 存储驱动
2465
+ */
2466
+
2467
+ /**
2468
+ * Cache:带过期时间的键值存储
2469
+ * 默认优先用 localStorage,其次 sessionStorage,都没有(如 Node 环境)时退回内存
2470
+ */
2471
+
2472
+ function createStorageDriver(storage) {
2473
+ return {
2474
+ getItem: function (key) {
2475
+ return storage.getItem(key)
2476
+ },
2477
+ setItem: function (key, value) {
2478
+ storage.setItem(key, value);
2479
+ },
2480
+ removeItem: function (key) {
2481
+ storage.removeItem(key);
2482
+ },
2483
+ keys: function () {
2484
+ let result = [];
2485
+ for (let i = 0; i < storage.length; i++) result.push(storage.key(i));
2486
+ return result
2487
+ }
2488
+ }
2489
+ }
2490
+
2491
+ function createMemoryDriver() {
2492
+ let store = new Map();
2493
+
2494
+ return {
2495
+ getItem: function (key) {
2496
+ return store.has(key) ? store.get(key) : null
2497
+ },
2498
+ setItem: function (key, value) {
2499
+ store.set(key, value);
2500
+ },
2501
+ removeItem: function (key) {
2502
+ store.delete(key);
2503
+ },
2504
+ keys: function () {
2505
+ return Array.from(store.keys())
2506
+ }
2507
+ }
2508
+ }
2509
+
2510
+ function tryStorage(name) {
2511
+ try {
2512
+ if (typeof globalThis !== "undefined" && globalThis[name]) {
2513
+ let storage = globalThis[name];
2514
+ let probe = "__corejs_probe__";
2515
+ storage.setItem(probe, "1");
2516
+ storage.removeItem(probe);
2517
+ return createStorageDriver(storage)
2518
+ }
2519
+ } catch (error) {
2520
+ // 隐私模式等场景写入会抛错,直接降级
2521
+ }
2522
+ return null
2523
+ }
2524
+
2525
+ function resolveDriver(driver) {
2526
+ if (driver && typeof driver === "object"
2527
+ && typeof driver.getItem === "function"
2528
+ && typeof driver.setItem === "function"
2529
+ && typeof driver.removeItem === "function") {
2530
+ return driver
2531
+ }
2532
+
2533
+ if (driver === "memory") return createMemoryDriver()
2534
+
2535
+ if (driver === "local") {
2536
+ let local = tryStorage("localStorage");
2537
+ if (local) return local
2538
+ return createMemoryDriver()
2539
+ }
2540
+
2541
+ if (driver === "session") {
2542
+ let session = tryStorage("sessionStorage");
2543
+ if (session) return session
2544
+ return createMemoryDriver()
2545
+ }
2546
+
2547
+ return tryStorage("localStorage") || tryStorage("sessionStorage") || createMemoryDriver()
2548
+ }
2549
+
2550
+ /**
2551
+ * Cache 过期时间
2552
+ */
2553
+
2554
+ function toExpire(expire) {
2555
+ if (expire === undefined || expire === null || expire === 0) return 0
2556
+
2557
+ if (expire instanceof Date) {
2558
+ let stamp = expire.getTime();
2559
+ if (!isFinite(stamp)) throw new TypeError("非法的过期时间")
2560
+ return stamp
2561
+ }
2562
+
2563
+ if (typeof expire === "number") {
2564
+ if (!isFinite(expire) || expire < 0) throw new TypeError("非法的过期时间:" + expire)
2565
+ // 小于 1e11 的按“相对毫秒”处理,否则按“绝对时间戳”处理
2566
+ return expire < 100000000000 ? Date.now() + expire : expire
2567
+ }
2568
+
2569
+ throw new TypeError("非法的过期时间:" + expire)
2570
+ }
2571
+
2572
+ /**
2573
+ * Cache 读写
2574
+ */
2575
+
2576
+ function useStore(Cache) {
2577
+ /**
2578
+ * 写入缓存
2579
+ *
2580
+ * @param {string} key 键
2581
+ * @param {*} value 值,会被 JSON 序列化
2582
+ * @param {number|Date} expire 过期时间:毫秒(相对)或时间戳 / Date(绝对),不传表示不过期
2583
+ */
2584
+ Cache.prototype.set = function (key, value, expire) {
2585
+ let data = {
2586
+ v: value,
2587
+ e: toExpire(expire)
2588
+ };
2589
+
2590
+ this._driver.setItem(this._key(key), JSON.stringify(data));
2591
+ return this
2592
+ };
2593
+
2594
+ /**
2595
+ * 读取缓存,过期或不存在时返回 defaultValue
2596
+ */
2597
+ Cache.prototype.get = function (key, defaultValue) {
2598
+ let str = this._driver.getItem(this._key(key));
2599
+ if (str === null || str === undefined) return defaultValue
2600
+
2601
+ let data;
2602
+ try {
2603
+ data = JSON.parse(str);
2604
+ } catch (error) {
2605
+ this.remove(key);
2606
+ return defaultValue
2607
+ }
2608
+
2609
+ if (!data || typeof data !== "object" || !Object.prototype.hasOwnProperty.call(data, "v")) {
2610
+ this.remove(key);
2611
+ return defaultValue
2612
+ }
2613
+
2614
+ if (data.e && data.e <= Date.now()) {
2615
+ this.remove(key);
2616
+ return defaultValue
2617
+ }
2618
+
2619
+ return data.v
2620
+ };
2621
+
2622
+ Cache.prototype.has = function (key) {
2623
+ let str = this._driver.getItem(this._key(key));
2624
+ if (str === null || str === undefined) return false
2625
+
2626
+ let data;
2627
+ try {
2628
+ data = JSON.parse(str);
2629
+ } catch (error) {
2630
+ this.remove(key);
2631
+ return false
2632
+ }
2633
+
2634
+ if (!data || typeof data !== "object") {
2635
+ this.remove(key);
2636
+ return false
2637
+ }
2638
+
2639
+ if (data.e && data.e <= Date.now()) {
2640
+ this.remove(key);
2641
+ return false
2642
+ }
2643
+
2644
+ return true
2645
+ };
2646
+
2647
+ Cache.prototype.remove = function (key) {
2648
+ this._driver.removeItem(this._key(key));
2649
+ return this
2650
+ };
2651
+
2652
+ /**
2653
+ * 当前命名空间下仍然有效的键
2654
+ */
2655
+ Cache.prototype.keys = function () {
2656
+ let prefix = this.namespace + ":";
2657
+ let result = [];
2658
+
2659
+ this._driver.keys().forEach(function (fullKey) {
2660
+ if (fullKey.indexOf(prefix) === 0) result.push(fullKey.substring(prefix.length));
2661
+ });
2662
+
2663
+ let self = this;
2664
+ return result.filter(function (key) {
2665
+ return self.has(key)
2666
+ })
2667
+ };
2668
+
2669
+ Cache.prototype.size = function () {
2670
+ return this.keys().length
2671
+ };
2672
+
2673
+ /**
2674
+ * 清空当前命名空间(不会影响其它命名空间的数据)
2675
+ */
2676
+ Cache.prototype.clear = function () {
2677
+ let self = this;
2678
+ this.keys().forEach(function (key) {
2679
+ self.remove(key);
2680
+ });
2681
+ return this
2682
+ };
2683
+ }
2684
+
2685
+ /**
2686
+ * Cache:带过期时间的键值存储
2687
+ * 默认优先用 localStorage,其次 sessionStorage,都没有(如 Node 环境)时退回内存
2688
+ */
2689
+
2690
+ /**
2691
+ * @param {string} namespace 命名空间,默认 corejs
2692
+ * @param {object} options
2693
+ * @param {string|object} options.driver local、session、memory,或自定义 { getItem, setItem, removeItem }
2694
+ */
2695
+ function Cache(namespace, options) {
2696
+ if (typeof namespace === "object" && namespace !== null && options === undefined) {
2697
+ options = namespace;
2698
+ namespace = undefined;
2699
+ }
2700
+
2701
+ options = options || {};
2702
+
2703
+ this.namespace = namespace || "corejs";
2704
+
2705
+ Object.defineProperty(this, "_driver", {
2706
+ value: resolveDriver(options.driver),
2707
+ enumerable: false
2708
+ });
2709
+ }
2710
+
2711
+ Cache.prototype._key = function (key) {
2712
+ return this.namespace + ":" + key
222
2713
  };
223
2714
 
2715
+ useStore(Cache);
2716
+
2717
+ exports.Array = ArrayUtil;
2718
+ exports.Cache = Cache;
2719
+ exports.Color = ColorUtil;
224
2720
  exports.Digits = Digits;
2721
+ exports.Id = IdUtil;
2722
+ exports.Object = ObjectUtil;
2723
+ exports.Query = QueryUtil;
2724
+ exports.String = StringUtil;
225
2725
  exports.Time = Time;
2726
+ exports.Validate = Valid;
226
2727
 
227
2728
  }));