@wiajs/core 1.2.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/util/tool.js CHANGED
@@ -1,26 +1,42 @@
1
+ // 1. 安全地获取开发环境状态(兼容打包工具、浏览器和 Node.js)
2
+ // 如果 Rspack 注入了 __DEV__,就用注入的值;如果是在 Node.js 下,就回退读取 process.env.NODE_ENV
3
+ const isDev = typeof __DEV__ !== 'undefined' ? __DEV__ : process.env.NODE_ENV !== 'production'
4
+
5
+ // 全局单例复用空对象、空数组,避免重复创建,保障了开发期的内存安全、还兼顾了生产期的极致性能
6
+ /** @type {{ readonly [key: string]: any }} */
7
+ const EMPTY_OBJ = isDev ? Object.freeze({}) : {}
8
+ const EMPTY_ARR = isDev ? Object.freeze([]) : []
9
+
10
+ const NOOP = () => {}
11
+
12
+ /**
13
+ * Always return false.
14
+ */
15
+ const NO = () => false
16
+
1
17
  class StringBuf {
2
18
  constructor() {
3
- this.buf = [];
19
+ this.buf = []
4
20
  }
5
21
 
6
22
  append(str, ...args) {
7
- if (args.length > 0) this.buf.push(format(str, ...args));
23
+ if (args.length > 0) this.buf.push(format(str, ...args))
8
24
  // 参数传递
9
- else this.buf.push(String(str));
25
+ else this.buf.push(String(str))
10
26
  }
11
27
 
12
28
  insert(str, ...args) {
13
- if (args.length > 0) this.buf.unshift(format(str, ...args));
29
+ if (args.length > 0) this.buf.unshift(format(str, ...args))
14
30
  // 参数传递
15
- else this.buf.unshift(String(str));
31
+ else this.buf.unshift(String(str))
16
32
  }
17
33
 
18
34
  pop() {
19
- this.buf.pop();
35
+ this.buf.pop()
20
36
  }
21
37
 
22
38
  toString() {
23
- return this.buf.join('');
39
+ return this.buf.join('')
24
40
  }
25
41
  }
26
42
 
@@ -29,63 +45,63 @@ class StringBuf {
29
45
  * @type {Function}
30
46
  */
31
47
  function format(f, ...args) {
32
- let i = 0;
33
- const len = args.length;
48
+ let i = 0
49
+ const len = args.length
34
50
  const str = String(f).replace(/%[sdjo%]/g, x => {
35
- if (x === '%%') return '%';
36
- if (i >= len) return x;
51
+ if (x === '%%') return '%'
52
+ if (i >= len) return x
37
53
  switch (x) {
38
54
  case '%s':
39
- return String(args[i++]);
55
+ return String(args[i++])
40
56
  case '%d':
41
- return Number(args[i++]);
57
+ return Number(args[i++])
42
58
  case '%j':
43
59
  case '%o':
44
- return JSON.stringify(args[i++]);
60
+ return JSON.stringify(args[i++])
45
61
  default:
46
- return x;
62
+ return x
47
63
  }
48
- });
64
+ })
49
65
 
50
- return str;
66
+ return str
51
67
  }
52
68
 
53
69
  /**
54
70
  * 去除字符串头部空格或指定字符
55
71
  */
56
72
  function trimStart(s, c) {
57
- if (!c) return String(s).replace(/(^\s*)/g, '');
73
+ if (!c) return String(s).replace(/(^\s*)/g, '')
58
74
 
59
- const rx = new RegExp(format('^%s*', c));
60
- return String(s).replace(rx, '');
75
+ const rx = new RegExp(format('^%s*', c))
76
+ return String(s).replace(rx, '')
61
77
  }
62
78
 
63
79
  /**
64
80
  * 去除字符串尾部空格或指定字符
65
81
  */
66
82
  function trimEnd(s, c) {
67
- if (!s) return '';
83
+ if (!s) return ''
68
84
 
69
- if (!c) return String(s).replace(/(\s*$)/g, '');
85
+ if (!c) return String(s).replace(/(\s*$)/g, '')
70
86
 
71
- const rx = new RegExp(format('%s*$', c));
72
- return String(s).replace(rx, '');
87
+ const rx = new RegExp(format('%s*$', c))
88
+ return String(s).replace(rx, '')
73
89
  }
74
90
 
75
91
  function addDay(n, d) {
76
- if (!d) d = new Date();
92
+ if (!d) d = new Date()
77
93
  else if (typeof d === 'string') {
78
94
  // 兼容
79
95
  d = d
80
- .replace(/\-/g, '/')
96
+ .replace(/-/g, '/')
81
97
  .replace(/T/g, ' ')
82
- .replace(/\.+[0-9]+[A-Z]$/, '');
98
+ .replace(/\.+[0-9]+[A-Z]$/, '')
83
99
  // 还原时区,内部保存为标准时间
84
- d = new Date(d).getTime() - 3600000 * (new Date().getTimezoneOffset() / 60);
85
- d = new Date(d);
100
+ d = new Date(d).getTime() - 3600000 * (new Date().getTimezoneOffset() / 60)
101
+ d = new Date(d)
86
102
  }
87
103
 
88
- return new Date(d.getTime() + n * 36000000);
104
+ return new Date(d.getTime() + n * 36000000)
89
105
  }
90
106
 
91
107
  /**
@@ -94,19 +110,19 @@ function addDay(n, d) {
94
110
  function setTitle(val) {
95
111
  setTimeout(() => {
96
112
  // 利用iframe的onload事件刷新页面
97
- document.title = val;
113
+ document.title = val
98
114
 
99
- const fr = document.createElement('iframe');
115
+ const fr = document.createElement('iframe')
100
116
  // fr.style.visibility = 'hidden';
101
- fr.style.display = 'none';
117
+ fr.style.display = 'none'
102
118
  // fr.src = 'https://cos.nuoya.io/mall/favicon.ico';
103
119
  fr.onload = () => {
104
120
  setTimeout(() => {
105
- document.body.removeChild(fr);
106
- }, 0);
107
- };
108
- document.body.appendChild(fr);
109
- }, 0);
121
+ document.body.removeChild(fr)
122
+ }, 0)
123
+ }
124
+ document.body.appendChild(fr)
125
+ }, 0)
110
126
  }
111
127
 
112
128
  /**
@@ -114,18 +130,17 @@ function setTitle(val) {
114
130
  * @param {int} len
115
131
  */
116
132
  function newFileName(len) {
117
- const R = [];
118
- len = len || 32;
133
+ const R = []
134
+ len = len || 32
119
135
  // 键盘上的所有可见字符
120
136
  // 不包含 *?:/\<>|
121
137
  const str =
122
138
  // 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_~()';
123
- '123456789-_~()!';
124
- const size = str.length;
125
- for (let i = 0; i < len; i++) {
126
- R.push(str.charAt(Math.floor(Math.random() * size)));
127
- }
128
- return R.join('');
139
+ '123456789-_~()!'
140
+ const size = str.length
141
+ for (let i = 0; i < len; i++) R.push(str.charAt(Math.floor(Math.random() * size)))
142
+
143
+ return R.join('')
129
144
  }
130
145
 
131
146
  /**
@@ -179,15 +194,15 @@ function compareObj(k, desc, type, sub) {
179
194
  * @param {*} fn
180
195
  */
181
196
  function sortObj(obj) {
182
- const res = {};
197
+ const res = {}
183
198
 
184
199
  Object.keys(obj)
185
200
  .sort()
186
201
  .forEach(k => {
187
- res[k] = obj[k];
188
- });
202
+ res[k] = obj[k]
203
+ })
189
204
 
190
- return res;
205
+ return res
191
206
  }
192
207
 
193
208
  /**
@@ -197,7 +212,7 @@ function sortObj(obj) {
197
212
  function serObj(obj) {
198
213
  return Object.keys(obj)
199
214
  .map(k => `${k}=${obj[k]}`)
200
- .join('&');
215
+ .join('&')
201
216
  }
202
217
 
203
218
  /**
@@ -253,24 +268,25 @@ function delay(ms) {
253
268
  function promisify(f, type = 1) {
254
269
  return (...arg) =>
255
270
  new Promise((res, rej) => {
256
- if (type == null || type === 1)
271
+ if (type == null || type === 1) {
257
272
  f(...arg, (err, rs) => {
258
273
  if (err) rej(err)
259
274
  else res(rs)
260
275
  })
261
- else if (type === 0) f(...arg, rs => res(rs))
262
- else if (type === 2)
276
+ } else if (type === 0) f(...arg, rs => res(rs))
277
+ else if (type === 2) {
263
278
  f(
264
279
  ...arg,
265
280
  rs => res(rs),
266
281
  rs => rej(rs || new Error('reject'))
267
282
  )
268
- else if (type === 3)
283
+ } else if (type === 3) {
269
284
  f(
270
285
  ...arg,
271
286
  rs => res(rs),
272
287
  rs => rej(rs || new Error('reject'))
273
288
  )
289
+ }
274
290
  })
275
291
  }
276
292
 
@@ -281,9 +297,8 @@ function promisify(f, type = 1) {
281
297
  * @returns {string} 格式化后的字符串
282
298
  */
283
299
  function formatNum(num, cnt = 2) {
284
- if (typeof num !== 'number' || isNaN(num)) {
285
- return '0.00' // 如果不是数字,返回默认值
286
- }
300
+ if (typeof num !== 'number' || isNaN(num)) return '0.00' // 如果不是数字,返回默认值
301
+
287
302
  return num.toLocaleString('en-US', {
288
303
  minimumFractionDigits: cnt, // 最少保留 2 位小数
289
304
  maximumFractionDigits: cnt, // 最多保留 2 位小数
@@ -298,30 +313,18 @@ function formatNum(num, cnt = 2) {
298
313
  * false: false/0/非空对象、非空数组、值
299
314
  */
300
315
  function isEmpty(p) {
301
- if (p === undefined || p === null || p === '') {
302
- return true
303
- }
316
+ if (p === undefined || p === null || p === '') return true
304
317
 
305
- if (typeof p === 'string' && p.trim() === '') {
306
- return true
307
- }
318
+ if (typeof p === 'string' && p.trim() === '') return true
308
319
 
309
- if (Array.isArray(p) && p.length === 0) {
310
- return true
311
- }
320
+ if (Array.isArray(p) && p.length === 0) return true
312
321
 
313
- if (p instanceof Map && p.size === 0) {
314
- return true
315
- }
322
+ if (p instanceof Map && p.size === 0) return true
316
323
 
317
- if (p instanceof Set && p.size === 0) {
318
- return true
319
- }
324
+ if (p instanceof Set && p.size === 0) return true
320
325
 
321
326
  // 检查普通空对象
322
- if (typeof p === 'object' && p !== null && p.constructor === Object && Object.keys(p).length === 0) {
323
- return true
324
- }
327
+ if (typeof p === 'object' && p !== null && p.constructor === Object && Object.keys(p).length === 0) return true
325
328
 
326
329
  return false
327
330
  }
@@ -358,9 +361,7 @@ function isNumber(value) {
358
361
  function needParam(p, msg) {
359
362
  if (isEmpty(p)) throw new Err(Err.MissParam, msg)
360
363
 
361
- if (Array.isArray(p)) {
362
- if (p.some(m => isEmpty(m))) throw new Err(Err.MissParam, msg)
363
- }
364
+ if (Array.isArray(p)) if (p.some(m => isEmpty(m))) throw new Err(Err.MissParam, msg)
364
365
  }
365
366
 
366
367
  /**
@@ -415,6 +416,10 @@ async function sign(r, secret, opts = {nonce: true}) {
415
416
  }
416
417
 
417
418
  export {
419
+ EMPTY_OBJ,
420
+ EMPTY_ARR,
421
+ NOOP,
422
+ NO,
418
423
  StringBuf,
419
424
  format,
420
425
  trimStart,
@@ -425,5 +430,13 @@ export {
425
430
  sortObj,
426
431
  serObj,
427
432
  setTitle,
428
- toYuan, toFen, promisify, delay, formatNum, isNumber, isDate, needParam, sign
429
- };
433
+ toYuan,
434
+ toFen,
435
+ promisify,
436
+ delay,
437
+ formatNum,
438
+ isNumber,
439
+ isDate,
440
+ needParam,
441
+ sign,
442
+ }
package/.eslintignore DELETED
@@ -1,5 +0,0 @@
1
- src/assets
2
- dist
3
- lib
4
- log
5
- public
package/.eslintrc.js DELETED
@@ -1,121 +0,0 @@
1
- const rules = {
2
- // Disable for console/alert
3
- // 0 关闭 1 警告 2 报错 https://eslint.org/docs/rules/ 中文网址:http://eslint.cn/docs/rules/
4
- // "arrow-parens": [2, "as-needed"],
5
- 'arrow-parens': [2, 'as-needed', {requireForBlockBody: false}],
6
- 'arrow-body-style': [2, 'as-needed'],
7
- 'global-require': 0,
8
- 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
9
- 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
10
- quotes: [1, 'single'],
11
- 'no-alert': 0,
12
- 'no-trailing-spaces': 0,
13
- 'nonblock-statement-body-position': 0, // [2, "beside"], // if else 强制单行
14
- 'block-spacing': 0, // 对象空格
15
- 'function-paren-newline': 0, // 函数参数换行
16
- 'linebreak-style': 0,
17
- 'lines-between-class-members': 0,
18
- 'class-methods-use-this': 0,
19
- 'import/no-extraneous-dependencies': 0,
20
- indent: [2, 2, {SwitchCase: 1}],
21
- 'object-curly-spacing': 0,
22
- 'no-plusplus': 0,
23
- 'no-multi-spaces': 0,
24
- 'no-param-reassign': ['warn', {props: false}],
25
- 'no-use-before-define': [2, {functions: false, classes: true}],
26
- 'no-unused-expressions': ['error', {allowShortCircuit: true}],
27
- 'no-underscore-dangle': 0,
28
- 'no-unused-vars': [1, {vars: 'local', args: 'after-used'}],
29
- 'no-cond-assign': ['error', 'except-parens'],
30
- 'no-return-assign': [2, 'except-parens'],
31
- 'no-await-in-loop': 0,
32
- 'import/prefer-default-export': 0,
33
- 'operator-linebreak': 0,
34
- 'generator-star-spacing': 0,
35
- // if while function 后面的{必须与if在同一行,java风格。
36
- // "brace-style": [2, "1tbs", { "allowSingleLine": true }]
37
-
38
- // 数组和对象键值对最后一个逗号, never 参数:不能带末尾的逗号, always参数:必须带末尾的逗号,
39
- // always-multiline:多行模式必须带逗号,单行模式不能带逗号
40
- 'comma-dangle': [2, 'only-multiline'],
41
- // 控制逗号前后的空格
42
- 'comma-spacing': [2, {before: false, after: true}],
43
- // 控制逗号在行尾出现还是在行首出现
44
- // http://eslint.org/docs/rules/comma-style
45
- 'comma-style': [0, 'last'],
46
- 'max-len': [2, 120, 2],
47
- curly: [0, 'multi'], // 单行无需大括号
48
- // 强制方法必须返回值,TypeScript强类型,不配置
49
- 'consistent-return': 0,
50
- 'object-curly-newline': 0,
51
- semi: 0, // 分号检查
52
- 'space-before-function-paren': 0, // ["error", "never"]
53
- 'func-names': ['error', 'never'],
54
- };
55
-
56
- module.exports = {
57
- root: true, // 停止父目录查找配置
58
- parser: '@babel/eslint-parser', // "typescript-eslint-parser", "babel-eslint",
59
- env: {
60
- es6: true,
61
- es2017: true,
62
- es2020: true,
63
- es2021: true,
64
- browser: true, // 浏览器环境中的全局变量
65
- worker: true,
66
- node: true,
67
- commonjs: true,
68
- mongo: true,
69
- jest: true,
70
- jquery: true,
71
- },
72
- globals: {
73
- XMLHttpRequest: true,
74
- Blob: true,
75
- Document: true,
76
- FormData: true,
77
- Dom: true,
78
- $: true,
79
- document: true,
80
- window: true,
81
- },
82
- parserOptions: {
83
- ecmaVersion: 'latest',
84
- sourceType: 'module',
85
- ecmaFeatures: {
86
- jsx: true,
87
- },
88
- },
89
- plugins: [
90
- // 插件,需安装好,配置时省略 eslint-plugin-
91
- // babel,
92
- // react,
93
- ],
94
- extends: [
95
- // 继承规则 // 'airbnb', 'eslint:recommended'
96
- 'plugin:react/recommended',
97
- 'airbnb',
98
- 'plugin:prettier/recommended',
99
- 'plugin:import/recommended',
100
- ],
101
- rules: {
102
- ...rules,
103
- },
104
- overrides: [
105
- {
106
- files: ['src/**/*.js'],
107
- extends: [
108
- 'plugin:react/recommended',
109
- 'airbnb-base',
110
- 'plugin:prettier/recommended',
111
- 'plugin:import/recommended'
112
- ],
113
- plugins: ['react'],
114
- rules: {
115
- ...rules,
116
- 'react/no-unknown-property': ['off'],
117
- 'react/jsx-key': ['off'],
118
- },
119
- },
120
- ],
121
- };
package/.prettierignore DELETED
@@ -1,24 +0,0 @@
1
- .*
2
- *.ejs
3
- *.ico
4
- *.map
5
- *.png
6
- *.svg
7
- *.xml
8
-
9
- .eslintignore
10
- .eslintrc
11
- .eslintrc.js
12
- .prettierignore
13
- .prettierrc
14
- prettier.config.js
15
- wiamap.yml
16
-
17
- package.json
18
- package-lock.json
19
- yarn.lock
20
-
21
- node_modules
22
- dist
23
- doc
24
- .vscode
@@ -1,13 +0,0 @@
1
- module.exports = {
2
- tabWidth: 2, // 使用 2 个空格缩进
3
- useTabs: false, // 不使用缩进符,而使用空格
4
- semi: true, // 行尾需要有分号
5
- singleQuote: true, // 使用单引号
6
- bracketSpacing: false, // 大括号内的首尾需要空格
7
- trailingComma: 'es5', // 末尾是否需要逗号
8
- jsxBracketSameLine: true, // jsx 标签的反尖括号不换行
9
- arrowParens: 'avoid', // 尽可能省略箭头函数参数括号。 示例:x => x
10
- printWidth: 100, // 代码换行长度
11
- endOfLine: 'auto',
12
- // jsxSingleQuote: false, // jsx 使用双引号
13
- };