whitlockjc / json-refs

Various utilities for JSON Pointers (http://tools.ietf.org/html/rfc6901) and JSON References (http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03).
MIT License
223 stars 63 forks source link

`resolveCirculars` doesn't work #206

Open DetachHead opened 1 year ago

DetachHead commented 1 year ago
import { resolveRefs } from 'json-refs'

const resolved = await resolveRefs(
    {
        $ref: '#/definitions/Foo',
        definitions: {
            Foo: {
                type: 'object',
                properties: {
                    a: {
                        $ref: '#/definitions/Foo',
                    },
                },
            },
        },
    },
    { resolveCirculars: true },
)
C:\project\node_modules\json-refs\index.js:139
      throw Error('JSON Pointer points to missing location: ' + pathToPtr(path));
            ^

Error: JSON Pointer points to missing location: #/definitions/Foo/properties
    at C:\project\node_modules\json-refs\index.js:139:13
    at Array.forEach (<anonymous>)
    at findValue (C:\project\node_modules\json-refs\index.js:135:8)
    at setValue (C:\project\node_modules\json-refs\index.js:422:3)
    at C:\project\node_modules\json-refs\index.js:1045:11
    at C:\project\node_modules\lodash\lodash.js:4967:15
    at baseForOwn (C:\project\node_modules\lodash\lodash.js:3032:24)
    at Function.forOwn (C:\project\node_modules\lodash\lodash.js:13082:24)
    at C:\project\node_modules\json-refs\index.js:1037:9
    at async file:///C:/project/asdf.js:3:18
whitlockjc commented 1 year ago

The issue here is that at the root of your document, you have an invalid JSON Reference because $ref cannot be adjacent to any other properties. If you use #findRefs, you get the following:

{
  '#': {
    def: { '$ref': '#/definitions/Foo', definitions: [Object] },
    uri: '#/definitions/Foo',
    uriDetails: {
      scheme: undefined,
      userinfo: undefined,
      host: undefined,
      port: undefined,
      path: '',
      query: undefined,
      fragment: '/definitions/Foo',
      reference: 'same-document'
    },
    type: 'local',
    warning: 'Extra JSON Reference properties will be ignored: definitions'
  }
}

So while a JSON Reference is found, it's invalid and resolution will fail. This is a "garbage in, garbage out" kind of situation. I've thought about how to handle this and the first option would be to just not attempt to resolve invalid JSON References. That's about the only clean option we have. Thoughts?

DetachHead commented 1 year ago

thanks for the reply. this schema was generated by pydantic so i raised it there and will see what they say https://github.com/pydantic/pydantic/issues/5316