58 lines
2.0 KiB
TypeScript
58 lines
2.0 KiB
TypeScript
import path from 'path'
|
|
import { lstat } from 'fs/promises'
|
|
import { normalizeSafeFileName } from './path-security'
|
|
|
|
export function getUploadStorageExtension(fileName: string): string {
|
|
const extension = path.extname(fileName)
|
|
return /^\.[A-Za-z0-9]{1,16}$/.test(extension) ? extension : ''
|
|
}
|
|
|
|
export async function inspectUploadOutput(
|
|
directory: string,
|
|
storageStem: string,
|
|
legacyPrefix: string,
|
|
fileName: string,
|
|
) {
|
|
const outputPath = path.join(directory, `${storageStem}${getUploadStorageExtension(fileName) || '.bin'}`)
|
|
const paths = [outputPath]
|
|
const legacyName = `${legacyPrefix}${fileName}`
|
|
if (normalizeSafeFileName(legacyName) === legacyName) {
|
|
const legacyPath = path.join(directory, legacyName)
|
|
if (legacyPath !== outputPath) paths.push(legacyPath)
|
|
}
|
|
// 保留重试时对升级前已合并产物的引用。
|
|
for (const filePath of paths) {
|
|
const stats = await lstat(filePath).catch((error: NodeJS.ErrnoException) => {
|
|
if (error.code === 'ENOENT') return null
|
|
throw error
|
|
})
|
|
if (stats) return { outputPath, existing: { filePath, stats } }
|
|
}
|
|
return { outputPath, existing: null }
|
|
}
|
|
|
|
export function buildStoredUploadPath(...segments: string[]) {
|
|
return path.posix.join('uploads', ...segments.map((segment) => String(segment || '').replace(/\\/g, '/')))
|
|
}
|
|
|
|
export function getUploadRootDir(): string {
|
|
const configuredUploadDir = String(process.env.UPLOAD_DIR || '').trim()
|
|
if (!configuredUploadDir) {
|
|
return path.join(process.cwd(), 'uploads')
|
|
}
|
|
|
|
return path.isAbsolute(configuredUploadDir)
|
|
? configuredUploadDir
|
|
: path.resolve(process.cwd(), configuredUploadDir)
|
|
}
|
|
|
|
export function resolveStoredUploadPath(storedPath: string): string {
|
|
const normalizedPath = String(storedPath || '').replace(/\\/g, '/')
|
|
if (path.isAbsolute(normalizedPath)) {
|
|
return normalizedPath
|
|
}
|
|
|
|
const relativeToUploadRoot = normalizedPath.replace(/^\.?\/*uploads\//i, '')
|
|
return path.join(getUploadRootDir(), relativeToUploadRoot)
|
|
}
|