@anjianshi/utils 2.5.0 → 2.7.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/README.md +10 -0
- package/eslint.config.cjs +33 -0
- package/package.json +26 -15
- package/publish-prepare.cjs +16 -0
- package/src/env-browser/device.ts +62 -0
- package/src/env-browser/global.ts +21 -0
- package/src/env-browser/load-script.ts +13 -0
- package/src/env-browser/logging.ts +58 -0
- package/src/env-browser/manage-vconsole.ts +54 -0
- package/src/env-node/crypto-random.ts +30 -0
- package/src/env-node/fs.ts +50 -0
- package/src/env-node/index.ts +6 -0
- package/src/env-node/logging/handlers.ts +190 -0
- package/src/env-node/logging/index.ts +16 -0
- package/src/env-node/safe-request.ts +66 -0
- package/src/env-react/emotion.tsx +42 -0
- package/src/env-service/controllers.ts +93 -0
- package/src/env-service/env-reader.ts +141 -0
- package/src/env-service/index.ts +6 -0
- package/src/env-service/prisma/adapt-logging.ts +39 -0
- package/src/env-service/prisma/extensions/exist.ts +21 -0
- package/src/env-service/prisma/extensions/find-and-count.ts +24 -0
- package/src/env-service/prisma/extensions/soft-delete.ts +162 -0
- package/src/env-service/prisma/extensions/with-transaction.ts +65 -0
- package/src/env-service/prisma/index.ts +6 -0
- package/src/env-service/prisma/transaction-contexted.ts +80 -0
- package/src/env-service/redis-cache.ts +142 -0
- package/src/env-service/tasks.ts +45 -0
- package/src/index.ts +3 -0
- package/src/init-dayjs.ts +8 -0
- package/src/lang/async.ts +47 -0
- package/src/lang/color.ts +119 -0
- package/src/lang/index.ts +7 -0
- package/src/lang/may-success.ts +57 -0
- package/src/lang/object.ts +39 -0
- package/src/lang/random.ts +25 -0
- package/src/lang/string.ts +95 -0
- package/src/lang/time.ts +19 -0
- package/{lang/types.d.ts → src/lang/types.ts} +43 -23
- package/src/logging/adapt.ts +49 -0
- package/src/logging/formatters.ts +23 -0
- package/src/logging/index.ts +106 -0
- package/src/md5.ts +318 -0
- package/src/url.ts +185 -0
- package/src/validators/array.ts +97 -0
- package/src/validators/base.ts +145 -0
- package/src/validators/boolean.ts +21 -0
- package/src/validators/datetime.ts +39 -0
- package/src/validators/factory.ts +244 -0
- package/src/validators/index.ts +9 -0
- package/src/validators/number.ts +54 -0
- package/src/validators/object.ts +101 -0
- package/src/validators/one-of.ts +33 -0
- package/src/validators/string.ts +72 -0
- package/env-browser/device.d.ts +0 -24
- package/env-browser/device.js +0 -50
- package/env-browser/global.d.ts +0 -10
- package/env-browser/global.js +0 -15
- package/env-browser/load-script.d.ts +0 -5
- package/env-browser/load-script.js +0 -13
- package/env-browser/logging.d.ts +0 -18
- package/env-browser/logging.js +0 -49
- package/env-browser/manage-vconsole.d.ts +0 -16
- package/env-browser/manage-vconsole.js +0 -38
- package/env-node/crypto-random.d.ts +0 -13
- package/env-node/crypto-random.js +0 -28
- package/env-node/fs.d.ts +0 -19
- package/env-node/fs.js +0 -48
- package/env-node/index.d.ts +0 -5
- package/env-node/index.js +0 -5
- package/env-node/logging/handlers.d.ts +0 -58
- package/env-node/logging/handlers.js +0 -154
- package/env-node/logging/index.d.ts +0 -11
- package/env-node/logging/index.js +0 -14
- package/env-react/emotion.d.ts +0 -20
- package/env-react/emotion.jsx +0 -34
- package/env-service/controllers.d.ts +0 -30
- package/env-service/controllers.js +0 -41
- package/env-service/env-reader.d.ts +0 -55
- package/env-service/env-reader.js +0 -79
- package/env-service/index.d.ts +0 -6
- package/env-service/index.js +0 -6
- package/env-service/prisma/adapt-logging.d.ts +0 -21
- package/env-service/prisma/adapt-logging.js +0 -30
- package/env-service/prisma/extensions/exist.d.ts +0 -10
- package/env-service/prisma/extensions/exist.js +0 -16
- package/env-service/prisma/extensions/find-and-count.d.ts +0 -7
- package/env-service/prisma/extensions/find-and-count.js +0 -19
- package/env-service/prisma/extensions/soft-delete.d.ts +0 -52
- package/env-service/prisma/extensions/soft-delete.js +0 -123
- package/env-service/prisma/extensions/with-transaction.d.ts +0 -9
- package/env-service/prisma/extensions/with-transaction.js +0 -54
- package/env-service/prisma/index.d.ts +0 -6
- package/env-service/prisma/index.js +0 -6
- package/env-service/prisma/transaction-contexted.d.ts +0 -11
- package/env-service/prisma/transaction-contexted.js +0 -52
- package/env-service/redis-cache.d.ts +0 -39
- package/env-service/redis-cache.js +0 -116
- package/env-service/tasks.d.ts +0 -12
- package/env-service/tasks.js +0 -37
- package/index.d.ts +0 -3
- package/index.js +0 -3
- package/init-dayjs.d.ts +0 -2
- package/init-dayjs.js +0 -7
- package/lang/async.d.ts +0 -19
- package/lang/async.js +0 -34
- package/lang/index.d.ts +0 -7
- package/lang/index.js +0 -7
- package/lang/may-success.d.ts +0 -40
- package/lang/may-success.js +0 -27
- package/lang/object.d.ts +0 -5
- package/lang/object.js +0 -31
- package/lang/random.d.ts +0 -13
- package/lang/random.js +0 -24
- package/lang/string.d.ts +0 -29
- package/lang/string.js +0 -92
- package/lang/time.d.ts +0 -10
- package/lang/time.js +0 -18
- package/lang/types.js +0 -28
- package/logging/adapt.d.ts +0 -10
- package/logging/adapt.js +0 -43
- package/logging/formatters.d.ts +0 -10
- package/logging/formatters.js +0 -22
- package/logging/index.d.ts +0 -45
- package/logging/index.js +0 -90
- package/md5.d.ts +0 -30
- package/md5.js +0 -308
- package/url.d.ts +0 -77
- package/url.js +0 -149
- package/validators/array.d.ts +0 -30
- package/validators/array.js +0 -47
- package/validators/base.d.ts +0 -82
- package/validators/base.js +0 -42
- package/validators/boolean.d.ts +0 -3
- package/validators/boolean.js +0 -22
- package/validators/factory.d.ts +0 -66
- package/validators/factory.js +0 -109
- package/validators/index.d.ts +0 -8
- package/validators/index.js +0 -8
- package/validators/number.d.ts +0 -19
- package/validators/number.js +0 -26
- package/validators/object.d.ts +0 -28
- package/validators/object.js +0 -49
- package/validators/oneOf.d.ts +0 -10
- package/validators/oneOf.js +0 -15
- package/validators/string.d.ts +0 -22
- package/validators/string.js +0 -35
package/README.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Common JavaScript Utils
|
|
2
|
+
|
|
3
|
+
## 依赖
|
|
4
|
+
|
|
5
|
+
- `init-dayjs` 依赖 `dayjs`
|
|
6
|
+
- `/logging` 依赖 `dayjs`,且会自动引用 `init-dayjs`
|
|
7
|
+
- `/env-node/logging` 依赖 `chalk`
|
|
8
|
+
- `/env-react/emotion` 依赖 `@emotion/*` 系列类库和 `react`
|
|
9
|
+
- `/env-service/prisma` 依赖 `@prisma/client`
|
|
10
|
+
- `/env-service/env-reader` 依赖 `dotenv`
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const globals = require('@anjianshi/presets-eslint-base/globals.cjs')
|
|
2
|
+
const { limitFiles } = require('@anjianshi/presets-eslint-base/utils.cjs')
|
|
3
|
+
|
|
4
|
+
const configs = [
|
|
5
|
+
...require('@anjianshi/presets-eslint-base'),
|
|
6
|
+
...require('@anjianshi/presets-eslint-typescript'),
|
|
7
|
+
...limitFiles(
|
|
8
|
+
['*.cjs', 'src/{env-node, env-service}/'],
|
|
9
|
+
require('@anjianshi/presets-eslint-node/exclusive.cjs'),
|
|
10
|
+
),
|
|
11
|
+
...limitFiles('src/env-browser/', {
|
|
12
|
+
languageOptions: {
|
|
13
|
+
globals: { ...globals.browser },
|
|
14
|
+
},
|
|
15
|
+
}),
|
|
16
|
+
...limitFiles('src/env-react/', require('@anjianshi/presets-eslint-react/exclusive.cjs')),
|
|
17
|
+
...limitFiles('src/env-service/prisma/', {
|
|
18
|
+
rules: {
|
|
19
|
+
// prisma 相关方法需要保证返回的是 PrismaPromise 而不能是经过 async function 转过的 Promise,所以不能把函数标记为 async function
|
|
20
|
+
'@typescript-eslint/promise-function-async': 'off',
|
|
21
|
+
},
|
|
22
|
+
}),
|
|
23
|
+
...limitFiles('src/env-service/prisma/extensions/', {
|
|
24
|
+
rules: {
|
|
25
|
+
// prisma extension 需要用到 any 类型
|
|
26
|
+
'@typescript-eslint/no-explicit-any': 'off',
|
|
27
|
+
'@typescript-eslint/no-unsafe-call': 'off',
|
|
28
|
+
'@typescript-eslint/no-unsafe-member-access': 'off',
|
|
29
|
+
'@typescript-eslint/no-unsafe-assignment': 'off',
|
|
30
|
+
},
|
|
31
|
+
}),
|
|
32
|
+
]
|
|
33
|
+
module.exports = configs
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anjianshi/utils",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.7.0",
|
|
4
4
|
"description": "Common JavaScript Utils",
|
|
5
5
|
"homepage": "https://github.com/anjianshi/js-packages/utils",
|
|
6
6
|
"bugs": {
|
|
@@ -12,26 +12,37 @@
|
|
|
12
12
|
"repository": "github:anjianshi/js-packages",
|
|
13
13
|
"publishConfig": {
|
|
14
14
|
"registry": "https://registry.npmjs.org/",
|
|
15
|
-
"access": "public"
|
|
15
|
+
"access": "public",
|
|
16
|
+
"directory": "dist"
|
|
16
17
|
},
|
|
17
18
|
"type": "module",
|
|
19
|
+
"scripts": {
|
|
20
|
+
"watch": "npm run clear && tsc --watch",
|
|
21
|
+
"build": "npm run clear && tsc",
|
|
22
|
+
"clear": "rm -rf dist",
|
|
23
|
+
"prepublishOnly": "npm run build && node publish-prepare.cjs",
|
|
24
|
+
"postpublish": "rm dist/package.json",
|
|
25
|
+
"lint": "tsc --noEmit && node ../node_modules/eslint/bin/eslint.js './src/'"
|
|
26
|
+
},
|
|
18
27
|
"main": "index.js",
|
|
19
28
|
"dependencies": {
|
|
20
29
|
"lodash": "^4.17.21"
|
|
21
30
|
},
|
|
22
31
|
"devDependencies": {
|
|
23
|
-
"@
|
|
24
|
-
"@
|
|
25
|
-
"@
|
|
26
|
-
"
|
|
27
|
-
"
|
|
32
|
+
"@anjianshi/presets-eslint-base": "workspace:*",
|
|
33
|
+
"@anjianshi/presets-eslint-node": "workspace:*",
|
|
34
|
+
"@anjianshi/presets-eslint-react": "workspace:*",
|
|
35
|
+
"@anjianshi/presets-eslint-typescript": "workspace:*",
|
|
36
|
+
"@anjianshi/presets-prettier": "workspace:*",
|
|
37
|
+
"@anjianshi/presets-typescript": "workspace:*",
|
|
38
|
+
"@types/lodash": "^4.17.20",
|
|
39
|
+
"@types/node": "^22.16.0",
|
|
40
|
+
"@types/react": "^19.1.8",
|
|
41
|
+
"dotenv": "^17.0.1",
|
|
42
|
+
"eslint": "^9.30.1",
|
|
43
|
+
"redis": "^5.5.6",
|
|
28
44
|
"typescript": "^5.8.3",
|
|
29
|
-
"vconsole": "^3.15.1"
|
|
30
|
-
"@anjianshi/presets-eslint-node": "4.2.3",
|
|
31
|
-
"@anjianshi/presets-eslint-react": "4.2.3",
|
|
32
|
-
"@anjianshi/presets-prettier": "3.0.3",
|
|
33
|
-
"@anjianshi/presets-typescript": "3.2.4",
|
|
34
|
-
"@anjianshi/presets-eslint-typescript": "5.2.3"
|
|
45
|
+
"vconsole": "^3.15.1"
|
|
35
46
|
},
|
|
36
47
|
"peerDependencies": {
|
|
37
48
|
"@emotion/react": "^11.14.0",
|
|
@@ -40,7 +51,7 @@
|
|
|
40
51
|
"@prisma/client": "^6.8.2",
|
|
41
52
|
"chalk": "^5.4.1",
|
|
42
53
|
"dayjs": "^1.11.13",
|
|
43
|
-
"dotenv": "^
|
|
54
|
+
"dotenv": "^17.0.1",
|
|
44
55
|
"react": "^19.1.0"
|
|
45
56
|
},
|
|
46
57
|
"peerDependenciesMeta": {
|
|
@@ -70,4 +81,4 @@
|
|
|
70
81
|
}
|
|
71
82
|
},
|
|
72
83
|
"prettier": "@anjianshi/presets-prettier/prettierrc"
|
|
73
|
-
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const fs = require('node:fs')
|
|
2
|
+
const path = require('node:path')
|
|
3
|
+
|
|
4
|
+
const base = path.resolve(__dirname, './')
|
|
5
|
+
const dist = path.join(base, 'dist')
|
|
6
|
+
|
|
7
|
+
const packageJSON = require(path.join(base, 'package.json'))
|
|
8
|
+
delete packageJSON.publishConfig.directory
|
|
9
|
+
delete packageJSON.scripts
|
|
10
|
+
for (const [key, value] of Object.entries(packageJSON.dependencies)) {
|
|
11
|
+
packageJSON.dependencies[key] = value.replace('workspace:', 'workspace:../')
|
|
12
|
+
}
|
|
13
|
+
for (const [key, value] of Object.entries(packageJSON.devDependencies)) {
|
|
14
|
+
packageJSON.devDependencies[key] = value.replace('workspace:', 'workspace:../')
|
|
15
|
+
}
|
|
16
|
+
fs.writeFileSync(path.join(dist, 'package.json'), JSON.stringify(packageJSON, null, 2))
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-deprecated */
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 自动计算最合适的 rem 大小,应用到页面样式上。
|
|
5
|
+
*
|
|
6
|
+
* rem 的意义是对于大屏幕,适当地同步放大界面元素,以提供更饱满的显示效果。
|
|
7
|
+
* 不过也不是所有地方都原封不动地大就好了,所以还要配合 media query 来实现最佳效果。
|
|
8
|
+
*/
|
|
9
|
+
export function autoRem() {
|
|
10
|
+
const resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 计算规则:
|
|
14
|
+
* - 微信标准的 375px 宽度下,1rem 为 50px(这个比例的来由是这样的:移动端通常像素比 >= 2,这个 375px 的实际渲染像素是 750px,也就是实际渲染 750px 的情况下,1rem 为 100px)。
|
|
15
|
+
* - 在平板等特大屏幕下,限制 rem 的最大值为 75px,再大就夸张了。
|
|
16
|
+
* - 竖屏时取宽度来适配 rem,横屏时取高度来适配,以保证屏幕朝向不同时,界面元素的放大比例是一致的(这应该更符合人的认知:对于一个同样大小的屏幕,无论什么朝向,上面的文字应该是一样大的)。
|
|
17
|
+
* 注意:此计算方式仅适合“不能任意调整浏览器大小的”移动设备,对于浏览器窗口可能任意尺寸、比例的桌面端,还是应该始终按照宽度来适配。
|
|
18
|
+
*
|
|
19
|
+
* 从 px 到 rem 的换算:
|
|
20
|
+
* 原 px 单位的值换算成 rem,只要除以 50 即可。例如 12px 变成 0.24rem。
|
|
21
|
+
*/
|
|
22
|
+
function updateRem() {
|
|
23
|
+
const { clientWidth, clientHeight } = document.documentElement
|
|
24
|
+
const refSize = Math.min(clientWidth, clientHeight)
|
|
25
|
+
const rem = Math.min((refSize / 750) * 100, 75)
|
|
26
|
+
document.documentElement.style.fontSize = `${rem}px`
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
window.addEventListener(resizeEvt, updateRem, false)
|
|
30
|
+
document.addEventListener('DOMContentLoaded', updateRem, false)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 当前设备是否是全面屏
|
|
35
|
+
* 页面刚加载时可能取不到 offsetHeight,因此通过一个函数而不是常量来提供此值
|
|
36
|
+
*/
|
|
37
|
+
export function isFullScreen() {
|
|
38
|
+
const rate = document.documentElement.offsetHeight / document.documentElement.offsetWidth
|
|
39
|
+
const limit = window.screen.height === window.screen.availHeight ? 1.8 : 1.65 // 临界判断值
|
|
40
|
+
return rate > limit
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 当前是否是 iOS 设备
|
|
45
|
+
*/
|
|
46
|
+
export const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent)
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 当前是否是移动设备
|
|
50
|
+
*/
|
|
51
|
+
export const isMobile =
|
|
52
|
+
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
|
|
53
|
+
navigator.userAgent || navigator.vendor,
|
|
54
|
+
) ||
|
|
55
|
+
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
|
|
56
|
+
(navigator.userAgent || navigator.vendor).substr(0, 4),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 当前是否是微信内部浏览器
|
|
61
|
+
*/
|
|
62
|
+
export const isWechat = /micromessenger/i.test(navigator.userAgent)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 通过此模块注册全局变量以便于调试
|
|
3
|
+
* 变量会注册到 window.app = {} 下
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
declare global {
|
|
7
|
+
interface Window {
|
|
8
|
+
app: Record<string, unknown>
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// web-worker 环境下不存在 window 变量,无法执行注册
|
|
13
|
+
let hasWindow = false
|
|
14
|
+
try {
|
|
15
|
+
window.app = {}
|
|
16
|
+
hasWindow = true
|
|
17
|
+
} catch (e) {} // eslint-disable-line no-empty
|
|
18
|
+
|
|
19
|
+
export default function registerGlobal(key: string, content: unknown) {
|
|
20
|
+
if (hasWindow) window.app[key] = content
|
|
21
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 加载脚本文件
|
|
3
|
+
* 返回 Promise,成功则 resolve,失败 reject
|
|
4
|
+
*/
|
|
5
|
+
export default async function loadScript(url: string): Promise<void> {
|
|
6
|
+
return new Promise((resolve, reject) => {
|
|
7
|
+
const script = document.createElement('script')
|
|
8
|
+
script.src = url
|
|
9
|
+
script.onload = () => resolve()
|
|
10
|
+
script.onerror = err => reject(err) // eslint-disable-line @typescript-eslint/prefer-promise-reject-errors
|
|
11
|
+
window.document.head.appendChild(script)
|
|
12
|
+
})
|
|
13
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 针对浏览器环境定制 logging
|
|
3
|
+
*/
|
|
4
|
+
import {
|
|
5
|
+
logger as defaultLogger,
|
|
6
|
+
type Logger,
|
|
7
|
+
type LogInfo,
|
|
8
|
+
LogLevel,
|
|
9
|
+
LogHandler,
|
|
10
|
+
formatters,
|
|
11
|
+
} from '../logging/index.js'
|
|
12
|
+
|
|
13
|
+
export * from '../logging/index.js'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 实现向浏览器 console 输出日志
|
|
17
|
+
*/
|
|
18
|
+
export class ConsoleHandler extends LogHandler {
|
|
19
|
+
log(info: LogInfo) {
|
|
20
|
+
const color = (value = 'black') => `color: ${value};`
|
|
21
|
+
const prefix =
|
|
22
|
+
'%c' + [formatters.time(info), info.logger].map((v: string) => (v ? `[${v}]` : '')).join('')
|
|
23
|
+
const prefixColor = info.logger ? color(ConsoleHandler.getColor(info.logger)) : color()
|
|
24
|
+
|
|
25
|
+
const values = [prefix, prefixColor, ...info.args]
|
|
26
|
+
if (info.level === LogLevel.Debug) console.debug(...values)
|
|
27
|
+
else if (info.level === LogLevel.Info) console.log(...values)
|
|
28
|
+
else if (info.level === LogLevel.Warning) console.warn(...values)
|
|
29
|
+
else console.error(...values)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// 按顺序给各主题分配颜色(取自 http://chriskempson.com/projects/base16/)
|
|
33
|
+
private static readonly colors = [
|
|
34
|
+
'#dc9656',
|
|
35
|
+
'#7cafc2',
|
|
36
|
+
'#ba8baf',
|
|
37
|
+
'#a16946',
|
|
38
|
+
'#ab4642',
|
|
39
|
+
'#86c1b9',
|
|
40
|
+
'#a1b56c',
|
|
41
|
+
'#f7ca88',
|
|
42
|
+
]
|
|
43
|
+
private static readonly colorMap = new Map<string, string>()
|
|
44
|
+
static getColor(name: string) {
|
|
45
|
+
if (!ConsoleHandler.colorMap.has(name)) {
|
|
46
|
+
const nextIndex = ConsoleHandler.colorMap.size % ConsoleHandler.colors.length
|
|
47
|
+
ConsoleHandler.colorMap.set(name, ConsoleHandler.colors[nextIndex]!)
|
|
48
|
+
}
|
|
49
|
+
return ConsoleHandler.colorMap.get(name)!
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 预设的初始化行为
|
|
55
|
+
*/
|
|
56
|
+
export function initLogger(logger: Logger = defaultLogger) {
|
|
57
|
+
logger.addHandler(new ConsoleHandler())
|
|
58
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type default as VConsole } from 'vconsole'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 注册 VConsole 代码
|
|
5
|
+
* 此类库自己并不加载 VConsole,需使用者自行通过依赖或者 CDN 加载 VConsole 然后传给此类库
|
|
6
|
+
*/
|
|
7
|
+
let VConsoleLib: (new () => VConsole) | undefined
|
|
8
|
+
|
|
9
|
+
export function registerVConsoleLib(lib: new () => VConsole) {
|
|
10
|
+
VConsoleLib = lib
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 管理 VConsole 实例
|
|
15
|
+
*/
|
|
16
|
+
declare global {
|
|
17
|
+
interface Window {
|
|
18
|
+
VConsole: VConsole | null
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
window.VConsole = null
|
|
23
|
+
|
|
24
|
+
export function isVConsoleEnabled() {
|
|
25
|
+
return localStorage.getItem('vconsole') === '1'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function detectVConsole() {
|
|
29
|
+
if (isVConsoleEnabled()) {
|
|
30
|
+
runVConsole()
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function enableVConsole() {
|
|
35
|
+
localStorage.setItem('vconsole', '1')
|
|
36
|
+
runVConsole()
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function disableVConsole() {
|
|
40
|
+
localStorage.setItem('vconsole', '0')
|
|
41
|
+
destoryVConsole()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function runVConsole() {
|
|
45
|
+
if (window.VConsole !== null) return
|
|
46
|
+
if (VConsoleLib === undefined) return console.warn('尚未传入 VConsole 对象,无法启动')
|
|
47
|
+
window.VConsole = new VConsoleLib()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function destoryVConsole() {
|
|
51
|
+
if (!window.VConsole) return
|
|
52
|
+
window.VConsole.destroy()
|
|
53
|
+
window.VConsole = null
|
|
54
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 类似 lang/random.ts,但基于 Node.js 的 crypto 模块,提供密码级的随机数。
|
|
3
|
+
*/
|
|
4
|
+
import crypto from 'node:crypto'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 返回随机数,包含 min 和 max
|
|
8
|
+
*/
|
|
9
|
+
export function getCryptoRandomInt(min: number, max: number) {
|
|
10
|
+
// 如果传入的 max 小于 min,把它拉到和 min 一样。不然 crypto.randomInt 无法处理
|
|
11
|
+
const fixedMax = Math.max(min, max)
|
|
12
|
+
return crypto.randomInt(min, fixedMax + 1)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 返回随机字符串
|
|
17
|
+
*/
|
|
18
|
+
export function getCryptoRandomString(length = 6, seed = '0123456789abcdefghijklmnopqrstuvwxyz') {
|
|
19
|
+
let result = ''
|
|
20
|
+
while (result.length < length) result += seed[getCryptoRandomInt(0, seed.length - 1)]!
|
|
21
|
+
return result
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 从给定的选择中随机选中一项
|
|
26
|
+
* 如果数组为空,会返回 undefined
|
|
27
|
+
*/
|
|
28
|
+
export function cryptoChoiceRandom<T>(choices: T[]) {
|
|
29
|
+
return choices[getCryptoRandomInt(0, choices.length - 1)]
|
|
30
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import * as fs from 'node:fs'
|
|
2
|
+
import * as path from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 确认一个路径是否存在且是文件
|
|
7
|
+
*/
|
|
8
|
+
export async function isFileExists(filepath: string) {
|
|
9
|
+
try {
|
|
10
|
+
const res = await fs.promises.stat(filepath)
|
|
11
|
+
return res.isFile()
|
|
12
|
+
} catch (e) {
|
|
13
|
+
return false
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 确认一个路径是否存在且是文件夹
|
|
19
|
+
*/
|
|
20
|
+
export async function isDirectoryExists(dirpath: string) {
|
|
21
|
+
try {
|
|
22
|
+
const res = await fs.promises.stat(dirpath)
|
|
23
|
+
return res.isDirectory()
|
|
24
|
+
} catch (e) {
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 返回当前文件的绝对路径
|
|
31
|
+
* 需要传入当前文件的 ImportMeta 对象(可通过 import.meta 取得)
|
|
32
|
+
*/
|
|
33
|
+
export function getFilePath(fileUrl: string | ImportMeta) {
|
|
34
|
+
if (typeof fileUrl !== 'string') fileUrl = fileUrl.url
|
|
35
|
+
return fileURLToPath(new URL(fileUrl))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 返回文件所处目录的绝对路径
|
|
40
|
+
*/
|
|
41
|
+
export function getDirectoryPath(fileUrl: string | ImportMeta) {
|
|
42
|
+
return path.dirname(getFilePath(fileUrl))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 确保目录存在,如果不存在就创建(会递归创建上级目录) */
|
|
46
|
+
export async function mkdirp(dirpath: string, mode?: number | string) {
|
|
47
|
+
if (!(await isDirectoryExists(dirpath))) {
|
|
48
|
+
await fs.promises.mkdir(dirpath, { recursive: true, mode })
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
import util from 'node:util'
|
|
5
|
+
import chalk from 'chalk'
|
|
6
|
+
import dayjs from 'dayjs'
|
|
7
|
+
import { type LogInfo, LogLevel, LogHandler, formatters } from '../../logging/index.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 向 console 输出日志
|
|
11
|
+
*/
|
|
12
|
+
export class ConsoleHandler extends LogHandler {
|
|
13
|
+
log(info: LogInfo) {
|
|
14
|
+
const { logger, level, args } = info
|
|
15
|
+
const method = ConsoleHandler.consoleMethods[level]
|
|
16
|
+
const levelColor = ConsoleHandler.levelColors[level]
|
|
17
|
+
const levelName = formatters.level(info)
|
|
18
|
+
const loggerColor = chalk[ConsoleHandler.getLoggerColor(logger)]
|
|
19
|
+
const prefix = [
|
|
20
|
+
chalk.white(`[${formatters.time(info)}]`),
|
|
21
|
+
levelColor(`[${levelName}]`),
|
|
22
|
+
...(logger ? [loggerColor(`[${logger}]`)] : []),
|
|
23
|
+
].join('')
|
|
24
|
+
method(prefix, ...args)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
static readonly consoleMethods = {
|
|
28
|
+
[LogLevel.Debug]: console.debug.bind(console),
|
|
29
|
+
[LogLevel.Info]: console.info.bind(console),
|
|
30
|
+
[LogLevel.Warning]: console.warn.bind(console),
|
|
31
|
+
[LogLevel.Error]: console.error.bind(console),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
static readonly levelColors = {
|
|
35
|
+
[LogLevel.Debug]: chalk.whiteBright,
|
|
36
|
+
[LogLevel.Info]: chalk.white,
|
|
37
|
+
[LogLevel.Warning]: chalk.yellowBright,
|
|
38
|
+
[LogLevel.Error]: chalk.redBright,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 可供 logger 选择的颜色
|
|
42
|
+
private static readonly loggerColors = [
|
|
43
|
+
'green',
|
|
44
|
+
'yellow',
|
|
45
|
+
'blue',
|
|
46
|
+
'magenta',
|
|
47
|
+
'cyan',
|
|
48
|
+
'greenBright',
|
|
49
|
+
'yellowBright',
|
|
50
|
+
'blueBright',
|
|
51
|
+
'magentaBright',
|
|
52
|
+
'cyanBright',
|
|
53
|
+
] as const
|
|
54
|
+
private static readonly loggerColorMap = new Map<string, (typeof this.loggerColors)[number]>()
|
|
55
|
+
static getLoggerColor(logger: string) {
|
|
56
|
+
if (!ConsoleHandler.loggerColorMap.has(logger)) {
|
|
57
|
+
const color =
|
|
58
|
+
ConsoleHandler.loggerColors[
|
|
59
|
+
ConsoleHandler.loggerColorMap.size % ConsoleHandler.loggerColors.length
|
|
60
|
+
]!
|
|
61
|
+
ConsoleHandler.loggerColorMap.set(logger, color)
|
|
62
|
+
}
|
|
63
|
+
return ConsoleHandler.loggerColorMap.get(logger)!
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 写入文件日志
|
|
69
|
+
*/
|
|
70
|
+
export interface FileHandlerOptions {
|
|
71
|
+
dir: string // 日志存放目录 Logs directory
|
|
72
|
+
filePrefix: string // 日志文件名前缀 Prefix of the log file name
|
|
73
|
+
maxLength: number // 单条日志最长多少字符 Maximum length of a single log message
|
|
74
|
+
flushLength: number // 触发写入的缓存字符串数 Length of buffered strings that trigger a write operation
|
|
75
|
+
flushInterval: number // 缓存定时写入间隔(单位:ms),为 0 则所有日志立刻写入 Buffered strings write interval, 0 means all logs are written immediately.
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export class FileHandler extends LogHandler {
|
|
79
|
+
readonly options: FileHandlerOptions
|
|
80
|
+
|
|
81
|
+
constructor(options?: Partial<FileHandlerOptions>) {
|
|
82
|
+
super()
|
|
83
|
+
|
|
84
|
+
const dirname = path.dirname(fileURLToPath(new URL(import.meta.url)))
|
|
85
|
+
this.options = {
|
|
86
|
+
dir: path.resolve(dirname, 'logs'),
|
|
87
|
+
filePrefix: '',
|
|
88
|
+
maxLength: 10000,
|
|
89
|
+
flushLength: 100000,
|
|
90
|
+
flushInterval: 1000,
|
|
91
|
+
...(options ?? {}),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
this.initLogDir()
|
|
95
|
+
|
|
96
|
+
// 进程退出前把尚未写入文件的日志强制写入
|
|
97
|
+
// 这里必须用同步的方式来写,不然会写入不进去(可能是因为异步的话是放到下一个事件循环,但进程在这个事件循环内就退出了)
|
|
98
|
+
process.on('exit', () => this.flush(true))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Format log content
|
|
102
|
+
log(info: LogInfo) {
|
|
103
|
+
const { logger, args } = info
|
|
104
|
+
const prefix =
|
|
105
|
+
[
|
|
106
|
+
`[${formatters.datetime(info)}]`,
|
|
107
|
+
`[${formatters.level(info)}]`,
|
|
108
|
+
logger ? `[${logger}]` : '',
|
|
109
|
+
].join('') + ' '
|
|
110
|
+
|
|
111
|
+
const itemStrings: string[] = []
|
|
112
|
+
let totalLength = prefix.length
|
|
113
|
+
for (const item of args) {
|
|
114
|
+
const itemString = this.stringifyDataItem(item)
|
|
115
|
+
|
|
116
|
+
// 截断过长的日志内容 Truncate overly long log messages
|
|
117
|
+
if (totalLength + itemString.length < this.options.maxLength) {
|
|
118
|
+
itemStrings.push((totalLength === prefix.length ? '' : ' ') + itemString)
|
|
119
|
+
totalLength += itemString.length
|
|
120
|
+
} else {
|
|
121
|
+
itemStrings.push(
|
|
122
|
+
itemString.slice(0, this.options.maxLength - totalLength) + ' [too long, sliced]',
|
|
123
|
+
)
|
|
124
|
+
break
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
this.pushBuffer(prefix, ...itemStrings, '\n')
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
protected stringifyDataItem(item: unknown) {
|
|
132
|
+
// 去掉颜色控制字符
|
|
133
|
+
if (typeof item === 'string') item = item.replace(/\x1b\[\d+m/g, '')
|
|
134
|
+
|
|
135
|
+
// 利用 util.format() 获得和 console.log() 相同的输出(因为 console.log() 底层也是用的 util.format())
|
|
136
|
+
return util.format(item)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Handle buffer & flush
|
|
140
|
+
private buffer: string[] = []
|
|
141
|
+
private bufferSize = 0
|
|
142
|
+
private flushTimeoutId: NodeJS.Timeout | null = null
|
|
143
|
+
|
|
144
|
+
protected pushBuffer(...strings: string[]) {
|
|
145
|
+
this.buffer.push(...strings)
|
|
146
|
+
this.bufferSize = strings.reduce((sum, v) => sum + v.length, this.bufferSize)
|
|
147
|
+
if (this.options.flushInterval === 0 || this.bufferSize >= this.options.flushLength) {
|
|
148
|
+
this.flush()
|
|
149
|
+
} else if (!this.flushTimeoutId) {
|
|
150
|
+
this.flushTimeoutId = setTimeout(() => this.flush(), this.options.flushInterval)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
protected flush(sync?: boolean) {
|
|
155
|
+
if (this.flushTimeoutId) {
|
|
156
|
+
clearTimeout(this.flushTimeoutId)
|
|
157
|
+
this.flushTimeoutId = null
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (this.buffer.length) {
|
|
161
|
+
const content = this.buffer.join('')
|
|
162
|
+
this.buffer = []
|
|
163
|
+
this.bufferSize = 0
|
|
164
|
+
this.write(content, sync)
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// 文件系统交互 File system interaction
|
|
169
|
+
get filepath() {
|
|
170
|
+
const { dir, filePrefix } = this.options
|
|
171
|
+
return path.join(
|
|
172
|
+
dir,
|
|
173
|
+
`${filePrefix ? `${filePrefix}-` : ''}${dayjs().format('YYYY-MM-DD')}.log`,
|
|
174
|
+
)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
protected initLogDir() {
|
|
178
|
+
if (!fs.existsSync(this.options.dir)) fs.mkdirSync(this.options.dir)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
protected write(content: string, sync = false) {
|
|
182
|
+
if (sync) {
|
|
183
|
+
fs.appendFileSync(this.filepath, content)
|
|
184
|
+
} else {
|
|
185
|
+
fs.appendFile(this.filepath, content, error => {
|
|
186
|
+
if (error) console.error('[logger] write failed: ', error)
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 针对 Node.js 环境定制 logging
|
|
3
|
+
* 注意:使用此模块需要 chalk 依赖
|
|
4
|
+
*/
|
|
5
|
+
import { logger as defaultLogger, type Logger } from '../../logging/index.js'
|
|
6
|
+
import { ConsoleHandler } from './handlers.js'
|
|
7
|
+
|
|
8
|
+
export * from './handlers.js'
|
|
9
|
+
export * from '../../logging/index.js'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 预设的初始化行为
|
|
13
|
+
*/
|
|
14
|
+
export function initLogger(logger: Logger = defaultLogger) {
|
|
15
|
+
logger.addHandler(new ConsoleHandler())
|
|
16
|
+
}
|