Skip to content
This repository has been archived by the owner on Nov 14, 2022. It is now read-only.

Commit

Permalink
Bugfix: make compile() non-mutating (fix bcherny#370, fix bcherny#443)
Browse files Browse the repository at this point in the history
  • Loading branch information
Boris Cherny committed May 22, 2022
1 parent a7d14c4 commit b78a616
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {readFileSync} from 'fs'
import {JSONSchema4} from 'json-schema'
import {Options as $RefOptions} from 'json-schema-ref-parser'
import {endsWith, merge} from 'lodash'
import {cloneDeep, endsWith, merge} from 'lodash'
import {dirname} from 'path'
import {Options as PrettierOptions} from 'prettier'
import {format} from './formatter'
Expand Down Expand Up @@ -138,9 +138,12 @@ export async function compile(schema: JSONSchema4, name: string, options: Partia
_options.cwd += '/'
}

const dereferenced = await dereference(schema, _options)
// Initial clone to avoid mutating the input
const _schema = cloneDeep(schema)

const dereferenced = await dereference(_schema, _options)
if (process.env.VERBOSE) {
if (isDeepStrictEqual(schema, dereferenced)) {
if (isDeepStrictEqual(_schema, dereferenced)) {
log('green', 'dereferencer', time(), '✅ No change')
} else {
log('green', 'dereferencer', time(), '✅ Result:', dereferenced)
Expand Down
2 changes: 2 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {run as runCLITests} from './testCLI'
import {run as runCompileFromFileTests} from './testCompileFromFile'
import {hasOnly, run as runE2ETests} from './testE2E'
import {run as runIdempotenceTests} from './testIdempotence'
import {run as runLinkerTests} from './testLinker'
import {run as runNormalizerTests} from './testNormalizer'
import {run as runUtilsTests} from './testUtils'
Expand All @@ -10,6 +11,7 @@ runE2ETests()
if (!hasOnly()) {
runCompileFromFileTests()
runCLITests()
runIdempotenceTests()
runLinkerTests()
runNormalizerTests()
runUtilsTests()
Expand Down
28 changes: 28 additions & 0 deletions test/testIdempotence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import test from 'ava'
import {JSONSchema4} from 'json-schema'
import {cloneDeep} from 'lodash'
import {compile} from '../src'

export function run() {
const SCHEMA: JSONSchema4 = {
type: 'object',
properties: {
firstName: {
type: 'string'
}
},
required: ['firstName']
}

test('compile() should not mutate its input', async t => {
const before = cloneDeep(SCHEMA)
await compile(SCHEMA, 'A')
t.deepEqual(before, SCHEMA)
})

test('compile() should be idempotent', async t => {
const a = await compile(SCHEMA, 'A')
const b = await compile(SCHEMA, 'A')
t.deepEqual(a, b)
})
}

0 comments on commit b78a616

Please sign in to comment.