@@ -17,6 +17,17 @@ import {
1717} from './types' ;
1818import { 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 ( value : string | number | boolean ) : namedTypes . Literal | namedTypes . UnaryExpression {
25+ if ( typeof value === 'number' && value < 0 ) {
26+ return builders . unaryExpression ( '-' , builders . literal ( - value ) ) ;
27+ }
28+ return builders . literal ( value ) ;
29+ }
30+
2031/**
2132 * Compile a JSON schema into a validation function.
2233 */
@@ -727,7 +738,7 @@ function compileNumberSchema(
727738 builders . binaryExpression (
728739 schema . exclusiveMaximum ? '>=' : '>' ,
729740 value ,
730- builders . literal ( schema . maximum ) ,
741+ createSafeLiteral ( schema . maximum ) ,
731742 ) ,
732743 builders . blockStatement ( [
733744 builders . returnStatement ( error ( 'value greater than maximum' ) ) ,
@@ -742,7 +753,7 @@ function compileNumberSchema(
742753 builders . binaryExpression (
743754 schema . exclusiveMinimum ? '<=' : '<' ,
744755 value ,
745- builders . literal ( schema . minimum ) ,
756+ createSafeLiteral ( schema . minimum ) ,
746757 ) ,
747758 builders . blockStatement ( [
748759 builders . returnStatement ( error ( 'value less than minimum' ) ) ,
@@ -987,10 +998,7 @@ function compileEnumableCheck(
987998 builders . ifStatement (
988999 schema . enum . reduce (
9891000 ( acc , val ) => {
990- // Handle negative numbers by creating a unary expression instead of a negative literal
991- const literalValue = typeof val === 'number' && val < 0
992- ? builders . unaryExpression ( '-' , builders . literal ( - val ) )
993- : builders . literal ( val ) ;
1001+ const literalValue = createSafeLiteral ( val ) ;
9941002 const test = builders . binaryExpression ( '!==' , value , literalValue ) ;
9951003
9961004 if ( ! acc ) {
0 commit comments