generate-sri.mjs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env node
  2. 'use strict'
  3. import crypto from 'crypto'
  4. import { readFileSync, writeFileSync } from 'fs'
  5. import path from 'path'
  6. import { fileURLToPath } from 'node:url'
  7. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  8. const configFile = path.join(__dirname, '../pages/_data/site.json')
  9. console.log(configFile)
  10. const files = [
  11. {
  12. file: 'dist/css/tabler.min.css',
  13. configPropertyName: 'css_hash'
  14. },
  15. {
  16. file: 'dist/css/tabler.rtl.min.css',
  17. configPropertyName: 'css_rtl_hash'
  18. },
  19. {
  20. file: 'dist/css/tabler-flags.min.css',
  21. configPropertyName: 'css_flags_hash'
  22. },
  23. {
  24. file: 'dist/css/tabler-payments.min.css',
  25. configPropertyName: 'css_payments_hash'
  26. },
  27. {
  28. file: 'dist/css/tabler-social.min.css',
  29. configPropertyName: 'css_social_hash'
  30. },
  31. {
  32. file: 'dist/css/tabler-vendors.min.css',
  33. configPropertyName: 'css_vendors_hash'
  34. },
  35. {
  36. file: 'dist/js/tabler.min.js',
  37. configPropertyName: 'js_hash'
  38. },
  39. {
  40. file: 'dist/js/tabler.bundle.min.js',
  41. configPropertyName: 'js_bundle_hash'
  42. }
  43. ]
  44. files.forEach((file) => {
  45. const data = readFileSync(path.join(__dirname, '..', file.file), 'utf8')
  46. const algo = 'sha384'
  47. const hash = crypto.createHash(algo).update(data, 'utf8').digest('base64')
  48. const integrity = `${algo}-${hash}`
  49. let config = readFileSync(configFile, 'utf8')
  50. const regex = new RegExp(`"${file.configPropertyName}"\\:\\s+("|')(\\S+)(\\1)`, 'gm')
  51. config = config.replace(regex, function() {
  52. return `"${file.configPropertyName}": ${arguments[1]}${integrity}${arguments[3]}`
  53. })
  54. writeFileSync(configFile, config, 'utf8')
  55. })