/** * Parse JSON with comments (// line comments and block comments), the format of the tuning * files and of the patch definitions. Comments are blanked out, outside string literals only; * the rest goes to JSON.parse, so the error positions still match the file. */ export function parseJsonc(text: string): unknown { return JSON.parse(stripComments(text)); } function stripComments(text: string): string { let out = ''; let index = 0; while (index < text.length) { const ch = text[index]!; const next = text[index + 1]; if (ch === '"') { const end = stringEnd(text, index); out += text.slice(index, end); index = end; } else if (ch === '/' && next === '/') { while (index < text.length && text[index] !== '\n') index++; } else if (ch === '/' && next === '*') { const end = text.indexOf('*/', index + 2); const stop = end < 0 ? text.length : end + 2; out += text.slice(index, stop).replace(/[^\n]/g, ' '); index = stop; } else { out += ch; index++; } } return out; } /** Index just past the closing quote of the string literal starting at `start`. */ function stringEnd(text: string, start: number): number { let index = start + 1; while (index < text.length) { if (text[index] === '\\') index += 2; else if (text[index] === '"') return index + 1; else index++; } return text.length; }