@webeach/code-parser
Version:
Parse code strings into HTML or HAST with syntax highlighting for the WebEach ecosystem
54 lines (50 loc) • 1.79 kB
JavaScript
;
var hastUtilToHtml = require('hast-util-to-html');
var lowlight$1 = require('lowlight');
var aliases = require('./aliases.js');
var grammars = require('./grammars.js');
/**
* Lowlight instance used to perform syntax highlighting.
* We register all known grammars and their aliases below.
*/
const lowlight = lowlight$1.createLowlight();
// Register base grammars (e.g. javascript, typescript, css, etc.)
lowlight.register(grammars.grammars);
// Register additional language aliases (e.g. jsx -> javascript)
lowlight.registerAlias(aliases.aliases);
/**
* Converts raw code into a syntax-highlighted HAST structure using `lowlight`.
*
* If a language is provided, it is used directly. Otherwise, `highlightAuto` is used
* to detect the best matching language.
*
* @param code - The raw source code string
* @param lang - Optional language key or alias to use
* @returns A HAST representation of the highlighted code
*/
function parseCodeToHast(code, lang = null) {
if (lang === null) {
return lowlight.highlightAuto(code, {
prefix: '_token-',
});
}
return lowlight.highlight(lang, code, {
prefix: '_token-',
});
}
/**
* Converts code to a syntax-highlighted HTML string using `lowlight` and `hast-util-to-html`.
*
* Internally calls `parseCodeToHast()` and serializes the result to HTML.
*
* @param code - The raw source code string
* @param langKey - Optional language key or alias to use
* @returns An HTML string with tokenized spans
*/
function parseCodeToHtml(code, langKey = null) {
const hast = parseCodeToHast(code, langKey);
return hastUtilToHtml.toHtml(hast);
}
exports.parseCodeToHast = parseCodeToHast;
exports.parseCodeToHtml = parseCodeToHtml;
//# sourceMappingURL=functions.js.map