forked from thegeeklab/hugo-geekdoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webpack.plugins.js
57 lines (48 loc) · 1.54 KB
/
webpack.plugins.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
const fs = require("fs")
const crypto = require("crypto")
const path = require("path")
const { validate } = require("schema-utils")
class SRIPlugin {
static defaultOptions = {
algorithm: "sha512",
sourceFile: "assets.json"
}
constructor(options = {}) {
const schema = {
type: "object",
properties: {
outputFile: {
type: "string"
},
algorithm: {
type: "string"
}
}
}
this.options = { ...SRIPlugin.defaultOptions, ...options }
validate(schema, options, {
name: "SRI Plugin",
baseDataPath: "options"
})
}
apply(compiler) {
compiler.hooks.done.tap("SRIPlugin", (manifest) => {
let data = JSON.parse(fs.readFileSync(this.options.sourceFile, "utf8"))
let outputFile = this.options.outputFile ? this.options.outputFile : this.options.sourceFile
const checksum = (str, algorithm = this.options.algorithm, encoding = "base64") =>
crypto.createHash(algorithm).update(str, "utf8").digest(encoding)
const fileSum = (file, algorithm) => checksum(fs.readFileSync(file), algorithm)
const calculateSRI = (file, algorithm = this.options.algorithm) =>
`${algorithm}-${fileSum(path.join(".", "static", file), algorithm)}`
Object.keys(data).forEach((key) => {
let element = data[key]
element.integrity = calculateSRI(element.src)
})
fs.writeFileSync(outputFile, JSON.stringify(data, null, 2), {
encoding: "utf8",
flag: "w"
})
})
}
}
module.exports = SRIPlugin