vanilla-jui 1.6.6 → 1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vanilla-jui",
3
- "version": "1.6.6",
3
+ "version": "1.7.0",
4
4
  "private": false,
5
5
  "description": "A lightweight, reactive, and fully customizable vanilla JS UI library.",
6
6
  "keywords": [
@@ -55,3 +55,76 @@ export function randomId(length: number = 8): string {
55
55
 
56
56
  return base64.substring(0, length).replace(/\+/g, '-').replace(/\//g, '_');
57
57
  }
58
+
59
+ /**
60
+ * 查询参数值类型
61
+ */
62
+ type QueryParamValue =
63
+ | string
64
+ | number
65
+ | boolean
66
+ | null
67
+ | undefined
68
+ | QueryParamValue[]
69
+ | { [key: string]: QueryParamValue };
70
+
71
+ /**
72
+ * 查询参数对象类型
73
+ */
74
+ type QueryParams = Record<string, QueryParamValue>;
75
+
76
+ /**
77
+ * 对查询参数进行 SHA-256 哈希编码,生成用于缓存的 key
78
+ *
79
+ * @param params - 查询参数对象
80
+ * @param bytes - 取哈希前 N 字节,默认为 8,范围 1-32
81
+ * @returns 36 进制哈希字符串
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * const key = await hashQueryParams({ page: 1, sort: 'desc' });
86
+ * // 返回: "2k7x9f3m4n5p"
87
+ * ```
88
+ */
89
+ export async function hashQueryParams(
90
+ params: QueryParams,
91
+ bytes: number = 8
92
+ ): Promise<string> {
93
+ // 1. 参数验证
94
+ if (typeof params !== 'object' || params === null) {
95
+ throw new TypeError('params must be a non-null object');
96
+ }
97
+
98
+ if (bytes < 1 || bytes > 32) {
99
+ throw new RangeError('bytes must be between 1 and 32');
100
+ }
101
+
102
+ // 2. 排序并规范化参数
103
+ const normalized: QueryParams = {};
104
+ const sortedKeys = Object.keys(params).sort();
105
+
106
+ for (const key of sortedKeys) {
107
+ const value = params[key];
108
+ // 字符串 trim 处理
109
+ normalized[key] = typeof value === 'string' ? value.trim() : value;
110
+ }
111
+
112
+ // 3. 序列化
113
+ const str = JSON.stringify(normalized);
114
+ const buffer = new TextEncoder().encode(str);
115
+
116
+ // 4. SHA-256 哈希
117
+ const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
118
+
119
+ // 5. 取前 N 字节(防越界)
120
+ const safeBytes = Math.min(bytes, hashBuffer.byteLength);
121
+ const slice = new Uint8Array(hashBuffer, 0, safeBytes);
122
+
123
+ // 6. 转为 BigInt 再转 36 进制
124
+ let num = 0n;
125
+ for (const byte of slice) {
126
+ num = (num << 8n) | BigInt(byte);
127
+ }
128
+
129
+ return num.toString(36);
130
+ }