import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' import type { GitPluginPageData } from '@vuepress/plugin-git' import { describe, expect, it, vi } from 'vitest' import type { App, Page } from 'vuepress/core' import { createMarkdown } from 'vuepress/markdown' import type { MarkdownEnv } from 'vuepress/markdown' import { appendDateToPage } from '../../src/node/appendDate.js' import { appendDatePlugin } from '../../src/node/appendDatePlugin.js' import { getDateString, getFullDateString, getTimeString, } from '../../src/node/formatDate.js' import { logger } from '../../src/node/logger.js' import { normalizeAppendDateOptions } from '../../src/node/normalizeOptions.js' const CREATED_TIME = 1_700_000_000_000 const DATE_TEXT = getDateString(new Date(CREATED_TIME)) const TIME_TEXT = getTimeString(new Date(CREATED_TIME)) const FULL_DATE_TEXT = getFullDateString(new Date(CREATED_TIME)) const createTempDir = (): Promise => mkdtemp(path.join(tmpdir(), 'vuepress-append-date-')) const writeTempFile = async ( dir: string, name: string, content: string, ): Promise => { const filePath = path.join(dir, name) await writeFile(filePath, content, 'utf-8') return filePath } const createPage = ( filePath: string, frontmatter: Record = {}, ): Page => ({ filePath, frontmatter, data: { git: { createdTime: CREATED_TIME } }, }) as unknown as Page // A single frontmatter block has exactly two delimiter lines const countFrontmatterDelimiters = (content: string): number => content .replace(/^\uFEFF/u, '') .split(/\r?\n/u) .filter((line) => line === '---').length // An LF that is not part of a CRLF means the EOL style was mixed const hasLoneLf = (content: string): boolean => content.replaceAll('\r\n', '').includes('\n') // Parse frontmatter with the same VuePress markdown pipeline used by builds const parseFrontmatter = (content: string): Record => { const env: MarkdownEnv = {} createMarkdown().render(content, env) return env.frontmatter ?? {} } describe(appendDatePlugin, () => { it('should use the published package name as the plugin name', () => { expect(appendDatePlugin({}).name).toBe('@vuepress/plugin-append-date') }) it('should warn only once for multiple pages using time format with the date key', async () => { const dir = await createTempDir() const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) try { const pages = await Promise.all( ['one.md', 'two.md'].map(async (name) => createPage( await writeTempFile( dir, name, '---\ntitle: Hello\n---\n\nBody text\n', ), ), ), ) const plugin = appendDatePlugin({ format: 'time', key: 'date' }) const onInitialized = plugin.onInitialized as unknown as ( app: App, ) => Promise await onInitialized({ pages, pluginApi: { plugins: [{ name: '@vuepress/plugin-git' }] }, } as unknown as App) expect(warn).toHaveBeenCalledTimes(1) const contents = await Promise.all( pages.map((page) => readFile(page.filePath!, 'utf-8')), ) for (const content of contents) expect(content).toContain(`date: ${FULL_DATE_TEXT}`) } finally { warn.mockRestore() await rm(dir, { force: true, recursive: true }) } }) }) describe(normalizeAppendDateOptions, () => { it('should default to the date key and date format', () => { expect(normalizeAppendDateOptions({})).toStrictEqual({ key: 'date', format: 'date', }) }) it('should default to the time key for time format', () => { expect(normalizeAppendDateOptions({ format: 'time' })).toStrictEqual({ key: 'time', format: 'time', }) }) it('should keep an explicitly configured key for time format', () => { expect( normalizeAppendDateOptions({ format: 'time', key: 'updated' }), ).toStrictEqual({ key: 'updated', format: 'time', }) }) it('should fall back to full format for the date key in time format', () => { const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) try { expect( normalizeAppendDateOptions({ format: 'time', key: 'date' }), ).toStrictEqual({ key: 'date', format: 'full', }) expect(warn).toHaveBeenCalledTimes(1) expect(warn.mock.calls[0][0]).toContain('"full"') } finally { warn.mockRestore() } }) }) describe(appendDateToPage, () => { it('should prepend the date to LF frontmatter', async () => { const dir = await createTempDir() try { const original = '---\ntitle: Hello\nauthor: Test\n---\n\n# Heading\n\nBody text\n' const filePath = await writeTempFile(dir, 'lf.md', original) const page = createPage(filePath) await appendDateToPage({}, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe( `---\ndate: ${DATE_TEXT}\ntitle: Hello\nauthor: Test\n---\n\n# Heading\n\nBody text\n`, ) expect(countFrontmatterDelimiters(content)).toBe(2) expect(content).toContain('# Heading') expect(content).toContain('Body text') expect(page.frontmatter.date).toBeInstanceOf(Date) expect(page.frontmatter.date).toStrictEqual(new Date(CREATED_TIME)) } finally { await rm(dir, { force: true, recursive: true }) } }) it('should prepend the date to CRLF frontmatter and keep CRLF', async () => { const dir = await createTempDir() try { const original = '---\r\ntitle: Hello\r\nauthor: Test\r\n---\r\n\r\n# Heading\r\n\r\nBody text\r\n' const filePath = await writeTempFile(dir, 'crlf.md', original) const page = createPage(filePath) await appendDateToPage({}, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe( `---\r\ndate: ${DATE_TEXT}\r\ntitle: Hello\r\nauthor: Test\r\n---\r\n\r\n# Heading\r\n\r\nBody text\r\n`, ) expect(countFrontmatterDelimiters(content)).toBe(2) expect(content).toContain('# Heading') expect(content).toContain('Body text') expect(content).toContain('\r\n') expect(hasLoneLf(content)).toBe(false) expect(page.frontmatter.date).toBeInstanceOf(Date) expect(page.frontmatter.date).toStrictEqual(new Date(CREATED_TIME)) } finally { await rm(dir, { force: true, recursive: true }) } }) it('should prepend the date to BOM + LF frontmatter and keep the BOM', async () => { const dir = await createTempDir() try { const original = '\uFEFF---\ntitle: Hello\n---\n\n# Heading\n\nBody text\n' const filePath = await writeTempFile(dir, 'bom-lf.md', original) const page = createPage(filePath) await appendDateToPage({}, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe( `\uFEFF---\ndate: ${DATE_TEXT}\ntitle: Hello\n---\n\n# Heading\n\nBody text\n`, ) expect(countFrontmatterDelimiters(content)).toBe(2) expect(content.charCodeAt(0)).toBe(0xfe_ff) expect(content.indexOf('\uFEFF', 1)).toBe(-1) expect(content).toContain('# Heading') expect(page.frontmatter.date).toBeInstanceOf(Date) } finally { await rm(dir, { force: true, recursive: true }) } }) it('should prepend the date to BOM + CRLF frontmatter and keep the BOM and CRLF', async () => { const dir = await createTempDir() try { const original = '\uFEFF---\r\ntitle: Hello\r\n---\r\n\r\n# Heading\r\n\r\nBody text\r\n' const filePath = await writeTempFile(dir, 'bom-crlf.md', original) const page = createPage(filePath) await appendDateToPage({}, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe( `\uFEFF---\r\ndate: ${DATE_TEXT}\r\ntitle: Hello\r\n---\r\n\r\n# Heading\r\n\r\nBody text\r\n`, ) expect(countFrontmatterDelimiters(content)).toBe(2) expect(content.charCodeAt(0)).toBe(0xfe_ff) expect(content.indexOf('\uFEFF', 1)).toBe(-1) expect(hasLoneLf(content)).toBe(false) expect(page.frontmatter.date).toBeInstanceOf(Date) } finally { await rm(dir, { force: true, recursive: true }) } }) it('should create a frontmatter block when there is none', async () => { const dir = await createTempDir() try { const original = '# Heading\n\nBody text\n' const filePath = await writeTempFile(dir, 'no-frontmatter.md', original) const page = createPage(filePath) await appendDateToPage({}, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe( `---\ndate: ${DATE_TEXT}\n---\n\n# Heading\n\nBody text\n`, ) expect(countFrontmatterDelimiters(content)).toBe(2) expect(content.startsWith(`---\ndate: ${DATE_TEXT}\n---\n\n`)).toBe(true) expect(page.frontmatter.date).toBeInstanceOf(Date) expect(page.frontmatter.date).toStrictEqual(new Date(CREATED_TIME)) } finally { await rm(dir, { force: true, recursive: true }) } }) it('should hoist a leading BOM in front of a new frontmatter block', async () => { const dir = await createTempDir() try { const original = '\uFEFF# Heading\n\nBody text\n' const filePath = await writeTempFile( dir, 'no-frontmatter-bom.md', original, ) const page = createPage(filePath) await appendDateToPage({}, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe( `\uFEFF---\ndate: ${DATE_TEXT}\n---\n\n# Heading\n\nBody text\n`, ) expect(content.charCodeAt(0)).toBe(0xfe_ff) expect(content.indexOf('\uFEFF', 1)).toBe(-1) expect(countFrontmatterDelimiters(content)).toBe(2) expect(page.frontmatter.date).toBeInstanceOf(Date) } finally { await rm(dir, { force: true, recursive: true }) } }) it('should use the configured key for the appended date', async () => { const dir = await createTempDir() try { const original = '---\ntitle: Hello\n---\n\nBody text\n' const filePath = await writeTempFile(dir, 'custom-key.md', original) const page = createPage(filePath) await appendDateToPage({ key: 'updated' }, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe( `---\nupdated: ${DATE_TEXT}\ntitle: Hello\n---\n\nBody text\n`, ) expect(page.frontmatter.updated).toBeInstanceOf(Date) expect(page.frontmatter.date).toBeUndefined() } finally { await rm(dir, { force: true, recursive: true }) } }) it('should not touch the file when the frontmatter key is already set', async () => { const dir = await createTempDir() try { const original = '---\r\ndate: 2020-01-01\r\ntitle: Hello\r\n---\r\n\r\nBody text\r\n' const filePath = await writeTempFile(dir, 'existing-date.md', original) const existingDate = new Date('2020-01-01') const page = createPage(filePath, { date: existingDate }) await appendDateToPage({}, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe(original) expect(countFrontmatterDelimiters(content)).toBe(2) expect(page.frontmatter.date).toBe(existingDate) expect(page.frontmatter.date).not.toStrictEqual(new Date(CREATED_TIME)) } finally { await rm(dir, { force: true, recursive: true }) } }) it('should append quoted time under the time key by default in time format', async () => { const dir = await createTempDir() try { const original = '---\ntitle: Hello\n---\n\nBody text\n' const filePath = await writeTempFile(dir, 'time.md', original) const page = createPage(filePath) await appendDateToPage({ format: 'time' }, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe( `---\ntime: "${TIME_TEXT}"\ntitle: Hello\n---\n\nBody text\n`, ) expect(page.frontmatter.time).toBe(TIME_TEXT) expect(page.frontmatter.date).toBeUndefined() expect(parseFrontmatter(content).time).toBe(TIME_TEXT) } finally { await rm(dir, { force: true, recursive: true }) } }) it('should warn and append a full date when time format uses the date key', async () => { const dir = await createTempDir() const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) try { const original = '---\ntitle: Hello\n---\n\nBody text\n' const filePath = await writeTempFile(dir, 'time-date.md', original) const page = createPage(filePath) await appendDateToPage({ format: 'time', key: 'date' }, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe( `---\ndate: ${FULL_DATE_TEXT}\ntitle: Hello\n---\n\nBody text\n`, ) expect(page.frontmatter.date).toBeInstanceOf(Date) expect(page.frontmatter.date).toStrictEqual(new Date(CREATED_TIME)) expect(warn).toHaveBeenCalledTimes(1) } finally { warn.mockRestore() await rm(dir, { force: true, recursive: true }) } }) it('should append a full date that can be parsed back as Date', async () => { const dir = await createTempDir() try { const original = '---\ntitle: Hello\n---\n\nBody text\n' const filePath = await writeTempFile(dir, 'full.md', original) const page = createPage(filePath) await appendDateToPage({ format: 'full' }, page) const content = await readFile(filePath, 'utf-8') expect(FULL_DATE_TEXT).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/u) expect(new Date(FULL_DATE_TEXT).getTime()).toBe(CREATED_TIME) expect(content).toBe( `---\ndate: ${FULL_DATE_TEXT}\ntitle: Hello\n---\n\nBody text\n`, ) expect(page.frontmatter.date).toBeInstanceOf(Date) expect(page.frontmatter.date).toStrictEqual(new Date(CREATED_TIME)) const parsedFrontmatter = parseFrontmatter(content) expect(parsedFrontmatter.date).toBeInstanceOf(Date) expect(parsedFrontmatter.date).toStrictEqual(new Date(CREATED_TIME)) } finally { await rm(dir, { force: true, recursive: true }) } }) it('should warn about an existing quoted time-only date without touching the file', async () => { const dir = await createTempDir() const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) try { const original = '---\ndate: "12:34:56"\ntitle: Hello\n---\n\nBody text\n' const filePath = await writeTempFile(dir, 'existing-time.md', original) const page = createPage(filePath, { date: '12:34:56' }) await appendDateToPage({}, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe(original) expect(page.frontmatter.date).toBe('12:34:56') expect(warn).toHaveBeenCalledTimes(1) } finally { warn.mockRestore() await rm(dir, { force: true, recursive: true }) } }) it('should warn about an existing unquoted time-only date without touching the file', async () => { const dir = await createTempDir() const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) try { const original = '---\ndate: 12:34:56\ntitle: Hello\n---\n\nBody text\n' const filePath = await writeTempFile( dir, 'existing-unquoted-time.md', original, ) // js-yaml 3 parses 12:34:56 as the sexagesimal number 45296 const page = createPage(filePath, { date: 45_296 }) await appendDateToPage({}, page) const content = await readFile(filePath, 'utf-8') expect(content).toBe(original) expect(page.frontmatter.date).toBe(45_296) expect(warn).toHaveBeenCalledTimes(1) } finally { warn.mockRestore() await rm(dir, { force: true, recursive: true }) } }) })