mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Replace strip-json-comments with jsonc-parser for better error reporting
This commit is contained in:
1 parent
e1890d0554
commit
e1a4a70d3d
13 files changed
+132
-34
No files matched your search
@@ -1,3 +1,4 @@
|
||||
export * from './config'
|
||||
export * from './schemas'
|
||||
export * from './types'
|
||||
export * from './utils'
|
||||
@@ -198,7 +198,7 @@ export const OpenCodeConfigSchema = z.object({
|
||||
disabled_providers: z.array(z.string()).optional(),
|
||||
share: z.enum(["manual", "auto", "disabled"]).optional(),
|
||||
plugin: z.array(z.string()).optional(),
|
||||
});
|
||||
}).strip();
|
||||
|
||||
export type OpenCodeConfigContent = z.infer<typeof OpenCodeConfigSchema>;
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export * from './jsonc'
|
||||
@@ -0,0 +1,45 @@
|
||||
import { parse as parseJsoncLib, type ParseError } from 'jsonc-parser'
|
||||
|
||||
export function parseJsonc<T = unknown>(content: string): T {
|
||||
const errors: ParseError[] = []
|
||||
const result = parseJsoncLib(content, errors, {
|
||||
allowTrailingComma: true,
|
||||
disallowComments: false,
|
||||
})
|
||||
|
||||
if (errors.length > 0) {
|
||||
const error = errors[0]!
|
||||
const message = getParseErrorMessage(error.error, content, error.offset)
|
||||
throw new SyntaxError(message)
|
||||
}
|
||||
|
||||
return result as T
|
||||
}
|
||||
|
||||
export function getParseErrorMessage(error: number, content: string, offset: number | undefined): string {
|
||||
if (offset === undefined) {
|
||||
return getErrorMessageByCode(error)
|
||||
}
|
||||
|
||||
const line = content.substring(0, offset).split('\n').length
|
||||
const col = (content.substring(0, offset).split('\n').pop()?.length ?? 0) + 1
|
||||
|
||||
const message = getErrorMessageByCode(error)
|
||||
return `${message} at line ${line}, column ${col}`
|
||||
}
|
||||
|
||||
function getErrorMessageByCode(error: number): string {
|
||||
const errorMessages: Record<number, string> = {
|
||||
1: 'Invalid symbol',
|
||||
2: 'Invalid number format',
|
||||
3: 'Property name expected',
|
||||
4: 'Value expected',
|
||||
5: 'Colon expected',
|
||||
6: 'Comma expected',
|
||||
7: 'Trailing comma not allowed',
|
||||
8: 'Unexpected end of input',
|
||||
9: 'Invalid comment',
|
||||
}
|
||||
|
||||
return errorMessages[error] || 'Invalid JSONC'
|
||||
}
|
||||
Reference in new issue
Block a user