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

feat: check code examples syntax #7396

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
29 changes: 29 additions & 0 deletions apps/site/next.mdx.shiki.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

import { parse } from 'acorn';
import classNames from 'classnames';
import { toString } from 'hast-util-to-string';
import { SKIP, visit } from 'unist-util-visit';
Expand Down Expand Up @@ -53,6 +54,29 @@ function isCodeBlock(node) {
);
}

/**
* Check code syntax is valid.
*
* @param {string} code - The code to be checked.
* @param {string} languageId - The language id.
* @returns {boolean}
*/
function checkCodeSyntax(code, languageId) {
try {
if (!['js', 'cjs', 'mjs'].includes(languageId)) {
return true;
}

parse(code, {
ecmaVersion: 'latest',
sourceType: languageId === 'cjs' ? 'script' : 'module',
});
return true;
} catch {
return false;
}
}

export default function rehypeShikiji() {
return function (tree) {
visit(tree, 'element', (_, index, parent) => {
Expand Down Expand Up @@ -168,6 +192,11 @@ export default function rehypeShikiji() {
// Grabs the relevant alias/name of the language
const languageId = codeLanguage.slice(languagePrefix.length);

// Check code for syntax errors
if (!checkCodeSyntax(preElementContents, languageId)) {
throw new Error('Code block contains syntax errors');
}

// Parses the <pre> contents and returns a HAST tree with the highlighted code
const { children } = highlightToHast(preElementContents, languageId);

Expand Down
87 changes: 44 additions & 43 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"prepare": "husky"
},
"dependencies": {
"acorn": "^8.14.0",
"husky": "9.1.7",
"lint-staged": "15.3.0",
"turbo": "2.3.3"
Expand Down
Loading