import fs from 'node:fs/promises'; import path from 'node:path'; import os from 'node:os'; const privateDirectory = /^(\.git|\.ssh|\.aws|\.azure|\.secrets|\.desktop-profile|System Volume Information|\$RECYCLE\.BIN)$/i; const fail = message => Object.assign(new Error(message), { status: 400 }); // This user-facing, authenticated picker reads one directory at a time. It // neither recursively scans the machine nor exposes a model filesystem tool. export async function localDirectories(input = '') { if (typeof input !== 'string' || input.length > 2000 || /[\x00-\x1f]/.test(input)) throw fail('文件夹路径无效。'); const requested = input || os.homedir(); if (!path.isAbsolute(requested) || process.platform === 'win32' && !/^[a-z]:[\\/]/i.test(requested)) throw fail('请输入本机文件夹的完整路径。'); let current; try { current = await fs.realpath(requested); if (!(await fs.stat(current)).isDirectory()) throw fail('请选择文件夹。'); } catch (cause) { throw fail(cause.code === 'EACCES' || cause.code === 'EPERM' ? '没有权限打开此文件夹,请选择其他位置。' : '文件夹不存在或无法访问,请检查路径。'); } const directories = []; let scanned = 0, truncated = false; try { const directory = await fs.opendir(current); for await (const entry of directory) { if (++scanned > 4000 || directories.length >= 1000) { truncated = true; break; } if (!entry.isDirectory() || entry.isSymbolicLink() || privateDirectory.test(entry.name)) continue; directories.push({ name: entry.name, path: path.join(current, entry.name) }); } } catch { throw fail('无法列出此文件夹,请选择其他位置或直接输入路径。'); } directories.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN', { numeric: true })); const candidates = [{ name: '用户文件夹', path: os.homedir() }, ...['Desktop', 'Documents', 'Downloads'].map((name, index) => ({ name: ['桌面', '文档', '下载'][index], path: path.join(os.homedir(), name) }))]; if (process.platform === 'win32') for (const drive of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') candidates.push({ name: drive + ':', path: drive + ':\\' }); else candidates.push({ name: '文件系统', path: '/' }); const bookmarks = (await Promise.all(candidates.map(async item => { try { return (await fs.stat(item.path)).isDirectory() ? item : null; } catch { return null; } }))).filter(Boolean); return { current, parent: path.dirname(current) === current ? null : path.dirname(current), directories, bookmarks, truncated }; }