generate-sri.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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-2021 The Bootstrap Authors
  8. * Copyright 2017-2021 Twitter, Inc.
  9. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/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. sh.config.fatal = true
  17. const configFile = path.join(__dirname, '../config.yml')
  18. // Array of objects which holds the files to generate SRI hashes for.
  19. // `file` is the path from the root folder
  20. // `configPropertyName` is the config.yml variable's name of the file
  21. const files = [
  22. {
  23. file: 'dist/css/bootstrap.min.css',
  24. configPropertyName: 'css_hash'
  25. },
  26. {
  27. file: 'dist/css/bootstrap.rtl.min.css',
  28. configPropertyName: 'css_rtl_hash'
  29. },
  30. {
  31. file: 'dist/js/bootstrap.min.js',
  32. configPropertyName: 'js_hash'
  33. },
  34. {
  35. file: 'dist/js/bootstrap.bundle.min.js',
  36. configPropertyName: 'js_bundle_hash'
  37. },
  38. {
  39. file: 'node_modules/@popperjs/core/dist/umd/popper.min.js',
  40. configPropertyName: 'popper_hash'
  41. }
  42. ]
  43. files.forEach(file => {
  44. fs.readFile(file.file, 'utf8', (err, data) => {
  45. if (err) {
  46. throw err
  47. }
  48. const algo = 'sha384'
  49. const hash = crypto.createHash(algo).update(data, 'utf8').digest('base64')
  50. const integrity = `${algo}-${hash}`
  51. console.log(`${file.configPropertyName}: ${integrity}`)
  52. sh.sed('-i', new RegExp(`^(\\s+${file.configPropertyName}:\\s+["'])\\S*(["'])`), `$1${integrity}$2`, configFile)
  53. })
  54. })