generate-sri.js 1.6 KB

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