@@ -17,6 +17,19 @@ 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 (
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