@el-j/magic-helix-core 4.0.0-beta.1 → 4.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin-plugins/cpp/index.d.ts +46 -0
- package/dist/builtin-plugins/index.d.ts +1 -0
- package/dist/default_templates/generic/lang-typescript.md +49 -3
- package/dist/default_templates/generic/style-tailwind.md +72 -2
- package/dist/default_templates/generic/test-vitest.md +126 -1
- package/dist/default_templates/vue/vue-core.md +90 -10
- package/dist/{index-BkJhe5Af.js → index-0GK4RlUx.js} +2 -2
- package/dist/{index-BkJhe5Af.js.map → index-0GK4RlUx.js.map} +1 -1
- package/dist/{index-Jz0HYZ7B.js → index-BQ6v041y.js} +2 -2
- package/dist/index-BQ6v041y.js.map +1 -0
- package/dist/index-Baxb1vI_.js +210 -0
- package/dist/index-Baxb1vI_.js.map +1 -0
- package/dist/{index-L3IVvhd1.cjs → index-BqTqxCpG.cjs} +2 -2
- package/dist/{index-L3IVvhd1.cjs.map → index-BqTqxCpG.cjs.map} +1 -1
- package/dist/{index-Dm37u5ut.js → index-DkvW5yBY.js} +362 -241
- package/dist/index-DkvW5yBY.js.map +1 -0
- package/dist/index-Dn1ehjIj.cjs +80 -0
- package/dist/index-Dn1ehjIj.cjs.map +1 -0
- package/dist/index-nioXOg4m.cjs +76 -0
- package/dist/index-nioXOg4m.cjs.map +1 -0
- package/dist/{index-J1qAfsnO.cjs → index-okhY3fWD.cjs} +2 -2
- package/dist/index-okhY3fWD.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/plugin-loader.d.ts +5 -0
- package/package.json +1 -1
- package/dist/index-B_6W_RnJ.cjs +0 -76
- package/dist/index-B_6W_RnJ.cjs.map +0 -1
- package/dist/index-Dm37u5ut.js.map +0 -1
- package/dist/index-J1qAfsnO.cjs.map +0 -1
- package/dist/index-Jz0HYZ7B.js.map +0 -1
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";var K=Object.create;var L=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var ee=Object.getOwnPropertyNames;var te=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty;var ne=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ee(e))!se.call(n,i)&&i!==t&&L(n,i,{get:()=>e[i],enumerable:!(s=Z(e,i))||s.enumerable});return n};var ie=(n,e,t)=>(t=n!=null?K(te(n)):{},ne(e||!n||!n.__esModule?L(t,"default",{value:n,enumerable:!0}):t,n));const C=require("node:path"),re=require("node:url"),j=require("node:fs"),b=require("picocolors"),oe=require("glob");var T=typeof document<"u"?document.currentScript:null;function R(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const f=R(C),p=R(j);function ae(n){if(n==="src/**/*.ts")return/^src\/.*\.ts$/;if(n==="src/**/*.vue")return/^src\/.*\.vue$/;const e=n.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&")}$`)}function ce(n,e){const t=ae(e);return n.some(s=>t.test(s))}function le(n,e,t,s){const i=new Set;for(const[r,o]of Object.entries(n.dependencies))e[r]&&i.add(e[r]);for(const r of n.configFiles)t[r]&&i.add(t[r]);for(const r in s){const o=s[r];ce(n.projectFiles,r)&&i.add(o)}return i}const O={target:"github-copilot",templateDirectory:"ai_templates",outputDirectory:".github/instructions",aiRefinement:{quality:"standard",contextLevel:"balanced",outputFormat:"markdown",tokenBudget:4e3,includeExamples:!0,includeBestPractices:!0},dependencyTagMap:{vue:"framework-vue",react:"framework-react","@angular/core":"framework-angular","@nestjs/core":"framework-nestjs",tailwindcss:"style-tailwind",primevue:"style-primevue","@mui/material":"style-mui",quasar:"style-quasar",vitest:"test-vitest",jest:"test-jest",cypress:"test-cypress",playwright:"test-playwright",rxjs:"state-rxjs",pinia:"state-pinia",redux:"state-redux",zustand:"state-zustand"},configFileTagMap:{"tailwind.config.js":"style-tailwind","tailwind.config.ts":"style-tailwind","vite.config.ts":"build-vite","vite.config.js":"build-vite","tsconfig.json":"lang-typescript"},fileGlobTagMap:{"src/**/*.vue":"framework-vue","src/**/*.tsx":"framework-react","src/**/*.go":"lang-go","src/**/*.py":"lang-python"},tagTemplateMap:{"framework-vue":[{template:"vue/vue-core.md",suffix:"vue.instructions.md"}],"state-pinia":[{template:"vue/vue-pinia.md",suffix:"vue-pinia.instructions.md"}],"style-primevue":[{template:"vue/style-primevue.md",suffix:"vue-primevue.instructions.md"}],"style-quasar":[{template:"vue/style-quasar.md",suffix:"vue-quasar.instructions.md"}],"framework-react":[{template:"react/react-core.md",suffix:"react.instructions.md"}],"state-zustand":[{template:"react/react-zustand.md",suffix:"react-zustand.instructions.md"}],"framework-nestjs":[{template:"nestjs/nestjs-core.md",suffix:"nestjs.instructions.md"}],"framework-angular":[{template:"angular/angular-core.md",suffix:"angular.instructions.md"}],"style-tailwind":[{template:"generic/style-tailwind.md",suffix:"tailwind.instructions.md"}],"style-mui":[{template:"generic/style-mui.md",suffix:"mui.instructions.md"}],"test-vitest":[{template:"generic/test-vitest.md",suffix:"vitest.instructions.md"}],"test-jest":[{template:"generic/test-jest.md",suffix:"jest.instructions.md"}],"test-cypress":[{template:"generic/test-cypress.md",suffix:"cypress.instructions.md"}],"test-playwright":[{template:"generic/test-playwright.md",suffix:"playwright.instructions.md"}],"lang-typescript":[{template:"generic/lang-typescript.md",suffix:"typescript.instructions.md"}],"lang-python":[{template:"python/lang-python.md",suffix:"python.instructions.md"}],"lang-go":[{template:"go/lang-go.md",suffix:"go.instructions.md"}],"state-rxjs":[{template:"generic/state-rxjs.md",suffix:"rxjs.instructions.md"}],"state-redux":[{template:"generic/state-redux.md",suffix:"redux.instructions.md"}]}},I={quality:"standard",contextLevel:"balanced",outputFormat:"markdown",tokenBudget:4e3,includeExamples:!0,includeBestPractices:!0};function ue(n,e){const t={...I,...e};let s=n;return s=fe(s,t.outputFormat),s=de(s,t.quality),s=ge(s,t.contextLevel),t.includeExamples||(s=pe(s)),t.includeBestPractices||(s=me(s)),s=he(s,t.tokenBudget),s}function de(n,e){switch(e){case"basic":return n.split(/\n(?=##? )/).filter(s=>{s.toLowerCase();const i=s.split(`
|
|
2
|
+
`)[0].toLowerCase();return i.includes("# ")||i.includes("overview")||i.includes("basic")||i.includes("essential")}).join(`
|
|
3
|
+
`);case"comprehensive":return n;default:return n.split(/\n(?=##? )/).filter(s=>{const i=s.split(`
|
|
4
|
+
`)[0].toLowerCase();return!i.includes("advanced")&&!i.includes("deep dive")}).join(`
|
|
5
|
+
`)}}function ge(n,e){switch(e){case"minimal":return n.split(/\n(?=##? )/).filter(s=>{const i=s.split(`
|
|
6
|
+
`)[0].toLowerCase();return!i.includes("background")&&!i.includes("why ")&&!i.includes("explanation")&&!i.includes("deep dive")}).join(`
|
|
7
|
+
`);case"extensive":return n;default:return n.split(`
|
|
8
|
+
`).filter(t=>t.startsWith("#")||t.startsWith("-")||t.startsWith("*")||t.match(/^\d+\./)||t.startsWith("```")||t.startsWith(" ")||t.trim().length===0||t.trim().length<200).join(`
|
|
9
|
+
`)}}function fe(n,e){switch(e){case"structured":return n.replace(/^### /gm,"#### ").replace(/^## /gm,"### ").replace(/^# /gm,"## ");case"conversational":return n.replace(/^- (.+)$/gm,(t,s)=>`${s}.`).replace(/\n{3,}/g,`
|
|
10
|
+
|
|
11
|
+
`);case"code-focused":{const t=n.split(`
|
|
12
|
+
`);let s=!1;return t.filter(i=>i.startsWith("```")?(s=!s,!0):s||i.startsWith("#")||i.trim().length===0?!0:i.match(/^[^.]+\./)).join(`
|
|
13
|
+
`)}default:return n}}function pe(n){let e="",t=!1,s=!1;for(const i of n.split(`
|
|
14
|
+
`)){if(i.startsWith("```")){t=!t;continue}if(!t){if(i.match(/^##+ .*example/i)){s=!0;continue}i.startsWith("##")&&(s=!1)}!t&&!s&&(e+=`${i}
|
|
15
|
+
`)}return e}function me(n){return n.split(`
|
|
16
|
+
`).filter(e=>{const t=e.toLowerCase();return!(t.match(/^##+ .*best practice/i)||t.match(/^##+ .*recommendation/i)||t.match(/^##+ .*tip/i))}).join(`
|
|
17
|
+
`)}function he(n,e){const t=e*4;if(n.length<=t)return n;const s=n.substring(0,t),i=s.lastIndexOf(`
|
|
18
|
+
## `);return i>t*.7?`${s.substring(0,i)}
|
|
19
|
+
|
|
20
|
+
<!-- Content truncated to fit token budget -->`:`${s}
|
|
21
|
+
|
|
22
|
+
<!-- Content truncated to fit token budget -->`}function ye(n){return Math.ceil(n.length/4)}const M="magic-helix.config.json",we=["ai-aligner.config.json"];function ve(n){const t=(n?[f.resolve(process.cwd(),n)]:[f.resolve(process.cwd(),M),...we.map(s=>f.resolve(process.cwd(),s))]).find((s,i)=>{const r=p.existsSync(s);return!n&&r&&i>0&&console.warn(b.yellow(` Detected legacy config file ${f.basename(s)}. Please rename it to ${M}.`)),r});if(!t)return console.log(b.gray(" No user config file found. Using built-in conventions only.")),{};try{return console.log(b.blue(" User config file found. Merging with built-in conventions.")),JSON.parse(p.readFileSync(t,"utf-8"))}catch(s){return console.error(b.red(`❌ Error parsing config file: ${s.message}`)),console.warn(b.yellow(" Please fix the JSON or remove the file. Using built-in conventions only.")),{}}}function Pe(n){const e=O,t=be(n.outputDirectory??e.outputDirectory);return{target:n.target||e.target,templateDirectory:n.templateDirectory??e.templateDirectory,outputDirectory:t,dependencyTagMap:{...e.dependencyTagMap,...n.dependencyTagMap||{}},configFileTagMap:{...e.configFileTagMap,...n.configFileTagMap||{}},fileGlobTagMap:{...e.fileGlobTagMap,...n.fileGlobTagMap||{}},tagTemplateMap:{...e.tagTemplateMap,...n.tagTemplateMap||{}},aiRefinement:{...I,...n.aiRefinement||{}}}}function be(n){const e=n.trim();if(e.endsWith(".github/instruction")||/\binstruction\/?$/.test(e)){const t=e.replace(/instruction\/?$/,"instructions");return console.warn(b.yellow(` Normalized outputDirectory from "${e}" to "${t}". Using ".github/instructions" as the default convention.`)),t}return e}class _{format(e,t,s){return e}getFileExtension(){return".md"}getFrontmatter(e,t){return`---
|
|
23
|
+
applyTo: "${e}"
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
`}}class Ce{format(e,t,s){return e.replace(/- \*\*([^*]+)\*\*/g,"- **$1** (important)")}getFileExtension(){return".md"}getFrontmatter(e,t){return`---
|
|
27
|
+
applyTo: "${e}"
|
|
28
|
+
assistant: claude
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
`}}class ke{format(e,t,s){return e.replace(/- \*\*ALWAYS\*\*/g,"- 🔴").replace(/- \*\*NEVER\*\*/g,"- ❌")}getFileExtension(){return".md"}getFrontmatter(e,t){return`---
|
|
32
|
+
applyTo: "${e}"
|
|
33
|
+
context: chat
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
`}}class Fe{format(e,t,s){return e}getFileExtension(){return".md"}getFrontmatter(e,t){return`---
|
|
37
|
+
applyTo: "${e}"
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
`}}function Se(n){switch(n){case"github-copilot":return new _;case"claude":return new Ce;case"copilot-chat":return new ke;case"generic":return new Fe;default:return new _}}const v={},Te=Object.freeze(Object.defineProperty({__proto__:null,default:v},Symbol.toStringTag,{value:"Module"}));function A(){const n=v.join(__dirname,"default_templates","patterns"),e=new Map,t=["role-definition","organization","tool-guidelines","reasoning","domain-expertise","safety","tone","environment"];for(const s of t){const i=v.join(n,s);if(!v.existsSync(i))continue;const r=v.readdirSync(i).filter(o=>o.endsWith(".md"));for(const o of r){const a=o.replace(".md",""),c=v.readFileSync(v.join(i,o),"utf-8");e.set(a,{name:a,category:s,content:c,priority:Ee(s)})}}return e}function Ee(n){return{"role-definition":1,organization:2,"tool-guidelines":3,reasoning:4,"domain-expertise":5,environment:6,tone:7,safety:8}[n]}function N(n,e){const t=[],s=n.get("expert-identity"),i=n.get("scope-boundaries");s&&t.push(s),i&&t.push(i);const r=n.get("heading-hierarchy");r&&t.push(r);const o=n.get("function-schemas"),a=n.get("usage-policies");if(o&&t.push(o),a&&t.push(a),e.framework==="react"||e.framework==="vue"){const u=n.get("react-patterns");u&&t.push(u)}if(e.libraries){if(e.libraries.includes("tailwind")){const u=n.get("tailwind-patterns");u&&t.push(u)}if(e.libraries.includes("shadcn-ui")){const u=n.get("shadcn-ui");u&&t.push(u)}}if(e.aiModel==="claude"){const u=n.get("thinking-tags"),d=n.get("concise-communication");u&&t.push(u),d&&t.push(d)}if(e.tone==="concise"){const u=n.get("concise-communication"),d=n.get("forbidden-phrases");u&&t.push(u),d&&t.push(d)}if(e.environment==="vscode"){const u=n.get("ide-features");u&&t.push(u)}const c=n.get("refusal-messages"),l=n.get("destructive-warnings");if(c&&t.push(c),l&&t.push(l),e.includePatterns)for(const u of e.includePatterns){const d=n.get(u);d&&!t.includes(d)&&t.push(d)}return e.excludePatterns?t.filter(u=>!e.excludePatterns?.includes(u.name)):t}function W(n){const e=n.sort((g,m)=>g.priority-m.priority),t=[],s=new Map;for(const g of e){s.has(g.category)||s.set(g.category,[]);const m=s.get(g.category);m&&m.push(g)}t.push(`# AI Agent Instructions
|
|
41
|
+
`);const i=s.get("role-definition");if(i){t.push(`## Role & Identity
|
|
42
|
+
`);for(const g of i)t.push(w(g.content))}const r=s.get("organization");if(r){t.push(`## Instruction Structure
|
|
43
|
+
`);for(const g of r)t.push(w(g.content))}const o=s.get("tool-guidelines");if(o){t.push(`## Tool Usage Guidelines
|
|
44
|
+
`);for(const g of o)t.push(w(g.content))}const a=s.get("reasoning");if(a){t.push(`## Reasoning & Execution Patterns
|
|
45
|
+
`);for(const g of a)t.push(w(g.content))}const c=s.get("domain-expertise");if(c){t.push(`## Domain-Specific Guidelines
|
|
46
|
+
`);for(const g of c)t.push(w(g.content))}const l=s.get("environment");if(l){t.push(`## Environment Context
|
|
47
|
+
`);for(const g of l)t.push(w(g.content))}const u=s.get("tone");if(u){t.push(`## Communication Style
|
|
48
|
+
`);for(const g of u)t.push(w(g.content))}const d=s.get("safety");if(d){t.push(`## Safety & Refusal Protocols
|
|
49
|
+
`);for(const g of d)t.push(w(g.content))}return t.join(`
|
|
50
|
+
|
|
51
|
+
`)}function w(n){let e=n.replace(/^# .+ Pattern\n+/,"");const t=e.match(/## Examples\n([\s\S]+?)(?=\n## |\n---|Z)/);return t?t[1].trim():(e=e.replace(/## Purpose\n.+?\n\n/,""),e=e.replace(/## Template\n[\s\S]+?(?=\n## |$)/,""),e=e.replace(/## Best Practices\n[\s\S]+$/,""),e.trim())}function z(n){const e=A(),t=N(e,n);return W(t)}const G=[{name:"Expert Identity",weight:1,required:!0,check:n=>/you are (an?|the) .+? (expert|specialist|assistant)/i.test(n)},{name:"Capability Declarations",weight:.8,required:!0,check:n=>/you (can|excel at|have expertise in)/i.test(n)},{name:"Scope Boundaries",weight:.7,required:!1,check:n=>/you (will not|won't|cannot|must not)/i.test(n)},{name:"Clear Headings",weight:.9,required:!0,check:n=>(n.match(/^##? /gm)||[]).length>=3},{name:"Structured Sections",weight:.8,required:!1,check:n=>/<rules>|<thinking>|```xml/i.test(n)||(n.match(/^###? /gm)||[]).length>=5},{name:"Tool Documentation",weight:1,required:!0,check:n=>/tool|function|command|api/i.test(n)&&/parameter|argument|input/i.test(n)},{name:"Tool Usage Policies",weight:.9,required:!0,check:n=>/when to use|when not to use|prefer|avoid/i.test(n)},{name:"Concrete Examples",weight:.8,required:!0,check:n=>(n.match(/```[\s\S]+?```/g)||[]).length>=2},{name:"Step-by-Step Process",weight:.7,required:!1,check:n=>/^\d+\. /gm.test(n)||/first|then|next|finally/i.test(n)},{name:"Thinking/Planning Phase",weight:.6,required:!1,check:n=>/<thinking>|before .+?, (think|plan|analyze)/i.test(n)},{name:"Confirmation Gates",weight:.8,required:!1,check:n=>/confirmation|preview|show .+? before|ask .+? before/i.test(n)},{name:"Refusal Guidelines",weight:1,required:!0,check:n=>/refuse|decline|cannot (assist|help) with|inappropriate/i.test(n)},{name:"Destructive Action Warnings",weight:.9,required:!1,check:n=>/warning|caution|delete|remove|overwrite/i.test(n)},{name:"Communication Style",weight:.5,required:!1,check:n=>/concise|brief|direct|friendly|professional|tone/i.test(n)},{name:"Forbidden Phrases",weight:.4,required:!1,check:n=>/do not (say|use|start with)|avoid (saying|phrases like)/i.test(n)}];function $(n){const e=G.map(d=>({element:d,passed:d.check(n)})),t=e.filter(d=>["Clear Headings","Structured Sections"].includes(d.element.name)),s=E(t),i=e.filter(d=>["Concrete Examples","Communication Style","Forbidden Phrases"].includes(d.element.name)),r=E(i),o=e.filter(d=>d.element.required),a=E(o),c=Math.round(s*.3+r*.2+a*.5),l=e.filter(d=>d.element.required&&!d.passed).map(d=>d.element.name),u=je(e,n);return{overallScore:c,structureScore:s,clarityScore:r,completenessScore:a,recommendations:u,missingElements:l}}function E(n){if(n.length===0)return 100;const e=n.reduce((s,i)=>s+i.element.weight,0),t=n.filter(s=>s.passed).reduce((s,i)=>s+i.element.weight,0);return Math.round(t/e*100)}function je(n,e){const t=[],s=n.filter(a=>a.element.required&&!a.passed);s.length>0&&t.push(`Add ${s.length} critical element(s): ${s.map(a=>a.element.name).join(", ")}`),n.find(a=>a.element.name==="Expert Identity")?.passed||t.push('Add expert identity: Start with "You are an expert [domain] specialist..."'),n.find(a=>a.element.name==="Tool Documentation")?.passed||t.push("Add tool documentation: Include function schemas with parameters and examples"),n.find(a=>a.element.name==="Refusal Guidelines")?.passed||t.push("Add refusal guidelines: Specify what requests should be declined and how");const i=(e.match(/```[\s\S]+?```/g)||[]).length;i<3&&t.push(`Add more code examples: Currently ${i}, aim for at least 5 concrete examples`),/✅|❌|good:|bad:/i.test(e)||t.push("Add ✅/❌ comparisons: Show good vs bad examples for clarity");const o=e.split(/\s+/).length;return o<500?t.push(`Instructions may be too brief (${o} words). Aim for 1000-3000 words for comprehensive guidance.`):o>5e3&&t.push(`Instructions may be too long (${o} words). Consider breaking into sections or modules.`),n.find(a=>a.element.name==="Confirmation Gates")?.passed||t.push("Consider adding confirmation gates for destructive operations (delete, overwrite)"),t.length===0&&t.push("Instructions meet quality standards. Consider A/B testing variants for optimization."),t}function xe(n,e=70){return $(n).overallScore>=e}function q(n){return n>=90?"A":n>=80?"B":n>=70?"C":n>=60?"D":"F"}function Ie(n){const e=[];if(e.push(`=== Instruction Quality Report ===
|
|
52
|
+
`),e.push(`Overall Score: ${n.overallScore}/100 (${q(n.overallScore)})
|
|
53
|
+
`),e.push(` Structure: ${n.structureScore}/100`),e.push(` Clarity: ${n.clarityScore}/100`),e.push(` Completeness: ${n.completenessScore}/100
|
|
54
|
+
`),n.missingElements.length>0){e.push("❌ Missing Critical Elements:");for(const t of n.missingElements)e.push(` - ${t}`);e.push("")}if(n.recommendations.length>0){e.push("💡 Recommendations:");for(const t of n.recommendations)e.push(` - ${t}`);e.push("")}return e.join(`
|
|
55
|
+
`)}let B=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.name)&&console.warn(`Plugin "${e.name}" is already registered. Overwriting.`),this.plugins.set(e.name,e)}unregister(e){return this.plugins.delete(e)}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}clear(){this.plugins.clear()}get size(){return this.plugins.size}};const h=new B;class $e{constructor(e,t=new Map){this.analysisData=e,this.fileContentCache=t}get files(){return this.analysisData.projectFiles}get dependencies(){return this.analysisData.dependencies}get configFiles(){return this.analysisData.configFiles}getTextFile(e){return this.fileContentCache.has(e)&&this.fileContentCache.get(e)||null}hasFile(e){return this.analysisData.projectFiles.includes(e)||this.analysisData.configFiles.includes(e)}matchesPattern(e){const t=this.globToRegex(e);return this.analysisData.projectFiles.some(s=>t.test(s))}globToRegex(e){const t=e.replace(/\\/g,"\\\\").replace(/\*\*/g,"§DOUBLESTAR§").replace(/\*/g,"[^/]*").replace(/§DOUBLESTAR§/g,".*").replace(/\./g,"\\.");return new RegExp(`^${t}$`)}}async function De(n,e){const t=new Set,s=[],i=new Map,r=new Map;if(e)for(const c of n.configFiles){const l=e(c);l&&r.set(c,l)}const o=new $e(n,r);if(e){const c=o.getTextFile.bind(o);o.getTextFile=l=>{const u=c(l);return u!==null?u:e(l)}}const a=h.getAll();for(const c of a)try{const l=await Promise.resolve(c.detect(o));if(l.detected){if(l.tags)for(const d of l.tags)t.add(d);l.metadata&&i.set(c.name,l.metadata);const u=await Promise.resolve(c.generateInstructions(o,l.metadata));s.push(...u)}}catch(l){console.error(`Error running plugin ${c.name}:`,l)}return{tags:t,instructions:s,metadata:i}}function Le(){Promise.resolve().then(()=>require("./index-okhY3fWD.cjs")).then(n=>{h.register(new n.GolangPlugin),h.register(new n.PythonPlugin),h.register(new n.RustPlugin),h.register(new n.PHPPlugin),h.register(new n.DockerPlugin),h.register(new n.GitHubActionsPlugin),h.register(new n.GitLabCIPlugin),h.register(new n.MonorepoPlugin),h.register(new n.CodeOwnersPlugin)})}class Me{constructor(){this.name="codeowners",this.description="Detects CODEOWNERS file and provides code ownership instructions",this.version="1.0.0"}detect(e){if(!(e.hasFile(".github/CODEOWNERS")||e.hasFile("CODEOWNERS")||e.hasFile("docs/CODEOWNERS")))return{detected:!1};const s={hasCodeOwners:!0};let i="";e.hasFile(".github/CODEOWNERS")?i=".github/CODEOWNERS":e.hasFile("CODEOWNERS")?i="CODEOWNERS":i="docs/CODEOWNERS",s.location=i;const r=e.getTextFile(i);if(r){const a=r.split(`
|
|
56
|
+
`).filter(l=>l.trim()&&!l.trim().startsWith("#"));s.ruleCount=a.length;const c=new Set;for(const l of a){const u=l.trim().split(/\s+/);if(u.length>1)for(const d of u.slice(1))d.startsWith("@")&&c.add(d)}s.ownerCount=c.size,s.owners=Array.from(c).slice(0,10)}return{detected:!0,tags:["architecture-codeowners"],metadata:s}}generateInstructions(e,t){return[{template:"architecture/codeowners.md",suffix:"codeowners.md",targetFiles:[".github/CODEOWNERS","CODEOWNERS","docs/CODEOWNERS"]}]}}class _e{constructor(){this.name="docker",this.description="Detects Docker usage and provides Docker-specific instructions",this.version="1.0.0"}detect(e){const t=e.hasFile("Dockerfile")||e.matchesPattern("**/Dockerfile"),s=e.hasFile("docker-compose.yml")||e.hasFile("docker-compose.yaml")||e.hasFile("compose.yml")||e.hasFile("compose.yaml"),i=e.hasFile(".dockerignore");if(!(t||s))return{detected:!1};const o={hasDockerfile:t,hasDockerCompose:s,hasDockerignore:i};if(t){const a=e.getTextFile("Dockerfile");if(a){const c=(a.match(/FROM\s+\S+\s+AS\s+\S+/gi)||[]).length;c>0&&(o.multiStage=!0,o.stageCount=c)}}return{detected:!0,tags:["devops-docker"],metadata:o}}generateInstructions(e,t){const s=[];return t?.hasDockerfile&&s.push({template:"devops/docker-dockerfile.md",suffix:"docker-dockerfile.md",targetFiles:["**/Dockerfile"]}),t?.hasDockerCompose&&s.push({template:"devops/docker-compose.md",suffix:"docker-compose.md",targetFiles:["**/docker-compose.yml","**/docker-compose.yaml","**/compose.yml","**/compose.yaml"]}),s}}class Re{constructor(){this.name="github-actions",this.description="Detects GitHub Actions workflows and provides CI/CD-specific instructions",this.version="1.0.0"}detect(e){if(!(e.matchesPattern(".github/workflows/*.yml")||e.matchesPattern(".github/workflows/*.yaml")))return{detected:!1};const s={hasWorkflows:!0},i=e.files.filter(r=>r.startsWith(".github/workflows/")&&(r.endsWith(".yml")||r.endsWith(".yaml")));if(i.length>0){s.workflowCount=i.length,s.workflowFiles=i;const r=e.getTextFile(i[0]);r&&(s.hasMatrixStrategy=r.includes("strategy:")&&r.includes("matrix:"),s.hasCaching=r.includes("actions/cache")||r.includes("cache:"),s.hasArtifacts=r.includes("actions/upload-artifact")||r.includes("actions/download-artifact"))}return{detected:!0,tags:["devops-github-actions","ci-cd"],metadata:s}}generateInstructions(e,t){return[{template:"devops/github-actions.md",suffix:"github-actions.md",targetFiles:[".github/workflows/*.yml",".github/workflows/*.yaml"]}]}}class Oe{constructor(){this.name="gitlab-ci",this.description="Detects GitLab CI/CD configuration and provides CI/CD-specific instructions",this.version="1.0.0"}detect(e){if(!e.hasFile(".gitlab-ci.yml"))return{detected:!1};const s={hasGitLabCI:!0},i=e.getTextFile(".gitlab-ci.yml");if(i){i.match(/^stages:\s*$/m)&&(s.hasStages=!0),s.hasCache=i.includes("cache:"),s.hasArtifacts=i.includes("artifacts:"),s.hasServices=i.includes("services:"),s.hasIncludes=i.includes("include:");const o=i.match(/^stages:\s*\n((?: {2}- .+\n?)+)/m);if(o){const a=o[1].match(/- (.+)/g)?.map(c=>c.replace(/- /,"").trim());a&&(s.stages=a)}}return{detected:!0,tags:["devops-gitlab-ci","ci-cd"],metadata:s}}generateInstructions(e,t){return[{template:"devops/gitlab-ci.md",suffix:"gitlab-ci.md",targetFiles:[".gitlab-ci.yml"]}]}}class Ae{constructor(){this.name="golang",this.description="Detects Go (Golang) projects and provides Go-specific instructions",this.version="1.0.0"}detect(e){const t=e.hasFile("go.mod"),s=e.matchesPattern("**/*.go");if(!(t||s))return{detected:!1};const r=e.getTextFile("go.mod"),o={hasGoMod:t,hasGoFiles:s};if(r){const a=r.match(/^module\s+(.+)$/m);a&&(o.moduleName=a[1].trim());const c=r.match(/^go\s+([\d.]+)$/m);c&&(o.goVersion=c[1])}return{detected:!0,tags:["lang-go"],metadata:o}}generateInstructions(e,t){return[{template:"go/lang-go.md",suffix:"lang-go.md",targetFiles:["**/*.go"]}]}}class Ne{constructor(){this.name="monorepo",this.description="Detects monorepo structures and provides monorepo-specific instructions",this.version="1.0.0"}detect(e){const t=e.hasFile("turbo.json"),s=e.hasFile("nx.json"),i=e.hasFile("pnpm-workspace.yaml"),r=e.hasFile("lerna.json"),o=e.hasFile("package.json")&&e.getTextFile("package.json")?.includes('"workspaces"');if(e.hasFile("package.json")&&e.getTextFile("package.json")?.includes('"workspaces"'),!(t||s||i||r||o))return{detected:!1};const c={hasTurbo:t,hasNx:s,hasPnpmWorkspace:i,hasLerna:r,hasYarnWorkspaces:o};if(t){c.tool="turborepo";const d=e.getTextFile("turbo.json");d&&(c.hasPipeline=d.includes('"pipeline"'))}else s?c.tool="nx":i?c.tool="pnpm":r?c.tool="lerna":c.tool="npm/yarn workspaces";const l=["packages/*/package.json","apps/*/package.json"],u=e.files.filter(d=>l.some(g=>new RegExp(g.replace(/\*/g,"[^/]+")).test(d)));return u.length>0&&(c.packageCount=u.length),{detected:!0,tags:["architecture-monorepo"],metadata:c}}generateInstructions(e,t){const s=[{template:"architecture/monorepo.md",suffix:"monorepo.md",targetFiles:["package.json","turbo.json","nx.json","pnpm-workspace.yaml","lerna.json"]}];return t?.tool==="turborepo"?s.push({template:"architecture/turborepo.md",suffix:"turborepo.md",targetFiles:["turbo.json"]}):t?.tool==="nx"&&s.push({template:"architecture/nx.md",suffix:"nx.md",targetFiles:["nx.json","workspace.json"]}),s}}class We{constructor(){this.name="php",this.description="Detects PHP projects and provides PHP-specific instructions",this.version="1.0.0"}detect(e){const t=e.hasFile("composer.json"),s=e.hasFile("composer.lock"),i=e.matchesPattern("**/*.php");if(!(t||i))return{detected:!1};const o={hasComposerJson:t,hasComposerLock:s,hasPhpFiles:i},a=e.getTextFile("composer.json");if(a){a.includes('"laravel/framework"')?(o.framework="laravel",o.hasArtisan=e.hasFile("artisan")):a.includes('"symfony/')&&(o.framework="symfony");const c=a.match(/"name"\s*:\s*"([^"]+)"/);c&&(o.projectName=c[1])}return{detected:!0,tags:["lang-php"],metadata:o}}generateInstructions(e,t){const s=[{template:"php/lang-php.md",suffix:"lang-php.md",targetFiles:["**/*.php"]}];return t?.framework==="laravel"&&s.push({template:"php/framework-laravel.md",suffix:"framework-laravel.md",targetFiles:["**/*.php"]}),s}}class ze{constructor(){this.name="python",this.description="Detects Python projects and provides Python-specific instructions",this.version="1.0.0"}detect(e){const t=e.hasFile("pyproject.toml"),s=e.hasFile("requirements.txt"),i=e.hasFile("setup.py"),r=e.hasFile("Pipfile"),o=e.matchesPattern("**/*.py");if(!(t||s||i||r||o))return{detected:!1};const c={hasPyprojectToml:t,hasRequirementsTxt:s,hasSetupPy:i,hasPipfile:r,hasPyFiles:o};if(t){const d=e.getTextFile("pyproject.toml");d&&(d.includes("[tool.poetry]")?c.packageManager="poetry":d.includes("[build-system]")&&(c.packageManager="pip"))}else r?c.packageManager="pipenv":s&&(c.packageManager="pip");const l=[],u=e.getTextFile("requirements.txt");return u&&(u.includes("django")&&l.push("django"),u.includes("flask")&&l.push("flask"),u.includes("fastapi")&&l.push("fastapi")),l.length>0&&(c.frameworks=l),{detected:!0,tags:["lang-python"],metadata:c}}generateInstructions(e,t){return[{template:"python/lang-python.md",suffix:"lang-python.md",targetFiles:["**/*.py"]}]}}class Ge{constructor(){this.name="rust",this.description="Detects Rust projects and provides Rust-specific instructions",this.version="1.0.0"}detect(e){const t=e.hasFile("Cargo.toml"),s=e.hasFile("Cargo.lock"),i=e.matchesPattern("**/*.rs");if(!(t||i))return{detected:!1};const o=e.getTextFile("Cargo.toml"),a={hasCargoToml:t,hasCargoLock:s,hasRustFiles:i};if(o){const c=o.match(/^\[package\][\s\S]*?^name\s*=\s*"(.+?)"/m);c&&(a.packageName=c[1]);const l=o.match(/^edition\s*=\s*"(\d+)"/m);l&&(a.edition=l[1]),o.includes("[workspace]")&&(a.isWorkspace=!0)}return{detected:!0,tags:["lang-rust"],metadata:a}}generateInstructions(e,t){return[{template:"rust/lang-rust.md",suffix:"lang-rust.md",targetFiles:["**/*.rs"]}]}}class x{constructor(e={}){this.loadedPlugins=new Map,this.loadErrors=[],this.verbose=e.verbose??!1}async loadBuiltinPlugins(e){const t=[];try{const{NodeJSPlugin:s}=await Promise.resolve().then(()=>require("./index-B6BeG1yT.cjs")),{GoPlugin:i}=await Promise.resolve().then(()=>require("./index-TPAX4XKg.cjs")),{PythonPlugin:r}=await Promise.resolve().then(()=>require("./index-K39pdw94.cjs")),{RustPlugin:o}=await Promise.resolve().then(()=>require("./index-BqTqxCpG.cjs")),{JavaPlugin:a}=await Promise.resolve().then(()=>require("./index-CN8J45Nc.cjs")),{RubyPlugin:c}=await Promise.resolve().then(()=>require("./index-DO30AzDe.cjs")),{PHPPlugin:l}=await Promise.resolve().then(()=>require("./index-DDPXXXDy.cjs")),{CSharpPlugin:u}=await Promise.resolve().then(()=>require("./index-DqHvgoXJ.cjs")),{SwiftPlugin:d}=await Promise.resolve().then(()=>require("./index-Bv4Q1Pr7.cjs")),{CppPlugin:g}=await Promise.resolve().then(()=>require("./index-Dn1ehjIj.cjs")),m=[s,i,r,o,a,c,l,u,d,g];for(const S of m){const P=new S;if(e&&!e.includes(P.name))continue;const X=Date.now(),D={plugin:P,source:{type:"builtin",identifier:P.name,packageName:"magic-helix-plugins"},loadTime:Date.now()-X};this.loadedPlugins.set(P.name,D),t.push(D),this.log(`Loaded built-in plugin: ${P.displayName} (${P.name})`)}}catch(s){this.handleLoadError({type:"builtin",identifier:"magic-helix-plugins"},s)}return t}async loadNpmPlugin(e){try{const t=Date.now(),s=await this.tryImport(e);if(!s)throw new Error(`Package "${e}" not found`);const i=s.default||s.Plugin||s;if(typeof i!="function")throw new Error(`Package "${e}" does not export a valid plugin class`);const r=new i,o=Date.now()-t;this.validatePlugin(r);const a={plugin:r,source:{type:"npm",identifier:e,packageName:e},loadTime:o};return this.loadedPlugins.set(r.name,a),this.log(`✓ Loaded npm plugin: ${r.displayName} from ${e} (${o}ms)`),a}catch(t){return this.handleLoadError({type:"npm",identifier:e,packageName:e},t),null}}async loadLocalPlugin(e){try{const t=f.resolve(e);if(!p.existsSync(t))throw new Error(`Plugin file not found: ${t}`);const s=Date.now(),i=await import(t),r=Date.now()-s,o=i.default||i.Plugin||i;if(typeof o!="function")throw new Error(`File "${e}" does not export a valid plugin class`);const a=new o;this.validatePlugin(a);const c={plugin:a,source:{type:"local",identifier:e,path:t},loadTime:r};return this.loadedPlugins.set(a.name,c),this.log(`✓ Loaded local plugin: ${a.displayName} from ${e} (${r}ms)`),c}catch(t){return this.handleLoadError({type:"local",identifier:e,path:e},t),null}}async loadWorkspacePlugins(e,t){const s=[],i=t||[".magic-helix/plugins/**/*.js",".magic-helix/plugins/**/*.mjs"];try{const{glob:r}=await import("glob");for(const o of i){const a=await r(o,{cwd:e,absolute:!0});for(const c of a){const l=await this.loadLocalPlugin(c);l&&(l.source.type="workspace",s.push(l))}}}catch(r){this.logWarning(`Error loading workspace plugins: ${r.message}`)}return s}getPlugin(e){return this.loadedPlugins.get(e)?.plugin}getAllPlugins(){return Array.from(this.loadedPlugins.values()).map(e=>e.plugin).sort((e,t)=>t.priority-e.priority)}getPluginsByNames(e){return e.map(t=>this.getPlugin(t)).filter(t=>t!==void 0)}async detectProject(e){const t=this.getAllPlugins();for(const s of t)try{this.log(`Trying plugin: ${s.displayName}`);const i=await s.detect(e);if(i)return this.log(`✓ Detected ${i.language} project with ${s.displayName}`),{metadata:i,plugin:s}}catch(i){this.logWarning(`Plugin ${s.name} detection failed: ${i.message}`)}return null}async scanForProjects(e,t=5){const s=new Set,i=new Set,r=["package.json","Cargo.toml","go.mod","go.sum","setup.py","pyproject.toml","requirements.txt","pom.xml","build.gradle","build.gradle.kts","Package.swift","Gemfile","composer.json","CMakeLists.txt","Makefile","platformio.ini"],o=new Set(["node_modules","target","dist","build",".git",".svn",".hg","vendor","__pycache__",".venv","venv","env",".cargo",".gradle"]),a=async(c,l)=>{if(l>t)return;const u=f.normalize(c);if(!i.has(u)){i.add(u);try{const d=await p.promises.readdir(c,{withFileTypes:!0});let g=!1;for(const m of d)if(!m.isDirectory()&&r.includes(m.name)){s.add(c),g=!0;break}for(const m of d)if(m.isDirectory()&&!o.has(m.name)){const S=f.join(c,m.name);await a(S,l+1)}}catch{return}}};return await a(e,0),Array.from(s).sort()}async detectAllProjects(e){const t=[],s=new Set,i=this.getAllPlugins();for(const r of i)try{const o=await r.detect(e);if(o&&(s.add(o.projectPath),t.push({metadata:o,plugin:r}),o.workspaceMembers&&o.workspaceMembers.length>0))for(const a of o.workspaceMembers){const c=f.resolve(e,a);if(!s.has(c)){const l=await this.detectProject(c);l&&(s.add(l.metadata.projectPath),t.push(l))}}}catch(o){this.logWarning(`Plugin ${r.name} failed: ${o.message}`)}try{const r=await this.scanForProjects(e);for(const o of r)if(!s.has(o)){const a=await this.detectProject(o);a&&(s.add(a.metadata.projectPath),t.push(a))}}catch(r){this.logWarning(`Recursive scan failed: ${r.message}`)}return t}getLoadErrors(){return[...this.loadErrors]}clear(){this.loadedPlugins.clear(),this.loadErrors=[]}getStats(){const e=Array.from(this.loadedPlugins.values()),t={};for(const s of e)t[s.source.type]=(t[s.source.type]||0)+1;return{totalLoaded:e.length,totalErrors:this.loadErrors.length,averageLoadTime:e.length>0?e.reduce((s,i)=>s+i.loadTime,0)/e.length:0,byType:t}}validatePlugin(e){if(!e||typeof e!="object")throw new Error("Plugin must be an object");const t=e;if(!t.name||typeof t.name!="string")throw new Error('Plugin must have a "name" property');if(!t.displayName||typeof t.displayName!="string")throw new Error('Plugin must have a "displayName" property');if(!t.version||typeof t.version!="string")throw new Error('Plugin must have a "version" property');if(typeof t.priority!="number")throw new Error('Plugin must have a "priority" property');if(typeof t.detect!="function")throw new Error('Plugin must implement "detect" method');if(typeof t.getTemplates!="function")throw new Error('Plugin must implement "getTemplates" method')}async tryImport(e){try{return await import(e)}catch{return null}}handleLoadError(e,t){this.loadErrors.push({source:e,error:t,timestamp:new Date}),this.logWarning(`Failed to load plugin "${e.identifier}": ${t.message}`)}log(e){this.verbose&&console.log(`[PluginLoader] ${e}`)}logWarning(e){this.verbose&&console.warn(`[PluginLoader] ⚠️ ${e}`)}}const y=class y{constructor(){this.initialized=!1,this.loader=new x({verbose:!1}),this.config={}}static getInstance(){return y.instance||(y.instance=new y),y.instance}async initialize(e={}){if(!this.initialized&&(this.config=e,this.loader=new x({verbose:e.verbose}),await this.loadConfiguredPlugins(e.plugins),this.initialized=!0,e.verbose)){const t=this.loader.getStats();console.log(`[PluginRegistry] Initialized with ${t.totalLoaded} plugins`),console.log(`[PluginRegistry] Load time: ${t.averageLoadTime.toFixed(2)}ms avg`)}}reset(){this.loader.clear(),this.initialized=!1,this.config={}}async ensureInitialized(){this.initialized||await this.initialize()}async getPlugin(e){return await this.ensureInitialized(),this.loader.getPlugin(e)}async getAllPlugins(){return await this.ensureInitialized(),this.loader.getAllPlugins()}async detectProject(e){return await this.ensureInitialized(),this.loader.detectProject(e)}async detectAllProjects(e){return await this.ensureInitialized(),this.loader.detectAllProjects(e)}async getPluginForLanguage(e){await this.ensureInitialized();const t=this.loader.getAllPlugins();let s=t.find(i=>i.name===e.toLowerCase());return s||(s=t.find(i=>i.displayName.toLowerCase()===e.toLowerCase()),s)||(s=t.find(i=>i.displayName.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(i.name))),s}async loadPlugin(e){return await this.ensureInitialized(),(e.type==="npm"?await this.loader.loadNpmPlugin(e.path):await this.loader.loadLocalPlugin(e.path))?.plugin??null}async getStats(){await this.ensureInitialized();const e=this.loader.getStats();return{totalPlugins:e.totalLoaded,loadErrors:e.totalErrors,averageLoadTime:e.averageLoadTime,pluginsByType:e.byType}}async getLoadErrors(){return await this.ensureInitialized(),this.loader.getLoadErrors().map(e=>({source:e.source.identifier,error:e.error.message,timestamp:e.timestamp}))}getStatistics(){return this.loader.getStats()}async loadConfiguredPlugins(e={}){const{builtin:t=[],npm:s=[],local:i=[],workspace:r=[],disabled:o=[]}=e;if(t.length>0){const a=t.filter(c=>!o.includes(c));await this.loader.loadBuiltinPlugins(a)}else await this.loader.loadBuiltinPlugins();o.includes("@el-j/magic-helix-plugins")||await this.loader.loadNpmPlugin("@el-j/magic-helix-plugins").catch(()=>{});for(const a of s)o.includes(a)||await this.loader.loadNpmPlugin(a);for(const a of i)if(!o.includes(a)){const c=this.resolvePath(a);await this.loader.loadLocalPlugin(c)}this.config.workspacePath&&r.length>0&&await this.loader.loadWorkspacePlugins(this.config.workspacePath,r),e.priority&&this.applyPriorityOverrides(e.priority)}resolvePath(e){if(e.startsWith("~/")){const s=process.env.HOME||process.env.USERPROFILE||"";return f.join(s,e.slice(2))}if(f.isAbsolute(e))return e;const t=this.config.workspacePath||process.cwd();return f.resolve(t,e)}applyPriorityOverrides(e){for(const[t,s]of Object.entries(e)){const i=this.loader.getPlugin(t);i&&(i.priority=s)}}static async loadConfigFromFile(e){try{if(!p.existsSync(e))return null;const t=p.readFileSync(e,"utf-8");return JSON.parse(t)}catch(t){return console.warn(`Failed to load config from ${e}: ${t.message}`),null}}static async loadConfig(e){const t=[],s=process.env.HOME||process.env.USERPROFILE;if(s){const i=f.join(s,".magic-helix","config.json"),r=await y.loadConfigFromFile(i);r&&t.push(r)}if(e){const i=f.join(e,".magic-helix.json"),r=await y.loadConfigFromFile(i);r&&(r.workspacePath=e,t.push(r))}return t.length===0?{workspacePath:e}:t.reduce((i,r)=>{const o={...i.plugins||{},...r.plugins||{}},a={...i.templates||{},...r.templates||{}};return Object.assign({},i,r,{plugins:o,templates:a})},{workspacePath:e})}};y.instance=null;let k=y;function qe(){return k.getInstance()}async function Be(n){const e=k.getInstance();return await e.initialize(n),e}class Ue{constructor(e={}){this.templateCache=new Map,this.config=e.config||{},this.verbose=e.verbose??!1,this.cacheEnabled=e.cacheEnabled??!0}async loadTemplate(e,t=[]){const s=`${e}:${t.map(i=>i.name).join(",")}`;if(this.cacheEnabled&&this.templateCache.has(s)){const i=this.templateCache.get(s);if(i)return{content:i,source:"plugin",path:"(cached)"}}if(this.config.overrides?.[e]){const i=this.config.overrides[e],r=await this.loadFromPath(i,"override");if(r)return this.cacheTemplate(s,r.content),r}if(this.config.searchPaths)for(const i of this.config.searchPaths){const r=await this.searchInDirectory(i,e,i.includes(".magic-helix")?"workspace":"global");if(r)return this.cacheTemplate(s,r.content),r}for(const i of t){const r=await this.loadFromPlugin(i,e);if(r)return this.cacheTemplate(s,r.content),r}return this.log(`Template "${e}" not found`),null}async loadPluginTemplates(e){try{const t=await Promise.resolve(e.getTemplates());return this.log(`Loaded ${t.length} templates from ${e.displayName}`),t}catch(t){return this.logWarning(`Failed to load templates from ${e.name}: ${t.message}`),[]}}async loadTemplates(e,t=[]){const s=new Map;for(const i of e){const r=await this.loadTemplate(i,t);r&&s.set(i,r)}return s}async findTemplatesByTags(e,t=[]){const s=[];for(const i of t){const r=await this.loadPluginTemplates(i);s.push(...r)}return s.filter(i=>i.tags.some(r=>e.includes(r)))}async resolveTemplateContent(e){return typeof e.content=="string"?e.content:await Promise.resolve(e.content())}clearCache(){this.templateCache.clear(),this.log("Template cache cleared")}getCacheStats(){return{size:this.templateCache.size,keys:Array.from(this.templateCache.keys())}}async loadFromPath(e,t){try{const s=this.resolvePath(e);if(!p.existsSync(s))return this.log(`Template not found at: ${s}`),null;const i=p.readFileSync(s,"utf-8");return this.log(`✓ Loaded template from ${t}: ${s}`),{content:i,source:t,path:s}}catch(s){return this.logWarning(`Failed to load template from ${e}: ${s.message}`),null}}async searchInDirectory(e,t,s){const i=this.resolvePath(e);if(!p.existsSync(i))return null;const r=this.config.extensions||[".md",".txt",""];for(const o of r){const a=t.endsWith(o)?t:`${t}${o}`,c=f.join(i,a);if(p.existsSync(c))return this.loadFromPath(c,s)}return null}async loadFromPlugin(e,t){try{const i=(await this.loadPluginTemplates(e)).find(o=>o.name===t);if(!i)return null;const r=await this.resolveTemplateContent(i);return this.log(`✓ Loaded template "${t}" from plugin: ${e.displayName}`),{content:r,source:"plugin",path:`plugin:${e.name}/${t}`,plugin:e.name}}catch(s){return this.logWarning(`Failed to load template "${t}" from plugin ${e.name}: ${s.message}`),null}}resolvePath(e){if(e.startsWith("~/")){const t=process.env.HOME||process.env.USERPROFILE||"";return f.join(t,e.slice(2))}return f.isAbsolute(e)?e:f.resolve(process.cwd(),e)}cacheTemplate(e,t){this.cacheEnabled&&this.templateCache.set(e,t)}log(e){this.verbose&&console.log(`[TemplateLoader] ${e}`)}logWarning(e){this.verbose&&console.warn(`[TemplateLoader] ⚠️ ${e}`)}}const F=".magic-helix",U="meta-instructions.json";function H(n){const e=f.join(n,F,U);if(!p.existsSync(e))return null;try{const t=p.readFileSync(e,"utf-8");return JSON.parse(t)}catch(t){return console.warn(`Failed to load meta-instruction config: ${t.message}`),null}}function V(n){const e=f.join(n,F,"overrides"),t=new Map;if(!p.existsSync(e))return t;const s=oe.glob.sync("**/*.md",{cwd:e,absolute:!0});for(const i of s){const r=f.basename(i,".md"),o=p.readFileSync(i,"utf-8");t.set(r,o)}return t}function J(n,e,t){const s=new Map(n);if(e.ignoreTags)for(const r of e.ignoreTags)s.delete(r);const i=V(t);for(const[r,o]of i)s.set(r,o);if(e.overrides)for(const r of e.overrides){const o=s.get(r.tag);switch(r.mode){case"replace":s.set(r.tag,r.content);break;case"prepend":o?s.set(r.tag,`${r.content}
|
|
57
|
+
|
|
58
|
+
${o}`):s.set(r.tag,r.content);break;case"append":o?s.set(r.tag,`${o}
|
|
59
|
+
|
|
60
|
+
${r.content}`):s.set(r.tag,r.content);break}}return s}function Y(n,e){const t=new Map(n);let s=e.template;for(const i of e.tags){const r=n.get(i);r&&(s=s.replace(`{{${i}}}`,r))}return t.set(e.outputTag,s),t}function He(n,e){const t=H(e);if(!t)return n;let s=J(n,t,e);if(t.combiners)for(const i of t.combiners)s=Y(s,i);return s}function Ve(n){const e=f.join(n,F);return p.existsSync(e)}function Je(n){const e=f.join(n,F),t=f.join(e,"overrides");p.mkdirSync(e,{recursive:!0}),p.mkdirSync(t,{recursive:!0});const s={overrides:[{tag:"example-tag",content:`# Custom Instruction
|
|
61
|
+
|
|
62
|
+
Your content here...`,mode:"replace"}],combiners:[{tags:["tag1","tag2"],outputTag:"combined-tag",template:`# Combined Instructions
|
|
63
|
+
|
|
64
|
+
{{tag1}}
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
{{tag2}}`}],ignoreTags:["unwanted-tag"]},i=f.join(e,U);p.writeFileSync(i,JSON.stringify(s,null,2)),p.writeFileSync(f.join(t,"example.md"),`# Example Override
|
|
69
|
+
|
|
70
|
+
This file overrides the default instructions for this tag.
|
|
71
|
+
Create files like:
|
|
72
|
+
- react-core.md → overrides "react-core" tag
|
|
73
|
+
- style-tailwind.md → overrides "style-tailwind" tag
|
|
74
|
+
`),console.log(`✅ Initialized .magic-helix/ directory structure at: ${e}`)}class Q{constructor(e={}){this.enabled=!!e.enabled;const t=e.dir||C.resolve(process.cwd(),".magic-helix/telemetry");this.filePath=C.join(t,"events.jsonl"),this.sessionId=e.sessionId,this.variant=e.variant,this.projectRoot=e.projectRoot,this.enabled&&j.mkdirSync(C.dirname(this.filePath),{recursive:!0})}isEnabled(){return this.enabled}track(e){if(!this.enabled)return;const t={...e,timestamp:new Date().toISOString(),sessionId:this.sessionId,projectRoot:this.projectRoot};"variant"in e&&e.variant?t.variant=e.variant:t.variant=this.variant;const s=`${JSON.stringify(t)}
|
|
75
|
+
`;j.appendFileSync(this.filePath,s,"utf-8")}}function Ye(n={}){const e=n.enabled??process.env.MAGIC_HELIX_TELEMETRY==="1",t=n.dir||process.env.MAGIC_HELIX_TELEMETRY_DIR,s=n.sessionId||process.env.MAGIC_HELIX_SESSION_ID||`${Date.now()}`,i=n.variant||process.env.MAGIC_HELIX_VARIANT||"default",r=n.projectRoot||process.cwd();return new Q({enabled:e,dir:t,sessionId:s,variant:i,projectRoot:r})}function Qe(n){return n.map(e=>{const t=z(e.context),s=$(t);return{variant:e.name,instructions:t,score:s.overallScore,structureScore:s.structureScore,clarityScore:s.clarityScore,completenessScore:s.completenessScore,missingCount:s.missingElements.length}})}function Xe(n){return n.length===0?{variant:"",instructions:"",score:0,structureScore:0,clarityScore:0,completenessScore:0,missingCount:0}:n.reduce((e,t)=>t.score>e.score?t:e,n[0])}function Ke(n,e){if(e?.isEnabled())for(const t of n){const s={type:"instruction_validation",file:`ab-test-variant-${t.variant}`,score:t.score,structureScore:t.structureScore,clarityScore:t.clarityScore,completenessScore:t.completenessScore,missingCount:t.missingCount,variant:t.variant};e.track(s)}}const Ze=re.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("index-nioXOg4m.cjs",document.baseURI).href),et=C.dirname(Ze),tt=C.resolve(et,"default_templates");exports.BUILT_IN_CONFIG=O;exports.BUILT_IN_TEMPLATE_DIR=tt;exports.CodeOwnersPlugin=Me;exports.DEFAULT_AI_REFINEMENT=I;exports.DockerPlugin=_e;exports.GitHubActionsPlugin=Re;exports.GitLabCIPlugin=Oe;exports.GolangPlugin=Ae;exports.INSTRUCTION_ELEMENTS=G;exports.MonorepoPlugin=Ne;exports.PHPPlugin=We;exports.PluginLoader=x;exports.PluginRegistry=B;exports.PluginRegistry$1=k;exports.PythonPlugin=ze;exports.RustPlugin=Ge;exports.TelemetryClient=Q;exports.TemplateLoader=Ue;exports.__viteBrowserExternal=Te;exports.analyzeBestVariant=Xe;exports.analyzeProjectTags=le;exports.analyzeWithPlugins=De;exports.applyCombiner=Y;exports.applyMetaInstructions=He;exports.applyOverrides=J;exports.combinePatterns=W;exports.createTelemetry=Ye;exports.estimateTokens=ye;exports.formatValidationReport=Ie;exports.generateABVariants=Qe;exports.generateInstructions=z;exports.getFormatter=Se;exports.getQualityGrade=q;exports.getRegistry=qe;exports.hasMetaInstructions=Ve;exports.initMetaInstructions=Je;exports.initializeRegistry=Be;exports.loadMetaConfig=H;exports.loadOverrideInstructions=V;exports.loadPatternTemplates=A;exports.loadUserConfig=ve;exports.mergeConfigs=Pe;exports.passesQualityThreshold=xe;exports.pluginRegistry=h;exports.refineInstructions=ue;exports.registerBuiltInPlugins=Le;exports.selectPatterns=N;exports.trackABTest=Ke;exports.validateInstructions=$;
|
|
76
|
+
//# sourceMappingURL=index-nioXOg4m.cjs.map
|