Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(@angular-devkit/build-angular): error during critical CSS inlining for external stylesheets #25584

Merged
merged 1 commit into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,15 @@ class CrittersExtended extends Critters {
this.conditionallyInsertCspLoadingScript(document, cspNonce);
}

link.prev?.setAttribute('nonce', cspNonce);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could've kept this and checked that link.prev.tagName === 'style' but that'll be incorrect for a markup like this:

<head>
  <style></style>
  <link rel="stylesheet" href="https://some/external/style.css">
</head>

// Ideally we would hook in at the time Critters inserts the `style` tags, but there isn't
// a way of doing that at the moment so we fall back to doing it any time a `link` tag is
// inserted. We mitigate it by only iterating the direct children of the `<head>` which
// should be pretty shallow.
document.head.children.forEach((child) => {
if (child.tagName === 'style' && !child.hasAttribute('nonce')) {
child.setAttribute('nonce', cspNonce);
}
});
}

return returnValue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,34 @@ describe('InlineCriticalCssProcessor', () => {
html { color: white; }
</style>`);
});

it('should not modify the document for external stylesheets', async () => {
const inlineCssProcessor = new InlineCriticalCssProcessor({
readAsset,
});

const initialContent = `
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://google.com/styles.css" />
</head>
<body>
<app ngCspNonce="{% nonce %}"></app>
</body>
</html>
`;

const { content } = await inlineCssProcessor.process(initialContent, {
outputPath: '/dist/',
});

expect(tags.stripIndents`${content}`).toContain(tags.stripIndents`
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://google.com/styles.css">
</head>
`);
});
});