@nickyzj2023/utils 1.0.48 → 1.0.50
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/AGENTS.md +58 -22
- package/dist/dom/index.d.ts +1 -0
- package/dist/dom/timeLog.d.ts +8 -0
- package/dist/function/index.d.ts +1 -0
- package/dist/function/loopUntil.d.ts +22 -0
- package/dist/hoc/index.d.ts +1 -0
- package/dist/hoc/withCache.d.ts +42 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +2 -0
- package/dist/is/index.d.ts +5 -0
- package/dist/is/isFalsy.d.ts +9 -0
- package/dist/is/isNil.d.ts +9 -0
- package/dist/is/isObject.d.ts +8 -0
- package/dist/is/isPrimitive.d.ts +9 -0
- package/dist/is/isTruthy.d.ts +8 -0
- package/dist/lru-cache.d.ts +18 -0
- package/dist/network/fetcher.d.ts +56 -0
- package/dist/network/getRealURL.d.ts +2 -0
- package/dist/network/image.d.ts +59 -0
- package/dist/network/index.d.ts +4 -0
- package/dist/network/to.d.ts +9 -0
- package/dist/number/index.d.ts +1 -0
- package/dist/number/randomInt.d.ts +7 -0
- package/dist/object/index.d.ts +3 -0
- package/dist/object/mapKeys.d.ts +17 -0
- package/dist/object/mapValues.d.ts +21 -0
- package/dist/object/mergeObjects.d.ts +12 -0
- package/dist/string/case.d.ts +32 -0
- package/dist/string/compact.d.ts +22 -0
- package/dist/string/index.d.ts +2 -0
- package/dist/time/debounce.d.ts +20 -0
- package/dist/time/index.d.ts +3 -0
- package/dist/time/sleep.d.ts +7 -0
- package/dist/time/throttle.d.ts +20 -0
- package/docs/assets/highlight.css +92 -99
- package/docs/assets/navigation.js +1 -1
- package/docs/assets/search.js +1 -1
- package/docs/functions/camelToSnake.html +178 -178
- package/docs/functions/capitalize.html +178 -178
- package/docs/functions/compactStr.html +182 -182
- package/docs/functions/debounce.html +187 -187
- package/docs/functions/decapitalize.html +178 -178
- package/docs/functions/fetcher.html +189 -189
- package/docs/functions/getRealURL.html +175 -175
- package/docs/functions/imageUrlToBase64.html +191 -187
- package/docs/functions/isFalsy.html +178 -178
- package/docs/functions/isNil.html +178 -178
- package/docs/functions/isObject.html +178 -178
- package/docs/functions/isPrimitive.html +178 -178
- package/docs/functions/isTruthy.html +178 -178
- package/docs/functions/loopUntil.html +180 -180
- package/docs/functions/mapKeys.html +180 -180
- package/docs/functions/mapValues.html +182 -182
- package/docs/functions/mergeObjects.html +184 -184
- package/docs/functions/randomInt.html +178 -178
- package/docs/functions/sleep.html +179 -179
- package/docs/functions/snakeToCamel.html +178 -178
- package/docs/functions/throttle.html +187 -187
- package/docs/functions/timeLog.html +178 -178
- package/docs/functions/to.html +180 -180
- package/docs/functions/withCache.html +185 -185
- package/docs/modules.html +174 -174
- package/docs/types/BunFetchOptions.html +176 -0
- package/docs/types/CamelToSnake.html +174 -174
- package/docs/types/Capitalize.html +174 -174
- package/docs/types/Decapitalize.html +174 -174
- package/docs/types/DeepMapKeys.html +174 -174
- package/docs/types/DeepMapValues.html +174 -174
- package/docs/types/Falsy.html +174 -174
- package/docs/types/ImageCompressionOptions.html +188 -184
- package/docs/types/Primitive.html +174 -174
- package/docs/types/RequestInit.html +174 -174
- package/docs/types/SetTtl.html +174 -174
- package/docs/types/SnakeToCamel.html +174 -174
- package/package.json +2 -2
- package/src/dom/index.ts +1 -0
- package/src/function/index.ts +1 -0
- package/src/{function.ts → function/loopUntil.ts} +36 -36
- package/src/hoc/index.ts +1 -0
- package/src/{hoc.ts → hoc/withCache.ts} +117 -117
- package/src/is/index.ts +5 -0
- package/src/is/isFalsy.ts +12 -0
- package/src/is/isNil.ts +11 -0
- package/src/is/isObject.ts +10 -0
- package/src/is/isPrimitive.ts +23 -0
- package/src/is/isTruthy.ts +10 -0
- package/src/lru-cache.ts +50 -50
- package/src/network/fetcher.ts +1 -1
- package/src/network/index.ts +1 -1
- package/src/number/index.ts +1 -0
- package/src/object/index.ts +3 -0
- package/src/object/mapKeys.ts +50 -0
- package/src/object/mapValues.ts +77 -0
- package/src/object/mergeObjects.ts +50 -0
- package/src/time/debounce.ts +34 -0
- package/src/time/index.ts +3 -0
- package/src/time/sleep.ts +11 -0
- package/src/time/throttle.ts +34 -0
- package/.github/workflows/docs.yml +0 -39
- package/src/is.ts +0 -70
- package/src/object.ts +0 -179
- package/src/time.ts +0 -81
- /package/src/{dom.ts → dom/timeLog.ts} +0 -0
- /package/src/{number.ts → number/randomInt.ts} +0 -0
package/AGENTS.md
CHANGED
|
@@ -4,17 +4,16 @@ This file contains essential information for AI coding agents working on this pr
|
|
|
4
4
|
|
|
5
5
|
## Project Overview
|
|
6
6
|
|
|
7
|
-
这是一个前端工具库(Frontend Utility Library),提供常用的 TypeScript/JavaScript 工具函数,帮助开发者简化日常开发任务。项目使用 Bun
|
|
7
|
+
这是一个前端工具库(Frontend Utility Library),提供常用的 TypeScript/JavaScript 工具函数,帮助开发者简化日常开发任务。项目使用 Bun 作为运行时和包管理器,发布到 npm 仓库 `@nickyzj2023/utils`。
|
|
8
8
|
|
|
9
9
|
## Technology Stack
|
|
10
10
|
|
|
11
11
|
- **Runtime**: [Bun](https://bun.com) v1.3.2+ - 快速的 JavaScript 运行时和包管理器
|
|
12
12
|
- **Language**: TypeScript 5.9.3+
|
|
13
|
-
- **Build Tool**: Bun 内置打包器
|
|
13
|
+
- **Build Tool**: Bun 内置打包器 + TypeScript 编译器
|
|
14
14
|
- **Linting/Formatting**: Biome 2.3.14
|
|
15
15
|
- **Documentation**: TypeDoc 0.28.16 + Material Theme
|
|
16
|
-
- **Dependencies**:
|
|
17
|
-
- `sharp` (^0.34.5) - 图片处理库,用于 `imageUrlToBase64` 功能
|
|
16
|
+
- **Dependencies**: 零运行时依赖,仅开发依赖
|
|
18
17
|
|
|
19
18
|
## Project Structure
|
|
20
19
|
|
|
@@ -22,21 +21,52 @@ This file contains essential information for AI coding agents working on this pr
|
|
|
22
21
|
.
|
|
23
22
|
├── src/ # 源代码目录
|
|
24
23
|
│ ├── index.ts # 入口文件,导出所有模块
|
|
25
|
-
│ ├── dom
|
|
26
|
-
│ ├──
|
|
27
|
-
│
|
|
28
|
-
│ ├──
|
|
29
|
-
│ ├──
|
|
30
|
-
│
|
|
31
|
-
│ ├──
|
|
32
|
-
│ ├──
|
|
33
|
-
│
|
|
34
|
-
│
|
|
24
|
+
│ ├── dom/ # DOM 相关工具
|
|
25
|
+
│ │ ├── index.ts # 模块导出
|
|
26
|
+
│ │ └── timeLog.ts # 带时间的 console.log
|
|
27
|
+
│ ├── function/ # 函数控制工具
|
|
28
|
+
│ │ ├── index.ts # 模块导出
|
|
29
|
+
│ │ └── loopUntil.ts # 循环执行直到满足条件
|
|
30
|
+
│ ├── hoc/ # 高阶函数
|
|
31
|
+
│ │ ├── index.ts # 模块导出
|
|
32
|
+
│ │ └── withCache.ts # 带缓存的高阶函数
|
|
33
|
+
│ ├── is/ # 类型判断工具
|
|
34
|
+
│ │ ├── index.ts # 模块导出
|
|
35
|
+
│ │ ├── isFalsy.ts # 假值判断
|
|
36
|
+
│ │ ├── isNil.ts # 空值判断
|
|
37
|
+
│ │ ├── isObject.ts # 普通对象判断
|
|
38
|
+
│ │ ├── isPrimitive.ts # 原始值判断
|
|
39
|
+
│ │ └── isTruthy.ts # 真值判断
|
|
40
|
+
│ ├── network/ # 网络请求工具
|
|
41
|
+
│ │ ├── index.ts # 模块导出
|
|
42
|
+
│ │ ├── fetcher.ts # 基于 Fetch API 的请求客户端
|
|
43
|
+
│ │ ├── getRealURL.ts # 从响应头获取真实链接
|
|
44
|
+
│ │ ├── image.ts # 图片 URL 转 Base64
|
|
45
|
+
│ │ └── to.ts # Go 语言风格的异步处理
|
|
46
|
+
│ ├── number/ # 数字工具
|
|
47
|
+
│ │ ├── index.ts # 模块导出
|
|
48
|
+
│ │ └── randomInt.ts # 生成随机整数
|
|
49
|
+
│ ├── object/ # 对象操作工具
|
|
50
|
+
│ │ ├── index.ts # 模块导出
|
|
51
|
+
│ │ ├── mapKeys.ts # 递归处理对象 key
|
|
52
|
+
│ │ ├── mapValues.ts # 递归处理对象 value
|
|
53
|
+
│ │ └── mergeObjects.ts # 深度合并对象
|
|
54
|
+
│ ├── string/ # 字符串处理工具
|
|
55
|
+
│ │ ├── index.ts # 模块导出
|
|
56
|
+
│ │ ├── case.ts # 命名法转换(snake/camel/capitalize)
|
|
57
|
+
│ │ └── compact.ts # 字符串压缩为单行
|
|
58
|
+
│ ├── time/ # 时间控制工具
|
|
59
|
+
│ │ ├── index.ts # 模块导出
|
|
60
|
+
│ │ ├── debounce.ts # 防抖函数
|
|
61
|
+
│ │ ├── sleep.ts # 延迟执行
|
|
62
|
+
│ │ └── throttle.ts # 节流函数
|
|
63
|
+
│ └── lru-cache.ts # LRU 缓存实现(默认导出)
|
|
35
64
|
├── dist/ # 构建输出目录(包含 .js 和 .d.ts 文件)
|
|
36
65
|
├── docs/ # TypeDoc 生成的文档网站
|
|
37
66
|
├── package.json # 包配置
|
|
38
67
|
├── tsconfig.json # TypeScript 配置
|
|
39
68
|
├── biome.json # Biome 代码规范配置
|
|
69
|
+
├── bun.lock # Bun 锁定文件
|
|
40
70
|
└── .gitignore # Git 忽略规则
|
|
41
71
|
```
|
|
42
72
|
|
|
@@ -51,7 +81,7 @@ bun run docs
|
|
|
51
81
|
```
|
|
52
82
|
|
|
53
83
|
构建流程:
|
|
54
|
-
1. `bun build --target=bun --outdir ./dist --minify ./src/index.ts` - 使用 Bun 打包并压缩
|
|
84
|
+
1. `bun build --target=bun --outdir ./dist --minify ./src/index.ts --packages external` - 使用 Bun 打包并压缩
|
|
55
85
|
2. `tsc` - 生成 TypeScript 类型声明文件(.d.ts)
|
|
56
86
|
3. `typedoc src/index.ts --plugin typedoc-material-theme` - 生成 API 文档
|
|
57
87
|
|
|
@@ -82,19 +112,24 @@ bun run docs
|
|
|
82
112
|
|
|
83
113
|
## Module Organization
|
|
84
114
|
|
|
85
|
-
|
|
115
|
+
项目按功能领域划分模块,每个模块是一个子目录:
|
|
86
116
|
|
|
87
117
|
| 模块 | 功能描述 | 主要导出 |
|
|
88
118
|
|------|---------|---------|
|
|
89
119
|
| `is` | 类型判断 | `isObject`, `isPrimitive`, `isFalsy`, `isTruthy`, `isNil`, `Primitive`, `Falsy` |
|
|
90
|
-
| `network` | 网络请求 | `fetcher`, `to`, `getRealURL`, `RequestInit` |
|
|
120
|
+
| `network` | 网络请求 | `fetcher`, `to`, `getRealURL`, `imageUrlToBase64`, `RequestInit`, `ImageCompressionOptions` |
|
|
91
121
|
| `object` | 对象操作 | `mergeObjects`, `mapKeys`, `mapValues`, `DeepMapKeys`, `DeepMapValues` |
|
|
92
|
-
| `string` | 字符串处理 | `snakeToCamel`, `camelToSnake`, `capitalize`, `decapitalize`, `
|
|
122
|
+
| `string` | 字符串处理 | `snakeToCamel`, `camelToSnake`, `capitalize`, `decapitalize`, `compactStr` |
|
|
93
123
|
| `time` | 时间控制 | `sleep`, `debounce`, `throttle` |
|
|
94
124
|
| `function` | 函数控制 | `loopUntil` |
|
|
95
125
|
| `hoc` | 高阶函数 | `withCache`, `SetTtl` |
|
|
96
126
|
| `lru-cache` | 缓存实现 | `LRUCache`(默认导出) |
|
|
97
127
|
| `dom` | DOM 工具 | `timeLog` |
|
|
128
|
+
| `number` | 数字工具 | `randomInt` |
|
|
129
|
+
|
|
130
|
+
每个模块目录结构:
|
|
131
|
+
- `index.ts` - 集中导出该模块的所有功能
|
|
132
|
+
- 具体实现文件(如 `sleep.ts`, `debounce.ts` 等)
|
|
98
133
|
|
|
99
134
|
## Testing
|
|
100
135
|
|
|
@@ -112,8 +147,8 @@ bun run docs
|
|
|
112
147
|
## Security Considerations
|
|
113
148
|
|
|
114
149
|
1. **敏感信息**: `.npmrc` 文件包含 npm 认证令牌,已在 `.gitignore` 中配置忽略
|
|
115
|
-
2.
|
|
116
|
-
3.
|
|
150
|
+
2. **网络请求**: `fetcher` 函数会解析 JSON 错误响应,注意潜在的安全风险
|
|
151
|
+
3. **动态导入**: `imageUrlToBase64` 使用动态导入尝试加载 `sharp`,避免在浏览器环境报错
|
|
117
152
|
|
|
118
153
|
## Development Workflow
|
|
119
154
|
|
|
@@ -127,5 +162,6 @@ bun run docs
|
|
|
127
162
|
|
|
128
163
|
- 项目使用 ES Module(`"type": "module"`),不支持 CommonJS
|
|
129
164
|
- 构建目标为 Bun 运行时(`--target=bun`)
|
|
130
|
-
- `imageUrlToBase64`
|
|
131
|
-
- `fetcher` 函数基于 Fetch API,在 Bun
|
|
165
|
+
- `imageUrlToBase64` 功能在浏览器环境使用 OffscreenCanvas 压缩,在 Node.js/Bun 环境尝试使用 sharp(可选依赖)
|
|
166
|
+
- `fetcher` 函数基于 Fetch API,在 Bun 环境下支持 `proxy` 选项
|
|
167
|
+
- 所有工具函数均为纯函数,无副作用
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { timeLog } from "./timeLog";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { loopUntil } from "./loopUntil";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 循环执行函数,直到符合停止条件
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* // 循环请求大语言模型,直到其不再调用工具
|
|
6
|
+
* loopUntil(
|
|
7
|
+
* async () => {
|
|
8
|
+
* const completion = await chatCompletions();
|
|
9
|
+
* completion.tool_calls?.forEach(chooseAndHandleTool)
|
|
10
|
+
* return completion;
|
|
11
|
+
* },
|
|
12
|
+
* {
|
|
13
|
+
* shouldStop: (completion) => !completion.tool_calls,
|
|
14
|
+
* },
|
|
15
|
+
* ),
|
|
16
|
+
*/
|
|
17
|
+
export declare const loopUntil: <T>(fn: (count: number) => Promise<T>, options?: {
|
|
18
|
+
/** 最大循环次数,默认 5 次 */
|
|
19
|
+
maxRetries?: number;
|
|
20
|
+
/** 停止循环条件,默认立即停止 */
|
|
21
|
+
shouldStop?: (result: T) => boolean;
|
|
22
|
+
}) => Promise<T>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { type SetTtl, withCache } from "./withCache";
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export type SetTtl = (seconds: number) => void;
|
|
2
|
+
/**
|
|
3
|
+
* 创建一个带缓存的高阶函数
|
|
4
|
+
*
|
|
5
|
+
* @template Args 被包装函数的参数类型数组
|
|
6
|
+
* @template Result 被包装函数的返回类型
|
|
7
|
+
*
|
|
8
|
+
* @param fn 需要被缓存的函数,参数里附带的 setTtl 方法用于根据具体情况改写过期时间
|
|
9
|
+
* @param ttlSeconds 以秒为单位的过期时间,-1 表示永不过期,默认 -1,会被回调函数里的 setTtl() 覆盖
|
|
10
|
+
*
|
|
11
|
+
* @returns 返回包装后的函数,以及缓存相关的额外方法
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* // 异步函数示例
|
|
15
|
+
* const fetchData = withCache(async function (url: string) {
|
|
16
|
+
* const data = await fetch(url).then((res) => res.json());
|
|
17
|
+
* this.setTtl(data.expiresIn); // 根据实际情况调整过期时间
|
|
18
|
+
* return data;
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* await fetchData(urlA);
|
|
22
|
+
* await fetchData(urlA); // 使用缓存结果
|
|
23
|
+
* await fetchData(urlB);
|
|
24
|
+
* await fetchData(urlB); // 使用缓存结果
|
|
25
|
+
*
|
|
26
|
+
* fetchData.clear(); // 清除缓存
|
|
27
|
+
* await fetchData(urlA); // 重新请求
|
|
28
|
+
* await fetchData(urlB); // 重新请求
|
|
29
|
+
*
|
|
30
|
+
* // 缓存过期前
|
|
31
|
+
* await sleep();
|
|
32
|
+
* fetchData.updateTtl(180); // 更新 ttl 并为所有未过期的缓存续期
|
|
33
|
+
* await fetchData(urlA); // 使用缓存结果
|
|
34
|
+
* await fetchData(urlB); // 使用缓存结果
|
|
35
|
+
*/
|
|
36
|
+
export declare const withCache: <Args extends any[], Result>(fn: (this: {
|
|
37
|
+
setTtl: SetTtl;
|
|
38
|
+
}, ...args: Args) => Result, ttlSeconds?: number) => {
|
|
39
|
+
(...args: Args): Result;
|
|
40
|
+
clear(): void;
|
|
41
|
+
updateTtl(seconds: number): void;
|
|
42
|
+
};
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var m=(...x)=>{console.log(`${new Date().toLocaleTimeString()}`,...x)};var O=async(x,z)=>{let{maxRetries:T=5,shouldStop:E=()=>!0}=z??{};for(let P=0;P<T;P++){let C=await x(P);if(E(C))return C}throw Error(`\u8D85\u8FC7\u4E86\u6700\u5927\u5FAA\u73AF\u6B21\u6570\uFF08${T}\uFF09\u4E14\u672A\u6EE1\u8DB3\u505C\u6B62\u6267\u884C\u6761\u4EF6`)};var R=(x,z=-1)=>{let T=new Map,E=(...P)=>{let C=JSON.stringify(P),D=Date.now(),G=T.get(C);if(G&&D<G.expiresAt)return G.value;let M=z===-1?1/0:D+z*1000,J={setTtl:(H)=>{M=D+H*1000}},Y=x.apply(J,P);if(Y instanceof Promise){let H=Y.then((Q)=>{return T.set(C,{value:Q,expiresAt:M}),Q});return T.set(C,{value:H,expiresAt:M}),H}return T.set(C,{value:Y,expiresAt:M}),Y};return E.clear=()=>T.clear(),E.updateTtl=(P)=>{z=P;let C=Date.now(),D=C+P*1000;for(let[G,M]of T.entries())if(M.expiresAt>C)M.expiresAt=D,T.set(G,M)},E};var q=(x)=>{return!x};var _=(x)=>{return x===null||x===void 0};var $=(x)=>{return x?.constructor===Object};var X=(x)=>{return x===null||x===void 0||typeof x!=="object"&&typeof x!=="function"};var K=(x)=>{return!!x};var d=(x,z)=>{if(Array.isArray(x))return x.map((T)=>d(T,z));if($(x))return Object.keys(x).reduce((E,P)=>{let C=z(P),D=x[P];return E[C]=d(D,z),E},{});return x};var o=(x,z,T)=>{let{filter:E}=T??{};if(Array.isArray(x)){let P=x.map((C,D)=>{if($(C))return o(C,z,T);return z(C,D)});if(E)return P.filter((C,D)=>E(C,D));return P}if($(x))return Object.keys(x).reduce((C,D)=>{let G=x[D],M;if($(G)||Array.isArray(G))M=o(G,z,T);else M=z(G,D);if(!E||E(M,D))C[D]=M;return C},{});return x};var Z=(x,z)=>{let T={...x};for(let E of Object.keys(z)){let P=T[E],C=z[E];if(X(P)&&X(C)){T[E]=C;continue}if(Array.isArray(P)&&Array.isArray(C)){T[E]=P.concat(C);continue}if($(P)&&$(C)){T[E]=Z(P,C);continue}T[E]=C}return T};var c=(x="",z={})=>{let T=async(E,P={})=>{let C=new URL(x?`${x}${E}`:E),{params:D,parser:G,...M}=Z(z,P);if($(D))Object.entries(D).forEach(([H,Q])=>{if(_(Q))return;C.searchParams.append(H,Q.toString())});if($(M.body))M.body=JSON.stringify(M.body),M.headers={...M.headers,"Content-Type":"application/json"};let J=await fetch(C,M);if(!J.ok){if(J.headers.get("Content-Type")?.startsWith("application/json"))throw await J.json();throw Error(J.statusText)}return await(G?.(J)??J.json())};return{get:(E,P)=>T(E,{...P,method:"GET"}),post:(E,P,C)=>T(E,{...C,method:"POST",body:P}),put:(E,P,C)=>T(E,{...C,method:"PUT",body:P}),delete:(E,P)=>T(E,{...P,method:"DELETE"})}};var I=async(x)=>{try{return[null,await x]}catch(z){return[z,void 0]}};var A=async(x)=>{let[z,T]=await I(fetch(x,{method:"HEAD",redirect:"manual"}));if(z)return x;return T.headers.get("location")||x};var W=(x)=>{let z=new Uint8Array(x),T="";for(let E=0;E<z.byteLength;E++)T+=String.fromCharCode(z[E]);return btoa(T)},L=async()=>{try{let z=await Function("modulePath","return import(modulePath)")("sharp");return z.default||z}catch{return null}},n=async(x,z,T,E)=>{let P=Buffer.from(z),C=x(P);if(T==="image/jpeg")C=C.jpeg({quality:Math.round(E*100)});else if(T==="image/png"){let G=Math.round((1-E)*9);C=C.png({compressionLevel:G})}let D=await C.toBuffer();return`data:${T};base64,${D.toString("base64")}`},U=async(x,z={})=>{let{quality:T=0.92,compressor:E,fetcher:P=fetch}=z;if(!x.startsWith("http"))throw Error("\u56FE\u7247\u5730\u5740\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934");let C=await P(x);if(!C.ok)throw Error(`\u83B7\u53D6\u56FE\u7247\u5931\u8D25: ${C.statusText}`);let D=C.headers.get("Content-Type")||"image/jpeg",G=await C.arrayBuffer();if(D!=="image/jpeg"&&D!=="image/png"){let Y=W(G);return`data:${D};base64,${Y}`}if(E)return await E(G,D,T);if(typeof OffscreenCanvas<"u"){let Y=null;try{let H=new Blob([G],{type:D});Y=await createImageBitmap(H);let Q=new OffscreenCanvas(Y.width,Y.height),S=Q.getContext("2d");if(!S)throw Error("\u65E0\u6CD5\u83B7\u53D6 OffscreenCanvas context");S.drawImage(Y,0,0),Y.close(),Y=null;let f=await(await Q.convertToBlob({type:D,quality:T})).arrayBuffer(),F=W(f);return`data:${D};base64,${F}`}catch{Y?.close();let H=W(G);return`data:${D};base64,${H}`}}let M=await L();if(M)try{return await n(M,G,D,T)}catch{let Y=W(G);return`data:${D};base64,${Y}`}let J=W(G);return`data:${D};base64,${J}`};var V=(x,z)=>{return Math.floor(Math.random()*(z-x+1))+x};var h=(x)=>{return x.replace(/_([a-zA-Z])/g,(z,T)=>T.toUpperCase())},N=(x)=>{return x.replace(/([A-Z])/g,(z,T)=>`_${T.toLowerCase()}`)},w=(x)=>{return x.charAt(0).toUpperCase()+x.slice(1)},g=(x)=>{return x.charAt(0).toLowerCase()+x.slice(1)};var B=(x="",z)=>{if(!x)return"";let{maxLength:T=1/0,disableNewLineReplace:E=!1,disableWhitespaceCollapse:P=!1,omission:C="..."}=z??{},D=x;if(!E)D=D.replace(/\r?\n/g,"\\n");else D=D.replace(/\r?\n/g," ");if(!P)D=D.replace(/\s+/g," ");if(D=D.trim(),T>0&&D.length>T)return D.slice(0,T)+C;return D};var p=(x,z=300)=>{let T=null;return(...E)=>{if(T)clearTimeout(T);T=setTimeout(()=>{x(...E)},z)}};var k=async(x=150)=>{return new Promise((z)=>{setTimeout(z,x)})};var r=(x,z=300)=>{let T=null;return function(...E){if(!T)T=setTimeout(()=>{T=null,x.apply(this,E)},z)}};export{R as withCache,I as to,m as timeLog,r as throttle,h as snakeToCamel,k as sleep,V as randomInt,Z as mergeObjects,o as mapValues,d as mapKeys,O as loopUntil,K as isTruthy,X as isPrimitive,$ as isObject,_ as isNil,q as isFalsy,U as imageUrlToBase64,A as getRealURL,c as fetcher,g as decapitalize,p as debounce,B as compactStr,w as capitalize,N as camelToSnake};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type Primitive = number | string | boolean | symbol | bigint | undefined | null;
|
|
2
|
+
/**
|
|
3
|
+
* 检测传入的值是否为**原始值**(number、string、boolean、symbol、bigint、undefined、null)
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* isPrimitive(1); // true
|
|
7
|
+
* isPrimitive([]); // false
|
|
8
|
+
*/
|
|
9
|
+
export declare const isPrimitive: (value: any) => value is Primitive;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 简易 LRU 缓存
|
|
3
|
+
* @example
|
|
4
|
+
* const cache = new LRUCache<string, number>(2);
|
|
5
|
+
* cache.set("a", 1);
|
|
6
|
+
* cache.set("b", 2);
|
|
7
|
+
* cache.set("c", 3); // 缓存已满,a 被淘汰
|
|
8
|
+
* cache.get("a"); // undefined
|
|
9
|
+
*/
|
|
10
|
+
declare class LRUCache<K, V> {
|
|
11
|
+
private cache;
|
|
12
|
+
private maxSize;
|
|
13
|
+
constructor(maxSize?: number);
|
|
14
|
+
get(key: K): V | undefined;
|
|
15
|
+
set(key: K, value: V): void;
|
|
16
|
+
has(key: K): boolean;
|
|
17
|
+
}
|
|
18
|
+
export default LRUCache;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export type BunFetchOptions = {
|
|
2
|
+
/** 代理服务器配置(仅 Bun 支持) */
|
|
3
|
+
proxy?: string;
|
|
4
|
+
};
|
|
5
|
+
export type RequestInit = globalThis.RequestInit & BunFetchOptions & {
|
|
6
|
+
params?: Record<string, any>;
|
|
7
|
+
parser?: (response: Response) => Promise<any>;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* 基于 Fetch API 的请求客户端
|
|
11
|
+
* @param baseURL 接口前缀
|
|
12
|
+
* @param baseOptions 客户端级别的请求体,后续调用时传递相同参数会覆盖上去
|
|
13
|
+
*
|
|
14
|
+
* @remarks
|
|
15
|
+
* 特性:
|
|
16
|
+
* - 合并实例、调用时的相同请求体
|
|
17
|
+
* - 在 params 里传递对象,自动转换为 queryString
|
|
18
|
+
* - 在 body 里传递对象,自动 JSON.stringify
|
|
19
|
+
* - 可选择使用 to() 转换请求结果为 [Error, Response]
|
|
20
|
+
* - 可选择使用 withCache() 缓存请求结果
|
|
21
|
+
* - 支持 proxy 选项(仅在 Bun 环境有效)
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
*
|
|
25
|
+
* // 用法1:直接发送请求
|
|
26
|
+
* const res = await fetcher().get<Blog>("https://nickyzj.run:3030/blogs/hello-world");
|
|
27
|
+
*
|
|
28
|
+
* // 用法2:创建实例
|
|
29
|
+
* const api = fetcher("https://nickyzj.run:3030", { headers: { Authorization: "Bearer token" } });
|
|
30
|
+
* const res = await api.get<Blog>("/blogs/hello-world", { headers: {...}, params: { page: 1 } }); // 与实例相同的 headers 会覆盖上去,params 会转成 ?page=1 跟到 url 后面
|
|
31
|
+
*
|
|
32
|
+
* // 用法3:使用代理(仅 Bun 环境)
|
|
33
|
+
* const api = fetcher("https://api.example.com", {
|
|
34
|
+
* proxy: "http://127.0.0.1:7890"
|
|
35
|
+
* });
|
|
36
|
+
*
|
|
37
|
+
* // 安全处理请求结果
|
|
38
|
+
* const [error, data] = await to(api.get<Blog>("/blogs/hello-world"));
|
|
39
|
+
* if (error) {
|
|
40
|
+
* console.error(error);
|
|
41
|
+
* return;
|
|
42
|
+
* }
|
|
43
|
+
* console.log(data);
|
|
44
|
+
*
|
|
45
|
+
* // 缓存请求结果
|
|
46
|
+
* const getBlogs = withCache(api.get);
|
|
47
|
+
* await getBlogs("/blogs");
|
|
48
|
+
* await sleep();
|
|
49
|
+
* await getBlogs("/blogs"); // 不发请求,使用缓存
|
|
50
|
+
*/
|
|
51
|
+
export declare const fetcher: (baseURL?: string, baseOptions?: RequestInit) => {
|
|
52
|
+
get: <T>(url: string, options?: Omit<RequestInit, "method">) => Promise<T>;
|
|
53
|
+
post: <T>(url: string, body: any, options?: Omit<RequestInit, "method" | "body">) => Promise<T>;
|
|
54
|
+
put: <T>(url: string, body: any, options?: Omit<RequestInit, "method" | "body">) => Promise<T>;
|
|
55
|
+
delete: <T>(url: string, options?: Omit<RequestInit, "method" | "body">) => Promise<T>;
|
|
56
|
+
};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 图片压缩选项
|
|
3
|
+
*/
|
|
4
|
+
export type ImageCompressionOptions = {
|
|
5
|
+
/** 压缩比率,默认 0.92 */
|
|
6
|
+
quality?: number;
|
|
7
|
+
/**
|
|
8
|
+
* 自定义压缩函数,用于覆盖默认压缩行为
|
|
9
|
+
* @param arrayBuffer 图片的 ArrayBuffer 数据
|
|
10
|
+
* @param mime 图片的 MIME 类型
|
|
11
|
+
* @param quality 压缩质量
|
|
12
|
+
* @returns 压缩后的 base64 字符串
|
|
13
|
+
*/
|
|
14
|
+
compressor?: (arrayBuffer: ArrayBuffer, mime: string, quality: number) => Promise<string> | string;
|
|
15
|
+
/**
|
|
16
|
+
* 自定义 fetch 函数,用于使用自己封装的请求库读取图片
|
|
17
|
+
* 必须返回符合 Web 标准的 Response 对象
|
|
18
|
+
* @param url 图片地址
|
|
19
|
+
* @returns Promise<Response>
|
|
20
|
+
*/
|
|
21
|
+
fetcher?: (url: string) => Promise<Response>;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* 图片地址转 base64 数据
|
|
25
|
+
*
|
|
26
|
+
* @param imageUrl 图片地址
|
|
27
|
+
* @param options 可选配置
|
|
28
|
+
* @param options.quality 压缩比率,默认 0.92
|
|
29
|
+
* @param options.compressor 自定义压缩函数,用于覆盖默认压缩行为
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* // 基本用法(浏览器自动使用 Canvas 压缩,Node.js/Bun 自动检测并使用 sharp)
|
|
33
|
+
* imageUrlToBase64("https://example.com/image.jpg");
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* // 使用自定义 fetch 函数(如 axios 封装)
|
|
37
|
+
* imageUrlToBase64("https://example.com/image.jpg", {
|
|
38
|
+
* fetcher: async (url) => {
|
|
39
|
+
* // 使用 axios 或其他请求库,但必须返回 Response 对象
|
|
40
|
+
* const response = await axios.get(url, { responseType: 'arraybuffer' });
|
|
41
|
+
* return new Response(response.data, {
|
|
42
|
+
* status: response.status,
|
|
43
|
+
* statusText: response.statusText,
|
|
44
|
+
* headers: response.headers
|
|
45
|
+
* });
|
|
46
|
+
* }
|
|
47
|
+
* });
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* // 使用自定义压缩函数覆盖默认行为
|
|
51
|
+
* imageUrlToBase64("https://example.com/image.jpg", {
|
|
52
|
+
* quality: 0.8,
|
|
53
|
+
* compressor: async (buffer, mime, quality) => {
|
|
54
|
+
* // 自定义压缩逻辑
|
|
55
|
+
* return `data:${mime};base64,...`;
|
|
56
|
+
* }
|
|
57
|
+
* });
|
|
58
|
+
*/
|
|
59
|
+
export declare const imageUrlToBase64: (imageUrl: string, options?: ImageCompressionOptions) => Promise<string>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Go 语言风格的异步处理方式
|
|
3
|
+
* @param promise 一个能被 await 的异步函数
|
|
4
|
+
* @returns 如果成功,返回 [null, 异步函数结果],否则返回 [Error, undefined]
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* const [error, response] = await to(fetcher().get<Blog>("/blogs/hello-world"));
|
|
8
|
+
*/
|
|
9
|
+
export declare const to: <T, E = Error>(promise: Promise<T>) => Promise<[null, T] | [E, undefined]>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { randomInt } from "./randomInt";
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type DeepMapKeys<T> = T extends Array<infer U> ? Array<DeepMapKeys<U>> : T extends object ? {
|
|
2
|
+
[key: string]: DeepMapKeys<T[keyof T]>;
|
|
3
|
+
} : T;
|
|
4
|
+
/**
|
|
5
|
+
* 递归处理对象里的 key
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* 无法完整推导出类型,只能做到有递归,key 全为 string,value 为同层级的所有类型的联合
|
|
9
|
+
*
|
|
10
|
+
* @template T 要转换的对象
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* const obj = { a: { b: 1 } };
|
|
14
|
+
* const result = mapKeys(obj, (key) => key.toUpperCase());
|
|
15
|
+
* console.log(result); // { A: { B: 1 } }
|
|
16
|
+
*/
|
|
17
|
+
export declare const mapKeys: <T>(obj: T, getNewKey: (key: string) => string) => DeepMapKeys<T>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export type DeepMapValues<T, R> = T extends Array<infer U> ? Array<DeepMapValues<U, R>> : T extends object ? {
|
|
2
|
+
[K in keyof T]: T[K] extends object ? DeepMapValues<T[K], R> : R;
|
|
3
|
+
} : R;
|
|
4
|
+
/**
|
|
5
|
+
* 递归处理对象里的 value
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* 无法完整推导出类型,所有 value 最终都会变为 any
|
|
9
|
+
*
|
|
10
|
+
* @template T 要转换的对象
|
|
11
|
+
* @template R 转换后的值类型,为 any,无法进一步推导
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* const obj = { a: 1, b: { c: 2 } };
|
|
15
|
+
* const result = mapValues(obj, (value, key) => isPrimitive(value) ? value + 1 : value);
|
|
16
|
+
* console.log(result); // { a: 2, b: { c: 3 } }
|
|
17
|
+
*/
|
|
18
|
+
export declare const mapValues: <T, R = any>(obj: T, getNewValue: (value: any, key: string | number) => R, options?: {
|
|
19
|
+
/** 过滤函数,返回 true 表示保留该字段 */
|
|
20
|
+
filter?: (value: any, key: string | number) => boolean;
|
|
21
|
+
}) => DeepMapValues<T, R>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 深度合并两个对象,规则如下:
|
|
3
|
+
* 1. 原始值覆盖:如果两个值都是原始类型,则用后者覆盖;
|
|
4
|
+
* 2. 数组拼接:如果两个值都是数组,则拼接为大数组;
|
|
5
|
+
* 3. 对象递归合并:如果两个值都是对象,则进行递归深度合并;
|
|
6
|
+
*
|
|
7
|
+
* @template T 第一个对象
|
|
8
|
+
* @template U 第二个对象
|
|
9
|
+
* @param {T} obj1 要合并的第一个对象,相同字段会被 obj2 覆盖
|
|
10
|
+
* @param {U} obj2 要合并的第二个对象
|
|
11
|
+
*/
|
|
12
|
+
export declare const mergeObjects: <T extends Record<string, any>, U extends Record<string, any>>(obj1: T, obj2: U) => T & U;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export type SnakeToCamel<S extends string> = S extends `${infer Before}_${infer After}` ? After extends `${infer First}${infer Rest}` ? `${Before}${Uppercase<First>}${SnakeToCamel<Rest>}` : Before : S;
|
|
2
|
+
/**
|
|
3
|
+
* 下划线命名法转为驼峰命名法
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* snakeToCamel("user_name") // "userName"
|
|
7
|
+
*/
|
|
8
|
+
export declare const snakeToCamel: <S extends string>(str: S) => SnakeToCamel<S>;
|
|
9
|
+
export type CamelToSnake<S extends string> = S extends `${infer First}${infer Rest}` ? Rest extends Uncapitalize<Rest> ? `${Lowercase<First>}${CamelToSnake<Rest>}` : `${Lowercase<First>}_${CamelToSnake<Rest>}` : Lowercase<S>;
|
|
10
|
+
/**
|
|
11
|
+
* 驼峰命名法转为下划线命名法
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* camelToSnake("shouldComponentUpdate") // "should_component_update"
|
|
15
|
+
*/
|
|
16
|
+
export declare const camelToSnake: <S extends string>(str: S) => CamelToSnake<S>;
|
|
17
|
+
export type Capitalize<S extends string> = S extends `${infer P1}${infer Rest}` ? P1 extends Capitalize<P1> ? S : `${Uppercase<P1>}${Rest}` : S;
|
|
18
|
+
/**
|
|
19
|
+
* 字符串首字母大写
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* capitalize("hello") // "Hello"
|
|
23
|
+
*/
|
|
24
|
+
export declare const capitalize: <S extends string>(s: S) => Capitalize<S>;
|
|
25
|
+
export type Decapitalize<S extends string> = S extends `${infer P1}${infer Rest}` ? P1 extends Lowercase<P1> ? P1 : `${Lowercase<P1>}${Rest}` : S;
|
|
26
|
+
/**
|
|
27
|
+
* 字符串首字母小写
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* decapitalize("Hello") // "hello"
|
|
31
|
+
*/
|
|
32
|
+
export declare const decapitalize: <S extends string>(s: S) => Decapitalize<S>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 将字符串压缩为单行精简格式
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* // "Hello, world."
|
|
6
|
+
* compactStr(`
|
|
7
|
+
* Hello,
|
|
8
|
+
* world!
|
|
9
|
+
* `, {
|
|
10
|
+
* disableNewLineReplace: false,
|
|
11
|
+
* });
|
|
12
|
+
*/
|
|
13
|
+
export declare const compactStr: (text?: string, options?: {
|
|
14
|
+
/** 最大保留长度,设为 0 或 Infinity 则不截断,默认 Infinity */
|
|
15
|
+
maxLength?: number;
|
|
16
|
+
/** 是否将换行符替换为字面量 \n,默认开启 */
|
|
17
|
+
disableNewLineReplace?: boolean;
|
|
18
|
+
/** 是否合并连续的空格/制表符为一个空格,默认开启 */
|
|
19
|
+
disableWhitespaceCollapse?: boolean;
|
|
20
|
+
/** 截断后的后缀,默认为 "..." */
|
|
21
|
+
omission?: string;
|
|
22
|
+
}) => string;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 防抖:在指定时间内只执行最后一次调用
|
|
3
|
+
* @param fn 要防抖的函数
|
|
4
|
+
* @param delay 延迟时间,默认 300ms
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* 连续触发时,只有最后一次会执行。适合用于搜索框输入、窗口大小调整等场景。
|
|
8
|
+
* 例如:用户输入"hello"过程中,不会触发搜索,只有停下来时才执行。
|
|
9
|
+
*
|
|
10
|
+
* 防抖 vs 节流:
|
|
11
|
+
* - 防抖:等待触发停止后才执行(最后一次)
|
|
12
|
+
* - 节流:按固定节奏执行(每隔多久执行一次)
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const search = debounce((keyword: string) => {
|
|
16
|
+
* console.log('搜索:', keyword);
|
|
17
|
+
* });
|
|
18
|
+
* search('hello'); // 300ms 后执行
|
|
19
|
+
*/
|
|
20
|
+
export declare const debounce: <T extends (...args: any[]) => any>(fn: T, delay?: number) => (...args: Parameters<T>) => void;
|