import { main } from '../../bin/main.js'; import { htmlIsEqual } from '@markedjs/testutils'; import { resolve } from 'node:path'; import { describe, it, mock } from 'node:test'; import assert from 'node:assert'; import { exec, execFile } from 'node:child_process'; import { promisify } from 'node:util'; import { mkdtemp, readFile, rm, symlink, writeFile, access } from 'node:fs/promises'; import { tmpdir } from 'node:os'; const execAsync = promisify(exec); const execFileAsync = promisify(execFile); function createMocks() { const mocks = { stdout: '', stderr: '', code: null, stdin: { data: null, error: null, end: null, }, process: { cwd: mock.fn(() => '/cwd'), env: [], argv: [], stdout: { write: mock.fn((str, callback) => { mocks.stdout += str; callback?.(); }), }, stderr: { write: mock.fn((str, callback) => { mocks.stderr += str; callback?.(); }), }, stdin: { setEncoding: mock.fn(), on: mock.fn((method, func) => { mocks.stdin[method] = func; }), resume: mock.fn(), }, exit: mock.fn((code) => { mocks.code = code; }), }, }; return mocks; } function testInput({ args = [], stdin = '', stdinError = '', stdout = '', stderr = '', code = 0 } = {}) { return async() => { const mocks = createMocks(); mocks.process.argv = ['node', 'marked', ...args]; const mainPromise = main(mocks.process); if (typeof mocks.stdin.end === 'function') { if (stdin) { mocks.stdin.data(stdin); } if (stdinError) { mocks.stdin.error(stdinError); } mocks.stdin.end(); } await mainPromise; assert.ok(await htmlIsEqual(mocks.stdout, stdout)); assert.strictEqual(mocks.stderr, stderr); assert.strictEqual(mocks.code, code); }; } function fixturePath(filePath) { return resolve(import.meta.dirname, './fixtures', filePath); } async function execMarkedString(args, markdown) { const { stdout, stderr } = await execFileAsync(process.execPath, [ resolve(import.meta.dirname, '../../bin/marked.js'), ...args, '--string', markdown, ]); assert.strictEqual(stderr, ''); return stdout; } function execMarked({ args = '', stdin = '', stdout = '', stderr = '' }) { const execPath = resolve(import.meta.dirname, '../../bin/marked'); return async() => { let command = ''; if (stdin) { command += `node -e "process.stdout.write('${stdin}')" | `; } command += `node ${execPath}`; if (args) { command += ` ${args}`; } const res = await execAsync(command); assert.ok(await htmlIsEqual(res.stdout, stdout)); assert.strictEqual(res.stderr, stderr); }; } describe('bin/marked', () => { describe('required option values', () => { for (const option of ['-o', '--output', '-i', '--input', '-s', '--string', '-c', '--config']) { it(`rejects ${option} without a value`, testInput({ args: [option], stdin: '# ignored', stderr: `marked: option '${option}' requires an argument`, code: 1, })); } }); describe('output', () => { it('writes all error output before exiting when stderr is piped', async() => { const dir = await mkdtemp(resolve(tmpdir(), 'marked-stderr-')); try { const config = resolve(dir, 'config.cjs'); const message = 'config error '.repeat(131072); await writeFile(config, `module.exports = () => { throw new Error(${JSON.stringify(message)}); };\n`); await assert.rejects(execFileAsync(process.execPath, [ resolve(import.meta.dirname, '../../bin/marked.js'), '--config', config, '--string', '# test', ], { maxBuffer: 4 * 1024 * 1024 }), (err) => { assert.strictEqual(err.code, 1); assert.strictEqual(err.stdout, ''); assert.strictEqual(err.stderr.length, message.length); assert.strictEqual(err.stderr, message); return true; }); } finally { await rm(dir, { recursive: true, force: true }); } }); it('writes all output before exiting when stdout is piped', async() => { const dir = await mkdtemp(resolve(tmpdir(), 'marked-stdout-')); try { const input = resolve(dir, 'input.md'); const markdown = 'markdown output '.repeat(131072); await writeFile(input, markdown); const { stdout, stderr } = await execFileAsync(process.execPath, [ resolve(import.meta.dirname, '../../bin/marked.js'), '--input', input, ], { maxBuffer: 4 * 1024 * 1024 }); assert.strictEqual(stdout, `

${markdown}

\n\n`); assert.strictEqual(stderr, ''); } finally { await rm(dir, { recursive: true, force: true }); } }); it('does not follow an existing dangling symlink with --no-clobber', { skip: process.platform === 'win32' }, async() => { const dir = await mkdtemp(resolve(tmpdir(), 'marked-no-clobber-')); try { const output = resolve(dir, 'output.html'); const target = resolve(dir, 'target.html'); await symlink(target, output); await testInput({ args: ['--no-clobber', '--output', output, '--string', '# test'], stderr: `marked: output file '${output}' already exists, disable the '-n' / '--no-clobber' flag to overwrite\n`, code: 1, })(); await assert.rejects(access(target), { code: 'ENOENT' }); } finally { await rm(dir, { recursive: true, force: true }); } }); it('preserves an existing file with --no-clobber', async() => { const dir = await mkdtemp(resolve(tmpdir(), 'marked-no-clobber-')); try { const output = resolve(dir, 'output.html'); await writeFile(output, 'original'); await testInput({ args: ['--no-clobber', '--output', output, '--string', '# test'], stderr: `marked: output file '${output}' already exists, disable the '-n' / '--no-clobber' flag to overwrite\n`, code: 1, })(); assert.strictEqual(await readFile(output, 'utf8'), 'original'); } finally { await rm(dir, { recursive: true, force: true }); } }); for (const args of [[], ['--no-clobber']]) { it(`creates a new output file with ${args.join(' ') || 'default options'}`, async() => { const dir = await mkdtemp(resolve(tmpdir(), 'marked-no-clobber-')); try { const output = resolve(dir, 'output.html'); await testInput({ args: [...args, '--output', output, '--string', '# test'] })(); assert.strictEqual(await readFile(output, 'utf8'), '

test

\n'); } finally { await rm(dir, { recursive: true, force: true }); } }); } it('overwrites an existing output file by default', async() => { const dir = await mkdtemp(resolve(tmpdir(), 'marked-no-clobber-')); try { const output = resolve(dir, 'output.html'); await writeFile(output, 'original'); await testInput({ args: ['--output', output, '--string', '# test'] })(); assert.strictEqual(await readFile(output, 'utf8'), '

test

\n'); } finally { await rm(dir, { recursive: true, force: true }); } }); }); describe('string', () => { it('--string= accepts empty input instead of reading stdin', testInput({ args: ['--string='], stdin: '# ignored', stdout: '\n', })); it('-s', testInput({ args: ['-s', '# test'], stdout: '

test

', })); it('--string', testInput({ args: ['--string', '# test'], stdout: '

test

', })); it('--string accepts empty input instead of reading stdin', testInput({ args: ['--string', ''], stdin: '# ignored', stdout: '\n', })); }); describe('config', () => { it('uses GFM by default', async() => { const result = await execMarkedString([], '~~test~~'); assert.strictEqual(result, '

test

\n\n'); }); it('uses options from the config file in a separate process', async() => { const result = await execMarkedString(['--config', fixturePath('bin-config.js')], 'line1\nline2'); assert.strictEqual(result, '

line1
line2

\n\n'); }); it('uses a tokenizer from the config file', async() => { const result = await execMarkedString(['--config', fixturePath('bin-config-tokenizer.js')], '`test`'); assert.strictEqual(result, '

TEST

\n\n'); }); it('lets command-line options override config options', async() => { const result = await execMarkedString(['--config', fixturePath('bin-config.js'), '--no-breaks'], 'line1\nline2'); assert.strictEqual(result, '

line1\nline2

\n\n'); }); it('-c', testInput({ args: ['-c', fixturePath('bin-config.js'), '-s', 'line1\nline2'], stdout: '

line1
line2

', })); it('--config', testInput({ args: ['--config', fixturePath('bin-config.js'), '-s', 'line1\nline2'], stdout: '

line1
line2

', })); it('config path with hash', testInput({ args: ['--config', fixturePath('bin-config#hash.js'), '-s', 'line1\nline2'], stdout: '

line1
line2

', })); it('config with top-level await', testInput({ args: ['--config', fixturePath('bin-config-await.mjs'), '-s', 'line1\nline2'], stdout: '

line1
line2

', })); it('config with a synchronous function', testInput({ args: ['--config', fixturePath('bin-config-function.js'), '-s', 'line1\nline2'], stdout: '

line1
line2

', })); it('waits for an async config function', async() => { const { stdout, stderr } = await execFileAsync(process.execPath, [ resolve(import.meta.dirname, '../../bin/marked.js'), '--config', fixturePath('bin-config-async.mjs'), '--string', 'line1\nline2', ]); assert.strictEqual(stdout, '

line1
line2

\n\n'); assert.strictEqual(stderr, ''); }); it('reports a rejected config function', async() => { await assert.rejects(execFileAsync(process.execPath, [ resolve(import.meta.dirname, '../../bin/marked.js'), '--config', fixturePath('bin-config-reject.cjs'), '--string', '# test', ]), { code: 1, stdout: '', stderr: 'Async config failed', }); }); it('config not found', testInput({ args: ['--config', fixturePath('does-not-exist.js'), '-s', 'line1\nline2'], stderr: `Cannot load config file '${fixturePath('does-not-exist.js')}'`, code: 1, })); }); describe('tokens', () => { async function tokens(args, markdown) { const stdout = await execMarkedString(['--tokens', ...args], markdown); return JSON.parse(stdout); } it('uses GFM by default', async() => { const result = await tokens([], '~~test~~'); assert.strictEqual(result[0].tokens[0].type, 'del'); }); it('uses options from the config file', async() => { const result = await tokens(['--config', fixturePath('bin-config.js')], 'line1\nline2'); assert.deepStrictEqual(result[0].tokens.map(token => token.type), ['text', 'br', 'text']); }); it('uses a tokenizer from the config file', async() => { const result = await tokens(['--config', fixturePath('bin-config-tokenizer.js')], '`test`'); assert.strictEqual(result[0].tokens[0].type, 'codespan'); assert.strictEqual(result[0].tokens[0].text, 'TEST'); }); it('lets command-line options override config options', async() => { const result = await tokens(['--config', fixturePath('bin-config.js'), '--no-breaks'], 'line1\nline2'); assert.deepStrictEqual(result[0].tokens.map(token => token.type), ['text']); }); }); describe('input', () => { it('does not treat --=value as the end of options', testInput({ args: ['--=ignored', '--string', '# test'], stdout: '

test

', })); it('does not treat the value of an unknown --option=value as an input file', testInput({ args: ['--unknown=ignored'], stdin: '# test\n', stdout: '

test

', })); it('supports --option=false for boolean options without treating false as a file', testInput({ args: ['--gfm=false'], stdin: '~~text~~\n', stdout: '

~~text~~

', })); it('ignores prototype property names like --to-string without consuming the next argument', testInput({ args: ['--to-string', fixturePath('bin-input.md')], stdout: '

file

', })); for (const filename of ['-s.md', '--version']) { it(`treats ${filename} as a filename after --`, async() => { const dir = await mkdtemp(resolve(tmpdir(), 'marked-end-options-')); try { await writeFile(resolve(dir, filename), '~~file contents~~'); const { stdout, stderr } = await execFileAsync(process.execPath, [ resolve(import.meta.dirname, '../../bin/marked.js'), '--no-gfm', '--', filename, ], { cwd: dir }); assert.strictEqual(stdout, '

~~file contents~~

\n\n'); assert.strictEqual(stderr, ''); } finally { await rm(dir, { recursive: true, force: true }); } }); } it('input file positional', testInput({ args: [fixturePath('bin-input.md')], stdout: '

file

', })); it('input file not found', testInput({ args: [fixturePath('does-not-exist.md')], stderr: `marked: ${fixturePath('does-not-exist.md')}: No such file or directory`, code: 1, })); it('input file not found --input', testInput({ args: ['--input', fixturePath('does-not-exist.md')], stderr: `marked: ${fixturePath('does-not-exist.md')}: No such file or directory`, code: 1, })); it('reads from stdin when no files are provided', testInput({ stdin: '# test\n', stdout: '

test

', })); }); }); describe('exec', () => { it('stdin', execMarked({ stdin: '# test', stdout: '

test

', })); it('string', execMarked({ args: '-s "# test"', stdout: '

test

', })); it('input', execMarked({ args: `-i ${fixturePath('bin-input.md')}`, stdout: '

file

', })); it('input file positional', execMarked({ args: fixturePath('bin-input.md'), stdout: '

file

', })); it('input last file positional', execMarked({ args: `${fixturePath('does-not-exist.md')} ${fixturePath('bin-input.md')}`, stdout: '

file

', })); });