UNPKG

markdown-toc-gen

Version:

Generating and updating table of contents in Markdown files which conform with prettier.

73 lines (72 loc) 2.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TocService = void 0; const jest_diff_1 = require("jest-diff"); /** * TocService * provides method to parse and validate toc */ class TocService { constructor() { this._tocPlaceholder = new RegExp('<!--\\s?toc\\s?-->(?<toc>(?:.*\\r?\\n)+)<!--\\s?tocstop\\s?-->'); } /** * creates unique id link * @param caption - heading title * @param counter - amount of repetition of given caption (optional) * @returns - unique id link */ createLink(caption, counter) { if (counter) { return `(#${this.toLinkId(caption)}-${counter})`; } return `(#${this.toLinkId(caption)})`; } /** * parses and validates toc in given markdown file and evaluates given toc with generated toc * @return toc validation */ validateToc(parsedToc, expectedToc) { const diffHeadings = this.getDiffHeadings(parsedToc.split('\n').filter((item) => item), expectedToc.split('\n').filter((item) => item)); if (diffHeadings) { return diffHeadings; } return null; } /** * finds and parses table of content in given markdown file * @returns parsed table of content */ parseToc(content) { const match = this._tocPlaceholder.exec(content); if (match && match.groups && match.groups.toc) { return match.groups.toc; } return ''; } /** * get diff for the headings between the parsed table of contend and the parsed headings * @param parsedTOCHeadings - parsed existing table of content * @param parsedHeadings - table of contents which is created out of the parsed headings * @returns diff for existing and created table of content */ getDiffHeadings(parsedTOCHeadings, parsedHeadings) { const diffHeadings = (0, jest_diff_1.diffLinesRaw)(parsedTOCHeadings, parsedHeadings); if (diffHeadings.filter((val) => val['0'] !== 0).length > 0) { return (0, jest_diff_1.diffLinesUnified)(parsedTOCHeadings, parsedHeadings); } return null; } /** * transform given string to gfm link id * @param str - given string which should be transformed * @returns - transformed string */ toLinkId(str) { return str .replace(/[\s]+/g, '-') .replace(/[^a-zA-Z0-9-_]*/g, '') .toLowerCase(); } } exports.TocService = TocService;