import { promises as fs } from 'node:fs';
import { join } from 'node:path';
import { formatError } from '../utils/error-formatter.js';
/**
 * Reject `.` / `..` and any entry containing a path separator. Mirrors the
 * defensive check duplicated in the existing custom-tools and
 * custom-commands loaders.
 */
function isSafeEntry(entry) {
    return (entry !== '..' &&
        entry !== '.' &&
        !entry.includes('/') &&
        !entry.includes('\\'));
}
function errorMessage(err) {
    return formatError(err);
}
export async function loadMdDir(dir, parse) {
    const result = { entries: [], errors: [] };
    let entries;
    try {
        entries = await fs.readdir(dir);
    }
    catch (err) {
        const code = err.code;
        if (code === 'ENOENT' || code === 'ENOTDIR')
            return result;
        result.errors.push({ filePath: dir, error: errorMessage(err) });
        return result;
    }
    for (const entry of entries) {
        if (!isSafeEntry(entry))
            continue;
        if (!entry.endsWith('.md'))
            continue;
        const filePath = join(dir, entry);
        try {
            const stat = await fs.stat(filePath);
            if (!stat.isFile())
                continue;
        }
        catch {
            continue;
        }
        try {
            const parsed = await parse(filePath);
            result.entries.push({ filePath, parsed });
        }
        catch (err) {
            result.errors.push({ filePath, error: errorMessage(err) });
        }
    }
    return result;
}
//# sourceMappingURL=load-md-dir.js.map