-
-
Notifications
You must be signed in to change notification settings - Fork 309
/
Copy pathindex.js
389 lines (359 loc) · 12.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/** @typedef {import('parse5').TreeAdapter} TreeAdapter */
/** @typedef {import('parse5').Element} Element */
/** @typedef {import('parse5').Attribute} Attribute */
/** @typedef {import('parse5').Node} Node */
/** @typedef {import('parse5').ParentNode} ParentNode */
/** @typedef {import('parse5').ChildNode} ChildNode */
/** @typedef {import('parse5').CommentNode} CommentNode */
/** @typedef {import('parse5').TextNode} TextNode */
const parse5 = require('parse5');
const adapter = require('parse5/lib/tree-adapters/default');
const DEFAULT_NAMESPACE = 'http://www.w3.org/1999/xhtml';
const REGEXP_IS_HTML_DOCUMENT = /^\s*<(!doctype|html|head|body)\b/i;
/**
* Creates an element node.
*
* @param {string} tagName Tag name of the element.
* @param {Record<string, string>} attrs Attribute name-value pair array. Foreign attributes may contain `namespace` and `prefix` fields as well.
* @param {string} namespaceURI Namespace of the element.
* @returns {Element}
*/
function createElement(tagName, attrs = {}, namespaceURI = DEFAULT_NAMESPACE) {
const attrsArray = Object.entries(attrs).map(([name, value]) => ({ name, value }));
return adapter.createElement(tagName, namespaceURI, attrsArray);
}
/**
* Creates a script element.
* @param {Record<string,string>} [attrs]
* @param {string} [code]
* @returns {Element}
*/
function createScript(attrs = {}, code = undefined) {
const element = createElement('script', attrs);
if (code) {
setTextContent(element, code);
}
return element;
}
/**
* @param {string} html
*/
function isHtmlFragment(html) {
let htmlWithoutComments = html.replace(/<!--.*?-->/gs, '');
return !REGEXP_IS_HTML_DOCUMENT.test(htmlWithoutComments);
}
/**
* @param {Element} element
*/
function getAttributes(element) {
const attrsArray = adapter.getAttrList(element);
/** @type {Record<string,string>} */
const attrsObj = {};
for (const e of attrsArray) {
attrsObj[e.name] = e.value;
}
return attrsObj;
}
/**
* @param {Element} element
* @param {string} name
*/
function getAttribute(element, name) {
const attrList = adapter.getAttrList(element);
if (!attrList) {
return null;
}
const attr = attrList.find(a => a.name == name);
if (attr) {
return attr.value;
}
}
/**
* @param {Element} element
* @param {string} name
*/
function hasAttribute(element, name) {
return getAttribute(element, name) != null;
}
/**
* @param {Element} element
* @param {string} name
* @param {string} value
*/
function setAttribute(element, name, value) {
const attrs = adapter.getAttrList(element);
const existing = attrs.find(a => a.name === name);
if (existing) {
existing.value = value;
} else {
attrs.push({ name, value });
}
}
/**
* @param {Element} element
* @param {Record<string,string|undefined>} attributes
*/
function setAttributes(element, attributes) {
for (const [name, value] of Object.entries(attributes)) {
if (value !== undefined) {
setAttribute(element, name, value);
}
}
}
/**
* @param {Element} element
* @param {string} name
*/
function removeAttribute(element, name) {
const attrs = adapter.getAttrList(element);
element.attrs = attrs.filter(attr => attr.name !== name);
}
/**
* @param {Node} node
* @returns {string}
*/
function getTextContent(node) {
if (adapter.isCommentNode(node)) {
return node.data || '';
}
if (adapter.isTextNode(node)) {
return node.value || '';
}
const subtree = findNodes(node, n => adapter.isTextNode(n));
return subtree.map(getTextContent).join('');
}
/**
* @param {Node} node
* @param {string} value
*/
function setTextContent(node, value) {
if (adapter.isCommentNode(node)) {
node.data = value;
} else if (adapter.isTextNode(node)) {
node.value = value;
} else {
const textNode = {
nodeName: '#text',
value: value,
parentNode: node,
attrs: [],
__location: undefined,
};
/** @type {ParentNode} */ (node).childNodes = [/** @type {TextNode} */ (textNode)];
}
}
/**
* Removes element from the AST.
* @param {ChildNode} node
*/
function remove(node) {
const parent = node.parentNode;
if (parent && parent.childNodes) {
const idx = parent.childNodes.indexOf(node);
parent.childNodes.splice(idx, 1);
}
/** @type {any} */ (node).parentNode = undefined;
}
/**
* Looks for a child node which passes the given test
* @param {Node[] | Node} nodes
* @param {(node: Node) => boolean} test
* @returns {Node | null}
*/
function findNode(nodes, test) {
const n = Array.isArray(nodes) ? nodes.slice() : [nodes];
while (n.length > 0) {
const node = n.shift();
if (!node) {
continue;
}
if (test(node)) {
return node;
}
const children = getNodeChildren(node);
if (Array.isArray(children)) {
n.unshift(...children);
}
}
return null;
}
/**
* Looks for all child nodes which passes the given test
* @param {Node | Node[]} nodes
* @param {(node: Node) => boolean} test
* @returns {Node[]}
*/
function findNodes(nodes, test) {
const n = Array.isArray(nodes) ? nodes.slice() : [nodes];
/** @type {Node[]} */
const found = [];
while (n.length) {
const node = n.shift();
if (!node) {
continue;
}
if (test(node)) {
found.push(node);
}
const children = getNodeChildren(node);
if (Array.isArray(children)) {
n.unshift(...children);
}
}
return found;
}
/**
* Get all children of a node or all children of a `<template>` element's content
* @param {Node} node
* @returns {Node[]}
*/
function getNodeChildren(node) {
/** @type {Node[]} */
let children = [];
if (adapter.isElementNode(node) && adapter.getTagName(node) === 'template') {
const content = adapter.getTemplateContent(node);
if (content) {
children = adapter.getChildNodes(content);
}
} else {
children = adapter.getChildNodes(/** @type {ParentNode} */ (node));
}
return children;
}
/**
* Looks for a child element which passes the given test
* @param {Node[] | Node} nodes
* @param {(node: Element) => boolean} test
* @returns {Element | null}
*/
function findElement(nodes, test) {
return /** @type {Element | null} */ (findNode(nodes, n => adapter.isElementNode(n) && test(n)));
}
/**
* Looks for all child elements which passes the given test
* @param {Node | Node[]} nodes
* @param {(node: Element) => boolean} test
* @returns {Element[]}
*/
function findElements(nodes, test) {
return /** @type {Element[]} */ (findNodes(nodes, n => adapter.isElementNode(n) && test(n)));
}
/**
* @param {ParentNode} parent
* @param {ChildNode} node
*/
function prepend(parent, node) {
parent.childNodes.unshift(node);
node.parentNode = parent;
}
/**
* Prepends HTML snippet to the given html document. The document must have either
* a <body> or <head> element.
* @param {string} document
* @param {string} appendedHtml
* @returns {string | null}
*/
function prependToDocument(document, appendedHtml) {
const documentAst = parse5.parse(document, { sourceCodeLocationInfo: true });
let appendNode = findElement(documentAst, node => adapter.getTagName(node) === 'head');
if (!appendNode || !appendNode.sourceCodeLocation || !appendNode.sourceCodeLocation.startTag) {
// the original code did not contain a head
appendNode = findElement(documentAst, node => adapter.getTagName(node) === 'body');
if (!appendNode || !appendNode.sourceCodeLocation || !appendNode.sourceCodeLocation.startTag) {
// the original code did not contain a head or body, so we go with the generated AST
const head = findElement(documentAst, node => adapter.getTagName(node) === 'head');
if (!head) throw new Error('parse5 did not generated a head element');
const fragment = parse5.parseFragment(appendedHtml);
for (const node of adapter.getChildNodes(fragment).reverse()) {
prepend(head, node);
}
return parse5.serialize(documentAst);
}
}
// the original source contained a head or body element, use string manipulation
// to preserve original code formatting
const { endOffset } = appendNode.sourceCodeLocation.startTag;
const start = document.substring(0, endOffset);
const end = document.substring(endOffset);
return `${start}${appendedHtml}${end}`;
}
/**
* Append HTML snippet to the given html document. The document must have either
* a <body> or <head> element.
* @param {string} document
* @param {string} appendedHtml
*/
function appendToDocument(document, appendedHtml) {
const documentAst = parse5.parse(document, { sourceCodeLocationInfo: true });
let appendNode = findElement(documentAst, node => adapter.getTagName(node) === 'body');
if (!appendNode || !appendNode.sourceCodeLocation || !appendNode.sourceCodeLocation.endTag) {
// there is no body node in the source, use the head instead
appendNode = findElement(documentAst, node => adapter.getTagName(node) === 'head');
if (!appendNode || !appendNode.sourceCodeLocation || !appendNode.sourceCodeLocation.endTag) {
// the original code did not contain a head or body, so we go with the generated AST
const body = findElement(documentAst, node => adapter.getTagName(node) === 'body');
if (!body) throw new Error('parse5 did not generated a body element');
const fragment = parse5.parseFragment(appendedHtml);
for (const node of adapter.getChildNodes(fragment)) {
adapter.appendChild(body, node);
}
return parse5.serialize(documentAst);
}
}
// the original source contained a head or body element, use string manipulation
// to preserve original code formatting
const { startOffset } = appendNode.sourceCodeLocation.endTag;
const start = document.substring(0, startOffset);
const end = document.substring(startOffset);
return `${start}${appendedHtml}${end}`;
}
module.exports.createDocument = adapter.createDocument;
module.exports.createDocumentFragment = adapter.createDocumentFragment;
module.exports.createElement = createElement;
module.exports.createScript = createScript;
module.exports.createCommentNode = adapter.createCommentNode;
module.exports.appendChild = adapter.appendChild;
module.exports.insertBefore = adapter.insertBefore;
module.exports.setTemplateContent = adapter.setTemplateContent;
module.exports.getTemplateContent = adapter.getTemplateContent;
module.exports.setDocumentType = adapter.setDocumentType;
module.exports.setDocumentMode = adapter.setDocumentMode;
module.exports.getDocumentMode = adapter.getDocumentMode;
module.exports.detachNode = adapter.detachNode;
module.exports.insertText = adapter.insertText;
module.exports.insertTextBefore = adapter.insertTextBefore;
module.exports.adoptAttributes = adapter.adoptAttributes;
module.exports.getFirstChild = adapter.getFirstChild;
module.exports.getChildNodes = adapter.getChildNodes;
module.exports.getParentNode = adapter.getParentNode;
module.exports.getAttrList = adapter.getAttrList;
module.exports.getTagName = adapter.getTagName;
module.exports.getNamespaceURI = adapter.getNamespaceURI;
module.exports.getTextNodeContent = adapter.getTextNodeContent;
module.exports.getCommentNodeContent = adapter.getCommentNodeContent;
module.exports.getDocumentTypeNodeName = adapter.getDocumentTypeNodeName;
module.exports.getDocumentTypeNodePublicId = adapter.getDocumentTypeNodePublicId;
module.exports.getDocumentTypeNodeSystemId = adapter.getDocumentTypeNodeSystemId;
module.exports.isTextNode = adapter.isTextNode;
module.exports.isCommentNode = adapter.isCommentNode;
module.exports.isDocumentTypeNode = adapter.isDocumentTypeNode;
module.exports.isElementNode = adapter.isElementNode;
module.exports.setNodeSourceCodeLocation = adapter.setNodeSourceCodeLocation;
module.exports.getNodeSourceCodeLocation = adapter.getNodeSourceCodeLocation;
module.exports.isHtmlFragment = isHtmlFragment;
module.exports.hasAttribute = hasAttribute;
module.exports.getAttribute = getAttribute;
module.exports.getAttributes = getAttributes;
module.exports.setAttribute = setAttribute;
module.exports.setAttributes = setAttributes;
module.exports.removeAttribute = removeAttribute;
module.exports.setTextContent = setTextContent;
module.exports.getTextContent = getTextContent;
module.exports.remove = remove;
module.exports.findNode = findNode;
module.exports.findNodes = findNodes;
module.exports.findElement = findElement;
module.exports.findElements = findElements;
module.exports.prepend = prepend;
module.exports.prependToDocument = prependToDocument;
module.exports.appendToDocument = appendToDocument;