import{writeFileSync as E}from"node:fs";import R from"path";import{combineUrls as v}from"@redocly/theme/core/utils";import{SCORECARD_OUTPUT_FILE_NAME as y}from"../../constants/common.js";import{ensureDir as D,logger as O,readEnvVariable as I}from"../../utils/index.js";import{getTemplatePath as L}from"./get-template-path.js";import{getAllRuleNames as T}from"./lint.js";import{getScorecardConfig as P}from"./get-scorecard-config.js";import{mapObject as h}from"../../../shared/jsUtils.js";import{CUSTOM_FIELDS_SERVER_PROPS_GETTER_ID as _}from"../catalog-classic/index.js";import{getScorecardSlug as b}from"./shared-utils.js";import{scorecardConfigLoader as A}from"./loaders/scorecard-config.js";import{scorecardLoader as F}from"./loaders/scorecard.js";import{computeScorecard as j}from"./compute-scorecard.js";const w="scorecard";async function K(){let u=null,p=null,S=!1;return{id:"scorecard",requiredEntitlements:["scorecard"],loaders:{"scorecard-config":A,scorecard:F},async processContent(r,i){const g=r.createTemplate(w,L("./template/index.js")),c=await i.getConfig(),n=P(c),f=c?.reunite??{},m=c.catalogClassic??{},a=n.levels||[];if(a.length<1)throw Error("Invalid configuration of levels config");u===null&&(u=await j({actions:r,context:i,scorecardConfig:n,reuniteConfig:f}));const{data:{configs:s}}=await i.cache.load("","scorecard-config"),{perLevel:e,all:d}=T(s);p={levelNames:a.map(l=>l.name),rules:d,rulesPerLevel:e};for(const[l,t]of Object.entries(m)){const o=v(t.slug,"scorecard/");r.addRoute({duplicateInAllLocales:!0,slug:o,fsPath:v(t.slug,"scorecard/"),templateId:g,hasClientRoutes:!0,excludeFromSidebar:!0,serverPropsGetterIds:[_],sharedData:[{id:"scorecard",key:"scorecard"},{key:"catalog",id:"catalog-"+l}],getNavText:()=>Promise.resolve(t.title||"API design scorecard"),getStaticData:async()=>({props:{catalogId:l,catalogConfig:{...t,items:void 0},scorecardConfig:n,scorecardInfo:p}})})}},afterRoutesCreated:async(r,{getConfig:i})=>{const g=await i(),c=g.catalogClassic??{},n=P(g);if(Object.keys(c).length){const a={};for(const[s,e]of Object.entries(u||{})){const d=r.getRouteByFsPath(s),l=v(Object.values(c)[0].slug,"scorecard/"),t=r.getRouteByFsPath(s)?.slug;if(t&&(d&&!n.ignoreMetadata&&(d.metadata={...d.metadata,scorecardStatus:e.status,scorecardLevel:e.scorecardLevel,scorecardLevelIdx:e.scorecardLevelIdx,scorecardLevels:h(e.levels,o=>({uniqueErrors:o.uniqueErrors,uniqueWarnings:o.uniqueWarnings})),scoreCardSlug:l+"?api="+encodeURIComponent(t)}),a[t]={...e,levels:h(e.levels,o=>({...o,problems:o.problems.map(C=>({ruleId:C.ruleId,severity:C.severity}))}))},!S)){const o=R.resolve(r.outdir,"_scorecard",b(t));E(D(o),JSON.stringify(e))}}await r.createSharedData("scorecard",a)}const f={};for(const[a,s]of Object.entries(u||{})){const e=r.getRouteByFsPath(a)?.slug;e&&(f[e]=s)}const m=I("REDOCLY_METADATA_OUTPUT_FOLDER");!S&&m&&(O.info("Writing scorecard data..."),E(R.join(m,y),JSON.stringify({scorecardData:f,...p}))),S=!0}}}export{K as scorecardPlugin};
