Code Monkey home page Code Monkey logo

json-schema-library's People

Contributors

benurb avatar brettz9 avatar dependabot[bot] avatar felixebertsz avatar from-the-river-to-the-sea avatar heikoter avatar mrbrn197 avatar sagold avatar zearin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

json-schema-library's Issues

getTemplate loses compiled references

We continue to have issues with getTemplate erroring out when we have referenced schemas. It appears that within the createTemplateSchema there are a number of copy / merge functions which lose the non-enumerable properties which have been compiled into the schema. This causes the getRoot function to not exist and instead of properly referencing the actual compiled schema, it instead tries to find the definitions from the core.rootSchema.

ESM-Bundle for using in browser

Thanks a lot for this library, which I plan to use for model-validation in the browser.

Currently I'm a bit stuck, because I can't use the es6-bundle inside dist/module. The generated code imports files without file-extension .js, but this would be needed for browser imports.

Ideally, everything would be bundles into a single jsonSchemaLibrary.esm.min.js.

I can give it a try and add a bundle-script in package.json using esbuild.

Support for future JSON Schema Drafts / Specifications

Hello @sagold ,

Me and @tcompa, are opening this issue because the team behind Fractal Analytics Platform, an open platform to perform analysis on high magnitude of data, is considering to introduce in one of its packages this great library as dependency.

Since having a new dependency is always something to consider, I would like to ask what are your plan to support future releases of JSON Schema specifications.

As far as my understanding goes, this library currently supports JSON Schema until "Draft 7" which has been around for quite a while until now.

Do you have any plan to introduce the support for further iterations of the Schema? Like Draft 2019-09?
I'm considering the specs as defined by https://json-schema.org/specification-links.html

Any kind of insights on this matter would be helpful for our project! Thank you.

Unable to iterate over schema using eachSchema

I have used almost every utility in this library, and I like it very much.

While using the eachSchema method to iterate over schema I faced an issue. It will iterate only if the type keyword is not an array.

eg: { type: 'string' } works fine but { type: ['string', 'null'] } doesn't.

https://github.com/sagold/json-schema-library/blob/master/lib/schema/getTypeId.ts at line 24 if (types[schema.type]) { schema.type is assumed not to be an array everytime

"export 'default' (imported as 'deepmerge') was not found in 'deepmerge'

我的项目安装了[json-schema-library],在启动项目时报"export 'default' (imported as 'deepmerge') was not found in 'deepmerge'错误,我排查了一下原因,使用的deepmerge依赖版本是4.3.1,与我的项目不兼容。

我测试了deepmerge的1.5.2版本,我的项目可以正常运行。

请问我现在应该如何处理呢?

Tests fail to run on Windows

The current npm test scripts use some syntax which unfortunately does not work on Windows. Namely semicolons ; and the use of single-quote characters ' around some of the arguments. Replacing the semicolons with either & or && and replacing the single-quotes with double-quotes " should enable the tests to run on all platforms.

Is it possible to add a custom "core" for mongodb's json schema variant?

Hey,

I love your project -- finally gave me the piece I'd been looking for to build a mongodb tool I've been working with. The only issue I'm hitting is that mongoDB adds a lot of custom types -- and they do it using a different field.

{
  "type": "object",
  "title": "Consumer",
  "properties": {
    "_id": {
      "bsonType": "objectId",
      "tsType": "ObjectId",
    },
    "uniqueSlug": { "type": "string" },
    "name": { "type": "string" },
    "count": { "type": "number" },
    "perms": {
      "type": "array",
      "items": {
        "enum": ["read", "admin"]
      }
    },
    "pubKey": { "type": "string", "default": "NONE DEFINED" }
  },
  "required": ["_id", "uniqueSlug", "name", "perms"],
  "additionalProperties": false
}

This is an example of a schema that I'm working with; while most of the types are "normal", there are some mongodb types that you represent by providing {bsonType: '(type'} instead of using {type: '(type)'. Looking through your API docs and your source code I'm not seeing a way to set something which will match based on a different field name.

One of the things I've been using is schemaEach to try to enumerate all the fields that could be on an object (is there a better way?) but in the above schema it does not fire for _id and I can't help thinking there will be other issues as well.

I'm trying to add a validator for those fields:

    addValidator.format(this, 'objectId', (core, schema, value, pointer) => {
      if (schema.bsonType === 'objectId') {
        if (ObjectId.isValid(value)) {
          return;
        }
        return {
          type: 'error',
          name: 'objectId',
          code: 'INVALID_OBJECT_ID',
          message: 'Invalid objectId',
          data: {
            value,
            pointer,
          },
        };
      }
    });
  }

It seems plausible, but also seems like it may well only fire if {type: 'objectId'} which will never be the case.

Any suggestions? =] I don't mind tweaking code and submitting a PR, but I'd rather not reinvent the wheel if I don't have to.

Wrongful Error on chained negative logic If cases

When validating an object against a JSON schema that uses conditional constraints, the library appears to be incorrectly flagging valid combinations as invalid.

Example Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.com/schemas/animal_traits",
  "type": "object",
  "properties": {
    "animal_species": {
      "enum": ["cat", "eagle"]
    },
    "diet_type": {
      "enum": ["carnivore", "omnivore"]
    },
    "habitat_type": {
      "enum": ["forest", "mountain"]
    }
  },
  "allOf": [
    {
      "if": {
        "not": {
          "properties": {
            "animal_species": {
              "const": "cat"
            }
          }
        }
      },
      "then": {
        "properties": {
          "diet_type": {
            "const": "carnivore"
          }
        }
      }
    },
    {
      "if": {
        "not": {
          "properties": {
            "diet_type": {
              "const": "carnivore"
            },
            "animal_species": {
              "const": "cat"
            }
          }
        }
      },
      "then": {
        "properties": {
          "habitat_type": {
            "const": "mountain"
          }
        }
      }
    }
  ]
}

Object to validate:

{
  "animal_species": "cat",
  "diet_type": "omnivore",
  "habitat_type": "mountain"
}

Based on the provided schema, the object should be valid:

  1. The animal_species is "cat", so the diet_type can be either "carnivore" or "omnivore".
  2. Given that diet_type is "omnivore" and animal_species is "cat", habitat_type should be "mountain".

However, when validating the object against the schema using the json-schema-library, an error is thrown indicating that diet_type must be "carnivore". This is contrary to the schema's specifications and seems to indicate an issue in how the library handles the conditional constraints.

Would appreciate any assistance in resolving this. Thank you!

Handling definitions in `each`?

Hi, thank you for your library, it is doing just what I need to. I just ran into a problem with definitions.

My schema:

{
	$schema: "http://json-schema.org/draft-07/schema",
	definitions: {
		object1: {
			type: "object",
			properties: {
				prop1: {
					type: "string",
				},
				prop2: {
					type: "string",
				},
			},
			required: ["prop1", "prop2"],
		},
	},
	$ref: "#/definitions/object1",
}

Validating this with

jsonSchema.each(
	{
		prop1: "foo",
		prop2: "foo",
	},
	myCallback
);

gives me:

[
  {
    schema: {
      '$schema': 'http://json-schema.org/draft-07/schema',
      definitions: [Object],
      '$ref': '#/definitions/object1',
      '$defs': [Object]
    },
    value: { prop1: 'foo', prop2: 'foo' },
    pointer: '#'
  },
  {
    schema: {
      type: 'error',
      name: 'UnknownPropertyError',
      code: 'unknown-property-error',
      message: 'Could not find a valid schema for property `#` within object',
      data: [Object]
    },
    value: 'foo',
    pointer: '#/prop1'
  },
  {
    schema: {
      type: 'error',
      name: 'UnknownPropertyError',
      code: 'unknown-property-error',
      message: 'Could not find a valid schema for property `#` within object',
      data: [Object]
    },
    value: 'foo',
    pointer: '#/prop2'
  }
]

This seems to be a problem with definitions, are they not being resolved?

Add missing support for `dependencies` in `getSchema`

Hey 👋

I wonder if theres a different way to do this, but it looks like that I'm unable to get the schema for something that is defined in dependencies.

Say I have a schema that looks like the following:

const parsed = new Draft07({
  title: "Fill in some steps",
  required: [
    "name"
  ],
  properties: {
    name: {
      title: "Name",
      type: "string",
      description: "Unique name of the component"
    },
    generation: {
      type: "string",
      title: "Generation Method",
      enum: [
        "Hide Custom Field",
        "Display Custom Field"
      ],
      default: "Hide Custom Field"
    }
  },
  dependencies: {
    generation: {
      oneOf: [
        {
          properties: {
            generation: {
              const: "Hide Custom Field"
            }
          }
        },
        {
          required: [
            "customField"
          ],
          properties: {
            generation: {
              const: "Display Custom Field"
            },
            customField: {
              title: "Custom Field",
              type: "string"
            }
          }
        }
      ]
    }
  }
})

And then if I do parsed.getSchema('#/customField', { generation: 'Display Custom Field' }) I get Could not find a valid schema for property '#/customField' within object where as it should be part of the json schema for validation. Is there something I'm missing here or a way to get back the schema { type: string } for this bit in the schema?

Thanks!

Unable to get default values for all properties

I would like to start this thread mentioning that I really like this tool.

I'm trying to design a JSON Schema which default values help to complete the initial data. This is my schema.json file:

{
  "$schema": "http://json-schema.org/draft/2019-09/schema",
  "type": "object",
  "additionalProperties": false,
  "required": ["job-type-a", "job-type-b"],
  "properties": {
    "job-type-a": {
      "$ref": "#/definitions/job-type-a"
    },
    "job-type-b": {
      "$ref": "#/definitions/job-type-b"
    }
  },
  "definitions": {
    "cluster": {
      "type": "string",
      "enum": ["cluster-a", "cluster-b"],
      "default": "cluster-a"
    },
    "runner": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "cluster": {
          "$ref": "#/definitions/cluster"
        }
      },
      "required": ["cluster"]
    },
    "job-type-a": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "runner": {
          "$ref": "#/definitions/runner"
        }
      }
    },
    "job-type-b": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "runner": {
          "$ref": "#/definitions/runner"
        }
      }
    }
  }
}

I write this code to get default values for previous schema

import { Draft, Draft07 } from 'json-schema-library';
import jsonSchemaSpec from '../schema.json';

const initData = {};
const jsonSchema: Draft = new Draft07(jsonSchemaSpec);
const data = jsonSchema.getTemplate(initData);
console.log(data);

but the result of the previous code is not the expected. This is the result:
{ 'job-type-a': { runner: { cluster: 'cluster-a' } }, 'job-type-b': { runner: undefined } }

but I expected a result like that:
{ 'job-type-a': { runner: { cluster: 'cluster-a' } }, 'job-type-b': { runner: { cluster: 'cluster-a' } } }

I think it is a bug.

getTemplate falsely returns default for type number when schema type is set to integer

I recently bumped up my version from 4.0.0 to 7.4.4 and noticed some inconsistencies with using getTemplate.

The problem appears once I use getTemplate with input data where it seems to replace existing values of type integer with a default (0). This problem only seems to happen when the schema type is integer and works fine when the type of a property is number.

Example schema:

{
    "type": "object",
    "properties": {
        "id": {
            "type": "string"
        },
        "title": {
            "type": "string"
        },
        "students": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string"
                    },
                    "age": {
                        "type": "integer"
                    }
                }
            }
        }
    }
}

Example input data:

{
    id: '4235809c-bdc7-46c5-be3d-b1b679bb1c13',
    title: 'JavaScript Data Structures 101',
    students: [
        {
            name: 'Phil',
            age: 31
        },
        {
            name: 'Irina',
            age: 27
        }
    ]
}

My implementation looks like this:

const jsonSchema = new Draft04();
const template = jsonSchema.getTemplate(data, schema, {
    addOptionalProps: false,
});

Received output:

{
    id: '4235809c-bdc7-46c5-be3d-b1b679bb1c13',
        title: 'JavaScript Data Structures 101',
        students: [
        {
            name: 'Phil',
            age: 0
        },
        {
            name: 'Irina',
            age: 0
        }
    ]
}

Once I change the type of age to number it works fine so it seems to be related to the schema type-definition.

Clearly document how remote schemas are identified

Our schemas are mostly defined for file-based access and we utilise the library for stitching together the schemas. We found a fair bit of hassle with the way the remote schemas were keyed when adding through addRemoteSchema.

{
    "$id": "OurCoolSchema.json"
}

{
    "$id": "ConsumerSchema.json",
    "properties": {
        "referenced": {
             "$ref": "OurCoolSchema.json"
        }
    }
}

To have this properly resolve, its needed to do draft.addRemoteSchema("ConsumerSchema.json/OurCoolSchema.json", OurCoolSchema). This isn't documented anywhere and it took quite a bit of searching to get this right. This is a common issue we have found with json-schema libraries, but a nice note about how the resolution works would be appreciated.

multipleOf running into floating point issue

We have the use case of wanting to enforce numbers having no more than 2 decimal places so we're using the multipleOf keyword with .01 to try to achieve this. Unfortunately it fails in unexpected ways.

There is a well known issue with multipleOf keyword when used with floating point numbers:

Do you think this is something that this parser would like to fix or should we just use strings with regexes to achieve a similar result?

Mutiple typeIds [not, oneOf] matched in subschema

Hello,

I'm trying to add the OpenAPI 3.0 schema to one of my projects using Draft04, but I'm running into an error I cannot comprehend.

Error:

Mutiple typeIds [not, oneOf] matched in {...}

Offending sub-schema:

"SchemaXORContent": {
        "description": "Schema and content are mutually exclusive, at least one is required",
        "not": {
          "required": [
            "schema",
            "content"
          ]
        },
        "oneOf": [
          {
            "required": [
              "schema"
            ]
          },
          {
            "required": [
              "content"
            ],
            "description": "Some properties are not allowed if content is present",
            "allOf": [
              {
                "not": {
                  "required": [
                    "style"
                  ]
                }
              },
              {
                "not": {
                  "required": [
                    "explode"
                  ]
                }
              },
              {
                "not": {
                  "required": [
                    "allowReserved"
                  ]
                }
              },
              {
                "not": {
                  "required": [
                    "example"
                  ]
                }
              },
              {
                "not": {
                  "required": [
                    "examples"
                  ]
                }
              }
            ]
          }
        ]
      }

If this is expected, are there any known solutions?

Best regards

Top level "oneOf" does not validate correctly

Reproduce

const draft = new Draft07();
assert.strict.notDeepEqual(draft.validate(true, { oneOf: [{type: string}, {type: number}]}, [])

Expectation

Validation should properly validate a top level schema that does not specify a top level type

Notes

  • This appears to be a bug within validate and getJsonSchemaType where it will default to the received value when no type is found.
  • This succeeds when it is within a nested property
  • I presume this is not limited to "oneOf"

Edit

On further inspection, this may only occur when non-object values are passed with the "oneOf" top level schema.

The purpose of minLengthOneError

Hi,
First of all want to say thank you for developing such useful lib for JSON Schema.
Have one question: what the purpose of minLengthOneError?
According to official JSON Schema specification there is no such validator.
Wouldn't say it cause a problem but still have to handle it separately.

ESM in source and as distribution format

I haven't dug in yet, but this looks like a very usable, robust, and pretty well-documented tool.

May I suggest though switching to ES6 Modules in source, as well as using Rollup instead of Webpack so you can also provide an ES6 distribution as well (and point to it with module in package.json)?

ESM allows the convenience to browser applications of declaring their dependencies modularly (rather than within an HTML file), also thereby eliminating the "magic" of figuring out where a dependency comes from.

Also an off-topic question if I may--any thoughts about supporting async as-needed loading of schemas--like as in iterator?

Cannot read properties of undefined (reading 'getRef')

Hi,

thank you for your library!
We are using your library in order to create default-templates based on a schema.

At this point we are facing an issue:

{
  $schema: 'http://json-schema.org/draft-04/schema#',
  version: 1.0,
  type: 'object',
  definitions: {
    saneUrl: {
      format: 'uri',
      pattern: '^https?://',
      default: 'https://localhost:8080',
    },
  },
  properties: {
    ContainerAddress: {
      $ref: '#/definitions/saneUrl',
    },
  },
}

regarding: https://www.jsonschemavalidator.net/ the schema itself should be valid.

import { Draft04 as JsonSchemaLibrary } from 'json-schema-library';

const schema = {
  $schema: 'http://json-schema.org/draft-04/schema#',
  version: 1.0,
  type: 'object',
  definitions: {
    saneUrl: {
      format: 'uri',
      pattern: '^https?://',
      default: 'https://localhost:8080',
    },
  },
  properties: {
    ContainerAddress: {
      $ref: '#/definitions/saneUrl',
    },
  },
};

export const jsonSchemaToTemplateConverter = () => {
  const data = {
    AnalyticsContainerAddress: 'https://asdf',
  };

  const jsonSchema = new JsonSchemaLibrary();
  const result = jsonSchema.getTemplate({}, schema);
  return result;
};

getTemplate throws the following exception:
TypeError: Cannot read properties of undefined (reading 'getRef')

Are we missing something?

Kind regards
Tim

Undefined behavior when a schema's "type" is an array of types

Hello! 👋

In a few of my JSON Schemas, I specify an array of valid types, such as:

"type": ["object", "null"]

This is indeed valid JSON Schema syntax, but this library currently has undefined behavior when type is an array, and as such it ends up always rejecting the provided value.

Aside from this one issue, this library has been super helpful and I'm using it in some fun projects. Thanks for making it! ❤️

Vulnerability on `gson-pointer` dependendency

Hey 👋

We've had a report that the gson-pointer dependency has a vulnerability which I believe to be this one: sagold/json-pointer#3 but it seems that this library looks like it's not been updated in a while.

Would it be possible to merge the suggested fix and deploy a new version of this library with the minimum version requirement to be the latest of gson-pointer?

Thanks for a great library!

Yarn 3 YN0001- Error while persisting

I'm getting YN0001- Error while persisting.... on windows when I run yarn install . Version Yarn 3.2.3

It occurs during the linking process. I'm using node-modules linker.

➤ YN0001: │ Error: While persisting /C:/Users/.../AppData/Local/Yarn/Berry/cache/json-schema-library-npm-7.2.0-542ab2e6c3-8.zip/node_modules/json-schema-library/ -> /C:/Users/...backstage/node_modules/json-schema-library ENOENT: no such file or directory, open 'C:\Users\PNastasi\Documents\eg-group\backstage\node_modules\json-schema-library\profiles\develop-doValidations-2022-09-28 15:37:34.txt'

I created this issue before in yarn in the following link: yarnpkg/berry#4985. and their verdict it was cause to the colon in the file that is not allowed on windows https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions:~:text=except%20for%20the,%3A%20(colon)

MinItemsError rendering incorrectly

I'm seeing in practice the too few items error rendering incorrectly as:

Too few items in #/separatePolicies/linkFormats, should be at least undefined, but got 1

When I look at the code I believe it's because we're trying to interpolate the minimum key, but we should be referencing minItems. Also the test doesn't actually test that the string is correct it only tests that it's rendering roughly the correct message.

Here's how I'm defining the json schema for that field:

 "linkFormats": {
    "minItems": 3,
    "type": "array",
    "items": {
      "type": "string"
    }
  }

If you want I can try to submit a CR for this unless you're very eager to fix.

Screenshot 2024-03-27 at 11 08 55 am

Array values mutated during validate when allOf exists

This is a weird one....but....if I freeze an array in the values under certain conditions (you have an array AND allOf must exist), it will throw an error.

const schema = {
  "id": "animals",
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "horse": {
      "type": "string"
    },
    "dog": {
      "type": "string"
    },
    "lizards": {
      "minItems": 3,
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  },
  "allOf": [
    {
      "if": {
        "properties": {
          "horse": {
            "const": ""
          }
        }
      },
      "then": {
        "properties": {
          "dog": {
            "minLength": 1
          }
        }
      }
    }
  ]
};

var Draft07 = new require("json-schema-library").Draft07;
var x = new Draft07(schema);
x.validate({ lizards: Object.freeze([]) });

/**
  * Uncaught TypeError: Cannot add property 0, object is not extensible
  * at Object.array 
  *  (/node_modules/json-schema-library/dist/jsonSchemaLibrary.js:2:53249)
  *     at fr (/node_modules/json-schema-library/dist/jsonSchemaLibrary.js:2:51135)
 **/

And wildly if you don't freeze the array, it just fills it up with an empty string for the number of items are set with minItems. What a good time!

> var a = [];
> var Draft07 = new require("json-schema-library").Draft07;
var x = new Draft07(schema);
x.validate({ lizards: a })
[]
> a
[ '', '', '' ]

I think the error is happening here, but haven't had time to look into it yet:

d[i] = getTemplate(

How to properly obtain a template of a def?

I have a schema I'm working with that is something like the following:

const mySchema = {
  properties: {
    inputs: {
      items: {
        $ref: '#/$defs/Input'
      },
      type: 'array',
    }
  },
  additionalProperties: false,
  type: 'object',
  required: [
    'inputs'
  ],
  $defs: {
    Input: {
      properties: {
        name: {
          type: 'string'
        },
        value: {
          oneOf: [
            {
              type: 'string'
            },
            {
              type: 'number'
            },
        }
      },
      additionalProperties: false,
      type: 'object',
      required: ['name']
    }
  }
};

When I use:

const newSchema = new Draft04(mySchema);
const template = newSchema.getTemplate();

I get back a JSON object that looks something like:

{
    inputs: []
}

What I need to do now is grab a template of the Input definition referenced in the schema's $defs section, but I'm not quite sure how to do that. I thought that something like

const compiledSchema = newSchema.compileSchema({ $ref: "/$defs/Input" });
const inputSchema = compiledSchema.getRef();

would work, but that didn't yield any results. All that happened was that compiledSchema and inputSchema were the exact same sets of data, no schema to be found. What I'm expecting to get back is something like:

{
    name: ''
}

But I'd also need to know how to get something like

{
    name: '',
    value: ''
}

as value in this definition isn't required, but I may have access to that data depending on the context and will want to fill it in.

Type 'number' accepts null/NaN as value

Hi,
when validating a value of type number, null or NaN are assumed as valid value. If the type integer is validated, this error message appears:

Expected NaN (number) in # to be of type integer

Expected behavior:

When checking the type number, this error message is generated for a value of null or NaN:

Expected NaN (number) in # to be of type number

Schema

{
   type: 'number'
}

Value

null

Version: v7.3.2

Template generation for arrays with `anyOf` clobbers valid default values using first schema's template

Given the following schema listSchemaWithDefault:

{
  "type": "object",
  "properties": {
    "someList": {
      "type": "array",
      "items": { "anyOf": [{ "a": "number" }, { "b": "string" }, { "c": { "const": "foo" } }] },
      "minItems": 3,
      "default": [
        { "a": 1 },
        { "b": "schfifty-five" },
        { "c": "foo" }
      ]
    }
  }
}

calling new Draft07(listSchemaWithDefault).getTemplate() will return something to the effect of:

{
  "someList": [
    { "a": 1 },
    { "a": 0, "b": "schfifty-five" }
    { "a": 0, "c": "foo" }
  ]
}

(furthermore, as an additional and separate issue, these objects are permanently overwritten in the original schema object as an unavoidable side-effect.)

The expected behavior in this case would be to return the default value as-is, as each object is valid according to one of the schemas in anyOf. Additionally, if the middle schema in the anyOf was modified to { "required": ["b", "f"], "b": "string", "f": { "const": "bar" } }, I would expect that the middle object would be returned from getTemplate as { "b": "schfifty-five", "f": "bar" } (without modifying the original value).

My understanding is the getSchema function already has the ability to a piece of data to a specific schema that is present in an anyOf (as per the docs):

image

In this case, as I understand it, calling new Draft07(listSchemaWithDefault).getSchema('/someList/1', listSchemaWithDefault.properties.someList.default) would return the value { "b": "string" } as expected. Therefore, my belief is that the bug lies in getTemplateSchema - instead of always taking the first item, it should attempt to resolve the passed in data to the matching schema from the anyOf using the same technique as in getSchema.

getSchema() and each() don't seem to handle anyOf

I have a schema with a top-level anyOf with a bunch of $refs to definitions (essentially a union type).

My use case for getSchema() or each() is to let the library resolve which of the anyOf items match and give me the matching schema (resolved from $ref).

But all I am getting is UnknownPropertyError (Could not find a valid schema for property # within object) in each(), and getSchema() always just returns the root schema. isValid() however returns true.

If I change the anyOf to oneOf and move it to a nested property instead of top-level, it works, but obviously that changes the semantics.

Would really love to use this helper, I've not found any JSON schema library that offers similar utility.

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

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"

Tests fail on case-sensitive OSes, such as Linux

npm test currently fails on case-sensitive OSes such as Ubuntu (and other Linux distros), due to a number of references to draft04 in the tests, as opposed to Draft04, which is the file's actual name on-disk.

Request for Full ESM Support and Enabling "type: module"

I kindly request the following enhancements in json-schema-library:

  1. Full ESM Support: Enable comprehensive ESM support to ensure seamless integration into projects using ECMAScript modules.
  2. Enable "type: module": We propose enabling the "type: module" field in the package.json to facilitate the use of ECMAScript modules.

For more context, I am coming from this issue: codemirror-json-schema issue 66

tl;dr: We want to integrate @uiw/react-codemirror into our nextjs app and add the extension codemirror-json-schema for linting and code completion. After a short discussion it seems to be possible if your lib supports ESM and type: module.

If feasible, I am open to contributing to this enhancement by opening a PR. However, before doing so, I would appreciate guidance and validation from you to ensure that the proposed changes align with the project's goals and conventions.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.