pinafore/bin/build-inline-script.js

46 lines
1.4 KiB
JavaScript
Raw Normal View History

import crypto from 'crypto'
import fs from 'fs'
import { promisify } from 'util'
import path from 'path'
import { rollup } from 'rollup'
import { terser } from 'rollup-plugin-terser'
2020-01-12 18:32:40 +00:00
import replace from '@rollup/plugin-replace'
import fromPairs from 'lodash-es/fromPairs'
import { themes } from '../src/routes/_static/themes'
import terserOptions from './terserOptions'
const writeFile = promisify(fs.writeFile)
2018-04-14 22:50:16 +00:00
const themeColors = fromPairs(themes.map(_ => ([_.name, _.color])))
export async function buildInlineScript () {
2019-08-03 20:49:37 +00:00
const inlineScriptPath = path.join(__dirname, '../src/inline-script/inline-script.js')
2018-04-14 22:50:16 +00:00
2019-08-03 20:49:37 +00:00
const bundle = await rollup({
input: inlineScriptPath,
plugins: [
replace({
'process.browser': true,
'process.env.THEME_COLORS': JSON.stringify(themeColors)
}),
!process.env.DEBUG && terser(terserOptions)
]
})
2019-08-03 20:49:37 +00:00
const { output } = await bundle.generate({
format: 'iife',
sourcemap: true
})
2019-08-03 20:49:37 +00:00
const { code, map } = output[0]
2019-08-03 20:49:37 +00:00
const fullCode = `${code}//# sourceMappingURL=/inline-script.js.map`
const checksum = crypto.createHash('sha256').update(fullCode).digest('base64')
2018-04-14 22:50:16 +00:00
await writeFile(path.resolve(__dirname, '../src/inline-script/checksum.js'),
`module.exports = ${JSON.stringify(checksum)}`, 'utf8')
await writeFile(path.resolve(__dirname, '../static/inline-script.js.map'),
map.toString(), 'utf8')
return '<script>' + fullCode + '</script>'
2018-04-14 22:50:16 +00:00
}