"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const generateInFolder_1 = require("../../utils/generateInFolder");
const util_1 = require("util");
const rimraf_1 = __importDefault(require("rimraf"));
const del = util_1.promisify(rimraf_1.default);
jest.setTimeout(30000);
describe('runtime works', () => {
    const subDirs = getSubDirs(__dirname);
    for (const dir of subDirs) {
        const nodeModules = path_1.default.join(dir, 'node_modules');
        const testName = path_1.default.basename(dir);
        const shouldSucceed = shouldTestSucceed(dir);
        const testTitle = `${testName} example should${shouldSucceed ? '' : ' not'} succeed`;
        test(testTitle, async () => {
            if (fs_1.default.existsSync(nodeModules)) {
                await del(nodeModules);
            }
            const envVars = getEnvVars(dir);
            process.env = Object.assign(Object.assign({}, process.env), envVars);
            await generateInFolder_1.generateInFolder({
                projectDir: dir,
                useLocalRuntime: false,
                transpile: true,
            });
            if (envVars) {
                for (const key of Object.keys(envVars)) {
                    delete process.env[key];
                }
            }
            const filePath = path_1.default.join(dir, 'index.js');
            const fn = require(filePath);
            if (shouldSucceed) {
                expect(fn()).resolves.toMatchSnapshot(testTitle);
            }
            else {
                try {
                    await fn();
                }
                catch (e) {
                    expect(e).toMatchSnapshot(testTitle);
                }
            }
        });
    }
});
function getSubDirs(dir) {
    const files = fs_1.default.readdirSync(dir);
    return files
        .map(file => path_1.default.join(dir, file))
        .filter(file => fs_1.default.lstatSync(file).isDirectory() && !file.includes('__snapshots__'));
}
function getEnvVars(dir) {
    const envPath = path_1.default.join(dir, 'env.json');
    if (fs_1.default.existsSync(envPath)) {
        return JSON.parse(fs_1.default.readFileSync(envPath, 'utf-8'));
    }
    return undefined;
}
function shouldTestSucceed(dir) {
    const manifestPath = path_1.default.join(dir, 'manifest.json');
    if (!fs_1.default.existsSync(manifestPath)) {
        throw new Error(`Runtime Test dir ${dir} needs a manifest.json`);
    }
    const manifest = JSON.parse(fs_1.default.readFileSync(manifestPath, 'utf-8'));
    return manifest.shouldSucceed;
}
//# sourceMappingURL=runtime.test.js.map