project-profile.ts 6.11 KB
import { existsSync, readFileSync } from 'fs';
import { join } from 'path';
import { emptyProfile, type ProjectProfile } from '../types/project-profile';

/**
 * Runtime project profile holder. Service mode spawns one engine child per
 * job, so a module-level value is safe and mirrors the existing runtime
 * model/figma config pattern in `config.ts`. When no profile is set, prompts
 * render nothing and the engine behaves exactly as before (generic output).
 */
let runtimeProfile: ProjectProfile | null = null;

export function setProjectProfile(profile: ProjectProfile | null): void {
    runtimeProfile = profile;
}

export function getProjectProfile(): ProjectProfile | null {
    return runtimeProfile;
}

export function clearProjectProfile(): void {
    runtimeProfile = null;
}

/**
 * Load a project profile from a target project root. It reads two optional
 * files:
 *  - `coderio.profile.json` — the structured manifest (tokens / components /
 *    utils / conventions). Any missing field falls back to the empty template.
 *  - `CODERIO.md` — prose constraints; its content is merged into
 *    `conventions` when the JSON does not already define it.
 *
 * Returns `null` when neither file exists (so callers can skip silently).
 */
export function loadProjectProfile(rootDir: string): ProjectProfile | null {
    const jsonPath = join(rootDir, 'coderio.profile.json');
    const mdPath = join(rootDir, 'CODERIO.md');

    const hasJson = existsSync(jsonPath);
    const hasMd = existsSync(mdPath);
    if (!hasJson && !hasMd) return null;

    const base = emptyProfile();
    let parsed: Partial<ProjectProfile> = {};
    if (hasJson) {
        try {
            parsed = JSON.parse(readFileSync(jsonPath, 'utf8')) as Partial<ProjectProfile>;
        } catch {
            parsed = {};
        }
    }

    const mdContent = hasMd ? readFileSync(mdPath, 'utf8') : '';

    return {
        ...base,
        ...parsed,
        projectName: parsed.projectName || base.projectName,
        rootDir: parsed.rootDir || rootDir,
        tokens: parsed.tokens ?? [],
        components: parsed.components ?? [],
        utils: parsed.utils ?? [],
        conventions: parsed.conventions ?? mdContent,
    };
}

/**
 * Render the project profile into a compact, model-friendly constraint block
 * injected into the CODE node system instructions. When the profile is empty
 * (no components / tokens / utils / conventions) it returns an empty string so
 * generation stays fully generic.
 */
export function renderProfileConstraint(profile: ProjectProfile): string {
    const hasContent =
        profile.components.length > 0 ||
        profile.tokens.length > 0 ||
        profile.utils.length > 0 ||
        (profile.conventions && profile.conventions.trim().length > 0);
    if (!hasContent) return '';

    const lines: string[] = [];

    const meta = [
        profile.projectName && `Target: ${profile.projectName}`,
        profile.framework && `Framework: ${profile.framework}`,
        profile.language && `Language: ${profile.language}`,
        profile.styling && `Styling: ${profile.styling}`,
        profile.componentLibrary && `Components: ${profile.componentLibrary}`,
        profile.stateManagement && `State: ${profile.stateManagement}`,
        profile.dataFetching && `Data: ${profile.dataFetching}`,
        profile.routing && `Routing: ${profile.routing}`,
        profile.importAlias && `Alias: ${profile.importAlias}`,
        profile.landingPath && `Landing: ${profile.landingPath}`,
    ]
        .filter(Boolean)
        .join(' | ');
    if (meta) lines.push(`  <meta>${meta}</meta>`);

    if (profile.tokens.length > 0) {
        lines.push('  <tokens>');
        for (const t of profile.tokens) {
            const val = t.value ? ` (raw ${t.value})` : '';
            lines.push(
                `    - ${t.category} ${t.name} => use \`${t.code}\`${val}`,
            );
        }
        lines.push('  </tokens>');
    }

    if (profile.components.length > 0) {
        lines.push('  <components>');
        for (const c of profile.components) {
            const props = c.props && c.props.length ? ` (props: ${c.props.join(', ')})` : '';
            const desc = c.description ? ` — ${c.description}` : '';
            const variantNote =
                c.variants && Object.keys(c.variants).length
                    ? ` [variants: ${Object.entries(c.variants)
                          .map(([k, v]) => `${k}=${v}`)
                          .join(', ')}]`
                    : '';
            const kind = c.exportType === 'named' ? '{ ' + c.name + ' }' : c.name;
            lines.push(
                `    - ${c.name} => import ${kind} from "${c.importPath}"${props}${desc}${variantNote}`,
            );
        }
        lines.push('  </components>');
    }

    if (profile.utils.length > 0) {
        lines.push('  <utils>');
        for (const u of profile.utils) {
            const desc = u.description ? ` — ${u.description}` : '';
            lines.push(`    - ${u.name} => import { ${u.name} } from "${u.importPath}"${desc}`);
        }
        lines.push('  </utils>');
    }

    if (profile.conventions && profile.conventions.trim().length > 0) {
        lines.push('  <conventions>');
        for (const ln of profile.conventions.trim().split('\n')) {
            lines.push(`    ${ln}`);
        }
        lines.push('  </conventions>');
    }

    return [
        '',
        '  <project_profile>',
        ...lines,
        '  </project_profile>',
        '',
        '  <profile_rules>',
        '    - You MUST prefer the components, utils, and design tokens listed in <project_profile>.',
        '    - Use the EXACT import paths given. Never invent a different path for a listed component.',
        '    - Reference design tokens via their code expression (e.g. `theme.colors.brand`) instead of hardcoding raw values like `#2563eb`.',
        '    - When a Figma node clearly maps to a listed component, use it; otherwise fall back to primitives and add a `// TODO: replace with <ProjectComponent>` comment.',
        '    - Follow the <conventions> rules strictly (naming, directory, state library, i18n, etc.).',
        '  </profile_rules>',
    ].join('\n');
}