Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ref support #2

Open
wants to merge 7 commits into
base: feature/esm-cjs-dual-support
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kickstartds/json-schema-to-typescript",
"version": "13.1.7",
"version": "13.1.20",
"description": "compile json schema to typescript typings",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
Expand Down Expand Up @@ -30,15 +30,14 @@
"tdd": "concurrently -r -p '' -k 'npm run watch' 'npm run watch:test'",
"test": "npm run pre-test && ava --timeout=300s --verbose",
"stresstest": "seq 1 10 | xargs -I{} npm test",
"postinstall": "patch-package",
"prepublishOnly": "npm test",
"pre-test": "npm run clean && npm run format-check && npm run build:server && npm run build:test",
"watch": "tsup src/index.ts src/cli.ts --watch",
"watch:test": "ava -w"
},
"repository": {
"type": "git",
"url": "git+https://github.com/bcherny/json-schema-to-typescript.git"
"url": "git+https://github.com/kickstartds/json-schema-to-typescript.git"
},
"keywords": [
"json",
Expand Down Expand Up @@ -71,8 +70,6 @@
"lodash-es": "^4.17.21",
"minimist": "^1.2.6",
"mkdirp": "^1.0.4",
"patch-package": "^8.0.0",
"postinstall-postinstall": "^2.1.0",
"prettier": "^2.6.2"
},
"devDependencies": {
Expand All @@ -93,6 +90,8 @@
"eslint": "^8.15.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.0.0",
"patch-package": "^8.0.0",
"postinstall-postinstall": "^2.1.0",
"rimraf": "^3.0.2",
"shx": "^0.3.4",
"tsify": "^5.0.4",
Expand All @@ -105,7 +104,8 @@
],
"ignoredByWatcher": [
"./src"
]
],
"snapshotDir": "./test/__snapshots__"
},
"browserify": {
"transform": [
Expand Down
61 changes: 60 additions & 1 deletion src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export function generate(ast: AST, options = DEFAULT_OPTIONS): string {
return (
[
options.bannerComment,
declareReferencedTypeImports(ast, options, ast.standaloneName!),
declareNamedTypes(ast, options, ast.standaloneName!),
declareNamedInterfaces(ast, options, ast.standaloneName!),
declareEnums(ast, options),
Expand Down Expand Up @@ -142,6 +143,8 @@ function declareNamedTypes(ast: AST, options: Options, rootASTName: string, proc
]
.filter(Boolean)
.join('\n')
case 'REFERENCE':
return ``
default:
if (hasStandaloneName(ast)) {
return generateStandaloneType(ast, options)
Expand All @@ -150,6 +153,62 @@ function declareNamedTypes(ast: AST, options: Options, rootASTName: string, proc
}
}

function declareReferencedTypeImports(
ast: AST,
options: Options,
rootASTName: string,
processed = new Set<AST>(),
imports = new Set<string>(),
): string {
if (processed.has(ast)) {
return ''
}

processed.add(ast)

switch (ast.type) {
case 'ARRAY':
return [declareReferencedTypeImports(ast.params, options, rootASTName, processed, imports)]
.filter(Boolean)
.join('\n')
case 'ENUM':
return ''
case 'INTERFACE':
return getSuperTypesAndParams(ast)
.map(
ast =>
(ast.standaloneName === rootASTName || options.declareExternallyReferenced) &&
declareReferencedTypeImports(ast, options, rootASTName, processed, imports),
)
.filter(Boolean)
.join('\n')
case 'INTERSECTION':
case 'TUPLE':
case 'UNION':
return [
ast.params
.map(ast => declareReferencedTypeImports(ast, options, rootASTName, processed, imports))
.filter(Boolean)
.join('\n'),
'spreadParam' in ast && ast.spreadParam
? declareReferencedTypeImports(ast.spreadParam, options, rootASTName, processed, imports)
: undefined,
]
.filter(Boolean)
.join('\n')
case 'REFERENCE':
const importName = options.renderImportStatement(ast.params)
if (imports.has(importName)) {
return ''
} else {
imports.add(importName)
return importName
}
default:
return ''
}
}

function generateTypeUnmemoized(ast: AST, options: Options): string {
const type = generateRawType(ast, options)

Expand Down Expand Up @@ -193,7 +252,7 @@ function generateRawType(ast: AST, options: Options): string {
case 'OBJECT':
return 'object'
case 'REFERENCE':
return ast.params
return options.renderImportName(ast.params)
case 'STRING':
return 'string'
case 'TUPLE':
Expand Down
10 changes: 10 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ export interface Options {
* Disclaimer comment prepended to the top of each generated file.
*/
bannerComment: string
/**
* Rendering function for the import name added when processing a reference.
*/
renderImportName: (reference: string) => string
/**
* Rendering function for the import itself when processing a reference..
*/
renderImportStatement: (reference: string) => string
/**
* Root directory for resolving [`$ref`](https://tools.ietf.org/id/draft-pbryan-zyp-json-ref-03.html)s.
*/
Expand Down Expand Up @@ -87,6 +95,8 @@ export const DEFAULT_OPTIONS: Options = {
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/`,
renderImportName: reference => reference,
renderImportStatement: reference => reference,
cwd: process.cwd(),
declareExternallyReferenced: true,
enableConstEnums: true,
Expand Down
10 changes: 9 additions & 1 deletion src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,15 @@ function parseNonLiteral(
type: 'UNION',
}
case 'REFERENCE':
throw Error(format('Refs should have been resolved by the resolver!', schema))
if (!schema.$ref) throw Error(format('Refs should have been resolved by the resolver!', schema))
return {
comment: `Referenced component ${options.renderImportName(schema.$ref)}`,
deprecated: false,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
type: 'REFERENCE',
params: schema.$ref,
}
case 'STRING':
return {
comment: schema.description,
Expand Down
22 changes: 22 additions & 0 deletions test/e2e/refExternal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export const input = {
title: 'Referencing',
type: 'object',
properties: {
foo: {
$ref: 'ReferencedType.json',
},
},
required: ['foo'],
additionalProperties: false,
}

export const options = {
declareExternallyReferenced: true,
$refOptions: {
resolve: {
external: false,
http: false,
file: false,
},
},
}
2 changes: 2 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {run as runIdempotenceTests} from './testIdempotence.js'
import {run as runLinkerTests} from './testLinker.js'
import {run as runNormalizerTests} from './testNormalizer.js'
import {run as runUtilsTests} from './testUtils.js'
import {run as runExternalRefsTests} from './testExternalRefs.js'

runE2ETests()

Expand All @@ -15,4 +16,5 @@ if (!hasOnly()) {
runLinkerTests()
runNormalizerTests()
runUtilsTests()
runExternalRefsTests()
}
12 changes: 12 additions & 0 deletions test/testExternalRefs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import test from 'ava'

import {link} from '../src/linker.js'
import {compile} from '../src/index.js'
import {input, options} from './e2e/refExternal.js'

export function run() {
test('should correctly generate TypeScript typings from JSON schema with $ref, and declareExternallyReferenced false', async t => {
const schema = link(input) as any
t.snapshot(await compile(schema, schema.$id, options), 'This will not match')
})
}