-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (66 loc) · 1.74 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
const jsdom = require('jsdom')
const { JSDOM } = jsdom
const emptyHtml = '<html><head></head><body></body></html>'
class DevTools {
constructor(htmlString = emptyHtml) {
this.__htmlString__ = function () {
return htmlString
}
this.dom = new JSDOM(htmlString)
this.index = 0
}
get html() {
return this.__htmlString__()
}
get outerHTML() {
return this.dom.window.document.documentElement.outerHTML
}
getDom() {
return this.dom
}
getDocument() {
return this.getDom().window.document
}
// getOuterHtml() {
// return this.getDom().window.document.documentElement.outerHTML
// }
run(raw) {
const document = this.getDocument()
const code = raw
.replace(/this\./g, 'document.')
.replace(/\$\$\(["']([^\)]+)["']\)/g, 'Array.from(document.querySelectorAll(\'$1\'))')
.replace(/\$\(["']([^\)]+)["']\)/g, 'document.querySelector(\'$1\')')
if('.' === code) {
return document
}
if(/^(\.\w*)+\[]/.test(code)) {
function fold(s) {
if(s.length === 1) {
return 'x => x' + s[0]
}
let obj = s.shift()
obj = obj === '.' ? 'x' : 'x' + obj
return `x => Object.values(${obj}).flatMap(${fold(s)})`
}
code = fold(code.split('[]'))
}
if(/^\.\[/.test(code)) {
return eval(`function fn() {
return this${code.substring(1)}
}; fn`).call(document)
}
if(/^\./.test(code)) {
return eval(`function fn() {
return this${code}
}; fn`).call(document)
}
var fn = eval(`function fn() {
return ${code}
}; fn`).call(document)
if(typeof fn === 'function') {
return fn(document)
}
return fn || ''
}
}
module.exports = DevTools