generate-sri.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env node
  2. /*!
  3. * Script to generate SRI hashes for use in our docs.
  4. * Remember to use the same vendor files as the CDN ones,
  5. * otherwise the hashes won't match!
  6. *
  7. * Copyright 2017-2019 The Bootstrap Authors
  8. * Copyright 2017-2019 Twitter, Inc.
  9. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  10. */
  11. 'use strict'
  12. const crypto = require('crypto')
  13. const fs = require('fs')
  14. const path = require('path')
  15. const sh = require('shelljs')
  16. const pkg = require('../package.json')
  17. sh.config.fatal = true
  18. const configFile = path.join(__dirname, '../_config.yml')
  19. // Array of objects which holds the files to generate SRI hashes for.
  20. // `file` is the path from the root folder
  21. // `configPropertyName` is the _config.yml variable's name of the file
  22. const files = [
  23. {
  24. file: 'dist/css/bootstrap.min.css',
  25. configPropertyName: 'css_hash'
  26. },
  27. {
  28. file: 'dist/js/bootstrap.min.js',
  29. configPropertyName: 'js_hash'
  30. },
  31. {
  32. file: 'dist/js/bootstrap.bundle.min.js',
  33. configPropertyName: 'js_bundle_hash'
  34. },
  35. {
  36. file: `site/docs/${pkg.version_short}/assets/js/vendor/jquery-slim.min.js`,
  37. configPropertyName: 'jquery_hash'
  38. },
  39. {
  40. file: 'node_modules/popper.js/dist/umd/popper.min.js',
  41. configPropertyName: 'popper_hash'
  42. }
  43. ]
  44. files.forEach((file) => {
  45. fs.readFile(file.file, 'utf8', (err, data) => {
  46. if (err) {
  47. throw err
  48. }
  49. const algo = 'sha384'
  50. const hash = crypto.createHash(algo).update(data, 'utf8').digest('base64')
  51. const integrity = `${algo}-${hash}`
  52. console.log(`${file.configPropertyName}: ${integrity}`)
  53. sh.sed('-i', new RegExp(`(\\s${file.configPropertyName}:\\s+"|')(\\S+)("|')`), `$1${integrity}$3`, configFile)
  54. })
  55. })