Skip to content

Commit 136b3c6

Browse files
authored
Fix support for negative values (#7)
* Add failing test * Fix enum with negative values * Improve it everywhere * Format
1 parent da89937 commit 136b3c6

File tree

3 files changed

+519
-3
lines changed

3 files changed

+519
-3
lines changed

src/compileValueSchema.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,19 @@ import {
1717
} from './types';
1818
import { ValidationErrorIdentifier } from './error';
1919

20+
/**
21+
* Creates a literal value that handles negative numbers properly for escodegen.
22+
* For negative numbers, creates a unary expression instead of a negative literal.
23+
*/
24+
function createSafeLiteral(
25+
value: string | number | boolean,
26+
): namedTypes.Literal | namedTypes.UnaryExpression {
27+
if (typeof value === 'number' && value < 0) {
28+
return builders.unaryExpression('-', builders.literal(-value));
29+
}
30+
return builders.literal(value);
31+
}
32+
2033
/**
2134
* Compile a JSON schema into a validation function.
2235
*/
@@ -727,7 +740,7 @@ function compileNumberSchema(
727740
builders.binaryExpression(
728741
schema.exclusiveMaximum ? '>=' : '>',
729742
value,
730-
builders.literal(schema.maximum),
743+
createSafeLiteral(schema.maximum),
731744
),
732745
builders.blockStatement([
733746
builders.returnStatement(error('value greater than maximum')),
@@ -742,7 +755,7 @@ function compileNumberSchema(
742755
builders.binaryExpression(
743756
schema.exclusiveMinimum ? '<=' : '<',
744757
value,
745-
builders.literal(schema.minimum),
758+
createSafeLiteral(schema.minimum),
746759
),
747760
builders.blockStatement([
748761
builders.returnStatement(error('value less than minimum')),
@@ -987,7 +1000,8 @@ function compileEnumableCheck(
9871000
builders.ifStatement(
9881001
schema.enum.reduce(
9891002
(acc, val) => {
990-
const test = builders.binaryExpression('!==', value, builders.literal(val));
1003+
const literalValue = createSafeLiteral(val);
1004+
const test = builders.binaryExpression('!==', value, literalValue);
9911005

9921006
if (!acc) {
9931007
return test;

0 commit comments

Comments
 (0)