import { describe, expect, it } from 'vitest'; import { tryFixJSON } from '../json-fixer'; describe('tryFixJSON', () => { it('fixes trailing comma before }', () => { const result = tryFixJSON('{"a": 1,}'); expect(result).toBeDefined(); expect(JSON.parse(result!) as unknown).toEqual({ a: 1 }); }); it('fixes trailing comma before ]', () => { const result = tryFixJSON('{"items": [1, 2, 3,]}'); expect(result).toBeDefined(); expect(JSON.parse(result!) as unknown).toEqual({ items: [1, 2, 3] }); }); it('fixes trailing commas with newlines', () => { const input = `{ "a": 1, "b": 2, }`; const result = tryFixJSON(input); expect(result).toBeDefined(); expect(JSON.parse(result!) as unknown).toEqual({ a: 1, b: 2 }); }); it('fixes nested trailing commas', () => { const input = '{"a": [1, 2,], "b": {"key": 3,},}'; const result = tryFixJSON(input); expect(result).toBeDefined(); expect(JSON.parse(result!) as unknown).toEqual({ a: [1, 2], b: { key: 3 }, }); }); it('does not modify commas inside strings', () => { const input = '{"a": "hello, world,"}'; const result = tryFixJSON(input); expect(result).toBeDefined(); expect(JSON.parse(result!) as unknown).toEqual({ a: 'hello, world,' }); }); it('returns undefined for unfixable JSON', () => { expect(tryFixJSON('{"a": }')).toBeUndefined(); }); it('returns undefined for missing commas (not auto-fixable)', () => { expect(tryFixJSON('{"a": 1 "b": 2}')).toBeUndefined(); }); it('fixes a realistic machine config with trailing commas', () => { const input = `{ "components": [ { "name": "my-motor", "type": "motor", "model": "gpio", "attributes": { "pins": { "a": "13", "b": "15", }, "board": "my-board", }, }, ], "services": [], }`; const result = tryFixJSON(input); expect(result).toBeDefined(); expect(() => JSON.parse(result!) as unknown).not.toThrow(); }); it('handles strings with escaped quotes', () => { const input = String.raw`{"a": "value with \"comma,\"",}`; const result = tryFixJSON(input); expect(result).toBeDefined(); }); });