/**
 * Format a TapTree as a string
 * If the argument is an array, descend recursively with formatTr and wrap result in curly braces
 * Otherwise, format the node with formatN
 */
function formatTr(tree) {
    return Array.isArray(tree) ? `{` + tree.map(formatTr).join(",") + `}` : formatN(tree);
}
function formatN(n) {
    if (typeof n === "string") {
        return n;
    }
    if (typeof n === "number") {
        return String(n);
    }
    if (Array.isArray(n)) {
        return n.map(formatN).join(",");
    }
    if (n && typeof n === "object") {
        const entries = Object.entries(n);
        if (entries.length !== 1) {
            throw new Error(`Invalid node: ${n}`);
        }
        const [name, value] = entries[0];
        if (name === "tr" && Array.isArray(value)) {
            const [key, tree] = value;
            return formatN({ tr: formatN([key, formatTr(tree)]) });
        }
        return `${name}(${formatN(value)})`;
    }
    throw new Error(`Invalid node: ${n}`);
}
/** Format a Miniscript or Descriptor node as a descriptor string (without checksum) */
export function formatNode(n) {
    return formatN(n);
}
