UNPKG

@lusito/require-libs

Version:

Some libraries to setup require hooks

58 lines (57 loc) 2.21 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createMarkdownCompiler = createMarkdownCompiler; exports.createMarkdownHandler = createMarkdownHandler; const path_1 = require("path"); const markdown_it_1 = __importDefault(require("markdown-it")); const highlight_js_1 = __importDefault(require("highlight.js")); const front_matter_1 = __importDefault(require("front-matter")); const protocolPattern = /^https?:\/\//; function createMarkdownCompiler({ copyAsset, createElement, postProcess, setup }) { const md = new markdown_it_1.default({ linkify: true, html: true, highlight(str, lang) { let code; if (lang && highlight_js_1.default.getLanguage(lang)) { try { code = highlight_js_1.default.highlight(str, { language: lang, ignoreIllegals: true }).value; } catch (e) { console.error("Failed highlighting", e); } } return `<pre><code class="hljs">${code ?? md.utils.escapeHtml(str)}</code></pre>`; }, }); setup?.(md); return (code, filename) => { const dir = (0, path_1.dirname)(filename); const dom = createElement("div"); const result = (0, front_matter_1.default)(code); dom.innerHTML = md.render(result.body); dom.querySelectorAll("img").forEach((img) => { if (!protocolPattern.test(img.src)) { img.src = copyAsset((0, path_1.resolve)(dir, img.src)); } }); const meta = postProcess({ filename, dir, dom, frontMatter: result.attributes, }); return { html: dom.innerHTML, meta: meta ?? {}, frontMatter: result.attributes, }; }; } function createMarkdownHandler(options) { const compile = createMarkdownCompiler(options); return (code, filename) => `module.exports = ${JSON.stringify(compile(code, filename))}`; }