diff --git a/docs/options/cleaning.md b/docs/options/cleaning.md index ebee8103e..f268e624f 100644 --- a/docs/options/cleaning.md +++ b/docs/options/cleaning.md @@ -10,3 +10,5 @@ tsdown --no-clean > [!NOTE] > By default, all files in the output directory will be removed before the build process begins. Make sure this behavior aligns with your project requirements to avoid accidentally deleting important files. +> +> Paths outside the project root are never cleaned, and tsdown does not delete files through a symbolic link that points outside the project root. If tsdown skips a matched path for this reason, it logs a warning. diff --git a/docs/zh-CN/options/cleaning.md b/docs/zh-CN/options/cleaning.md index ba17f7e81..97fe7eef0 100644 --- a/docs/zh-CN/options/cleaning.md +++ b/docs/zh-CN/options/cleaning.md @@ -10,3 +10,5 @@ tsdown --no-clean > [!NOTE] > 默认情况下,输出目录中的所有文件将在构建过程开始之前被删除。请确保此行为符合您的项目需求,以避免意外删除重要文件。 +> +> 项目根目录之外的路径永远不会被清理,`tsdown` 也不会通过指向项目根目录之外的符号链接删除文件。如果 `tsdown` 因此跳过了匹配到的路径,会输出警告。 diff --git a/schema.json b/schema.json index 315e902af..71a02cb56 100644 --- a/schema.json +++ b/schema.json @@ -155,7 +155,7 @@ { "const": true }, { "type": "array", "items": { "type": "string" } } ], - "description": "Clean directories before build.\n\nDefault to output directory.", + "description": "Clean directories before build.\n\nDefault to output directory.\n\nPaths outside the project root are never cleaned.", "default": true }, "minify": { @@ -523,7 +523,7 @@ { "const": true }, { "type": "array", "items": { "type": "string" } } ], - "description": "Clean directories before build.\n\nDefault to output directory.", + "description": "Clean directories before build.\n\nDefault to output directory.\n\nPaths outside the project root are never cleaned.", "default": true }, "minify": { diff --git a/skills/tsdown/references/option-cleaning.md b/skills/tsdown/references/option-cleaning.md index 9afa0f806..c3f8f79ef 100644 --- a/skills/tsdown/references/option-cleaning.md +++ b/skills/tsdown/references/option-cleaning.md @@ -57,6 +57,10 @@ export default defineConfig({ - Preserving other files - Watch mode (faster rebuilds) +### Paths Outside the Project Root + +tsdown never cleans paths outside the project root, and it does not delete files through a symbolic link that points outside the project root. Files reached through a symbolic link that points inside the project root are cleaned as usual. If a pattern matches a symbolic link itself, tsdown removes the link and keeps its target. If tsdown skips a matched path for this reason, it logs a warning. The `outDir` directory itself is never removed, only its contents. + ## Common Patterns ### Production Build diff --git a/src/config/types.ts b/src/config/types.ts index 1ce0d28a2..daecdf088 100644 --- a/src/config/types.ts +++ b/src/config/types.ts @@ -397,6 +397,8 @@ export interface UserConfig { * Clean directories before build. * * Default to output directory. + * + * Paths outside the project root are never cleaned. * @default true */ clean?: boolean | string[] diff --git a/src/features/clean.ts b/src/features/clean.ts index 5ab936b03..a8ca189b6 100644 --- a/src/features/clean.ts +++ b/src/features/clean.ts @@ -1,3 +1,4 @@ +import { realpath } from 'node:fs/promises' import path from 'node:path' import { createDebug } from 'obug' import { glob } from 'tinyglobby' @@ -33,13 +34,34 @@ export async function cleanOutDir(configs: ResolvedConfig[]): Promise { }) const normalizedOutDir = config.outDir.replace(RE_LAST_SLASH, '') + const realCwd = await realpath(config.cwd) + const realDirs = new Map>() + const skipped = new Set() for (const file of files) { const normalizedFile = file.replace(RE_LAST_SLASH, '') - if (normalizedFile !== normalizedOutDir) { - removes.add(file) + if (normalizedFile === normalizedOutDir) continue + if ( + !isInsideDir(normalizedFile, config.cwd) || + !(await isRealPathInside(normalizedFile, realCwd, realDirs)) + ) { + skipped.add(normalizedFile) + continue } + removes.add(file) + } + + if (skipped.size) { + const shown = [...skipped].slice(0, 5).map((file) => ` - ${file}`) + if (skipped.size > shown.length) { + shown.push(` ...and ${skipped.size - shown.length} more`) + } + config.logger.warn( + config.nameLabel, + `Skipped cleaning ${skipped.size} path(s) outside the project root:\n${shown.join('\n')}`, + ) } } + if (!removes.size) return globalLogger.info(`Cleaning ${removes.size} files`) @@ -52,6 +74,38 @@ export async function cleanOutDir(configs: ResolvedConfig[]): Promise { debug('Removed %d files', removes.size) } +/** + * Checks the real location of `file` without following `file` itself, so a + * symlink inside the root is removed as a link, and nothing is removed through + * a symlinked parent directory that resolves outside the root. + */ +async function isRealPathInside( + file: string, + realCwd: string, + realDirs: Map>, +): Promise { + const dir = path.dirname(file) + let realDir = realDirs.get(dir) + if (!realDir) { + realDir = realpath(dir).catch(() => undefined) + realDirs.set(dir, realDir) + } + const resolved = await realDir + return ( + !!resolved && isInsideDir(path.join(resolved, path.basename(file)), realCwd) + ) +} + +function isInsideDir(file: string, dir: string): boolean { + const relative = path.relative(dir, file) + return ( + !!relative && + relative !== '..' && + !relative.startsWith(`..${path.sep}`) && + !path.isAbsolute(relative) + ) +} + export function resolveClean( clean: UserConfig['clean'], outDir: string, diff --git a/tests/__snapshots__/clean/should-not-clean-paths-outside-the-project-root.snap.md b/tests/__snapshots__/clean/should-not-clean-paths-outside-the-project-root.snap.md new file mode 100644 index 000000000..de6629e3f --- /dev/null +++ b/tests/__snapshots__/clean/should-not-clean-paths-outside-the-project-root.snap.md @@ -0,0 +1,8 @@ +## index.mjs + +```mjs +// index.ts +const hello = "world"; +export { hello }; + +``` diff --git a/tests/clean.test.ts b/tests/clean.test.ts index 2b25cf6b8..3bc73cb30 100644 --- a/tests/clean.test.ts +++ b/tests/clean.test.ts @@ -1,9 +1,24 @@ -import { mkdir, writeFile } from 'node:fs/promises' +import { lstat, mkdir, rm, symlink, writeFile } from 'node:fs/promises' import path from 'node:path' -import { describe, expect, test } from 'vitest' +import process from 'node:process' +import { describe, expect, test, vi, type TestContext } from 'vitest' import { fsExists } from '../src/utils/fs.ts' import { getTestDir, testBuild } from './utils.ts' +async function createOutsideDir( + context: TestContext, + testDir: string, +): Promise { + const outsidePath = `${testDir}-outside` + await rm(outsidePath, { recursive: true, force: true }) + context.onTestFinished(() => + rm(outsidePath, { recursive: true, force: true }), + ) + await mkdir(outsidePath, { recursive: true }) + await writeFile(path.join(outsidePath, 'keep.txt'), 'keep me') + return outsidePath +} + describe('clean', () => { test('should clean dist directory by default', async (context) => { const files = { @@ -159,6 +174,180 @@ describe('clean', () => { ).rejects.toThrow('Cannot clean the current working directory') }) + test('should not clean paths outside the project root', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + + await testBuild({ + context, + files, + options: { + clean: [`../${path.basename(outsidePath)}`], + }, + }) + + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }) + + test('should warn through the configured logger when skipping paths', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + const warn = vi.fn() + + await testBuild({ + context, + files, + options: { + clean: [`../${path.basename(outsidePath)}`], + customLogger: { + level: 'info', + info: vi.fn(), + warn, + warnOnce: vi.fn(), + error: vi.fn(), + success: vi.fn(), + clearScreen: vi.fn(), + }, + }, + snapshot: false, + }) + + const messages = warn.mock.calls + .flat() + .filter((arg) => typeof arg === 'string') + expect( + messages.some((message) => + message.includes('Skipped cleaning 2 path(s) outside the project root'), + ), + ).toBe(true) + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }) + + test('should not clean outDir outside the project root', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + + await testBuild({ + context, + files, + options: { + outDir: `../${path.basename(outsidePath)}`, + }, + snapshot: false, + }) + + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }) + + test('should not clean through a symlinked directory', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + await mkdir(path.join(testDir, 'temp'), { recursive: true }) + await symlink(outsidePath, path.join(testDir, 'temp', 'link'), 'junction') + + await testBuild({ + context, + files, + options: { + clean: ['temp/*/keep.txt'], + }, + snapshot: false, + }) + + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }) + + test('should not clean under a symlinked parent directory', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + await mkdir(path.join(outsidePath, 'session'), { recursive: true }) + await writeFile(path.join(outsidePath, 'session', 'keep.txt'), 'keep me') + await mkdir(testDir, { recursive: true }) + await symlink(outsidePath, path.join(testDir, 'cache'), 'junction') + + await testBuild({ + context, + files, + options: { + clean: ['cache/session/**'], + }, + snapshot: false, + }) + + expect(await fsExists(path.join(outsidePath, 'session', 'keep.txt'))).toBe( + true, + ) + }) + + test.skipIf(process.platform === 'win32')( + 'should remove a symlink itself, not its target', + async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + const linkPath = path.join(testDir, 'temp', 'link') + await mkdir(path.dirname(linkPath), { recursive: true }) + await symlink(path.join(outsidePath, 'keep.txt'), linkPath) + + await testBuild({ + context, + files, + options: { + clean: ['temp/link'], + }, + snapshot: false, + }) + + await expect(lstat(linkPath)).rejects.toThrow() + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }, + ) + + test('should clean a directory whose name starts with ..', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const dotDotPath = path.join(testDir, '..cache') + await mkdir(dotDotPath, { recursive: true }) + await writeFile(path.join(dotDotPath, 'old.txt'), 'old') + + await testBuild({ + context, + files, + options: { + clean: ['..cache'], + }, + snapshot: false, + }) + + expect(await fsExists(dotDotPath)).toBe(false) + }) + test('should clean nested directories', async (context) => { const files = { 'index.ts': 'export const hello = "world"',