"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mountMemoryDrive = mountMemoryDrive;
const tslib_1 = require("tslib");
const fslib_1 = require("@yarnpkg/fslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const ZipFS_1 = require("./ZipFS");
function mountMemoryDrive(origFs, mountPoint, source = Buffer.alloc(0), opts) {
    const archive = new ZipFS_1.ZipFS(source);
    const getMountPoint = (p) => {
        const detectedMountPoint = p === mountPoint || p.startsWith(`${mountPoint}/`) ? p.slice(0, mountPoint.length) : null;
        return detectedMountPoint;
    };
    const factoryPromise = async (baseFs, p) => {
        return () => archive;
    };
    const factorySync = (baseFs, p) => {
        return archive;
    };
    // We must copy the fs into a local, because otherwise
    // 1. we would make the NodeFS instance use the function that we patched (infinite loop)
    // 2. Object.create(fs) isn't enough, since it won't prevent the proto from being modified
    const localFs = { ...origFs };
    const nodeFs = new fslib_1.NodeFS(localFs);
    const mountFs = new fslib_1.MountFS({
        baseFs: nodeFs,
        getMountPoint,
        factoryPromise,
        factorySync,
        magicByte: 21,
        maxAge: Infinity,
        typeCheck: opts?.typeCheck,
    });
    (0, fslib_1.patchFs)(fs_1.default, new fslib_1.PosixFS(mountFs));
    return archive;
}
