import t from"node:fs";import n from"node:path";import s from"./getRelativePath.mjs";import o from"./isPathNotFoundError.mjs";class e{filePath="";cwd="";constructor({filePath:t,cwd:n}){this.filePath=t,this.cwd=n}async suppress(t,o){if(void 0===t)return;const i=await this.load();for(const c of t){const t=c.source;if(!t)continue;const r=n.isAbsolute(t)?s(this.cwd,t):t,u=e.countProblemsByRule(c.warnings);for(const[t,n]of u){if(o&&!o.includes(t))continue;i.has(r)||i.set(r,new Map);const s=i.get(r);s&&s.set(t,n)}}const{unused:c}=this.applySuppressions(t,i),r=this.#t(c,i);return this.#n(r)}#t(t,n){for(const[s,o]of t){if(!n.has(s))continue;for(const[t,e]of o){const o=n.get(s);if(!o)continue;const i=o.get(t);if(!i)continue;const c=i.count,r=e.count;if(c===r)o.delete(t);else{const n=o.get(t);n&&(n.count-=r)}}const t=n.get(s);t&&0===t.size&&n.delete(s)}return n}applySuppressions(t,o){const i=t.map(t=>({...t,warnings:structuredClone(t.warnings)})),c=new Map;for(const t of i){const i=t.source;if(!i)continue;const r=n.isAbsolute(i)?s(this.cwd,i):i;if(!o.has(r))continue;const u=e.countProblemsByRule(t.warnings);for(const[n,s]of u){const e=o.get(r);if(!e)continue;const i=e.get(n);if(!i)continue;const u=i.count;if(!s)continue;const f=s.count;if(f<=u&&(t.warnings=t.warnings.filter(t=>t.rule!==n)),f<u){c.has(r)||c.set(r,new Map);const t=c.get(r);if(t&&!t.has(n)&&t.set(n,{count:0}),t){const s=t.get(n);s&&(s.count=u-f)}}}const f=o.get(r);if(f)for(const[t,n]of f){if(u.has(t))continue;if(!n)continue;c.has(r)||c.set(r,new Map);const s=c.get(r);s&&s.set(t,n)}}return{results:i,unused:c}}async load(){try{const n=await t.promises.readFile(this.filePath,"utf8"),s=JSON.parse(n),o=new Map;for(const[t,n]of Object.entries(s)){const s=new Map;for(const[t,o]of Object.entries(n))s.set(t,o);o.set(t,s)}return o}catch(t){if(o(t))return new Map;throw new Error(`Failed to parse suppressions file at ${this.filePath}`)}}#n(n){const s={};for(const[t,o]of n){s[t]={};for(const[n,e]of o)s[t][n]=e}return t.promises.writeFile(this.filePath,`${JSON.stringify(s,null,2)}\n`)}static countProblemsByRule(t){const n=new Map;for(const s of t){const t=s.rule;if("error"!==s.severity||!t)continue;n.has(t)||n.set(t,{count:0});const o=n.get(t);o&&(o.count+=1)}return n}}export{e as SuppressionsService};