fix: don't throw when Shiki doesn't recognize a language (#3911)

* Don't throw when Shiki doesn't recognise a language

* Changeset
This commit is contained in:
Juan Martín Seery 2022-07-13 16:31:59 -03:00 committed by GitHub
parent d8af02a944
commit ca45c0c270
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 34 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'@astrojs/markdown-remark': patch
---
Don't throw when Shiki doesn't recognize a language

View file

@ -119,6 +119,9 @@ describe('Astro Markdown Shiki', () => {
expect(segments[0].attribs.style).to.be.equal('color: #C9D1D9');
expect(segments[1].attribs.style).to.be.equal('color: #79C0FF');
expect(segments[2].attribs.style).to.be.equal('color: #C9D1D9');
const unknownLang = $('.line').last().html();
expect(unknownLang).to.be.equal('<span style="color: #c9d1d9">This language does not exist</span>')
});
it('<Markdown /> component', async () => {
@ -129,6 +132,9 @@ describe('Astro Markdown Shiki', () => {
expect(segments).to.have.lengthOf(3);
expect(segments[0].attribs.style).to.be.equal('color: #C9D1D9');
expect(segments[1].attribs.style).to.be.equal('color: #79C0FF');
const unknownLang = $('.line').last().html();
expect(unknownLang).to.be.equal('<span style="color: #c9d1d9">This language does not exist</span>')
});
});

View file

@ -23,5 +23,9 @@ import Layout from '../layouts/content.astro';
Iniciar(Rinfo, 1, 1)
fin
```
```unknown
This language does not exist
```
</Markdown>
</Layout>

View file

@ -20,3 +20,7 @@ comenzar
Iniciar(Rinfo, 1, 1)
fin
```
```unknown
This language does not exist
```

View file

@ -30,7 +30,21 @@ const remarkShiki = async (
return () => (tree: any) => {
visit(tree, 'code', (node) => {
let html = highlighter!.codeToHtml(node.value, { lang: node.lang ?? 'plaintext' });
let lang: string;
if (typeof node.lang === 'string') {
const langExists = highlighter.getLoadedLanguages().includes(node.lang);
if (langExists) {
lang = node.lang;
} else {
console.warn(`The language "${node.lang}" doesn't exist, falling back to plaintext.`);
lang = 'plaintext';
}
} else {
lang = 'plaintext';
}
let html = highlighter!.codeToHtml(node.value, { lang });
// Q: Couldn't these regexes match on a user's inputted code blocks?
// A: Nope! All rendered HTML is properly escaped.