import path from 'node:path';
import { wrappedFs as fs } from './wrapped-fs.js';
import { Pickle } from './pickle.js';
import { Filesystem } from './filesystem.js';
import { ensureWithin } from './path-validation.js';
import stream from 'node:stream/promises';
let filesystemCache = Object.create(null);
class HeaderValidationError extends Error {
    constructor(path, message) {
        super(`Invalid archive header at "${path}": ${message}`);
        this.name = 'HeaderValidationError';
    }
}
function validateFileEntry(entry, entryPath) {
    if (typeof entry.offset !== 'string') {
        throw new HeaderValidationError(entryPath, `"offset" must be a string, got ${typeof entry.offset}`);
    }
    if (!/^\d+$/.test(entry.offset)) {
        throw new HeaderValidationError(entryPath, `"offset" must be a numeric string, got "${entry.offset}"`);
    }
    if (typeof entry.size !== 'number' || !Number.isFinite(entry.size) || entry.size < 0) {
        throw new HeaderValidationError(entryPath, `"size" must be a non-negative number, got ${JSON.stringify(entry.size)}`);
    }
    if (entry.unpacked !== undefined && typeof entry.unpacked !== 'boolean') {
        throw new HeaderValidationError(entryPath, `"unpacked" must be a boolean, got ${typeof entry.unpacked}`);
    }
    if (entry.executable !== undefined && typeof entry.executable !== 'boolean') {
        throw new HeaderValidationError(entryPath, `"executable" must be a boolean, got ${typeof entry.executable}`);
    }
    if (entry.integrity !== undefined) {
        validateIntegrity(entry.integrity, entryPath);
    }
}
function validateUnpackedFileEntry(entry, entryPath) {
    if (typeof entry.size !== 'number' || !Number.isFinite(entry.size) || entry.size < 0) {
        throw new HeaderValidationError(entryPath, `"size" must be a non-negative number, got ${JSON.stringify(entry.size)}`);
    }
    if (entry.unpacked !== true) {
        throw new HeaderValidationError(entryPath, `"unpacked" must be true for unpacked file entries`);
    }
    if (entry.executable !== undefined && typeof entry.executable !== 'boolean') {
        throw new HeaderValidationError(entryPath, `"executable" must be a boolean, got ${typeof entry.executable}`);
    }
    if (entry.integrity !== undefined) {
        validateIntegrity(entry.integrity, entryPath);
    }
}
function validateIntegrity(integrity, entryPath) {
    if (typeof integrity !== 'object' || integrity === null || Array.isArray(integrity)) {
        throw new HeaderValidationError(entryPath, `"integrity" must be an object`);
    }
    const rec = integrity;
    if (typeof rec.algorithm !== 'string') {
        throw new HeaderValidationError(entryPath, `"integrity.algorithm" must be a string`);
    }
    if (typeof rec.hash !== 'string') {
        throw new HeaderValidationError(entryPath, `"integrity.hash" must be a string`);
    }
    if (typeof rec.blockSize !== 'number' || !Number.isFinite(rec.blockSize) || rec.blockSize <= 0) {
        throw new HeaderValidationError(entryPath, `"integrity.blockSize" must be a positive number`);
    }
    if (!Array.isArray(rec.blocks)) {
        throw new HeaderValidationError(entryPath, `"integrity.blocks" must be an array`);
    }
    for (let i = 0; i < rec.blocks.length; i++) {
        if (typeof rec.blocks[i] !== 'string') {
            throw new HeaderValidationError(entryPath, `"integrity.blocks[${i}]" must be a string`);
        }
    }
}
function validateLinkEntry(entry, entryPath) {
    if (typeof entry.link !== 'string') {
        throw new HeaderValidationError(entryPath, `"link" must be a string, got ${typeof entry.link}`);
    }
    if (entry.link.length === 0) {
        throw new HeaderValidationError(entryPath, `"link" must not be empty`);
    }
}
function validateDirectoryEntry(entry, entryPath) {
    if (typeof entry.files !== 'object' || entry.files === null || Array.isArray(entry.files)) {
        throw new HeaderValidationError(entryPath, `"files" must be a plain object`);
    }
    const files = entry.files;
    for (const [name, child] of Object.entries(files)) {
        if (name.includes('/') || name.includes('\\') || name === '.' || name === '..') {
            throw new HeaderValidationError(entryPath, `invalid entry name "${name}"`);
        }
        const childPath = entryPath === '/' ? `/${name}` : `${entryPath}/${name}`;
        validateHeaderEntry(child, childPath);
    }
}
function validateHeaderEntry(entry, entryPath) {
    if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
        throw new HeaderValidationError(entryPath, 'entry must be an object');
    }
    const rec = entry;
    if ('link' in rec) {
        validateLinkEntry(rec, entryPath);
    }
    else if ('files' in rec) {
        validateDirectoryEntry(rec, entryPath);
    }
    else if ('offset' in rec) {
        validateFileEntry(rec, entryPath);
    }
    else if ('unpacked' in rec && rec.unpacked === true && 'size' in rec) {
        validateUnpackedFileEntry(rec, entryPath);
    }
    else {
        throw new HeaderValidationError(entryPath, 'entry must be a directory (with "files"), a file (with "offset" or "unpacked"), or a link (with "link")');
    }
}
export function validateHeader(header) {
    if (typeof header !== 'object' || header === null || Array.isArray(header)) {
        throw new HeaderValidationError('/', 'header must be an object');
    }
    const rec = header;
    if (!('files' in rec)) {
        throw new HeaderValidationError('/', 'root header must be a directory with a "files" property');
    }
    validateDirectoryEntry(rec, '/');
}
async function copyFile(dest, src, filename) {
    const srcFile = path.join(src, filename);
    const targetFile = path.join(dest, filename);
    const [content, stats] = await Promise.all([
        fs.readFile(srcFile),
        fs.stat(srcFile),
        fs.mkdirp(path.dirname(targetFile)),
    ]);
    return fs.writeFile(targetFile, content, { mode: stats.mode });
}
async function streamTransformedFile(stream, outStream) {
    return new Promise((resolve, reject) => {
        stream.pipe(outStream, { end: false });
        stream.on('error', reject);
        stream.on('end', () => resolve());
    });
}
const writeFileListToStream = async function (dest, filesystem, out, lists, metadata) {
    const { files, links } = lists;
    // Batch cached buffers into a single write to avoid per-file write syscalls
    let pendingBuffers = [];
    const flushPendingBuffers = async () => {
        if (pendingBuffers.length === 0)
            return;
        const combined = pendingBuffers.length === 1 ? pendingBuffers[0] : Buffer.concat(pendingBuffers);
        pendingBuffers = [];
        await new Promise((resolve, reject) => {
            out.write(combined, (err) => (err ? reject(err) : resolve()));
        });
    };
    for (const file of files) {
        if (file.unpack) {
            await flushPendingBuffers();
            const filename = path.relative(filesystem.getRootPath(), file.filename);
            await copyFile(`${dest}.unpacked`, filesystem.getRootPath(), filename);
        }
        else {
            const fileMeta = metadata[file.filename];
            if (fileMeta.cachedBuffer) {
                pendingBuffers.push(fileMeta.cachedBuffer);
                fileMeta.cachedBuffer = undefined;
            }
            else {
                await flushPendingBuffers();
                const transformed = fileMeta.transformed;
                const stream = fs.createReadStream(transformed ? transformed.path : file.filename);
                await streamTransformedFile(stream, out);
            }
        }
    }
    await flushPendingBuffers();
    for (const file of links.filter((f) => f.unpack)) {
        const filename = path.relative(filesystem.getRootPath(), file.filename);
        const link = await fs.readlink(file.filename);
        await createSymlink(dest, filename, link);
    }
    return new Promise((resolve, reject) => {
        out.on('error', reject);
        out.end(() => resolve());
    });
};
export async function writeFilesystem(dest, filesystem, lists, metadata) {
    const out = await createFilesystemWriteStream(filesystem, dest);
    return writeFileListToStream(dest, filesystem, out, lists, metadata);
}
export async function streamFilesystem(dest, filesystem, lists) {
    const out = await createFilesystemWriteStream(filesystem, dest);
    const { files, links } = lists;
    for await (const file of files) {
        // the file should not be packed into archive
        if (file.unpack) {
            const targetFile = path.join(`${dest}.unpacked`, file.filename);
            await fs.mkdirp(path.dirname(targetFile));
            const writeStream = fs.createWriteStream(targetFile, { mode: file.mode });
            await stream.pipeline(file.streamGenerator(), writeStream);
        }
        else {
            await streamTransformedFile(file.streamGenerator(), out);
        }
    }
    for (const file of links.filter((f) => f.unpack && f.link)) {
        // the symlink needs to be recreated outside in .unpacked
        await createSymlink(dest, file.filename, file.link);
    }
    return new Promise((resolve, reject) => {
        out.on('error', reject);
        out.end(() => resolve());
    });
}
export function readArchiveHeaderSync(archivePath) {
    const fd = fs.openSync(archivePath, 'r');
    let size;
    let headerBuf;
    try {
        const archiveSize = fs.fstatSync(fd).size;
        const sizeBuf = Buffer.alloc(8);
        if (fs.readSync(fd, sizeBuf, 0, 8, null) !== 8) {
            throw new Error('Unable to read header size');
        }
        const sizePickle = Pickle.createFromBuffer(sizeBuf);
        size = sizePickle.createIterator().readUInt32();
        if (size < 0 || size > archiveSize - 8) {
            throw new Error(`Header size ${size} exceeds archive size ${archiveSize}. The archive is corrupted.`);
        }
        headerBuf = Buffer.alloc(size);
        if (fs.readSync(fd, headerBuf, 0, size, null) !== size) {
            throw new Error('Unable to read header');
        }
    }
    finally {
        fs.closeSync(fd);
    }
    const headerPickle = Pickle.createFromBuffer(headerBuf);
    const header = headerPickle.createIterator().readString();
    const parsedHeader = JSON.parse(header);
    validateHeader(parsedHeader);
    return { headerString: header, header: parsedHeader, headerSize: size };
}
export function readFilesystemSync(archivePath) {
    if (!filesystemCache[archivePath]) {
        const header = readArchiveHeaderSync(archivePath);
        const filesystem = new Filesystem(archivePath);
        filesystem.setHeader(header.header, header.headerSize);
        filesystemCache[archivePath] = filesystem;
    }
    return filesystemCache[archivePath];
}
export function uncacheFilesystem(archivePath) {
    if (filesystemCache[archivePath]) {
        filesystemCache[archivePath] = undefined;
        return true;
    }
    return false;
}
export function uncacheAll() {
    filesystemCache = {};
}
export function readFileSync(filesystem, filename, info) {
    if (info.size <= 0) {
        return Buffer.alloc(0);
    }
    if (info.unpacked) {
        // it's an unpacked file, copy it.
        const unpackedDir = `${filesystem.getRootPath()}.unpacked`;
        return fs.readFileSync(ensureWithin(unpackedDir, filename));
    }
    // Node throws an exception when reading 0 bytes into a 0-size buffer,
    // so we short-circuit the read in this case.
    const fd = fs.openSync(filesystem.getRootPath(), 'r');
    try {
        const fileOffset = parseInt(info.offset);
        if (Number.isNaN(fileOffset) || fileOffset < 0 || !Number.isSafeInteger(fileOffset)) {
            throw new Error(`Invalid file offset in archive header: ${info.offset}`);
        }
        const offset = 8 + filesystem.getHeaderSize() + fileOffset;
        if (!Number.isSafeInteger(offset)) {
            throw new Error(`Computed offset exceeds safe integer range`);
        }
        const archiveSize = fs.fstatSync(fd).size;
        if (offset < 0 || offset + info.size > archiveSize) {
            throw new Error(`File entry extends beyond archive boundary (offset=${offset}, size=${info.size}, archiveSize=${archiveSize})`);
        }
        const buffer = Buffer.alloc(info.size);
        fs.readSync(fd, buffer, 0, info.size, offset);
        return buffer;
    }
    finally {
        fs.closeSync(fd);
    }
}
export function readFileWithFd(fd, filesystem, filename, info) {
    let buffer = Buffer.alloc(info.size);
    if (info.size <= 0) {
        return buffer;
    }
    if (info.unpacked) {
        const unpackedDir = `${filesystem.getRootPath()}.unpacked`;
        buffer = fs.readFileSync(ensureWithin(unpackedDir, filename));
    }
    else {
        const offset = 8 + filesystem.getHeaderSize() + parseInt(info.offset);
        fs.readSync(fd, buffer, 0, info.size, offset);
    }
    return buffer;
}
async function createFilesystemWriteStream(filesystem, dest) {
    const headerPickle = Pickle.createEmpty();
    headerPickle.writeString(JSON.stringify(filesystem.getHeader()));
    const headerBuf = headerPickle.toBuffer();
    const sizePickle = Pickle.createEmpty();
    sizePickle.writeUInt32(headerBuf.length);
    const sizeBuf = sizePickle.toBuffer();
    const out = fs.createWriteStream(dest);
    await new Promise((resolve, reject) => {
        out.on('error', reject);
        out.write(sizeBuf);
        return out.write(headerBuf, () => resolve());
    });
    return out;
}
async function createSymlink(dest, filepath, link) {
    // if symlink is within subdirectories, then we need to recreate dir structure
    await fs.mkdirp(path.join(`${dest}.unpacked`, path.dirname(filepath)));
    // create symlink within unpacked dir
    await fs.symlink(link, path.join(`${dest}.unpacked`, filepath)).catch(async (error) => {
        if (error.code === 'EPERM' && error.syscall === 'symlink') {
            throw new Error('Could not create symlinks for unpacked assets. On Windows, consider activating Developer Mode to allow non-admin users to create symlinks by following the instructions at https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development.');
        }
        throw error;
    });
}
//# sourceMappingURL=disk.js.map