generate-sri.mjs 1.7 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-2025 The Bootstrap Authors
  8. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
  9. */
  10. import crypto from 'node:crypto'
  11. import fs from 'node:fs'
  12. import path from 'node:path'
  13. import { fileURLToPath } from 'node:url'
  14. import sh from 'shelljs'
  15. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  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. for (const { file, configPropertyName } of files) {
  44. fs.readFile(file, 'utf8', (error, data) => {
  45. if (error) {
  46. throw error
  47. }
  48. const algorithm = 'sha384'
  49. const hash = crypto.createHash(algorithm).update(data, 'utf8').digest('base64')
  50. const integrity = `${algorithm}-${hash}`
  51. console.log(`${configPropertyName}: ${integrity}`)
  52. sh.sed('-i', new RegExp(`^(\\s+${configPropertyName}:\\s+["'])\\S*(["'])`), `$1${integrity}$2`, configFile)
  53. })
  54. }