import{existsSync as d,readFileSync as y}from"node:fs";import{join as f,dirname as m}from"node:path";var u=class{static async loadContext(e,s,a={}){let t={},r=a.filenames||["CONTEXT.md","AGENTS.md"];if(e){let i=m(f(s,e));for(let o of r){let c=await this.findAndMergeContextFiles(o,i,s);if(c){let l=o.replace(/\.[^.]+$/,"").toLowerCase();t[l]=c}}}let n=a.discovery||{};for(let[i,o]of Object.entries(n))try{let c=f(s,o);if(d(c)){let l=await this.loadFile(c);t[i]=l}}catch(c){console.warn(`\u26A0\uFE0F  Could not load context '${i}' from '${o}': ${c.message}`)}return t}static async findAndMergeContextFiles(e,s,a){let t=[],r=s;for(;r.startsWith(a);){let n=f(r,e);if(d(n))try{let o=await this.loadFile(n);t.unshift(o)}catch(o){console.warn(`\u26A0\uFE0F  Could not load ${e} from ${n}: ${o.message}`)}let i=m(r);if(i===r)break;r=i}return t.length===0?null:t.every(n=>typeof n=="string")?t.join(`

---

`):t.every(n=>typeof n=="object")?Object.assign({},...t):t[t.length-1]}static async loadFile(e){let s=y(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(s);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:a}=await import("url"),t=await import(a(e).href);return t.default||t}return s}};export{u as ContextLoader};
