/*
 * Copyright (c) 2018, 2025, Oracle and/or its affiliates.
 * Licensed under The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 */
const TsxUtils=require("../jetwc-lib/jetwcutils-tsxUtils");const ruleDef=function(){};ruleDef.prototype.getName=function(){return"jetwco-validate-applied-audits"};ruleDef.prototype.getShortDescription=function(){return"Validate Applied Audits"};ruleDef.prototype.getDescription=function(){return"This rule checks that any applied-audits defined by a component are actually valid in the context of the available rule-packs"};ruleDef.prototype.register=function(context){return{startup:this._setupRuleBasis,compjson:this._doAudit,Program:this._doVComponentAudit}};ruleDef.prototype._setupRuleBasis=function(context){this.validRuleNames=this._extractValidRuleNames(context);if(this.validRuleNames.size===0){context.utils.msgLib.error("Configuration for jetwco-validate-applied-audits is in error, the supplied value for \"auditRuleBundles\" does not yield any rules");return false}else{context.utils.msgLib.info(`jetwco-validate-applied-audits is using the following audit names for validation:\n${[...this.validRuleNames.keys()].join(", ")}`);return true}};ruleDef.prototype._doAudit=function(context){const componentMetadata=context.suppData.obj;this._checkAppliedAudits(context,componentMetadata)};ruleDef.prototype._doVComponentAudit=function(context){const componentInfo=TsxUtils.matchToVComponentImpl(context,context.filepath);this._checkAppliedAudits(context,componentInfo)};ruleDef.prototype._checkAppliedAudits=function(context,componentMetadata){if(componentMetadata?.extension?.catalog?.appliedAudits){componentMetadata.extension.catalog.appliedAudits.forEach(namedRule=>{if(!this.validRuleNames.has(namedRule?.auditName)){issue=new context.Issue(`The named applied audit "${namedRule.auditName}" does not exist in the specified audit rule pack(s)`);issue.setMsgKey(context.ruleName+"_1");context.reporter.addIssue(issue,context)}})}};ruleDef.prototype._extractValidRuleNames=function(context){const ruleBundles=context.rulePack.getRuleCustomOption("auditRuleBundles");const flattenedRuleNames=new Set;if(Array.isArray(ruleBundles)&&ruleBundles.length>0){ruleBundles.forEach(bundle=>{if(context.utils.fsUtils.fileExistsSync(bundle)){const ruleBundleDef=context.utils.fsUtils.readJsonSync(bundle,true);if(ruleBundleDef.rules){Object.keys(ruleBundleDef.rules).forEach(ruleName=>{flattenedRuleNames.add(ruleName)})}}})}return flattenedRuleNames};module.exports=ruleDef;