@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/dist/utils.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
 
2
2
  /*!
3
- * @since Last modified: 2026-1-16 15:18:30
3
+ * @since Last modified: 2026-2-5 17:4:41
4
4
  * @name Utils for web front-end.
5
- * @version 0.0.38
5
+ * @version 0.0.40
6
6
  * @author AXUI development team <3217728223@qq.com>
7
7
  * @description This is a set of general-purpose JavaScript utility functions developed by the AXUI team. All functions are pure and do not involve CSS or other third-party libraries. They are suitable for any web front-end environment.
8
8
  * @see {@link https://www.axui.cn|Official website}
@@ -947,30 +947,31 @@
947
947
  let type = getDataType(data), flag;
948
948
  if (!data) {
949
949
  //0,'',false,undefined,null
950
- flag = true;
950
+ return true;
951
951
  }
952
- else {
953
- //function(){}|()=>{}
954
- //[null]|[undefined]|['']|[""]
955
- //[]|{}
956
- //Symbol()|Symbol.for()
957
- //Set,Map
958
- //Date/Regex
959
- flag = (type === 'Object') ? (Object.keys(data).length === 0) :
960
- (type === 'Array') ? data.join('') === '' :
961
- (type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
962
- (type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
963
- (type === 'Set' || type === 'Map') ? data.size === 0 :
964
- type === 'Date' ? isNaN(data.getTime()) :
965
- type === 'RegExp' ? data.source === '' :
966
- type === 'ArrayBuffer' ? data.byteLength === 0 :
967
- (type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
968
- ('length' in data && typeof data.length === 'number') ? data.length === 0 :
969
- ('size' in data && typeof data.size === 'number') ? data.size === 0 :
970
- (type === 'Error' || data instanceof Error) ? data.message === '' :
971
- (type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
972
- false;
952
+ if (['String', 'Number', 'Boolean'].includes(type)) {
953
+ return false;
973
954
  }
955
+ //function(){}|()=>{}
956
+ //[null]|[undefined]|['']|[""]
957
+ //[]|{}
958
+ //Symbol()|Symbol.for()
959
+ //Set,Map
960
+ //Date/Regex
961
+ flag = (type === 'Object') ? (Object.keys(data).length === 0) :
962
+ (type === 'Array') ? data.join('') === '' :
963
+ (type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
964
+ (type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
965
+ (type === 'Set' || type === 'Map') ? data.size === 0 :
966
+ type === 'Date' ? isNaN(data.getTime()) :
967
+ type === 'RegExp' ? data.source === '' :
968
+ type === 'ArrayBuffer' ? data.byteLength === 0 :
969
+ (type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
970
+ ('length' in data && typeof data.length === 'number') ? data.length === 0 :
971
+ ('size' in data && typeof data.size === 'number') ? data.size === 0 :
972
+ (type === 'Error' || data instanceof Error) ? data.message === '' :
973
+ (type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
974
+ false;
974
975
  return flag;
975
976
  };
976
977
 
@@ -1344,6 +1345,549 @@
1344
1345
  return textArea.value; // Get the decoded string from the text area
1345
1346
  };
1346
1347
 
1348
+ const getBodyHTML = (htmlText, selector) => {
1349
+ // Return early if the input is not a valid string or doesn't look like HTML
1350
+ if (!htmlText || typeof htmlText !== 'string') {
1351
+ return '';
1352
+ }
1353
+ try {
1354
+
1355
+ const parser = new DOMParser(),
1356
+
1357
+ doc = parser.parseFromString(htmlText, 'text/html'),
1358
+
1359
+ bodyContent = doc.body.innerHTML;
1360
+ if (selector) {
1361
+ // Normalize hash: ensure it's a valid ID selector
1362
+ const targetEl = doc.querySelector(selector);
1363
+ if (targetEl) {
1364
+ return targetEl.innerHTML;
1365
+ }
1366
+ // If hash is provided but element not found, we fallback to body or warn
1367
+ console.warn(`Element with selector "${selector}" not found in the HTML.`);
1368
+ }
1369
+ return bodyContent ? bodyContent.trim() : htmlText;
1370
+ }
1371
+ catch (error) {
1372
+
1373
+ console.error("Failed to parse HTML content using DOMParser:", error);
1374
+ return htmlText;
1375
+ }
1376
+ };
1377
+
1378
+ const getUrlHash = (url) => {
1379
+ // Return empty if input is null, undefined, or not a string
1380
+ if (!url || typeof url !== 'string') {
1381
+ return '';
1382
+ }
1383
+ try {
1384
+
1385
+ const baseUrl = window?.location?.origin || 'https://www.axui.cn', urlObj = new URL(url, baseUrl);
1386
+ return urlObj.hash;
1387
+ }
1388
+ catch (error) {
1389
+
1390
+ return '';
1391
+ }
1392
+ };
1393
+
1394
+ const cleanQueryString = (data) => {
1395
+ return typeof data === 'string' && (data.startsWith('?') || data.startsWith('&'))
1396
+ ? data.slice(1) // Remove the leading '?' or '&'
1397
+ : data; // Return the string as-is if no leading character is present
1398
+ };
1399
+
1400
+ const buildUrl = ({ url, data, cacheBustKey = '_t', appendCacheBust = true }) => {
1401
+ // 1. Extract and remove the hash (e.g., /page#section -> hash="#section")
1402
+ const hashIndex = url.indexOf('#');
1403
+ let hash = '', pureUrl = url;
1404
+ // If a hash exists, separate it from the base URL
1405
+ if (hashIndex !== -1) {
1406
+ hash = url.slice(hashIndex);
1407
+ pureUrl = url.slice(0, hashIndex);
1408
+ }
1409
+ // 2. Use the URL object to handle the base URL and existing query parameters.
1410
+ // `window.location.origin` ensures the support for relative paths (e.g., '/api/list').
1411
+ const urlObj = new URL(pureUrl, window.location.origin);
1412
+ // 3. Append business data (query parameters) to the URL if data is not empty
1413
+ if (!isEmpty(data)) {
1414
+ let params, dataType = getDataType(data);
1415
+ // If the data is a URLSearchParams object, directly use it
1416
+ if (dataType === 'URLSearchParams') {
1417
+ params = data;
1418
+ }
1419
+ else if (dataType === 'object') {
1420
+ // If the data is an object, convert it to URLSearchParams
1421
+ params = new URLSearchParams(data);
1422
+ }
1423
+ else {
1424
+ // If the data is a string, clean it up (remove leading '?' or '&')
1425
+ params = new URLSearchParams(cleanQueryString(data));
1426
+ }
1427
+ // Append new parameters to the existing URL search parameters
1428
+ params.forEach((value, key) => {
1429
+ urlObj.searchParams.append(key, value);
1430
+ });
1431
+ }
1432
+ // 4. Optionally add the cache-busting parameter if the flag is set
1433
+ appendCacheBust && cacheBustKey && urlObj.searchParams.set(cacheBustKey, Date.now().toString());
1434
+ // 5. Return the final URL: base URL + query parameters + original hash (if any)
1435
+ return urlObj.toString() + hash;
1436
+ };
1437
+
1438
+ const capitalize = (str) => {
1439
+ // Check if the input string is empty or undefined
1440
+ if (!str)
1441
+ return str;
1442
+ // Capitalize the first letter and return the new string
1443
+ return str.charAt(0).toUpperCase() + str.slice(1);
1444
+ };
1445
+
1446
+ const ajax = (options) => {
1447
+ // Validation
1448
+ if (isEmpty(options)) {
1449
+ return Promise.reject(new Error('Options are required'));
1450
+ }
1451
+ if (!options.url || typeof options.url !== 'string') {
1452
+ return Promise.reject(new Error('URL is required and must be a string'));
1453
+ }
1454
+ // Default configuration
1455
+ const config = {
1456
+ url: '',
1457
+ method: 'POST',
1458
+ async: true,
1459
+ selector: '',
1460
+ data: null,
1461
+ timeout: 3600000,
1462
+ headers: {},
1463
+ responseType: '',
1464
+ catchError: false,
1465
+ signal: null,
1466
+ xhrFields: {},
1467
+ cacheBustKey: '_t',
1468
+ precision: 2,
1469
+ //
1470
+ onAbort: null,
1471
+ onTimeout: null,
1472
+ //
1473
+ onBeforeSend: null,
1474
+ //
1475
+ onCreated: null,
1476
+ onOpened: null,
1477
+ onHeadersReceived: null,
1478
+ onLoading: null,
1479
+ //
1480
+ onSuccess: null,
1481
+ onFailure: null,
1482
+ onInformation: null,
1483
+ onRedirection: null,
1484
+ onClientError: null,
1485
+ onServerError: null,
1486
+ onUnknownError: null,
1487
+ onError: null,
1488
+ onFinish: null,
1489
+ //
1490
+ onDownload: null,
1491
+ onUpload: null,
1492
+ onComplete: null,
1493
+ };
1494
+ //合并参数
1495
+ Object.assign(config, options);
1496
+ //
1497
+ const method = config.method.toUpperCase() || 'POST', methodsWithoutBody = ['GET', 'HEAD', 'TRACE'];
1498
+ //创建XMLHttpRequest
1499
+ let xhr = new XMLHttpRequest(),
1500
+ //设置发送数据和预设请求头
1501
+ requestData = null, headerContentType = config?.headers?.['Content-Type'] || config?.headers?.['content-type'], removeHeader = () => {
1502
+ if (headerContentType) {
1503
+ delete config.headers['Content-Type'];
1504
+ delete config.headers['content-type'];
1505
+ }
1506
+ };
1507
+ if (!isEmpty(config.data)) {
1508
+ let dataType = getDataType(config.data);
1509
+ if (dataType === 'FormData') {
1510
+ //如果是new FormData格式,直接相等
1511
+ requestData = config.data;
1512
+ // 不需要手动设置Content-Type,浏览器会自动设置
1513
+ //config.contType = 'multipart/form-data';
1514
+ removeHeader();
1515
+ }
1516
+ else if (dataType === 'Object') {
1517
+ //如果是对象格式{name:'',age:''}
1518
+ //并且此时已经设置了contType
1519
+ if (!headerContentType) {
1520
+ //如果未设置则默认设为如下contType
1521
+ //Content-Type=application/x-www-form-urlencoded
1522
+
1523
+ requestData = new URLSearchParams(config.data).toString();
1524
+ //URLSearchParams.toString => `a=1&b=3`
1525
+ //非get、head方法修正content-type
1526
+ if (!methodsWithoutBody.includes(method)) {
1527
+ config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
1528
+ }
1529
+ }
1530
+ else if (headerContentType?.includes('application/json')) {
1531
+ //Content-Type=application/json或contentType=application/json
1532
+ requestData = JSON.stringify(config.data);
1533
+ }
1534
+ else {
1535
+ requestData = config.data;
1536
+ }
1537
+ }
1538
+ else if (dataType === 'String') {
1539
+ //未设置或,已经设置了Content-Type=application/x-www-form-urlencoded
1540
+ if (!headerContentType || headerContentType.includes('urlencoded')) {
1541
+ //如果是name=''&age=''字符串
1542
+ //?name=''&age=''或&name=''&age=''统一去掉第一个&/?
1543
+ requestData = cleanQueryString(config.data.trim());
1544
+ //非get、head方法修正content-type
1545
+ if (!methodsWithoutBody.includes(method) && !headerContentType) {
1546
+ config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
1547
+ }
1548
+ }
1549
+ else {
1550
+ requestData = config.data;
1551
+ }
1552
+ }
1553
+ else {
1554
+ requestData = config.data;
1555
+ }
1556
+ }
1557
+ //设置超时时间
1558
+ xhr.timeout = config.timeout;
1559
+ // 响应类型
1560
+ if (config.responseType) {
1561
+ xhr.responseType = config.responseType;
1562
+ }
1563
+ //返回promise
1564
+ const result = new Promise((resolve, reject) => {
1565
+ //超时监听
1566
+ const timeoutHandler = () => {
1567
+ cleanup();
1568
+ let resp = { ...context, status: xhr.status, content: xhr.response, type: 'timeout' };
1569
+ //回调,status和content在此确认
1570
+ config?.onTimeout?.(resp);
1571
+ //reject只能接受一个参数
1572
+ config.catchError ? reject(resp) : resolve(resp);
1573
+ //超时也是不能获得数据的行为,定义为failure
1574
+ config?.onFailure?.(resp);
1575
+ //timeout会经过onreadystatechange,但是被及时的return了,所以这里多加一行
1576
+ config?.onFinish?.(resp);
1577
+ },
1578
+ //报错监听
1579
+ errorHandler = (resp) => {
1580
+ //这几个错误来自xhr.onreadystatechange
1581
+ if (resp.type === 'client-error') {
1582
+ config?.onClientError?.({ ...context });
1583
+ }
1584
+ else if (resp.type === 'server-error') {
1585
+ config?.onServerError?.({ ...context });
1586
+ }
1587
+ else if (resp.type === 'unknown-error') {
1588
+ config?.onUnknownError?.({ ...context });
1589
+ }
1590
+ //此外还会有xhr.onerror的错误,所以需要统一使用onError监听
1591
+ config?.onError?.(resp);
1592
+ //reject只能接受一个参数
1593
+ config.catchError ? reject(resp) : resolve(resp);
1594
+ },
1595
+ //取消监听
1596
+ abortHandler = () => {
1597
+ cleanup();
1598
+ const resp = { ...context, status: xhr.status, type: 'abort' };
1599
+ config.catchError ? reject(resp) : resolve(resp);
1600
+ //回调,status和content在此确认
1601
+ config?.onAbort?.(resp);
1602
+ //abort行为不会经过onreadystatechange,这里需要多这一行以表示xhr的完成(结束)
1603
+ config?.onFinish?.(resp);
1604
+ }, abortHandlerWithSignal = () => {
1605
+ //先中止请求,防止触发其他 readystate 事件
1606
+ xhr.abort();
1607
+ abortHandler();
1608
+ },
1609
+ //成功监听
1610
+ successHandler = (resp) => {
1611
+ //成功回调
1612
+ config?.onSuccess?.(resp);
1613
+ //resolve只能接受一个参数
1614
+ resolve(resp);
1615
+ },
1616
+ //统一处理abort
1617
+ cleanup = () => {
1618
+ // 如果使用了AbortSignal,则移除它的事件监听器
1619
+ config.signal && config.signal.removeEventListener('abort', abortHandlerWithSignal);
1620
+ // 移除各类事件监听器
1621
+ config.onError && xhr.removeEventListener('error', errorHandler);
1622
+ config.onTimeout && xhr.removeEventListener('timeout', timeoutHandler);
1623
+ // 解绑上传/下载进度事件
1624
+ config.onUpload && xhr.upload.removeEventListener('progress', uploadProgressHandler);
1625
+ config.onDownload && xhr.removeEventListener('progress', downloadProgressHandler);
1626
+ //销毁
1627
+ xhr.onreadystatechange = null;
1628
+ },
1629
+ // Context object to track state
1630
+ context = {
1631
+ //原始xhr
1632
+ xhr,
1633
+ //发送的数据
1634
+ data: requestData,
1635
+ //可取消的函数
1636
+ abort: abortHandler,
1637
+ //xhr.status
1638
+ status: '',
1639
+ //响应的内容
1640
+ content: null,
1641
+ //0~4阶段编号
1642
+ stage: 0,
1643
+ //阶段名称
1644
+ type: 'unset',
1645
+ //上传和下载进度
1646
+ progress: {}
1647
+ }, getProgressValues = (ratio) => {
1648
+ let text = (ratio * 100).toFixed(config.precision);
1649
+ return { percent: parseFloat(text), text };
1650
+ },
1651
+ //定义进度函数
1652
+ progressHandler = (name, data, callback) => {
1653
+ if (data.lengthComputable) {
1654
+ const resp = { ...context, status: xhr.status }, ratio = data.loaded / data.total, { percent, text } = getProgressValues(ratio);
1655
+ resp.progress = {
1656
+ name,
1657
+ loaded: data.loaded,
1658
+ total: data.total,
1659
+ timestamp: (new Date(data.timeStamp)).getTime(),
1660
+ ratio,
1661
+ percent,
1662
+ text,
1663
+ };
1664
+ callback?.(resp);
1665
+ if (ratio >= 1) {
1666
+ Object.assign(resp.progress, getProgressValues(1));
1667
+ config?.onComplete?.(resp);
1668
+ }
1669
+ }
1670
+ }, uploadProgressHandler = (data) => {
1671
+ progressHandler('upload', data, (resp) => config.onUpload(resp));
1672
+ }, downloadProgressHandler = (data) => {
1673
+ progressHandler('download', data, (resp) => config.onDownload(resp));
1674
+ };
1675
+ //使用AbortSignal
1676
+ if (config.signal) {
1677
+ if (config.signal.aborted)
1678
+ return abortHandlerWithSignal();
1679
+ config.signal.addEventListener('abort', abortHandlerWithSignal);
1680
+ }
1681
+ //监听上传进度
1682
+ config.onUpload && xhr.upload.addEventListener('progress', uploadProgressHandler);
1683
+ //监听下载进度
1684
+ config.onDownload && xhr.addEventListener('progress', downloadProgressHandler);
1685
+ // 事件监听器
1686
+ config.onError && xhr.addEventListener('error', errorHandler);
1687
+ config.onTimeout && xhr.addEventListener('timeout', timeoutHandler);
1688
+ config.onAbort && xhr.addEventListener('abort', abortHandler);
1689
+ // 手动触发 Created 状态
1690
+ config.onCreated?.({ ...context, type: 'created' });
1691
+ //状态判断
1692
+ xhr.onreadystatechange = function () {
1693
+ context.stage = xhr.readyState;
1694
+ context.status = xhr.status;
1695
+ const statusMap = { 1: 'opened', 2: 'headersReceived', 3: 'loading' };
1696
+ //0=created放在外侧确保能触发,如果放在.onreadystatechange可能触发不了
1697
+ if (xhr.readyState < 4) {
1698
+ if (!xhr.readyState)
1699
+ return;
1700
+ context.type = statusMap[xhr.readyState];
1701
+ config[`on${capitalize(context.type)}`]?.({ ...context });
1702
+ return;
1703
+ }
1704
+ //tiemeout事件也会执行这里,此时需要让它触发onTimeout事件
1705
+ //abort和timeout行为的status是0
1706
+ //不过abort行为不会执行到这里
1707
+ if (xhr.status === 0 && context.type !== 'abort') {
1708
+ return;
1709
+ }
1710
+ //已经请求成功,不会有timeout事件,也不需要abort了,所以移除abort事件
1711
+ cleanup();
1712
+ //根据状态码判断响应结果
1713
+ const isInformation = xhr.status >= 100 && xhr.status < 200, isSuccess = (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304, isRedirection = xhr.status >= 300 && xhr.status < 400, isClientError = xhr.status >= 400 && xhr.status < 500, isServerError = xhr.status >= 500 && xhr.status < 600;
1714
+ //已经获得返回数据
1715
+ if (isSuccess) {
1716
+ if (!config.responseType || xhr.responseType === 'text') {
1717
+ //可能返回字符串类型的对象,wordpress的REST API
1718
+ let trim = xhr.responseText.trim(), content = '';
1719
+ if ((trim.startsWith('[') && trim.endsWith(']')) || (trim.startsWith('{') && trim.endsWith('}'))) {
1720
+ //通过判断开头字符是{或[来确定异步页面是否是JSON内容,如果是则转成JSON对象
1721
+ try {
1722
+ content = JSON.parse(trim);
1723
+ }
1724
+ catch {
1725
+ console.warn('Malformed JSON detected, falling back to text.');
1726
+ content = xhr.responseText;
1727
+ }
1728
+ }
1729
+ else if (/(<\/html>|<\/body>)/i.test(trim)) {
1730
+ //请求了一个HTML页面
1731
+ //返回文本类型DOMstring
1732
+ let urlHash = getUrlHash(config.url);
1733
+ content = getBodyHTML(trim, config.selector || urlHash);
1734
+ }
1735
+ else {
1736
+ //普通文本,不做任何处理
1737
+ content = xhr.responseText;
1738
+ }
1739
+ //content=文本字符串/json
1740
+ context.content = content;
1741
+ }
1742
+ else {
1743
+ //content=json、blob、document、arraybuffer等类型,如果知道服务器返回的XML, xhr.responseType应该为document
1744
+ context.content = xhr.response;
1745
+ }
1746
+ context.type = 'success';
1747
+ successHandler({ ...context });
1748
+ }
1749
+ else {
1750
+ //失败回调
1751
+ context.content = xhr.response;
1752
+ context.type = isInformation ? 'infomation' : isRedirection ? 'redirection' : isClientError ? 'client-error' : isServerError ? 'server-error' : 'unknown-error';
1753
+ //
1754
+ if (isInformation) {
1755
+ config?.onInformation?.({ ...context });
1756
+ }
1757
+ else if (isRedirection) {
1758
+ config?.onRedirection?.({ ...context });
1759
+ }
1760
+ else {
1761
+ errorHandler({ ...context });
1762
+ }
1763
+ //
1764
+ config?.onFailure?.({ ...context });
1765
+ }
1766
+ config?.onFinish?.({ ...context });
1767
+ };
1768
+ //发送异步请求
1769
+ let openParams = [method, config.url, config.async];
1770
+ if (methodsWithoutBody.includes(method)) {
1771
+ // 拼接url => xxx.com?a=0&b=1#hello
1772
+ const url = buildUrl({
1773
+ url: config.url,
1774
+ data: requestData,
1775
+ cacheBustKey: config.cacheBustKey,
1776
+ appendCacheBust: true,
1777
+ });
1778
+ openParams = [method, url, config.async];
1779
+ }
1780
+ //设置xhr其他字段
1781
+ for (let k in config.xhrFields) {
1782
+ config.xhrFields.hasOwnProperty(k) && (xhr[k] = config.xhrFields[k]);
1783
+ }
1784
+ //与服务器建立连接
1785
+ xhr.open(...openParams);
1786
+ //有则设置,仅跳过空内容
1787
+ for (let k in config.headers) {
1788
+ config.headers.hasOwnProperty(k) && !isEmpty(config.headers[k]) && xhr.setRequestHeader(k, config.headers[k]);
1789
+ }
1790
+ config?.onBeforeSend?.(({ ...context, status: xhr.status, type: 'beforeSend' }));
1791
+ //发送请求,get和head不需要发送数据
1792
+ xhr.send(methodsWithoutBody.includes(method) ? null : (requestData || null));
1793
+ //open和send阶段已经是异步了,无法使用try+catch捕获错误
1794
+ });
1795
+ //绑定xhr和abort
1796
+ result.xhr = xhr;
1797
+ result.abort = () => xhr.abort();
1798
+ return result;
1799
+ };
1800
+ // Static Helper Methods
1801
+ //get、head、trace是不需要发送数据的,data将被转为url参数处理
1802
+ ['post', 'put', 'delete', 'patch', 'options', 'get', 'head', 'trace'].forEach(method => {
1803
+ ajax[method] = (url, data, options = { url: '' }) => ajax({ ...options, method, url, data });
1804
+ });
1805
+ ajax.all = (requests) => Promise.all(requests.map(ajax));
1806
+
1807
+ const stringToEncodings = (name, options = {}) => {
1808
+ // Default: Supplementary Private Use Area (Plane 15 and Plane 16)
1809
+ //1,114,110 places,5000 strings => 0 collision
1810
+ const start = options.start ?? 0xF0000, end = options.end ?? 0x10FFFD, range = BigInt(end - start + 1), registry = options.registryMap,
1811
+
1812
+ formatResult = (name, codePoint, hash, collision) => {
1813
+ const hex = codePoint.toString(16).toUpperCase();
1814
+ return {
1815
+ name,
1816
+ unicode: `U+${hex}`,
1817
+ htmlDec: `&#${codePoint};`,
1818
+ htmlHex: `&#x${hex};`,
1819
+ hex,
1820
+ codePoint,
1821
+ hash,
1822
+ collision,
1823
+ };
1824
+ };
1825
+ // -----------------------------
1826
+ // 1. Compute FNV-1a 64-bit hash
1827
+ // -----------------------------
1828
+ let hash = BigInt("0xcbf29ce484222325");
1829
+ const prime = BigInt("0x100000001b3");
1830
+ for (const ch of name) {
1831
+ hash ^= BigInt(ch.codePointAt(0));
1832
+ hash *= prime;
1833
+ }
1834
+ const hashHex = hash.toString(16).toUpperCase();
1835
+ // -----------------------------
1836
+ // 2. Stateless mode (no registry)
1837
+ // -----------------------------
1838
+ if (!registry) {
1839
+ const offset = Number(hash % range), codePoint = start + offset;
1840
+ return formatResult(name, codePoint, hashHex, false);
1841
+ }
1842
+ // -----------------------------
1843
+ // 3. Registry mode (0 collision)
1844
+ // -----------------------------
1845
+ // Already assigned → return stable mapping
1846
+ if (registry.has(name)) {
1847
+ return formatResult(name, registry.get(name), hashHex, false);
1848
+ }
1849
+ // Initial candidate from hash
1850
+ let offset = Number(hash % range), codePoint = start + offset, collision = false;
1851
+ const used = new Set(registry.values());
1852
+ // Linear probing to resolve collisions
1853
+ while (used.has(codePoint)) {
1854
+ collision = true;
1855
+ offset = (offset + 1) % Number(range);
1856
+ codePoint = start + offset;
1857
+ }
1858
+ // Commit allocation
1859
+ registry.set(name, codePoint);
1860
+ return formatResult(name, codePoint, hashHex, collision);
1861
+ };
1862
+
1863
+ const unicodeToEncodings = (input) => {
1864
+ let codePoint;
1865
+ if (typeof input === "number") {
1866
+ codePoint = input;
1867
+ }
1868
+ else {
1869
+ const cleaned = input.trim()
1870
+ .replace(/^U\+/i, "")
1871
+ .replace(/^0x/i, "");
1872
+ codePoint = /^[0-9A-F]+$/i.test(cleaned)
1873
+ ? parseInt(cleaned, 16)
1874
+ : parseInt(cleaned, 10);
1875
+ }
1876
+ // Validate parsed code point
1877
+ if (!Number.isFinite(codePoint)) {
1878
+ throw new Error("Invalid Unicode input");
1879
+ }
1880
+ // Convert code point to uppercase hexadecimal representation
1881
+ const hex = codePoint.toString(16).toUpperCase();
1882
+ return {
1883
+ unicode: `U+${hex}`,
1884
+ hex,
1885
+ codePoint,
1886
+ htmlDec: `&#${codePoint};`,
1887
+ htmlHex: `&#x${hex};`,
1888
+ };
1889
+ };
1890
+
1347
1891
  const utils = {
1348
1892
  //executeStr,
1349
1893
  getDataType,
@@ -1387,6 +1931,14 @@
1387
1931
  escapeHTML,
1388
1932
  toSingleLine,
1389
1933
  renderTpl,
1934
+ getBodyHTML,
1935
+ getUrlHash,
1936
+ buildUrl,
1937
+ ajax,
1938
+ capitalize,
1939
+ cleanQueryString,
1940
+ stringToEncodings,
1941
+ unicodeToEncodings,
1390
1942
  };
1391
1943
 
1392
1944
  return utils;