"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
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.SubspacePnpmfileConfiguration = void 0;
const path = __importStar(require("node:path"));
const node_core_library_1 = require("@rushstack/node-core-library");
const PathConstants_1 = require("../../utilities/PathConstants");
const RushConstants_1 = require("../RushConstants");
/**
 * Loads PNPM's pnpmfile.js configuration, and invokes it to preprocess package.json files,
 * optionally utilizing a pnpmfile shim to inject preferred versions.
 */
class SubspacePnpmfileConfiguration {
    /**
     * Split workspace use global pnpmfile, because in split workspace, user may set `shared-workspace-lockfile=false`.
     * That means each project owns their individual pnpmfile under project folder. While the global pnpmfile could be
     * under the common/temp-split/ folder and be used by all split workspace projects.
     */
    static async writeCommonTempSubspaceGlobalPnpmfileAsync(rushConfiguration, subspace, variant) {
        if (rushConfiguration.packageManager !== 'pnpm') {
            throw new Error(`PnpmfileConfiguration cannot be used with package manager "${rushConfiguration.packageManager}"`);
        }
        const targetDir = subspace.getSubspaceTempFolderPath();
        const subspaceGlobalPnpmfilePath = path.join(targetDir, RushConstants_1.RushConstants.pnpmfileGlobalFilename);
        // Write the shim itself
        await node_core_library_1.FileSystem.copyFileAsync({
            sourcePath: `${PathConstants_1.scriptsFolderPath}/${PathConstants_1.subspacePnpmfileShimFilename}`,
            destinationPath: subspaceGlobalPnpmfilePath
        });
        const subspaceGlobalPnpmfileShimSettings = SubspacePnpmfileConfiguration.getSubspacePnpmfileShimSettings(rushConfiguration, subspace, variant);
        // Write the settings file used by the shim
        await node_core_library_1.JsonFile.saveAsync(subspaceGlobalPnpmfileShimSettings, path.join(targetDir, 'pnpmfileSettings.json'), {
            ensureFolderExists: true
        });
    }
    static getSubspacePnpmfileShimSettings(rushConfiguration, subspace, variant) {
        const workspaceProjects = {};
        const subspaceProjects = {};
        const projectNameToInjectedDependenciesMap = SubspacePnpmfileConfiguration._getProjectNameToInjectedDependenciesMap(rushConfiguration, subspace);
        for (const project of rushConfiguration.projects) {
            const { packageName, projectRelativeFolder, packageJson } = project;
            const workspaceProjectInfo = {
                packageName,
                projectRelativeFolder,
                packageVersion: packageJson.version,
                injectedDependencies: Array.from(projectNameToInjectedDependenciesMap.get(packageName) || [])
            };
            (subspace.contains(project) ? subspaceProjects : workspaceProjects)[packageName] = workspaceProjectInfo;
        }
        const settings = {
            workspaceProjects,
            subspaceProjects,
            semverPath: node_core_library_1.Import.resolveModule({ modulePath: 'semver', baseFolderPath: __dirname })
        };
        // common/config/subspaces/<subspace_name>/.pnpmfile.cjs
        const userPnpmfilePath = path.join(subspace.getVariantDependentSubspaceConfigFolderPath(variant), rushConfiguration.packageManagerWrapper.pnpmfileFilename);
        if (node_core_library_1.FileSystem.exists(userPnpmfilePath)) {
            settings.userPnpmfilePath = userPnpmfilePath;
        }
        return settings;
    }
    static _getProjectNameToInjectedDependenciesMap(rushConfiguration, subspace) {
        var _a, _b, _c, _d;
        const projectNameToInjectedDependenciesMap = new Map();
        const workspaceProjectsMap = new Map();
        const subspaceProjectsMap = new Map();
        for (const project of rushConfiguration.projects) {
            if (subspace.contains(project)) {
                subspaceProjectsMap.set(project.packageName, project);
            }
            else {
                workspaceProjectsMap.set(project.packageName, project);
            }
            projectNameToInjectedDependenciesMap.set(project.packageName, new Set());
        }
        const processTransitiveInjectedInstallQueue = [];
        for (const subspaceProject of subspaceProjectsMap.values()) {
            const injectedDependencySet = new Set();
            const dependenciesMeta = subspaceProject.packageJson.dependenciesMeta;
            if (dependenciesMeta) {
                for (const [dependencyName, { injected }] of Object.entries(dependenciesMeta)) {
                    if (injected) {
                        injectedDependencySet.add(dependencyName);
                        (_a = projectNameToInjectedDependenciesMap.get(subspaceProject.packageName)) === null || _a === void 0 ? void 0 : _a.add(dependencyName);
                        //if this dependency is in the same subspace, leave as it is, PNPM will handle it
                        //if this dependency is in another subspace, then it is transitive injected installation
                        //so, we need to let all the workspace dependencies along the dependency chain to use injected installation
                        if (!subspaceProjectsMap.has(dependencyName)) {
                            processTransitiveInjectedInstallQueue.push(workspaceProjectsMap.get(dependencyName));
                        }
                    }
                }
            }
            // if alwaysInjectDependenciesFromOtherSubspaces policy is true in pnpm-config.json
            // and the dependency is not injected yet
            // and the dependency is in another subspace
            // then, make this dependency as injected dependency
            const pnpmOptions = subspace.getPnpmOptions() || rushConfiguration.pnpmOptions;
            if (pnpmOptions && pnpmOptions.alwaysInjectDependenciesFromOtherSubspaces) {
                const dependencyProjects = subspaceProject.dependencyProjects;
                for (const dependencyProject of dependencyProjects) {
                    const dependencyName = dependencyProject.packageName;
                    if (!injectedDependencySet.has(dependencyName) && !subspaceProjectsMap.has(dependencyName)) {
                        (_b = projectNameToInjectedDependenciesMap.get(subspaceProject.packageName)) === null || _b === void 0 ? void 0 : _b.add(dependencyName);
                        // process transitive injected installation
                        processTransitiveInjectedInstallQueue.push(workspaceProjectsMap.get(dependencyName));
                    }
                }
            }
        }
        // rewrite all workspace dependencies to injected install all for transitive injected installation case
        while (processTransitiveInjectedInstallQueue.length > 0) {
            const currentProject = processTransitiveInjectedInstallQueue.shift();
            const dependencies = (_c = currentProject === null || currentProject === void 0 ? void 0 : currentProject.packageJson) === null || _c === void 0 ? void 0 : _c.dependencies;
            const optionalDependencies = (_d = currentProject === null || currentProject === void 0 ? void 0 : currentProject.packageJson) === null || _d === void 0 ? void 0 : _d.optionalDependencies;
            if (currentProject) {
                if (dependencies) {
                    SubspacePnpmfileConfiguration._processDependenciesForTransitiveInjectedInstall(projectNameToInjectedDependenciesMap, processTransitiveInjectedInstallQueue, dependencies, currentProject, rushConfiguration);
                }
                if (optionalDependencies) {
                    SubspacePnpmfileConfiguration._processDependenciesForTransitiveInjectedInstall(projectNameToInjectedDependenciesMap, processTransitiveInjectedInstallQueue, optionalDependencies, currentProject, rushConfiguration);
                }
            }
        }
        return projectNameToInjectedDependenciesMap;
    }
    static _processDependenciesForTransitiveInjectedInstall(projectNameToInjectedDependencies, processTransitiveInjectedInstallQueue, dependencies, currentProject, rushConfiguration) {
        var _a;
        for (const dependencyName in dependencies) {
            if (dependencies[dependencyName].startsWith('workspace:')) {
                (_a = projectNameToInjectedDependencies.get(currentProject.packageName)) === null || _a === void 0 ? void 0 : _a.add(dependencyName);
                const nextProject = rushConfiguration.getProjectByName(dependencyName);
                if (nextProject) {
                    processTransitiveInjectedInstallQueue.push(nextProject);
                }
            }
        }
    }
}
exports.SubspacePnpmfileConfiguration = SubspacePnpmfileConfiguration;
//# sourceMappingURL=SubspacePnpmfileConfiguration.js.map