"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseBundleAsts = parseBundleAsts;
exports.parseBundleInfo = parseBundleInfo;
const SWC = __importStar(require("./swc"));
const find_1 = require("./find");
const resolve_import_1 = require("./utils/resolve-import");
async function parseBundleAsts(bundleChunks) {
    return Object.fromEntries(await Promise.all(Object.entries(bundleChunks).map(async ([filename, code]) => [
        filename,
        await SWC.parse(code, {
            syntax: "ecmascript",
            target: "es2022"
        })
    ])));
}
async function parseBundleInfo(bundleAsts) {
    const bundleInfo = Object.fromEntries(Object.keys(bundleAsts).map(moduleName => [
        moduleName,
        {
            imported: null,
            importedBy: [],
            transformNeeded: null
        }
    ]));
    // Pass 1: build dependency graph and its reverse graph
    //         determine top-level await and dynamic import usage in each module
    for (const moduleName in bundleAsts) {
        const ast = bundleAsts[moduleName];
        const moduleInfo = bundleInfo[moduleName];
        // Parse imports
        moduleInfo.imported = ast.body
            .map(item => {
            if (item.type === "ImportDeclaration" || (item.type === "ExportNamedDeclaration" && item.source)) {
                return (0, resolve_import_1.resolveImport)(moduleName, item.source.value);
            }
        })
            .filter(x => x);
        // Add reverse edges for dependency graph traversal
        moduleInfo.imported.forEach(importedModuleName => {
            if (bundleInfo[importedModuleName]) {
                bundleInfo[importedModuleName].importedBy.push(moduleName);
            }
            else {
                /* istanbul ignore next */
                console.warn(`[vite-plugin-top-level-await] Non-existing module ${JSON.stringify(importedModuleName)} imported by ${JSON.stringify(moduleName)}, ignoring.`);
            }
        });
        const highestPattern = (0, find_1.findHighestPattern)(ast);
        moduleInfo.transformNeeded =
            highestPattern === find_1.CodePattern.TopLevelAwait || highestPattern === find_1.CodePattern.DynamicImport;
        moduleInfo.withTopLevelAwait = highestPattern === find_1.CodePattern.TopLevelAwait;
    }
    // Pass 2: transfer each modules's "top-level await usage" property to all successors in reverse graph
    const q = Object.entries(bundleInfo)
        .filter(([, module]) => module.withTopLevelAwait)
        .map(([moduleName]) => moduleName);
    while (q.length > 0) {
        const moduleName = q.shift();
        for (const nextModuleName of bundleInfo[moduleName].importedBy) {
            // Skip modules which are already enqueued once
            if (bundleInfo[nextModuleName].withTopLevelAwait)
                continue;
            // Enqueue next module
            bundleInfo[nextModuleName].withTopLevelAwait = true;
            bundleInfo[nextModuleName].transformNeeded = true;
            q.push(nextModuleName);
        }
    }
    return bundleInfo;
}
