@textlint/markdown-to-ast
Version:
Parse Markdown to AST with location info.
68 lines • 3.23 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = exports.Syntax = void 0;
const markdown_syntax_map_1 = require("./mapping/markdown-syntax-map");
const ast_node_types_1 = require("@textlint/ast-node-types");
Object.defineProperty(exports, "Syntax", { enumerable: true, get: function () { return ast_node_types_1.ASTNodeTypes; } });
const traverse_1 = __importDefault(require("traverse"));
const debug_1 = __importDefault(require("debug"));
const parse_markdown_1 = require("./parse-markdown");
const debug = (0, debug_1.default)("@textlint/markdown-to-ast");
/**
* parse markdown text and return ast mapped location info.
* @param {string} text
* @returns {TxtNode}
*/
function parse(text) {
// remark-parse's AST does not consider BOM
// AST's position does not +1 by BOM
// So, just trim BOM and parse it for `raw` property
// textlint's SourceCode also take same approach - trim BOM and check the position
// This means that the loading side need to consider BOM position - for example fs.readFile and text slice script.
// https://github.com/micromark/micromark/blob/0f19c1ac25964872a160d8b536878b125ddfe393/lib/preprocess.mjs#L29-L31
const hasBOM = text.charCodeAt(0) === 0xfeff;
const textWithoutBOM = hasBOM ? text.slice(1) : text;
const ast = (0, parse_markdown_1.parseMarkdown)(textWithoutBOM);
(0, traverse_1.default)(ast).forEach(function (node) {
// eslint-disable-next-line no-invalid-this
if (this.notLeaf) {
if (node.type) {
const replacedType = markdown_syntax_map_1.SyntaxMap[node.type];
if (!replacedType) {
debug(`replacedType : ${replacedType} , node.type: ${node.type}`);
}
else {
// @ts-expect-error: TxtNodeType + Markdown extension type
node.type = replacedType;
}
}
// map `range`, `loc` and `raw` to node
if (node.position) {
const position = node.position;
// line start with 1
// column start with 0
const positionCompensated = {
start: { line: position.start.line, column: Math.max(position.start.column - 1, 0) },
end: { line: position.end.line, column: Math.max(position.end.column - 1, 0) }
};
const range = [position.start.offset, position.end.offset];
node.loc = positionCompensated;
node.range = range;
node.raw = textWithoutBOM.slice(range[0], range[1]);
// Compatible for https://github.com/syntax-tree/unist, but it is hidden
Object.defineProperty(node, "position", {
enumerable: false,
configurable: false,
writable: false,
value: position
});
}
}
});
return ast;
}
exports.parse = parse;
//# sourceMappingURL=index.js.map