@@ -17,6 +17,19 @@ 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 (
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
+
20
33
/**
21
34
* Compile a JSON schema into a validation function.
22
35
*/
@@ -727,7 +740,7 @@ function compileNumberSchema(
727
740
builders . binaryExpression (
728
741
schema . exclusiveMaximum ? '>=' : '>' ,
729
742
value ,
730
- builders . literal ( schema . maximum ) ,
743
+ createSafeLiteral ( schema . maximum ) ,
731
744
) ,
732
745
builders . blockStatement ( [
733
746
builders . returnStatement ( error ( 'value greater than maximum' ) ) ,
@@ -742,7 +755,7 @@ function compileNumberSchema(
742
755
builders . binaryExpression (
743
756
schema . exclusiveMinimum ? '<=' : '<' ,
744
757
value ,
745
- builders . literal ( schema . minimum ) ,
758
+ createSafeLiteral ( schema . minimum ) ,
746
759
) ,
747
760
builders . blockStatement ( [
748
761
builders . returnStatement ( error ( 'value less than minimum' ) ) ,
@@ -987,7 +1000,8 @@ function compileEnumableCheck(
987
1000
builders . ifStatement (
988
1001
schema . enum . reduce (
989
1002
( acc , val ) => {
990
- const test = builders . binaryExpression ( '!==' , value , builders . literal ( val ) ) ;
1003
+ const literalValue = createSafeLiteral ( val ) ;
1004
+ const test = builders . binaryExpression ( '!==' , value , literalValue ) ;
991
1005
992
1006
if ( ! acc ) {
993
1007
return test ;
0 commit comments