UNPKG

myst-cli

Version:
39 lines (38 loc) 1.5 kB
import fs from 'node:fs'; import { RuleId } from 'myst-common'; import { selectAll } from 'unist-util-select'; import { join, dirname } from 'node:path'; import { addWarningForFile } from '../utils/addWarningForFile.js'; /** * This is the {mdast} directive, that loads from disk * For example, tables that can't be represented in markdown. */ export function importMdastFromJson(session, filename, mdast) { const mdastNodes = selectAll('mdast', mdast); const loadedData = {}; const dir = dirname(filename); mdastNodes.forEach((node) => { const [mdastFilename, id] = node.id.split('#'); let data = loadedData[mdastFilename]; if (!data) { try { data = JSON.parse(fs.readFileSync(join(dir, mdastFilename)).toString()); loadedData[mdastFilename] = data; } catch { addWarningForFile(session, filename, `Mdast Node import: Could not load ${mdastFilename}`, 'error', { ruleId: RuleId.mdastSnippetImports }); return; } } if (!data[id]) { addWarningForFile(session, filename, `Mdast Node import: Could not find ${id} in ${mdastFilename}`, 'error', { ruleId: RuleId.mdastSnippetImports }); return; } // Clear the current object Object.keys(node).forEach((k) => { delete node[k]; }); // Replace with the import Object.assign(node, data[id]); }); }