fix(jsonc-parser): strip UTF-8 BOM before parsing to fix Windows "InvalidSymbol at offset 0" errors
Windows editors often save UTF-8 files with a BOM (Byte Order Mark: \uFEFF). When this is present, jsonc-parser reports InvalidSymbol at offset 0 because the BOM is not valid JSON/JSONC syntax. This commit strips the BOM before parsing, fixing issues #3164 where Windows users report their opencode.jsonc file fails to parse even though it appears to start with a valid '{' character. Fixes: #3164 Co-authored-by: Jobdori <agent@yeongyu.kim>
This commit is contained in:
@@ -139,6 +139,33 @@ describe("parseJsonc", () => {
|
|||||||
// then
|
// then
|
||||||
expect(() => parseJsonc(invalid)).toThrow()
|
expect(() => parseJsonc(invalid)).toThrow()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("parses JSONC with UTF-8 BOM (Windows BOM files)", () => {
|
||||||
|
// given - JSON with UTF-8 BOM marker
|
||||||
|
const bom = "\uFEFF"
|
||||||
|
const jsonc = `${bom}{ "key": "value" }`
|
||||||
|
|
||||||
|
// when
|
||||||
|
const result = parseJsonc<{ key: string }>(jsonc)
|
||||||
|
|
||||||
|
// then
|
||||||
|
expect(result.key).toBe("value")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("parses JSONC with BOM and comments", () => {
|
||||||
|
// given - JSONC with UTF-8 BOM and comments
|
||||||
|
const bom = "\uFEFF"
|
||||||
|
const jsonc = `${bom}{
|
||||||
|
// Windows editor saved with BOM
|
||||||
|
"key": "value"
|
||||||
|
}`
|
||||||
|
|
||||||
|
// when
|
||||||
|
const result = parseJsonc<{ key: string }>(jsonc)
|
||||||
|
|
||||||
|
// then
|
||||||
|
expect(result.key).toBe("value")
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("parseJsoncSafe", () => {
|
describe("parseJsoncSafe", () => {
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ export interface JsoncParseResult<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function parseJsonc<T = unknown>(content: string): T {
|
export function parseJsonc<T = unknown>(content: string): T {
|
||||||
|
// Strip UTF-8 BOM if present (Windows UTF-8 with BOM files)
|
||||||
|
content = content.replace(/^\uFEFF/, "")
|
||||||
|
|
||||||
const errors: ParseError[] = []
|
const errors: ParseError[] = []
|
||||||
const result = parse(content, errors, {
|
const result = parse(content, errors, {
|
||||||
allowTrailingComma: true,
|
allowTrailingComma: true,
|
||||||
|
|||||||
Reference in New Issue
Block a user