@@ -9,6 +9,7 @@ const { randomUUID } = require('crypto')
99
1010const validate = require ( './schema-validator' )
1111const Serializer = require ( './serializer' )
12+ const RefResolver = require ( './ref-resolver' )
1213const buildAjv = require ( './ajv' )
1314
1415let largeArraySize = 2e4
@@ -58,19 +59,12 @@ function resolveRef (location, ref) {
5859 const jsonPointer = ref . slice ( hashIndex ) || '#'
5960
6061 const schemaRef = schemaId + jsonPointer
62+ const schema = refResolver . getSchema ( schemaRef )
6163
62- let ajvSchema
63- try {
64- ajvSchema = ajvInstance . getSchema ( schemaRef )
65- } catch ( error ) {
64+ if ( schema === undefined ) {
6665 throw new Error ( `Cannot find reference "${ ref } "` )
6766 }
6867
69- if ( ajvSchema === undefined ) {
70- throw new Error ( `Cannot find reference "${ ref } "` )
71- }
72-
73- const schema = ajvSchema . schema
7468 if ( schema . $ref !== undefined ) {
7569 return resolveRef ( { schema, schemaId, jsonPointer } , schema . $ref )
7670 }
@@ -83,6 +77,7 @@ const objectReferenceSerializersMap = new Map()
8377
8478let rootSchemaId = null
8579let ajvInstance = null
80+ let refResolver = null
8681let contextFunctions = null
8782
8883function build ( schema , options ) {
@@ -95,11 +90,13 @@ function build (schema, options) {
9590 options = options || { }
9691
9792 ajvInstance = buildAjv ( options . ajv )
93+ refResolver = new RefResolver ( )
9894 rootSchemaId = schema . $id || randomUUID ( )
9995
10096 isValidSchema ( schema )
10197 extendDateTimeType ( schema )
10298 ajvInstance . addSchema ( schema , rootSchemaId )
99+ refResolver . addSchema ( schema , rootSchemaId )
103100
104101 if ( options . schema ) {
105102 const externalSchemas = clone ( options . schema )
@@ -114,8 +111,9 @@ function build (schema, options) {
114111 schemaKey = key + externalSchema . $id // relative URI
115112 }
116113
117- if ( ajvInstance . getSchema ( schemaKey ) === undefined ) {
114+ if ( refResolver . getSchema ( schemaKey ) === undefined ) {
118115 ajvInstance . addSchema ( externalSchema , schemaKey )
116+ refResolver . addSchema ( externalSchema , key )
119117 }
120118 }
121119 }
@@ -178,6 +176,7 @@ function build (schema, options) {
178176 const stringifyFunc = contextFunc ( ajvInstance , serializer )
179177
180178 ajvInstance = null
179+ refResolver = null
181180 rootSchemaId = null
182181 contextFunctions = null
183182 arrayItemsReferenceSerializersMap . clear ( )
@@ -493,6 +492,7 @@ function mergeAllOfSchema (location, schema, mergedSchema) {
493492
494493 mergedSchema . $id = `merged_${ randomUUID ( ) } `
495494 ajvInstance . addSchema ( mergedSchema )
495+ refResolver . addSchema ( mergedSchema )
496496 location . schemaId = mergedSchema . $id
497497 location . jsonPointer = '#'
498498}
0 commit comments