@codady/utils 0.0.38 → 0.0.40

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 (58) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/utils.cjs.js +576 -24
  3. package/dist/utils.cjs.min.js +3 -3
  4. package/dist/utils.esm.js +576 -24
  5. package/dist/utils.esm.min.js +3 -3
  6. package/dist/utils.umd.js +576 -24
  7. package/dist/utils.umd.min.js +3 -3
  8. package/dist.zip +0 -0
  9. package/examples/ajax-download.html +94 -0
  10. package/examples/ajax-get.html +59 -0
  11. package/examples/ajax-hook.html +55 -0
  12. package/examples/ajax-method.html +36 -0
  13. package/examples/ajax-post.html +37 -0
  14. package/examples/ajax-signal.html +91 -0
  15. package/examples/ajax-timeout.html +85 -0
  16. package/examples/buildUrl.html +99 -0
  17. package/examples/getUrlHash.html +71 -0
  18. package/examples/stringToEncodings-collision-test-registry.html +117 -0
  19. package/examples/stringToEncodings-collision-test.html +71 -0
  20. package/examples/stringToEncodings.html +138 -0
  21. package/examples/unicodeToEncodings.html +195 -0
  22. package/modules.js +17 -1
  23. package/modules.ts +17 -1
  24. package/package.json +1 -1
  25. package/src/ajax.js +380 -0
  26. package/src/ajax.ts +470 -0
  27. package/src/buildUrl.js +64 -0
  28. package/src/buildUrl.ts +86 -0
  29. package/src/capitalize.js +19 -0
  30. package/src/capitalize.ts +20 -0
  31. package/src/cleanQueryString.js +19 -0
  32. package/src/cleanQueryString.ts +20 -0
  33. package/src/getBodyHTML.js +53 -0
  34. package/src/getBodyHTML.ts +61 -0
  35. package/src/getEl.js +1 -1
  36. package/src/getEl.ts +6 -5
  37. package/src/getEls.js +1 -1
  38. package/src/getEls.ts +5 -5
  39. package/src/getUrlHash.js +37 -0
  40. package/src/getUrlHash.ts +39 -0
  41. package/src/isEmpty.js +24 -23
  42. package/src/isEmpty.ts +26 -23
  43. package/src/sliceStrEnd.js +63 -0
  44. package/src/sliceStrEnd.ts +60 -0
  45. package/src/stringToEncodings.js +56 -0
  46. package/src/stringToEncodings.ts +110 -0
  47. package/src/unicodeToEncodings.js +51 -0
  48. package/src/unicodeToEncodings.ts +55 -0
  49. package/src/arrayMutableMethods - /345/211/257/346/234/254.js" +0 -5
  50. package/src/comma - /345/211/257/346/234/254.js" +0 -2
  51. package/src/deepCloneToJSON - /345/211/257/346/234/254.js" +0 -47
  52. package/src/deepMergeMaps - /345/211/257/346/234/254.js" +0 -78
  53. package/src/escapeHTML - /345/211/257/346/234/254.js" +0 -29
  54. package/src/getDataType - /345/211/257/346/234/254.js" +0 -38
  55. package/src/isEmpty - /345/211/257/346/234/254.js" +0 -45
  56. package/src/mapMutableMethods - /345/211/257/346/234/254.js" +0 -5
  57. package/src/setMutableMethods - /345/211/257/346/234/254.js" +0 -5
  58. package/src/wrapMap - /345/211/257/346/234/254.js" +0 -119
package/src/ajax.ts ADDED
@@ -0,0 +1,470 @@
1
+ /**
2
+ * @since Last modified: 2026/01/20 18:14:18
3
+ * Sends an asynchronous HTTP request (AJAX).
4
+ * @function ajax
5
+ * @param {AjaxOptions} options - Configuration for the request.
6
+ * @returns {Promise<AjaxResponse>} Returns a promise that resolves with the response context.
7
+ * @example
8
+ * ajax({ url: '/api/data', method: 'GET' }).then(res => console.log(res.content));
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ import isEmpty from './isEmpty';
14
+ import getDataType from './getDataType';
15
+ import getBodyHTML from './getBodyHTML';
16
+ import getUrlHash from './getUrlHash';
17
+ import capitalize from './capitalize';
18
+ import buildUrl from './buildUrl';
19
+ import cleanQueryString from './cleanQueryString';
20
+
21
+ /**
22
+ * Interface for the AJAX configuration options.
23
+ */
24
+ interface AjaxOptions {
25
+ url: string; // Request URL
26
+ method?: string | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD' | 'TRACE';
27
+ async?: boolean; // Whether the request is asynchronous
28
+ data?: any; // Data to be sent
29
+ selector?: string; // Selector to extract specific content from HTML response
30
+ timeout?: number; // Request timeout in milliseconds
31
+ headers?: Record<string, string>; // HTTP headers
32
+ responseType?: XMLHttpRequestResponseType; // Expected response type (json, blob, etc.)
33
+ catchError?: boolean; // Whether to reject the promise on error/timeout
34
+ signal?: AbortSignal; // AbortSignal for canceling the request
35
+ xhrFields?: Record<string, any>; // Additional fields to set on the XHR object
36
+ cacheBustKey?: string,
37
+ precision?: number,
38
+ // Callbacks
39
+ onAbort?: ((resp: AjaxResponse) => void) | null;
40
+ onTimeout?: ((resp: AjaxResponse) => void) | null;
41
+ onOpened?: ((resp: AjaxResponse) => void) | null;
42
+ onHeadersReceived?: ((resp: AjaxResponse) => void) | null;
43
+ onLoading?: ((resp: AjaxResponse) => void) | null;
44
+ onBeforeSend?: ((resp: AjaxResponse) => void) | null;
45
+ onDownload?: ((resp: AjaxResponse) => void) | null;
46
+ onUpload?: ((resp: AjaxResponse) => void) | null;
47
+ onComplete?: ((resp: AjaxResponse) => void) | null; // Called when upload/download reaches 100%
48
+ onSuccess?: ((resp: AjaxResponse) => void) | null;
49
+ onFailure?: ((resp: AjaxResponse) => void) | null;
50
+ onInformation?: ((resp: AjaxResponse) => void) | null;
51
+ onRedirection?: ((resp: AjaxResponse) => void) | null;
52
+ onUnknownError?: ((resp: AjaxResponse) => void) | null;
53
+ onClientError?: ((resp: AjaxResponse) => void) | null;
54
+ onServerError?: ((resp: AjaxResponse) => void) | null;
55
+ onError?: ((resp: AjaxResponse) => void) | null;
56
+ onFinish?: ((resp: AjaxResponse) => void) | null; // Called on both success and failure
57
+ onCreated?: ((resp: AjaxResponse) => void) | null;
58
+ }
59
+
60
+ /**
61
+ * Interface for the response object passed to callbacks.
62
+ */
63
+ interface AjaxResponse {
64
+ xhr: XMLHttpRequest;
65
+ data: any; // The processed data sent in the request
66
+ abort: () => void; // Function to manually abort the request
67
+ status: number | string;
68
+ content: any; // The response body (parsed JSON, DOM string, etc.)
69
+ stage: number; // XHR readyState (0-4)
70
+ type: string; // Current stage name (e.g., 'success', 'timeout')
71
+ progress: {
72
+ name?: 'upload' | 'download';
73
+ loaded?: number;
74
+ total?: number;
75
+ timestamp?: number;
76
+ ratio?: number;
77
+ percent?: number;
78
+ text?: string;
79
+ };
80
+ }
81
+
82
+ const ajax = (options: AjaxOptions) => {
83
+ // Validation
84
+ if (isEmpty(options)) {
85
+ return Promise.reject(new Error('Options are required'));
86
+ }
87
+
88
+ if (!options.url || typeof options.url !== 'string') {
89
+ return Promise.reject(new Error('URL is required and must be a string'));
90
+ }
91
+
92
+ // Default configuration
93
+ const config: Required<AjaxOptions> = {
94
+ url: '',
95
+ method: 'POST',
96
+ async: true,
97
+ selector: '',
98
+ data: null,
99
+ timeout: 3600000,
100
+ headers: {},
101
+ responseType: '',
102
+ catchError: false,
103
+ signal: null as any,
104
+ xhrFields: {},
105
+ cacheBustKey: '_t',
106
+ precision: 2,
107
+ //
108
+ onAbort: null,
109
+ onTimeout: null,
110
+ //
111
+ onBeforeSend: null,
112
+ //
113
+ onCreated: null,
114
+ onOpened: null,
115
+ onHeadersReceived: null,
116
+ onLoading: null,
117
+ //
118
+ onSuccess: null,
119
+ onFailure: null,
120
+ onInformation: null,
121
+ onRedirection: null,
122
+ onClientError: null,
123
+ onServerError: null,
124
+ onUnknownError: null,
125
+ onError: null,
126
+ onFinish: null,
127
+ //
128
+ onDownload: null,
129
+ onUpload: null,
130
+ onComplete: null,
131
+ };
132
+
133
+ //合并参数
134
+ Object.assign(config, options);
135
+
136
+ //
137
+ const method = config.method.toUpperCase() || 'POST',
138
+ methodsWithoutBody = ['GET', 'HEAD', 'TRACE'];
139
+
140
+ //创建XMLHttpRequest
141
+ let xhr: any = new XMLHttpRequest(),
142
+ //设置发送数据和预设请求头
143
+ requestData: any = null,
144
+ headerContentType = config?.headers?.['Content-Type'] || config?.headers?.['content-type'],
145
+ removeHeader = () => {
146
+ if (headerContentType) {
147
+ delete config.headers['Content-Type'];
148
+ delete config.headers['content-type'];
149
+ }
150
+ }
151
+ if (!isEmpty(config.data)) {
152
+
153
+ let dataType = getDataType(config.data)
154
+ if (dataType === 'FormData') {
155
+ //如果是new FormData格式,直接相等
156
+ requestData = config.data;
157
+ // 不需要手动设置Content-Type,浏览器会自动设置
158
+ //config.contType = 'multipart/form-data';
159
+ removeHeader();
160
+ } else if (dataType === 'Object') {
161
+ //如果是对象格式{name:'',age:''}
162
+ //并且此时已经设置了contType
163
+ if (!headerContentType) {
164
+ //如果未设置则默认设为如下contType
165
+ //Content-Type=application/x-www-form-urlencoded
166
+ /* for (let k in config.data) {
167
+ requestData += '&' + k + '=' + config.data[k];
168
+ } */
169
+ requestData = new URLSearchParams(config.data).toString();
170
+ //URLSearchParams.toString => `a=1&b=3`
171
+ //非get、head方法修正content-type
172
+ if (!methodsWithoutBody.includes(method)) {
173
+ config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
174
+ }
175
+ } else if (headerContentType?.includes('application/json')) {
176
+ //Content-Type=application/json或contentType=application/json
177
+ requestData = JSON.stringify(config.data);
178
+ } else {
179
+ requestData = config.data;
180
+ }
181
+ } else if (dataType === 'String') {
182
+ //未设置或,已经设置了Content-Type=application/x-www-form-urlencoded
183
+ if (!headerContentType || headerContentType.includes('urlencoded')) {
184
+ //如果是name=''&age=''字符串
185
+ //?name=''&age=''或&name=''&age=''统一去掉第一个&/?
186
+ requestData = cleanQueryString(config.data.trim());
187
+ //非get、head方法修正content-type
188
+ if (!methodsWithoutBody.includes(method) && !headerContentType) {
189
+ config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
190
+ }
191
+ } else {
192
+ requestData = config.data;
193
+ }
194
+ } else {
195
+ requestData = config.data;
196
+ }
197
+ }
198
+
199
+ //设置超时时间
200
+ xhr.timeout = config.timeout;
201
+ // 响应类型
202
+ if (config.responseType) {
203
+ xhr.responseType = config.responseType as XMLHttpRequestResponseType;
204
+ }
205
+
206
+ //返回promise
207
+
208
+ const result = new Promise((resolve, reject) => {
209
+
210
+ //超时监听
211
+ const timeoutHandler = () => {
212
+ cleanup();
213
+ let resp = { ...context, status: xhr.status, content: xhr.response, type: 'timeout' };
214
+ //回调,status和content在此确认
215
+ config?.onTimeout?.(resp);
216
+ //reject只能接受一个参数
217
+ config.catchError ? reject(resp) : resolve(resp);
218
+ //超时也是不能获得数据的行为,定义为failure
219
+ config?.onFailure?.(resp);
220
+ //timeout会经过onreadystatechange,但是被及时的return了,所以这里多加一行
221
+ config?.onFinish?.(resp);
222
+ },
223
+ //报错监听
224
+ errorHandler = (resp: any) => {
225
+ //这几个错误来自xhr.onreadystatechange
226
+ if (resp.type === 'client-error') {
227
+ config?.onClientError?.({ ...context });
228
+ } else if (resp.type === 'server-error') {
229
+ config?.onServerError?.({ ...context });
230
+ } else if (resp.type === 'unknown-error') {
231
+ config?.onUnknownError?.({ ...context });
232
+ }
233
+ //此外还会有xhr.onerror的错误,所以需要统一使用onError监听
234
+
235
+ config?.onError?.(resp);
236
+ //reject只能接受一个参数
237
+ config.catchError ? reject(resp) : resolve(resp);
238
+ },
239
+ //取消监听
240
+ abortHandler = () => {
241
+ cleanup();
242
+ const resp = { ...context, status: xhr.status, type: 'abort' }
243
+ config.catchError ? reject(resp) : resolve(resp);
244
+ //回调,status和content在此确认
245
+ config?.onAbort?.(resp);
246
+ //abort行为不会经过onreadystatechange,这里需要多这一行以表示xhr的完成(结束)
247
+ config?.onFinish?.(resp);
248
+ },
249
+ abortHandlerWithSignal = () => {
250
+ //先中止请求,防止触发其他 readystate 事件
251
+ xhr.abort();
252
+ abortHandler();
253
+ },
254
+ //成功监听
255
+ successHandler = (resp: any) => {
256
+ //成功回调
257
+ config?.onSuccess?.(resp);
258
+ //resolve只能接受一个参数
259
+ resolve(resp);
260
+ },
261
+ //统一处理abort
262
+ cleanup = () => {
263
+ // 如果使用了AbortSignal,则移除它的事件监听器
264
+ config.signal && config.signal.removeEventListener('abort', abortHandlerWithSignal);
265
+ // 移除各类事件监听器
266
+ config.onError && xhr.removeEventListener('error', errorHandler);
267
+ config.onTimeout && xhr.removeEventListener('timeout', timeoutHandler);
268
+ // 解绑上传/下载进度事件
269
+ config.onUpload && xhr.upload.removeEventListener('progress', uploadProgressHandler);
270
+ config.onDownload && xhr.removeEventListener('progress', downloadProgressHandler);
271
+ //销毁
272
+ xhr.onreadystatechange = null;
273
+ },
274
+ // Context object to track state
275
+ context: AjaxResponse = {
276
+ //原始xhr
277
+ xhr,
278
+ //发送的数据
279
+ data: requestData,
280
+ //可取消的函数
281
+ abort: abortHandler,
282
+ //xhr.status
283
+ status: '',
284
+ //响应的内容
285
+ content: null,
286
+ //0~4阶段编号
287
+ stage: 0,
288
+ //阶段名称
289
+ type: 'unset',
290
+ //上传和下载进度
291
+ progress: {}
292
+ },
293
+ getProgressValues = (ratio: number) => {
294
+ let text = (ratio * 100).toFixed(config.precision);
295
+ return { percent: parseFloat(text), text }
296
+ },
297
+ //定义进度函数
298
+ progressHandler = (name: 'upload' | 'download', data: any, callback: Function) => {
299
+ if (data.lengthComputable) {
300
+ const resp = { ...context, status: xhr.status },
301
+ ratio = data.loaded / data.total,
302
+ { percent, text } = getProgressValues(ratio);
303
+ resp.progress = {
304
+ name,
305
+ loaded: data.loaded,
306
+ total: data.total,
307
+ timestamp: (new Date(data.timeStamp)).getTime(),
308
+ ratio,
309
+ percent,
310
+ text,
311
+ }
312
+ callback?.(resp);
313
+ if (ratio >= 1) {
314
+ Object.assign(resp.progress, getProgressValues(1));
315
+ config?.onComplete?.(resp);
316
+ }
317
+
318
+ }
319
+ }, uploadProgressHandler = (data: any) => {
320
+ progressHandler('upload', data, (resp: any) => (config.onUpload as Function)(resp));
321
+ },
322
+ downloadProgressHandler = (data: any) => {
323
+ progressHandler('download', data, (resp: any) => (config.onDownload as Function)(resp));
324
+ };
325
+
326
+
327
+ //使用AbortSignal
328
+ if (config.signal) {
329
+ if (config.signal.aborted) return abortHandlerWithSignal();
330
+ config.signal.addEventListener('abort', abortHandlerWithSignal);
331
+ }
332
+
333
+ //监听上传进度
334
+ config.onUpload && xhr.upload.addEventListener('progress', uploadProgressHandler);
335
+
336
+ //监听下载进度
337
+ config.onDownload && xhr.addEventListener('progress', downloadProgressHandler);
338
+
339
+ // 事件监听器
340
+ config.onError && xhr.addEventListener('error', errorHandler);
341
+ config.onTimeout && xhr.addEventListener('timeout', timeoutHandler);
342
+ config.onAbort && xhr.addEventListener('abort', abortHandler);
343
+
344
+ // 手动触发 Created 状态
345
+ config.onCreated?.({ ...context, type: 'created' });
346
+
347
+ //状态判断
348
+ xhr.onreadystatechange = function () {
349
+ context.stage = xhr.readyState;
350
+ context.status = xhr.status;
351
+ const statusMap: Record<number, string> = { 1: 'opened', 2: 'headersReceived', 3: 'loading' };
352
+ //0=created放在外侧确保能触发,如果放在.onreadystatechange可能触发不了
353
+ if (xhr.readyState < 4) {
354
+ if (!xhr.readyState) return;
355
+ context.type = statusMap[xhr.readyState];
356
+ (config as any)[`on${capitalize(context.type)}`]?.({ ...context });
357
+ return;
358
+ }
359
+
360
+ //tiemeout事件也会执行这里,此时需要让它触发onTimeout事件
361
+ //abort和timeout行为的status是0
362
+ //不过abort行为不会执行到这里
363
+ if (xhr.status === 0 && context.type !== 'abort') {
364
+ return;
365
+ }
366
+
367
+ //已经请求成功,不会有timeout事件,也不需要abort了,所以移除abort事件
368
+ cleanup();
369
+
370
+ //根据状态码判断响应结果
371
+ const isInformation = xhr.status >= 100 && xhr.status < 200,
372
+ isSuccess = (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304,
373
+ isRedirection = xhr.status >= 300 && xhr.status < 400,
374
+ isClientError = xhr.status >= 400 && xhr.status < 500,
375
+ isServerError = xhr.status >= 500 && xhr.status < 600;
376
+
377
+ //已经获得返回数据
378
+ if (isSuccess) {
379
+ if (!config.responseType || xhr.responseType === 'text') {
380
+ //可能返回字符串类型的对象,wordpress的REST API
381
+ let trim = xhr.responseText.trim(),
382
+ content = '';
383
+ if ((trim.startsWith('[') && trim.endsWith(']')) || (trim.startsWith('{') && trim.endsWith('}'))) {
384
+ //通过判断开头字符是{或[来确定异步页面是否是JSON内容,如果是则转成JSON对象
385
+ try {
386
+ content = JSON.parse(trim);
387
+ } catch {
388
+ console.warn('Malformed JSON detected, falling back to text.');
389
+ content = xhr.responseText;
390
+ }
391
+ } else if (/(<\/html>|<\/body>)/i.test(trim)) {
392
+ //请求了一个HTML页面
393
+ //返回文本类型DOMstring
394
+ let urlHash = getUrlHash(config.url);
395
+ content = getBodyHTML(trim, config.selector || urlHash);
396
+ } else {
397
+ //普通文本,不做任何处理
398
+ content = xhr.responseText;
399
+ }
400
+ //content=文本字符串/json
401
+ context.content = content;
402
+ } else {
403
+ //content=json、blob、document、arraybuffer等类型,如果知道服务器返回的XML, xhr.responseType应该为document
404
+ context.content = xhr.response;
405
+ }
406
+ context.type = 'success';
407
+ successHandler({ ...context });
408
+ } else {
409
+ //失败回调
410
+ context.content = xhr.response;
411
+ context.type = isInformation ? 'infomation' : isRedirection ? 'redirection' : isClientError ? 'client-error' : isServerError ? 'server-error' : 'unknown-error';
412
+ //
413
+ if (isInformation) {
414
+ config?.onInformation?.({ ...context });
415
+ } else if (isRedirection) {
416
+ config?.onRedirection?.({ ...context });
417
+ } else {
418
+ errorHandler({ ...context });
419
+ }
420
+ //
421
+ config?.onFailure?.({ ...context });
422
+ }
423
+ config?.onFinish?.({ ...context });
424
+ };
425
+
426
+ //发送异步请求
427
+ let openParams: (string | boolean)[] = [method, config.url, config.async];
428
+ if (methodsWithoutBody.includes(method)) {
429
+ // 拼接url => xxx.com?a=0&b=1#hello
430
+ const url = buildUrl({
431
+ url: config.url,
432
+ data: requestData,
433
+ cacheBustKey: config.cacheBustKey,
434
+ appendCacheBust: true,
435
+ });
436
+ openParams = [method, url, config.async];
437
+ }
438
+
439
+ //设置xhr其他字段
440
+ for (let k in config.xhrFields) {
441
+ config.xhrFields.hasOwnProperty(k) && (xhr[k] = config.xhrFields[k]);
442
+ }
443
+ //与服务器建立连接
444
+ xhr.open(...openParams);
445
+
446
+ //有则设置,仅跳过空内容
447
+ for (let k in config.headers) {
448
+ config.headers.hasOwnProperty(k) && !isEmpty(config.headers[k]) && xhr.setRequestHeader(k, config.headers[k]);
449
+ }
450
+
451
+ config?.onBeforeSend?.(({ ...context, status: xhr.status, type: 'beforeSend' }));
452
+ //发送请求,get和head不需要发送数据
453
+ xhr.send(methodsWithoutBody.includes(method) ? null : (requestData || null));
454
+ //open和send阶段已经是异步了,无法使用try+catch捕获错误
455
+ });
456
+ //绑定xhr和abort
457
+ (result as any).xhr = xhr;
458
+ (result as any).abort = () => xhr.abort();
459
+ return result;
460
+ };
461
+ // Static Helper Methods
462
+ //get、head、trace是不需要发送数据的,data将被转为url参数处理
463
+ ['post', 'put', 'delete', 'patch', 'options', 'get', 'head', 'trace'].forEach(method => {
464
+ (ajax as any)[method] = (url: string, data: any, options: AjaxOptions = { url: '' }) =>
465
+ ajax({ ...options, method, url, data });
466
+ });
467
+
468
+ ajax.all = (requests: AjaxOptions[]): Promise<AjaxResponse[]> => Promise.all(requests.map(ajax) as any);
469
+
470
+ export default ajax;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @since Last modified: 2026/01/20 13:56:36
3
+ * Builds a URL with query parameters, an optional cache-busting key, and preserves the hash.
4
+ * This function processes the base URL, appends query parameters, and optionally adds a cache-busting parameter.
5
+ * It also keeps the hash fragment intact if it exists in the original URL.
6
+ *
7
+ * @param {string} url - The original URL string that may or may not contain query parameters and a hash.
8
+ * @param {string | Record<string, string> | URLSearchParams} [data] - The data to be appended as query parameters.
9
+ * This can be a query string, an object, or a `URLSearchParams` object.
10
+ * @param {string} [cacheBustKey='_t'] - The cache-busting query parameter key to be appended to the URL. Default is '_t'.
11
+ * @param {boolean} [appendCacheBust=true] - A flag to indicate whether to append the cache-busting parameter. Default is true.
12
+ *
13
+ * @returns {string} The final constructed URL with the original URL, query parameters, and hash (if any).
14
+ *
15
+ * @example
16
+ * buildUrl({
17
+ * url: '/api/data',
18
+ * data: { key: 'value' },
19
+ * cacheBustKey: '_cache',
20
+ * appendCacheBust: true
21
+ * });
22
+ * // Returns: '/api/data?key=value&_cache=1638311234567'
23
+ */
24
+ import cleanQueryString from "./cleanQueryString";
25
+ import getDataType from "./getDataType";
26
+ import isEmpty from "./isEmpty";
27
+ const buildUrl = ({ url, data, cacheBustKey = '_t', appendCacheBust = true }) => {
28
+ // 1. Extract and remove the hash (e.g., /page#section -> hash="#section")
29
+ const hashIndex = url.indexOf('#');
30
+ let hash = '', pureUrl = url;
31
+ // If a hash exists, separate it from the base URL
32
+ if (hashIndex !== -1) {
33
+ hash = url.slice(hashIndex);
34
+ pureUrl = url.slice(0, hashIndex);
35
+ }
36
+ // 2. Use the URL object to handle the base URL and existing query parameters.
37
+ // `window.location.origin` ensures the support for relative paths (e.g., '/api/list').
38
+ const urlObj = new URL(pureUrl, window.location.origin);
39
+ // 3. Append business data (query parameters) to the URL if data is not empty
40
+ if (!isEmpty(data)) {
41
+ let params, dataType = getDataType(data);
42
+ // If the data is a URLSearchParams object, directly use it
43
+ if (dataType === 'URLSearchParams') {
44
+ params = data;
45
+ }
46
+ else if (dataType === 'object') {
47
+ // If the data is an object, convert it to URLSearchParams
48
+ params = new URLSearchParams(data);
49
+ }
50
+ else {
51
+ // If the data is a string, clean it up (remove leading '?' or '&')
52
+ params = new URLSearchParams(cleanQueryString(data));
53
+ }
54
+ // Append new parameters to the existing URL search parameters
55
+ params.forEach((value, key) => {
56
+ urlObj.searchParams.append(key, value);
57
+ });
58
+ }
59
+ // 4. Optionally add the cache-busting parameter if the flag is set
60
+ appendCacheBust && cacheBustKey && urlObj.searchParams.set(cacheBustKey, Date.now().toString());
61
+ // 5. Return the final URL: base URL + query parameters + original hash (if any)
62
+ return urlObj.toString() + hash;
63
+ };
64
+ export default buildUrl;
@@ -0,0 +1,86 @@
1
+ 
2
+
3
+ /**
4
+ * @since Last modified: 2026/01/20 13:56:36
5
+ * Builds a URL with query parameters, an optional cache-busting key, and preserves the hash.
6
+ * This function processes the base URL, appends query parameters, and optionally adds a cache-busting parameter.
7
+ * It also keeps the hash fragment intact if it exists in the original URL.
8
+ *
9
+ * @param {string} url - The original URL string that may or may not contain query parameters and a hash.
10
+ * @param {string | Record<string, string> | URLSearchParams} [data] - The data to be appended as query parameters.
11
+ * This can be a query string, an object, or a `URLSearchParams` object.
12
+ * @param {string} [cacheBustKey='_t'] - The cache-busting query parameter key to be appended to the URL. Default is '_t'.
13
+ * @param {boolean} [appendCacheBust=true] - A flag to indicate whether to append the cache-busting parameter. Default is true.
14
+ *
15
+ * @returns {string} The final constructed URL with the original URL, query parameters, and hash (if any).
16
+ *
17
+ * @example
18
+ * buildUrl({
19
+ * url: '/api/data',
20
+ * data: { key: 'value' },
21
+ * cacheBustKey: '_cache',
22
+ * appendCacheBust: true
23
+ * });
24
+ * // Returns: '/api/data?key=value&_cache=1638311234567'
25
+ */
26
+
27
+ import cleanQueryString from "./cleanQueryString";
28
+ import getDataType from "./getDataType";
29
+ import isEmpty from "./isEmpty";
30
+
31
+ const buildUrl = ({
32
+ url,
33
+ data,
34
+ cacheBustKey = '_t',
35
+ appendCacheBust = true
36
+ }: {
37
+ url: string;
38
+ data?: string | Record<string, string> | URLSearchParams;
39
+ cacheBustKey?: string;
40
+ appendCacheBust?: boolean;
41
+ }): string => {
42
+ // 1. Extract and remove the hash (e.g., /page#section -> hash="#section")
43
+ const hashIndex = url.indexOf('#');
44
+ let hash = '',
45
+ pureUrl = url;
46
+
47
+ // If a hash exists, separate it from the base URL
48
+ if (hashIndex !== -1) {
49
+ hash = url.slice(hashIndex);
50
+ pureUrl = url.slice(0, hashIndex);
51
+ }
52
+
53
+ // 2. Use the URL object to handle the base URL and existing query parameters.
54
+ // `window.location.origin` ensures the support for relative paths (e.g., '/api/list').
55
+ const urlObj = new URL(pureUrl, window.location.origin);
56
+
57
+ // 3. Append business data (query parameters) to the URL if data is not empty
58
+ if (!isEmpty(data)) {
59
+ let params: URLSearchParams,
60
+ dataType = getDataType(data);
61
+
62
+ // If the data is a URLSearchParams object, directly use it
63
+ if (dataType === 'URLSearchParams') {
64
+ params = data as URLSearchParams;
65
+ } else if (dataType === 'object') {
66
+ // If the data is an object, convert it to URLSearchParams
67
+ params = new URLSearchParams(data);
68
+ } else {
69
+ // If the data is a string, clean it up (remove leading '?' or '&')
70
+ params = new URLSearchParams(cleanQueryString(data as string));
71
+ }
72
+
73
+ // Append new parameters to the existing URL search parameters
74
+ params.forEach((value, key) => {
75
+ urlObj.searchParams.append(key, value);
76
+ });
77
+ }
78
+
79
+ // 4. Optionally add the cache-busting parameter if the flag is set
80
+ appendCacheBust && cacheBustKey && urlObj.searchParams.set(cacheBustKey, Date.now().toString());
81
+
82
+ // 5. Return the final URL: base URL + query parameters + original hash (if any)
83
+ return urlObj.toString() + hash;
84
+ };
85
+
86
+ export default buildUrl;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @since Last modified: 2026/01/20 11:52:35
3
+ * Capitalizes the first letter of the given string.
4
+ *
5
+ * This function takes a string as input and returns a new string with the first letter
6
+ * capitalized, while leaving the rest of the string unchanged. If the input string is
7
+ * empty or undefined, it returns the input string as is.
8
+ *
9
+ * @param str - The string whose first letter will be capitalized.
10
+ * @returns A new string with the first letter capitalized, or the input string if it's empty.
11
+ */
12
+ const capitalize = (str) => {
13
+ // Check if the input string is empty or undefined
14
+ if (!str)
15
+ return str;
16
+ // Capitalize the first letter and return the new string
17
+ return str.charAt(0).toUpperCase() + str.slice(1);
18
+ };
19
+ export default capitalize;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @since Last modified: 2026/01/20 11:52:35
3
+ * Capitalizes the first letter of the given string.
4
+ *
5
+ * This function takes a string as input and returns a new string with the first letter
6
+ * capitalized, while leaving the rest of the string unchanged. If the input string is
7
+ * empty or undefined, it returns the input string as is.
8
+ *
9
+ * @param str - The string whose first letter will be capitalized.
10
+ * @returns A new string with the first letter capitalized, or the input string if it's empty.
11
+ */
12
+ const capitalize = (str: string): string => {
13
+ // Check if the input string is empty or undefined
14
+ if (!str) return str;
15
+
16
+ // Capitalize the first letter and return the new string
17
+ return str.charAt(0).toUpperCase() + str.slice(1);
18
+ }
19
+
20
+ export default capitalize;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @since Last modified: 2026/01/20 13:55:13
3
+ * Cleans a query string by removing the leading '?' or '&' character if it exists.
4
+ * This ensures that the string is in a valid format for use in URLSearchParams.
5
+ *
6
+ * @param {string} data - The query string to clean.
7
+ * @returns {string} The cleaned query string without leading '?' or '&'.
8
+ *
9
+ * @example
10
+ * cleanQueryString('?key=value&name=John'); // Returns 'key=value&name=John'
11
+ * cleanQueryString('&key=value&name=John'); // Returns 'key=value&name=John'
12
+ * cleanQueryString('key=value&name=John'); // Returns 'key=value&name=John'
13
+ */
14
+ const cleanQueryString = (data) => {
15
+ return typeof data === 'string' && (data.startsWith('?') || data.startsWith('&'))
16
+ ? data.slice(1) // Remove the leading '?' or '&'
17
+ : data; // Return the string as-is if no leading character is present
18
+ };
19
+ export default cleanQueryString;