Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
udamir committed Jun 17, 2023
0 parents commit d6127c9
Show file tree
Hide file tree
Showing 20 changed files with 8,176 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
node_modules
.env
.vscode
dist
.vuepress
temp
browser
coverage
.DS_store
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) 2022 Damir Yusipov

MIT License:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
89 changes: 89 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# allof-merge
<img alt="npm" src="https://img.shields.io/npm/v/allof-merge"> <img alt="npm" src="https://img.shields.io/npm/dm/allof-merge?label=npm"> <img alt="npm type definitions" src="https://img.shields.io/npm/types/allof-merge"> <img alt="GitHub" src="https://img.shields.io/github/license/udamir/allof-merge">

Merge schemas combined using allOf into a more readable composed schema free from allOf.

## Features
- Safe merging of schemas combined with allOf in whole JsonSchema document
- Merged schema does not validate more or less than the original schema
- Removes almost all logical impossibilities
- Correctly merge additionalProperties, patternProperties and properties taking into account common validations
- Correctly merge items and additionalItems taking into account common validations
- Supports merging JsonSchemas draft-04 and draft-06
- Supports rules extension to support other JsonSchema versions
- Supports $refs and circular references either (internal references only)
- Typescript syntax support out of the box
- No dependencies, can be used in nodejs or browser

## Other libraries
There are some libraries that can merge schemas combined with allOf. One of the most popular is [mokkabonna/json-schema-merge-allof](https://www.npmjs.com/package/json-schema-merge-allof), but it has some limitatons: Does not support circular $refs and no Typescript syntax out of the box.

## External $ref
If one of your schemas contain a external $ref you should bundle them via [api-ref-bundler](https://github.com/udamir/api-ref-bundler) first.

## Installation
```SH
npm install allof-merge --save
```

## Usage

### Nodejs
```ts
import { merge } from 'allof-merge'

const merged = merge({
type: ['object', 'null'],
additionalProperties: {
type: 'string',
minLength: 5
},
allOf: [{
type: ['array', 'object'],
additionalProperties: {
type: 'string',
minLength: 10,
maxLength: 20
}
}]
})

console.log(merged)
// {
// type: 'object',
// additionalProperties: {
// type: 'string',
// minLength: 10,
// maxLength: 20
// }
// }

```

### Browsers

A browser version of `allof-merge` is also available via CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/allof-merge@latest/browser/allof-merge.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/allof-merge@latest/browser/allof-merge.js"></script>
```

Reference `allof-merge.min.js` in your HTML and use the global variable `AllOfMerge`.
```HTML
<script>
var merged = AllOfMerge.merge({ /* ... */ })
</script>
```

## Documentation

TBD

## Contributing
When contributing, keep in mind that it is an objective of `allof-merge` to have no package dependencies. This may change in the future, but for now, no-dependencies.

Please run the unit tests before submitting your PR: `npm test`. Hopefully your PR includes additional unit tests to illustrate your change/modification!

## License

MIT
62 changes: 62 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"name": "allof-merge",
"version": "0.1.0",
"description": "Simplify your JsonSchema by combining allOf safely.",
"module": "dist/esm/index.js",
"main": "dist/cjs/index.js",
"types": "dist/cjs/index.d.ts",
"files": [
"dist",
"browser"
],
"browser": {
"./dist/cjs/index.js": "./browser/allof-merge.js"
},
"scripts": {
"build": "tsc && tsc --module commonjs --outDir dist/cjs",
"test": "jest --verbose",
"prepublish": "rm -r dist || true && npm run build && npm run build:web",
"test:coverage": "jest --verbose --coverage",
"build:web": "vite build"
},
"keywords": [
"jsonschema",
"allof",
"merge"
],
"author": "Damir Yusipov",
"license": "MIT",
"devDependencies": {
"@types/jest": "^26.0.0",
"jest": "^26.0.1",
"js-yaml": "^4.1.0",
"ts-jest": "^26.1.0",
"ts-loader": "^8.4.0",
"ts-node": "^10.7.0",
"tslint": "^6.1.2",
"typescript": "^4.6.2",
"vite": "^4.3.9",
"vite-plugin-dts": "^2.3.0"
},
"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testRegex": "(/tests/.*|(\\.|/)(test|spec))\\.(ts?|tsx?|js?|jsx?)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"modulePathIgnorePatterns": [
"<rootDir>/dist/"
],
"collectCoverage": true
},
"dependencies": {
"json-crawl": "^0.1.0"
}
}
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export * from "./merge"
export * from "./resolvers"
export * from "./rules"
export * from "./types"
export * from "./utils"
162 changes: 162 additions & 0 deletions src/merge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { JsonPath, SyncCloneHook, isObject, syncClone } from "json-crawl"

import { buildPointer, isEqual, isRefNode, resolveRefNode } from "./utils"
import { jsonSchemaMergeResolver } from "./resolvers"
import { MergeContext, MergeOptions } from "./types"
import { jsonSchemaMergeRules } from "./rules"

const flattenAllOf = (items: any[], source: any): any[] => {
// allOf: [{ allOf: [a,b], c }] => allOf: [a, b, c]

const result: any[] = []
for (const item of items) {
if (!isObject(item)) {
// error, object expected
continue
}

if (!item.allOf || !Array.isArray(item.allOf)) {
// TODO skip non-array allOf
result.push(item)
continue
}

const { allOf, ...sibling } = item
const allOfItems = Object.keys(sibling).length ? [sibling, ...allOf] : allOf
const resolvedAllOfItems = allOfItems.map((item) => isRefNode(item) ? resolveRefNode(source, item) : item)
result.push(...flattenAllOf(resolvedAllOfItems, source))
}

return result
}

export const removeDuplicates = <T>(array: T[]): T[] => {
const uniqueItems: T[] = [];

for (const item of array) {
if (!uniqueItems.some((uniqueItem) => isEqual(uniqueItem, item))) {
uniqueItems.push(item);
}
}

return uniqueItems;
}

const getAllOfRule = (path: JsonPath, rules: any) => {

for (const key of path) {
let _key = `/${key}`
if (!(_key in rules)) {
_key = "/*"
}

rules = rules[_key]
rules = typeof rules === "function" ? rules() : rules

if (!rules) { return }
}

if ("/" in rules) {
rules = rules["/"]
rules = typeof rules === "function" ? rules() : rules
}

return rules["/allOf"]
}

const findNodeToDelete = (path: JsonPath): [string, number] | undefined => {
for (let i = path.length - 2; i >= 0; i--) {
if ((path[i] === "anyOf" || path[i] === "oneOf")) {
const _path = path.slice(0, i+1)
return [JSON.stringify(_path), path[i+1] as number]
}
}
return
}

export const allOfResolverHook = (options?: MergeOptions): SyncCloneHook<{}> => {

const resolvedCache = new Map<string, any>()
const nodeToDelete: Map<string, number> = new Map()
let source = options?.source
const mergeRules = options?.rules || jsonSchemaMergeRules()

return (value, ctx) => {
// save root value as source if source is not defined
if (!ctx.path.length && !options?.source) {
source = value
}

// check if current node is JsonSchema
const rules = getAllOfRule(ctx.path, mergeRules)

// console.log(ctx.path, `JsonSchema: ${!!rules}`)

const exitHook = () => {
const { node } = ctx.state
const strPath = JSON.stringify(ctx.path)
if (nodeToDelete.has(strPath)) {
const key = nodeToDelete.get(strPath)!
if (Array.isArray(node[ctx.key])) {
if (node[ctx.key].length < 2) {
throw new Error('Could not merge values of :"' + key + '". They are probably incompatible')
// options?.onMergeError?.('Could not merge values. They are probably incompatible', ctx.path, (value as any)?.allOf)
}
node[ctx.key].splice(key, 1)
}
}
if ("anyOf" in node) {
node.anyOf = removeDuplicates(node.anyOf)
}
if ("oneOf" in node) {
node.oneOf = removeDuplicates(node.oneOf)
}
}

if (!rules) { return { value, exitHook } }

// skip if no allOf
if (!isObject(value) || !value.allOf) {
return { value, exitHook }
}

const pointer = buildPointer(ctx.path)
if (resolvedCache.has(pointer)) {
return { value: resolvedCache.get(pointer) }
}

const { allOf, ...sibling } = value

// remove allOf from scheam if is wrong type or empty
if (!Array.isArray(allOf) || !allOf.length) {
return { value: sibling, exitHook }
}

const allOfItems = Object.keys(sibling).length ? [...allOf, sibling] : allOf
const resolvedAllOfItems = allOfItems.map((item) => isRefNode(item) ? resolveRefNode(source, item) : item)

try {
const _ctx: MergeContext = {
allOfItems: [],
mergeRules,
mergeError: (msg, values) => options?.onMergeError?.(msg, ctx.path, values)
}
const mergedNode = jsonSchemaMergeResolver(flattenAllOf(resolvedAllOfItems, source), _ctx)
return { value: mergedNode, exitHook }
} catch (error) {
const args = findNodeToDelete(ctx.path)
if (args) {
nodeToDelete.set(...args)
return { exitHook }
}
throw error
}
}
}

export const merge = (value: any, options?: MergeOptions) => {

const hook = allOfResolverHook(options)

return syncClone(value, hook, {})
}
Loading

0 comments on commit d6127c9

Please sign in to comment.