2.3.0 • Published 8 months ago

ts-json-schema-generator v2.3.0

Weekly downloads
40,515
License
MIT
Repository
github
Last release
8 months ago

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

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.

Programmatic Usage

// main.js

const tsj = require("ts-json-schema-generator");
const fs = require("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 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";
import ts from "typescript";

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

Current state

  • interface types
  • enum types
  • union, tuple, type[] types
  • Date, RegExp 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

To publish a new version, run the workflow at https://github.com/vega/ts-json-schema-generator/actions?query=workflow%3APublish.

native-stream-wa-automate@mayahq/waborn@onhand/ts-transform-json-schemastv-test2@infinitebrahmanuniverse/nolb-ts-j@everything-registry/sub-chunk-2977tanuki.tsvite-plugin-lessmockvolar-plugin-vue-routervscode-extensions-json-generatorvite-plugin-apits2mockvite-plugin-json-schema-generatorvite-plugin-type-to-schemavalidate-data-ql@dpc-sdp/ripple-tide-api@divine/judgement-cli@commonninja/nindo@commonninja/nindo-internals@comparaonline/openapi-generator@dendronhq/dendron-clijuisyipsamvelisomor-json-schema-generatorkda-buildtyped-factorieststoswagts-json-schema-generator-webpack-plugints-to-openapits-v-gentypescript-schema-to-joitypesmithtool-validate@antmjs/rapper@apimda/devtime@appsemble/cli@angga30prabu/wa-modified@andreas-timm/config-ts@atek-cloud/tsgen@chili-api/cli@cloudcannon/configuration-types1schema@deepcrawl/oreo@ddadaal/next-typed-api-routes@ddadaal/next-typed-api-routes-cli@dbos-inc/operon@dbos-inc/dbos-openapi@deep-grasp/build@dext7r/swagger-api-typesyyabuildervingle-corgi-cliundertale-fight-creatorts2json-schemats-auditts-autotapits-runtime-validation@fastify-dev-toolkit/backend@fastify-dev-toolkit/compiler@fastify-dev-toolkit/plugin@field123/ep-ts-converting@easyv/swagger-api-types@gtsc/ts-to-openapi@gtsc/ts-to-schema@flink-app/flink@hindawi/phenom-events-validator@hurx/core@fluxapi/cli@floip/flow-runner@floe/config@gallofeliz/typescript-transform-to-json-schema@gallolabs/typescript-transform-to-json-schema@goldstack/utils-package-config-generate@furystack/onboard@kriblet/wa-automate@kiwi-app/nextjs@interweb/ts-json-schema@lxcat/schema@m3dicine/dashboard_engine@lura/cli@nightgale/volar-service-pages@nil-/rebundler@everywhere-computer/every-cli@extcore/server@ezbackend/common@mergulhao/wa-automate@justingorham/tsjsvg@jnig/chili-api-cli@jorgellose/core@kitajs/parser@jprustv/sulla-hotfix@hyperweb/ts-json-schema@octopusdeploy/step-package-build@odda-studio/schema-builder@odda-studio/cms-models@omegadot/tsrc@ombori/ts-schema@rm98/polaris-schema-gen@polaris-sloc/polaris-nx@polaris-sloc/schema-gen@nrfcloud/ts-json-schema-transformer@nornir/rest
2.4.0-next.4

8 months ago

2.3.0

11 months ago

2.2.0

12 months ago

2.2.0-next.2

12 months ago

2.2.0-next.0

12 months ago

2.2.0-next.1

12 months ago

2.4.0-next.1

10 months ago

2.4.0-next.0

10 months ago

2.4.0-next.3

9 months ago

2.4.0-next.2

9 months ago

2.3.0-next.1

12 months ago

2.3.0-next.2

12 months ago

2.3.0-next.0

12 months ago

2.3.0-next.5

11 months ago

2.3.0-next.3

11 months ago

2.3.0-next.4

11 months ago

2.1.2-next.1

1 year ago

2.1.2-next.0

1 year ago

2.1.1

1 year ago

3.0.0-next.0

1 year ago

2.1.1-next.0

1 year ago

2.1.0

1 year ago

2.1.0-next.2

1 year ago

2.1.0-next.1

1 year ago

2.1.0-next.0

1 year ago

2.0.1-next.0

1 year ago

1.5.2-next.0

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.5.1

1 year ago

1.5.1-next.4

1 year ago

1.5.1-next.2

1 year ago

1.5.1-next.3

1 year ago

1.5.1-next.1

1 year ago

1.5.0

1 year ago

1.4.1

1 year ago

1.5.1-next.0

1 year ago

1.5.0-next.0

1 year ago

1.4.1-next.0

1 year ago

1.4.0-next.1

2 years ago

1.4.0-next.0

2 years ago

1.4.0

2 years ago

1.3.0

2 years ago

1.3.0-next.5

2 years ago

1.3.0-next.6

2 years ago

1.3.0-next.7

2 years ago

1.3.0-next.8

2 years ago

1.3.0-next.9

2 years ago

1.2.1-next.2

2 years ago

1.2.1-next.0

2 years ago

1.2.1-next.1

2 years ago

1.3.0-next.2

2 years ago

1.3.0-next.3

2 years ago

1.3.0-next.4

2 years ago

1.3.0-next.0

2 years ago

1.3.0-next.1

2 years ago

1.2.0

2 years ago

1.2.0-next.6

2 years ago

1.2.0-next.5

2 years ago

1.2.0-next.7

2 years ago

1.2.0-next.2

2 years ago

1.2.0-next.1

3 years ago

1.2.0-next.4

2 years ago

1.2.0-next.3

2 years ago

1.2.0-next.0

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.1.2

3 years ago

1.1.0-next.6

3 years ago

1.1.2-next.0

3 years ago

1.1.1-next.0

3 years ago

2.0.0-next.0

3 years ago

1.1.0-next.5

3 years ago

1.1.0-next.4

3 years ago

1.1.0-next.3

3 years ago

1.1.0-next.2

3 years ago

1.0.1-next.1

3 years ago

1.0.1-next.0

3 years ago

0.98.1-next.1

3 years ago

0.98.1-next.0

3 years ago

0.98.1-next.4

3 years ago

0.98.1-next.3

3 years ago

0.98.1-next.2

3 years ago

1.1.0-next.1

3 years ago

1.1.0-next.0

3 years ago

1.0.0

3 years ago

0.97.1-next.1

3 years ago

0.97.1-next.0

3 years ago

0.98.0-next.1

3 years ago

0.98.0

3 years ago

0.98.0-next.0

3 years ago

0.97.0-next.5

4 years ago

0.97.0

4 years ago

0.97.0-next.4

4 years ago

0.97.0-next.2

4 years ago

0.97.0-next.3

4 years ago

0.97.0-next.0

4 years ago

0.97.0-next.1

4 years ago

0.96.0-next.1

4 years ago

0.96.0-next.2

4 years ago

0.96.0

4 years ago

0.96.0-next.0

4 years ago

0.95.0

4 years ago

0.94.1

4 years ago

0.94.0

4 years ago

0.93.0

4 years ago

0.91.0

4 years ago

0.92.0

4 years ago

0.90.0

4 years ago

0.89.3

4 years ago

0.89.2

4 years ago

0.89.1

4 years ago

0.89.0

4 years ago

0.87.0

4 years ago

0.88.0

4 years ago

0.86.1

4 years ago

0.86.0

4 years ago

0.85.0

4 years ago

0.84.0

4 years ago

0.83.2

4 years ago

0.83.1

4 years ago

0.83.0

4 years ago

0.82.0

4 years ago

0.81.0

4 years ago

0.80.1

4 years ago

0.80.0

4 years ago

0.79.0

4 years ago

0.78.0

4 years ago

0.77.0

5 years ago

0.76.1

5 years ago

0.76.0

5 years ago

0.75.0

5 years ago

0.74.0

5 years ago

0.73.0

5 years ago

0.72.1

5 years ago

0.72.0

5 years ago

0.71.2

5 years ago

0.71.1

5 years ago

0.71.0

5 years ago

0.70.2

5 years ago

0.70.1

5 years ago

0.70.0

5 years ago

0.69.0

5 years ago

0.68.1

5 years ago

0.68.0

5 years ago

0.67.0

5 years ago

0.67.1

5 years ago

0.66.0

5 years ago

0.65.0

5 years ago

0.64.0

5 years ago

0.63.0

5 years ago

0.62.0

5 years ago

0.61.1

5 years ago

0.61.0

5 years ago

0.60.0

5 years ago

0.59.0

5 years ago

0.58.1

5 years ago

0.58.0

5 years ago

0.57.0

5 years ago

0.56.0

6 years ago

0.55.0

6 years ago

0.54.0

6 years ago

0.53.0

6 years ago

0.52.14

6 years ago

0.52.13

6 years ago

0.32.14

6 years ago

0.52.12

6 years ago

0.52.9

6 years ago

0.52.10

6 years ago

0.52.2

6 years ago

0.51.0

6 years ago

0.50.2

6 years ago

0.50.1

6 years ago

0.50.0

6 years ago

0.49.0

6 years ago

0.48.0

6 years ago

0.47.0

6 years ago

0.46.0

6 years ago

0.45.0

6 years ago

0.44.0

6 years ago

0.43.0

6 years ago

0.42.0

6 years ago

0.41.0

6 years ago

0.40.0

6 years ago

0.39.0

6 years ago

0.38.1

6 years ago

0.38.0

6 years ago

0.37.1

6 years ago

0.37.0

6 years ago

0.36.3

6 years ago

0.36.0

7 years ago

0.35.1

7 years ago

0.35.0

7 years ago

0.34.0

7 years ago

0.33.0

7 years ago

0.32.0

7 years ago

0.31.0

7 years ago

0.30.0

7 years ago

0.29.0

7 years ago

0.28.2

7 years ago

0.28.1

7 years ago

0.28.0

7 years ago

0.27.0

7 years ago

0.26.0

7 years ago

0.25.1

7 years ago

0.25.0

7 years ago

0.24.7

7 years ago

0.24.6

7 years ago

0.24.5

7 years ago

0.24.3

7 years ago

0.24.2

7 years ago

0.24.1

7 years ago

0.23.0

7 years ago

0.22.0

7 years ago

0.21.0

7 years ago

0.20.0

7 years ago

0.19.0

7 years ago

0.18.0

7 years ago

0.16.0

8 years ago

0.15.0

8 years ago

0.14.0

8 years ago

0.13.0

8 years ago

0.12.0

8 years ago

0.11.0

8 years ago

0.10.0

8 years ago

0.9.0

8 years ago