"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.restoreFs = exports.shimFs = void 0;
const libzip_1 = require("@yarnpkg/libzip");
const fslib_1 = require("@yarnpkg/fslib");
const SnapshotZipFS_1 = require("./SnapshotZipFS");
const assert = __importStar(require("assert"));
const constants = __importStar(require("constants"));
const path_1 = require("path");
let originalFsMethods = null;
let lazyRestoreFs = () => { };
const patches = process.nexe.patches || {};
const originalPatches = Object.assign({}, patches);
delete process.nexe;
function shimFs(binary, fs = require('fs')) {
    if (originalFsMethods !== null) {
        return;
    }
    originalFsMethods = Object.assign({}, fs);
    const realFs = Object.assign({}, fs);
    const nodeFs = new fslib_1.NodeFS(realFs);
    const blob = Buffer.allocUnsafe(binary.layout.resourceSize);
    const blobFd = realFs.openSync(binary.blobPath, 'r');
    const bytesRead = realFs.readSync(blobFd, blob, 0, binary.layout.resourceSize, binary.layout.resourceStart);
    assert.equal(bytesRead, binary.layout.resourceSize);
    const zipFs = new libzip_1.ZipFS(blob, { readOnly: true });
    const snapshotZipFS = new SnapshotZipFS_1.SnapshotZipFS({
        libzip: (0, libzip_1.getLibzipSync)(),
        zipFs,
        baseFs: nodeFs,
        root: (0, path_1.dirname)(process.argv[0]),
    });
    const posixSnapshotZipFs = new fslib_1.PosixFS(snapshotZipFS);
    (0, fslib_1.patchFs)(fs, posixSnapshotZipFs);
    let log = (_) => true;
    if ((process.env.DEBUG || '').toLowerCase().includes('nexe:require')) {
        process.stderr.write(
        // @ts-ignore
        `[nexe] - FILES ${JSON.stringify(Array.from(zipFs.entries.keys()), null, 4)}\n`);
        process.stderr.write(
        // @ts-ignore
        `[nexe] - DIRECTORIES ${JSON.stringify(Array.from(zipFs.listings.keys()), null, 4)}\n`);
        log = (text) => {
            return process.stderr.write(`[nexe] - ${text}\n`);
        };
    }
    function internalModuleReadFile(original, ...args) {
        log(`internalModuleReadFile ${args[0]}`);
        try {
            return posixSnapshotZipFs.readFileSync(args[0], 'utf-8');
        }
        catch (e) {
            return '';
        }
    }
    if (patches.internalModuleReadFile) {
        patches.internalModuleReadFile = internalModuleReadFile;
    }
    let returningArray;
    patches.internalModuleReadJSON = function (original, ...args) {
        if (returningArray == null)
            returningArray = Array.isArray(original.call(this, ''));
        const res = internalModuleReadFile.call(this, original, ...args);
        return returningArray && !Array.isArray(res)
            ? res === ''
                ? []
                : [res, /"(main|name|type|exports|imports)"/.test(res)]
            : res;
    };
    patches.internalModuleStat = function (original, ...args) {
        let statPath = args[0];
        //in node 22, the path arg moved to arg[1]
        if (typeof args[0] !== 'string')
            statPath = args[1];
        let result = 0;
        try {
            const stat = posixSnapshotZipFs.statSync(statPath);
            if (stat.isDirectory())
                result = 1;
            else
                result = 0;
        }
        catch (e) {
            result = -constants.ENOENT;
        }
        log(`internalModuleStat ${result} ${statPath}`);
        return result;
    };
    lazyRestoreFs = () => {
        Object.assign(fs, originalFsMethods);
        Object.assign(patches, originalPatches);
        lazyRestoreFs = () => { };
    };
}
exports.shimFs = shimFs;
function restoreFs() {
    lazyRestoreFs();
}
exports.restoreFs = restoreFs;
