import * as fs from 'fs'
import * as path from 'path'
import { RECORD_FILE_NAME } from './fileUtils.js'
/**
* Interface for compression record structure using relative paths.
*/
export interface CompressionRecord {
compressedFiles: {
[relativePath: string]: {
hash: string
size: number
mtime: number
compressedAt: string
originalSize: number
compressedSize: number
savings: number
}
}
lastUpdated: string
version: string
}
/**
* Read compression record from record.json file.
*
* @param directoryPath The path to the directory containing the record file.
* @returns Promise that resolves to the compression record or null if file doesn't exist.
*/
export async function readCompressionRecord(directoryPath: string): Promise<CompressionRecord | null> {
const recordPath = path.join(directoryPath, RECORD_FILE_NAME)
try {
if (!fs.existsSync(recordPath)) {
return null
}
const recordContent = await fs.promises.readFile(recordPath, 'utf-8')
const record = JSON.parse(recordContent) as CompressionRecord
/* Validate record structure */
if (record.version === '2.0' && typeof record.compressedFiles === 'object') {
return record
}
/* Invalid or unknown format, return null */
return null
} catch (error) {
/* Return null if record file is corrupted or cannot be read */
return null
}
}
/**
* Write compression record to record.json file.
*
* @param directoryPath The path to the directory to write the record file.
* @param record The compression record to write.
* @returns Promise that resolves when the record is written.
*/
export async function writeCompressionRecord(directoryPath: string, record: CompressionRecord): Promise<void> {
const recordPath = path.join(directoryPath, RECORD_FILE_NAME)
const recordContent = JSON.stringify(record, null, 2)
await fs.promises.writeFile(recordPath, recordContent, 'utf-8')
}