"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;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const compiler_1 = require("../compiler");
const path_1 = require("path");
const resolve_dependencies_1 = __importStar(require("resolve-dependencies"));
const util_1 = require("../util");
function getStdIn(stdin) {
    let out = '';
    return new Promise((resolve) => {
        stdin
            .setEncoding('utf8')
            .on('readable', () => {
            let current;
            while ((current = stdin.read())) {
                out += current;
            }
        })
            .on('end', () => resolve(out.trim()));
        setTimeout(() => {
            if (!out.trim()) {
                resolve(out.trim());
            }
        }, 1000);
    });
}
function bundle(compiler, next) {
    return __awaiter(this, void 0, void 0, function* () {
        const { bundle: doBundle, cwd, input: inputPath } = compiler.options;
        let input = inputPath;
        compiler.entrypoint = './' + (0, path_1.relative)(cwd, input);
        if ((0, util_1.semverGt)(compiler.target.version, '11.99')) {
            compiler.startup = '';
        }
        else {
            compiler.startup = ';require("module").runMain();';
        }
        if (!doBundle) {
            yield compiler.addResource((0, path_1.resolve)(cwd, input));
            return next();
        }
        let code = '';
        if (typeof doBundle === 'string') {
            code = yield require(doBundle).createBundle(compiler.options);
        }
        if (input === util_1.STDIN_FLAG && (code = code || (0, util_1.dequote)(yield getStdIn(process.stdin)))) {
            compiler.stdinUsed = true;
            compiler.entrypoint = './__nexe_stdin.js';
            yield compiler.addResource((0, path_1.resolve)(cwd, compiler.entrypoint), code);
            return next();
        }
        if (input === util_1.STDIN_FLAG) {
            const maybeInput = (0, resolve_dependencies_1.resolveSync)(cwd, '.');
            if (!maybeInput || !maybeInput.absPath) {
                throw new compiler_1.NexeError('No valid input detected');
            }
            input = maybeInput.absPath;
            compiler.entrypoint = './' + (0, path_1.relative)(cwd, input);
        }
        const step = compiler.log.step('Resolving dependencies...');
        const { files, warnings } = yield (0, resolve_dependencies_1.default)(input, ...Object.keys(compiler.bundle.list).filter((x) => x.endsWith('.js') || x.endsWith('.mjs')), { cwd, expand: 'variable', loadContent: false });
        if (warnings.filter((x) => x.startsWith('Error parsing file') && !x.includes('node_modules')).length) {
            throw new compiler_1.NexeError('Parsing Error:\n' + warnings.join('\n'));
        }
        //TODO: warnings.forEach((x) => console.log(x))
        yield Promise.all(Object.entries(files).map(([key]) => {
            step.log(`Including dependency: ${key}`);
            return compiler.addResource(key);
        }));
        return next();
    });
}
exports.default = bundle;
