UNPKG

@intlayer/chokidar

Version:

Uses chokidar to scan and build Intlayer declaration files into dictionaries based on Intlayer configuration.

62 lines (60 loc) 2.76 kB
import { detectFormatCommand } from "../detectFormatCommand.mjs"; import { mkdir, rename, rm, writeFile } from "node:fs/promises"; import { basename, dirname, join } from "node:path"; import { MARKDOWN } from "@intlayer/types/nodeType"; import { execSync } from "node:child_process"; //#region src/writeContentDeclaration/writeMarkdownFile.ts const stringifyYamlFrontmatter = (fields) => Object.entries(fields).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => { if (Array.isArray(value)) return `${key}:\n${value.map((item) => ` - ${JSON.stringify(item)}`).join("\n")}`; if (typeof value === "string" && (value.includes(":") || value.includes("\n") || value.includes("#"))) return `${key}: ${JSON.stringify(value)}`; return `${key}: ${value}`; }).join("\n"); const getMarkdownBody = (content) => { const lines = content.split(/\r?\n/); const firstNonEmptyIndex = lines.findIndex((line) => line.trim() !== ""); if (firstNonEmptyIndex === -1 || lines[firstNonEmptyIndex].trim() !== "---") return content; let endIndex = -1; for (let i = firstNonEmptyIndex + 1; i < lines.length; i++) if (lines[i].trim() === "---") { endIndex = i; break; } if (endIndex === -1) return content; return lines.slice(endIndex + 1).join("\n").trimStart(); }; const EXCLUDED_FRONTMATTER_KEYS = new Set([ "content", "$schema", "id", "filePath" ]); const writeMarkdownFile = async (absoluteFilePath, dictionary, configuration) => { const content = dictionary.content; const markdownBody = getMarkdownBody(typeof content === "object" && content?.nodeType === MARKDOWN ? content[MARKDOWN] ?? "" : ""); const fileContent = `---\n${stringifyYamlFrontmatter(Object.fromEntries(Object.entries(dictionary).filter(([k, v]) => !EXCLUDED_FRONTMATTER_KEYS.has(k) && v !== void 0)))}\n---\n\n${markdownBody}`; await mkdir(dirname(absoluteFilePath), { recursive: true }); const tempDir = configuration.system?.tempDir; if (tempDir) await mkdir(tempDir, { recursive: true }); const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`; const tempPath = tempDir ? join(tempDir, tempFileName) : `${absoluteFilePath}.${tempFileName}`; try { await writeFile(tempPath, fileContent, "utf-8"); await rename(tempPath, absoluteFilePath); } catch (error) { try { await rm(tempPath, { force: true }); } catch {} throw error; } const formatCommand = detectFormatCommand(configuration); if (formatCommand) try { execSync(formatCommand.replace("{{file}}", absoluteFilePath), { stdio: "inherit", cwd: configuration.system.baseDir }); } catch (error) { console.error(error); } }; //#endregion export { writeMarkdownFile }; //# sourceMappingURL=writeMarkdownFile.mjs.map