11'use strict'
22
33var fastSafeStringify = require ( 'fast-safe-stringify' )
4+ var Ajv = require ( 'ajv' )
45
56var uglify = null
67var isLong
@@ -87,8 +88,18 @@ function build (schema, options) {
8788 code = uglifyCode ( code )
8889 }
8990
91+ var dependencies = [ ]
92+ var dependenciesName = [ ]
9093 if ( hasAdditionalPropertiesTrue ( schema ) ) {
91- return ( new Function ( 'fastSafeStringify' , code ) ) ( fastSafeStringify )
94+ dependencies . push ( fastSafeStringify )
95+ dependenciesName . push ( 'fastSafeStringify' )
96+ }
97+ if ( hasAnyOf ( schema ) ) {
98+ dependencies . push ( new Ajv ( ) )
99+ dependenciesName . push ( 'ajv' )
100+ }
101+ if ( dependencies . length > 0 ) {
102+ return ( new Function ( ...dependenciesName , code ) ) ( ...dependencies )
92103 }
93104 return ( new Function ( code ) ) ( )
94105}
@@ -107,6 +118,20 @@ function hasAdditionalPropertiesTrue (schema) {
107118 return false
108119}
109120
121+ function hasAnyOf ( schema ) {
122+ if ( 'anyOf' in schema ) { return true }
123+
124+ var objectKeys = Object . keys ( schema )
125+ for ( var i = 0 ; i < objectKeys . length ; i ++ ) {
126+ var value = schema [ objectKeys [ i ] ]
127+ if ( typeof value === 'object' ) {
128+ if ( hasAnyOf ( value ) ) { return true }
129+ }
130+ }
131+
132+ return false
133+ }
134+
110135function $asNull ( ) {
111136 return 'null'
112137}
@@ -517,8 +542,22 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe
517542 funcName = ( name + key + subKey ) . replace ( / [ - . \[ \] ] / g, '' ) // eslint-disable-line
518543 laterCode = buildArray ( schema , laterCode , funcName , externalSchema , fullSchema )
519544 code += `
520- json += ${ funcName } (obj${ accessor } )
521- `
545+ json += ${ funcName } (obj${ accessor } )
546+ `
547+ break
548+
549+ case undefined :
550+ if ( 'anyOf' in schema ) {
551+ schema . anyOf . forEach ( ( s , index ) => {
552+ code += `
553+ ${ index === 0 ? 'if' : 'else if' } (ajv.validate(${ require ( 'util' ) . inspect ( s , { depth : null } ) } , obj${ accessor } ))
554+ ${ nested ( laterCode , name , key , s , externalSchema , fullSchema , subKey ) . code }
555+ `
556+ } )
557+ code += `
558+ else json+= null
559+ `
560+ } else throw new Error ( `${ schema } unsupported` )
522561 break
523562 default :
524563 throw new Error ( `${ type } unsupported` )
0 commit comments