/** * INI / properties file parser. * Parse INI files, read sections and keys, convert to JSON. */ export interface IniDocument { /** Global keys (before any section header). */ global: Record; /** Named sections. */ sections: Record>; } /** Parse an INI/properties file. */ export function parseIni(text: string): IniDocument { const doc: IniDocument = { global: {}, sections: {} }; let currentSection: Record = doc.global; for (const rawLine of text.split(/\r?\n/)) { const line = rawLine.trim(); // Skip empty lines and comments if (line === "" || line.startsWith("#") || line.startsWith(";")) continue; // Section header const sectionMatch = line.match(/^\[([^\]]+)\]$/); if (sectionMatch) { const name = sectionMatch[1].trim(); if (!doc.sections[name]) doc.sections[name] = {}; currentSection = doc.sections[name]; continue; } // Key-value pair (supports = and : as delimiters) const eqIdx = line.indexOf("="); const colonIdx = line.indexOf(":"); let delimIdx: number; if (eqIdx === -1 && colonIdx === -1) continue; if (eqIdx === -1) delimIdx = colonIdx; else if (colonIdx === -1) delimIdx = eqIdx; else delimIdx = Math.min(eqIdx, colonIdx); const key = line.slice(0, delimIdx).trim(); let value = line.slice(delimIdx + 1).trim(); // Strip surrounding quotes if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { value = value.slice(1, -1); } currentSection[key] = value; } return doc; } /** Get all section names from an INI document. */ export function getSections(doc: IniDocument): string[] { return Object.keys(doc.sections); } /** Get a specific key from a section (or global if section is undefined). */ export function getValue( doc: IniDocument, key: string, section?: string ): string | undefined { if (section) { return doc.sections[section]?.[key]; } return doc.global[key]; } /** Convert an INI document to a flat JSON-compatible object. */ export function iniToJson(doc: IniDocument): Record { const result: Record = {}; // Global keys go to root for (const [k, v] of Object.entries(doc.global)) { result[k] = v; } // Each section becomes a nested object for (const [section, kvs] of Object.entries(doc.sections)) { result[section] = { ...kvs }; } return result; } /** Convert a JSON object back to INI format string. */ export function jsonToIni(data: Record): string { const lines: string[] = []; // First write top-level scalar values (global) for (const [key, value] of Object.entries(data)) { if (typeof value !== "object" || value === null) { lines.push(`${key} = ${String(value)}`); } } // Then write sections for (const [key, value] of Object.entries(data)) { if (typeof value === "object" && value !== null && !Array.isArray(value)) { if (lines.length > 0) lines.push(""); lines.push(`[${key}]`); for (const [k, v] of Object.entries(value as Record)) { lines.push(`${k} = ${String(v)}`); } } } return lines.join("\n") + "\n"; }