forked from rehypejs/rehype-minify
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (65 loc) · 1.64 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
/**
* rehype plugin to minify event handlers.
*
* ## What is this?
*
* This package is a plugin that can minify the JavaScript used as the values of
* event handler attributes.
*
* ## When should I use this?
*
* You can use this plugin when you want to improve the size of HTML documents.
*
* ## API
*
* ### `unified().use(rehypeMinifyEventHandler)`
*
* Minify whitespace in attributes.
* There are no options.
*
* @example
* <h1 onclick="javascript:alert(false)">Hello</h1>
*/
/**
* @typedef {import('hast').Root} Root
*/
import Uglify from 'uglify-js'
import {visit} from 'unist-util-visit'
import {hasProperty} from 'hast-util-has-property'
import {isEventHandler} from 'hast-util-is-event-handler'
const prefix = 'function a(){'
const suffix = '}a();'
/**
* Minify event handler attributes.
*
* @type {import('unified').Plugin<Array<void>, Root>}
*/
export default function rehypeMinifyEventHandler() {
return (tree) => {
visit(tree, 'element', (node) => {
const props = node.properties || {}
/** @type {string} */
let name
for (name in props) {
if (hasProperty(node, name) && isEventHandler(name)) {
props[name] = minify(props[name])
}
}
})
}
}
/**
* @param {null|undefined|string|number|boolean|Array<string|number>} value
* @returns {null|undefined|string|number|boolean|Array<string|number>}
*/
function minify(value) {
let result = value
if (typeof result !== 'string') {
return result
}
try {
const output = Uglify.minify(prefix + result + suffix)
result = output.code.slice(prefix.length, -suffix.length)
} catch {}
return result.trim()
}