@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.
Files changed (104) hide show
  1. package/AGENTS.md +58 -22
  2. package/dist/dom/index.d.ts +1 -0
  3. package/dist/dom/timeLog.d.ts +8 -0
  4. package/dist/function/index.d.ts +1 -0
  5. package/dist/function/loopUntil.d.ts +22 -0
  6. package/dist/hoc/index.d.ts +1 -0
  7. package/dist/hoc/withCache.d.ts +42 -0
  8. package/dist/index.d.ts +9 -0
  9. package/dist/index.js +2 -0
  10. package/dist/is/index.d.ts +5 -0
  11. package/dist/is/isFalsy.d.ts +9 -0
  12. package/dist/is/isNil.d.ts +9 -0
  13. package/dist/is/isObject.d.ts +8 -0
  14. package/dist/is/isPrimitive.d.ts +9 -0
  15. package/dist/is/isTruthy.d.ts +8 -0
  16. package/dist/lru-cache.d.ts +18 -0
  17. package/dist/network/fetcher.d.ts +56 -0
  18. package/dist/network/getRealURL.d.ts +2 -0
  19. package/dist/network/image.d.ts +59 -0
  20. package/dist/network/index.d.ts +4 -0
  21. package/dist/network/to.d.ts +9 -0
  22. package/dist/number/index.d.ts +1 -0
  23. package/dist/number/randomInt.d.ts +7 -0
  24. package/dist/object/index.d.ts +3 -0
  25. package/dist/object/mapKeys.d.ts +17 -0
  26. package/dist/object/mapValues.d.ts +21 -0
  27. package/dist/object/mergeObjects.d.ts +12 -0
  28. package/dist/string/case.d.ts +32 -0
  29. package/dist/string/compact.d.ts +22 -0
  30. package/dist/string/index.d.ts +2 -0
  31. package/dist/time/debounce.d.ts +20 -0
  32. package/dist/time/index.d.ts +3 -0
  33. package/dist/time/sleep.d.ts +7 -0
  34. package/dist/time/throttle.d.ts +20 -0
  35. package/docs/assets/highlight.css +92 -99
  36. package/docs/assets/navigation.js +1 -1
  37. package/docs/assets/search.js +1 -1
  38. package/docs/functions/camelToSnake.html +178 -178
  39. package/docs/functions/capitalize.html +178 -178
  40. package/docs/functions/compactStr.html +182 -182
  41. package/docs/functions/debounce.html +187 -187
  42. package/docs/functions/decapitalize.html +178 -178
  43. package/docs/functions/fetcher.html +189 -189
  44. package/docs/functions/getRealURL.html +175 -175
  45. package/docs/functions/imageUrlToBase64.html +191 -187
  46. package/docs/functions/isFalsy.html +178 -178
  47. package/docs/functions/isNil.html +178 -178
  48. package/docs/functions/isObject.html +178 -178
  49. package/docs/functions/isPrimitive.html +178 -178
  50. package/docs/functions/isTruthy.html +178 -178
  51. package/docs/functions/loopUntil.html +180 -180
  52. package/docs/functions/mapKeys.html +180 -180
  53. package/docs/functions/mapValues.html +182 -182
  54. package/docs/functions/mergeObjects.html +184 -184
  55. package/docs/functions/randomInt.html +178 -178
  56. package/docs/functions/sleep.html +179 -179
  57. package/docs/functions/snakeToCamel.html +178 -178
  58. package/docs/functions/throttle.html +187 -187
  59. package/docs/functions/timeLog.html +178 -178
  60. package/docs/functions/to.html +180 -180
  61. package/docs/functions/withCache.html +185 -185
  62. package/docs/modules.html +174 -174
  63. package/docs/types/BunFetchOptions.html +176 -0
  64. package/docs/types/CamelToSnake.html +174 -174
  65. package/docs/types/Capitalize.html +174 -174
  66. package/docs/types/Decapitalize.html +174 -174
  67. package/docs/types/DeepMapKeys.html +174 -174
  68. package/docs/types/DeepMapValues.html +174 -174
  69. package/docs/types/Falsy.html +174 -174
  70. package/docs/types/ImageCompressionOptions.html +188 -184
  71. package/docs/types/Primitive.html +174 -174
  72. package/docs/types/RequestInit.html +174 -174
  73. package/docs/types/SetTtl.html +174 -174
  74. package/docs/types/SnakeToCamel.html +174 -174
  75. package/package.json +2 -2
  76. package/src/dom/index.ts +1 -0
  77. package/src/function/index.ts +1 -0
  78. package/src/{function.ts → function/loopUntil.ts} +36 -36
  79. package/src/hoc/index.ts +1 -0
  80. package/src/{hoc.ts → hoc/withCache.ts} +117 -117
  81. package/src/is/index.ts +5 -0
  82. package/src/is/isFalsy.ts +12 -0
  83. package/src/is/isNil.ts +11 -0
  84. package/src/is/isObject.ts +10 -0
  85. package/src/is/isPrimitive.ts +23 -0
  86. package/src/is/isTruthy.ts +10 -0
  87. package/src/lru-cache.ts +50 -50
  88. package/src/network/fetcher.ts +1 -1
  89. package/src/network/index.ts +1 -1
  90. package/src/number/index.ts +1 -0
  91. package/src/object/index.ts +3 -0
  92. package/src/object/mapKeys.ts +50 -0
  93. package/src/object/mapValues.ts +77 -0
  94. package/src/object/mergeObjects.ts +50 -0
  95. package/src/time/debounce.ts +34 -0
  96. package/src/time/index.ts +3 -0
  97. package/src/time/sleep.ts +11 -0
  98. package/src/time/throttle.ts +34 -0
  99. package/.github/workflows/docs.yml +0 -39
  100. package/src/is.ts +0 -70
  101. package/src/object.ts +0 -179
  102. package/src/time.ts +0 -81
  103. /package/src/{dom.ts → dom/timeLog.ts} +0 -0
  104. /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 作为运行时和构建工具,发布到 npm 仓库 `@nickyzj2023/utils`。
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.ts # DOM 相关工具(timeLog)
26
- │ ├── function.ts # 函数控制工具(loopUntil)
27
- ├── hoc.ts # 高阶函数(withCache)
28
- │ ├── is.ts # 类型判断工具(isObject, isPrimitive, isFalsy, isTruthy, isNil)
29
- │ ├── lru-cache.ts # LRU 缓存实现
30
- ├── network.ts # 网络请求工具(fetcher, to, getRealURL)
31
- │ ├── number.ts # 数字工具(randomInt)
32
- │ ├── object.ts # 对象操作工具(mergeObjects, mapKeys, mapValues)
33
- ├── string.ts # 字符串工具(snakeToCamel, camelToSnake, capitalize, decapitalize, imageUrlToBase64, compactStr)
34
- └── time.ts # 时间控制工具(sleep, debounce, throttle)
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`, `imageUrlToBase64`, `compactStr` |
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. **依赖安全**: `sharp` 是原生依赖,需要确保其安全性
116
- 3. **网络请求**: `fetcher` 函数会解析 JSON 错误响应,注意潜在的安全风险
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` 功能依赖 `sharp` 库,需要 Node.js/Bun 原生环境支持
131
- - `fetcher` 函数基于 Fetch API,在 Bun 环境下使用 `BunFetchRequestInit` 类型
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,8 @@
1
+ /**
2
+ * 附带时间的 console.log
3
+ * @param args
4
+ *
5
+ * @example
6
+ * timeLog("Hello", "World"); // 14:30:00 Hello World
7
+ */
8
+ export declare const timeLog: (...args: any[]) => void;
@@ -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
+ };
@@ -0,0 +1,9 @@
1
+ export * from "./dom";
2
+ export * from "./function";
3
+ export * from "./hoc";
4
+ export * from "./is";
5
+ export * from "./network";
6
+ export * from "./number";
7
+ export * from "./object";
8
+ export * from "./string";
9
+ export * from "./time";
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,5 @@
1
+ export { type Falsy, isFalsy } from "./isFalsy";
2
+ export { isNil } from "./isNil";
3
+ export { isObject } from "./isObject";
4
+ export { isPrimitive, type Primitive } from "./isPrimitive";
5
+ export { isTruthy } from "./isTruthy";
@@ -0,0 +1,9 @@
1
+ export type Falsy = false | 0 | -0 | 0n | "" | null | undefined;
2
+ /**
3
+ * 检测传入的值是否为**假值**(false、0、''、null、undefined、NaN等)
4
+ *
5
+ * @example
6
+ * isFalsy(""); // true
7
+ * isFalsy(1); // false
8
+ */
9
+ export declare const isFalsy: (value: any) => value is Falsy;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 检测传入的值是否为**空值**(null、undefined)
3
+ *
4
+ * @example
5
+ * isNil(null); // true
6
+ * isNil(undefined); // true
7
+ * isNil(1); // false
8
+ */
9
+ export declare const isNil: (value: any) => value is null | undefined;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * 检测传入的值是否为**普通对象**
3
+ *
4
+ * @example
5
+ * const obj = { a: 1 };
6
+ * isObject(obj); // true
7
+ */
8
+ export declare const isObject: (value: any) => value is Record<string, any>;
@@ -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,8 @@
1
+ /**
2
+ * 检测传入的值是否为**真值**
3
+ *
4
+ * @example
5
+ * isTruthy(1); // true
6
+ * isTruthy(""); // false
7
+ */
8
+ export declare const isTruthy: (value: any) => value is any;
@@ -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,2 @@
1
+ /** 从 url 响应头获取真实链接 */
2
+ export declare const getRealURL: (originURL: string) => Promise<string>;
@@ -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,4 @@
1
+ export { type BunFetchOptions, fetcher, type RequestInit } from "./fetcher";
2
+ export { getRealURL } from "./getRealURL";
3
+ export { type ImageCompressionOptions, imageUrlToBase64 } from "./image";
4
+ export { to } from "./to";
@@ -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,7 @@
1
+ /**
2
+ * 在指定闭区间内生成随机整数
3
+ *
4
+ * @example
5
+ * randomInt(1, 10); // 1 <= x <= 10
6
+ */
7
+ export declare const randomInt: (min: number, max: number) => number;
@@ -0,0 +1,3 @@
1
+ export { type DeepMapKeys, mapKeys } from "./mapKeys";
2
+ export { type DeepMapValues, mapValues } from "./mapValues";
3
+ export { mergeObjects } from "./mergeObjects";
@@ -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,2 @@
1
+ export { type CamelToSnake, type Capitalize, camelToSnake, capitalize, type Decapitalize, decapitalize, type SnakeToCamel, snakeToCamel, } from "./case";
2
+ export { compactStr } from "./compact";
@@ -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;
@@ -0,0 +1,3 @@
1
+ export { debounce } from "./debounce";
2
+ export { sleep } from "./sleep";
3
+ export { throttle } from "./throttle";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * 延迟一段时间再执行后续代码
3
+ * @param time 延迟时间,默认 150ms
4
+ * @example
5
+ * await sleep(1000); // 等待 1 秒执行后续代码
6
+ */
7
+ export declare const sleep: (time?: number) => Promise<unknown>;