55const merge = require ( '@fastify/deepmerge' ) ( )
66const clone = require ( 'rfdc' ) ( { proto : true } )
77const { randomUUID } = require ( 'node:crypto' )
8+ const { RefResolver } = require ( 'json-schema-ref-resolver' )
89
910const validate = require ( './lib/schema-validator' )
1011const Serializer = require ( './lib/serializer' )
1112const Validator = require ( './lib/validator' )
12- const RefResolver = require ( './lib/ref-resolver' )
1313const Location = require ( './lib/location' )
1414
1515let largeArraySize = 2e4
@@ -53,8 +53,7 @@ function resolveRef (context, location, ref) {
5353 const jsonPointer = ref . slice ( hashIndex ) || '#'
5454
5555 const schema = context . refResolver . getSchema ( schemaId , jsonPointer )
56-
57- if ( schema === undefined ) {
56+ if ( schema === null ) {
5857 throw new Error ( `Cannot find reference "${ ref } "` )
5958 }
6059
@@ -66,6 +65,13 @@ function resolveRef (context, location, ref) {
6665 return newLocation
6766}
6867
68+ function getSchemaId ( schema , rootSchemaId ) {
69+ if ( schema . $id && schema . $id . charAt ( 0 ) !== '#' ) {
70+ return schema . $id
71+ }
72+ return rootSchemaId
73+ }
74+
6975function build ( schema , options ) {
7076 isValidSchema ( schema )
7177
@@ -82,12 +88,19 @@ function build (schema, options) {
8288 validatorSchemasIds : new Set ( )
8389 }
8490
85- context . refResolver . addSchema ( schema , context . rootSchemaId )
91+ const schemaId = getSchemaId ( schema , context . rootSchemaId )
92+ if ( ! context . refResolver . hasSchema ( schemaId ) ) {
93+ context . refResolver . addSchema ( schema , context . rootSchemaId )
94+ }
8695
8796 if ( options . schema ) {
88- for ( const key of Object . keys ( options . schema ) ) {
89- isValidSchema ( options . schema [ key ] , key )
90- context . refResolver . addSchema ( options . schema [ key ] , key )
97+ for ( const key in options . schema ) {
98+ const schema = options . schema [ key ]
99+ const schemaId = getSchemaId ( schema , key )
100+ if ( ! context . refResolver . hasSchema ( schemaId ) ) {
101+ isValidSchema ( schema , key )
102+ context . refResolver . addSchema ( schema , key )
103+ }
91104 }
92105 }
93106
0 commit comments