Skip to content

Commit

Permalink
fix(posthtml#220): should not merge <style> or <script> with SRI
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Jan 8, 2023
1 parent 5478092 commit 9681eaa
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 5 deletions.
12 changes: 8 additions & 4 deletions lib/modules/mergeScripts.es6
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
/* Merge multiple <script> into one */
export default function mergeScripts(tree) {
export default function mergeScripts (tree) {
let scriptNodesIndex = {};
let scriptSrcIndex = 1;

tree.match({tag: 'script'}, node => {
tree.match({ tag: 'script' }, node => {
const nodeAttrs = node.attrs || {};
if (nodeAttrs.src) {
if (
'src' in nodeAttrs
// Skip SRI
|| 'integrity' in nodeAttrs
) {
scriptSrcIndex++;
return node;
}
Expand All @@ -23,7 +27,7 @@ export default function mergeScripts(tree) {
async: nodeAttrs.async !== undefined,
index: scriptSrcIndex,
});
if (! scriptNodesIndex[scriptKey]) {
if (!scriptNodesIndex[scriptKey]) {
scriptNodesIndex[scriptKey] = [];
}

Expand Down
3 changes: 2 additions & 1 deletion lib/modules/mergeStyles.es6
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ export default function mergeStyles(tree) {
const nodeAttrs = node.attrs || {};
// Skip <style scoped></style>
// https://developer.mozilla.org/en/docs/Web/HTML/Element/style
if (nodeAttrs.scoped !== undefined) {
// Also skip SRI
if ('scoped' in nodeAttrs || 'integrity' in nodeAttrs) {
return node;
}

Expand Down
13 changes: 13 additions & 0 deletions test/modules/mergeScripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,17 @@ describe('mergeScripts', () => {
options
);
});

it('should not merge script with SRI', () => {
return init(
`<script>window.foo1 = 'foo'</script><script>window.foo2 = 'foo'</script>
<script integrity="example">window.foo2 = 'foo'</script><script>window.foo3 = 'baz'</script>
<script>window.bar1 = 'foo'</script><script>window.bar2 = 'bar'</script>`,

`<script>window.foo1 = 'foo';window.foo2 = 'foo'</script>
<script integrity="example">window.foo2 = 'foo'</script>
<script>window.foo3 = 'baz';window.bar1 = 'foo';window.bar2 = 'bar'</script>`,
options
);
});
});
9 changes: 9 additions & 0 deletions test/modules/mergeStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ describe('mergeStyles', () => {
);
});

it('should skip <style> with SRI', () => {
const html = `<style>h1 { color: red }</style>
<div></div>
<style integrity="example">div { color: blue }</style>`;
return init(
html, html, options
);
});


it('should preserve amp-custom', () => {
return init(
Expand Down

0 comments on commit 9681eaa

Please sign in to comment.