@@ -17,6 +17,17 @@ import {
17
17
} from './types' ;
18
18
import { ValidationErrorIdentifier } from './error' ;
19
19
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
+
20
31
/**
21
32
* Compile a JSON schema into a validation function.
22
33
*/
@@ -727,7 +738,7 @@ function compileNumberSchema(
727
738
builders . binaryExpression (
728
739
schema . exclusiveMaximum ? '>=' : '>' ,
729
740
value ,
730
- builders . literal ( schema . maximum ) ,
741
+ createSafeLiteral ( schema . maximum ) ,
731
742
) ,
732
743
builders . blockStatement ( [
733
744
builders . returnStatement ( error ( 'value greater than maximum' ) ) ,
@@ -742,7 +753,7 @@ function compileNumberSchema(
742
753
builders . binaryExpression (
743
754
schema . exclusiveMinimum ? '<=' : '<' ,
744
755
value ,
745
- builders . literal ( schema . minimum ) ,
756
+ createSafeLiteral ( schema . minimum ) ,
746
757
) ,
747
758
builders . blockStatement ( [
748
759
builders . returnStatement ( error ( 'value less than minimum' ) ) ,
@@ -987,10 +998,7 @@ function compileEnumableCheck(
987
998
builders . ifStatement (
988
999
schema . enum . reduce (
989
1000
( 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 ) ;
994
1002
const test = builders . binaryExpression ( '!==' , value , literalValue ) ;
995
1003
996
1004
if ( ! acc ) {
0 commit comments