@gateweb/react-utils 1.15.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,879 @@
1
+ 'use client';
2
+ /* eslint-disable no-bitwise */ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3
+ /**
4
+ * 將位元組陣列編碼為 base64 字串
5
+ *
6
+ * @param bytes 要編碼的位元組陣列
7
+ * @returns base64 編碼的字串
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const bytes = new TextEncoder().encode('Hello World');
12
+ * const encoded = encodeBase64(bytes);
13
+ * console.log(encoded); // 'SGVsbG8gV29ybGQ='
14
+ * ```
15
+ */ const encodeBase64 = (bytes)=>{
16
+ let out = '';
17
+ for(let i = 0; i < bytes.length; i += 3){
18
+ const n = bytes[i] << 16 | (bytes[i + 1] || 0) << 8 | (bytes[i + 2] || 0);
19
+ out += chars[n >> 18 & 63] + chars[n >> 12 & 63] + (i + 1 < bytes.length ? chars[n >> 6 & 63] : '=') + (i + 2 < bytes.length ? chars[n & 63] : '=');
20
+ }
21
+ return out;
22
+ };
23
+ /**
24
+ * 將 base64 字串解碼為位元組陣列
25
+ *
26
+ * @param base64 要解碼的 base64 字串(支援 base64url 格式)
27
+ * @returns 解碼後的位元組陣列
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const decoded = decodeBase64('SGVsbG8gV29ybGQ=');
32
+ * const text = new TextDecoder().decode(decoded);
33
+ * console.log(text); // 'Hello World'
34
+ * ```
35
+ */ const decodeBase64 = (base64)=>{
36
+ let out = base64.replace(/-/g, '+').replace(/_/g, '/'); // 支援 base64url
37
+ while(out.length % 4)out += '='; // 自動補 "="
38
+ const buffer = [];
39
+ for(let i = 0; i < out.length; i += 4){
40
+ const n = chars.indexOf(out[i]) << 18 | chars.indexOf(out[i + 1]) << 12 | (chars.indexOf(out[i + 2]) & 63) << 6 | chars.indexOf(out[i + 3]) & 63;
41
+ buffer.push(n >> 16 & 255);
42
+ if (out[i + 2] !== '=') buffer.push(n >> 8 & 255);
43
+ if (out[i + 3] !== '=') buffer.push(n & 255);
44
+ }
45
+ return new Uint8Array(buffer);
46
+ };
47
+ /**
48
+ * 將 JSON 資料編碼為 base64 字串
49
+ *
50
+ * @param data 要編碼的 JSON 可序列化資料
51
+ * @returns base64 編碼的字串
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * const data = { name: 'John', age: 30 };
56
+ * const encoded = encodeJson(data);
57
+ * console.log(encoded); // 'eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9'
58
+ *
59
+ * const array = [1, 2, 3];
60
+ * const encodedArray = encodeJson(array);
61
+ * ```
62
+ */ const encodeJson = (data)=>{
63
+ const json = JSON.stringify(data);
64
+ return encodeBase64(new TextEncoder().encode(json));
65
+ };
66
+ /**
67
+ * 將 base64 字串解碼為 JSON 資料
68
+ *
69
+ * @param b64 要解碼的 base64 字串
70
+ * @returns 解碼後的資料
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * const encoded = 'eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9';
75
+ * const decoded = decodeJson<{ name: string; age: number }>(encoded);
76
+ * console.log(decoded); // { name: 'John', age: 30 }
77
+ *
78
+ * const decodedArray = decodeJson<number[]>(encodedArray);
79
+ * ```
80
+ */ const decodeJson = (b64)=>{
81
+ const json = new TextDecoder().decode(decodeBase64(b64));
82
+ return JSON.parse(json);
83
+ };
84
+
85
+ const FILE_SIZE_UNITS = [
86
+ 'Bytes',
87
+ 'KB',
88
+ 'MB',
89
+ 'GB',
90
+ 'TB',
91
+ 'PB',
92
+ 'EB',
93
+ 'ZB',
94
+ 'YB'
95
+ ];
96
+ /**
97
+ * 代表字節大小的類,提供各種格式化和轉換方法
98
+ */ class ByteSize {
99
+ /**
100
+ * 建立一個新的 ByteSize 實例
101
+ * @param bytes 位元組數值
102
+ */ constructor(bytes){
103
+ this.bytes = bytes;
104
+ }
105
+ /**
106
+ * 取得原始位元組數值
107
+ */ get value() {
108
+ return this.bytes;
109
+ }
110
+ /**
111
+ * 將位元組轉換為指定單位的數值
112
+ *
113
+ * @param unit 目標單位 (例如 'KB', 'MB', 'GB')
114
+ * @returns 轉換後的數值
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * const size = createByteSize(1024);
119
+ * size.to('KB'); // 1
120
+ * size.to('MB'); // 0.0009765625
121
+ * ```
122
+ */ to(unit) {
123
+ if (!FILE_SIZE_UNITS.includes(unit)) {
124
+ console.warn(`Invalid unit: ${unit}. Valid units are: ${FILE_SIZE_UNITS.join(', ')}`);
125
+ return this.bytes;
126
+ }
127
+ const k = 1024;
128
+ const i = FILE_SIZE_UNITS.indexOf(unit);
129
+ return this.bytes / k ** i;
130
+ }
131
+ /**
132
+ * 轉換為適當單位的可讀字符串
133
+ *
134
+ * @param unit 指定單位 (例如 'KB', 'MB', 'GB'),不指定則自動選擇最適合的單位
135
+ * @param decimals 小數點位數 (預設為 2)
136
+ * @returns 格式化後的字符串
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * const size = createByteSize(1024);
141
+ * size.format(); // '1.00 KB'
142
+ * size.format('KB'); // '1.00 KB'
143
+ * size.format('MB', 3); // '0.001 MB'
144
+ * ```
145
+ */ format(unit, decimals = 2) {
146
+ if (this.bytes === 0) return `0 ${unit || 'Bytes'}`;
147
+ const k = 1024;
148
+ // 如果指定了有效單位,則使用;否則,計算最適合的單位
149
+ const i = unit && FILE_SIZE_UNITS.includes(unit) ? FILE_SIZE_UNITS.indexOf(unit) : Math.floor(Math.log(this.bytes) / Math.log(k));
150
+ return `${(this.bytes / k ** i).toFixed(decimals)} ${FILE_SIZE_UNITS[i]}`;
151
+ }
152
+ /**
153
+ * 比較兩個 ByteSize 實例
154
+ *
155
+ * @param other 要比較的另一個 ByteSize 實例
156
+ * @returns 比較結果:-1 表示小於,0 表示等於,1 表示大於
157
+ */ compareTo(other) {
158
+ if (this.bytes < other.value) return -1;
159
+ if (this.bytes > other.value) return 1;
160
+ return 0;
161
+ }
162
+ /**
163
+ * 轉換為字符串表示
164
+ * @returns 預設格式化的字符串
165
+ */ toString() {
166
+ return this.format();
167
+ }
168
+ }
169
+ /**
170
+ * 將位元組轉換為可讀字符串 (保留舊的 API 以確保向後兼容)
171
+ *
172
+ * @param bytes 位元組數值
173
+ * @param unit 目標單位 (例如 'KB', 'MB', 'GB'),不指定則自動選擇最適合的單位
174
+ * @param decimals 小數點位數 (預設為 2)
175
+ * @returns 格式化後的字符串
176
+ *
177
+ * @example
178
+ * ```ts
179
+ * convertBytes(0) // '0 Bytes'
180
+ * convertBytes(1024, 'KB') // '1 KB'
181
+ * convertBytes(1024, 'KB', 2) // '1.00 KB'
182
+ * convertBytes(1024 * 1024, 'MB') // '1 MB'
183
+ * convertBytes(1024 * 1024, 'KB') // '1024 KB'
184
+ * ```
185
+ */ const convertBytes = (bytes, unit, decimals = 2)=>new ByteSize(bytes).format(unit, decimals);
186
+
187
+ /**
188
+ * 檢查兩個值是否相等(包含陣列等引用型別)
189
+ * - 支援基本型別的直接比較
190
+ * - 特別處理空陣列比較
191
+ * - 支援非空陣列的深度比較
192
+ *
193
+ * @param value1 - 第一個值
194
+ * @param value2 - 第二個值
195
+ * @returns 如果值相等則返回 true
196
+ *
197
+ * @example
198
+ * // 基本型別比較
199
+ * isEqual(1, 1); // true
200
+ * isEqual('abc', 'abc'); // true
201
+ * isEqual(null, null); // true
202
+ *
203
+ * // 陣列比較
204
+ * isEqual([], []); // true
205
+ * isEqual([1, 2], [1, 2]); // true
206
+ * isEqual([1, 2], [1, 3]); // false
207
+ */ const isEqual = (value1, value2)=>{
208
+ // 處理基本型別
209
+ if (value1 === value2) {
210
+ return true;
211
+ }
212
+ // 處理空陣列
213
+ if (Array.isArray(value1) && Array.isArray(value2) && value1.length === 0 && value2.length === 0) {
214
+ return true;
215
+ }
216
+ // 兩者都是非 null 的物件(包含陣列)
217
+ if (value1 !== null && value2 !== null && typeof value1 === 'object' && typeof value2 === 'object') {
218
+ // 處理非空陣列
219
+ if (Array.isArray(value1) && Array.isArray(value2)) {
220
+ if (value1.length !== value2.length) {
221
+ return false;
222
+ }
223
+ return value1.every((item, index)=>isEqual(item, value2[index]));
224
+ }
225
+ // 未來可以擴展這裡,增加其他物件型別的深度比較
226
+ }
227
+ return false;
228
+ };
229
+
230
+ /**
231
+ * 將指定格式的物件轉換成類似 enum 的物件
232
+ *
233
+ * @param enumObject enum 物件
234
+ * @param valueKey value 的 key
235
+ *
236
+ * @example
237
+ * const myObj = {
238
+ * A: { value: 'a' },
239
+ * B: { value: 'b', other: 'other' },
240
+ * } as const;
241
+ * const enumCode = extractEnumLikeObject(myObj, 'value');
242
+ * // => { A: 'a', B: 'b' }
243
+ */ const extractEnumLikeObject = (enumObject, valueKey)=>Object.entries(enumObject).reduce((acc, [key, value])=>({
244
+ ...acc,
245
+ [key]: value[valueKey]
246
+ }), {});
247
+ // 實作
248
+ function createEnumLikeObject(obj, options) {
249
+ const name = options?.name;
250
+ const scene = options?.scene;
251
+ const valueKey = options?.valueKey ?? 'value';
252
+ const Enum = extractEnumLikeObject(obj, valueKey);
253
+ // List:根據有無 scene 做不同處理
254
+ let list;
255
+ if (scene) {
256
+ // scenes 版本:解構指定 scene 的 label
257
+ list = Object.entries(obj).map(([key, item])=>({
258
+ key,
259
+ value: item?.[valueKey],
260
+ ...item.scenes?.[scene] ?? {}
261
+ }));
262
+ } else {
263
+ // label only 版本
264
+ list = Object.entries(obj).map(([key, item])=>({
265
+ key,
266
+ value: item?.[valueKey],
267
+ ...item
268
+ }));
269
+ }
270
+ function getLabel(value) {
271
+ const targetItem = list.find((item)=>// 如果 list 項目內含有 valueKey 對應欄位,優先以該欄位比對;否則以 value 欄位比對
272
+ valueKey in item ? item[valueKey] === value : item.value === value);
273
+ if (!targetItem) return String(value);
274
+ if ('label' in targetItem) return targetItem.label;
275
+ return String(value);
276
+ }
277
+ if (name) {
278
+ // 命名版:使用 Enum${name}, ${name}List, get${name}Label 鍵名
279
+ return {
280
+ [`Enum${name}`]: Enum,
281
+ [`${name}List`]: list,
282
+ [`get${name}Label`]: getLabel
283
+ };
284
+ }
285
+ // 未命名:提供預設鍵名 Enum, List, getLabel
286
+ return {
287
+ Enum,
288
+ List: list,
289
+ getLabel
290
+ };
291
+ }
292
+
293
+ /**
294
+ * simulate a fake api request
295
+ *
296
+ * @param returnValue the value to return
297
+ * @param result the result of the request
298
+ * @param time the time to wait before resolving
299
+ *
300
+ * @example
301
+ *
302
+ * const result = await fakeApi({ foo: 'bar' });
303
+ * console.log(result); // { result: true, data: { foo: 'bar' } }
304
+ */ const fakeApi = (returnValue, result = true, time = 1000)=>new Promise((resolve)=>{
305
+ setTimeout(()=>{
306
+ if (result) resolve({
307
+ result,
308
+ data: returnValue
309
+ });
310
+ else resolve({
311
+ result,
312
+ message: 'error'
313
+ });
314
+ }, time);
315
+ });
316
+
317
+ const MimeTypeMap = {
318
+ jpeg: 'image/jpeg',
319
+ jpg: 'image/jpeg',
320
+ gif: 'image/gif',
321
+ png: 'image/png',
322
+ pdf: 'application/pdf',
323
+ zip: 'application/zip',
324
+ csv: 'text/csv',
325
+ ppt: 'application/vnd.ms-powerpoint',
326
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
327
+ xls: 'application/vnd.ms-excel',
328
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
329
+ doc: 'application/msword',
330
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
331
+ txt: 'text/plain'
332
+ };
333
+ const OtherMimeType = 'application/octet-stream';
334
+
335
+ /**
336
+ * 檢查檔案是否為合法的檔案類型
337
+ *
338
+ * `accepts` 可同時接受副檔名以及 MIME 類型
339
+ *
340
+ * @param file 檔案
341
+ * @param accepts 允許的類型
342
+ *
343
+ * @example
344
+ *
345
+ * ```js
346
+ * validateFileType({ type: 'image/png' }, ['image/png', 'image/jpeg']) // true
347
+ * validateFileType({ type: 'image/png' }, ['image/jpeg']) // false
348
+ * validateFileType({ type: 'image/png' }, ['image/*']) // true
349
+ * validateFileType({ name: '圖片.png', type: 'image/png' }, ['.png']) // true
350
+ * ```
351
+ */ const validateFileType = (file, accepts)=>{
352
+ if (accepts.length === 0) return true;
353
+ // 獲取文件的MIME類型
354
+ const fileMimeType = file.type;
355
+ // 提取副檔名(含 .,且轉小寫)
356
+ const fileExt = file.name.includes('.') ? `.${file.name.split('.').pop().toLowerCase()}` : '';
357
+ return accepts.some((accept)=>{
358
+ if (accept.startsWith('.')) {
359
+ // 以副檔名檢查,忽略大小寫
360
+ return fileExt === accept.toLowerCase();
361
+ }
362
+ if (accept === fileMimeType) {
363
+ return true;
364
+ }
365
+ if (accept.endsWith('/*')) {
366
+ return accept.split('/')[0] === fileMimeType.split('/')[0];
367
+ }
368
+ return false;
369
+ });
370
+ };
371
+ /**
372
+ * 根據檔案副檔名取得對應的 MIME Type
373
+ *
374
+ * 目前支援的副檔名有:pdf, csv, jpeg, jpg, png, zip, txt
375
+ * 除此之外的副檔名皆回傳 application/octet-stream
376
+ *
377
+ * @param fileExtension 檔案副檔名
378
+ *
379
+ * @example
380
+ *
381
+ * getMimeType('pdf') // 'application/pdf'
382
+ * getMimeType('csv') // 'text/csv'
383
+ * getMimeType('jpeg') // 'image/jpeg'
384
+ * getMimeType('jpg') // 'image/jpeg'
385
+ * getMimeType('png') // 'image/png'
386
+ * getMimeType('txt') // 'text/plain'
387
+ * getMimeType('zip') // 'application/zip'
388
+ * getMimeType('mp4') // 'application/octet-stream'
389
+ * getMimeType('xls') // 'application/vnd.ms-excel'
390
+ * getMimeType('xlsx') // 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
391
+ * getMimeType('doc') // 'application/msword'
392
+ * getMimeType('docx') // 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
393
+ *
394
+ * @deprecated use `parseFileInfoFromFilename` instead
395
+ */ const getMimeType = (fileName)=>{
396
+ const ext = (fileName.split('.').pop() || '').toLowerCase();
397
+ return MimeTypeMap[ext] ?? OtherMimeType;
398
+ };
399
+ /**
400
+ * 用來解析後端在 response header content-disposition 的內容
401
+ *
402
+ * 一般來說格式會有以下兩種
403
+ *
404
+ * - Content-Disposition: attachment; filename="file name.jpg"
405
+ * - Content-Disposition: attachment; filename*=UTF-8''file%20name2.jpg
406
+ *
407
+ * 如果格式正確就會取得檔案名稱(包含副檔名),優先取 filename* 內的內容
408
+ *
409
+ * @param disposition Content-Disposition
410
+ *
411
+ * @example
412
+ *
413
+ * parseFilenameFromDisposition('attachment; filename="file name1.jpg') // file name.jpg
414
+ * parseFilenameFromDisposition('attachment; filename*=UTF-8''file%20name2.jpg') // file name2.jpg
415
+ * parseFilenameFromDisposition('attachment; filename="file name.jpg; filename*=UTF-8''file%20name2.jpg') // file name2.jpg
416
+ */ const parseFilenameFromDisposition = (disposition)=>{
417
+ // 1. 先找 filename*
418
+ const filenameStarMatch = disposition.match(/filename\*\s*=\s*(?:UTF-8'')?([^;]+)/i);
419
+ if (filenameStarMatch && filenameStarMatch[1]) {
420
+ // 依 RFC 5987 格式(UTF-8''URL-ENCODED),要先 decode
421
+ try {
422
+ return decodeURIComponent(filenameStarMatch[1].replace(/(^['"]|['"]$)/g, ''));
423
+ } catch {
424
+ // fallback,如果 decode 失敗,直接傳回原值
425
+ return filenameStarMatch[1];
426
+ }
427
+ }
428
+ // 2. 沒有 filename*,再找 filename
429
+ const filenameMatch = disposition.match(/filename\s*=\s*("?)([^";]+)\1/i);
430
+ if (filenameMatch && filenameMatch[2]) {
431
+ return filenameMatch[2];
432
+ }
433
+ // 3. 都沒有則 undefined
434
+ return undefined;
435
+ };
436
+ /**
437
+ * 解析 `filename` 回傳檔名、副檔名、MIME type
438
+ *
439
+ * @param filename 檔案名稱
440
+ *
441
+ * @example
442
+ *
443
+ * parseFileInfoFromFilename('image.jpg') // ['image', 'jpg', 'image/jpeg']
444
+ * parseFileInfoFromFilename('image') // ['image', '', 'application/octet-stream']
445
+ */ const parseFileInfoFromFilename = (filename)=>{
446
+ const lastDot = filename.lastIndexOf('.');
447
+ if (lastDot === -1) return [
448
+ filename,
449
+ '',
450
+ OtherMimeType
451
+ ]; // 沒有副檔名
452
+ return [
453
+ filename.slice(0, lastDot),
454
+ filename.slice(lastDot + 1),
455
+ MimeTypeMap[filename.slice(lastDot + 1)] ?? OtherMimeType
456
+ ];
457
+ };
458
+
459
+ // const isProduction: boolean = process.env.NODE_ENV === 'production';
460
+ const prefix = 'Invariant failed';
461
+ // Throw an error if the condition fails
462
+ // Strip out error messages for production
463
+ // > Not providing an inline default argument for message as the result is smaller
464
+ function invariant(condition, // Can provide a string, or a function that returns a string for cases where
465
+ // the message takes a fair amount of effort to compute
466
+ message) {
467
+ if (condition) {
468
+ return;
469
+ }
470
+ // Condition not passed
471
+ // In production we strip the message but still throw
472
+ if (process.env.NODE_ENV === 'production') {
473
+ throw new Error(prefix);
474
+ }
475
+ // When not in production we allow the message to pass through
476
+ // *This block will be removed in production builds*
477
+ const provided = typeof message === 'function' ? message() : message;
478
+ // Options:
479
+ // 1. message provided: `${prefix}: ${provided}`
480
+ // 2. message not provided: prefix
481
+ const value = provided ? `${prefix}: ${provided}` : prefix;
482
+ throw new Error(value);
483
+ }
484
+
485
+ /**
486
+ * 判斷執行環境是否為 Server(node.js) 端
487
+ */ const isServer = ()=>typeof window === 'undefined';
488
+
489
+ /**
490
+ * 將物件中的某些 key 排除
491
+ *
492
+ * @param object 原始物件
493
+ * @param keys 要排除的 key
494
+ *
495
+ * @example
496
+ * const a = { a: 1, b: 2, c: 3, d: 4 };
497
+ * const b = omit(a, 'a', 'b'); // { c: 3, d: 4 }
498
+ */ const omit = (object, ...keys)=>Object.keys(object).reduce((acc, cur)=>{
499
+ if (keys.includes(cur)) {
500
+ return acc;
501
+ }
502
+ return {
503
+ ...acc,
504
+ [cur]: object[cur]
505
+ };
506
+ }, {});
507
+ /**
508
+ * 將物件中的某些 value 排除
509
+ *
510
+ * @param object 原始物件
511
+ * @param values 要排除的 value
512
+ *
513
+ * @example
514
+ * const a = { a: undefined, b: null, c: 3, d: 4, e: [] };
515
+ * const b = omitByValue(a, undefined, null, []); // { c: 3, d: 4 }
516
+ */ const omitByValue = (object, ...values)=>Object.entries(object).reduce((acc, [key, value])=>{
517
+ // 使用深度比較檢查值是否應該被排除
518
+ const shouldOmit = values.some((excludeValue)=>isEqual(value, excludeValue));
519
+ if (shouldOmit) {
520
+ return acc;
521
+ }
522
+ return {
523
+ ...acc,
524
+ [key]: value
525
+ };
526
+ }, {});
527
+ /**
528
+ * extract the object fields by the given keys
529
+ *
530
+ * @param object - the object to pick fields from
531
+ * @param keys - the keys to pick
532
+ *
533
+ * @example
534
+ *
535
+ * const a = { a: 1, b: 2, c: 3, d: 4 };
536
+ * const b = pick(a, 'a', 'b'); // { a: 1, b: 2 }
537
+ */ const pick = (object, ...keys)=>keys.reduce((acc, cur)=>({
538
+ ...acc,
539
+ [cur]: object[cur]
540
+ }), {});
541
+ /**
542
+ * extract the object fields by the given values
543
+ *
544
+ * @param object - the object to pick fields from
545
+ * @param values - the values to pick
546
+ *
547
+ * @example
548
+ *
549
+ * const a = { a: 1, b: 2, c: 3, d: 4, e: [] };
550
+ * const b = pickByValue(a, 1, 2, []); // { a: 1, b: 2, e: [] }
551
+ */ const pickByValue = (object, ...values)=>Object.entries(object).reduce((acc, [key, value])=>{
552
+ // 使用深度比較檢查值是否應該被選擇
553
+ const shouldPick = values.some((pickValue)=>isEqual(value, pickValue));
554
+ if (shouldPick) {
555
+ return {
556
+ ...acc,
557
+ [key]: value
558
+ };
559
+ }
560
+ return acc;
561
+ }, {});
562
+ const isObject = (value)=>value !== null && typeof value === 'object';
563
+ /**
564
+ * merge two objects deeply
565
+ *
566
+ * @param target - the target object
567
+ * @param source - the source object
568
+ *
569
+ * @example
570
+ *
571
+ * const obja = { a: { a1: { a11: 'value 1', a12: 'value 2' }, a2: 'value 3' }, b: 'value 4' };
572
+ * const objb = { a: { a1: { a13: 'value 5', a14: 'value 6' }, a3: 'value 7' }};
573
+ *
574
+ * const mergeResult = deepMerge(obja, objb); // { a: { a1: { a11: 'value 1', a12: 'value 2', a13: 'value 5', a14: 'value 6' }, a2: 'value 3', a3: 'value 7' }, b: 'value 4' }
575
+ *
576
+ */ const deepMerge = (target, source)=>Object.entries(source).reduce((acc, [key, value])=>{
577
+ if (isObject(value)) {
578
+ acc[key] = key in target && isObject(target[key]) ? deepMerge(target[key], value) : value;
579
+ } else {
580
+ acc[key] = value;
581
+ }
582
+ return acc;
583
+ }, {
584
+ ...target
585
+ });
586
+ /**
587
+ * A utility function to deeply clone an object.
588
+ * @param obj - The object to clone.
589
+ *
590
+ * @example
591
+ *
592
+ * const original = { a: 1, b: { c: 2 } };
593
+ * const cloned = deepClone(original);
594
+ * console.log(cloned); // { a: 1, b: { c: 2 } }
595
+ *
596
+ */ const deepClone = (obj)=>{
597
+ if (obj === null || typeof obj !== 'object') {
598
+ return obj;
599
+ }
600
+ if (obj instanceof Date) {
601
+ return new Date(obj.getTime());
602
+ }
603
+ if (Array.isArray(obj)) {
604
+ return obj.map((item)=>deepClone(item));
605
+ }
606
+ const cloned = Object.keys(obj).reduce((acc, key)=>{
607
+ acc[key] = deepClone(obj[key]);
608
+ return acc;
609
+ }, {});
610
+ return cloned;
611
+ };
612
+ /**
613
+ * A utility function to rename a key in an object.
614
+ *
615
+ * @param obj - The object to modify.
616
+ * @param oldKey - The key to rename.
617
+ * @param newKey - The new key name.
618
+ *
619
+ * @example
620
+ *
621
+ * const obj = { a: 1, b: 2 };
622
+ * const newObj = renameKey(obj, 'a', 'c');
623
+ * console.log(newObj); // { c: 1, b: 2 }
624
+ */ const renameKey = (obj, oldKey, newKey)=>{
625
+ // 建立一個淺拷貝,避免修改原始物件
626
+ const { [oldKey]: oldValue, ...rest } = obj;
627
+ // 回傳新的物件:用新 key 存舊值,其他 key 保留
628
+ return {
629
+ ...rest,
630
+ [newKey]: oldValue
631
+ };
632
+ };
633
+
634
+ /**
635
+ * 將嵌套物件的所有屬性設為指定的布林值
636
+ * @param obj - 目標物件
637
+ * @param boolValue - 布林值
638
+ *
639
+ * @example
640
+ * const obj = { a: { b: 1, c: 2 }, d: 3 };
641
+ * const result = setBooleanToNestedObject(obj, true);
642
+ * console.log(result); // { a: { b: true, c: true }, d: true }
643
+ */ const setBooleanToNestedObject = (obj, boolValue)=>Object.entries(obj).reduce((acc, [key, value])=>{
644
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
645
+ // 如果是嵌套物件,遞歸處理
646
+ acc[key] = setBooleanToNestedObject(value, boolValue);
647
+ } else {
648
+ // 如果是基本類型,設為布林值
649
+ acc[key] = boolValue;
650
+ }
651
+ return acc;
652
+ }, {});
653
+ /**
654
+ * 深度合併配置物件的通用工具
655
+ *
656
+ * @param defaultConfig - 預設配置
657
+ * @param customConfig - 自訂配置
658
+ *
659
+ * @example
660
+ * const defaultConfig = { a: true, b: { b1: true, b2: true, b3: false }, c: true, d: false };
661
+ * mergeConfig(defaultConfig, { b: { b1: false }, d: true }); // { a: true, b: { b1: false, b2: true, b3: false }, c: true, d: true }
662
+ * mergeConfig(defaultConfig, { b: false }); // { a: true, b: { b1: false, b2: false, b3: false }, c: true, d: false }
663
+ * mergeConfig(defaultConfig, { b: true }); // { a: true, b: { b1: true, b2: true, b3: true }, c: true, d: false }
664
+ */ const mergeConfig = (defaultConfig, customConfig = {})=>{
665
+ // 深拷貝預設配置以避免修改原始物件
666
+ const result = deepClone(defaultConfig);
667
+ return Object.entries(customConfig).reduce((acc, [key, sourceValue])=>{
668
+ const targetValue = acc[key];
669
+ // 如果來源值為 null 或 undefined,跳過
670
+ if (sourceValue === null || sourceValue === undefined) {
671
+ return acc;
672
+ }
673
+ // 如果目標物件中對應的值是物件,且來源值是布林值
674
+ // 這是特殊情況:用布林值覆蓋整個嵌套物件
675
+ if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue) && typeof sourceValue === 'boolean') {
676
+ // 將嵌套物件的所有屬性設為該布林值
677
+ acc[key] = setBooleanToNestedObject(targetValue, sourceValue);
678
+ } else if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue) && typeof sourceValue === 'object' && sourceValue !== null && !Array.isArray(sourceValue)) {
679
+ acc[key] = mergeConfig(targetValue, sourceValue);
680
+ } else {
681
+ acc[key] = sourceValue;
682
+ }
683
+ return acc;
684
+ }, result);
685
+ };
686
+
687
+ /**
688
+ * debounce function
689
+ *
690
+ * @param {Function} fn function to be executed
691
+ * @param {number} delay time to wait before executing the function
692
+ *
693
+ * @example
694
+ * const debouncedFunction = debounce((a: number, b: number) => console.log(a + b), 1000);
695
+ * debouncedFunction(1, 2);
696
+ * debouncedFunction(3, 4);
697
+ * // after 1 second
698
+ * // 7
699
+ */ const debounce = (fn, delay)=>{
700
+ let timeout;
701
+ // if (isAsync) {
702
+ // return (...args: P[]) =>
703
+ // new Promise((resolve) => {
704
+ // if (timeout) {
705
+ // clearTimeout(timeout);
706
+ // }
707
+ // timeout = setTimeout(() => {
708
+ // resolve(fn(...args));
709
+ // }, delay);
710
+ // });
711
+ // }
712
+ return (...args)=>{
713
+ if (timeout) {
714
+ clearTimeout(timeout);
715
+ }
716
+ timeout = setTimeout(()=>{
717
+ fn(...args);
718
+ }, delay);
719
+ };
720
+ };
721
+ /**
722
+ * throttle function
723
+ *
724
+ * @param {Function} fn function to be executed
725
+ * @param {number} delay time to wait before executing the function
726
+ *
727
+ * @example
728
+ * const throttledFunction = throttle((a: number, b: number) => a + b, 1000);
729
+ * throttledFunction(1, 2); // 3
730
+ * throttledFunction(3, 4); // undefined
731
+ * setTimeout(() => {
732
+ * throttledFunction(5, 6); // 11
733
+ * }, 2000);
734
+ */ const throttle = (fn, delay)=>{
735
+ let wait = false;
736
+ return (...args)=>{
737
+ if (wait) return undefined;
738
+ const val = fn(...args);
739
+ wait = true;
740
+ setTimeout(()=>{
741
+ wait = false;
742
+ }, delay);
743
+ return val;
744
+ };
745
+ };
746
+
747
+ /**
748
+ * Wait for a given amount of time
749
+ * @param ms time to wait in milliseconds
750
+ */ const wait = (ms)=>{
751
+ };
752
+
753
+ /**
754
+ * 將單層物件轉換為 URLSearchParams 物件
755
+ * - 會自動排除 null、undefined、空字串和空陣列的值
756
+ * - 陣列會以逗號連接為字串
757
+ *
758
+ * @param obj - 要轉換的物件,只支援單層物件,其中值可以是 string、number、boolean、null、undefined 或字串陣列
759
+ * @returns URLSearchParams 實例
760
+ *
761
+ * @example
762
+ * const params = { a: '1', b: 123, c: false, d: ['1','2'], e: null, f: undefined, g: '', h: [] };
763
+ * objectToSearchParams(params).toString(); // 'a=1&b=123&c=false&d=1%2C2'
764
+ */ const objectToSearchParams = (obj)=>{
765
+ const searchParams = new URLSearchParams();
766
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
767
+ return searchParams;
768
+ }
769
+ Object.entries(omitByValue(obj, undefined, null, '', [])).forEach(([key, value])=>{
770
+ // 如果是陣列,則以逗號連接
771
+ const paramValue = Array.isArray(value) ? value.join(',') : String(value);
772
+ searchParams.append(key, paramValue);
773
+ });
774
+ return searchParams;
775
+ };
776
+ /**
777
+ * 將字串值轉換為指定的型別
778
+ *
779
+ * @param value - 要轉換的字串值
780
+ * @param targetType - 目標型別
781
+ * @returns 轉換後的值
782
+ */ const convertValueByType = (value, targetType)=>{
783
+ switch(targetType){
784
+ case 'number':
785
+ return value ? Number(value) : 0;
786
+ case 'boolean':
787
+ return value === 'true' || value === '1';
788
+ case 'array':
789
+ return value ? value.split(',') : [];
790
+ case 'string':
791
+ default:
792
+ // 預設為字串,不需要轉換
793
+ return value;
794
+ }
795
+ };
796
+ /**
797
+ * 將 URLSearchParams 或字串轉換為物件
798
+ *
799
+ * @param searchParams - 要轉換的搜尋參數字串或 URLSearchParams 實例
800
+ * @param typeMap - 可選的型別轉換映射表,用於指定每個參數的目標型別
801
+ * @returns
802
+ *
803
+ * @example
804
+ * const queryString = 'a=1&b=123&c=true&d=1,2,3&e=false';
805
+ * const result = searchParamsToObject(queryString);
806
+ * // result: { a: '1', b: '123', c: 'true', d: '1,2,3', e: 'false' }
807
+ * const result = searchParamsToObject(queryString, {
808
+ * a: 'string',
809
+ * b: 'number',
810
+ * c: 'boolean',
811
+ * d: 'array',
812
+ * e: 'boolean',
813
+ * });
814
+ * // result: { a: '1', b: 123, c: true, d: ['1', '2', '3'], e: false }
815
+ */ const searchParamsToObject = (searchParams, typeMap = {})=>{
816
+ const searchParamsInstance = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
817
+ const result = {};
818
+ // 從 URLSearchParams 取得所有參數
819
+ searchParamsInstance.forEach((value, key)=>{
820
+ if (!key) {
821
+ return;
822
+ }
823
+ const targetType = typeMap[key];
824
+ result[key] = convertValueByType(value, targetType);
825
+ });
826
+ return result;
827
+ };
828
+
829
+ /**
830
+ * 從 localStorage 取得資料,支援槽狀取值(Json 物件)
831
+ *
832
+ * @param key 鍵值
833
+ * @param deCode 是否解碼
834
+ * @returns 取得的資料
835
+ * @example
836
+ * const data = getLocalStorage('key');
837
+ *
838
+ * const data = getLocalStorage('key.subKey');
839
+ */ const getLocalStorage = (key, deCode = true)=>{
840
+ const keys = key.split('.');
841
+ const storage = localStorage.getItem(keys[0]);
842
+ if (!storage) return undefined;
843
+ let currentObject;
844
+ try {
845
+ if (deCode) {
846
+ currentObject = decodeJson(storage);
847
+ } else {
848
+ currentObject = JSON.parse(storage);
849
+ }
850
+ } catch (_error) {
851
+ return undefined;
852
+ }
853
+ // let currentObject = JSON.parse(storage);
854
+ if (keys.length === 1) {
855
+ return currentObject;
856
+ }
857
+ keys.shift();
858
+ while(keys.length > 0){
859
+ const currentKey = keys.shift();
860
+ if (!currentKey) break;
861
+ currentObject = currentObject[currentKey];
862
+ if (!currentObject) break;
863
+ }
864
+ return currentObject;
865
+ };
866
+ /**
867
+ * 將資料(Json 物件)存入 localStorage
868
+ * @param key 鍵值
869
+ * @param value 可序列化的資料
870
+ * @param enCode 是否編碼
871
+ */ const setLocalStorage = (key, value, enCode = true)=>{
872
+ if (enCode) {
873
+ localStorage.setItem(key, encodeJson(value));
874
+ } else {
875
+ localStorage.setItem(key, JSON.stringify(value));
876
+ }
877
+ };
878
+
879
+ export { throttle as A, ByteSize as B, wait as C, getLocalStorage as D, setLocalStorage as E, MimeTypeMap as M, OtherMimeType as O, encodeJson as a, decodeJson as b, convertBytes as c, decodeBase64 as d, encodeBase64 as e, extractEnumLikeObject as f, createEnumLikeObject as g, fakeApi as h, isEqual as i, getMimeType as j, parseFileInfoFromFilename as k, invariant as l, mergeConfig as m, isServer as n, objectToSearchParams as o, parseFilenameFromDisposition as p, omit as q, omitByValue as r, searchParamsToObject as s, pick as t, pickByValue as u, validateFileType as v, deepMerge as w, deepClone as x, renameKey as y, debounce as z };