"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldServe = exports.prepareCache = exports.build = exports.version = void 0;
const path_1 = __importDefault(require("path"));
const build_utils_1 = require("@vercel/build-utils");
Object.defineProperty(exports, "shouldServe", { enumerable: true, get: function () { return build_utils_1.shouldServe; } });
const utils_1 = require("./utils");
const COMPOSER_FILE = process.env.COMPOSER || 'composer.json';
// ###########################
// EXPORTS
// ###########################
exports.version = 3;
async function build({ files, entrypoint, workPath, config = {}, meta = {}, }) {
    // Check if now dev mode is used
    if (meta.isDev) {
        console.log(`
      🐘 vercel dev is not supported right now.
      Please use PHP built-in development server.

      php -S localhost:8000 api/index.php
    `);
        process.exit(255);
    }
    console.log('🐘 Downloading user files');
    // Collect user provided files
    const userFiles = await build_utils_1.download(files, workPath, meta);
    console.log('🐘 Downloading PHP runtime files');
    // Collect runtime files containing PHP bins and libs
    const runtimeFiles = {
        // Append brefphp files (bins + shared object)
        ...await utils_1.getBrefFiles(),
    };
    // If composer.json is provided try to
    // - install deps
    // - run composer scripts
    if (userFiles[COMPOSER_FILE]) {
        // Install dependencies (vendor is collected bellow, see harvestedFiles)
        await utils_1.runComposerInstall(workPath);
        // Run composer scripts (created files are collected bellow, , see harvestedFiles)
        // await runComposerScripts(userFiles[COMPOSER_FILE], workPath);
    }
    // Collect user files, files creating during build (composer vendor)
    // and other files and prefix them with "user" (/var/task/user folder).
    const harverstedFiles = build_utils_1.rename(await build_utils_1.glob('**', {
        cwd: workPath,
        ignore: config && config.excludeFiles
            ? Array.isArray(config.excludeFiles) ? config.excludeFiles : [config.excludeFiles]
            : ['node_modules/**', 'now.json', '.nowignore', 'vercel.json', '.vercelignore'],
    }), name => path_1.default.join('user', name));
    // Show some debug notes during build
    if (process.env.VERCEL_BREF_DEBUG === '1') {
        console.log('🐘 Entrypoint:', entrypoint);
        console.log('🐘 Config:', config);
        console.log('🐘 Work path:', workPath);
        console.log('🐘 Meta:', meta);
        console.log('🐘 User files:', Object.keys(harverstedFiles));
        console.log('🐘 Runtime files:', Object.keys(runtimeFiles));
    }
    console.log('🐘 Creating lambda');
    const lambda = await build_utils_1.createLambda({
        files: {
            // Located at /var/task/user
            ...harverstedFiles,
            // Located at /var/task/native (brefphp)
            ...runtimeFiles,
            // User our tuned bootstrap (wrapper around brefphp's bootstrap)
            ...{
                'bootstrap': new build_utils_1.FileFsRef({
                    mode: 0o755,
                    fsPath: path_1.default.join(__dirname, '../lib/bootstrap'),
                }),
            }
        },
        handler: entrypoint,
        runtime: 'provided',
        environment: {
            PHP_INI_SCAN_DIR: '/var/task/native/bref/etc/php/conf.d'
        },
    });
    return { output: lambda };
}
exports.build = build;
;
async function prepareCache({ workPath }) {
    return {
        // Composer
        ...(await build_utils_1.glob('vendor/**', workPath)),
        ...(await build_utils_1.glob('composer.lock', workPath)),
        // NPM
        ...(await build_utils_1.glob('node_modules/**', workPath)),
        ...(await build_utils_1.glob('package-lock.json', workPath)),
        ...(await build_utils_1.glob('yarn.lock', workPath)),
    };
}
exports.prepareCache = prepareCache;
