UNPKG

llm-md

Version:

Convert JSON to Markdown optimized for LLM consumption

84 lines (83 loc) 2.63 kB
"use strict"; /** * Key-Value Converter - converts simple objects to key-value lists */ Object.defineProperty(exports, "__esModule", { value: true }); exports.KeyValueConverter = void 0; const utils_1 = require("../utils"); class KeyValueConverter { constructor() { this.visited = new WeakSet(); } /** * Convert data to key-value list format * @param data Data to convert * @param options Conversion options * @returns Markdown key-value list */ convert(data, _options) { this.visited = new WeakSet(); // Reset for each conversion return this.convertValue(data, 0); } /** * Recursively convert values * @param value Value to convert * @param depth Current indentation depth * @returns Markdown string */ convertValue(value, depth) { if (value === null) { return '`null`'; } if (value === undefined) { return '`undefined`'; } if (typeof value !== 'object') { return String(value); } if (Array.isArray(value)) { return this.convertArray(value, depth); } return this.convertObject(value, depth); } /** * Convert an object to key-value pairs * @param obj Object to convert * @param depth Current indentation depth * @returns Markdown string */ convertObject(obj, depth) { // Check for circular reference if (this.visited.has(obj)) { return '`[Circular Reference]`'; } this.visited.add(obj); const indent = ' '.repeat(depth); const lines = []; Object.entries(obj).forEach(([key, value]) => { if (value !== null && typeof value === 'object' && !Array.isArray(value)) { // Nested object - add as sub-list lines.push(`${indent}- **${key}**:`); lines.push(this.convertObject(value, depth + 1)); } else { // Simple value lines.push(`${indent}- **${key}**: ${(0, utils_1.formatValue)(value)}`); } }); return lines.join('\n'); } /** * Convert an array to a numbered list * @param arr Array to convert * @param depth Current indentation depth * @returns Markdown string */ convertArray(arr, depth) { const indent = ' '.repeat(depth); return arr .map((item, i) => `${indent}${i + 1}. ${(0, utils_1.formatValue)(item)}`) .join('\n'); } } exports.KeyValueConverter = KeyValueConverter;