a2bei4-utils 1.0.2 → 1.0.4

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 (62) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +2 -2
  3. package/dist/a2bei4.utils.cjs.js +2080 -1846
  4. package/dist/a2bei4.utils.cjs.js.map +1 -1
  5. package/dist/a2bei4.utils.cjs.min.js +1 -1
  6. package/dist/a2bei4.utils.cjs.min.js.map +1 -1
  7. package/dist/a2bei4.utils.esm.js +2073 -1843
  8. package/dist/a2bei4.utils.esm.js.map +1 -1
  9. package/dist/a2bei4.utils.esm.min.js +1 -1
  10. package/dist/a2bei4.utils.esm.min.js.map +1 -1
  11. package/dist/a2bei4.utils.umd.js +2080 -1846
  12. package/dist/a2bei4.utils.umd.js.map +1 -1
  13. package/dist/a2bei4.utils.umd.min.js +1 -1
  14. package/dist/a2bei4.utils.umd.min.js.map +1 -1
  15. package/dist/arr.cjs +27 -27
  16. package/dist/arr.cjs.map +1 -1
  17. package/dist/arr.js +27 -27
  18. package/dist/arr.js.map +1 -1
  19. package/dist/audio.cjs +274 -274
  20. package/dist/audio.cjs.map +1 -1
  21. package/dist/audio.js +274 -274
  22. package/dist/audio.js.map +1 -1
  23. package/dist/browser.cjs +52 -52
  24. package/dist/browser.cjs.map +1 -1
  25. package/dist/browser.js +52 -52
  26. package/dist/browser.js.map +1 -1
  27. package/dist/common.cjs +369 -369
  28. package/dist/common.cjs.map +1 -1
  29. package/dist/common.js +369 -369
  30. package/dist/common.js.map +1 -1
  31. package/dist/date.cjs +421 -188
  32. package/dist/date.cjs.map +1 -1
  33. package/dist/date.js +414 -185
  34. package/dist/date.js.map +1 -1
  35. package/dist/download.cjs +102 -102
  36. package/dist/download.cjs.map +1 -1
  37. package/dist/download.js +102 -102
  38. package/dist/download.js.map +1 -1
  39. package/dist/evt.cjs +148 -148
  40. package/dist/evt.cjs.map +1 -1
  41. package/dist/evt.js +148 -148
  42. package/dist/evt.js.map +1 -1
  43. package/dist/id.cjs +68 -68
  44. package/dist/id.cjs.map +1 -1
  45. package/dist/id.js +68 -68
  46. package/dist/id.js.map +1 -1
  47. package/dist/timer.cjs +51 -50
  48. package/dist/timer.cjs.map +1 -1
  49. package/dist/timer.js +51 -50
  50. package/dist/timer.js.map +1 -1
  51. package/dist/tree.cjs +165 -165
  52. package/dist/tree.cjs.map +1 -1
  53. package/dist/tree.js +165 -165
  54. package/dist/tree.js.map +1 -1
  55. package/dist/webSocket.cjs +403 -403
  56. package/dist/webSocket.cjs.map +1 -1
  57. package/dist/webSocket.js +403 -403
  58. package/dist/webSocket.js.map +1 -1
  59. package/package.json +1 -1
  60. package/readme.txt +21 -11
  61. package/types/date.d.ts +243 -45
  62. package/types/index.d.ts +244 -47
@@ -1,1866 +1,2096 @@
1
- /**
2
- * 使用 Fisher-Yates 算法对数组 **原地** 随机乱序。
3
- * @template T
4
- * @param {T[]} arr - 要乱序的数组
5
- * @returns {T[]} 返回传入的同一数组实例(已乱序)
6
- */
7
- function shuffle(arr) {
8
- // 方式一:
9
- // arr.sort(() => Math.random() - 0.5);
10
- // 方式二:
11
- for (let i = arr.length - 1; i > 0; i--) {
12
- const j = Math.floor(Math.random() * (i + 1));
13
- [arr[i], arr[j]] = [arr[j], arr[i]];
14
- }
15
- return arr;
1
+ /**
2
+ * 使用 Fisher-Yates 算法对数组 **原地** 随机乱序。
3
+ * @template T
4
+ * @param {T[]} arr - 要乱序的数组
5
+ * @returns {T[]} 返回传入的同一数组实例(已乱序)
6
+ */
7
+ function shuffle(arr) {
8
+ // 方式一:
9
+ // arr.sort(() => Math.random() - 0.5);
10
+ // 方式二:
11
+ for (let i = arr.length - 1; i > 0; i--) {
12
+ const j = Math.floor(Math.random() * (i + 1));
13
+ [arr[i], arr[j]] = [arr[j], arr[i]];
14
+ }
15
+ return arr;
16
+ }
17
+
18
+ /**
19
+ * 将数组中的元素从 `fromIndex` 移动到 `toIndex`,**原地** 修改并返回该数组。
20
+ * @template T
21
+ * @param {T[]} arr - 要操作的数组
22
+ * @param {number} fromIndex - 原始下标
23
+ * @param {number} toIndex - 目标下标
24
+ * @returns {T[]} 返回传入的同一数组实例
25
+ */
26
+ function moveItem(arr, fromIndex, toIndex) {
27
+ arr.splice(toIndex, 0, arr.splice(fromIndex, 1)[0]);
16
28
  }
17
29
 
18
- /**
19
- * 将数组中的元素从 `fromIndex` 移动到 `toIndex`,**原地** 修改并返回该数组。
20
- * @template T
21
- * @param {T[]} arr - 要操作的数组
22
- * @param {number} fromIndex - 原始下标
23
- * @param {number} toIndex - 目标下标
24
- * @returns {T[]} 返回传入的同一数组实例
25
- */
26
- function moveItem(arr, fromIndex, toIndex) {
27
- arr.splice(toIndex, 0, arr.splice(fromIndex, 1)[0]);
30
+ const AudioStreamResamplerProcessorCode = `
31
+ class AudioStreamResamplerProcessor extends AudioWorkletProcessor {
32
+ constructor(options) {
33
+ super();
34
+ const config = options.processorOptions || {};
35
+ this.targetSampleRate = config.targetSampleRate || 16000;
36
+ this.sourceSampleRate = sampleRate;
37
+ this.downsampleRatio = this.sourceSampleRate / this.targetSampleRate;
38
+
39
+ // 16000Hz 用 60ms chunk (960 samples),其他用 1024
40
+ this.chunkSize = this.targetSampleRate === 16000 ? 960 : 1024;
41
+
42
+ const sourceBufferSize = config.sourceBufferSize || 16384; // ~340ms @48kHz
43
+ const pcmBufferSize = config.pcmBufferSize || (this.chunkSize * 10); // 更大缓冲,减少溢出概率
44
+
45
+ this.sourceBuffer = new Float32Array(sourceBufferSize);
46
+ this.sourceBufferLength = 0;
47
+
48
+ this.pcmBuffer = new Int16Array(pcmBufferSize);
49
+ this.pcmBufferIndex = 0;
50
+ }
51
+
52
+ process(inputs, outputs, parameters) {
53
+ const input = inputs[0];
54
+ if (!input || input.length === 0 || input[0].length === 0) return true;
55
+ const inputChannel = input[0];
56
+
57
+ // 1. 写入源缓冲区(溢出时覆盖最旧数据)
58
+ const newLength = this.sourceBufferLength + inputChannel.length;
59
+ if (newLength > this.sourceBuffer.length) {
60
+ const overflow = newLength - this.sourceBuffer.length;
61
+ this.sourceBuffer.copyWithin(0, overflow);
62
+ this.sourceBufferLength = this.sourceBuffer.length - inputChannel.length;
63
+ }
64
+ this.sourceBuffer.set(inputChannel, this.sourceBufferLength);
65
+ this.sourceBufferLength += inputChannel.length;
66
+
67
+ // 2. 计算可降采样样本数
68
+ const availableOutputSamples = Math.floor(this.sourceBufferLength / this.downsampleRatio);
69
+ if (availableOutputSamples === 0) return true;
70
+
71
+ // 3. 线性插值降采样
72
+ const downsampled = new Float32Array(availableOutputSamples);
73
+ for (let i = 0; i < availableOutputSamples; i++) {
74
+ const srcIndex = i * this.downsampleRatio;
75
+ const srcIndexInt = Math.floor(srcIndex);
76
+ const fraction = srcIndex - srcIndexInt;
77
+ const val0 = this.sourceBuffer[srcIndexInt];
78
+ const val1 = srcIndexInt + 1 < this.sourceBufferLength ? this.sourceBuffer[srcIndexInt + 1] : val0;
79
+ downsampled[i] = val0 + (val1 - val0) * fraction;
80
+ }
81
+
82
+ // 4. Float32 → Int16 PCM
83
+ const pcmData = this.floatTo16BitPCM(downsampled);
84
+
85
+ // 5. 写入 PCM 缓冲区(空间不足时直接覆盖最旧,缓冲区足够大基本不会触发)
86
+ if (this.pcmBufferIndex + pcmData.length > this.pcmBuffer.length) {
87
+ // 简单策略:从头覆盖(丢弃最旧数据)
88
+ this.pcmBufferIndex = 0;
89
+ }
90
+ this.pcmBuffer.set(pcmData, this.pcmBufferIndex);
91
+ this.pcmBufferIndex += pcmData.length;
92
+
93
+ // 6. 发送所有完整的 chunk(关键:复制到新数组再转移)
94
+ while (this.pcmBufferIndex >= this.chunkSize) {
95
+ // 方法1:推荐,使用 slice(隐式复制到新 ArrayBuffer)
96
+ const chunk = this.pcmBuffer.slice(0, this.chunkSize);
97
+
98
+ // 方法2:等价写法
99
+ // const chunk = new Int16Array(this.pcmBuffer.subarray(0, this.chunkSize));
100
+
101
+ this.port.postMessage(chunk, [chunk.buffer]); // 转移新缓冲区,安全!
102
+
103
+ // 移动剩余数据到开头
104
+ this.pcmBuffer.copyWithin(0, this.chunkSize, this.pcmBufferIndex);
105
+ this.pcmBufferIndex -= this.chunkSize;
106
+ }
107
+
108
+ // 7. 清理已消费的源数据
109
+ const consumedSrc = Math.floor(availableOutputSamples * this.downsampleRatio + 0.5); // 四舍五入更准
110
+ if (consumedSrc > 0) {
111
+ this.sourceBuffer.copyWithin(0, consumedSrc, this.sourceBufferLength);
112
+ this.sourceBufferLength -= consumedSrc;
113
+ }
114
+
115
+ return true;
116
+ }
117
+
118
+ floatTo16BitPCM(input) {
119
+ const output = new Int16Array(input.length);
120
+ for (let i = 0; i < input.length; i++) {
121
+ const s = Math.max(-1, Math.min(1, input[i]));
122
+ output[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
123
+ }
124
+ return output;
125
+ }
126
+ }
127
+
128
+ registerProcessor('audio-stream-resampler-processor', AudioStreamResamplerProcessor);
129
+ `;
130
+
131
+ /**
132
+ * 浏览器端实时音频流重采样器。
133
+ * 基于 AudioWorklet 将麦克风/媒体流转换为 16 kHz、16-bit、单声道 PCM,
134
+ * 并通过回调逐块输出,可选保存完整 PCM 用于后续合并。
135
+ */
136
+ class AudioStreamResampler {
137
+ /**
138
+ * @param {object} config
139
+ * @param {function(Int16Array)} config.onData - 收到一个 chunk PCM 数据的回调
140
+ * @param {function(string, string)} [config.onStateChange] - 状态变化回调
141
+ * @param {object} [config.processorOptions] - 传递给 AudioWorklet 的选项
142
+ * @param {boolean} [config.saveFullPcm=false] - 是否在内部保存所有 PCM 用于 stop 时合并(长时间录音建议关闭)
143
+ */
144
+ constructor(config) {
145
+ this.onData = config.onData || (() => {});
146
+ this.onStateChange = config.onStateChange || (() => {});
147
+ this.processorOptions = config.processorOptions || {};
148
+ this.saveFullPcm = config.saveFullPcm ?? false;
149
+
150
+ this.audioContext = null;
151
+ this.workletNode = null;
152
+ this.source = null;
153
+ this.workletUrl = null;
154
+ this.fullPcmData = this.saveFullPcm ? [] : null;
155
+
156
+ this.isInitialized = false;
157
+ this.isProcessing = false;
158
+ }
159
+
160
+ /**
161
+ * 初始化 AudioContext 并加载 AudioWorklet。
162
+ * 完成后状态变为 `"ready"`。
163
+ */
164
+ async init() {
165
+ this.onStateChange("initializing", "正在初始化音频环境...");
166
+ try {
167
+ this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
168
+
169
+ const blob = new Blob([AudioStreamResamplerProcessorCode], { type: "application/javascript" });
170
+ this.workletUrl = URL.createObjectURL(blob);
171
+ await this.audioContext.audioWorklet.addModule(this.workletUrl);
172
+
173
+ this.workletNode = new AudioWorkletNode(this.audioContext, "audio-stream-resampler-processor", {
174
+ processorOptions: this.processorOptions
175
+ });
176
+
177
+ this.workletNode.port.onmessage = (event) => {
178
+ const chunk = event.data; // Int16Array
179
+ this.onData(chunk);
180
+ if (this.saveFullPcm) {
181
+ this.fullPcmData.push(chunk);
182
+ }
183
+ };
184
+
185
+ this.isInitialized = true;
186
+ this.onStateChange("ready", "音频环境已就绪");
187
+ } catch (err) {
188
+ console.error("AudioStreamResampler init error:", err);
189
+ this.onStateChange("error", `初始化失败: ${err.message}`);
190
+ }
191
+ }
192
+
193
+ /**
194
+ * 绑定媒体流,开始实时处理。
195
+ * @param {MediaStream} stream - 通过 getUserMedia 或其他方式获得的流
196
+ */
197
+ setMediaStream(stream) {
198
+ if (!this.isInitialized) {
199
+ console.error("请先调用 init()");
200
+ return;
201
+ }
202
+
203
+ if (this.source) {
204
+ this.source.disconnect();
205
+ }
206
+
207
+ this.source = this.audioContext.createMediaStreamSource(stream);
208
+ this.source.connect(this.workletNode);
209
+ // workletNode 默认连接到 destination,可选断开以静音
210
+ // this.workletNode.connect(this.audioContext.destination);
211
+
212
+ this.isProcessing = true;
213
+ this.onStateChange("processing", "正在处理音频流...");
214
+ }
215
+
216
+ /**
217
+ * 停止处理并释放资源。
218
+ * @param {(fullPcm: Int16Array) => void} [callback] - 若构造时 `saveFullPcm=true`,会把合并后的完整 PCM 通过此回调传出
219
+ */
220
+ stop(callback) {
221
+ if (!this.isProcessing) return;
222
+
223
+ this.onStateChange("stopping", "正在停止...");
224
+
225
+ if (this.source) {
226
+ this.source.disconnect();
227
+ this.source = null;
228
+ }
229
+
230
+ this._cleanup();
231
+
232
+ this.onStateChange("stopped", "已停止");
233
+
234
+ if (this.saveFullPcm && callback && typeof callback === "function") {
235
+ const totalLength = this.fullPcmData.reduce((sum, chunk) => sum + chunk.length, 0);
236
+ const combined = new Int16Array(totalLength);
237
+ let offset = 0;
238
+ for (const chunk of this.fullPcmData) {
239
+ combined.set(chunk, offset);
240
+ offset += chunk.length;
241
+ }
242
+ callback(combined);
243
+ }
244
+ }
245
+
246
+ _cleanup() {
247
+ if (this.workletNode) {
248
+ this.workletNode.disconnect();
249
+ this.workletNode.port.close();
250
+ this.workletNode = null;
251
+ }
252
+ if (this.audioContext && this.audioContext.state !== "closed") {
253
+ this.audioContext.close();
254
+ this.audioContext = null;
255
+ }
256
+ if (this.workletUrl) {
257
+ URL.revokeObjectURL(this.workletUrl);
258
+ this.workletUrl = null;
259
+ }
260
+
261
+ this.isProcessing = false;
262
+ this.isInitialized = false;
263
+ if (this.fullPcmData) {
264
+ this.fullPcmData.length = 0;
265
+ }
266
+ }
267
+ }
268
+
269
+ /**
270
+ * 将 16-bit 单声道 PCM 数据封装成标准 WAV Blob。
271
+ *
272
+ * @param {Int16Array} pcmData - PCM 采样数据
273
+ * @param {number} [sampleRate=16000] - 采样率,默认 16 kHz
274
+ * @returns {Blob} audio/wav Blob
275
+ */
276
+ function pcmToWavBlob(pcmData, sampleRate = 16000) {
277
+ const length = pcmData.length;
278
+ const buffer = new ArrayBuffer(44 + length * 2);
279
+ const view = new DataView(buffer);
280
+ const writeString = (offset, string) => {
281
+ for (let i = 0; i < string.length; i++) {
282
+ view.setUint8(offset + i, string.charCodeAt(i));
283
+ }
284
+ };
285
+ writeString(0, "RIFF");
286
+ view.setUint32(4, 36 + length * 2, true);
287
+ writeString(8, "WAVE");
288
+ writeString(12, "fmt ");
289
+ view.setUint32(16, 16, true);
290
+ view.setUint16(20, 1, true);
291
+ view.setUint16(22, 1, true);
292
+ view.setUint32(24, sampleRate, true);
293
+ view.setUint32(28, sampleRate * 2, true);
294
+ view.setUint16(32, 2, true);
295
+ view.setUint16(34, 16, true);
296
+ writeString(36, "data");
297
+ view.setUint32(40, length * 2, true);
298
+ let offset = 44;
299
+ for (let i = 0; i < length; i++) {
300
+ view.setInt16(offset, pcmData[i], true);
301
+ offset += 2;
302
+ }
303
+ return new Blob([buffer], { type: "audio/wav" });
28
304
  }
29
305
 
30
- const AudioStreamResamplerProcessorCode = `
31
- class AudioStreamResamplerProcessor extends AudioWorkletProcessor {
32
- constructor(options) {
33
- super();
34
- const config = options.processorOptions || {};
35
- this.targetSampleRate = config.targetSampleRate || 16000;
36
- this.sourceSampleRate = sampleRate;
37
- this.downsampleRatio = this.sourceSampleRate / this.targetSampleRate;
38
-
39
- // 16000Hz 用 60ms chunk (960 samples),其他用 1024
40
- this.chunkSize = this.targetSampleRate === 16000 ? 960 : 1024;
41
-
42
- const sourceBufferSize = config.sourceBufferSize || 16384; // ~340ms @48kHz
43
- const pcmBufferSize = config.pcmBufferSize || (this.chunkSize * 10); // 更大缓冲,减少溢出概率
44
-
45
- this.sourceBuffer = new Float32Array(sourceBufferSize);
46
- this.sourceBufferLength = 0;
47
-
48
- this.pcmBuffer = new Int16Array(pcmBufferSize);
49
- this.pcmBufferIndex = 0;
50
- }
51
-
52
- process(inputs, outputs, parameters) {
53
- const input = inputs[0];
54
- if (!input || input.length === 0 || input[0].length === 0) return true;
55
- const inputChannel = input[0];
56
-
57
- // 1. 写入源缓冲区(溢出时覆盖最旧数据)
58
- const newLength = this.sourceBufferLength + inputChannel.length;
59
- if (newLength > this.sourceBuffer.length) {
60
- const overflow = newLength - this.sourceBuffer.length;
61
- this.sourceBuffer.copyWithin(0, overflow);
62
- this.sourceBufferLength = this.sourceBuffer.length - inputChannel.length;
63
- }
64
- this.sourceBuffer.set(inputChannel, this.sourceBufferLength);
65
- this.sourceBufferLength += inputChannel.length;
66
-
67
- // 2. 计算可降采样样本数
68
- const availableOutputSamples = Math.floor(this.sourceBufferLength / this.downsampleRatio);
69
- if (availableOutputSamples === 0) return true;
70
-
71
- // 3. 线性插值降采样
72
- const downsampled = new Float32Array(availableOutputSamples);
73
- for (let i = 0; i < availableOutputSamples; i++) {
74
- const srcIndex = i * this.downsampleRatio;
75
- const srcIndexInt = Math.floor(srcIndex);
76
- const fraction = srcIndex - srcIndexInt;
77
- const val0 = this.sourceBuffer[srcIndexInt];
78
- const val1 = srcIndexInt + 1 < this.sourceBufferLength ? this.sourceBuffer[srcIndexInt + 1] : val0;
79
- downsampled[i] = val0 + (val1 - val0) * fraction;
80
- }
81
-
82
- // 4. Float32 → Int16 PCM
83
- const pcmData = this.floatTo16BitPCM(downsampled);
84
-
85
- // 5. 写入 PCM 缓冲区(空间不足时直接覆盖最旧,缓冲区足够大基本不会触发)
86
- if (this.pcmBufferIndex + pcmData.length > this.pcmBuffer.length) {
87
- // 简单策略:从头覆盖(丢弃最旧数据)
88
- this.pcmBufferIndex = 0;
89
- }
90
- this.pcmBuffer.set(pcmData, this.pcmBufferIndex);
91
- this.pcmBufferIndex += pcmData.length;
92
-
93
- // 6. 发送所有完整的 chunk(关键:复制到新数组再转移)
94
- while (this.pcmBufferIndex >= this.chunkSize) {
95
- // 方法1:推荐,使用 slice(隐式复制到新 ArrayBuffer)
96
- const chunk = this.pcmBuffer.slice(0, this.chunkSize);
97
-
98
- // 方法2:等价写法
99
- // const chunk = new Int16Array(this.pcmBuffer.subarray(0, this.chunkSize));
100
-
101
- this.port.postMessage(chunk, [chunk.buffer]); // 转移新缓冲区,安全!
102
-
103
- // 移动剩余数据到开头
104
- this.pcmBuffer.copyWithin(0, this.chunkSize, this.pcmBufferIndex);
105
- this.pcmBufferIndex -= this.chunkSize;
106
- }
107
-
108
- // 7. 清理已消费的源数据
109
- const consumedSrc = Math.floor(availableOutputSamples * this.downsampleRatio + 0.5); // 四舍五入更准
110
- if (consumedSrc > 0) {
111
- this.sourceBuffer.copyWithin(0, consumedSrc, this.sourceBufferLength);
112
- this.sourceBufferLength -= consumedSrc;
113
- }
114
-
115
- return true;
116
- }
117
-
118
- floatTo16BitPCM(input) {
119
- const output = new Int16Array(input.length);
120
- for (let i = 0; i < input.length; i++) {
121
- const s = Math.max(-1, Math.min(1, input[i]));
122
- output[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
123
- }
124
- return output;
125
- }
126
- }
127
-
128
- registerProcessor('audio-stream-resampler-processor', AudioStreamResamplerProcessor);
129
- `;
130
-
131
- /**
132
- * 浏览器端实时音频流重采样器。
133
- * 基于 AudioWorklet 将麦克风/媒体流转换为 16 kHz、16-bit、单声道 PCM,
134
- * 并通过回调逐块输出,可选保存完整 PCM 用于后续合并。
135
- */
136
- class AudioStreamResampler {
137
- /**
138
- * @param {object} config
139
- * @param {function(Int16Array)} config.onData - 收到一个 chunk PCM 数据的回调
140
- * @param {function(string, string)} [config.onStateChange] - 状态变化回调
141
- * @param {object} [config.processorOptions] - 传递给 AudioWorklet 的选项
142
- * @param {boolean} [config.saveFullPcm=false] - 是否在内部保存所有 PCM 用于 stop 时合并(长时间录音建议关闭)
143
- */
144
- constructor(config) {
145
- this.onData = config.onData || (() => {});
146
- this.onStateChange = config.onStateChange || (() => {});
147
- this.processorOptions = config.processorOptions || {};
148
- this.saveFullPcm = config.saveFullPcm ?? false;
149
-
150
- this.audioContext = null;
151
- this.workletNode = null;
152
- this.source = null;
153
- this.workletUrl = null;
154
- this.fullPcmData = this.saveFullPcm ? [] : null;
155
-
156
- this.isInitialized = false;
157
- this.isProcessing = false;
158
- }
159
-
160
- /**
161
- * 初始化 AudioContext 并加载 AudioWorklet。
162
- * 完成后状态变为 `"ready"`。
163
- */
164
- async init() {
165
- this.onStateChange("initializing", "正在初始化音频环境...");
166
- try {
167
- this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
168
-
169
- const blob = new Blob([AudioStreamResamplerProcessorCode], { type: "application/javascript" });
170
- this.workletUrl = URL.createObjectURL(blob);
171
- await this.audioContext.audioWorklet.addModule(this.workletUrl);
172
-
173
- this.workletNode = new AudioWorkletNode(this.audioContext, "audio-stream-resampler-processor", {
174
- processorOptions: this.processorOptions
175
- });
176
-
177
- this.workletNode.port.onmessage = (event) => {
178
- const chunk = event.data; // Int16Array
179
- this.onData(chunk);
180
- if (this.saveFullPcm) {
181
- this.fullPcmData.push(chunk);
182
- }
183
- };
184
-
185
- this.isInitialized = true;
186
- this.onStateChange("ready", "音频环境已就绪");
187
- } catch (err) {
188
- console.error("AudioStreamResampler init error:", err);
189
- this.onStateChange("error", `初始化失败: ${err.message}`);
190
- }
191
- }
192
-
193
- /**
194
- * 绑定媒体流,开始实时处理。
195
- * @param {MediaStream} stream - 通过 getUserMedia 或其他方式获得的流
196
- */
197
- setMediaStream(stream) {
198
- if (!this.isInitialized) {
199
- console.error("请先调用 init()");
200
- return;
201
- }
202
-
203
- if (this.source) {
204
- this.source.disconnect();
205
- }
206
-
207
- this.source = this.audioContext.createMediaStreamSource(stream);
208
- this.source.connect(this.workletNode);
209
- // workletNode 默认连接到 destination,可选断开以静音
210
- // this.workletNode.connect(this.audioContext.destination);
211
-
212
- this.isProcessing = true;
213
- this.onStateChange("processing", "正在处理音频流...");
214
- }
215
-
216
- /**
217
- * 停止处理并释放资源。
218
- * @param {(fullPcm: Int16Array) => void} [callback] - 若构造时 `saveFullPcm=true`,会把合并后的完整 PCM 通过此回调传出
219
- */
220
- stop(callback) {
221
- if (!this.isProcessing) return;
222
-
223
- this.onStateChange("stopping", "正在停止...");
224
-
225
- if (this.source) {
226
- this.source.disconnect();
227
- this.source = null;
228
- }
229
-
230
- this._cleanup();
231
-
232
- this.onStateChange("stopped", "已停止");
233
-
234
- if (this.saveFullPcm && callback && typeof callback === "function") {
235
- const totalLength = this.fullPcmData.reduce((sum, chunk) => sum + chunk.length, 0);
236
- const combined = new Int16Array(totalLength);
237
- let offset = 0;
238
- for (const chunk of this.fullPcmData) {
239
- combined.set(chunk, offset);
240
- offset += chunk.length;
241
- }
242
- callback(combined);
243
- }
244
- }
245
-
246
- _cleanup() {
247
- if (this.workletNode) {
248
- this.workletNode.disconnect();
249
- this.workletNode.port.close();
250
- this.workletNode = null;
251
- }
252
- if (this.audioContext && this.audioContext.state !== "closed") {
253
- this.audioContext.close();
254
- this.audioContext = null;
255
- }
256
- if (this.workletUrl) {
257
- URL.revokeObjectURL(this.workletUrl);
258
- this.workletUrl = null;
259
- }
260
-
261
- this.isProcessing = false;
262
- this.isInitialized = false;
263
- if (this.fullPcmData) {
264
- this.fullPcmData.length = 0;
265
- }
266
- }
267
- }
268
-
269
- /**
270
- * 将 16-bit 单声道 PCM 数据封装成标准 WAV Blob。
271
- *
272
- * @param {Int16Array} pcmData - PCM 采样数据
273
- * @param {number} [sampleRate=16000] - 采样率,默认 16 kHz
274
- * @returns {Blob} audio/wav Blob
275
- */
276
- function pcmToWavBlob(pcmData, sampleRate = 16000) {
277
- const length = pcmData.length;
278
- const buffer = new ArrayBuffer(44 + length * 2);
279
- const view = new DataView(buffer);
280
- const writeString = (offset, string) => {
281
- for (let i = 0; i < string.length; i++) {
282
- view.setUint8(offset + i, string.charCodeAt(i));
283
- }
284
- };
285
- writeString(0, "RIFF");
286
- view.setUint32(4, 36 + length * 2, true);
287
- writeString(8, "WAVE");
288
- writeString(12, "fmt ");
289
- view.setUint32(16, 16, true);
290
- view.setUint16(20, 1, true);
291
- view.setUint16(22, 1, true);
292
- view.setUint32(24, sampleRate, true);
293
- view.setUint32(28, sampleRate * 2, true);
294
- view.setUint16(32, 2, true);
295
- view.setUint16(34, 16, true);
296
- writeString(36, "data");
297
- view.setUint32(40, length * 2, true);
298
- let offset = 44;
299
- for (let i = 0; i < length; i++) {
300
- view.setInt16(offset, pcmData[i], true);
301
- offset += 2;
302
- }
303
- return new Blob([buffer], { type: "audio/wav" });
304
- }
305
-
306
- /**
307
- * 视口尺寸对象。
308
- * @typedef {Object} ViewportDimensions
309
- * @property {number} w 视口宽度,单位像素。
310
- * @property {number} h 视口高度,单位像素。
311
- */
312
-
313
- /**
314
- * 获取当前视口(viewport)的宽高。
315
- *
316
- * 兼容策略:
317
- * 1. 优先使用 `window.innerWidth/innerHeight`(现代浏览器)。
318
- * 2. 降级到 `document.documentElement.clientWidth/clientHeight`(IE9+ 及怪异模式)。
319
- * 3. 最后降级到 `document.body.clientWidth/clientHeight`(IE6-8 怪异模式)。
320
- *
321
- * @returns {ViewportDimensions} 包含 `w`(宽度)和 `h`(高度)的对象,单位为像素。
322
- *
323
- * @example
324
- * const { w, h } = getViewportSize();
325
- * console.log(`视口尺寸:${w} × ${h}`);
326
- */
327
- function getViewportSize() {
328
- const d = document,
329
- root = d.documentElement,
330
- body = d.body;
331
-
332
- return {
333
- w: window.innerWidth || root.clientWidth || body.clientWidth,
334
- h: window.innerHeight || root.clientHeight || body.clientHeight
335
- };
336
- }
337
-
338
- /**
339
- * 将当前页面 URL 的 query 部分解析成键值对对象。
340
- *
341
- * @returns {Record<string, string>} 所有查询参数组成的平凡对象
342
- * (同名 key 仅保留最后一项)
343
- */
344
- function getAllSearchParams() {
345
- const urlSearchParams = new URLSearchParams(location.search);
346
- return Object.fromEntries(urlSearchParams.entries());
347
- }
348
-
349
- /**
350
- * 根据 key 获取当前页面 URL 中的单个查询参数。
351
- *
352
- * @param {string} key - 要提取的参数名
353
- * @returns {string | undefined} 对应参数值;不存在时返回 `undefined`
354
- */
355
- function getSearchParam(key) {
356
- const params = getAllSearchParams();
357
- return params[key];
358
- }
359
-
360
- //#region 数据类型判断
361
-
362
- /**
363
- * 返回任意值的运行时类型字符串(小写形式)。
364
- *
365
- * @param {*} obj 待检测的值
366
- * @returns {keyof globalThis|"blob"|"file"|"formdata"|string} 小写类型名
367
- */
368
- function getDataType(obj) {
369
- return Object.prototype.toString
370
- .call(obj)
371
- .replace(/^\[object\s(\w+)\]$/, "$1")
372
- .toLowerCase();
373
- }
374
-
375
- /**
376
- * 判断值是否为原生 Blob(含 File)。
377
- *
378
- * @param {*} obj - 待检测的值
379
- * @returns {obj is Blob}
380
- */
381
- function isBlob(obj) {
382
- return getDataType(obj) === "blob";
383
- }
384
-
385
- /**
386
- * 判断值是否为**纯粹**的 Object(即 `{}` 或 `new Object()`,不含数组、null、自定义类等)。
387
- *
388
- * @param {*} obj - 待检测的值
389
- * @returns {obj is Record<PropertyKey, any>}
390
- */
391
- function isPlainObject(obj) {
392
- return getDataType(obj) === "object";
393
- }
394
-
395
- /**
396
- * 判断值是否为 Promise(含 Promise 子类)。
397
- *
398
- * @param {*} obj - 待检测的值
399
- * @returns {obj is Promise<any>}
400
- */
401
- function isPromise(obj) {
402
- return getDataType(obj) === "promise";
403
- }
404
-
405
- /**
406
- * 判断值是否为合法 Date 对象(含 Invalid Date 返回 false)。
407
- *
408
- * @param {*} t - 待检测值
409
- * @returns {t is Date}
410
- */
411
- function isDate(t) {
412
- return getDataType(t) === "date";
413
- }
414
-
415
- /**
416
- * 判断值是否为函数(含异步函数、生成器函数、类)。
417
- *
418
- * @param {*} obj - 待检测的值
419
- * @returns {obj is Function}
420
- */
421
- function isFunction(obj) {
422
- return typeof obj === "function";
423
- }
424
-
425
- /**
426
- * 判断值是否为**非空**字符串。
427
- *
428
- * @param {*} obj - 待检测的值
429
- * @returns {obj is string}
430
- */
431
- function isNonEmptyString(obj) {
432
- return getDataType(obj) === "string" && obj.length > 0;
433
- }
434
-
435
- //#endregion
436
-
437
- //#region 随机数据
438
-
439
- /**
440
- * 在闭区间 [min, max] 内生成一个均匀分布的随机整数。
441
- * 若 min > max 则自动交换。
442
- *
443
- * @param {number} min - 整数下界(包含)
444
- * @param {number} max - 整数上界(包含)
445
- * @returns {number}
446
- * @throws {TypeError} 当 min 或 max 不是整数时抛出
447
- */
448
- function randomIntInRange(min, max) {
449
- if (!Number.isInteger(min) || !Number.isInteger(max)) {
450
- throw new TypeError("Arguments must be integers");
451
- }
452
- if (min > max) [min, max] = [max, min];
453
- // 注意加 1,否则 max 永远取不到;Math.floor 保证均匀
454
- return Math.floor(Math.random() * (max - min + 1)) + min;
455
- }
456
-
457
- /**
458
- * 随机生成一个汉字(可控制范围)。
459
- *
460
- * @param {boolean} [base=true] - 是否启用基本区(0x4E00-0x9FA5)
461
- * @param {boolean} [extA=false] - 是否启用扩展 A 区(0x3400-0x4DBF)
462
- * @param {boolean} [extBH=false] - 是否启用扩展 B~H 区(0x20000-0x2EBEF,代理对)
463
- * @returns {string} 单个汉字字符
464
- * @throws {RangeError} 未启用任何区段时抛出
465
- */
466
- function randomHan(base = true, extA = false, extBH = false) {
467
- // 1. 收集已启用的“区段”
468
- const ranges = [];
469
- if (base) ranges.push({ min: 0x4e00, max: 0x9fa5, surrogate: false });
470
- if (extA) ranges.push({ min: 0x3400, max: 0x4dbf, surrogate: false });
471
- if (extBH) ranges.push({ min: 0x20000, max: 0x2ebef, surrogate: true });
472
-
473
- if (ranges.length === 0) {
474
- throw new RangeError("At least one range must be enabled");
475
- }
476
-
477
- // 2. 按总码位数抽号
478
- const total = ranges.reduce((sum, r) => sum + (r.max - r.min + 1), 0);
479
- let n = randomIntInRange(0, total - 1);
480
-
481
- // 3. 定位落在哪个区段
482
- for (const { min, max, surrogate } of ranges) {
483
- const size = max - min + 1;
484
- if (n < size) {
485
- const code = min + n;
486
- if (!surrogate) return String.fromCharCode(code);
487
- // 代理对
488
- const offset = code - 0x10000;
489
- const hi = (offset >> 10) + 0xd800;
490
- const lo = (offset & 0x3ff) + 0xdc00;
491
- return String.fromCharCode(hi, lo);
492
- }
493
- n -= size;
494
- }
495
- }
496
-
497
- /**
498
- * 随机生成一个英文字母。
499
- *
500
- * @param {'lower'|'upper'} [type] - 指定大小写;留空则随机
501
- * @returns {string} 单个字母
502
- */
503
- function randomEnLetter(type) {
504
- const lower = "abcdefghijklmnopqrstuvwxyz";
505
- const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
506
- const randomNum = randomIntInRange(0, 25);
507
-
508
- switch (type) {
509
- case "lower":
510
- return lower[randomNum];
511
- case "upper":
512
- return upper[randomNum];
513
- default:
514
- return (Math.random() < 0.5 ? lower : upper)[randomNum];
515
- }
516
- }
517
-
518
- /**
519
- * 生成指定长度的随机“中英混合”字符串。
520
- *
521
- * @param {number} [len=1] - 目标长度(≥1,自动取整)
522
- * @param {number} [zhProb=0.5] - 每个位置选择汉字的概率,默认 0.5
523
- * @returns {string}
524
- */
525
- function randomHanOrEn(len, zhProb = 0.5) {
526
- len = Math.max(1, Math.floor(len));
527
- const buf = [];
528
- for (let i = 0; i < len; i++) {
529
- buf.push(Math.random() < zhProb ? randomHan() : randomEnLetter());
530
- }
531
- return buf.join("");
532
- }
533
-
534
- //#endregion
535
-
536
- //#region 防抖节流
537
-
538
- /**
539
- * 创建 debounced(防抖)函数。
540
- * - 默认 trailing 触发;当 `leading=true` 时,首次调用或超过等待间隔会立即执行。
541
- * - 支持手动取消。
542
- *
543
- * @template {(...args: any[]) => any} T
544
- * @param {T} fn - 要防抖的原始函数
545
- * @param {number} wait - 防抖等待时间(毫秒)
546
- * @param {boolean} [leading=false] - 是否启用立即执行(leading edge)
547
- * @returns {T & { cancel(): void }} 返回经过防抖包装的函数,并附带 `cancel` 方法
548
- * @throws {TypeError} 当 `fn` 不是函数时抛出
549
- */
550
- function debounce(fn, wait, leading = false) {
551
- if (typeof fn !== "function") throw new TypeError("fn must be function");
552
- wait = Math.max(0, Number(wait) || 0);
553
- let timeoutId;
554
- let lastCall = 0; // 0 表示从未调用过
555
-
556
- function debounced(...args) {
557
- const isFirst = lastCall === 0;
558
- const isOverWait = Date.now() - lastCall >= wait;
559
-
560
- clearTimeout(timeoutId);
561
-
562
- // 首次调用 || 已达到等待间隔
563
- if (leading && (isFirst || isOverWait)) {
564
- lastCall = Date.now();
565
- return fn.apply(this, args);
566
- }
567
-
568
- timeoutId = setTimeout(() => {
569
- lastCall = Date.now();
570
- fn.apply(this, args);
571
- }, wait);
572
- }
573
-
574
- debounced.cancel = () => {
575
- clearTimeout(timeoutId);
576
- lastCall = 0; // 恢复初始状态
577
- };
578
-
579
- return debounced;
580
- }
581
-
582
- /**
583
- * 创建 throttled(节流)函数。
584
- * 支持 leading/trailing 边缘触发,可手动取消。
585
- *
586
- * @template {(...args: any[]) => any} T
587
- * @param {T} fn - 要节流的原始函数
588
- * @param {number} wait - 节流间隔(毫秒)
589
- * @param {object} [options] - 配置项
590
- * @param {boolean} [options.leading=true] - 是否在 leading 边缘执行
591
- * @param {boolean} [options.trailing=true] - 是否在 trailing 边缘执行
592
- * @returns {T & { cancel(): void }} 返回经过节流包装的函数,并附带 `cancel` 方法
593
- * @throws {TypeError} 当 `fn` 不是函数时抛出
594
- */
595
- function throttle(fn, wait, { leading = true, trailing = true } = {}) {
596
- if (typeof fn !== "function") throw new TypeError("fn must be function");
597
- wait = Math.max(0, Number(wait) || 0);
598
-
599
- let timeoutId = null,
600
- lastCall = 0;
601
-
602
- function throttled(...args) {
603
- const remaining = wait - (Date.now() - lastCall);
604
-
605
- if (leading && (lastCall === 0 || remaining <= 0)) {
606
- lastCall = Date.now();
607
- fn.apply(this, args);
608
- } else if (trailing && !timeoutId) {
609
- timeoutId = setTimeout(
610
- () => {
611
- timeoutId = null;
612
- lastCall = Date.now();
613
- fn.apply(this, args);
614
- },
615
- remaining > 0 ? remaining : wait
616
- );
617
- }
618
- }
619
-
620
- throttled.cancel = () => {
621
- clearTimeout(timeoutId);
622
- timeoutId = null;
623
- lastCall = 0;
624
- };
625
-
626
- return throttled;
627
- }
628
-
629
- //#endregion
630
-
631
- /**
632
- * 利用 JSON 序列化/反序列化实现**深拷贝**。
633
- * 注意:会丢失 `undefined`、函数、循环引用、特殊包装对象等。
634
- *
635
- * @template T
636
- * @param {T} obj - 待拷贝的 JSON 兼容值
637
- * @returns {T} 深拷贝后的值
638
- */
639
- function deepCloneByJSON(obj) {
640
- return JSON.parse(JSON.stringify(obj));
641
- }
642
-
643
- /**
644
- * **安全**地将源对象中**已存在**的属性赋值到目标对象。
645
- * 不会新增键,也不会复制原型链上的属性。
646
- *
647
- * @template {Record<PropertyKey, any>} T
648
- * @param {T} target - 目标对象(将被就地修改)
649
- * @param {...Partial<T>} sources - 一个或多个源对象
650
- * @returns {T} 修改后的目标对象(即第一个参数本身)
651
- *
652
- * @example
653
- * const defaults = { a: 1, b: 2 };
654
- * assignExisting(defaults, { a: 9, c: 99 }); // defaults 变为 { a: 9, b: 2 }
655
- */
656
- function assignExisting(target, ...sources) {
657
- sources.forEach((source) => {
658
- Object.keys(source).forEach((key) => {
659
- if (target.hasOwnProperty(key)) {
660
- target[key] = source[key];
661
- }
662
- });
663
- });
664
- return target;
665
- }
666
-
667
- /**
668
- * 提取任意函数(含箭头函数、普通函数、async、class 构造器)的形参名称列表。
669
- * 通过源码正则解析,不支持解构参数、默认参数、剩余参数等复杂语法;
670
- * 若出现上述场景将返回空数组或部分名称。
671
- *
672
- * @param {Function} fn - 目标函数
673
- * @returns {string[]} 按声明顺序排列的参数名数组;解析失败时返回空数组
674
- *
675
- * @example
676
- * getFunctionArgNames(function (a, b) {}) // ["a", "b"]
677
- * getFunctionArgNames((foo, bar) => {}) // ["foo", "bar"]
678
- * getFunctionArgNames(async function x({a} = {}) {}) // [] (解构无法识别)
679
- */
680
- function getFunctionArgNames(fn) {
681
- const FN_ARG_SPLIT = /,/,
682
- FN_ARG = /^\s*(_?)(\S+?)\1\s*$/,
683
- FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m,
684
- ARROW_ARG = /^([^(]+?)=>/,
685
- STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;
686
-
687
- const fnText = Function.prototype.toString.call(fn).replace(STRIP_COMMENTS, "");
688
- const argDecl = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
689
- const retArgNames = [];
690
- [].forEach.call(argDecl[1].split(FN_ARG_SPLIT), function (arg) {
691
- arg.replace(FN_ARG, function (all, underscore, name) {
692
- retArgNames.push(name);
693
- });
694
- });
695
- return retArgNames;
696
- }
697
-
698
- /**
699
- * 将 Blob(或 File)读取为文本,并可选择自动执行 `JSON.parse`。
700
- * 当 `isParse=true` 且内容非法 JSON 时,会回退为返回原始文本。
701
- *
702
- * @param {Blob} blob - 待读取的 Blob/File 对象
703
- * @param {boolean} [isParse=true] - 是否尝试将结果按 JSON 解析
704
- * @returns {Promise<string | any>} 解析后的 JSON 对象或原始文本
705
- *
706
- * @example
707
- * const json = await readBlobAsText(blob); // 自动 JSON.parse
708
- * const text = await readBlobAsText(blob, false); // 仅返回文本
709
- */
710
- function readBlobAsText(blob, isParse = true) {
711
- return new Promise((resolve, reject) => {
712
- const reader = new FileReader();
713
- reader.onload = (evt) => {
714
- const result = evt.target.result;
715
- if (isParse) {
716
- try {
717
- resolve(JSON.parse(result));
718
- } catch (error) {
719
- console.error(error);
720
- resolve(result);
721
- }
722
- } else {
723
- resolve(result);
724
- }
725
- };
726
- reader.onerror = reject;
727
- reader.readAsText(blob);
728
- });
729
- }
730
-
731
- /**
732
- * 将任意值安全转换为 Date 对象。
733
- * - 数字/数字字符串:视为时间戳
734
- * - 字符串:尝试按 ISO/RFC 格式解析
735
- * - 对象:优先 valueOf(),再 toString()
736
- * - null / undefined / 无效值:返回 null
737
- *
738
- * @param {*} val - 待转换值
739
- * @returns {Date | null} 有效 Date 或 null
740
- */
741
- function toDate(val) {
742
- if (val == null) return null; // null / undefined
743
- if (val instanceof Date) return isNaN(val) ? null : val; // 已是 Date,但需排除 Invalid Date
744
-
745
- // 1. 数字或数字字符串 → 时间戳
746
- if (typeof val === "number" || (typeof val === "string" && /^-?\d+(\.\d+)?$/.test(val.trim()))) {
747
- const d = new Date(+val);
748
- return isNaN(d) ? null : d;
749
- }
750
-
751
- // 2. 标准 ISO 8601 / RFC 2825 等合法字符串
752
- if (typeof val === "string") {
753
- const d = new Date(val);
754
- return isNaN(d) ? null : d; // 非法格式返回 null
755
- }
756
-
757
- // 3. 对象带 valueOf / toString
758
- if (typeof val === "object") {
759
- // 优先调用 valueOf(期望返回数字时间戳)
760
- const prim = val.valueOf ? val.valueOf() : Object.prototype.valueOf.call(val);
761
- if (typeof prim === "number" && !isNaN(prim)) {
762
- const d = new Date(prim);
763
- return isNaN(d) ? null : d;
764
- }
765
- // 兜底用字符串
766
- const str = val.toString ? val.toString() : String(val);
767
- const d = new Date(str);
768
- return isNaN(d) ? null : d;
769
- }
770
-
771
- // 4. 其余情况
772
- return null;
773
- }
774
-
775
- /**
776
- * 在闭区间 [date1, date2] 内随机生成一个日期(含首尾)。
777
- * 若顺序相反则自动交换。
778
- *
779
- * @param {Date} date1 - 起始日期
780
- * @param {Date} date2 - 结束日期
781
- * @returns {Date} 随机日期
782
- */
783
- function randomDateInRange(date1, date2) {
784
- let v1 = date1.getTime(),
785
- v2 = date2.getTime();
786
- if (v1 > v2) [v1, v2] = [v2, v1];
787
- return new Date(v1 + Math.floor(Math.random() * (v2 - v1 + 1)));
306
+ /**
307
+ * 视口尺寸对象。
308
+ * @typedef {Object} ViewportDimensions
309
+ * @property {number} w 视口宽度,单位像素。
310
+ * @property {number} h 视口高度,单位像素。
311
+ */
312
+
313
+ /**
314
+ * 获取当前视口(viewport)的宽高。
315
+ *
316
+ * 兼容策略:
317
+ * 1. 优先使用 `window.innerWidth/innerHeight`(现代浏览器)。
318
+ * 2. 降级到 `document.documentElement.clientWidth/clientHeight`(IE9+ 及怪异模式)。
319
+ * 3. 最后降级到 `document.body.clientWidth/clientHeight`(IE6-8 怪异模式)。
320
+ *
321
+ * @returns {ViewportDimensions} 包含 `w`(宽度)和 `h`(高度)的对象,单位为像素。
322
+ *
323
+ * @example
324
+ * const { w, h } = getViewportSize();
325
+ * console.log(`视口尺寸:${w} × ${h}`);
326
+ */
327
+ function getViewportSize() {
328
+ const d = document,
329
+ root = d.documentElement,
330
+ body = d.body;
331
+
332
+ return {
333
+ w: window.innerWidth || root.clientWidth || body.clientWidth,
334
+ h: window.innerHeight || root.clientHeight || body.clientHeight
335
+ };
336
+ }
337
+
338
+ /**
339
+ * 将当前页面 URL 的 query 部分解析成键值对对象。
340
+ *
341
+ * @returns {Record<string, string>} 所有查询参数组成的平凡对象
342
+ * (同名 key 仅保留最后一项)
343
+ */
344
+ function getAllSearchParams() {
345
+ const urlSearchParams = new URLSearchParams(location.search);
346
+ return Object.fromEntries(urlSearchParams.entries());
347
+ }
348
+
349
+ /**
350
+ * 根据 key 获取当前页面 URL 中的单个查询参数。
351
+ *
352
+ * @param {string} key - 要提取的参数名
353
+ * @returns {string | undefined} 对应参数值;不存在时返回 `undefined`
354
+ */
355
+ function getSearchParam(key) {
356
+ const params = getAllSearchParams();
357
+ return params[key];
788
358
  }
789
359
 
790
- /**
791
- * 计算两个时间之间的剩余/已过时长(天-时-分-秒),返回带补零的展示对象。
792
- *
793
- * @param {string|number|Date} originalTime - 原始时间(可转 Date 的任意值)
794
- * @param {Date} [currentTime=new Date()] - 基准时间,默认当前
795
- * @returns {{days:number,hours:string,minutes:string,seconds:string}}
796
- */
797
- function calcTimeDifference(originalTime, currentTime = new Date()) {
798
- // 计算时间差(毫秒)
799
- const diffMs = currentTime - new Date(originalTime);
800
-
801
- // 转换为天、小时、分钟、秒
802
- const diffSeconds = Math.floor(diffMs / 1000);
803
- const days = Math.floor(diffSeconds / (3600 * 24));
804
- const hours = Math.floor((diffSeconds % (3600 * 24)) / 3600);
805
- const minutes = Math.floor((diffSeconds % 3600) / 60);
806
- const seconds = diffSeconds % 60;
807
-
808
- const padZero = (num) => String(num).padStart(2, "0");
809
-
810
- return {
811
- days,
812
- hours: padZero(hours),
813
- minutes: padZero(minutes),
814
- seconds: padZero(seconds)
815
- };
360
+ //#region 数据类型判断
361
+
362
+ /**
363
+ * 返回任意值的运行时类型字符串(小写形式)。
364
+ *
365
+ * @param {*} obj 待检测的值
366
+ * @returns {keyof globalThis|"blob"|"file"|"formdata"|string} 小写类型名
367
+ */
368
+ function getDataType(obj) {
369
+ return Object.prototype.toString
370
+ .call(obj)
371
+ .replace(/^\[object\s(\w+)\]$/, "$1")
372
+ .toLowerCase();
373
+ }
374
+
375
+ /**
376
+ * 判断值是否为原生 Blob(含 File)。
377
+ *
378
+ * @param {*} obj - 待检测的值
379
+ * @returns {obj is Blob}
380
+ */
381
+ function isBlob(obj) {
382
+ return getDataType(obj) === "blob";
383
+ }
384
+
385
+ /**
386
+ * 判断值是否为**纯粹**的 Object(即 `{}` 或 `new Object()`,不含数组、null、自定义类等)。
387
+ *
388
+ * @param {*} obj - 待检测的值
389
+ * @returns {obj is Record<PropertyKey, any>}
390
+ */
391
+ function isPlainObject(obj) {
392
+ return getDataType(obj) === "object";
393
+ }
394
+
395
+ /**
396
+ * 判断值是否为 Promise(含 Promise 子类)。
397
+ *
398
+ * @param {*} obj - 待检测的值
399
+ * @returns {obj is Promise<any>}
400
+ */
401
+ function isPromise(obj) {
402
+ return getDataType(obj) === "promise";
403
+ }
404
+
405
+ /**
406
+ * 判断值是否为合法 Date 对象(含 Invalid Date 返回 false)。
407
+ *
408
+ * @param {*} t - 待检测值
409
+ * @returns {t is Date}
410
+ */
411
+ function isDate(t) {
412
+ return getDataType(t) === "date";
413
+ }
414
+
415
+ /**
416
+ * 判断值是否为函数(含异步函数、生成器函数、类)。
417
+ *
418
+ * @param {*} obj - 待检测的值
419
+ * @returns {obj is Function}
420
+ */
421
+ function isFunction(obj) {
422
+ return typeof obj === "function";
423
+ }
424
+
425
+ /**
426
+ * 判断值是否为**非空**字符串。
427
+ *
428
+ * @param {*} obj - 待检测的值
429
+ * @returns {obj is string}
430
+ */
431
+ function isNonEmptyString(obj) {
432
+ return getDataType(obj) === "string" && obj.length > 0;
433
+ }
434
+
435
+ //#endregion
436
+
437
+ //#region 随机数据
438
+
439
+ /**
440
+ * 在闭区间 [min, max] 内生成一个均匀分布的随机整数。
441
+ * 若 min > max 则自动交换。
442
+ *
443
+ * @param {number} min - 整数下界(包含)
444
+ * @param {number} max - 整数上界(包含)
445
+ * @returns {number}
446
+ * @throws {TypeError} 当 min 或 max 不是整数时抛出
447
+ */
448
+ function randomIntInRange(min, max) {
449
+ if (!Number.isInteger(min) || !Number.isInteger(max)) {
450
+ throw new TypeError("Arguments must be integers");
451
+ }
452
+ if (min > max) [min, max] = [max, min];
453
+ // 注意加 1,否则 max 永远取不到;Math.floor 保证均匀
454
+ return Math.floor(Math.random() * (max - min + 1)) + min;
455
+ }
456
+
457
+ /**
458
+ * 随机生成一个汉字(可控制范围)。
459
+ *
460
+ * @param {boolean} [base=true] - 是否启用基本区(0x4E00-0x9FA5)
461
+ * @param {boolean} [extA=false] - 是否启用扩展 A 区(0x3400-0x4DBF)
462
+ * @param {boolean} [extBH=false] - 是否启用扩展 B~H 区(0x20000-0x2EBEF,代理对)
463
+ * @returns {string} 单个汉字字符
464
+ * @throws {RangeError} 未启用任何区段时抛出
465
+ */
466
+ function randomHan(base = true, extA = false, extBH = false) {
467
+ // 1. 收集已启用的“区段”
468
+ const ranges = [];
469
+ if (base) ranges.push({ min: 0x4e00, max: 0x9fa5, surrogate: false });
470
+ if (extA) ranges.push({ min: 0x3400, max: 0x4dbf, surrogate: false });
471
+ if (extBH) ranges.push({ min: 0x20000, max: 0x2ebef, surrogate: true });
472
+
473
+ if (ranges.length === 0) {
474
+ throw new RangeError("At least one range must be enabled");
475
+ }
476
+
477
+ // 2. 按总码位数抽号
478
+ const total = ranges.reduce((sum, r) => sum + (r.max - r.min + 1), 0);
479
+ let n = randomIntInRange(0, total - 1);
480
+
481
+ // 3. 定位落在哪个区段
482
+ for (const { min, max, surrogate } of ranges) {
483
+ const size = max - min + 1;
484
+ if (n < size) {
485
+ const code = min + n;
486
+ if (!surrogate) return String.fromCharCode(code);
487
+ // 代理对
488
+ const offset = code - 0x10000;
489
+ const hi = (offset >> 10) + 0xd800;
490
+ const lo = (offset & 0x3ff) + 0xdc00;
491
+ return String.fromCharCode(hi, lo);
492
+ }
493
+ n -= size;
494
+ }
495
+ }
496
+
497
+ /**
498
+ * 随机生成一个英文字母。
499
+ *
500
+ * @param {'lower'|'upper'} [type] - 指定大小写;留空则随机
501
+ * @returns {string} 单个字母
502
+ */
503
+ function randomEnLetter(type) {
504
+ const lower = "abcdefghijklmnopqrstuvwxyz";
505
+ const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
506
+ const randomNum = randomIntInRange(0, 25);
507
+
508
+ switch (type) {
509
+ case "lower":
510
+ return lower[randomNum];
511
+ case "upper":
512
+ return upper[randomNum];
513
+ default:
514
+ return (Math.random() < 0.5 ? lower : upper)[randomNum];
515
+ }
516
+ }
517
+
518
+ /**
519
+ * 生成指定长度的随机“中英混合”字符串。
520
+ *
521
+ * @param {number} [len=1] - 目标长度(≥1,自动取整)
522
+ * @param {number} [zhProb=0.5] - 每个位置选择汉字的概率,默认 0.5
523
+ * @returns {string}
524
+ */
525
+ function randomHanOrEn(len, zhProb = 0.5) {
526
+ len = Math.max(1, Math.floor(len));
527
+ const buf = [];
528
+ for (let i = 0; i < len; i++) {
529
+ buf.push(Math.random() < zhProb ? randomHan() : randomEnLetter());
530
+ }
531
+ return buf.join("");
532
+ }
533
+
534
+ //#endregion
535
+
536
+ //#region 防抖节流
537
+
538
+ /**
539
+ * 创建 debounced(防抖)函数。
540
+ * - 默认 trailing 触发;当 `leading=true` 时,首次调用或超过等待间隔会立即执行。
541
+ * - 支持手动取消。
542
+ *
543
+ * @template {(...args: any[]) => any} T
544
+ * @param {T} fn - 要防抖的原始函数
545
+ * @param {number} wait - 防抖等待时间(毫秒)
546
+ * @param {boolean} [leading=false] - 是否启用立即执行(leading edge)
547
+ * @returns {T & { cancel(): void }} 返回经过防抖包装的函数,并附带 `cancel` 方法
548
+ * @throws {TypeError} 当 `fn` 不是函数时抛出
549
+ */
550
+ function debounce(fn, wait, leading = false) {
551
+ if (typeof fn !== "function") throw new TypeError("fn must be function");
552
+ wait = Math.max(0, Number(wait) || 0);
553
+ let timeoutId;
554
+ let lastCall = 0; // 0 表示从未调用过
555
+
556
+ function debounced(...args) {
557
+ const isFirst = lastCall === 0;
558
+ const isOverWait = Date.now() - lastCall >= wait;
559
+
560
+ clearTimeout(timeoutId);
561
+
562
+ // 首次调用 || 已达到等待间隔
563
+ if (leading && (isFirst || isOverWait)) {
564
+ lastCall = Date.now();
565
+ return fn.apply(this, args);
566
+ }
567
+
568
+ timeoutId = setTimeout(() => {
569
+ lastCall = Date.now();
570
+ fn.apply(this, args);
571
+ }, wait);
572
+ }
573
+
574
+ debounced.cancel = () => {
575
+ clearTimeout(timeoutId);
576
+ lastCall = 0; // 恢复初始状态
577
+ };
578
+
579
+ return debounced;
580
+ }
581
+
582
+ /**
583
+ * 创建 throttled(节流)函数。
584
+ * 支持 leading/trailing 边缘触发,可手动取消。
585
+ *
586
+ * @template {(...args: any[]) => any} T
587
+ * @param {T} fn - 要节流的原始函数
588
+ * @param {number} wait - 节流间隔(毫秒)
589
+ * @param {object} [options] - 配置项
590
+ * @param {boolean} [options.leading=true] - 是否在 leading 边缘执行
591
+ * @param {boolean} [options.trailing=true] - 是否在 trailing 边缘执行
592
+ * @returns {T & { cancel(): void }} 返回经过节流包装的函数,并附带 `cancel` 方法
593
+ * @throws {TypeError} 当 `fn` 不是函数时抛出
594
+ */
595
+ function throttle(fn, wait, { leading = true, trailing = true } = {}) {
596
+ if (typeof fn !== "function") throw new TypeError("fn must be function");
597
+ wait = Math.max(0, Number(wait) || 0);
598
+
599
+ let timeoutId = null,
600
+ lastCall = 0;
601
+
602
+ function throttled(...args) {
603
+ const remaining = wait - (Date.now() - lastCall);
604
+
605
+ if (leading && (lastCall === 0 || remaining <= 0)) {
606
+ lastCall = Date.now();
607
+ fn.apply(this, args);
608
+ } else if (trailing && !timeoutId) {
609
+ timeoutId = setTimeout(
610
+ () => {
611
+ timeoutId = null;
612
+ lastCall = Date.now();
613
+ fn.apply(this, args);
614
+ },
615
+ remaining > 0 ? remaining : wait
616
+ );
617
+ }
618
+ }
619
+
620
+ throttled.cancel = () => {
621
+ clearTimeout(timeoutId);
622
+ timeoutId = null;
623
+ lastCall = 0;
624
+ };
625
+
626
+ return throttled;
627
+ }
628
+
629
+ //#endregion
630
+
631
+ /**
632
+ * 利用 JSON 序列化/反序列化实现**深拷贝**。
633
+ * 注意:会丢失 `undefined`、函数、循环引用、特殊包装对象等。
634
+ *
635
+ * @template T
636
+ * @param {T} obj - 待拷贝的 JSON 兼容值
637
+ * @returns {T} 深拷贝后的值
638
+ */
639
+ function deepCloneByJSON(obj) {
640
+ return JSON.parse(JSON.stringify(obj));
641
+ }
642
+
643
+ /**
644
+ * **安全**地将源对象中**已存在**的属性赋值到目标对象。
645
+ * 不会新增键,也不会复制原型链上的属性。
646
+ *
647
+ * @template {Record<PropertyKey, any>} T
648
+ * @param {T} target - 目标对象(将被就地修改)
649
+ * @param {...Partial<T>} sources - 一个或多个源对象
650
+ * @returns {T} 修改后的目标对象(即第一个参数本身)
651
+ *
652
+ * @example
653
+ * const defaults = { a: 1, b: 2 };
654
+ * assignExisting(defaults, { a: 9, c: 99 }); // defaults 变为 { a: 9, b: 2 }
655
+ */
656
+ function assignExisting(target, ...sources) {
657
+ sources.forEach((source) => {
658
+ Object.keys(source).forEach((key) => {
659
+ if (target.hasOwnProperty(key)) {
660
+ target[key] = source[key];
661
+ }
662
+ });
663
+ });
664
+ return target;
665
+ }
666
+
667
+ /**
668
+ * 提取任意函数(含箭头函数、普通函数、async、class 构造器)的形参名称列表。
669
+ * 通过源码正则解析,不支持解构参数、默认参数、剩余参数等复杂语法;
670
+ * 若出现上述场景将返回空数组或部分名称。
671
+ *
672
+ * @param {Function} fn - 目标函数
673
+ * @returns {string[]} 按声明顺序排列的参数名数组;解析失败时返回空数组
674
+ *
675
+ * @example
676
+ * getFunctionArgNames(function (a, b) {}) // ["a", "b"]
677
+ * getFunctionArgNames((foo, bar) => {}) // ["foo", "bar"]
678
+ * getFunctionArgNames(async function x({a} = {}) {}) // [] (解构无法识别)
679
+ */
680
+ function getFunctionArgNames(fn) {
681
+ const FN_ARG_SPLIT = /,/,
682
+ FN_ARG = /^\s*(_?)(\S+?)\1\s*$/,
683
+ FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m,
684
+ ARROW_ARG = /^([^(]+?)=>/,
685
+ STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;
686
+
687
+ const fnText = Function.prototype.toString.call(fn).replace(STRIP_COMMENTS, "");
688
+ const argDecl = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
689
+ const retArgNames = [];
690
+ [].forEach.call(argDecl[1].split(FN_ARG_SPLIT), function (arg) {
691
+ arg.replace(FN_ARG, function (all, underscore, name) {
692
+ retArgNames.push(name);
693
+ });
694
+ });
695
+ return retArgNames;
696
+ }
697
+
698
+ /**
699
+ * 将 Blob(或 File)读取为文本,并可选择自动执行 `JSON.parse`。
700
+ * 当 `isParse=true` 且内容非法 JSON 时,会回退为返回原始文本。
701
+ *
702
+ * @param {Blob} blob - 待读取的 Blob/File 对象
703
+ * @param {boolean} [isParse=true] - 是否尝试将结果按 JSON 解析
704
+ * @returns {Promise<string | any>} 解析后的 JSON 对象或原始文本
705
+ *
706
+ * @example
707
+ * const json = await readBlobAsText(blob); // 自动 JSON.parse
708
+ * const text = await readBlobAsText(blob, false); // 仅返回文本
709
+ */
710
+ function readBlobAsText(blob, isParse = true) {
711
+ return new Promise((resolve, reject) => {
712
+ const reader = new FileReader();
713
+ reader.onload = (evt) => {
714
+ const result = evt.target.result;
715
+ if (isParse) {
716
+ try {
717
+ resolve(JSON.parse(result));
718
+ } catch (error) {
719
+ console.error(error);
720
+ resolve(result);
721
+ }
722
+ } else {
723
+ resolve(result);
724
+ }
725
+ };
726
+ reader.onerror = reject;
727
+ reader.readAsText(blob);
728
+ });
816
729
  }
817
730
 
818
- /**
819
- * 将总秒数格式化成人类可读的时间段文本。
820
- * 固定进制:1 年=365 天,1 月=30 天。
821
- *
822
- * @param {number} totalSeconds - 非负总秒数
823
- * @param {object} [options] - 格式化选项
824
- * @param {Partial<{year:string,month:string,day:string,hour:string,minute:string,second:string}>} [options.labels] - 各单位的自定义文本
825
- * @param {('year'|'month'|'day'|'hour'|'minute'|'second')} [options.maxUnit] - 最大输出单位
826
- * @param {('year'|'month'|'day'|'hour'|'minute'|'second')} [options.minUnit] - 最小输出单位
827
- * @param {boolean} [options.showZero] - 是否强制显示 0 秒
828
- * @returns {string} 拼接后的时长文本,如“1天 02小时 30分钟”
829
- * @throws {TypeError} 当 totalSeconds 为非数字或负数时抛出
830
- */
831
- function formatDuration(totalSeconds, options = {}) {
832
- if (typeof totalSeconds !== "number" || totalSeconds < 0 || !isFinite(totalSeconds)) {
833
- throw new TypeError("totalSeconds 必须是非负数字");
834
- }
835
-
836
- // 1. 默认中文单位
837
- const DEFAULT_LABELS = {
838
- year: "年",
839
- month: "月",
840
- day: "天",
841
- hour: "小时",
842
- minute: "分钟",
843
- second: ""
844
- };
845
-
846
- // 2. 固定进制表(秒)
847
- const UNIT_TABLE = [
848
- { key: "year", seconds: 365 * 24 * 3600 },
849
- { key: "month", seconds: 30 * 24 * 3600 },
850
- { key: "day", seconds: 24 * 3600 },
851
- { key: "hour", seconds: 3600 },
852
- { key: "minute", seconds: 60 },
853
- { key: "second", seconds: 1 }
854
- ];
855
-
856
- // 3. 合并用户自定义文本
857
- const labels = Object.assign({}, DEFAULT_LABELS, options.labels);
858
-
859
- // 4. 根据 maxUnit / minUnit 截取
860
- let start = 0,
861
- end = UNIT_TABLE.length;
862
- if (options.maxUnit) {
863
- const idx = UNIT_TABLE.findIndex((u) => u.key === options.maxUnit);
864
- if (idx !== -1) start = idx;
865
- }
866
- if (options.minUnit) {
867
- const idx = UNIT_TABLE.findIndex((u) => u.key === options.minUnit);
868
- if (idx !== -1) end = idx + 1;
869
- }
870
- const units = UNIT_TABLE.slice(start, end);
871
- if (!units.length) units.push(UNIT_TABLE[UNIT_TABLE.length - 1]); // 保底秒
872
-
873
- // 5. 逐级计算
874
- let rest = Math.floor(totalSeconds);
875
- const parts = [];
876
-
877
- for (const { key, seconds } of units) {
878
- const val = Math.floor(rest / seconds);
879
- rest %= seconds;
880
-
881
- const shouldShow = val > 0 || (options.showZero && key === "second");
882
- if (shouldShow || (parts.length === 0 && rest === 0)) {
883
- parts.push(`${val}${labels[key]}`);
884
- }
885
- }
886
-
887
- // 6. 兜底
888
- if (parts.length === 0) {
889
- parts.push(`0${labels[units[units.length - 1].key]}`);
890
- }
891
-
892
- return parts.join("");
731
+ function getLocales_TimePeriod() {
732
+ return {
733
+ earlyMorning: "凌晨",
734
+ morning: "上午",
735
+ noon: "中午",
736
+ afternoon: "下午",
737
+ evening: "晚上"
738
+ };
739
+ }
740
+
741
+ /**
742
+ * 将任意值安全转换为 Date 对象。
743
+ * - 数字/数字字符串:视为时间戳
744
+ * - 字符串:尝试按 ISO/RFC 格式解析
745
+ * - 对象:优先 valueOf(),再 toString()
746
+ * - null / undefined / 无效值:返回 null
747
+ *
748
+ * @param {*} val - 待转换值
749
+ * @returns {Date | null} 有效 Date 或 null
750
+ */
751
+ function toDate(val) {
752
+ if (val == null) return null; // null / undefined
753
+ if (val instanceof Date) return isNaN(val) ? null : val; // 已是 Date,但需排除 Invalid Date
754
+
755
+ // 1. 数字或数字字符串 → 时间戳
756
+ if (typeof val === "number" || (typeof val === "string" && /^-?\d+(\.\d+)?$/.test(val.trim()))) {
757
+ const d = new Date(+val);
758
+ return isNaN(d) ? null : d;
759
+ }
760
+
761
+ // 2. 标准 ISO 8601 / RFC 2825 等合法字符串
762
+ if (typeof val === "string") {
763
+ const d = new Date(val);
764
+ return isNaN(d) ? null : d; // 非法格式返回 null
765
+ }
766
+
767
+ // 3. 对象带 valueOf / toString
768
+ if (typeof val === "object") {
769
+ // 优先调用 valueOf(期望返回数字时间戳)
770
+ const prim = val.valueOf ? val.valueOf() : Object.prototype.valueOf.call(val);
771
+ if (typeof prim === "number" && !isNaN(prim)) {
772
+ const d = new Date(prim);
773
+ return isNaN(d) ? null : d;
774
+ }
775
+ // 兜底用字符串
776
+ const str = val.toString ? val.toString() : String(val);
777
+ const d = new Date(str);
778
+ return isNaN(d) ? null : d;
779
+ }
780
+
781
+ // 4. 其余情况
782
+ return null;
783
+ }
784
+
785
+ /**
786
+ * 在闭区间 [date1, date2] 内随机生成一个日期(含首尾)。
787
+ * 若顺序相反则自动交换。
788
+ *
789
+ * @param {Date} date1 - 起始日期
790
+ * @param {Date} date2 - 结束日期
791
+ * @returns {Date} 随机日期
792
+ */
793
+ function randomDateInRange(date1, date2) {
794
+ let v1 = date1.getTime(),
795
+ v2 = date2.getTime();
796
+ if (v1 > v2) [v1, v2] = [v2, v1];
797
+ return new Date(v1 + Math.floor(Math.random() * (v2 - v1 + 1)));
798
+ }
799
+
800
+ //#region 持续时间相关
801
+
802
+ /**
803
+ * 时间持续对象(完整版本,包含年月日时分秒毫秒)
804
+ * @typedef {Object} DurationObject
805
+ * @property {number} years - 年数
806
+ * @property {number} months - 月数(0-11)
807
+ * @property {number} days - 天数(0-29,取决于 monthDays)
808
+ * @property {number} hours - 小时数(0-23)
809
+ * @property {number} minutes - 分钟数(0-59)
810
+ * @property {number} seconds - 秒数(0-59)
811
+ * @property {number} milliseconds - 毫秒数(0-999)
812
+ */
813
+
814
+ /**
815
+ * 时间持续对象(最大单位为天)
816
+ * @typedef {Object} DurationMaxDayObject
817
+ * @property {number} days - 天数
818
+ * @property {number} hours - 小时数(0-23)
819
+ * @property {number} minutes - 分钟数(0-59)
820
+ * @property {number} seconds - 秒数(0-59)
821
+ * @property {number} milliseconds - 毫秒数(0-999)
822
+ */
823
+
824
+ /**
825
+ * 时间持续对象(最大单位为小时)
826
+ * @typedef {Object} DurationMaxHourObject
827
+ * @property {number} hours - 小时数
828
+ * @property {number} minutes - 分钟数(0-59)
829
+ * @property {number} seconds - 秒数(0-59)
830
+ * @property {number} milliseconds - 毫秒数(0-999)
831
+ */
832
+
833
+ /**
834
+ * 将毫秒转换为时间持续对象。
835
+ *
836
+ * @param {number} milliseconds - 毫秒数(非负整数)
837
+ * @param {Object} [options] - 选项对象。
838
+ * @param {number} [options.yearDays=365] - 一年的天数。
839
+ * @param {number} [options.monthDays=30] - 一月的天数。
840
+ * @returns {DurationObject} 时间持续对象
841
+ * @throws {TypeError} 当 milliseconds 不是有效数字
842
+ * @throws {RangeError} 当 milliseconds 为负数
843
+ * @throws {RangeError} 当 yearDays 或 monthDays 不是正整数
844
+ *
845
+ * @example
846
+ * // 基本用法
847
+ * millisecond2Duration(42070000500);
848
+ * // 返回: { years: 1, months: 4, days: 1, hours: 22, minutes: 6, seconds: 40, milliseconds: 500 }
849
+ */
850
+ function millisecond2Duration(milliseconds, options = { yearDays: 365, monthDays: 30 }) {
851
+ // 参数验证
852
+ if (typeof milliseconds !== "number" || isNaN(milliseconds)) {
853
+ throw new TypeError("milliseconds must be a valid number");
854
+ }
855
+ if (milliseconds < 0) {
856
+ throw new RangeError("milliseconds must be a non-negative number");
857
+ }
858
+
859
+ // 默认选项
860
+ const { yearDays = 365, monthDays = 30 } = options;
861
+
862
+ // 选项验证
863
+ if (!Number.isInteger(yearDays) || yearDays <= 0) {
864
+ throw new RangeError("yearDays must be a positive integer");
865
+ }
866
+ if (!Number.isInteger(monthDays) || monthDays <= 0) {
867
+ throw new RangeError("monthDays must be a positive integer");
868
+ }
869
+
870
+ const totalMilliseconds = Math.floor(milliseconds);
871
+ const ms = totalMilliseconds % 1000;
872
+ const diffSeconds = Math.floor(totalMilliseconds / 1000);
873
+
874
+ const seconds = diffSeconds % 60;
875
+ const minutes = Math.floor(diffSeconds / 60) % 60;
876
+ const hours = Math.floor(diffSeconds / 3600) % 24;
877
+
878
+ // 计算年、月、日
879
+ const totalDays = Math.floor(diffSeconds / 3600 / 24);
880
+ const years = Math.floor(totalDays / yearDays);
881
+ const remainingDays = totalDays % yearDays;
882
+ const months = Math.floor(remainingDays / monthDays);
883
+ const days = remainingDays % monthDays;
884
+
885
+ return { years, months, days, hours, minutes, seconds, milliseconds: ms };
886
+ }
887
+
888
+ /**
889
+ * 将毫秒转换为时间持续对象(最大单位为天)。
890
+ * @param {number} milliseconds - 毫秒数(非负整数)
891
+ * @returns {DurationMaxDayObject} 包含天、小时、分钟、秒、毫秒的时间持续对象
892
+ * @throws {TypeError} 当 milliseconds 不是有效数字时抛出
893
+ * @throws {RangeError} 当 milliseconds 为负数时抛出
894
+ * @example
895
+ * // 返回 { days: 486, hours: 22, minutes: 6, seconds: 40, milliseconds: 500 }
896
+ * millisecond2DurationMaxDay(42070000500);
897
+ */
898
+ function millisecond2DurationMaxDay(milliseconds) {
899
+ if (typeof milliseconds !== "number" || isNaN(milliseconds)) {
900
+ throw new TypeError("milliseconds must be a valid number");
901
+ }
902
+ if (milliseconds < 0) {
903
+ throw new RangeError("milliseconds must be a non-negative number");
904
+ }
905
+
906
+ const totalMilliseconds = Math.floor(milliseconds);
907
+ const ms = totalMilliseconds % 1000;
908
+ const diffSeconds = Math.floor(totalMilliseconds / 1000);
909
+
910
+ const seconds = diffSeconds % 60;
911
+ const minutes = Math.floor(diffSeconds / 60) % 60;
912
+ const hours = Math.floor(diffSeconds / 3600) % 24;
913
+ const days = Math.floor(diffSeconds / 3600 / 24);
914
+
915
+ return { days, hours, minutes, seconds, milliseconds: ms };
916
+ }
917
+
918
+ /**
919
+ * 将毫秒转换为时间持续对象(最大单位为小时)。
920
+ * @param {number} milliseconds - 毫秒数(非负整数)
921
+ * @returns {DurationMaxHourObject} 包含小时、分钟、秒、毫秒的时间持续对象
922
+ * @throws {TypeError} 当 milliseconds 不是有效数字时抛出
923
+ * @throws {RangeError} 当 milliseconds 为负数时抛出
924
+ * @example
925
+ * // 返回 { hours: 11686, minutes: 6, seconds: 40, milliseconds: 500 }
926
+ * millisecond2DurationMaxHour(42070000500);
927
+ */
928
+ function millisecond2DurationMaxHour(milliseconds) {
929
+ if (typeof milliseconds !== "number" || isNaN(milliseconds)) {
930
+ throw new TypeError("milliseconds must be a valid number");
931
+ }
932
+ if (milliseconds < 0) {
933
+ throw new RangeError("milliseconds must be a non-negative number");
934
+ }
935
+
936
+ const totalMilliseconds = Math.floor(milliseconds);
937
+ const ms = totalMilliseconds % 1000;
938
+ const diffSeconds = Math.floor(totalMilliseconds / 1000);
939
+
940
+ const seconds = diffSeconds % 60;
941
+ const minutes = Math.floor(diffSeconds / 60) % 60;
942
+ const hours = Math.floor(diffSeconds / 3600);
943
+
944
+ return { hours, minutes, seconds, milliseconds: ms };
945
+ }
946
+
947
+ /**
948
+ * 将秒转换为时间持续对象。
949
+ *
950
+ * @param {number} seconds - 秒数(非负整数)
951
+ * @param {Object} [options] - 选项对象。
952
+ * @param {number} [options.yearDays=365] - 一年的天数。
953
+ * @param {number} [options.monthDays=30] - 一月的天数。
954
+ * @returns {DurationObject} 时间持续对象
955
+ * @throws {TypeError} 当 seconds 不是有效数字
956
+ * @throws {RangeError} 当 seconds 为负数
957
+ * @throws {RangeError} 当 yearDays 或 monthDays 不是正整数
958
+ *
959
+ * @example
960
+ * // 基本用法
961
+ * second2Duration(42070000.5);
962
+ * // 返回: { years: 1, months: 4, days: 1, hours: 22, minutes: 6, seconds: 40, milliseconds: 500 }
963
+ */
964
+ function second2Duration(seconds, options = { yearDays: 365, monthDays: 30 }) {
965
+ if (typeof seconds !== "number" || isNaN(seconds)) {
966
+ throw new TypeError("seconds must be a valid number");
967
+ }
968
+ if (seconds < 0) {
969
+ throw new RangeError("seconds must be a non-negative number");
970
+ }
971
+ return millisecond2Duration(seconds * 1000, options);
972
+ }
973
+
974
+ /**
975
+ * 将秒转换为时间持续对象(最大单位为天)。
976
+ * @param {number} seconds - 秒数(非负整数)
977
+ * @returns {DurationMaxDayObject} 包含天、小时、分钟、秒、毫秒的时间持续对象
978
+ * @throws {TypeError} 当 seconds 不是有效数字时抛出
979
+ * @throws {RangeError} 当 seconds 为负数时抛出
980
+ * @example
981
+ * // 返回 { days: 486, hours: 22, minutes: 6, seconds: 40, milliseconds: 500 }
982
+ * second2DurationMaxDay(42070000.5);
983
+ */
984
+ function second2DurationMaxDay(seconds) {
985
+ if (typeof seconds !== "number" || isNaN(seconds)) {
986
+ throw new TypeError("seconds must be a valid number");
987
+ }
988
+ if (seconds < 0) {
989
+ throw new RangeError("seconds must be a non-negative number");
990
+ }
991
+ return millisecond2DurationMaxDay(seconds * 1000);
992
+ }
993
+
994
+ /**
995
+ * 将秒转换为时间持续对象(最大单位为小时)。
996
+ * @param {number} seconds - 秒数(非负整数)
997
+ * @returns {DurationMaxHourObject} 包含小时、分钟、秒、毫秒的时间持续对象
998
+ * @throws {TypeError} 当 seconds 不是有效数字时抛出
999
+ * @throws {RangeError} 当 seconds 为负数时抛出
1000
+ * @example
1001
+ * // 返回 { hours: 11686, minutes: 6, seconds: 40, milliseconds: 500 }
1002
+ * second2DurationMaxHour(42070000.5);
1003
+ */
1004
+ function second2DurationMaxHour(seconds) {
1005
+ if (typeof seconds !== "number" || isNaN(seconds)) {
1006
+ throw new TypeError("seconds must be a valid number");
1007
+ }
1008
+ if (seconds < 0) {
1009
+ throw new RangeError("seconds must be a non-negative number");
1010
+ }
1011
+ return millisecond2DurationMaxHour(seconds * 1000);
1012
+ }
1013
+
1014
+ //#endregion
1015
+
1016
+ /**
1017
+ * 根据小时数返回对应的时间段名称。
1018
+ *
1019
+ * @param {number} hour - 24 小时制的小时(0-23)
1020
+ * @param {object} [locales] - 自定义时段文案
1021
+ * @param {string} [locales.earlyMorning="凌晨"] - 00-05
1022
+ * @param {string} [locales.morning="上午"] - 06-11
1023
+ * @param {string} [locales.noon="中午"] - 12-13
1024
+ * @param {string} [locales.afternoon="下午"] - 14-17
1025
+ * @param {string} [locales.evening="晚上"] - 18-23
1026
+ * @returns {string} 时段名称
1027
+ * @throws {RangeError} 当 hour 不在 0-23 范围时抛出
1028
+ */
1029
+ function getTimePeriodName(hour, locales = getLocales_TimePeriod()) {
1030
+ if (!Number.isInteger(hour) || hour < 0 || hour > 23) {
1031
+ throw new RangeError("hour 必须是 0-23 的整数");
1032
+ }
1033
+ if (hour >= 0 && hour < 6) return locales.earlyMorning;
1034
+ if (hour < 12) return locales.morning;
1035
+ if (hour < 14) return locales.noon;
1036
+ if (hour < 18) return locales.afternoon;
1037
+ return locales.evening;
1038
+ }
1039
+
1040
+ /**
1041
+ * 格式化时间戳为本地化的时间字符串。
1042
+ *
1043
+ * @param {number} timestamp - 要格式化的时间戳(毫秒)。
1044
+ * @param {Object} [locales] - 本地化配置对象,包含时间相关的本地化字符串。
1045
+ * @param {string} [locales.justNow='刚刚'] - 表示刚刚过去的时间。
1046
+ * @param {string} [locales.today='今天'] - 表示今天。
1047
+ * @param {string} [locales.yesterday='昨天'] - 表示昨天。
1048
+ * @param {string} [locales.beforeYesterday='前天'] - 表示前天。
1049
+ * @param {string} [locales.year='年'] - 年的单位。
1050
+ * @param {string} [locales.month='月'] - 月的单位。
1051
+ * @param {string} [locales.day='日'] - 日的单位。
1052
+ * @param {Object} [locales.timePeriod] - 一天中不同时间段的本地化字符串。
1053
+ * @param {string} [locales.timePeriod.earlyMorning='凌晨'] - 凌晨。
1054
+ * @param {string} [locales.timePeriod.morning='上午'] - 上午。
1055
+ * @param {string} [locales.timePeriod.noon='中午'] - 中午。
1056
+ * @param {string} [locales.timePeriod.afternoon='下午'] - 下午。
1057
+ * @param {string} [locales.timePeriod.evening='晚上'] - 晚上。
1058
+ * @param {Array<string>} [locales.weekDays=['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']] - 星期几的本地化字符串数组。
1059
+ *
1060
+ * @returns {string} - 格式化后的时间字符串。
1061
+ */
1062
+ function formatTimeForLocale(
1063
+ timestamp,
1064
+ locales = {
1065
+ justNow: "刚刚",
1066
+ today: "今天",
1067
+ yesterday: "昨天",
1068
+ beforeYesterday: "前天",
1069
+ year: "年",
1070
+ month: "月",
1071
+ day: "日",
1072
+ timePeriod: getLocales_TimePeriod(),
1073
+ weekDays: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
1074
+ }
1075
+ ) {
1076
+ const now = new Date();
1077
+ const messageDate = new Date(timestamp);
1078
+
1079
+ const nowTime = now.getTime();
1080
+ const msgTime = messageDate.getTime();
1081
+ const diff = nowTime - msgTime;
1082
+ const diffMinutes = Math.floor(diff / (1000 * 60));
1083
+
1084
+ const year = messageDate.getFullYear();
1085
+ const month = messageDate.getMonth() + 1;
1086
+ const day = messageDate.getDate();
1087
+ const hour = messageDate.getHours();
1088
+ const minute = messageDate.getMinutes().toString().padStart(2, "0");
1089
+
1090
+ // 刚刚:1分钟内
1091
+ if (diffMinutes < 1) {
1092
+ return locales.justNow;
1093
+ }
1094
+
1095
+ // 计算自然天数差(按日期而非时间差)
1096
+ const nowDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
1097
+ const msgDate = new Date(year, month - 1, day);
1098
+ const diffDays = Math.floor((nowDate.getTime() - msgDate.getTime()) / (1000 * 60 * 60 * 24));
1099
+
1100
+ const period = getTimePeriodName(hour, locales.timePeriod);
1101
+ const timeStr = `${hour}:${minute}`;
1102
+
1103
+ // 今天
1104
+ if (diffDays === 0) {
1105
+ return `${locales.today} ${period}${timeStr}`;
1106
+ }
1107
+
1108
+ // 昨天
1109
+ if (diffDays === 1) {
1110
+ return `${locales.yesterday} ${period}${timeStr}`;
1111
+ }
1112
+
1113
+ // 前天
1114
+ if (diffDays === 2) {
1115
+ return `${locales.beforeYesterday} ${period}${timeStr}`;
1116
+ }
1117
+
1118
+ // 本周内(周一到周日,且不是今天/昨天/前天)
1119
+ // 获取本周一的日期
1120
+ const nowDay = now.getDay() || 7; // 周日转为7
1121
+ const msgDay = messageDate.getDay() || 7;
1122
+ const mondayOfThisWeek = new Date(nowDate.getTime() - (nowDay - 1) * 24 * 60 * 60 * 1000);
1123
+ const mondayOfThatWeek = new Date(msgDate.getTime() - (msgDay - 1) * 24 * 60 * 60 * 1000);
1124
+
1125
+ if (mondayOfThisWeek.getTime() === mondayOfThatWeek.getTime() && diffDays < 7) {
1126
+ const weekDayName = locales.weekDays[messageDate.getDay()];
1127
+ return `${weekDayName}${period} ${timeStr}`;
1128
+ }
1129
+
1130
+ // 本月内(非本周)
1131
+ const nowYear = now.getFullYear();
1132
+ const nowMonth = now.getMonth();
1133
+ if (year === nowYear && messageDate.getMonth() === nowMonth) {
1134
+ return `${month}${locales.month}${day}${locales.day} ${period}${timeStr}`;
1135
+ }
1136
+
1137
+ // 本年内(非本月)
1138
+ if (year === nowYear) {
1139
+ return `${month}${locales.month}${day}${locales.day} ${period}${timeStr}`;
1140
+ }
1141
+
1142
+ // 其他(非本年)
1143
+ return `${year}${locales.year}${month}${locales.month}${day}${locales.day} ${period}${timeStr}`;
893
1144
  }
894
1145
 
895
- /**
896
- * 快捷调用 {@link formatDuration},最大单位到“天”。
897
- *
898
- * @param {number} totalSeconds
899
- * @param {Omit<Parameters<typeof formatDuration>[1],'maxUnit'>} [options]
900
- * @returns {string}
901
- */
902
- function formatDurationMaxDay(totalSeconds, options = {}) {
903
- return formatDuration(totalSeconds, { ...options, maxUnit: "day" });
904
- }
905
-
906
- /**
907
- * 快捷调用 {@link formatDuration},最大单位到“小时”。
908
- *
909
- * @param {number} totalSeconds
910
- * @param {Omit<Parameters<typeof formatDuration>[1],'maxUnit'>} [options]
911
- * @returns {string}
912
- */
913
- function formatDurationMaxHour(totalSeconds, options = {}) {
914
- return formatDuration(totalSeconds, { ...options, maxUnit: "hour" });
915
- }
916
-
917
- /**
918
- * 通过动态创建 `<a>` 标签触发浏览器下载。
919
- * 注意:此方法可能无法强制下载浏览器原生支持的文件(如图片、PDF),浏览器可能会选择直接打开。
920
- *
921
- * @param {string} url - 任意可下载地址(同源或允许跨域)
922
- * @param {string} [fileName] - 保存到本地的文件名;不传时使用时间戳
923
- */
924
- function downloadByUrl(url, fileName) {
925
- const a = document.createElement("a");
926
- a.style.display = "none";
927
- a.rel = "noopener";
928
- a.href = url;
929
- a.download = fileName || Date.now();
930
- document.body.appendChild(a);
931
- a.click();
932
- document.body.removeChild(a);
933
- }
934
-
935
- /**
936
- * 把 Blob 转成临时 URL 并触发下载,下载完成后立即释放内存。
937
- *
938
- * @param {Blob} blob - 待下载的 Blob(含 File)
939
- * @param {string} [fileName] - 保存到本地的文件名
940
- */
941
- function downloadByBlob(blob, fileName) {
942
- const url = URL.createObjectURL(blob);
943
- downloadByUrl(url, fileName);
944
- setTimeout(() => URL.revokeObjectURL(url), 0);
945
- }
946
-
947
- /**
948
- * 将任意数据包装成 Blob 并下载。
949
- *
950
- * @param {string | ArrayBufferView | ArrayBuffer | Blob} data - 要写入文件的数据
951
- * @param {string} [fileName] - 保存到本地的文件名
952
- * @param {string} [mimeType] - MIME 类型;默认 `application/octet-stream`
953
- */
954
- function downloadByData(data, fileName, mimeType = "application/octet-stream") {
955
- downloadByBlob(new Blob([data], { type: mimeType }), fileName);
956
- }
957
-
958
- /**
959
- * 快捷下载 Excel 文件(MIME 已固定)。
960
- *
961
- * @param {string | ArrayBufferView | ArrayBuffer | Blob} data - Excel 二进制或字符串内容
962
- * @param {string} [fileName] - 保存到本地的文件名
963
- */
964
- function downloadExcel(data, fileName) {
965
- downloadByData(data, fileName, "application/vnd.ms-excel");
966
- }
967
-
968
- /**
969
- * 快捷下载 JSON 文件(MIME 已固定)。
970
- * 若传入非字符串数据,会自行 `JSON.stringify`。
971
- *
972
- * @param {any} data - 要序列化的 JSON 数据
973
- * @param {string} [fileName] - 保存到本地的文件名
974
- */
975
- function downloadJSON(data, fileName) {
976
- // downloadByData(typeof data === "string" ? data : JSON.stringify(data, null, 4), fileName, "application/json");
977
- downloadByData(data, fileName, "application/json");
978
- }
979
-
980
- /**
981
- * 通过 `fetch` 获取资源并强制下载,避免浏览器直接打开文件。
982
- * 此方法适用于下载图片、PDF 等浏览器默认会打开的文件类型。
983
- * 如果 `fetch` 失败(如 CORS 策略阻止),会回退到 `downloadByUrl` 方法作为备选方案。
984
- *
985
- * @param {string} url - 文件的 URL 地址
986
- * @param {string} [fileName] - 保存到本地的文件名。如果不提供,会尝试从 URL 中自动提取
987
- * @returns {Promise<void>} 返回一个 Promise,在下载开始或失败后 resolve
988
- */
989
- async function fetchOrDownloadByUrl(url, fileName) {
990
- // 如果未提供文件名,尝试从 URL 路径中提取
991
- if (!fileName) {
992
- try {
993
- const urlPathname = new URL(url).pathname;
994
- // 获取路径的最后一部分作为文件名,并移除可能的查询参数
995
- fileName = urlPathname.substring(urlPathname.lastIndexOf("/") + 1).split("?")[0];
996
- } catch (e) {}
997
- // 如果提取后文件名为空(例如 URL 以 '/' 结尾),也使用时间戳
998
- if (!fileName) {
999
- fileName = Date.now().toString();
1000
- }
1001
- }
1002
-
1003
- try {
1004
- const response = await fetch(url, {
1005
- method: "GET",
1006
- mode: "cors",
1007
- cache: "no-cache"
1008
- });
1009
-
1010
- if (!response.ok) {
1011
- throw new Error(`HTTP error! ${response.status}: ${response.statusText}`);
1012
- }
1013
-
1014
- const blob = await response.blob();
1015
- downloadByBlob(blob, fileName);
1016
- } catch (error) {
1017
- downloadByUrl(url, fileName);
1018
- }
1146
+ /**
1147
+ * 通过动态创建 `<a>` 标签触发浏览器下载。
1148
+ * 注意:此方法可能无法强制下载浏览器原生支持的文件(如图片、PDF),浏览器可能会选择直接打开。
1149
+ *
1150
+ * @param {string} url - 任意可下载地址(同源或允许跨域)
1151
+ * @param {string} [fileName] - 保存到本地的文件名;不传时使用时间戳
1152
+ */
1153
+ function downloadByUrl(url, fileName) {
1154
+ const a = document.createElement("a");
1155
+ a.style.display = "none";
1156
+ a.rel = "noopener";
1157
+ a.href = url;
1158
+ a.download = fileName || Date.now();
1159
+ document.body.appendChild(a);
1160
+ a.click();
1161
+ document.body.removeChild(a);
1162
+ }
1163
+
1164
+ /**
1165
+ * Blob 转成临时 URL 并触发下载,下载完成后立即释放内存。
1166
+ *
1167
+ * @param {Blob} blob - 待下载的 Blob(含 File)
1168
+ * @param {string} [fileName] - 保存到本地的文件名
1169
+ */
1170
+ function downloadByBlob(blob, fileName) {
1171
+ const url = URL.createObjectURL(blob);
1172
+ downloadByUrl(url, fileName);
1173
+ setTimeout(() => URL.revokeObjectURL(url), 0);
1174
+ }
1175
+
1176
+ /**
1177
+ * 将任意数据包装成 Blob 并下载。
1178
+ *
1179
+ * @param {string | ArrayBufferView | ArrayBuffer | Blob} data - 要写入文件的数据
1180
+ * @param {string} [fileName] - 保存到本地的文件名
1181
+ * @param {string} [mimeType] - MIME 类型;默认 `application/octet-stream`
1182
+ */
1183
+ function downloadByData(data, fileName, mimeType = "application/octet-stream") {
1184
+ downloadByBlob(new Blob([data], { type: mimeType }), fileName);
1185
+ }
1186
+
1187
+ /**
1188
+ * 快捷下载 Excel 文件(MIME 已固定)。
1189
+ *
1190
+ * @param {string | ArrayBufferView | ArrayBuffer | Blob} data - Excel 二进制或字符串内容
1191
+ * @param {string} [fileName] - 保存到本地的文件名
1192
+ */
1193
+ function downloadExcel(data, fileName) {
1194
+ downloadByData(data, fileName, "application/vnd.ms-excel");
1195
+ }
1196
+
1197
+ /**
1198
+ * 快捷下载 JSON 文件(MIME 已固定)。
1199
+ * 若传入非字符串数据,会自行 `JSON.stringify`。
1200
+ *
1201
+ * @param {any} data - 要序列化的 JSON 数据
1202
+ * @param {string} [fileName] - 保存到本地的文件名
1203
+ */
1204
+ function downloadJSON(data, fileName) {
1205
+ // downloadByData(typeof data === "string" ? data : JSON.stringify(data, null, 4), fileName, "application/json");
1206
+ downloadByData(data, fileName, "application/json");
1207
+ }
1208
+
1209
+ /**
1210
+ * 通过 `fetch` 获取资源并强制下载,避免浏览器直接打开文件。
1211
+ * 此方法适用于下载图片、PDF 等浏览器默认会打开的文件类型。
1212
+ * 如果 `fetch` 失败(如 CORS 策略阻止),会回退到 `downloadByUrl` 方法作为备选方案。
1213
+ *
1214
+ * @param {string} url - 文件的 URL 地址
1215
+ * @param {string} [fileName] - 保存到本地的文件名。如果不提供,会尝试从 URL 中自动提取
1216
+ * @returns {Promise<void>} 返回一个 Promise,在下载开始或失败后 resolve
1217
+ */
1218
+ async function fetchOrDownloadByUrl(url, fileName) {
1219
+ // 如果未提供文件名,尝试从 URL 路径中提取
1220
+ if (!fileName) {
1221
+ try {
1222
+ const urlPathname = new URL(url).pathname;
1223
+ // 获取路径的最后一部分作为文件名,并移除可能的查询参数
1224
+ fileName = urlPathname.substring(urlPathname.lastIndexOf("/") + 1).split("?")[0];
1225
+ } catch (e) {}
1226
+ // 如果提取后文件名为空(例如 URL 以 '/' 结尾),也使用时间戳
1227
+ if (!fileName) {
1228
+ fileName = Date.now().toString();
1229
+ }
1230
+ }
1231
+
1232
+ try {
1233
+ const response = await fetch(url, {
1234
+ method: "GET",
1235
+ mode: "cors",
1236
+ cache: "no-cache"
1237
+ });
1238
+
1239
+ if (!response.ok) {
1240
+ throw new Error(`HTTP error! ${response.status}: ${response.statusText}`);
1241
+ }
1242
+
1243
+ const blob = await response.blob();
1244
+ downloadByBlob(blob, fileName);
1245
+ } catch (error) {
1246
+ downloadByUrl(url, fileName);
1247
+ }
1019
1248
  }
1020
1249
 
1021
- /**
1022
- * 简单、高性能的通用事件总线。
1023
- * - 支持命名空间事件
1024
- * - 支持一次性监听器
1025
- * - 返回唯一 flag,用于精确卸载
1026
- * - emit 时可选自定义 this 指向
1027
- */
1028
- class MyEvent {
1029
- constructor() {
1030
- this.evtPool = new Map();
1031
- }
1032
-
1033
- /**
1034
- * 注册事件监听器。
1035
- * @param {string} name - 事件名
1036
- * @param {Function} fn - 回调函数
1037
- * @returns {string} flag - 唯一标识,用于 off
1038
- */
1039
- on(name, fn) {
1040
- let flag = Date.now() + "_" + parseInt(Math.random() * 1e8);
1041
- const evtItem = {
1042
- flag,
1043
- fn
1044
- };
1045
- if (this.evtPool.has(name)) {
1046
- this.evtPool.get(name).push(evtItem);
1047
- } else {
1048
- this.evtPool.set(name, [evtItem]);
1049
- }
1050
- return flag;
1051
- }
1052
-
1053
- /**
1054
- * 注册一次性监听器,触发后自动移除。
1055
- * @param {string} name - 事件名
1056
- * @param {Function} fn - 回调函数
1057
- * @returns {string} flag - 唯一标识
1058
- */
1059
- once(name, fn) {
1060
- const _this = this;
1061
- let wrapper;
1062
- wrapper = function (data) {
1063
- _this.off(name, wrapper);
1064
- fn.call(this, data);
1065
- };
1066
- return this.on(name, wrapper);
1067
- }
1068
-
1069
- /**
1070
- * 移除指定事件监听器。
1071
- * @param {string} name - 事件名
1072
- * @param {Function|string} fnOrFlag - 回调函数或 flag
1073
- */
1074
- off(name, fnOrFlag) {
1075
- if (!this.evtPool.has(name)) return;
1076
- const evtItems = this.evtPool.get(name);
1077
- const filtered = evtItems.filter((item) => item.fn !== fnOrFlag && item.flag !== fnOrFlag);
1078
- if (filtered.length === 0) {
1079
- this.evtPool.delete(name);
1080
- } else {
1081
- this.evtPool.set(name, filtered);
1082
- }
1083
- }
1084
-
1085
- /**
1086
- * 触发事件(同步执行)。
1087
- * @param {string} name - 事件名
1088
- * @param {*} [data] - 任意载荷
1089
- * @param {*} [fnThis] - 回调内部 this 指向,默认 undefined
1090
- */
1091
- emit(name, data, fnThis) {
1092
- if (!this.evtPool.has(name)) return;
1093
- const evtItems = this.evtPool.get(name);
1094
- evtItems.forEach((item) => {
1095
- try {
1096
- item.fn.call(fnThis, data);
1097
- } catch (err) {
1098
- console.error(`Error in event listener for "${name}":`, err);
1099
- }
1100
- });
1101
- }
1102
- }
1103
-
1104
- /**
1105
- * 跨页通信插件:通过 localStorage + storage 事件将当前实例的 emit 广播到其他同源页面。
1106
- * 支持节流、命名空间隔离。
1107
- */
1108
- const MyEvent_CrossPagePlugin = (() => {
1109
- const INSTALLED = new WeakSet(); // 防止重复安装
1110
-
1111
- return {
1112
- /**
1113
- * 为指定 MyEvent 实例安装跨页插件。
1114
- * @param {MyEvent} bus - 事件总线实例
1115
- * @param {Options} [opts] - 配置项
1116
- */
1117
- install(bus, opts = {}) {
1118
- if (INSTALLED.has(bus)) return;
1119
- INSTALLED.add(bus);
1120
-
1121
- const ns = `___my-event-cross-page-${opts.namespace || "default"}___`;
1122
- const delay = opts.throttle || 16;
1123
- let last = 0;
1124
-
1125
- // 1、重写 emit
1126
- const rawEmit = bus.emit;
1127
- bus.emit = function (name, data, fnThis) {
1128
- rawEmit.call(bus, name, data, fnThis); // 本地先执行
1129
- const now = Date.now();
1130
- if (now - last < delay) return;
1131
- last = now;
1132
- const key = ns + name;
1133
- try {
1134
- localStorage.setItem(key, JSON.stringify({ name, data, ts: now }));
1135
- localStorage.removeItem(key); // 触发 storage 事件
1136
- } catch (e) {}
1137
- };
1138
-
1139
- // 2、监听其他页广播
1140
- function onStorageHandler(e) {
1141
- if (!e.key || !e.key.startsWith(ns)) return;
1142
- let payload;
1143
- try {
1144
- payload = JSON.parse(e.newValue || "{}");
1145
- } catch {
1146
- return;
1147
- }
1148
- if (!payload.ts || payload.ts <= last) return;
1149
- rawEmit.call(bus, e.key.slice(ns.length), payload.data); // 仅本地
1150
- }
1151
- addEventListener("storage", onStorageHandler);
1152
-
1153
- // 3、保存卸载器
1154
- bus._uninstallCrossPage = () => {
1155
- removeEventListener("storage", onStorageHandler);
1156
- bus.emit = rawEmit;
1157
- INSTALLED.delete(bus);
1158
- };
1159
- },
1160
-
1161
- /**
1162
- * 卸载插件,恢复原始 emit 并停止监听。
1163
- * @param {MyEvent} bus - 事件总线实例
1164
- */
1165
- uninstall(bus) {
1166
- if (typeof bus._uninstallCrossPage === "function") bus._uninstallCrossPage();
1167
- }
1168
- };
1250
+ /**
1251
+ * 简单、高性能的通用事件总线。
1252
+ * - 支持命名空间事件
1253
+ * - 支持一次性监听器
1254
+ * - 返回唯一 flag,用于精确卸载
1255
+ * - emit 时可选自定义 this 指向
1256
+ */
1257
+ class MyEvent {
1258
+ constructor() {
1259
+ this.evtPool = new Map();
1260
+ }
1261
+
1262
+ /**
1263
+ * 注册事件监听器。
1264
+ * @param {string} name - 事件名
1265
+ * @param {Function} fn - 回调函数
1266
+ * @returns {string} flag - 唯一标识,用于 off
1267
+ */
1268
+ on(name, fn) {
1269
+ let flag = Date.now() + "_" + parseInt(Math.random() * 1e8);
1270
+ const evtItem = {
1271
+ flag,
1272
+ fn
1273
+ };
1274
+ if (this.evtPool.has(name)) {
1275
+ this.evtPool.get(name).push(evtItem);
1276
+ } else {
1277
+ this.evtPool.set(name, [evtItem]);
1278
+ }
1279
+ return flag;
1280
+ }
1281
+
1282
+ /**
1283
+ * 注册一次性监听器,触发后自动移除。
1284
+ * @param {string} name - 事件名
1285
+ * @param {Function} fn - 回调函数
1286
+ * @returns {string} flag - 唯一标识
1287
+ */
1288
+ once(name, fn) {
1289
+ const _this = this;
1290
+ let wrapper;
1291
+ wrapper = function (data) {
1292
+ _this.off(name, wrapper);
1293
+ fn.call(this, data);
1294
+ };
1295
+ return this.on(name, wrapper);
1296
+ }
1297
+
1298
+ /**
1299
+ * 移除指定事件监听器。
1300
+ * @param {string} name - 事件名
1301
+ * @param {Function|string} fnOrFlag - 回调函数或 flag
1302
+ */
1303
+ off(name, fnOrFlag) {
1304
+ if (!this.evtPool.has(name)) return;
1305
+ const evtItems = this.evtPool.get(name);
1306
+ const filtered = evtItems.filter((item) => item.fn !== fnOrFlag && item.flag !== fnOrFlag);
1307
+ if (filtered.length === 0) {
1308
+ this.evtPool.delete(name);
1309
+ } else {
1310
+ this.evtPool.set(name, filtered);
1311
+ }
1312
+ }
1313
+
1314
+ /**
1315
+ * 触发事件(同步执行)。
1316
+ * @param {string} name - 事件名
1317
+ * @param {*} [data] - 任意载荷
1318
+ * @param {*} [fnThis] - 回调内部 this 指向,默认 undefined
1319
+ */
1320
+ emit(name, data, fnThis) {
1321
+ if (!this.evtPool.has(name)) return;
1322
+ const evtItems = this.evtPool.get(name);
1323
+ evtItems.forEach((item) => {
1324
+ try {
1325
+ item.fn.call(fnThis, data);
1326
+ } catch (err) {
1327
+ console.error(`Error in event listener for "${name}":`, err);
1328
+ }
1329
+ });
1330
+ }
1331
+ }
1332
+
1333
+ /**
1334
+ * 跨页通信插件:通过 localStorage + storage 事件将当前实例的 emit 广播到其他同源页面。
1335
+ * 支持节流、命名空间隔离。
1336
+ */
1337
+ const MyEvent_CrossPagePlugin = (() => {
1338
+ const INSTALLED = new WeakSet(); // 防止重复安装
1339
+
1340
+ return {
1341
+ /**
1342
+ * 为指定 MyEvent 实例安装跨页插件。
1343
+ * @param {MyEvent} bus - 事件总线实例
1344
+ * @param {Options} [opts] - 配置项
1345
+ */
1346
+ install(bus, opts = {}) {
1347
+ if (INSTALLED.has(bus)) return;
1348
+ INSTALLED.add(bus);
1349
+
1350
+ const ns = `___my-event-cross-page-${opts.namespace || "default"}___`;
1351
+ const delay = opts.throttle || 16;
1352
+ let last = 0;
1353
+
1354
+ // 1、重写 emit
1355
+ const rawEmit = bus.emit;
1356
+ bus.emit = function (name, data, fnThis) {
1357
+ rawEmit.call(bus, name, data, fnThis); // 本地先执行
1358
+ const now = Date.now();
1359
+ if (now - last < delay) return;
1360
+ last = now;
1361
+ const key = ns + name;
1362
+ try {
1363
+ localStorage.setItem(key, JSON.stringify({ name, data, ts: now }));
1364
+ localStorage.removeItem(key); // 触发 storage 事件
1365
+ } catch (e) {}
1366
+ };
1367
+
1368
+ // 2、监听其他页广播
1369
+ function onStorageHandler(e) {
1370
+ if (!e.key || !e.key.startsWith(ns)) return;
1371
+ let payload;
1372
+ try {
1373
+ payload = JSON.parse(e.newValue || "{}");
1374
+ } catch {
1375
+ return;
1376
+ }
1377
+ if (!payload.ts || payload.ts <= last) return;
1378
+ rawEmit.call(bus, e.key.slice(ns.length), payload.data); // 仅本地
1379
+ }
1380
+ addEventListener("storage", onStorageHandler);
1381
+
1382
+ // 3、保存卸载器
1383
+ bus._uninstallCrossPage = () => {
1384
+ removeEventListener("storage", onStorageHandler);
1385
+ bus.emit = rawEmit;
1386
+ INSTALLED.delete(bus);
1387
+ };
1388
+ },
1389
+
1390
+ /**
1391
+ * 卸载插件,恢复原始 emit 并停止监听。
1392
+ * @param {MyEvent} bus - 事件总线实例
1393
+ */
1394
+ uninstall(bus) {
1395
+ if (typeof bus._uninstallCrossPage === "function") bus._uninstallCrossPage();
1396
+ }
1397
+ };
1169
1398
  })();
1170
1399
 
1171
- /**
1172
- * 生成 RFC4122 版本 4 的 GUID/UUID。
1173
- * 收集来源:《基于mvc的javascript web富应用开发》 书中介绍是Robert Kieffer写的,还留了网址 http://goo.gl/0b0hu ,但实际访问不了。
1174
- * 格式:`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`
1175
- *
1176
- * @returns {string} 36 位大写 GUID
1177
- *
1178
- * @example
1179
- * // A2E0F340-6C3B-4D7F-B8C1-1E4F6A8B9C0D
1180
- * console.log(getGUID())
1181
- */
1182
- function getGUID() {
1183
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1184
- let r = (Math.random() * 16) | 0,
1185
- v = c == "x" ? r : (r & 0x3) | 0x8;
1186
- return v.toString(16).toUpperCase();
1187
- });
1188
- }
1189
-
1190
- /**
1191
- * 分布式短 ID 生成器。
1192
- * 格式:`${timestamp}${flag}${serial}`,其中:
1193
- * - timestamp:毫秒级时间戳
1194
- * - flag:客户端标识串(自定义)
1195
- * - serial:同一毫秒内的序号,左补零到固定长度
1196
- */
1197
- class MyId {
1198
- #ts = Date.now(); // 时间戳
1199
- #sn = 0; // 序号(保证同一客户端之间的唯一项)
1200
- #flag = ""; // 客户端标识(保证不同客户端之间的唯一项)
1201
- #len = 5; // 序号位长度(我的电脑测试,同一时间戳内可以for循环执行了1000次左右,没有一次超过3k,所以5位应该够用了)
1202
- // 测试代码
1203
- // let obj = {[Date.now()]:[]}; try { for (let i = 0; i < 100000; i++) { obj[Date.now()].push(i); } } catch { console.log(obj[Object.getOwnPropertyNames(obj)[0]].length); }
1204
-
1205
- /**
1206
- * @param {object} [option]
1207
- * @param {string} [option.flag] - 客户端标识,默认空串
1208
- * @param {number} [option.len=5] - 序号位长度(位数),安全范围 ≥0
1209
- */
1210
- constructor(option = {}) {
1211
- if (option) {
1212
- if (typeof option.flag === "string") {
1213
- this.#flag = option.flag;
1214
- }
1215
- if (Number.isSafeInteger(option.len) && len >= 0) {
1216
- this.#len = option.len;
1217
- }
1218
- }
1219
- }
1220
-
1221
- /**
1222
- * 生成下一个全局唯一字符串 ID。
1223
- * 同一毫秒序号自动递增;序号溢出时会在控制台警告。
1224
- * @returns {string}
1225
- */
1226
- nextId() {
1227
- let ts = Date.now();
1228
- if (ts === this.#ts) {
1229
- this.#sn++;
1230
- if (this.#sn >= 10 ** this.#len) {
1231
- console.log("长度不够用了!!!");
1232
- }
1233
- } else {
1234
- this.#sn = 0;
1235
- this.#ts = ts;
1236
- }
1237
- return ts.toString() + this.#flag + this.#sn.toString().padStart(this.#len, "0");
1238
- }
1239
- }
1240
-
1241
- /**
1242
- * 基于 `setTimeout` 的“间隔循环”定时器。
1243
- * 每次任务执行完成后才计算下一次间隔,避免任务堆积。
1244
- */
1245
- class IntervalTimer {
1246
- /**
1247
- * 创建定时器实例。
1248
- * @param {() => void} fn - 每次间隔要执行的业务函数
1249
- * @param {number} [ms=1000] - 间隔时间(毫秒)
1250
- * @throws {TypeError} 当 `fn` 不是函数时抛出
1251
- */
1252
- constructor(fn, ms = 1000) {
1253
- if (typeof fn !== "function") {
1254
- throw new TypeError("IntervalTimer: 必须传入一个函数");
1255
- }
1256
- this._fn = fn;
1257
- this._ms = ms;
1258
- this._timerId = null;
1259
- }
1260
-
1261
- /**
1262
- * 启动定时器;若已启动则先停止再重新启动。
1263
- * 首次执行会立即触发。
1264
- */
1265
- start() {
1266
- this.stop();
1267
- const loop = () => {
1268
- this._fn(); // 执行业务
1269
- this._timerId = setTimeout(loop, this._ms);
1270
- };
1271
- loop(); // 立即执行第一次
1272
- }
1273
-
1274
- /**
1275
- * 停止定时器。
1276
- */
1277
- stop() {
1278
- if (this._timerId !== null) {
1279
- clearTimeout(this._timerId);
1280
- this._timerId = null;
1281
- }
1282
- }
1283
-
1284
- /**
1285
- * 查询定时器是否正在运行。
1286
- * @returns {boolean}
1287
- */
1288
- isRunning() {
1289
- return this._timerId !== null;
1290
- }
1400
+ /**
1401
+ * 生成 RFC4122 版本 4 的 GUID/UUID。
1402
+ * 收集来源:《基于mvc的javascript web富应用开发》 书中介绍是Robert Kieffer写的,还留了网址 http://goo.gl/0b0hu ,但实际访问不了。
1403
+ * 格式:`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`
1404
+ *
1405
+ * @returns {string} 36 位大写 GUID
1406
+ *
1407
+ * @example
1408
+ * // A2E0F340-6C3B-4D7F-B8C1-1E4F6A8B9C0D
1409
+ * console.log(getGUID())
1410
+ */
1411
+ function getGUID() {
1412
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1413
+ let r = (Math.random() * 16) | 0,
1414
+ v = c == "x" ? r : (r & 0x3) | 0x8;
1415
+ return v.toString(16).toUpperCase();
1416
+ });
1417
+ }
1418
+
1419
+ /**
1420
+ * 分布式短 ID 生成器。
1421
+ * 格式:`${timestamp}${flag}${serial}`,其中:
1422
+ * - timestamp:毫秒级时间戳
1423
+ * - flag:客户端标识串(自定义)
1424
+ * - serial:同一毫秒内的序号,左补零到固定长度
1425
+ */
1426
+ class MyId {
1427
+ #ts = Date.now(); // 时间戳
1428
+ #sn = 0; // 序号(保证同一客户端之间的唯一项)
1429
+ #flag = ""; // 客户端标识(保证不同客户端之间的唯一项)
1430
+ #len = 5; // 序号位长度(我的电脑测试,同一时间戳内可以for循环执行了1000次左右,没有一次超过3k,所以5位应该够用了)
1431
+ // 测试代码
1432
+ // let obj = {[Date.now()]:[]}; try { for (let i = 0; i < 100000; i++) { obj[Date.now()].push(i); } } catch { console.log(obj[Object.getOwnPropertyNames(obj)[0]].length); }
1433
+
1434
+ /**
1435
+ * @param {object} [option]
1436
+ * @param {string} [option.flag] - 客户端标识,默认空串
1437
+ * @param {number} [option.len=5] - 序号位长度(位数),安全范围 ≥0
1438
+ */
1439
+ constructor(option = {}) {
1440
+ if (option) {
1441
+ if (typeof option.flag === "string") {
1442
+ this.#flag = option.flag;
1443
+ }
1444
+ if (Number.isSafeInteger(option.len) && len >= 0) {
1445
+ this.#len = option.len;
1446
+ }
1447
+ }
1448
+ }
1449
+
1450
+ /**
1451
+ * 生成下一个全局唯一字符串 ID。
1452
+ * 同一毫秒序号自动递增;序号溢出时会在控制台警告。
1453
+ * @returns {string}
1454
+ */
1455
+ nextId() {
1456
+ let ts = Date.now();
1457
+ if (ts === this.#ts) {
1458
+ this.#sn++;
1459
+ if (this.#sn >= 10 ** this.#len) {
1460
+ console.log("长度不够用了!!!");
1461
+ }
1462
+ } else {
1463
+ this.#sn = 0;
1464
+ this.#ts = ts;
1465
+ }
1466
+ return ts.toString() + this.#flag + this.#sn.toString().padStart(this.#len, "0");
1467
+ }
1291
1468
  }
1292
1469
 
1293
- /**
1294
- * 把嵌套树拍平成 `{ [id]: node }` 映射,同时把原 `children` 置为 `null`。
1295
- *
1296
- * @template T extends Record<PropertyKey, any>
1297
- * @param {T[]} data - 嵌套树森林
1298
- * @param {string} [idKey='id'] - 主键字段
1299
- * @param {string} [childrenKey='children'] - 子节点字段
1300
- * @returns {Record<string, T & { [k in typeof childrenKey]: null }>} id→节点的映射表
1301
- */
1302
- function nestedTree2IdMap(data, idKey = "id", childrenKey = "children") {
1303
- const retObj = {};
1304
- function fn(nodes) {
1305
- if (Array.isArray(nodes) && nodes.length > 0) {
1306
- nodes.forEach((node) => {
1307
- retObj[node[idKey]] = { ...node };
1308
- retObj[node[idKey]][childrenKey] = null;
1309
-
1310
- fn(node[childrenKey]);
1311
- });
1312
- }
1313
- }
1314
- fn(data);
1315
- return retObj;
1470
+ /**
1471
+ * 基于 `setTimeout` 的“间隔循环”定时器。
1472
+ * 每次任务执行完成后才计算下一次间隔,避免任务堆积。
1473
+ */
1474
+ class IntervalTimer {
1475
+
1476
+ /**
1477
+ * 创建定时器实例。
1478
+ * @param {() => void} fn - 每次间隔要执行的业务函数
1479
+ * @param {number} [ms=1000] - 间隔时间(毫秒)
1480
+ * @throws {TypeError} 当 `fn` 不是函数时抛出
1481
+ */
1482
+ constructor(fn, ms = 1000) {
1483
+ if (typeof fn !== "function") {
1484
+ throw new TypeError("IntervalTimer: 必须传入一个函数");
1485
+ }
1486
+ this._fn = fn;
1487
+ this._ms = ms;
1488
+ this._timerId = null;
1489
+ }
1490
+
1491
+ /**
1492
+ * 启动定时器;若已启动则先停止再重新启动。
1493
+ * 首次执行会立即触发。
1494
+ */
1495
+ start() {
1496
+ this.stop();
1497
+ const loop = () => {
1498
+ this._fn(); // 执行业务
1499
+ this._timerId = setTimeout(loop, this._ms);
1500
+ };
1501
+ loop(); // 立即执行第一次
1502
+ }
1503
+
1504
+ /**
1505
+ * 停止定时器。
1506
+ */
1507
+ stop() {
1508
+ if (this._timerId !== null) {
1509
+ clearTimeout(this._timerId);
1510
+ this._timerId = null;
1511
+ }
1512
+ }
1513
+
1514
+ /**
1515
+ * 查询定时器是否正在运行。
1516
+ * @returns {boolean}
1517
+ */
1518
+ isRunning() {
1519
+ return this._timerId !== null;
1520
+ }
1316
1521
  }
1317
1522
 
1318
- /**
1319
- * 把**已包含完整父子关系**的扁平节点列表还原成嵌套树(森林)。
1320
- *
1321
- * @template T extends Record<PropertyKey, any>
1322
- * @param {T[]} nodes - 扁平节点列表(必须包含 id / parentId)
1323
- * @param {number | string} [parentId=0] - 根节点标识值
1324
- * @param {Object} [opts] - 字段映射配置
1325
- * @param {string} [opts.idKey='id'] - 节点主键
1326
- * @param {string} [opts.parentKey='parentId'] - 父节点外键
1327
- * @param {string} [opts.childrenKey='children'] - 存放子节点的字段
1328
- * @returns {(T & { [k in typeof childrenKey]: T[] })[]} 嵌套树森林
1329
- */
1330
- function flatCompleteTree2NestedTree(nodes, parentId = 0, { idKey = "id", parentKey = "parentId", childrenKey = "children" } = {}) {
1331
- const map = new Map(); // id -> node
1332
- const items = []; // 多根森林
1333
-
1334
- // 1. 初始化:保证每个节点都有 children,并存入 map
1335
- for (const item of nodes) {
1336
- const node = { ...item, [childrenKey]: [] };
1337
- map.set(item[idKey], node);
1338
- }
1339
-
1340
- // 2. 建立父子关系
1341
- for (const item of nodes) {
1342
- const node = map.get(item[idKey]);
1343
- const parentIdVal = item[parentKey];
1344
-
1345
- if (parentIdVal === parentId) {
1346
- // 根层
1347
- items.push(node);
1348
- } else {
1349
- // 非根层:找到父节点,把自己挂上去
1350
- const parent = map.get(parentIdVal);
1351
- if (parent) parent[childrenKey].push(node);
1352
- // 如果 parent 不存在,说明数据不完整,可自定义处理
1353
- }
1354
- }
1355
-
1356
- return items;
1523
+ /**
1524
+ * 把嵌套树拍平成 `{ [id]: node }` 映射,同时把原 `children` 置为 `null`。
1525
+ *
1526
+ * @template T extends Record<PropertyKey, any>
1527
+ * @param {T[]} data - 嵌套树森林
1528
+ * @param {string} [idKey='id'] - 主键字段
1529
+ * @param {string} [childrenKey='children'] - 子节点字段
1530
+ * @returns {Record<string, T & { [k in typeof childrenKey]: null }>} id→节点的映射表
1531
+ */
1532
+ function nestedTree2IdMap(data, idKey = "id", childrenKey = "children") {
1533
+ const retObj = {};
1534
+ function fn(nodes) {
1535
+ if (Array.isArray(nodes) && nodes.length > 0) {
1536
+ nodes.forEach((node) => {
1537
+ retObj[node[idKey]] = { ...node };
1538
+ retObj[node[idKey]][childrenKey] = null;
1539
+
1540
+ fn(node[childrenKey]);
1541
+ });
1542
+ }
1543
+ }
1544
+ fn(data);
1545
+ return retObj;
1546
+ }
1547
+
1548
+ /**
1549
+ * 把**已包含完整父子关系**的扁平节点列表还原成嵌套树(森林)。
1550
+ *
1551
+ * @template T extends Record<PropertyKey, any>
1552
+ * @param {T[]} nodes - 扁平节点列表(必须包含 id / parentId)
1553
+ * @param {number | string} [parentId=0] - 根节点标识值
1554
+ * @param {Object} [opts] - 字段映射配置
1555
+ * @param {string} [opts.idKey='id'] - 节点主键
1556
+ * @param {string} [opts.parentKey='parentId'] - 父节点外键
1557
+ * @param {string} [opts.childrenKey='children'] - 存放子节点的字段
1558
+ * @returns {(T & { [k in typeof childrenKey]: T[] })[]} 嵌套树森林
1559
+ */
1560
+ function flatCompleteTree2NestedTree(nodes, parentId = 0, { idKey = "id", parentKey = "parentId", childrenKey = "children" } = {}) {
1561
+ const map = new Map(); // id -> node
1562
+ const items = []; // 多根森林
1563
+
1564
+ // 1. 初始化:保证每个节点都有 children,并存入 map
1565
+ for (const item of nodes) {
1566
+ const node = { ...item, [childrenKey]: [] };
1567
+ map.set(item[idKey], node);
1568
+ }
1569
+
1570
+ // 2. 建立父子关系
1571
+ for (const item of nodes) {
1572
+ const node = map.get(item[idKey]);
1573
+ const parentIdVal = item[parentKey];
1574
+
1575
+ if (parentIdVal === parentId) {
1576
+ // 根层
1577
+ items.push(node);
1578
+ } else {
1579
+ // 非根层:找到父节点,把自己挂上去
1580
+ const parent = map.get(parentIdVal);
1581
+ if (parent) parent[childrenKey].push(node);
1582
+ // 如果 parent 不存在,说明数据不完整,可自定义处理
1583
+ }
1584
+ }
1585
+
1586
+ return items;
1587
+ }
1588
+
1589
+ /**
1590
+ * 在嵌套树中按 `id` 递归查找节点,并返回其指定属性值。
1591
+ *
1592
+ * @template T extends Record<PropertyKey, any>
1593
+ * @param {string | number} id - 要查找的 id
1594
+ * @param {T[]} arr - 嵌套树森林
1595
+ * @param {string} [resultKey='name'] - 需要返回的字段
1596
+ * @param {string} [idKey='id'] - 主键字段
1597
+ * @param {string} [childrenKey='children'] - 子节点字段
1598
+ * @returns {any} 找到的值;未找到返回 `undefined`
1599
+ */
1600
+ const findObjAttrValueById = function findObjAttrValueByIdFn(id, arr, resultKey = "name", idKey = "id", childrenKey = "children") {
1601
+ if (Array.isArray(arr) && arr.length > 0) {
1602
+ for (let i = 0; i < arr.length; i++) {
1603
+ const item = arr[i];
1604
+ if (item[idKey]?.toString() === id?.toString()) {
1605
+ return item[resultKey];
1606
+ } else if (Array.isArray(item[childrenKey]) && item[childrenKey].length > 0) {
1607
+ const result = findObjAttrValueByIdFn(id, item[childrenKey], resultKey, idKey, childrenKey);
1608
+ if (result) {
1609
+ return result;
1610
+ }
1611
+ }
1612
+ }
1613
+ }
1614
+ };
1615
+
1616
+ /**
1617
+ * 从服务端返回的已选 id 数组里,提取出
1618
+ * 1. 叶子节点
1619
+ * 2. 所有子节点都被选中的父节点
1620
+ * 其余父节点一律丢弃(由前端 Tree 自动算半选)
1621
+ *
1622
+ * @param {Array} treeData 完整树
1623
+ * @param {Array} selectedKeys 后端给的选中 id 数组
1624
+ * @param {String} idKey 节点唯一字段
1625
+ * @param {String} childrenKey 子节点字段
1626
+ * @returns {{checked: string[], halfChecked: string[]}}
1627
+ */
1628
+ function extractFullyCheckedKeys(treeData, selectedKeys, idKey = "id", childrenKey = "children") {
1629
+ const selectedSet = new Set(selectedKeys);
1630
+ const checked = new Set();
1631
+ const halfChecked = new Set();
1632
+
1633
+ /* 返回值含义
1634
+ 0 - 未选中
1635
+ 1 - 半选
1636
+ 2 - 全选
1637
+ */
1638
+ function dfs(node) {
1639
+ const nodeId = node[idKey];
1640
+ const children = node[childrenKey] || [];
1641
+
1642
+ // 叶子
1643
+ if (!children.length) {
1644
+ if (selectedSet.has(nodeId)) {
1645
+ checked.add(nodeId);
1646
+ return 2;
1647
+ }
1648
+ return 0;
1649
+ }
1650
+
1651
+ // 非叶子
1652
+ let allChecked = true;
1653
+ let someChecked = false;
1654
+
1655
+ children.forEach((child) => {
1656
+ const childState = dfs(child);
1657
+ if (childState !== 2) allChecked = false;
1658
+ if (childState >= 1) someChecked = true;
1659
+ });
1660
+
1661
+ // 当前节点本身在 selectedKeys 里,但子节点未全选 → 只能算半选
1662
+ if (selectedSet.has(nodeId)) {
1663
+ if (allChecked) {
1664
+ checked.add(nodeId);
1665
+ return 2;
1666
+ }
1667
+ halfChecked.add(nodeId);
1668
+ return 1;
1669
+ }
1670
+
1671
+ // 当前节点不在 selectedKeys 里,看子节点
1672
+ if (allChecked) {
1673
+ checked.add(nodeId);
1674
+ return 2;
1675
+ }
1676
+ if (someChecked) {
1677
+ halfChecked.add(nodeId);
1678
+ return 1;
1679
+ }
1680
+ return 0;
1681
+ }
1682
+
1683
+ treeData.forEach(dfs);
1684
+ return {
1685
+ checked: [...checked],
1686
+ halfChecked: [...halfChecked]
1687
+ };
1357
1688
  }
1358
1689
 
1359
- /**
1360
- * 在嵌套树中按 `id` 递归查找节点,并返回其指定属性值。
1361
- *
1362
- * @template T extends Record<PropertyKey, any>
1363
- * @param {string | number} id - 要查找的 id
1364
- * @param {T[]} arr - 嵌套树森林
1365
- * @param {string} [resultKey='name'] - 需要返回的字段
1366
- * @param {string} [idKey='id'] - 主键字段
1367
- * @param {string} [childrenKey='children'] - 子节点字段
1368
- * @returns {any} 找到的值;未找到返回 `undefined`
1369
- */
1370
- const findObjAttrValueById = function findObjAttrValueByIdFn(id, arr, resultKey = "name", idKey = "id", childrenKey = "children") {
1371
- if (Array.isArray(arr) && arr.length > 0) {
1372
- for (let i = 0; i < arr.length; i++) {
1373
- const item = arr[i];
1374
- if (item[idKey]?.toString() === id?.toString()) {
1375
- return item[resultKey];
1376
- } else if (Array.isArray(item[childrenKey]) && item[childrenKey].length > 0) {
1377
- const result = findObjAttrValueByIdFn(id, item[childrenKey], resultKey, idKey, childrenKey);
1378
- if (result) {
1379
- return result;
1380
- }
1381
- }
1382
- }
1383
- }
1384
- };
1385
-
1386
- /**
1387
- * 从服务端返回的已选 id 数组里,提取出
1388
- * 1. 叶子节点
1389
- * 2. 所有子节点都被选中的父节点
1390
- * 其余父节点一律丢弃(由前端 Tree 自动算半选)
1391
- *
1392
- * @param {Array} treeData 完整树
1393
- * @param {Array} selectedKeys 后端给的选中 id 数组
1394
- * @param {String} idKey 节点唯一字段
1395
- * @param {String} childrenKey 子节点字段
1396
- * @returns {{checked: string[], halfChecked: string[]}}
1397
- */
1398
- function extractFullyCheckedKeys(treeData, selectedKeys, idKey = "id", childrenKey = "children") {
1399
- const selectedSet = new Set(selectedKeys);
1400
- const checked = new Set();
1401
- const halfChecked = new Set();
1402
-
1403
- /* 返回值含义
1404
- 0 - 未选中
1405
- 1 - 半选
1406
- 2 - 全选
1407
- */
1408
- function dfs(node) {
1409
- const nodeId = node[idKey];
1410
- const children = node[childrenKey] || [];
1411
-
1412
- // 叶子
1413
- if (!children.length) {
1414
- if (selectedSet.has(nodeId)) {
1415
- checked.add(nodeId);
1416
- return 2;
1417
- }
1418
- return 0;
1419
- }
1420
-
1421
- // 非叶子
1422
- let allChecked = true;
1423
- let someChecked = false;
1424
-
1425
- children.forEach((child) => {
1426
- const childState = dfs(child);
1427
- if (childState !== 2) allChecked = false;
1428
- if (childState >= 1) someChecked = true;
1429
- });
1430
-
1431
- // 当前节点本身在 selectedKeys 里,但子节点未全选 → 只能算半选
1432
- if (selectedSet.has(nodeId)) {
1433
- if (allChecked) {
1434
- checked.add(nodeId);
1435
- return 2;
1436
- }
1437
- halfChecked.add(nodeId);
1438
- return 1;
1439
- }
1440
-
1441
- // 当前节点不在 selectedKeys 里,看子节点
1442
- if (allChecked) {
1443
- checked.add(nodeId);
1444
- return 2;
1445
- }
1446
- if (someChecked) {
1447
- halfChecked.add(nodeId);
1448
- return 1;
1449
- }
1450
- return 0;
1451
- }
1452
-
1453
- treeData.forEach(dfs);
1454
- return {
1455
- checked: [...checked],
1456
- halfChecked: [...halfChecked]
1457
- };
1458
- }
1459
-
1460
- /**
1461
- * @class WebSocketManager - 一个纯粹、强大的 WebSocket 连接管理引擎
1462
- *
1463
- * @features
1464
- * - 智能断线重连 (指数退避算法)
1465
- * - 网络状态监听
1466
- * - 高度可定制的心跳保活机制 (通过注入函数实现)
1467
- * - 页面可见性 API 集成
1468
- * - 消息发送队列
1469
- * - 清晰的生命周期管理
1470
- * - 优雅的资源销毁
1471
- * - 可配置的数据序列化/反序列化
1472
- * - 纯粹的消息传递,不关心消息内容
1473
- */
1474
- class WebSocketManager {
1475
- /**
1476
- * @param {string} url - WebSocket 服务器的地址
1477
- * @param {object} [options={}] - 配置选项
1478
- * @param {number} [options.heartbeatInterval=30000] - 心跳间隔 (毫秒)
1479
- * @param {number} [options.heartbeatTimeout=10000] - 心跳超时时间 (毫秒)
1480
- * @param {number} [options.reconnectBaseInterval=1000] - 重连基础间隔 (毫秒)
1481
- * @param {number} [options.maxReconnectInterval=30000] - 最大重连间隔 (毫秒)
1482
- * @param {number} [options.maxReconnectAttempts=Infinity] - 最大重连次数
1483
- * @param {boolean} [options.autoConnect=true] - 是否在实例化后自动连接
1484
- * @param {boolean} [options.serializeData=false] - 发送数据时是否自动序列化为JSON字符串
1485
- * @param {boolean} [options.deserializeData=false] - 接收数据时是否自动反序列化为JSON对象
1486
- * @param {function|null} [options.getPingMessage=null] - 返回要发送的 ping 消息内容的函数。如果为 null,则不发送心跳。
1487
- * @param {function|null} [options.isPongMessage=null] - 判断接收到的消息是否为 pong 的函数。接收 MessageEvent 对象作为参数,返回布尔值。
1488
- * @param {object} [options.protocols] - WebSocket 协议
1489
- */
1490
- constructor(url, options = {}) {
1491
- this.url = url;
1492
-
1493
- // 默认的心跳实现,用于向后兼容
1494
- const defaultGetPingMessage = () => JSON.stringify({ type: "ping" });
1495
- const defaultIsPongMessage = (event) => {
1496
- try {
1497
- const message = JSON.parse(event.data);
1498
- return message.type === "pong";
1499
- } catch (e) {
1500
- return false;
1501
- }
1502
- };
1503
-
1504
- this.options = {
1505
- heartbeatInterval: 30000,
1506
- heartbeatTimeout: 10000,
1507
- reconnectBaseInterval: 1000,
1508
- maxReconnectInterval: 30000,
1509
- maxReconnectAttempts: Infinity,
1510
- autoConnect: true,
1511
- serializeData: false,
1512
- deserializeData: false,
1513
- getPingMessage: defaultGetPingMessage, // 默认提供 ping 消息生成器
1514
- isPongMessage: defaultIsPongMessage, // 默认提供 pong 消息判断器
1515
- ...options
1516
- };
1517
-
1518
- // WebSocket 实例
1519
- this.ws = null;
1520
-
1521
- // 状态管理
1522
- this.readyState = WebSocket.CLOSED;
1523
- this.reconnectAttempts = 0;
1524
- this.forcedClose = false;
1525
- this.isReconnecting = false;
1526
-
1527
- // 定时器
1528
- this.heartbeatTimer = null;
1529
- this.heartbeatTimeoutTimer = null;
1530
- this.reconnectTimer = null;
1531
-
1532
- // 消息队列
1533
- this.messageQueue = [];
1534
-
1535
- // 事件监听器
1536
- this.listeners = new Map();
1537
-
1538
- // 绑定方法上下文
1539
- this._onOpen = this._onOpen.bind(this);
1540
- this._onMessage = this._onMessage.bind(this);
1541
- this._onClose = this._onClose.bind(this);
1542
- this._onError = this._onError.bind(this);
1543
- this._handleVisibilityChange = this._handleVisibilityChange.bind(this);
1544
- this._handleOnline = this._handleOnline.bind(this);
1545
- this._handleOffline = this._handleOffline.bind(this);
1546
-
1547
- this._setupEventListeners();
1548
-
1549
- if (this.options.autoConnect) {
1550
- this.connect();
1551
- }
1552
- }
1553
-
1554
- // --- 公共 API ---
1555
-
1556
- /**
1557
- * 连接到 WebSocket 服务器
1558
- */
1559
- connect() {
1560
- if (this.ws && (this.ws.readyState === WebSocket.CONNECTING || this.ws.readyState === WebSocket.OPEN)) {
1561
- return;
1562
- }
1563
-
1564
- this.forcedClose = false;
1565
- this._updateReadyState(WebSocket.CONNECTING);
1566
- console.log(`[WS] 正在连接到 ${this.url}...`);
1567
- this._emit("connecting");
1568
-
1569
- try {
1570
- this.ws = new WebSocket(this.url, this.options.protocols);
1571
- this.ws.onopen = this._onOpen;
1572
- this.ws.onmessage = this._onMessage;
1573
- this.ws.onclose = this._onClose;
1574
- this.ws.onerror = this._onError;
1575
- } catch (error) {
1576
- console.error("[WS] 连接失败:", error);
1577
- this._onError(error);
1578
- }
1579
- }
1580
-
1581
- /**
1582
- * 发送数据
1583
- * @param {string|object|ArrayBuffer|Blob} data - 要发送的数据
1584
- */
1585
- send(data) {
1586
- if (this.readyState === WebSocket.OPEN) {
1587
- let message;
1588
- // 根据配置决定是否序列化数据
1589
- if (this.options.serializeData) {
1590
- message = JSON.stringify(data);
1591
- } else {
1592
- message = data;
1593
- }
1594
- this.ws.send(message);
1595
- console.log("[WS] 消息已发送:", message);
1596
- } else {
1597
- console.warn("[WS] 连接未打开,消息已加入队列:", data);
1598
- this.messageQueue.push(data);
1599
- }
1600
- }
1601
-
1602
- /**
1603
- * 主动关闭连接
1604
- * @param {number} [code=1000] - 关闭代码
1605
- * @param {string} [reason=''] - 关闭原因
1606
- */
1607
- close(code = 1000, reason = "Normal closure") {
1608
- this.forcedClose = true;
1609
- this._stopHeartbeat();
1610
- this._clearReconnectTimer();
1611
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1612
- this.ws.close(code, reason);
1613
- } else {
1614
- this._updateReadyState(WebSocket.CLOSED);
1615
- this._emit("close", { code, reason, wasClean: true });
1616
- }
1617
- }
1618
-
1619
- /**
1620
- * 彻底销毁实例,清理所有资源
1621
- */
1622
- destroy() {
1623
- console.log("[WS] 正在销毁实例...");
1624
- this.close(1000, "Instance destroyed");
1625
- this._removeEventListeners();
1626
- this.messageQueue = [];
1627
- this.listeners.clear();
1628
- this.ws = null;
1629
- }
1630
-
1631
- /**
1632
- * 添加事件监听器
1633
- * @param {string} eventName - 事件名 (e.g., 'open', 'message', 'close', 'error', 'reconnect')
1634
- * @param {function} callback - 回调函数
1635
- */
1636
- on(eventName, callback) {
1637
- if (!this.listeners.has(eventName)) {
1638
- this.listeners.set(eventName, []);
1639
- }
1640
- this.listeners.get(eventName).push(callback);
1641
- }
1642
-
1643
- /**
1644
- * 移除事件监听器
1645
- * @param {string} eventName - 事件名
1646
- * @param {function} callback - 回调函数
1647
- */
1648
- off(eventName, callback) {
1649
- if (this.listeners.has(eventName)) {
1650
- const callbacks = this.listeners.get(eventName);
1651
- const index = callbacks.indexOf(callback);
1652
- if (index > -1) {
1653
- callbacks.splice(index, 1);
1654
- }
1655
- }
1656
- }
1657
-
1658
- // --- 内部方法 ---
1659
-
1660
- _onOpen(event) {
1661
- console.log("[WS] 连接已建立");
1662
- this._updateReadyState(WebSocket.OPEN);
1663
- this.reconnectAttempts = 0;
1664
- this.isReconnecting = false;
1665
-
1666
- // 如果配置了 getPingMessage,则启动心跳
1667
- if (this.options.getPingMessage) {
1668
- this._startHeartbeat();
1669
- }
1670
-
1671
- this._flushMessageQueue();
1672
- this._emit("open", event);
1673
- }
1674
-
1675
- /**
1676
- * 纯粹的消息处理方法:处理心跳,然后将数据交给使用者
1677
- * @param {MessageEvent} event
1678
- */
1679
- _onMessage(event) {
1680
- // --- 步骤 1: 使用注入的函数优先处理内部心跳机制 ---
1681
- if (this.options.isPongMessage && this.options.isPongMessage(event)) {
1682
- this._handlePong();
1683
- return; // 是心跳消息,处理完毕,直接返回
1684
- }
1685
-
1686
- // --- 步骤 2: 根据用户配置处理业务消息 ---
1687
- if (this.options.deserializeData) {
1688
- try {
1689
- const parsedMessage = JSON.parse(event.data);
1690
- this._emit("message", parsedMessage, event);
1691
- } catch (e) {
1692
- this._emit("message", event.data, event);
1693
- }
1694
- } else {
1695
- this._emit("message", event.data, event);
1696
- }
1697
- }
1698
-
1699
- _onClose(event) {
1700
- console.log("[WS] 连接已关闭", event);
1701
- this._updateReadyState(WebSocket.CLOSED);
1702
- this._stopHeartbeat();
1703
- this._emit("close", event);
1704
-
1705
- if (!this.forcedClose) {
1706
- this._scheduleReconnect();
1707
- }
1708
- }
1709
-
1710
- _onError(event) {
1711
- console.error("[WS] 连接发生错误:", event);
1712
- this._emit("error", event);
1713
- }
1714
-
1715
- // --- 心跳机制 ---
1716
- _startHeartbeat() {
1717
- // 如果没有配置 getPingMessage,则无法启动心跳
1718
- if (!this.options.getPingMessage) {
1719
- return;
1720
- }
1721
-
1722
- this._stopHeartbeat();
1723
- this.heartbeatTimer = setInterval(() => {
1724
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1725
- try {
1726
- // 调用注入的函数获取消息内容并发送
1727
- const pingMessage = this.options.getPingMessage();
1728
- this.ws.send(pingMessage);
1729
- console.log("[WS] 发送 Ping:", pingMessage);
1730
- this._setHeartbeatTimeout();
1731
- } catch (error) {
1732
- console.error("[WS] 发送 Ping 消息失败:", error);
1733
- }
1734
- }
1735
- }, this.options.heartbeatInterval);
1736
- }
1737
-
1738
- _stopHeartbeat() {
1739
- if (this.heartbeatTimer) {
1740
- clearInterval(this.heartbeatTimer);
1741
- this.heartbeatTimer = null;
1742
- }
1743
- this._clearHeartbeatTimeout();
1744
- }
1745
-
1746
- _setHeartbeatTimeout() {
1747
- this._clearHeartbeatTimeout();
1748
- this.heartbeatTimeoutTimer = setTimeout(() => {
1749
- console.error("[WS] 心跳超时,主动断开连接");
1750
- this.ws.close(1006, "Heartbeat timeout");
1751
- }, this.options.heartbeatTimeout);
1752
- }
1753
-
1754
- _clearHeartbeatTimeout() {
1755
- if (this.heartbeatTimeoutTimer) {
1756
- clearTimeout(this.heartbeatTimeoutTimer);
1757
- this.heartbeatTimeoutTimer = null;
1758
- }
1759
- }
1760
-
1761
- _handlePong() {
1762
- console.log("[WS] 收到 Pong");
1763
- this._clearHeartbeatTimeout();
1764
- }
1765
-
1766
- // --- 重连机制 ---
1767
- _scheduleReconnect() {
1768
- if (this.forcedClose || this.isReconnecting || this.reconnectAttempts >= this.options.maxReconnectAttempts) {
1769
- if (this.reconnectAttempts >= this.options.maxReconnectAttempts) {
1770
- console.error("[WS] 已达到最大重连次数,停止重连");
1771
- this._emit("reconnect-failed");
1772
- }
1773
- return;
1774
- }
1775
-
1776
- this.isReconnecting = true;
1777
- const interval = Math.min(this.options.reconnectBaseInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
1778
-
1779
- console.log(`[WS] ${interval / 1000}秒后将尝试第 ${this.reconnectAttempts + 1} 次重连...`);
1780
- this._emit("reconnect-attempt", { attempt: this.reconnectAttempts + 1, interval });
1781
-
1782
- this.reconnectTimer = setTimeout(() => {
1783
- this.reconnectAttempts++;
1784
- this.connect();
1785
- }, interval);
1786
- }
1787
-
1788
- _clearReconnectTimer() {
1789
- if (this.reconnectTimer) {
1790
- clearTimeout(this.reconnectTimer);
1791
- this.reconnectTimer = null;
1792
- }
1793
- }
1794
-
1795
- // --- 消息队列 ---
1796
- _flushMessageQueue() {
1797
- if (this.messageQueue.length === 0) return;
1798
- console.log(`[WS] 发送队列中的 ${this.messageQueue.length} 条消息`);
1799
- const queue = [...this.messageQueue];
1800
- this.messageQueue = [];
1801
- queue.forEach((data) => this.send(data));
1802
- }
1803
-
1804
- // --- 事件系统 ---
1805
- _emit(eventName, ...args) {
1806
- if (this.listeners.has(eventName)) {
1807
- this.listeners.get(eventName).forEach((callback) => callback(...args));
1808
- }
1809
- }
1810
-
1811
- // --- 状态与监听器管理 ---
1812
- _updateReadyState(newState) {
1813
- this.readyState = newState;
1814
- this._emit("ready-state-change", newState);
1815
- }
1816
-
1817
- _setupEventListeners() {
1818
- document.addEventListener("visibilitychange", this._handleVisibilityChange);
1819
- window.addEventListener("online", this._handleOnline);
1820
- window.addEventListener("offline", this._handleOffline);
1821
- }
1822
-
1823
- _removeEventListeners() {
1824
- document.removeEventListener("visibilitychange", this._handleVisibilityChange);
1825
- window.removeEventListener("online", this._handleOnline);
1826
- window.removeEventListener("offline", this._handleOffline);
1827
- }
1828
-
1829
- _handleVisibilityChange() {
1830
- // 如果未启用心跳,不需要处理页面可见性变化
1831
- if (!this.options.getPingMessage) {
1832
- return;
1833
- }
1834
-
1835
- if (document.hidden) {
1836
- console.log("[WS] 页面隐藏,停止心跳");
1837
- this._stopHeartbeat();
1838
- } else {
1839
- console.log("[WS] 页面可见,检查连接状态");
1840
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1841
- this._startHeartbeat();
1842
- } else if (!this.forcedClose && !this.isReconnecting) {
1843
- this.connect();
1844
- }
1845
- }
1846
- }
1847
-
1848
- _handleOnline() {
1849
- console.log("[WS] 网络已恢复,尝试重连");
1850
- if (!this.forcedClose && this.readyState !== WebSocket.OPEN) {
1851
- this._clearReconnectTimer(); // 清除当前的重连计划
1852
- this.connect(); // 立即尝试连接
1853
- }
1854
- }
1855
-
1856
- _handleOffline() {
1857
- console.log("[WS] 网络已断开");
1858
- this._clearReconnectTimer(); // 停止重连尝试
1859
- // ws.onclose 会被触发,从而启动重连逻辑,但我们已经停止了
1860
- // 所以这里可以手动触发一次 close 事件来通知应用层
1861
- if (this.ws) this.ws.onclose({ code: 1006, reason: "Network offline" });
1862
- }
1690
+ /**
1691
+ * @class WebSocketManager - 一个纯粹、强大的 WebSocket 连接管理引擎
1692
+ *
1693
+ * @features
1694
+ * - 智能断线重连 (指数退避算法)
1695
+ * - 网络状态监听
1696
+ * - 高度可定制的心跳保活机制 (通过注入函数实现)
1697
+ * - 页面可见性 API 集成
1698
+ * - 消息发送队列
1699
+ * - 清晰的生命周期管理
1700
+ * - 优雅的资源销毁
1701
+ * - 可配置的数据序列化/反序列化
1702
+ * - 纯粹的消息传递,不关心消息内容
1703
+ */
1704
+ class WebSocketManager {
1705
+ /**
1706
+ * @param {string} url - WebSocket 服务器的地址
1707
+ * @param {object} [options={}] - 配置选项
1708
+ * @param {number} [options.heartbeatInterval=30000] - 心跳间隔 (毫秒)
1709
+ * @param {number} [options.heartbeatTimeout=10000] - 心跳超时时间 (毫秒)
1710
+ * @param {number} [options.reconnectBaseInterval=1000] - 重连基础间隔 (毫秒)
1711
+ * @param {number} [options.maxReconnectInterval=30000] - 最大重连间隔 (毫秒)
1712
+ * @param {number} [options.maxReconnectAttempts=Infinity] - 最大重连次数
1713
+ * @param {boolean} [options.autoConnect=true] - 是否在实例化后自动连接
1714
+ * @param {boolean} [options.serializeData=false] - 发送数据时是否自动序列化为JSON字符串
1715
+ * @param {boolean} [options.deserializeData=false] - 接收数据时是否自动反序列化为JSON对象
1716
+ * @param {function|null} [options.getPingMessage=null] - 返回要发送的 ping 消息内容的函数。如果为 null,则不发送心跳。
1717
+ * @param {function|null} [options.isPongMessage=null] - 判断接收到的消息是否为 pong 的函数。接收 MessageEvent 对象作为参数,返回布尔值。
1718
+ * @param {object} [options.protocols] - WebSocket 协议
1719
+ */
1720
+ constructor(url, options = {}) {
1721
+ this.url = url;
1722
+
1723
+ // 默认的心跳实现,用于向后兼容
1724
+ const defaultGetPingMessage = () => JSON.stringify({ type: "ping" });
1725
+ const defaultIsPongMessage = (event) => {
1726
+ try {
1727
+ const message = JSON.parse(event.data);
1728
+ return message.type === "pong";
1729
+ } catch (e) {
1730
+ return false;
1731
+ }
1732
+ };
1733
+
1734
+ this.options = {
1735
+ heartbeatInterval: 30000,
1736
+ heartbeatTimeout: 10000,
1737
+ reconnectBaseInterval: 1000,
1738
+ maxReconnectInterval: 30000,
1739
+ maxReconnectAttempts: Infinity,
1740
+ autoConnect: true,
1741
+ serializeData: false,
1742
+ deserializeData: false,
1743
+ getPingMessage: defaultGetPingMessage, // 默认提供 ping 消息生成器
1744
+ isPongMessage: defaultIsPongMessage, // 默认提供 pong 消息判断器
1745
+ ...options
1746
+ };
1747
+
1748
+ // WebSocket 实例
1749
+ this.ws = null;
1750
+
1751
+ // 状态管理
1752
+ this.readyState = WebSocket.CLOSED;
1753
+ this.reconnectAttempts = 0;
1754
+ this.forcedClose = false;
1755
+ this.isReconnecting = false;
1756
+
1757
+ // 定时器
1758
+ this.heartbeatTimer = null;
1759
+ this.heartbeatTimeoutTimer = null;
1760
+ this.reconnectTimer = null;
1761
+
1762
+ // 消息队列
1763
+ this.messageQueue = [];
1764
+
1765
+ // 事件监听器
1766
+ this.listeners = new Map();
1767
+
1768
+ // 绑定方法上下文
1769
+ this._onOpen = this._onOpen.bind(this);
1770
+ this._onMessage = this._onMessage.bind(this);
1771
+ this._onClose = this._onClose.bind(this);
1772
+ this._onError = this._onError.bind(this);
1773
+ this._handleVisibilityChange = this._handleVisibilityChange.bind(this);
1774
+ this._handleOnline = this._handleOnline.bind(this);
1775
+ this._handleOffline = this._handleOffline.bind(this);
1776
+
1777
+ this._setupEventListeners();
1778
+
1779
+ if (this.options.autoConnect) {
1780
+ this.connect();
1781
+ }
1782
+ }
1783
+
1784
+ // --- 公共 API ---
1785
+
1786
+ /**
1787
+ * 连接到 WebSocket 服务器
1788
+ */
1789
+ connect() {
1790
+ if (this.ws && (this.ws.readyState === WebSocket.CONNECTING || this.ws.readyState === WebSocket.OPEN)) {
1791
+ return;
1792
+ }
1793
+
1794
+ this.forcedClose = false;
1795
+ this._updateReadyState(WebSocket.CONNECTING);
1796
+ console.log(`[WS] 正在连接到 ${this.url}...`);
1797
+ this._emit("connecting");
1798
+
1799
+ try {
1800
+ this.ws = new WebSocket(this.url, this.options.protocols);
1801
+ this.ws.onopen = this._onOpen;
1802
+ this.ws.onmessage = this._onMessage;
1803
+ this.ws.onclose = this._onClose;
1804
+ this.ws.onerror = this._onError;
1805
+ } catch (error) {
1806
+ console.error("[WS] 连接失败:", error);
1807
+ this._onError(error);
1808
+ }
1809
+ }
1810
+
1811
+ /**
1812
+ * 发送数据
1813
+ * @param {string|object|ArrayBuffer|Blob} data - 要发送的数据
1814
+ */
1815
+ send(data) {
1816
+ if (this.readyState === WebSocket.OPEN) {
1817
+ let message;
1818
+ // 根据配置决定是否序列化数据
1819
+ if (this.options.serializeData) {
1820
+ message = JSON.stringify(data);
1821
+ } else {
1822
+ message = data;
1823
+ }
1824
+ this.ws.send(message);
1825
+ console.log("[WS] 消息已发送:", message);
1826
+ } else {
1827
+ console.warn("[WS] 连接未打开,消息已加入队列:", data);
1828
+ this.messageQueue.push(data);
1829
+ }
1830
+ }
1831
+
1832
+ /**
1833
+ * 主动关闭连接
1834
+ * @param {number} [code=1000] - 关闭代码
1835
+ * @param {string} [reason=''] - 关闭原因
1836
+ */
1837
+ close(code = 1000, reason = "Normal closure") {
1838
+ this.forcedClose = true;
1839
+ this._stopHeartbeat();
1840
+ this._clearReconnectTimer();
1841
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1842
+ this.ws.close(code, reason);
1843
+ } else {
1844
+ this._updateReadyState(WebSocket.CLOSED);
1845
+ this._emit("close", { code, reason, wasClean: true });
1846
+ }
1847
+ }
1848
+
1849
+ /**
1850
+ * 彻底销毁实例,清理所有资源
1851
+ */
1852
+ destroy() {
1853
+ console.log("[WS] 正在销毁实例...");
1854
+ this.close(1000, "Instance destroyed");
1855
+ this._removeEventListeners();
1856
+ this.messageQueue = [];
1857
+ this.listeners.clear();
1858
+ this.ws = null;
1859
+ }
1860
+
1861
+ /**
1862
+ * 添加事件监听器
1863
+ * @param {string} eventName - 事件名 (e.g., 'open', 'message', 'close', 'error', 'reconnect')
1864
+ * @param {function} callback - 回调函数
1865
+ */
1866
+ on(eventName, callback) {
1867
+ if (!this.listeners.has(eventName)) {
1868
+ this.listeners.set(eventName, []);
1869
+ }
1870
+ this.listeners.get(eventName).push(callback);
1871
+ }
1872
+
1873
+ /**
1874
+ * 移除事件监听器
1875
+ * @param {string} eventName - 事件名
1876
+ * @param {function} callback - 回调函数
1877
+ */
1878
+ off(eventName, callback) {
1879
+ if (this.listeners.has(eventName)) {
1880
+ const callbacks = this.listeners.get(eventName);
1881
+ const index = callbacks.indexOf(callback);
1882
+ if (index > -1) {
1883
+ callbacks.splice(index, 1);
1884
+ }
1885
+ }
1886
+ }
1887
+
1888
+ // --- 内部方法 ---
1889
+
1890
+ _onOpen(event) {
1891
+ console.log("[WS] 连接已建立");
1892
+ this._updateReadyState(WebSocket.OPEN);
1893
+ this.reconnectAttempts = 0;
1894
+ this.isReconnecting = false;
1895
+
1896
+ // 如果配置了 getPingMessage,则启动心跳
1897
+ if (this.options.getPingMessage) {
1898
+ this._startHeartbeat();
1899
+ }
1900
+
1901
+ this._flushMessageQueue();
1902
+ this._emit("open", event);
1903
+ }
1904
+
1905
+ /**
1906
+ * 纯粹的消息处理方法:处理心跳,然后将数据交给使用者
1907
+ * @param {MessageEvent} event
1908
+ */
1909
+ _onMessage(event) {
1910
+ // --- 步骤 1: 使用注入的函数优先处理内部心跳机制 ---
1911
+ if (this.options.isPongMessage && this.options.isPongMessage(event)) {
1912
+ this._handlePong();
1913
+ return; // 是心跳消息,处理完毕,直接返回
1914
+ }
1915
+
1916
+ // --- 步骤 2: 根据用户配置处理业务消息 ---
1917
+ if (this.options.deserializeData) {
1918
+ try {
1919
+ const parsedMessage = JSON.parse(event.data);
1920
+ this._emit("message", parsedMessage, event);
1921
+ } catch (e) {
1922
+ this._emit("message", event.data, event);
1923
+ }
1924
+ } else {
1925
+ this._emit("message", event.data, event);
1926
+ }
1927
+ }
1928
+
1929
+ _onClose(event) {
1930
+ console.log("[WS] 连接已关闭", event);
1931
+ this._updateReadyState(WebSocket.CLOSED);
1932
+ this._stopHeartbeat();
1933
+ this._emit("close", event);
1934
+
1935
+ if (!this.forcedClose) {
1936
+ this._scheduleReconnect();
1937
+ }
1938
+ }
1939
+
1940
+ _onError(event) {
1941
+ console.error("[WS] 连接发生错误:", event);
1942
+ this._emit("error", event);
1943
+ }
1944
+
1945
+ // --- 心跳机制 ---
1946
+ _startHeartbeat() {
1947
+ // 如果没有配置 getPingMessage,则无法启动心跳
1948
+ if (!this.options.getPingMessage) {
1949
+ return;
1950
+ }
1951
+
1952
+ this._stopHeartbeat();
1953
+ this.heartbeatTimer = setInterval(() => {
1954
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1955
+ try {
1956
+ // 调用注入的函数获取消息内容并发送
1957
+ const pingMessage = this.options.getPingMessage();
1958
+ this.ws.send(pingMessage);
1959
+ console.log("[WS] 发送 Ping:", pingMessage);
1960
+ this._setHeartbeatTimeout();
1961
+ } catch (error) {
1962
+ console.error("[WS] 发送 Ping 消息失败:", error);
1963
+ }
1964
+ }
1965
+ }, this.options.heartbeatInterval);
1966
+ }
1967
+
1968
+ _stopHeartbeat() {
1969
+ if (this.heartbeatTimer) {
1970
+ clearInterval(this.heartbeatTimer);
1971
+ this.heartbeatTimer = null;
1972
+ }
1973
+ this._clearHeartbeatTimeout();
1974
+ }
1975
+
1976
+ _setHeartbeatTimeout() {
1977
+ this._clearHeartbeatTimeout();
1978
+ this.heartbeatTimeoutTimer = setTimeout(() => {
1979
+ console.error("[WS] 心跳超时,主动断开连接");
1980
+ this.ws.close(1006, "Heartbeat timeout");
1981
+ }, this.options.heartbeatTimeout);
1982
+ }
1983
+
1984
+ _clearHeartbeatTimeout() {
1985
+ if (this.heartbeatTimeoutTimer) {
1986
+ clearTimeout(this.heartbeatTimeoutTimer);
1987
+ this.heartbeatTimeoutTimer = null;
1988
+ }
1989
+ }
1990
+
1991
+ _handlePong() {
1992
+ console.log("[WS] 收到 Pong");
1993
+ this._clearHeartbeatTimeout();
1994
+ }
1995
+
1996
+ // --- 重连机制 ---
1997
+ _scheduleReconnect() {
1998
+ if (this.forcedClose || this.isReconnecting || this.reconnectAttempts >= this.options.maxReconnectAttempts) {
1999
+ if (this.reconnectAttempts >= this.options.maxReconnectAttempts) {
2000
+ console.error("[WS] 已达到最大重连次数,停止重连");
2001
+ this._emit("reconnect-failed");
2002
+ }
2003
+ return;
2004
+ }
2005
+
2006
+ this.isReconnecting = true;
2007
+ const interval = Math.min(this.options.reconnectBaseInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
2008
+
2009
+ console.log(`[WS] ${interval / 1000}秒后将尝试第 ${this.reconnectAttempts + 1} 次重连...`);
2010
+ this._emit("reconnect-attempt", { attempt: this.reconnectAttempts + 1, interval });
2011
+
2012
+ this.reconnectTimer = setTimeout(() => {
2013
+ this.reconnectAttempts++;
2014
+ this.connect();
2015
+ }, interval);
2016
+ }
2017
+
2018
+ _clearReconnectTimer() {
2019
+ if (this.reconnectTimer) {
2020
+ clearTimeout(this.reconnectTimer);
2021
+ this.reconnectTimer = null;
2022
+ }
2023
+ }
2024
+
2025
+ // --- 消息队列 ---
2026
+ _flushMessageQueue() {
2027
+ if (this.messageQueue.length === 0) return;
2028
+ console.log(`[WS] 发送队列中的 ${this.messageQueue.length} 条消息`);
2029
+ const queue = [...this.messageQueue];
2030
+ this.messageQueue = [];
2031
+ queue.forEach((data) => this.send(data));
2032
+ }
2033
+
2034
+ // --- 事件系统 ---
2035
+ _emit(eventName, ...args) {
2036
+ if (this.listeners.has(eventName)) {
2037
+ this.listeners.get(eventName).forEach((callback) => callback(...args));
2038
+ }
2039
+ }
2040
+
2041
+ // --- 状态与监听器管理 ---
2042
+ _updateReadyState(newState) {
2043
+ this.readyState = newState;
2044
+ this._emit("ready-state-change", newState);
2045
+ }
2046
+
2047
+ _setupEventListeners() {
2048
+ document.addEventListener("visibilitychange", this._handleVisibilityChange);
2049
+ window.addEventListener("online", this._handleOnline);
2050
+ window.addEventListener("offline", this._handleOffline);
2051
+ }
2052
+
2053
+ _removeEventListeners() {
2054
+ document.removeEventListener("visibilitychange", this._handleVisibilityChange);
2055
+ window.removeEventListener("online", this._handleOnline);
2056
+ window.removeEventListener("offline", this._handleOffline);
2057
+ }
2058
+
2059
+ _handleVisibilityChange() {
2060
+ // 如果未启用心跳,不需要处理页面可见性变化
2061
+ if (!this.options.getPingMessage) {
2062
+ return;
2063
+ }
2064
+
2065
+ if (document.hidden) {
2066
+ console.log("[WS] 页面隐藏,停止心跳");
2067
+ this._stopHeartbeat();
2068
+ } else {
2069
+ console.log("[WS] 页面可见,检查连接状态");
2070
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
2071
+ this._startHeartbeat();
2072
+ } else if (!this.forcedClose && !this.isReconnecting) {
2073
+ this.connect();
2074
+ }
2075
+ }
2076
+ }
2077
+
2078
+ _handleOnline() {
2079
+ console.log("[WS] 网络已恢复,尝试重连");
2080
+ if (!this.forcedClose && this.readyState !== WebSocket.OPEN) {
2081
+ this._clearReconnectTimer(); // 清除当前的重连计划
2082
+ this.connect(); // 立即尝试连接
2083
+ }
2084
+ }
2085
+
2086
+ _handleOffline() {
2087
+ console.log("[WS] 网络已断开");
2088
+ this._clearReconnectTimer(); // 停止重连尝试
2089
+ // ws.onclose 会被触发,从而启动重连逻辑,但我们已经停止了
2090
+ // 所以这里可以手动触发一次 close 事件来通知应用层
2091
+ if (this.ws) this.ws.onclose({ code: 1006, reason: "Network offline" });
2092
+ }
1863
2093
  }
1864
2094
 
1865
- export { AudioStreamResampler, IntervalTimer, MyEvent, MyEvent_CrossPagePlugin, MyId, WebSocketManager, assignExisting, calcTimeDifference, debounce, deepCloneByJSON, downloadByBlob, downloadByData, downloadByUrl, downloadExcel, downloadJSON, extractFullyCheckedKeys, fetchOrDownloadByUrl, findObjAttrValueById, flatCompleteTree2NestedTree, formatDuration, formatDurationMaxDay, formatDurationMaxHour, getAllSearchParams, getDataType, getFunctionArgNames, getGUID, getSearchParam, getViewportSize, isBlob, isDate, isFunction, isNonEmptyString, isPlainObject, isPromise, moveItem, nestedTree2IdMap, pcmToWavBlob, randomDateInRange, randomEnLetter, randomHan, randomHanOrEn, randomIntInRange, readBlobAsText, shuffle, throttle, toDate };
2095
+ export { AudioStreamResampler, IntervalTimer, MyEvent, MyEvent_CrossPagePlugin, MyId, WebSocketManager, assignExisting, debounce, deepCloneByJSON, downloadByBlob, downloadByData, downloadByUrl, downloadExcel, downloadJSON, extractFullyCheckedKeys, fetchOrDownloadByUrl, findObjAttrValueById, flatCompleteTree2NestedTree, formatTimeForLocale, getAllSearchParams, getDataType, getFunctionArgNames, getGUID, getSearchParam, getTimePeriodName, getViewportSize, isBlob, isDate, isFunction, isNonEmptyString, isPlainObject, isPromise, millisecond2Duration, millisecond2DurationMaxDay, millisecond2DurationMaxHour, moveItem, nestedTree2IdMap, pcmToWavBlob, randomDateInRange, randomEnLetter, randomHan, randomHanOrEn, randomIntInRange, readBlobAsText, second2Duration, second2DurationMaxDay, second2DurationMaxHour, shuffle, throttle, toDate };
1866
2096
  //# sourceMappingURL=a2bei4.utils.esm.js.map