• Stars
    star
    1,312
  • Rank 34,404 (Top 0.7 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated 5 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate JSON schema from your Typescript sources

ts-json-schema-generator

Test codecov npm version

Extended version of https://github.com/xiag-ag/typescript-to-json-schema.

Inspired by YousefED/typescript-json-schema. Here's the differences list:

  • this implementation avoids the use of typeChecker.getTypeAtLocation() (so probably it keeps correct type aliases)
  • processing AST and formatting JSON schema have been split into two independent steps
  • not exported types, interfaces, enums are not exposed in the definitions section in the JSON schema

Contributors

This project is made possible by a community of contributors. We welcome contributions of any kind (issues, code, documentation, examples, tests,...). Please read our code of conduct.

CLI Usage

Run the schema generator with npx:

npx ts-json-schema-generator --path 'my/project/**/*.ts' --type 'My.Type.Name'

Or install the package and then run it

npm install --save ts-json-schema-generator
./node_modules/.bin/ts-json-schema-generator --path 'my/project/**/*.ts' --type 'My.Type.Name'

Note that different platforms (e.g. Windows) may use different path separators so you may have to adjust the command above.

Also note that you need to quote paths with * as otherwise the shell will expand the paths and therefore only pass the first path to the generator.

Programmatic Usage

// main.js

const tsj = require("ts-json-schema-generator");
const fs = require("fs");

/** @type {import('ts-json-schema-generator/dist/src/Config').Config} */
const config = {
    path: "path/to/source/file",
    tsconfig: "path/to/tsconfig.json",
    type: "*", // Or <type-name> if you want to generate schema for that one type only
};

const output_path = "path/to/output/file";

const schema = tsj.createGenerator(config).createSchema(config.type);
const schemaString = JSON.stringify(schema, null, 2);
fs.writeFile(output_path, schemaString, (err) => {
    if (err) throw err;
});

Run the schema generator via node main.js.

Custom formatting

Extending the built-in formatting is possible by creating a custom formatter and adding it to the main formatter:

  1. First we create a formatter, in this case for formatting function types:
// my-function-formatter.ts
import { BaseType, Definition, FunctionType, SubTypeFormatter } from "ts-json-schema-generator";
import ts from "typescript";

export class MyFunctionTypeFormatter implements SubTypeFormatter {
    // You can skip this line if you don't need childTypeFormatter
    public constructor(private childTypeFormatter: TypeFormatter) {}

    public supportsType(type: FunctionType): boolean {
        return type instanceof FunctionType;
    }

    public getDefinition(type: FunctionType): Definition {
        // Return a custom schema for the function property.
        return {
            type: "object",
            properties: {
                isFunction: {
                    type: "boolean",
                    const: true,
                },
            },
        };
    }

    // If this type does NOT HAVE children, generally all you need is:
    public getChildren(type: FunctionType): BaseType[] {
        return [];
    }

    // However, if children ARE supported, you'll need something similar to
    // this (see src/TypeFormatter/{Array,Definition,etc}.ts for some examples):
    public getChildren(type: FunctionType): BaseType[] {
        return this.childTypeFormatter.getChildren(type.getType());
    }
}
  1. Then we add the formatter as a child to the core formatter using the augmentation callback:
import { createProgram, createParser, SchemaGenerator, createFormatter } from "ts-json-schema-generator";
import { MyFunctionTypeFormatter } from "./my-function-formatter.ts";
import fs from "fs";

const config = {
    path: "path/to/source/file",
    tsconfig: "path/to/tsconfig.json",
    type: "*", // Or <type-name> if you want to generate schema for that one type only
};

// We configure the formatter an add our custom formatter to it.
const formatter = createFormatter(config, (fmt, circularReferenceTypeFormatter) => {
    // If your formatter DOES NOT support children, e.g. getChildren() { return [] }:
    fmt.addTypeFormatter(new MyFunctionTypeFormatter());
    // If your formatter DOES support children, you'll need this reference too:
    fmt.addTypeFormatter(new MyFunctionTypeFormatter(circularReferenceTypeFormatter));
});

const program = createProgram(config);
const parser = createParser(program, config);
const generator = new SchemaGenerator(program, parser, formatter, config);
const schema = generator.createSchema(config.type);

const schemaString = JSON.stringify(schema, null, 2);
fs.writeFile(output_path, schemaString, (err) => {
    if (err) throw err;
});

Custom parsing

Similar to custom formatting, extending the built-in parsing works practically the same way:

  1. First we create a parser, in this case for parsing construct types:
// my-constructor-parser.ts
import { Context, StringType, ReferenceType, BaseType, SubNodeParser } from "ts-json-schema-generator";
// use typescript exported by TJS to avoid version conflict
import ts from "ts-json-schema-generator";

export class MyConstructorParser implements SubNodeParser {
    supportsNode(node: ts.Node): boolean {
        return node.kind === ts.SyntaxKind.ConstructorType;
    }
    createType(node: ts.Node, context: Context, reference?: ReferenceType): BaseType | undefined {
        return new StringType(); // Treat constructors as strings in this example
    }
}
  1. Then we add the parser as a child to the core parser using the augmentation callback:
import { createProgram, createParser, SchemaGenerator, createFormatter } from "ts-json-schema-generator";
import { MyConstructorParser } from "./my-constructor-parser.ts";
import fs from "fs";

const config = {
    path: "path/to/source/file",
    tsconfig: "path/to/tsconfig.json",
    type: "*", // Or <type-name> if you want to generate schema for that one type only
};

const program = createProgram(config);

// We configure the parser an add our custom parser to it.
const parser = createParser(program, config, (prs) => {
    prs.addNodeParser(new MyConstructorParser());
});

const formatter = createFormatter(config);
const generator = new SchemaGenerator(program, parser, formatter, config);
const schema = generator.createSchema(config.type);

const schemaString = JSON.stringify(schema, null, 2);
fs.writeFile(output_path, schemaString, (err) => {
    if (err) throw err;
});

Options

-p, --path 'index.ts'
    The path to the TypeScript source file. If this is not provided, the type will be searched in the project specified in the `.tsconfig`.

-t, --type 'My.Type.Name'
    The type the generated schema will represent. If omitted, the generated schema will contain all
    types found in the files matching path. The same is true if '*' is specified.

-i, --id 'generatedSchemaId'
    The `$id` of the generated schema. If omitted, there will be no `$id`.

-e, --expose <all|none|export>
    all: Create shared $ref definitions for all types.
    none: Do not create shared $ref definitions.
    export (default): Create shared $ref definitions only for exported types (not tagged as `@internal`).

-f, --tsconfig 'my/project/tsconfig.json'
    Use a custom tsconfig file for processing typescript (see https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) instead of the default:
    {
        "compilerOptions": {
            "noEmit": true,
            "emitDecoratorMetadata": true,
            "experimentalDecorators": true,
            "target": "ES5",
            "module": "CommonJS",
            "strictNullChecks": false,
        }
    }

-j, --jsDoc <extended|none|basic>
    none: Do not use JsDoc annotations.
    basic: Read JsDoc annotations to provide schema properties.
    extended (default): Also read @nullable, and @asType annotations.

--unstable
    Do not sort properties.

--strict-tuples
    Do not allow additional items on tuples.

--no-top-ref
    Do not create a top-level $ref definition.

--no-type-check
    Skip type checks for better performance.

--no-ref-encode
    Do not encode references. According to the standard, references must be valid URIs but some tools do not support encoded references.

--validation-keywords
    Provide additional validation keywords to include.

-o, --out
    Specify the output file path. Without this option, the generator logs the response in the console.

--additional-properties <true|false>
    Controls whether or not to allow additional properties for objects that have no index signature.

    true: Additional properties are allowed
    false (default): Additional properties are not allowed

--minify
    Minify generated schema (default: false)

Current state

  • interface types
  • enum types
  • union, tuple, type[] types
  • Date, RegExp, URL types
  • string, boolean, number types
  • "value", 123, true, false, null, undefined literals
  • type aliases
  • generics
  • typeof
  • keyof
  • conditional types

Run locally

yarn --silent run run --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'

Debug

yarn --silent run debug --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'

And connect via the debugger protocol.

AST Explorer is amazing for developers of this tool!

Publish

Publishing is handled by a 2-branch pre-release process, configured in publish-auto.yml. All changes should be based off the default next branch, and are published automatically.

  • PRs made into the default branch are auto-deployed to the next pre-release tag on NPM. The result can be installed with npm install ts-json-schema-generator@next
    • When merging into next, please use the squash and merge strategy.
  • To release a new stable version, open a PR from next into stable using this compare link.
    • When merging from next into stable, please use the create a merge commit strategy.

More Repositories

1

vega

A visualization grammar.
JavaScript
10,564
star
2

vega-lite

A concise grammar of interactive graphics, built on Vega.
TypeScript
4,260
star
3

voyager

Visualization Tool for Data Exploration
TypeScript
1,405
star
4

lyra

An interactive, graphical Visualization Design Environment (VDE)
TypeScript
1,042
star
5

falcon

Brushing and linking for big data
Jupyter Notebook
919
star
6

datalib

JavaScript data utility library.
JavaScript
727
star
7

polestar

Lightweight Tableau-style interface for visual analysis, built on Vega-lite.
JavaScript
370
star
8

ipyvega

IPython/Jupyter notebook module for Vega and Vega-Lite
Jupyter Notebook
369
star
9

react-vega

Convert Vega spec into React class conveniently
TypeScript
363
star
10

vega-embed

Publish Vega visualizations as embedded web components with interactive parameters.
TypeScript
352
star
11

compassql

CompassQL Query Language for visualization recommendation.
TypeScript
258
star
12

vega-datasets

Common repository for example datasets used by Vega-related projects
TypeScript
234
star
13

vega-lite-api

A JavaScript API for Vega-Lite.
JavaScript
198
star
14

editor

Editor/IDE for Vega and Vega-Lite
TypeScript
134
star
15

vega-themes

Themes for stylized Vega and Vega-Lite visualizations.
TypeScript
104
star
16

vega-desktop

App for viewing visualizations created in Vega or Vega-lite
JavaScript
87
star
17

vega-tooltip

Tooltip Plugin for Vega-Lite
TypeScript
77
star
18

vega.github.io

The Vega landing page.
HTML
70
star
19

react-vega-lite

react + vega-lite
JavaScript
68
star
20

svelte-vega

Svelte component for Vega and Vega-Lite
Svelte
66
star
21

vl-convert

Utilities for converting Vega-Lite specs from the command line and Python
Rust
65
star
22

compass

Visualization Recommendation Engine, powered by Vega-Lite Specification Language
JavaScript
56
star
23

vega-loader-arrow

Data loader for the Apache Arrow format.
JavaScript
51
star
24

scalable-vega

A demo of scaling Vega to millions of records
TypeScript
45
star
25

vega-webgl-renderer

WebGL renderer for Vega.
JavaScript
41
star
26

vega-dataflow

Reactive dataflow processing.
JavaScript
39
star
27

vega-editor

[Deprecated] Please use https://github.com/vega/editor! (Link to deployed old editor: http://vega.github.io/vega-editor)
JavaScript
39
star
28

dataflow-api

JavaScript API for dataflow processing.
JavaScript
38
star
29

vega-plus

Make Vega charts of large datasets
TypeScript
35
star
30

vega-scenegraph

Vega scenegraph and renderers.
JavaScript
34
star
31

voyager2

Deprecated version of Voyager 2 (in Angular), please use https://github.com/vega/voyager.
JavaScript
30
star
32

schema

JSON schema for Vega and Vega-Lite
27
star
33

vega-lite-tutorials

Compilation of Vega-Lite & Altair Tutorials
Jupyter Notebook
24
star
34

vega-expression

Vega expression parser and code generator.
JavaScript
24
star
35

vega-lib

Include Vega in projects using minimal dependencies.
HTML
21
star
36

dataflow-vis

Experimental Vega Dataflow Visualization
JavaScript
20
star
37

vega-view

View component for Vega visualizations.
JavaScript
20
star
38

vega-label

Labeling algorithm for Vega.
JavaScript
19
star
39

vega-render-service

A service to render Vega visualizations
TypeScript
19
star
40

datalib-sketch

Probabilistic data structures for large or streaming data sets.
JavaScript
19
star
41

editor-backend

Backend for the Vega Editor
TypeScript
18
star
42

vega-bundler

Compile optimized Vega and Vega-Lite bundles.
JavaScript
17
star
43

vega-lite-ui

Common UI Library that powers Polestar and Voyager
JavaScript
13
star
44

vega-renderer-webgl

WebGL Renderer extension for Vega
JavaScript
13
star
45

vega-tutorials

Interactive tutorials for learning Vega.
JavaScript
13
star
46

vega-parser

Parse Vega specifications to runtime dataflows.
JavaScript
13
star
47

vega-vscode

Vega Language Plug-in for Visual Studio Code
TypeScript
12
star
48

vega-statistics

Statistical routines and probability distributions.
JavaScript
12
star
49

voyager-server

TypeScript
11
star
50

roadmap

The Vega and Vega-Lite Roadmap
9
star
51

vega-geo

Geographic data transforms for Vega dataflows.
JavaScript
8
star
52

vega-typings

Typings for Vega
TypeScript
8
star
53

vega-lite-transforms2sql

Convert extracted Vega-Lite transforms to SQL for scalable visualizations
TypeScript
6
star
54

vega-runtime

Runtime support for Vega dataflows.
JavaScript
6
star
55

vega-webgpu

WebGPU Renderer Extension for Vega
TypeScript
6
star
56

vega-crossfilter

Indexed cross-filtering for Vega dataflows.
JavaScript
6
star
57

vega-lite-to-api

Convert Vega-Lite JSON spec to Vega-Lite JS API
TypeScript
6
star
58

vega-hierarchy

Hierarchical layout transforms for Vega dataflows.
JavaScript
5
star
59

vega-logging

Vega logging utilities.
JavaScript
5
star
60

vega-util

JavaScript utilities for Vega.
JavaScript
4
star
61

vue-vega

Vue component for Vega and Vega-Lite
TypeScript
4
star
62

voyager-electron

JavaScript
4
star
63

vl-convert-service

Python
4
star
64

vega-loader

Network request and file loading utilities.
JavaScript
3
star
65

vega-wordcloud

Wordcloud layout algorithm for Vega dataflows.
JavaScript
3
star
66

vega-dataflow-examples

Example applications driven by Vega dataflows.
JavaScript
3
star
67

voyager-docs

3
star
68

vega-projection

Projections for cartographic mapping.
JavaScript
3
star
69

vega-event-selector

A CSS-inspired language to select, sequence, and compose DOM events into event streams.
JavaScript
3
star
70

vega-lite-v1

Copy of Vega-Lite 1.x website
TypeScript
2
star
71

vega-lite-params-proposal

2
star
72

vega-transforms

Data processing transforms for Vega dataflows.
JavaScript
2
star
73

vega-lite-dev-config

Version-controlled build config for easy re-use and sharing
TypeScript
2
star
74

vega-force

Force simulation transform for Vega dataflows.
JavaScript
2
star
75

vega-benchmarks

Scripts to benchmark Vega's performance
HTML
2
star
76

vega-lite-v4

Copy of the Vega-Lite 4 Website
JavaScript
2
star
77

ts-api

Typescript to API generator
TypeScript
2
star
78

vega-lite-shorthand

Shorthand Syntax for Vega-Lite
2
star
79

logos

Vega and Vega-Lite Logos
2
star
80

vega-embed-v2

Vega-Embed for Vega 2 and Vega-Lite 1
JavaScript
1
star
81

vega-gist

Client-side library for managing Vega GitHub gists.
1
star
82

vega-voronoi

Voronoi diagram transform for Vega dataflows.
JavaScript
1
star
83

vega-scale

Scales and color schemes for visual encoding.
JavaScript
1
star
84

vega-lite-v3

Copy of the Vega-Lite 3 Website
TypeScript
1
star
85

vega-view-transforms

View-specific transforms for Vega dataflows.
JavaScript
1
star
86

vega-canvas

Canvas and Image object instantiation utilities.
JavaScript
1
star
87

vega-encode

Visual encoding transforms for Vega dataflows.
JavaScript
1
star