sagold / json-schema-library

Customizable and hackable json-validator and json-schema utilities for traversal, data generation and validation
MIT License
164 stars 19 forks source link

`patternProperties` schemas cause `getSchema` to mangle subsequent pointers #50

Closed rsek closed 7 months ago

rsek commented 7 months ago

Minimal repro with json-schema-library 7.4.7:

import JsonSchema from 'json-schema-library'

const jsc = new JsonSchema.Draft07({
    type: 'object',
    properties: {
        npcs: {
            type: 'object',
            patternProperties: {
                '^[a-z][a-z_]*$': { $ref: '#/$defs/NpcCollection' }
            }
        }
    },
    $defs: {
        NpcCollection: {
            type: 'object',
            properties: {
                name: { type: 'string' },
                contents: {
                    type: 'object',
                    patternProperties: { '^[a-z][a-z_]*$': { $ref: '#/$defs/Npc' } }
                }
            },
            required: ['name', 'contents']
        },
        Npc: {
            type: 'object',
            properties: {
                name: { type: 'string' }
            },
            required: ['name']
        }
    }
})

const data = {
    npcs: {
        sample_npcs: {
            name: 'Sample NPCs',
            contents: {
                chiton: {
                    name: 'Chiton'
                }
            }
        }
    }
}

console.log(jsc.validate(data))
console.log(jsc.getSchema('npcs/sample_npcs')) // works as expected, returning the resolved reference for '#/$defs/NpcCollection'
console.log(jsc.getSchema('npcs/sample_npcs/contents')) // error reports pointer as "npcs/sample_npcs/contents/npcs/sample_npcs"
console.log(jsc.getSchema('npcs/sample_npcs/contents/chiton')) // error reports pointer as "npcs/sample_npcs/contents/chiton/npcs/sample_npcs"
console.log(jsc.getSchema('npcs/sample_npcs/contents/chiton/name')) // error reports pointer as "npcs/sample_npcs/contents/chiton/name/npcs/sample_npcs"
rsek commented 7 months ago

Ah, jeez -- just noticed that 7.4.7 is 2 major versions behind :facepalm: . I'll see if I can reproduce the behaviour in v9.

rsek commented 7 months ago

Hah, yeah, turns out the fix was npm i json-schema-library@9, so I'll close this -- thanks for already fixing the bug in your excellent library ;)