fix: reject negative numbers with leading zeros

This commit is contained in:
Johann Schopplich
2025-12-05 14:12:55 +01:00
parent 4852a09a76
commit 19719a136f
4 changed files with 13 additions and 11 deletions

View File

@@ -38,6 +38,6 @@
"test": "vitest"
},
"devDependencies": {
"@toon-format/spec": "^3.0.0"
"@toon-format/spec": "^3.0.1"
}
}

View File

@@ -14,12 +14,11 @@ export function isNumericLiteral(token: string): boolean {
if (!token)
return false
// Must not have leading zeros (except for `"0"` itself or decimals like `"0.5"`)
if (token.length > 1 && token[0] === '0' && token[1] !== '.') {
// Enforce JSON-like grammar with no forbidden leading zeros
const numericPattern = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[+-]?\d+)?$/i
if (!numericPattern.test(token))
return false
}
// Check if it's a valid number
const numericValue = Number(token)
return !Number.isNaN(numericValue) && Number.isFinite(numericValue)
}

View File

@@ -1,6 +1,9 @@
import { DEFAULT_DELIMITER, LIST_ITEM_MARKER } from '../constants'
import { isBooleanOrNullLiteral } from './literal-utils'
const NUMERIC_LIKE_PATTERN = /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i
const LEADING_ZERO_PATTERN = /^0\d+$/
/**
* Checks if a key can be used without quotes.
*
@@ -93,5 +96,5 @@ export function isSafeUnquoted(value: string, delimiter: string = DEFAULT_DELIMI
* Match numbers like `42`, `-3.14`, `1e-6`, `05`, etc.
*/
function isNumericLike(value: string): boolean {
return /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(value) || /^0\d+$/.test(value)
return NUMERIC_LIKE_PATTERN.test(value) || LEADING_ZERO_PATTERN.test(value)
}