"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { CONFIG_FILE_NAME: () => CONFIG_FILE_NAME, GET_DEFAULT_FRONT_MATTER: () => GET_DEFAULT_FRONT_MATTER, Notification: () => Notification, WORDS_PER_MINUTE: () => WORDS_PER_MINUTE, autoFrontMatter: () => autoFrontMatter, createConfigFile: () => createConfigFile, ensureMarkdownExtension: () => ensureMarkdownExtension, getArticleFromFrontMatter: () => getArticleFromFrontMatter, getDay: () => getDay, getFrontMatterFromDocument: () => getFrontMatterFromDocument, getFullYear: () => getFullYear, getMonth: () => getMonth, globMdExtension: () => globMdExtension, isCommittedFile: () => isCommittedFile, isEditable: () => isEditable, isSupportedFile: () => isSupportedFile, parseUserConfig: () => parseUserConfig, parseUserDir: () => parseUserDir, placeholderHelper: () => placeholderHelper, readUserConfigFile: () => readUserConfigFile, setDuration: () => setDuration, setLastModifiedDateOnSave: () => setLastModifiedDateOnSave, toMd: () => toMd, updateFrontMatter: () => updateFrontMatter }); module.exports = __toCommonJS(src_exports); // src/addFileExtension.ts var import_node_path = require("path"); var ensureMarkdownExtension = (fileName) => fileName.endsWith(".md") ? fileName : `${fileName}.md`; var globMdExtension = (dir) => dir.endsWith("*.md") ? dir : (0, import_node_path.join)(dir, "/**/*.md"); // src/commands/auto-front-matter.ts var import_node_fs = require("fs"); var import_node_path2 = require("path"); var import_node_process = __toESM(require("process"), 1); var import_prompts = require("@inquirer/prompts"); var import_cac = __toESM(require("cac"), 1); var import_chokidar = __toESM(require("chokidar"), 1); // package.json var version = "0.0.6"; // src/helpers/picocolors.ts var import_node_tty = __toESM(require("tty"), 1); var hasColors = import_node_tty.default.WriteStream.prototype.hasColors(); var formatter = (startCode, endCode) => hasColors ? (str) => `${startCode}${str}${endCode}` : (str) => str; var reset = (s) => `\x1B[0m${s}\x1B[0m`; var italic = formatter("\x1B[3m", "\x1B[23m"); var underline = formatter("\x1B[4m", "\x1B[24m"); var inverse = formatter("\x1B[7m", "\x1B[27m"); var hidden = formatter("\x1B[8m", "\x1B[28m"); var strikethrough = formatter("\x1B[9m", "\x1B[29m"); var black = formatter("\x1B[30m", "\x1B[39m"); var red = formatter("\x1B[31m", "\x1B[39m"); var green = formatter("\x1B[32m", "\x1B[39m"); var yellow = formatter("\x1B[33m", "\x1B[39m"); var blue = formatter("\x1B[34m", "\x1B[39m"); var magenta = formatter("\x1B[35m", "\x1B[39m"); var cyan = formatter("\x1B[36m", "\x1B[39m"); var white = formatter("\x1B[37m", "\x1B[39m"); var gray = formatter("\x1B[90m", "\x1B[39m"); var bgBlack = formatter("\x1B[40m", "\x1B[49m"); var bgRed = formatter("\x1B[41m", "\x1B[49m"); var bgGreen = formatter("\x1B[42m", "\x1B[49m"); var bgYellow = formatter("\x1B[43m", "\x1B[49m"); var bgBlue = formatter("\x1B[44m", "\x1B[49m"); var bgMagenta = formatter("\x1B[45m", "\x1B[49m"); var bgCyan = formatter("\x1B[46m", "\x1B[49m"); var bgWhite = formatter("\x1B[47m", "\x1B[49m"); var picocolors = { reset, italic, underline, inverse, hidden, strikethrough, black, red, green, yellow, blue, magenta, cyan, white, gray, bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite }; // src/commands/auto-front-matter.ts function autoFrontMatter() { const cli = (0, import_cac.default)("auto-front-matter"); cli.version(version).option("-c, --config ", "Set path to config file").help(); cli.command("watch [dir]", "Real time update your front-matter").action(watch); cli.command("create", "create a new Markdown file").action(createMdFromTemplate); cli.parse(); } function watch(dir) { const root = import_node_process.default.cwd(); const userConfig = readUserConfigFile(root, Notification); if (!userConfig) return; if (dir) { const dirname = parseUserDir(dir, root); userConfig.dirname = dirname; } const restart = () => { const watcher = import_chokidar.default.watch(userConfig.dirname, { ignored: /node_modules/, ignoreInitial: true }); watcher.on("change", async (path) => { const editFileName = (0, import_node_path2.basename)(path); const editFileContents = (0, import_node_fs.readFileSync)(path, "utf8"); const languageId = (0, import_node_path2.extname)(path).slice(1); const doc = updateFrontMatter({ workspaceFolder: root, userConfig, isSupportedFile: isSupportedFile(languageId), isEditable: isEditable(userConfig.dirname, userConfig.globOptions, editFileName), editFileName, editFileContents, lineCount: Infinity, isCommittedFile: await isCommittedFile(root, editFileName) }); if (doc) { (0, import_node_fs.writeFileSync)(path, doc, { encoding: "utf-8" }); watcher.close().then(() => { const relativePath = (0, import_node_path2.relative)(root, path); Notification.info(`${picocolors.green("Successfully")} file ${picocolors.bgCyan(picocolors.white(relativePath))} saved`); restart(); }); } }).on("error", (error) => Notification.error(`Watcher error: ${error}`)); }; restart(); Notification.info(`${picocolors.green("Start listening for changes to .md files")}`); } function createMdFromTemplate() { const root = import_node_process.default.cwd(); const userConfig = readUserConfigFile(root, Notification); if (!userConfig) return; (0, import_prompts.input)( { required: true, message: "Please input markdown's file name", default: `${getFullYear()}-${getMonth()}-${getDay()}.md` } ).then((answersFileName) => { const filePath = ensureMarkdownExtension(answersFileName); const absFilePath = (0, import_node_path2.join)(root, filePath); if ((0, import_node_fs.existsSync)(absFilePath)) { Notification.warning(`(${filePath}) file already exist.`); } else { const fileContents = toMd(userConfig.template.content ?? "", userConfig.template.data); (0, import_node_fs.writeFileSync)(absFilePath, fileContents, { encoding: "utf-8" }); Notification.info(`${picocolors.green("Successfully")} ${picocolors.blue(filePath)} file created.`); } }).catch((error) => { Notification.error(error); }); } autoFrontMatter(); // src/constant/index.ts var CONFIG_FILE_NAME = "frontmatter.json"; var WORDS_PER_MINUTE = 500; function GET_DEFAULT_FRONT_MATTER() { return { data: { date: new Date((/* @__PURE__ */ new Date()).toISOString()), author: "CondorHero", tags: ["hello", "world"], categories: "blog" }, content: "\n# Hello World!\n" }; } // src/convertFrontMatter.ts var import_gray_matter = __toESM(require("gray-matter"), 1); function getFrontMatterFromDocument(fileContents) { return (0, import_gray_matter.default)(fileContents); } function getArticleFromFrontMatter(article) { return import_gray_matter.default.stringify(article.content, article.data); } function toMd(content, data) { return import_gray_matter.default.stringify(content, data); } // src/createConfigFile.ts var import_node_fs2 = require("fs"); var import_node_path3 = require("path"); function createConfigFile(workspaceFolder) { const initialConfig = { name: CONFIG_FILE_NAME }; if (workspaceFolder) { const configPath = (0, import_node_path3.join)(workspaceFolder, CONFIG_FILE_NAME); if (!(0, import_node_fs2.existsSync)(configPath)) (0, import_node_fs2.writeFileSync)(configPath, JSON.stringify(initialConfig, null, 2), "utf8"); } } // src/formatDate.ts function getFullYear(date = /* @__PURE__ */ new Date()) { return date.getFullYear(); } function getMonth(date = /* @__PURE__ */ new Date()) { const month = date.getMonth(); return `${month + 1}`.padStart(2, "0"); } function getDay(date = /* @__PURE__ */ new Date()) { const days = date.getDate(); return `${days}`.padStart(2, "0"); } // src/git.ts var import_node_path4 = require("path"); var import_simple_git = __toESM(require("simple-git"), 1); async function isCommittedFile(workspaceFolder, fileName) { const git = (0, import_simple_git.default)(workspaceFolder); const statusResult = await git.status(); const filePath = (0, import_node_path4.isAbsolute)(fileName) ? fileName : (0, import_node_path4.join)(workspaceFolder, fileName); const editFile = statusResult.files.find( ({ path }) => (0, import_node_path4.join)(workspaceFolder, path) === filePath ); return editFile?.index === " " && editFile?.working_dir === "M"; } // src/isEditable.ts var import_fast_glob = __toESM(require("fast-glob"), 1); function isEditable(dirname, globOptions, absFileName) { const fileMatch = import_fast_glob.default.sync(dirname, globOptions); return fileMatch.includes(absFileName); } // src/isSupportedFile.ts function isSupportedFile(languageName) { const supportedLanguages = ["markdown", "mdx", "md"]; const languageId = languageName.toLowerCase(); return supportedLanguages.includes(languageId); } // src/notification.ts var Notification = class { static info(message, ...optionalParams) { console.info(`${message}`, ...optionalParams); return Promise.resolve("INFO"); } static error(message, ...optionalParams) { console.error(`${red(message)}`, ...optionalParams); return Promise.resolve("ERROR"); } static warning(message, ...optionalParams) { console.warn(`${yellow(message)}`, ...optionalParams); return Promise.resolve("WARNING"); } }; // src/parseUserDir.ts var import_node_path5 = require("path"); function parseUserDir(globDir, workspacePath) { if (Array.isArray(globDir)) { return globDir.map( (dirItem) => (0, import_node_path5.join)(workspacePath, globMdExtension(dirItem)) ); } if (typeof globDir === "string") return [(0, import_node_path5.join)(workspacePath, globMdExtension(globDir))]; return [(0, import_node_path5.join)(workspacePath, globMdExtension("."))]; } // src/placeholderHelper.ts function placeholderHelper(value) { if (typeof value === "string") { if (value.includes("{{now}}")) { const regex = /\{\{now\}\}/g; return new Date(value.replace(regex, (/* @__PURE__ */ new Date()).toISOString())); } if (value.includes("{{year}}")) { const regex = /\{\{year\}\}/g; value = value.replace(regex, getFullYear().toString()); } if (value.includes("{{month}}")) { const regex = /\{\{month\}\}/g; value = value.replace(regex, getMonth()); } if (value.includes("{{day}}")) { const regex = /\{\{day\}\}/g; value = value.replace(regex, getDay()); } return value; } return value; } // src/readUserConfigFile.ts var import_node_fs3 = require("fs"); var import_node_path6 = require("path"); function readUserConfigFile(workspaceFolder, Notification2) { const configPath = (0, import_node_path6.join)(workspaceFolder, CONFIG_FILE_NAME); if (configPath && (0, import_node_fs3.existsSync)(configPath)) { try { const localConfig = (0, import_node_fs3.readFileSync)(configPath, "utf8"); return parseUserConfig(localConfig, workspaceFolder); } catch { Notification2.error(`Please check your ${CONFIG_FILE_NAME} file`); } } else { Notification2.warning(`You have no ${CONFIG_FILE_NAME} file, please create ${CONFIG_FILE_NAME} file in your root project`); return void 0; } } function parseUserConfig(localConfig, workspaceFolder) { const userConfig = JSON.parse(localConfig); const defaultUserSetting = {}; defaultUserSetting.insertLastMod = userConfig.insertLastMod ?? true; defaultUserSetting.insertReadTime = userConfig.insertReadTime ?? true; defaultUserSetting.dirname = parseUserDir(userConfig.dirname, workspaceFolder); defaultUserSetting.wordsPerMinute = userConfig.wordsPerMinute ?? WORDS_PER_MINUTE; defaultUserSetting.newFileIsInsertLastMod = userConfig.newFileIsInsertLastMod ?? false; defaultUserSetting.newFileIsInsertReadTime = userConfig.newFileIsInsertReadTime ?? false; if (userConfig?.template?.data?.date) userConfig.template.data.date = placeholderHelper(userConfig.template.data.date); defaultUserSetting.template = userConfig.template ?? GET_DEFAULT_FRONT_MATTER(); return defaultUserSetting; } // src/setDuration.ts var import_reading_time = __toESM(require("reading-time"), 1); function setDuration(article, wordsPerMinute) { const duration = (0, import_reading_time.default)(article.content, { wordsPerMinute }).minutes; return { ...article, data: { ...article.data, duration: `${Math.ceil(duration)} min` } }; } // src/setLastModifiedDateOnSave.ts function setLastModifiedDateOnSave(article) { return { ...article, data: { ...article.data, lastmod: new Date((/* @__PURE__ */ new Date()).toISOString()) } }; } // src/updateFrontMatter.ts function updateFrontMatter({ isCommittedFile: isCommittedFile2, userConfig, editFileContents }) { const { newFileIsInsertLastMod, newFileIsInsertReadTime, wordsPerMinute, insertLastMod, insertReadTime } = userConfig; let article = getFrontMatterFromDocument(editFileContents); if (article && article.data && Object.keys(article.data).length) { delete article.data.duration; delete article.data.lastmod; if (!isCommittedFile2) { if (!newFileIsInsertLastMod && !newFileIsInsertReadTime) return; if (newFileIsInsertLastMod) article = setLastModifiedDateOnSave(article); if (newFileIsInsertReadTime) article = setDuration(article, wordsPerMinute); } else { if (insertLastMod) { article = setLastModifiedDateOnSave(article); } if (insertReadTime) { article = setDuration(article, wordsPerMinute); } } } return getArticleFromFrontMatter(article); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { CONFIG_FILE_NAME, GET_DEFAULT_FRONT_MATTER, Notification, WORDS_PER_MINUTE, autoFrontMatter, createConfigFile, ensureMarkdownExtension, getArticleFromFrontMatter, getDay, getFrontMatterFromDocument, getFullYear, getMonth, globMdExtension, isCommittedFile, isEditable, isSupportedFile, parseUserConfig, parseUserDir, placeholderHelper, readUserConfigFile, setDuration, setLastModifiedDateOnSave, toMd, updateFrontMatter });