import markdown from "markdown-it"; import highlight from "./highlight"; import type Token from "markdown-it/lib/token"; function assignScript(script: string) { const dependencies = {} as Record; const attrs = {} as Record; const content = script .replace(/import\s?\{.*\}.*/g, (item) => { const key = getInnerString(item.replace(/'/g, '"'), '"', '"'); const value = getInnerString(item.replace(/\s+/g, ""), "{", "}"); const list = value ? value.split(",") : []; if (key && dependencies[key]) { dependencies[key] = dependencies[key].concat(list); } else if (key) { dependencies[key] = list; } return ""; }) /** * const -> let * * const a = -> let a = * const a = -> a = */ .replace(/(const|let|var)\s\w*\s?=/g, (item) => { const attr = getInnerString(item, "\\s", "\\s?="); if (attr && !(attr in attrs)) { attrs[attr] = attr; return `let ${attr} =`; } else { return attr + " ="; } }) // Remove extra line breaks .replace(/\n+/gm, "\n"); // Combine the import const reImport = Object.keys(dependencies).reduce((all, item) => { const filterAttrs = [...new Set(dependencies[item])]; return all + `import {${filterAttrs + ","}} from '${item}';\n`; }, ""); return reImport + content; } /** * Extract part of the new string from the middle of the string * @param {string} string string * @param {string} prefix RegExp string * @param {string} postfix RegExp string * @param {string} type g | m | i */ function getInnerString( string: string, prefix: string, postfix = "", type: "i" | "g" | "m" = "i" ): string | undefined { const result = new RegExp(`${prefix}(.*)${postfix}`, type); const match = string.match(result); return match ? match[1].trim() : undefined; } let script = ""; // Record the `; } } } return ` ${description ? `` : ""} `; }, };