Use 'node-html-parser'

This commit is contained in:
Sidharth Vinod
2022-07-08 13:44:16 +05:30
parent 5b9823298e
commit d7388b0ccb
3 changed files with 43 additions and 23 deletions
+29 -16
View File
@@ -1,9 +1,11 @@
import fs from 'fs';
import path from 'path';
import { parse } from 'node-html-parser';
import prettier from 'prettier';
// parse monaco version out of package.json
const packageJson = JSON.parse(fs.readFileSync('package.json'));
const monacoVersion = packageJson.dependencies['monaco-editor'].substring(1);
const monacoVersion = packageJson.dependencies['monaco-editor'].replace('^', '');
// fetch monaco sri info from cdnjs api
const cdnjsAPIResp = await fetch(
@@ -11,22 +13,33 @@ const cdnjsAPIResp = await fetch(
);
if (cdnjsAPIResp.ok) {
const respJson = await cdnjsAPIResp.json();
const htmlPath = path.join('src', 'app.html');
const appHtml = fs
.readFileSync(htmlPath, 'utf8')
// update monaco version of every asset in app.html
.replaceAll(/[0-9.]+\/min\/vs/g, `${monacoVersion}/min/vs`);
const root = parse(appHtml);
const updateIntegrity = (tag, attr) => {
for (const node of root
.getElementsByTagName(tag)
.filter((node) => node.getAttribute(attr)?.includes('monaco-editor'))) {
const file = node.getAttribute(attr).split(`${monacoVersion}/`)[1];
node.setAttribute('integrity', respJson.sri[file]);
}
};
let appHtml = fs.readFileSync(path.join('src', 'app.html'), 'utf8');
// update monaco version of every asset in app.html
appHtml = appHtml.replaceAll(/[0-9.]+\/min\/vs/g, `${monacoVersion}/min/vs`);
// update sri integrity value for each asset
for (let monacoAssetMatch of appHtml.matchAll(/min\/vs\/[^"]+/g)) {
let monacoAsset = monacoAssetMatch[0];
appHtml = appHtml.replace(
new RegExp(
monacoAsset.replaceAll('/', '\\/').replaceAll('.', '\\.') + '" integrity=".+"',
'g'
),
`${monacoAsset}" integrity="${respJson.sri[monacoAsset]}"`
);
}
fs.writeFileSync(path.join('src', 'app.html'), appHtml);
updateIntegrity('script', 'src');
updateIntegrity('link', 'href');
fs.writeFileSync(
htmlPath,
prettier.format(root.toString(), {
singleQuote: false,
parser: 'html',
bracketSameLine: true,
useTabs: true
})
);
} else {
throw Error('Unable to fetch monaco sri data from cdnjs api.');
}