// Copyright (c) 2026 Modelware. All rights reserved.
import { parse } from 'yaml';
export function parseTemplateComposeDirective(source) {
    const normalized = source.replace(/^\uFEFF/, '');
    const frontMatterMatch = /^(---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*)([\s\S]*)$/.exec(normalized);
    if (!frontMatterMatch) {
        return undefined;
    }
    const trailing = frontMatterMatch[2] ?? '';
    if (trailing.trim().length > 0) {
        return undefined;
    }
    const yamlBody = frontMatterMatch[1]
        .replace(/^---[ \t]*\r?\n/, '')
        .replace(/\r?\n---[ \t]*$/, '');
    const parsed = parse(yamlBody);
    if (!isRecord(parsed)) {
        return undefined;
    }
    const id = normalizeString(parsed.id);
    if (!id) {
        return undefined;
    }
    const args = parseArgs(parsed.args);
    const bind = parseBind(parsed.bind);
    return { id, args, bind };
}
function parseArgs(value) {
    if (!isRecord(value)) {
        return {};
    }
    const args = {};
    for (const [key, raw] of Object.entries(value)) {
        const normalizedKey = normalizeString(key);
        if (!normalizedKey) {
            continue;
        }
        const converted = toTemplateValue(raw);
        if (converted !== undefined) {
            args[normalizedKey] = converted;
        }
    }
    return args;
}
function parseBind(value) {
    if (!isRecord(value)) {
        return {};
    }
    const bind = {};
    for (const [key, raw] of Object.entries(value)) {
        const normalizedKey = normalizeString(key);
        const source = normalizeString(raw);
        if (!normalizedKey || !source || !isTemplateBindingSource(source)) {
            continue;
        }
        bind[normalizedKey] = source;
    }
    return bind;
}
function toTemplateValue(value) {
    if (value === null) {
        return null;
    }
    if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
        return value;
    }
    if (Array.isArray(value)) {
        return value.every((entry) => typeof entry === 'string') ? value : undefined;
    }
    if (isRecord(value)) {
        return value;
    }
    return undefined;
}
function isTemplateBindingSource(value) {
    return value === 'context.member'
        || value === 'context.ontology'
        || value === 'context.modelUri'
        || value === 'context.selection[*]'
        || value === 'user'
        || /^context\.selection\[\d+]$/.test(value);
}
function normalizeString(value) {
    if (typeof value !== 'string') {
        return undefined;
    }
    const normalized = value.trim();
    return normalized.length > 0 ? normalized : undefined;
}
function isRecord(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
//# sourceMappingURL=compose.js.map