"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomTipsConfiguration = exports.PNPM_CUSTOM_TIPS = exports.RUSH_CUSTOM_TIPS = exports.CustomTipType = exports.CustomTipSeverity = exports.CustomTipId = void 0;
const path = __importStar(require("node:path"));
const node_core_library_1 = require("@rushstack/node-core-library");
const terminal_1 = require("@rushstack/terminal");
const custom_tips_schema_json_1 = __importDefault(require("../schemas/custom-tips.schema.json"));
/**
 * An identifier representing a Rush message that can be customized by
 * defining a custom tip in `common/config/rush/custom-tips.json`.
 * @remarks
 * Custom tip ids always start with the `TIP_` prefix.
 *
 * @privateRemarks
 * Events from the Rush process should with "TIP_RUSH_".
 * Events from a PNPM subprocess should start with "TIP_PNPM_".
 *
 * @beta
 */
var CustomTipId;
(function (CustomTipId) {
    // Events from the Rush process should with "TIP_RUSH_".
    CustomTipId["TIP_RUSH_INCONSISTENT_VERSIONS"] = "TIP_RUSH_INCONSISTENT_VERSIONS";
    CustomTipId["TIP_RUSH_DISALLOW_INSECURE_SHA1"] = "TIP_RUSH_DISALLOW_INSECURE_SHA1";
    // Events from a PNPM subprocess should start with "TIP_PNPM_".
    CustomTipId["TIP_PNPM_UNEXPECTED_STORE"] = "TIP_PNPM_UNEXPECTED_STORE";
    CustomTipId["TIP_PNPM_NO_MATCHING_VERSION"] = "TIP_PNPM_NO_MATCHING_VERSION";
    CustomTipId["TIP_PNPM_NO_MATCHING_VERSION_INSIDE_WORKSPACE"] = "TIP_PNPM_NO_MATCHING_VERSION_INSIDE_WORKSPACE";
    CustomTipId["TIP_PNPM_PEER_DEP_ISSUES"] = "TIP_PNPM_PEER_DEP_ISSUES";
    CustomTipId["TIP_PNPM_OUTDATED_LOCKFILE"] = "TIP_PNPM_OUTDATED_LOCKFILE";
    CustomTipId["TIP_PNPM_TARBALL_INTEGRITY"] = "TIP_PNPM_TARBALL_INTEGRITY";
    CustomTipId["TIP_PNPM_MISMATCHED_RELEASE_CHANNEL"] = "TIP_PNPM_MISMATCHED_RELEASE_CHANNEL";
    CustomTipId["TIP_PNPM_INVALID_NODE_VERSION"] = "TIP_PNPM_INVALID_NODE_VERSION";
})(CustomTipId || (exports.CustomTipId = CustomTipId = {}));
/**
 * The severity of a custom tip.
 * It determines the printing severity ("Error" = red, "Warning" = yellow, "Info" = normal).
 *
 * @beta
 */
var CustomTipSeverity;
(function (CustomTipSeverity) {
    CustomTipSeverity["Warning"] = "Warning";
    CustomTipSeverity["Error"] = "Error";
    CustomTipSeverity["Info"] = "Info";
})(CustomTipSeverity || (exports.CustomTipSeverity = CustomTipSeverity = {}));
/**
 * The type of the custom tip.
 *
 * @remarks
 * There might be types like `git` in the future.
 *
 * @beta
 */
var CustomTipType;
(function (CustomTipType) {
    CustomTipType["rush"] = "rush";
    CustomTipType["pnpm"] = "pnpm";
})(CustomTipType || (exports.CustomTipType = CustomTipType = {}));
exports.RUSH_CUSTOM_TIPS = {
    [CustomTipId.TIP_RUSH_DISALLOW_INSECURE_SHA1]: {
        tipId: CustomTipId.TIP_RUSH_DISALLOW_INSECURE_SHA1,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.pnpm,
        isMatch: (str) => {
            return str.includes('ERR_PNPM_DISALLOW_INSECURE_SHA1');
        }
    },
    [CustomTipId.TIP_RUSH_INCONSISTENT_VERSIONS]: {
        tipId: CustomTipId.TIP_RUSH_INCONSISTENT_VERSIONS,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.rush
    }
};
exports.PNPM_CUSTOM_TIPS = {
    [CustomTipId.TIP_PNPM_UNEXPECTED_STORE]: {
        tipId: CustomTipId.TIP_PNPM_UNEXPECTED_STORE,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.pnpm,
        isMatch: (str) => {
            return str.includes('ERR_PNPM_UNEXPECTED_STORE');
        }
    },
    [CustomTipId.TIP_PNPM_NO_MATCHING_VERSION]: {
        tipId: CustomTipId.TIP_PNPM_NO_MATCHING_VERSION,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.pnpm,
        isMatch: (str) => {
            // Example message: (do notice the difference between this one and the TIP_PNPM_NO_MATCHING_VERSION_INSIDE_WORKSPACE)
            // Error Message: ERR_PNPM_NO_MATCHING_VERSION  No matching version found for @babel/types@^7.22.5
            // The latest release of @babel/types is "7.22.4".
            // Other releases are:
            // * esm: 7.21.4-esm.4
            return str.includes('No matching version found for') && str.includes('The latest release of');
        }
    },
    [CustomTipId.TIP_PNPM_NO_MATCHING_VERSION_INSIDE_WORKSPACE]: {
        tipId: CustomTipId.TIP_PNPM_NO_MATCHING_VERSION_INSIDE_WORKSPACE,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.pnpm,
        isMatch: (str) => {
            return str.includes('ERR_PNPM_NO_MATCHING_VERSION_INSIDE_WORKSPACE');
        }
    },
    [CustomTipId.TIP_PNPM_PEER_DEP_ISSUES]: {
        tipId: CustomTipId.TIP_PNPM_PEER_DEP_ISSUES,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.pnpm,
        isMatch: (str) => {
            return str.includes('ERR_PNPM_PEER_DEP_ISSUES');
        }
    },
    [CustomTipId.TIP_PNPM_OUTDATED_LOCKFILE]: {
        tipId: CustomTipId.TIP_PNPM_OUTDATED_LOCKFILE,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.pnpm,
        isMatch: (str) => {
            // Todo: verify this
            return str.includes('ERR_PNPM_OUTDATED_LOCKFILE');
        }
    },
    [CustomTipId.TIP_PNPM_TARBALL_INTEGRITY]: {
        tipId: CustomTipId.TIP_PNPM_TARBALL_INTEGRITY,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.pnpm,
        isMatch: (str) => {
            // Todo: verify this
            return str.includes('ERR_PNPM_TARBALL_INTEGRITY');
        }
    },
    [CustomTipId.TIP_PNPM_MISMATCHED_RELEASE_CHANNEL]: {
        tipId: CustomTipId.TIP_PNPM_MISMATCHED_RELEASE_CHANNEL,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.pnpm,
        isMatch: (str) => {
            // Todo: verify this
            return str.includes('ERR_PNPM_MISMATCHED_RELEASE_CHANNEL');
        }
    },
    [CustomTipId.TIP_PNPM_INVALID_NODE_VERSION]: {
        tipId: CustomTipId.TIP_PNPM_INVALID_NODE_VERSION,
        severity: CustomTipSeverity.Error,
        type: CustomTipType.pnpm,
        isMatch: (str) => {
            // Todo: verify this
            return str.includes('ERR_PNPM_INVALID_NODE_VERSION');
        }
    }
};
/**
 * Used to access the `common/config/rush/custom-tips.json` config file,
 * which allows repo maintainers to configure extra details to be printed alongside
 * certain Rush messages.
 * @beta
 */
class CustomTipsConfiguration {
    constructor(configFilePath) {
        const providedCustomTips = new Map();
        let configuration;
        try {
            configuration = node_core_library_1.JsonFile.loadAndValidate(configFilePath, CustomTipsConfiguration._jsonSchema);
        }
        catch (e) {
            if (!node_core_library_1.FileSystem.isNotExistError(e)) {
                throw e;
            }
        }
        const customTips = configuration === null || configuration === void 0 ? void 0 : configuration.customTips;
        if (customTips) {
            for (const tipItem of customTips) {
                if (!(tipItem.tipId in CustomTipId)) {
                    throw new Error(`The ${path.basename(configFilePath)} configuration` +
                        ` references an unknown ID "${tipItem.tipId}"`);
                }
                if (providedCustomTips.has(tipItem.tipId)) {
                    throw new Error(`The ${path.basename(configFilePath)} configuration` +
                        ` specifies a duplicate definition for "${tipItem.tipId}"`);
                }
                else {
                    providedCustomTips.set(tipItem.tipId, tipItem);
                }
            }
        }
        this.providedCustomTipsByTipId = providedCustomTips;
    }
    /**
     * If custom-tips.json defines a tip for the specified tipId,  display the tip on the terminal.
     *
     * @remarks
     * The severity of the tip is defined in ${@link CustomTipsConfiguration.customTipRegistry}.
     * If you want to change the severity specifically for this call,
     * use other APIs such as {@link CustomTipsConfiguration._showErrorTip}.
     *
     * Custom tips by design do not replace Rush's standard messaging; instead, they annotate Rush's
     * output with additional team-specific advice.
     *
     * @internal
     */
    _showTip(terminal, tipId) {
        const severityOfOriginalMessage = CustomTipsConfiguration.customTipRegistry[tipId].severity;
        this._writeMessageWithPipes(terminal, severityOfOriginalMessage, tipId);
    }
    /**
     * If custom-tips.json defines a tip for the specified tipId, display the tip on the terminal.
     * @remarks
     * Custom tips by design do not replace Rush's standard messaging; instead, they annotate Rush's
     * output with additional team-specific advice.
     * @internal
     */
    _showInfoTip(terminal, tipId) {
        this._writeMessageWithPipes(terminal, CustomTipSeverity.Info, tipId);
    }
    /**
     * If custom-tips.json defines a tip for the specified tipId, display the tip on the terminal.
     * @remarks
     * Custom tips by design do not replace Rush's standard messaging; instead, they annotate Rush's
     * output with additional team-specific advice.
     * @internal
     */
    _showWarningTip(terminal, tipId) {
        this._writeMessageWithPipes(terminal, CustomTipSeverity.Warning, tipId);
    }
    /**
     * If custom-tips.json defines a tip for the specified tipId, display the tip on the terminal.
     * @remarks
     * Custom tips by design do not replace Rush's standard messaging; instead, they annotate Rush's
     * output with additional team-specific advice.
     * @internal
     */
    _showErrorTip(terminal, tipId) {
        this._writeMessageWithPipes(terminal, CustomTipSeverity.Error, tipId);
    }
    _writeMessageWithPipes(terminal, severity, tipId) {
        const customTipJsonItem = this.providedCustomTipsByTipId.get(tipId);
        if (customTipJsonItem) {
            let writeFunction;
            let prefix;
            switch (severity) {
                case CustomTipSeverity.Error:
                    writeFunction = terminal.writeErrorLine.bind(terminal);
                    prefix = terminal_1.Colorize.red('| ');
                    break;
                case CustomTipSeverity.Warning:
                    writeFunction = terminal.writeWarningLine.bind(terminal);
                    prefix = terminal_1.Colorize.yellow('| ');
                    break;
                default:
                    writeFunction = terminal.writeLine.bind(terminal);
                    prefix = '| ';
                    break;
            }
            writeFunction(`| Custom Tip (${tipId})`);
            writeFunction('|');
            const message = customTipJsonItem.message;
            const wrappedAndIndentedMessage = terminal_1.PrintUtilities.wrapWords(message, undefined, prefix);
            writeFunction(...wrappedAndIndentedMessage, { doNotOverrideSgrCodes: true });
            terminal.writeLine();
        }
    }
}
exports.CustomTipsConfiguration = CustomTipsConfiguration;
CustomTipsConfiguration._jsonSchema = node_core_library_1.JsonSchema.fromLoadedObject(custom_tips_schema_json_1.default);
/**
 * A registry mapping custom tip IDs to their corresponding metadata.
 *
 * @remarks
 * This registry is used to look up metadata for custom tips based on their IDs. The metadata includes
 * information such as the severity level, the type of tip, and an optional matching function.
 *
 * Each key in the registry corresponds to a `CustomTipIdEnum` value, and each value is an object
 * implementing the `ICustomTipInfo` interface.
 *
 * @example
 * ```typescript
 * const tipInfo = CustomTipsConfiguration.customTipRegistry[CustomTipIdEnum.TIP_RUSH_INCONSISTENT_VERSIONS];
 * console.log(tipInfo.severity);  // Output: CustomTipSeverity.Error
 * ```
 *
 * See {@link CustomTipId} for the list of custom tip IDs.
 * See {@link ICustomTipInfo} for the structure of the metadata.
 */
CustomTipsConfiguration.customTipRegistry = {
    ...exports.RUSH_CUSTOM_TIPS,
    ...exports.PNPM_CUSTOM_TIPS
};
//# sourceMappingURL=CustomTipsConfiguration.js.map