@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
|
@@ -0,0 +1,20 @@
|
|
|
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: string): string => {
|
|
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
|
+
|
|
20
|
+
export default cleanQueryString;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since Last modified: 2026/01/16 14:49:39
|
|
3
|
+
* escapeCharsMaps
|
|
4
|
+
* A collection of character escape mappings for different contexts in HTML and URI encoding.
|
|
5
|
+
*
|
|
6
|
+
* This object provides a set of character replacement mappings for use in different contexts such as:
|
|
7
|
+
* - `basic`: For basic HTML encoding (useful for preventing basic HTML injection).
|
|
8
|
+
* - `attribute`: For encoding characters within HTML attributes (useful for attributes like `src`, `href`).
|
|
9
|
+
* - `content`: For encoding characters within HTML content (useful for preventing XSS).
|
|
10
|
+
* - `uri`: For encoding characters in URIs (useful in attributes like `href` or `src`).
|
|
11
|
+
* - `paranoid`: A very strict escape for all potentially dangerous characters (useful for paranoid security contexts).
|
|
12
|
+
*
|
|
13
|
+
*/
|
|
14
|
+
const escapeCharsMaps = {
|
|
15
|
+
//code或pre标签中代码高亮是使用basic
|
|
16
|
+
basic: {
|
|
17
|
+
'&': '&',
|
|
18
|
+
'<': '<',
|
|
19
|
+
'>': '>',
|
|
20
|
+
},
|
|
21
|
+
//需要用在标签属性上attribute
|
|
22
|
+
attribute: {
|
|
23
|
+
'&': '&',
|
|
24
|
+
'<': '<',
|
|
25
|
+
'>': '>',
|
|
26
|
+
'"': '"',
|
|
27
|
+
"'": ''',
|
|
28
|
+
'`': '`',
|
|
29
|
+
},
|
|
30
|
+
//html中的正文内容使用content
|
|
31
|
+
content: {
|
|
32
|
+
'&': '&',
|
|
33
|
+
'<': '<',
|
|
34
|
+
'>': '>',
|
|
35
|
+
'"': '"',
|
|
36
|
+
"'": ''',
|
|
37
|
+
'/': '/',
|
|
38
|
+
},
|
|
39
|
+
//用于url链接则使用uri
|
|
40
|
+
uri: {
|
|
41
|
+
'&': '&',
|
|
42
|
+
'<': '<',
|
|
43
|
+
'>': '>',
|
|
44
|
+
'"': '"',
|
|
45
|
+
"'": ''',
|
|
46
|
+
'(': '(',
|
|
47
|
+
')': ')',
|
|
48
|
+
'[': '[',
|
|
49
|
+
']': ']',
|
|
50
|
+
},
|
|
51
|
+
//极致转意,避免任何注入或非法代码
|
|
52
|
+
paranoid: {
|
|
53
|
+
'&': '&',
|
|
54
|
+
'<': '<',
|
|
55
|
+
'>': '>',
|
|
56
|
+
'"': '"',
|
|
57
|
+
"'": ''',
|
|
58
|
+
'`': '`',
|
|
59
|
+
'/': '/',
|
|
60
|
+
'=': '=',
|
|
61
|
+
'!': '!',
|
|
62
|
+
'#': '#',
|
|
63
|
+
'(': '(',
|
|
64
|
+
')': ')',
|
|
65
|
+
'[': '[',
|
|
66
|
+
']': ']',
|
|
67
|
+
'{': '{',
|
|
68
|
+
'}': '}',
|
|
69
|
+
':': ':',
|
|
70
|
+
';': ';',
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
export default escapeCharsMaps;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since Last modified: 2026/01/16 14:49:39
|
|
3
|
+
* escapeCharsMaps
|
|
4
|
+
* A collection of character escape mappings for different contexts in HTML and URI encoding.
|
|
5
|
+
*
|
|
6
|
+
* This object provides a set of character replacement mappings for use in different contexts such as:
|
|
7
|
+
* - `basic`: For basic HTML encoding (useful for preventing basic HTML injection).
|
|
8
|
+
* - `attribute`: For encoding characters within HTML attributes (useful for attributes like `src`, `href`).
|
|
9
|
+
* - `content`: For encoding characters within HTML content (useful for preventing XSS).
|
|
10
|
+
* - `uri`: For encoding characters in URIs (useful in attributes like `href` or `src`).
|
|
11
|
+
* - `paranoid`: A very strict escape for all potentially dangerous characters (useful for paranoid security contexts).
|
|
12
|
+
*
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const escapeCharsMaps : Record<string, Record<string, string>> = {
|
|
16
|
+
//code或pre标签中代码高亮是使用basic
|
|
17
|
+
basic: {
|
|
18
|
+
'&': '&',
|
|
19
|
+
'<': '<',
|
|
20
|
+
'>': '>',
|
|
21
|
+
},
|
|
22
|
+
//需要用在标签属性上attribute
|
|
23
|
+
attribute: {
|
|
24
|
+
'&': '&',
|
|
25
|
+
'<': '<',
|
|
26
|
+
'>': '>',
|
|
27
|
+
'"': '"',
|
|
28
|
+
"'": ''',
|
|
29
|
+
'`': '`',
|
|
30
|
+
},
|
|
31
|
+
//html中的正文内容使用content
|
|
32
|
+
content: {
|
|
33
|
+
'&': '&',
|
|
34
|
+
'<': '<',
|
|
35
|
+
'>': '>',
|
|
36
|
+
'"': '"',
|
|
37
|
+
"'": ''',
|
|
38
|
+
'/': '/',
|
|
39
|
+
},
|
|
40
|
+
//用于url链接则使用uri
|
|
41
|
+
uri: {
|
|
42
|
+
'&': '&',
|
|
43
|
+
'<': '<',
|
|
44
|
+
'>': '>',
|
|
45
|
+
'"': '"',
|
|
46
|
+
"'": ''',
|
|
47
|
+
'(': '(',
|
|
48
|
+
')': ')',
|
|
49
|
+
'[': '[',
|
|
50
|
+
']': ']',
|
|
51
|
+
},
|
|
52
|
+
//极致转意,避免任何注入或非法代码
|
|
53
|
+
paranoid: {
|
|
54
|
+
'&': '&',
|
|
55
|
+
'<': '<',
|
|
56
|
+
'>': '>',
|
|
57
|
+
'"': '"',
|
|
58
|
+
"'": ''',
|
|
59
|
+
'`': '`',
|
|
60
|
+
'/': '/',
|
|
61
|
+
'=': '=',
|
|
62
|
+
'!': '!',
|
|
63
|
+
'#': '#',
|
|
64
|
+
'(': '(',
|
|
65
|
+
')': ')',
|
|
66
|
+
'[': '[',
|
|
67
|
+
']': ']',
|
|
68
|
+
'{': '{',
|
|
69
|
+
'}': '}',
|
|
70
|
+
':': ':',
|
|
71
|
+
';': ';',
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
export default escapeCharsMaps;
|
package/src/escapeHTML.js
CHANGED
|
@@ -1,29 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
|
+
* @since Last modified: 2026/01/16 14:47:26
|
|
2
3
|
* @function escapeHTML
|
|
3
|
-
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* @returns
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* escapeHTML(
|
|
11
|
-
*
|
|
4
|
+
* Escapes special characters in a string to prevent Cross-Site Scripting (XSS) attacks.
|
|
5
|
+
* * @param str - The raw string to be escaped.
|
|
6
|
+
* @param context - The context where the escaped string will be placed.
|
|
7
|
+
* Defaults to 'basic'.
|
|
8
|
+
* @returns The escaped string safe for the specified HTML context.
|
|
9
|
+
* * @example
|
|
10
|
+
* // Basic usage (HTML Body)
|
|
11
|
+
* escapeHTML('<script>', 'basic'); // "<script>"
|
|
12
|
+
* * @example
|
|
13
|
+
* // Attribute usage (e.g., <input value="...">)
|
|
14
|
+
* escapeHTML('value" onmouseover="alert(1)', 'attribute');
|
|
12
15
|
*/
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
'
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
'/': '/'
|
|
24
|
-
};
|
|
25
|
-
// Replace each special character in the input string with its corresponding HTML entity
|
|
26
|
-
return str.replace(/[&<>"'`=\/]/g, (match) => {
|
|
27
|
-
return escapes[match];
|
|
28
|
-
});
|
|
16
|
+
import escapeCharsMaps from "./escapeCharsMaps";
|
|
17
|
+
import escapeRegexMaps from "./escapeRegexMaps";
|
|
18
|
+
const escapeHTML = (str, strength = 'attribute') => {
|
|
19
|
+
// Return empty string if input is null, undefined, or not a string
|
|
20
|
+
if (typeof str !== 'string')
|
|
21
|
+
return '';
|
|
22
|
+
const map = escapeCharsMaps[strength], regex = escapeRegexMaps[strength];
|
|
23
|
+
// Use String.prototype.replace with a global regex.
|
|
24
|
+
// The callback function retrieves the replacement from the map using the matched character as key.
|
|
25
|
+
return str.replace(regex, (match) => map[match]);
|
|
29
26
|
};
|
|
27
|
+
export default escapeHTML;
|
package/src/escapeHTML.ts
CHANGED
|
@@ -1,30 +1,34 @@
|
|
|
1
1
|
/**
|
|
2
|
+
* @since Last modified: 2026/01/16 14:47:26
|
|
2
3
|
* @function escapeHTML
|
|
3
|
-
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* @returns
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* escapeHTML(
|
|
11
|
-
*
|
|
4
|
+
* Escapes special characters in a string to prevent Cross-Site Scripting (XSS) attacks.
|
|
5
|
+
* * @param str - The raw string to be escaped.
|
|
6
|
+
* @param context - The context where the escaped string will be placed.
|
|
7
|
+
* Defaults to 'basic'.
|
|
8
|
+
* @returns The escaped string safe for the specified HTML context.
|
|
9
|
+
* * @example
|
|
10
|
+
* // Basic usage (HTML Body)
|
|
11
|
+
* escapeHTML('<script>', 'basic'); // "<script>"
|
|
12
|
+
* * @example
|
|
13
|
+
* // Attribute usage (e.g., <input value="...">)
|
|
14
|
+
* escapeHTML('value" onmouseover="alert(1)', 'attribute');
|
|
12
15
|
*/
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const escapes: { [key: string]: string } = {
|
|
16
|
-
'&': '&',
|
|
17
|
-
'<': '<',
|
|
18
|
-
'>': '>',
|
|
19
|
-
'"': '"',
|
|
20
|
-
"'": ''',
|
|
21
|
-
'`': '`',
|
|
22
|
-
'=': '=',
|
|
23
|
-
'/': '/'
|
|
24
|
-
};
|
|
16
|
+
import escapeCharsMaps from "./escapeCharsMaps";
|
|
17
|
+
import escapeRegexMaps from "./escapeRegexMaps";
|
|
25
18
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
19
|
+
export type EscapeStrength = 'basic' | 'attribute' | 'content' | 'uri' | 'paranoid';
|
|
20
|
+
|
|
21
|
+
const escapeHTML = (
|
|
22
|
+
str: string,
|
|
23
|
+
strength: EscapeStrength = 'attribute'
|
|
24
|
+
): string => {
|
|
25
|
+
// Return empty string if input is null, undefined, or not a string
|
|
26
|
+
if (typeof str !== 'string') return '';
|
|
27
|
+
|
|
28
|
+
const map = escapeCharsMaps[strength],
|
|
29
|
+
regex = escapeRegexMaps[strength];
|
|
30
|
+
// Use String.prototype.replace with a global regex.
|
|
31
|
+
// The callback function retrieves the replacement from the map using the matched character as key.
|
|
32
|
+
return str.replace(regex, (match) => map[match]);
|
|
30
33
|
};
|
|
34
|
+
export default escapeHTML;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since Last modified: 2026/01/16 11:07:17
|
|
3
|
+
* @function escapeRegexMaps
|
|
4
|
+
* Generates a set of regular expressions that match the characters to be escaped
|
|
5
|
+
* in different contexts such as HTML content, attributes, and URIs.
|
|
6
|
+
*
|
|
7
|
+
* This function uses the `escapeCharsMaps` object to create regular expressions for
|
|
8
|
+
* matching characters that need to be escaped based on the context.
|
|
9
|
+
*
|
|
10
|
+
*/
|
|
11
|
+
import escapeCharsMaps from "./escapeCharsMaps";
|
|
12
|
+
const escapeRegexMaps = (Object.keys(escapeCharsMaps)).reduce((acc, key) => {
|
|
13
|
+
const chars = Object.keys(escapeCharsMaps[key]);
|
|
14
|
+
// Escape special regex characters to avoid issues in the regex. [ => \[
|
|
15
|
+
const escapedChars = chars.map((c) => c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
16
|
+
acc[key] = new RegExp(`[${escapedChars.join('')}]`, 'g');
|
|
17
|
+
return acc;
|
|
18
|
+
}, {});
|
|
19
|
+
export default escapeRegexMaps;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @since Last modified: 2026/01/16 11:07:17
|
|
5
|
+
* @function escapeRegexMaps
|
|
6
|
+
* Generates a set of regular expressions that match the characters to be escaped
|
|
7
|
+
* in different contexts such as HTML content, attributes, and URIs.
|
|
8
|
+
*
|
|
9
|
+
* This function uses the `escapeCharsMaps` object to create regular expressions for
|
|
10
|
+
* matching characters that need to be escaped based on the context.
|
|
11
|
+
*
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import escapeCharsMaps from "./escapeCharsMaps";
|
|
15
|
+
|
|
16
|
+
const escapeRegexMaps: Record<string, RegExp> = (Object.keys(escapeCharsMaps)).reduce(
|
|
17
|
+
(acc, key) => {
|
|
18
|
+
const chars = Object.keys(escapeCharsMaps[key]);
|
|
19
|
+
// Escape special regex characters to avoid issues in the regex. [ => \[
|
|
20
|
+
const escapedChars = chars.map((c) => c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
21
|
+
acc[key] = new RegExp(`[${escapedChars.join('')}]`, 'g');
|
|
22
|
+
return acc;
|
|
23
|
+
},
|
|
24
|
+
{} as Record<string, RegExp>
|
|
25
|
+
);
|
|
26
|
+
export default escapeRegexMaps;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since Last modified: 2026/01/19 15:58:30
|
|
3
|
+
* Extract the inner content of the <body> tag from an HTML string.
|
|
4
|
+
* This method uses the browser's native DOMParser for reliable parsing,
|
|
5
|
+
* which is safer and more robust than using Regular Expressions.
|
|
6
|
+
* * @param {string} htmlText - The raw HTML string received from an asynchronous request.
|
|
7
|
+
* @param {string} [selector] - Optional ID or selector (e.g., '.hello' or '#hello').
|
|
8
|
+
* @returns {string} - The trimmed innerHTML of the body, or the original text if parsing fails.
|
|
9
|
+
*/
|
|
10
|
+
const getBodyHTML = (htmlText, selector) => {
|
|
11
|
+
// Return early if the input is not a valid string or doesn't look like HTML
|
|
12
|
+
if (!htmlText || typeof htmlText !== 'string') {
|
|
13
|
+
return '';
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
/**
|
|
17
|
+
* 1. Initialize DOMParser
|
|
18
|
+
* DOMParser can parse XML or HTML source code from a string into a DOM Document.
|
|
19
|
+
*/
|
|
20
|
+
const parser = new DOMParser(),
|
|
21
|
+
/**
|
|
22
|
+
* 2. Parse the string into a Document object
|
|
23
|
+
* The 'text/html' mime type tells the parser to use the HTML lifting/error-correction algorithms.
|
|
24
|
+
*/
|
|
25
|
+
doc = parser.parseFromString(htmlText, 'text/html'),
|
|
26
|
+
/**
|
|
27
|
+
* 3. Extract body content
|
|
28
|
+
* Accessing doc.body automatically skips <!DOCTYPE>, <html>, and <head> sections.
|
|
29
|
+
* We use trim() to remove leading/trailing whitespace common in server responses.
|
|
30
|
+
*/
|
|
31
|
+
bodyContent = doc.body.innerHTML;
|
|
32
|
+
if (selector) {
|
|
33
|
+
// Normalize hash: ensure it's a valid ID selector
|
|
34
|
+
const targetEl = doc.querySelector(selector);
|
|
35
|
+
if (targetEl) {
|
|
36
|
+
return targetEl.innerHTML;
|
|
37
|
+
}
|
|
38
|
+
// If hash is provided but element not found, we fallback to body or warn
|
|
39
|
+
console.warn(`Element with selector "${selector}" not found in the HTML.`);
|
|
40
|
+
}
|
|
41
|
+
return bodyContent ? bodyContent.trim() : htmlText;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
/**
|
|
45
|
+
* Fallback mechanism
|
|
46
|
+
* If the environment (like Node.js without JSDOM) doesn't support DOMParser,
|
|
47
|
+
* or the string is malformed, we log the error and return the raw text.
|
|
48
|
+
*/
|
|
49
|
+
console.error("Failed to parse HTML content using DOMParser:", error);
|
|
50
|
+
return htmlText;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
export default getBodyHTML;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since Last modified: 2026/01/19 15:58:30
|
|
3
|
+
* Extract the inner content of the <body> tag from an HTML string.
|
|
4
|
+
* This method uses the browser's native DOMParser for reliable parsing,
|
|
5
|
+
* which is safer and more robust than using Regular Expressions.
|
|
6
|
+
* * @param {string} htmlText - The raw HTML string received from an asynchronous request.
|
|
7
|
+
* @param {string} [selector] - Optional ID or selector (e.g., '.hello' or '#hello').
|
|
8
|
+
* @returns {string} - The trimmed innerHTML of the body, or the original text if parsing fails.
|
|
9
|
+
*/
|
|
10
|
+
const getBodyHTML = (htmlText: string, selector?: string): string => {
|
|
11
|
+
// Return early if the input is not a valid string or doesn't look like HTML
|
|
12
|
+
if (!htmlText || typeof htmlText !== 'string') {
|
|
13
|
+
return '';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
/**
|
|
18
|
+
* 1. Initialize DOMParser
|
|
19
|
+
* DOMParser can parse XML or HTML source code from a string into a DOM Document.
|
|
20
|
+
*/
|
|
21
|
+
const parser: DOMParser = new DOMParser(),
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 2. Parse the string into a Document object
|
|
25
|
+
* The 'text/html' mime type tells the parser to use the HTML lifting/error-correction algorithms.
|
|
26
|
+
*/
|
|
27
|
+
doc: Document = parser.parseFromString(htmlText, 'text/html'),
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 3. Extract body content
|
|
31
|
+
* Accessing doc.body automatically skips <!DOCTYPE>, <html>, and <head> sections.
|
|
32
|
+
* We use trim() to remove leading/trailing whitespace common in server responses.
|
|
33
|
+
*/
|
|
34
|
+
bodyContent: string = doc.body.innerHTML;
|
|
35
|
+
|
|
36
|
+
if (selector) {
|
|
37
|
+
// Normalize hash: ensure it's a valid ID selector
|
|
38
|
+
const targetEl = doc.querySelector(selector);
|
|
39
|
+
|
|
40
|
+
if (targetEl) {
|
|
41
|
+
return targetEl.innerHTML;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// If hash is provided but element not found, we fallback to body or warn
|
|
45
|
+
console.warn(`Element with selector "${selector}" not found in the HTML.`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
return bodyContent ? bodyContent.trim() : htmlText;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
/**
|
|
52
|
+
* Fallback mechanism
|
|
53
|
+
* If the environment (like Node.js without JSDOM) doesn't support DOMParser,
|
|
54
|
+
* or the string is malformed, we log the error and return the raw text.
|
|
55
|
+
*/
|
|
56
|
+
console.error("Failed to parse HTML content using DOMParser:", error);
|
|
57
|
+
return htmlText;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export default getBodyHTML;
|
package/src/getEl.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @since Last modified: 2026/01/
|
|
2
|
+
* @since Last modified: 2026/01/19 10:15:24
|
|
3
3
|
* @function getEl
|
|
4
4
|
* @description Get a DOM node (real or virtual). Supports obtaining nodes from various types (not just HTMLElement).
|
|
5
5
|
* @param {string|Node} obj - Can be a node selector (e.g., #id, .classname, NODENAME, [attribute]) or any node type (HTMLElement, Node, DocumentFragment, etc.).
|
package/src/getEl.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @since Last modified: 2026/01/
|
|
2
|
+
* @since Last modified: 2026/01/19 10:15:24
|
|
3
3
|
* @function getEl
|
|
4
4
|
* @description Get a DOM node (real or virtual). Supports obtaining nodes from various types (not just HTMLElement).
|
|
5
5
|
* @param {string|Node} obj - Can be a node selector (e.g., #id, .classname, NODENAME, [attribute]) or any node type (HTMLElement, Node, DocumentFragment, etc.).
|
|
@@ -16,20 +16,21 @@
|
|
|
16
16
|
'use strict';
|
|
17
17
|
import getDataType from './getDataType';
|
|
18
18
|
|
|
19
|
+
export type QueryableNode = Document | DocumentFragment | Element | SVGElement | HTMLElement | ShadowRoot;
|
|
19
20
|
|
|
20
|
-
const getEl = (obj: string |
|
|
21
|
+
const getEl = (obj: string | QueryableNode | null, wrap: string | QueryableNode | null = document.body): QueryableNode | null => {
|
|
21
22
|
let objType = getDataType(obj),
|
|
22
23
|
parType = getDataType(wrap),
|
|
23
24
|
parent = parType.includes('HTML') || parType === 'ShadowRoot' ? wrap : document.querySelector(wrap as string),
|
|
24
25
|
//如果parent是template节点,需要通过node.content.querySelector取得子节点
|
|
25
26
|
root = parent && parent instanceof HTMLTemplateElement ? parent.content : parent,
|
|
26
|
-
result:
|
|
27
|
+
result: QueryableNode | null = null;
|
|
27
28
|
if (obj) {
|
|
28
29
|
if (objType.includes('HTML')) {
|
|
29
|
-
result = (obj as
|
|
30
|
+
result = (obj as QueryableNode);
|
|
30
31
|
} else if (objType === 'String') {
|
|
31
32
|
try {
|
|
32
|
-
result = ((
|
|
33
|
+
result = ((root as QueryableNode) || document).querySelector((obj as string).trim());
|
|
33
34
|
//可能会报错,报错则返回null
|
|
34
35
|
} catch {
|
|
35
36
|
result = null;
|
package/src/getEls.js
CHANGED
package/src/getEls.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @since Last modified: 2026/01/
|
|
2
|
+
* @since Last modified: 2026/01/19 10:10:38
|
|
3
3
|
* @function getEls
|
|
4
4
|
* @description Get the node array.
|
|
5
5
|
* @param {*} data - It can be a single node selector or a node array.
|
|
@@ -19,15 +19,15 @@
|
|
|
19
19
|
//返回:一个节点数组。
|
|
20
20
|
'use strict';
|
|
21
21
|
import getDataType from './getDataType';
|
|
22
|
-
import getEl from './getEl';
|
|
22
|
+
import getEl, { QueryableNode } from './getEl';
|
|
23
23
|
import isEmpty from './isEmpty';
|
|
24
24
|
|
|
25
|
-
const getEls = (data:
|
|
25
|
+
const getEls = (data: string | QueryableNode | null | (string | QueryableNode)[], parent: string | QueryableNode | null = document.body): QueryableNode[] => {
|
|
26
26
|
let type = getDataType(data),
|
|
27
27
|
parentEl = getEl(parent),
|
|
28
28
|
root = parentEl && parentEl instanceof HTMLTemplateElement ? parentEl.content : (parentEl || document),
|
|
29
29
|
result: any[] = [];
|
|
30
|
-
|
|
30
|
+
//data为空直接返回空数组
|
|
31
31
|
if (isEmpty(data)) { return result; }
|
|
32
32
|
if (type.includes('HTML')) {
|
|
33
33
|
//一个节点
|
|
@@ -39,7 +39,7 @@ const getEls = (data: Node | string | null | (Node | string)[], parent: Node |
|
|
|
39
39
|
return [...(root as any).querySelectorAll(k)];
|
|
40
40
|
}).flat();
|
|
41
41
|
} else if (type === 'Array') {
|
|
42
|
-
result = (data as
|
|
42
|
+
result = (data as QueryableNode[]).map((k: any) => {
|
|
43
43
|
return getEl(k, parentEl);
|
|
44
44
|
});
|
|
45
45
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since Last modified: 2026/01/19 09:56:44
|
|
3
|
+
* Extracts the hash (fragment) portion of a given URL or file path.
|
|
4
|
+
* * This function utilizes the native `URL` constructor to parse the input.
|
|
5
|
+
* It is a pure logical operation and does not trigger any network requests.
|
|
6
|
+
* * @param {string} url - The URL string or file path to parse (e.g., 'index.html#section', 'https://example.com#top').
|
|
7
|
+
* @returns {string} - The hash part of the URL including the '#' character (e.g., '#section').
|
|
8
|
+
* Returns an empty string if no hash is present or if the input is invalid.
|
|
9
|
+
* * @example
|
|
10
|
+
* getUrlHash('https://example.com/page#header'); // Returns '#header'
|
|
11
|
+
* getUrlHash('src/assets/style.css#debug'); // Returns '#debug'
|
|
12
|
+
*/
|
|
13
|
+
const getUrlHash = (url) => {
|
|
14
|
+
// Return empty if input is null, undefined, or not a string
|
|
15
|
+
if (!url || typeof url !== 'string') {
|
|
16
|
+
return '';
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
/**
|
|
20
|
+
* Use window.location.origin as the base URL to support relative paths.
|
|
21
|
+
* The URL constructor follows the WHATWG spec:
|
|
22
|
+
* 1. If 'url' is absolute (e.g., starts with http://), the base is ignored.
|
|
23
|
+
* 2. If 'url' is relative (e.g., starts with ../), it is resolved against the base.
|
|
24
|
+
* In both cases, the .hash property correctly extracts the fragment.
|
|
25
|
+
*/
|
|
26
|
+
const baseUrl = window?.location?.origin || 'https://www.axui.cn', urlObj = new URL(url, baseUrl);
|
|
27
|
+
return urlObj.hash;
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
/**
|
|
31
|
+
* Catch parsing errors for malformed strings.
|
|
32
|
+
* Since this is a utility, we fail silently and return an empty string.
|
|
33
|
+
*/
|
|
34
|
+
return '';
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
export default getUrlHash;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since Last modified: 2026/01/19 09:56:44
|
|
3
|
+
* Extracts the hash (fragment) portion of a given URL or file path.
|
|
4
|
+
* * This function utilizes the native `URL` constructor to parse the input.
|
|
5
|
+
* It is a pure logical operation and does not trigger any network requests.
|
|
6
|
+
* * @param {string} url - The URL string or file path to parse (e.g., 'index.html#section', 'https://example.com#top').
|
|
7
|
+
* @returns {string} - The hash part of the URL including the '#' character (e.g., '#section').
|
|
8
|
+
* Returns an empty string if no hash is present or if the input is invalid.
|
|
9
|
+
* * @example
|
|
10
|
+
* getUrlHash('https://example.com/page#header'); // Returns '#header'
|
|
11
|
+
* getUrlHash('src/assets/style.css#debug'); // Returns '#debug'
|
|
12
|
+
*/
|
|
13
|
+
const getUrlHash = (url: string): string => {
|
|
14
|
+
// Return empty if input is null, undefined, or not a string
|
|
15
|
+
if (!url || typeof url !== 'string') {
|
|
16
|
+
return '';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
try {
|
|
20
|
+
/**
|
|
21
|
+
* Use window.location.origin as the base URL to support relative paths.
|
|
22
|
+
* The URL constructor follows the WHATWG spec:
|
|
23
|
+
* 1. If 'url' is absolute (e.g., starts with http://), the base is ignored.
|
|
24
|
+
* 2. If 'url' is relative (e.g., starts with ../), it is resolved against the base.
|
|
25
|
+
* In both cases, the .hash property correctly extracts the fragment.
|
|
26
|
+
*/
|
|
27
|
+
const baseUrl: string = window?.location?.origin || 'https://www.axui.cn',
|
|
28
|
+
urlObj: URL = new URL(url, baseUrl);
|
|
29
|
+
return urlObj.hash;
|
|
30
|
+
} catch (error) {
|
|
31
|
+
/**
|
|
32
|
+
* Catch parsing errors for malformed strings.
|
|
33
|
+
* Since this is a utility, we fail silently and return an empty string.
|
|
34
|
+
*/
|
|
35
|
+
return '';
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export default getUrlHash;
|