generate-sri.js 1.7 KB
Newer Older
1
2
3
4
5
6
7
#!/usr/bin/env node

/*!
 * Script to generate SRI hashes for use in our docs.
 * Remember to use the same vendor files as the CDN ones,
 * otherwise the hashes won't match!
 *
XhmikosR's avatar
XhmikosR committed
8
9
 * Copyright 2017-2019 The Bootstrap Authors
 * Copyright 2017-2019 Twitter, Inc.
10
11
12
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */

13
14
'use strict'

XhmikosR's avatar
XhmikosR committed
15
const crypto = require('crypto')
16
17
18
19
const fs = require('fs')
const path = require('path')
const sh = require('shelljs')

20
21
const pkg = require('../package.json')

22
23
sh.config.fatal = true

24
const configFile = path.join(__dirname, '../_config.yml')
25
26
27
28
29
30
31
32
33
34
35
36
37
38

// Array of objects which holds the files to generate SRI hashes for.
// `file` is the path from the root folder
// `configPropertyName` is the _config.yml variable's name of the file
const files = [
  {
    file: 'dist/css/bootstrap.min.css',
    configPropertyName: 'css_hash'
  },
  {
    file: 'dist/js/bootstrap.min.js',
    configPropertyName: 'js_hash'
  },
  {
XhmikosR's avatar
XhmikosR committed
39
40
    file: 'dist/js/bootstrap.bundle.min.js',
    configPropertyName: 'js_bundle_hash'
41
  },
XhmikosR's avatar
XhmikosR committed
42
43
44
45
  {
    file: `site/docs/${pkg.version_short}/assets/js/vendor/jquery-slim.min.js`,
    configPropertyName: 'jquery_hash'
  },
46
47
48
  {
    file: 'node_modules/popper.js/dist/umd/popper.min.js',
    configPropertyName: 'popper_hash'
49
50
51
52
53
54
55
56
57
  }
]

files.forEach((file) => {
  fs.readFile(file.file, 'utf8', (err, data) => {
    if (err) {
      throw err
    }

XhmikosR's avatar
XhmikosR committed
58
59
60
    const algo = 'sha384'
    const hash = crypto.createHash(algo).update(data, 'utf8').digest('base64')
    const integrity = `${algo}-${hash}`
61
62
63

    console.log(`${file.configPropertyName}: ${integrity}`)

XhmikosR's avatar
XhmikosR committed
64
    sh.sed('-i', new RegExp(`(\\s${file.configPropertyName}:\\s+"|')(\\S+)("|')`), `$1${integrity}$3`, configFile)
65
66
  })
})