import YAML from 'yaml';
import { raw } from './style.js';

const replacer = (visited = new Set()) => (_, val) => {
    if (typeof val === 'string') {
        return raw(val);
    }
    if (typeof val === 'object') {
        if (visited.has(val)) {
            return '<recursive>';
        }
        visited.add(val);
        return val;
    }
    return val;
};

export const format = (value, type) => {
    switch (type) {
    case 'json':
        return JSON.stringify(value, replacer());
    case 'yaml':
        return YAML.stringify(value, replacer());
    default:
        if (Array.isArray(value)) {
            return value.map(String).join('\n');
        }
        return String(value);
    }
};
