Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-json-schema-generator

Package Overview
Dependencies
Maintainers
3
Versions
335
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-json-schema-generator - npm Package Compare versions

Comparing version 2.1.0-next.0 to 2.1.0-next.1

2

dist/package.json
{
"name": "ts-json-schema-generator",
"version": "2.1.0-next.0",
"version": "2.1.0-next.1",
"description": "Generate JSON schema from your Typescript sources",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

@@ -9,2 +9,4 @@ import ts from "typescript";

import { NeverType } from "../Type/NeverType.js";
import { ObjectType } from "../Type/ObjectType.js";
import { StringType } from "../Type/StringType.js";
export class IntersectionNodeParser {

@@ -25,5 +27,12 @@ typeChecker;

}
if (types.length === 2 && types.some((t) => t instanceof StringType) && types.some((t) => isEmptyObject(t))) {
return new StringType(true);
}
return translate(types);
}
}
function isEmptyObject(x) {
const t = derefType(x);
return t instanceof ObjectType && !t.getAdditionalProperties() && !t.getProperties().length;
}
function derefAndFlattenUnions(type) {

@@ -30,0 +39,0 @@ const derefed = derefType(type);

@@ -7,2 +7,3 @@ import ts from "typescript";

import { LiteralType } from "../Type/LiteralType.js";
import { NumberType } from "../Type/NumberType.js";
import { ObjectProperty } from "../Type/ObjectType.js";

@@ -21,3 +22,3 @@ import { StringType } from "../Type/StringType.js";

protected getAdditionalProperties(node: ts.MappedTypeNode, keyListType: UnionType, context: Context): BaseType | boolean;
protected createSubContext(node: ts.MappedTypeNode, key: LiteralType | StringType, parentContext: Context): Context;
protected createSubContext(node: ts.MappedTypeNode, key: LiteralType | StringType | NumberType, parentContext: Context): Context;
}

@@ -8,2 +8,3 @@ import { BaseType } from "./BaseType.js";

getValue(): LiteralValue;
isString(): boolean;
}

@@ -14,3 +14,6 @@ import { BaseType } from "./BaseType.js";

}
isString() {
return typeof this.value === "string";
}
}
//# sourceMappingURL=LiteralType.js.map
import { PrimitiveType } from "./PrimitiveType.js";
export declare class StringType extends PrimitiveType {
protected preserveLiterals: boolean;
constructor(preserveLiterals?: boolean);
getId(): string;
getPreserveLiterals(): boolean;
}
import { PrimitiveType } from "./PrimitiveType.js";
export class StringType extends PrimitiveType {
preserveLiterals;
constructor(preserveLiterals = false) {
super();
this.preserveLiterals = preserveLiterals;
}
getId() {
return "string";
}
getPreserveLiterals() {
return this.preserveLiterals;
}
}
//# sourceMappingURL=StringType.js.map

@@ -58,3 +58,3 @@ import { AnnotatedType } from "../Type/AnnotatedType.js";

else {
throw new Error(`Cannot assign discriminator tag to type: ${JSON.stringify(derefed)}. This tag can only be assigned to union types.`);
throw new Error(`Cannot assign discriminator tag to type: ${derefed.getName()}. This tag can only be assigned to union types.`);
}

@@ -61,0 +61,0 @@ }

import { Definition } from "../Schema/Definition.js";
import { RawTypeName } from "../Schema/RawType.js";
import { SubTypeFormatter } from "../SubTypeFormatter.js";
import { BaseType } from "../Type/BaseType.js";
import { LiteralType } from "../Type/LiteralType.js";
import { NullType } from "../Type/NullType.js";
import { UnionType } from "../Type/UnionType.js";

@@ -12,5 +9,2 @@ export declare class LiteralUnionTypeFormatter implements SubTypeFormatter {

getChildren(type: UnionType): BaseType[];
protected isLiteralUnion(type: UnionType): boolean;
protected getLiteralValue(value: LiteralType | NullType): string | number | boolean | null;
protected getLiteralType(value: LiteralType | NullType): RawTypeName;
}
import { LiteralType } from "../Type/LiteralType.js";
import { NullType } from "../Type/NullType.js";
import { StringType } from "../Type/StringType.js";
import { UnionType } from "../Type/UnionType.js";
import { derefAliasedType, isHiddenType } from "../Utils/derefType.js";
import { typeName } from "../Utils/typeName.js";

@@ -8,19 +10,47 @@ import { uniqueArray } from "../Utils/uniqueArray.js";

supportsType(type) {
return type instanceof UnionType && type.getTypes().length > 0 && this.isLiteralUnion(type);
return type instanceof UnionType && type.getTypes().length > 0 && isLiteralUnion(type);
}
getDefinition(type) {
const values = uniqueArray(type.getTypes().map((item) => this.getLiteralValue(item)));
const types = uniqueArray(type.getTypes().map((item) => this.getLiteralType(item)));
if (types.length === 1) {
let hasString = false;
let preserveLiterals = false;
let allStrings = true;
let hasNull = false;
const flattenedTypes = flattenTypes(type);
const types = flattenedTypes.filter((t) => {
if (t instanceof StringType) {
hasString = true;
preserveLiterals = preserveLiterals || t.getPreserveLiterals();
return false;
}
else if (t instanceof NullType) {
hasNull = true;
return true;
}
else if (t instanceof LiteralType && !t.isString()) {
allStrings = false;
}
return true;
});
if (allStrings && hasString && !preserveLiterals) {
return {
type: types[0],
enum: values,
type: hasNull ? ["string", "null"] : "string",
};
}
else {
const values = uniqueArray(types.map(getLiteralValue));
const typeNames = uniqueArray(types.map(getLiteralType));
const ret = {
type: typeNames.length === 1 ? typeNames[0] : typeNames,
enum: values,
};
if (preserveLiterals) {
return {
type: types,
enum: values,
anyOf: [
{
type: "string",
},
ret,
],
};
}
return ret;
}

@@ -30,12 +60,24 @@ getChildren(type) {

}
isLiteralUnion(type) {
return type.getTypes().every((item) => item instanceof LiteralType || item instanceof NullType);
}
getLiteralValue(value) {
return value instanceof LiteralType ? value.getValue() : null;
}
getLiteralType(value) {
return value instanceof LiteralType ? typeName(value.getValue()) : "null";
}
}
function flattenTypes(type) {
return type
.getTypes()
.filter((t) => !isHiddenType(t))
.map(derefAliasedType)
.flatMap((t) => {
if (t instanceof UnionType) {
return flattenTypes(t);
}
return t;
});
}
function isLiteralUnion(type) {
return flattenTypes(type).every((item) => item instanceof LiteralType || item instanceof NullType || item instanceof StringType);
}
function getLiteralValue(value) {
return value instanceof LiteralType ? value.getValue() : null;
}
function getLiteralType(value) {
return value instanceof LiteralType ? typeName(value.getValue()) : "null";
}
//# sourceMappingURL=LiteralUnionTypeFormatter.js.map

@@ -34,3 +34,3 @@ import { LiteralType } from "../Type/LiteralType.js";

if (undefinedIndex != -1) {
throw new Error(`Cannot find discriminator keyword "${discriminator}" in type ${JSON.stringify(type.getTypes()[undefinedIndex])}.`);
throw new Error(`Cannot find discriminator keyword "${discriminator}" in type ${type.getTypes()[undefinedIndex].getName()}.`);
}

@@ -81,33 +81,2 @@ const kindDefinitions = kindTypes.map((item) => this.childTypeFormatter.getDefinition(item));

const definitions = this.getTypeDefinitions(type);
let stringType = true;
let oneNotEnum = false;
for (const def of definitions) {
if (def.type !== "string") {
stringType = false;
break;
}
if (def.enum === undefined) {
oneNotEnum = true;
}
}
if (stringType && oneNotEnum) {
const values = [];
for (const def of definitions) {
if (def.enum) {
values.push(...def.enum);
}
else if (def.const) {
values.push(def.const);
}
else {
return {
type: "string",
};
}
}
return {
type: "string",
enum: values,
};
}
const flattenedDefinitions = [];

@@ -114,0 +83,0 @@ for (const def of definitions) {

import { BaseType } from "../Type/BaseType.js";
export declare function derefType(type: BaseType): BaseType;
export declare function derefAnnotatedType(type: BaseType): BaseType;
export declare function isHiddenType(type: BaseType): boolean;
export declare function derefAliasedType(type: BaseType): BaseType;
import { AliasType } from "../Type/AliasType.js";
import { AnnotatedType } from "../Type/AnnotatedType.js";
import { DefinitionType } from "../Type/DefinitionType.js";
import { HiddenType } from "../Type/HiddenType.js";
import { NeverType } from "../Type/NeverType.js";
import { ReferenceType } from "../Type/ReferenceType.js";

@@ -20,2 +22,17 @@ export function derefType(type) {

}
export function isHiddenType(type) {
if (type instanceof HiddenType || type instanceof NeverType) {
return true;
}
else if (type instanceof DefinitionType || type instanceof AliasType || type instanceof AnnotatedType) {
return isHiddenType(type.getType());
}
return false;
}
export function derefAliasedType(type) {
if (type instanceof AliasType) {
return derefAliasedType(type.getType());
}
return type;
}
//# sourceMappingURL=derefType.js.map

@@ -11,3 +11,3 @@ import { UndefinedType } from "../Type/UndefinedType.js";

if (newType instanceof UndefinedType) {
numRemoved += 1;
numRemoved++;
}

@@ -14,0 +14,0 @@ else if (newType instanceof UnionType) {

import { BaseType } from "../Type/BaseType.js";
import { LiteralType } from "../Type/LiteralType.js";
import { NumberType } from "../Type/NumberType.js";
import { StringType } from "../Type/StringType.js";
export declare function getTypeKeys(type: BaseType): LiteralType[];
export declare function getTypeByKey(type: BaseType, index: LiteralType | StringType): BaseType | undefined;
export declare function getTypeByKey(type: BaseType, index: LiteralType | StringType | NumberType): BaseType | undefined;
export function uniqueArray(array) {
return array.reduce((result, item) => {
if (result.indexOf(item) < 0) {
if (!result.includes(item)) {
result.push(item);

@@ -5,0 +5,0 @@ }

@@ -37,3 +37,3 @@ import { ChainTypeFormatter } from "../src/ChainTypeFormatter.js";

formatter: MutableTypeFormatter,
circularReferenceTypeFormatter: CircularReferenceTypeFormatter
circularReferenceTypeFormatter: CircularReferenceTypeFormatter,
) => void;

@@ -40,0 +40,0 @@

@@ -79,3 +79,3 @@ import ts from "typescript";

nodeParser,
new ExtendedAnnotationsReader(typeChecker, extraTags, config.markdownDescription)
new ExtendedAnnotationsReader(typeChecker, extraTags, config.markdownDescription),
);

@@ -153,7 +153,7 @@ } else if (config.jsDoc === "basic") {

withJsDoc(chainNodeParser),
config.additionalProperties
)
)
)
)
config.additionalProperties,
),
),
),
),
)

@@ -164,6 +164,6 @@ .addNodeParser(

withJsDoc(
new TypeLiteralNodeParser(typeChecker, withJsDoc(chainNodeParser), config.additionalProperties)
)
)
)
new TypeLiteralNodeParser(typeChecker, withJsDoc(chainNodeParser), config.additionalProperties),
),
),
),
)

@@ -170,0 +170,0 @@

@@ -28,3 +28,3 @@ import * as glob from "glob";

{},
configFile
configFile,
);

@@ -31,0 +31,0 @@ parseResult.options.noEmit = true;

{
"name": "ts-json-schema-generator",
"version": "2.1.0-next.0",
"version": "2.1.0-next.1",
"description": "Generate JSON schema from your Typescript sources",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

@@ -11,3 +11,3 @@ import json5 from "json5";

extraTags?: Set<string>,
private markdownDescription?: boolean
private markdownDescription?: boolean,
) {

@@ -14,0 +14,0 @@ super(extraTags);

@@ -14,3 +14,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected nodeParsers: SubNodeParser[]
protected nodeParsers: SubNodeParser[],
) {}

@@ -17,0 +17,0 @@

@@ -7,3 +7,3 @@ import ts from "typescript";

super(
diagnostics.map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")).join("\n\n")
diagnostics.map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")).join("\n\n"),
);

@@ -10,0 +10,0 @@ }

@@ -7,3 +7,3 @@ import ts from "typescript";

private node: ts.Node,
private reference?: ts.Node
private reference?: ts.Node,
) {

@@ -13,3 +13,3 @@ super(

ts.SyntaxKind[node.kind]
}"`
}"`,
);

@@ -16,0 +16,0 @@ }

@@ -15,3 +15,3 @@ import ts from "typescript";

protected expose: "all" | "none" | "export",
protected jsDoc: "none" | "extended" | "basic"
protected jsDoc: "none" | "extended" | "basic",
) {}

@@ -18,0 +18,0 @@

@@ -17,3 +17,3 @@ import ts from "typescript";

protected childNodeParser: SubNodeParser,
protected annotationsReader: AnnotationsReader
protected annotationsReader: AnnotationsReader,
) {}

@@ -20,0 +20,0 @@

@@ -13,3 +13,3 @@ import { TupleType } from "../Type/TupleType.js";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -16,0 +16,0 @@

@@ -13,3 +13,3 @@ import ts from "typescript";

public parameterName: string,
public type: BaseType
public type: BaseType,
) {}

@@ -21,3 +21,3 @@ }

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -41,3 +41,3 @@

result ? node.trueType : node.falseType,
this.createSubContext(node, context, undefined, result ? inferMap : new Map())
this.createSubContext(node, context, undefined, result ? inferMap : new Map()),
);

@@ -55,3 +55,3 @@ }

node.trueType,
this.createSubContext(node, context, new CheckType(checkTypeParameterName, trueCheckType), inferMap)
this.createSubContext(node, context, new CheckType(checkTypeParameterName, trueCheckType), inferMap),
);

@@ -65,3 +65,3 @@ if (result) {

node.falseType,
this.createSubContext(node, context, new CheckType(checkTypeParameterName, falseCheckType))
this.createSubContext(node, context, new CheckType(checkTypeParameterName, falseCheckType)),
);

@@ -105,3 +105,3 @@ if (result) {

checkType?: CheckType,
inferMap: Map<string, BaseType> = new Map()
inferMap: Map<string, BaseType> = new Map(),
): Context {

@@ -108,0 +108,0 @@ const subContext = new Context(node);

@@ -14,3 +14,3 @@ import ts from "typescript";

protected childNodeParser: NodeParser,
protected functions: FunctionOptions
protected functions: FunctionOptions,
) {}

@@ -17,0 +17,0 @@

@@ -22,3 +22,3 @@ import ts from "typescript";

.filter((member: ts.EnumMember) => !isNodeHidden(member))
.map((member, index) => this.getMemberValue(member, index))
.map((member, index) => this.getMemberValue(member, index)),
);

@@ -25,0 +25,0 @@ }

@@ -9,3 +9,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -22,3 +22,3 @@

aliasedSymbol.declarations![0],
this.createSubContext(node, context)
this.createSubContext(node, context),
);

@@ -25,0 +25,0 @@ } else if (typeSymbol.flags & ts.SymbolFlags.TypeParameter) {

@@ -15,3 +15,3 @@ import ts from "typescript";

protected childNodeParser: NodeParser,
protected functions: FunctionOptions
protected functions: FunctionOptions,
) {}

@@ -30,3 +30,3 @@

node: ts.FunctionTypeNode | ts.FunctionExpression | ts.FunctionDeclaration | ts.ArrowFunction,
context: Context
context: Context,
): BaseType {

@@ -52,3 +52,3 @@ if (this.functions === "hide") {

| ts.ConstructorTypeNode,
context: Context
context: Context,
) {

@@ -72,3 +72,3 @@ if (node.parameters.length === 0) {

}),
false
false,
);

@@ -83,3 +83,3 @@ }

| ts.ArrowFunction
| ts.ConstructorTypeNode
| ts.ConstructorTypeNode,
): string | undefined {

@@ -86,0 +86,0 @@ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionTypeNode(node)) {

@@ -19,3 +19,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -40,3 +40,3 @@

ts.isIdentifier(m.name) &&
m.name.text === indexType.getValue()
m.name.text === indexType.getValue(),
);

@@ -67,3 +67,3 @@

throw new LogicError(
`Unexpected type "${type.getId()}" (expected "LiteralType.js" or "StringType.js" or "NumberType.js")`
`Unexpected type "${type.getId()}" (expected "LiteralType.js" or "StringType.js" or "NumberType.js")`,
);

@@ -70,0 +70,0 @@ }

@@ -10,3 +10,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -13,0 +13,0 @@

@@ -17,3 +17,3 @@ import ts, { PropertyName } from "typescript";

protected childNodeParser: NodeParser,
protected readonly additionalProperties: boolean
protected readonly additionalProperties: boolean,
) {}

@@ -28,3 +28,3 @@

context: Context,
reference?: ReferenceType
reference?: ReferenceType,
): BaseType {

@@ -102,3 +102,3 @@ if (node.typeParameters?.length) {

],
[]
[],
);

@@ -109,3 +109,3 @@ }

node: ts.InterfaceDeclaration | ts.ClassDeclaration,
context: Context
context: Context,
): ObjectProperty[] | undefined {

@@ -119,3 +119,3 @@ let hasRequiredNever = false;

const params = member.parameters.filter((param) =>
ts.isParameterPropertyDeclaration(param, param.parent)
ts.isParameterPropertyDeclaration(param, param.parent),
) as ts.ParameterPropertyDeclaration[];

@@ -128,3 +128,3 @@ members.push(...params);

},
[] as (ts.PropertyDeclaration | ts.PropertySignature | ts.ParameterPropertyDeclaration)[]
[] as (ts.PropertyDeclaration | ts.PropertySignature | ts.ParameterPropertyDeclaration)[],
)

@@ -152,4 +152,4 @@ .filter((member) => isPublic(member) && !isStatic(member) && !isNodeHidden(member))

this.childNodeParser.createType(memberType, context),
!member.questionToken
)
!member.questionToken,
),
)

@@ -173,3 +173,3 @@ .filter((prop) => {

node: ts.InterfaceDeclaration | ts.ClassDeclaration,
context: Context
context: Context,
): BaseType | boolean {

@@ -176,0 +176,0 @@ const indexSignature = (node.members as ts.NodeArray<ts.NamedDeclaration>).find(ts.isIndexSignatureDeclaration);

@@ -12,2 +12,4 @@ import ts from "typescript";

import { NeverType } from "../Type/NeverType.js";
import { ObjectType } from "../Type/ObjectType.js";
import { StringType } from "../Type/StringType.js";

@@ -17,3 +19,3 @@ export class IntersectionNodeParser implements SubNodeParser {

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -33,2 +35,7 @@

// handle autocomplete hacks like `string & {}`
if (types.length === 2 && types.some((t) => t instanceof StringType) && types.some((t) => isEmptyObject(t))) {
return new StringType(true);
}
return translate(types);

@@ -38,2 +45,7 @@ }

function isEmptyObject(x: BaseType) {
const t = derefType(x);
return t instanceof ObjectType && !t.getAdditionalProperties() && !t.getProperties().length;
}
function derefAndFlattenUnions(type: BaseType): BaseType[] {

@@ -40,0 +52,0 @@ const derefed = derefType(type);

@@ -25,3 +25,3 @@ import ts from "typescript";

protected childNodeParser: NodeParser,
protected readonly additionalProperties: boolean
protected readonly additionalProperties: boolean,
) {}

@@ -44,3 +44,3 @@

this.getProperties(node, keyListType, context),
this.getAdditionalProperties(node, keyListType, context)
this.getAdditionalProperties(node, keyListType, context),
);

@@ -58,3 +58,3 @@ } else if (keyListType instanceof LiteralType) {

node.type!,
this.createSubContext(node, keyListType, context)
this.createSubContext(node, keyListType, context),
);

@@ -91,3 +91,3 @@ return type instanceof NeverType ? new NeverType() : new ArrayType(type);

constraintType ? constraintType.getId() : constraintType
}" for type "${node.getText()}" (expected "UnionType" or "StringType")`
}" for type "${node.getText()}" (expected "UnionType" or "StringType")`,
);

@@ -102,3 +102,3 @@ }

const key = derefType(
this.childNodeParser.createType(node.nameType, this.createSubContext(node, rawKey, context))
this.childNodeParser.createType(node.nameType, this.createSubContext(node, rawKey, context)),
);

@@ -118,3 +118,3 @@

node.type!,
this.createSubContext(node, key, context)
this.createSubContext(node, key, context),
);

@@ -133,3 +133,3 @@

preserveAnnotation(propertyType, newType),
!node.questionToken && !hasUndefined
!node.questionToken && !hasUndefined,
);

@@ -149,3 +149,3 @@

node.type!,
this.createSubContext(node, new LiteralType(value!), context)
this.createSubContext(node, new LiteralType(value!), context),
);

@@ -160,3 +160,3 @@

keyListType: UnionType,
context: Context
context: Context,
): BaseType | boolean {

@@ -176,4 +176,4 @@ const key = keyListType.getTypes().filter((type) => !(type instanceof LiteralType))[0];

node: ts.MappedTypeNode,
key: LiteralType | StringType,
parentContext: Context
key: LiteralType | StringType | NumberType,
parentContext: Context,
): Context {

@@ -180,0 +180,0 @@ const subContext = new Context(node);

@@ -22,4 +22,4 @@ import { NodeParser } from "../NodeParser.js";

this.childNodeParser.createType((t as any).initializer, context),
!(t as any).questionToken
)
!(t as any).questionToken,
),
);

@@ -26,0 +26,0 @@

@@ -31,3 +31,3 @@ import ts from "typescript";

throw new Error(
`Expected operand to be "LiteralType" but is "${operand ? operand.constructor.name : operand}"`
`Expected operand to be "LiteralType" but is "${operand ? operand.constructor.name : operand}"`,
);

@@ -34,0 +34,0 @@ }

@@ -9,3 +9,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -12,0 +12,0 @@

@@ -31,3 +31,3 @@ import ts from "typescript";

return extractLiterals(type).map((value) => value + suffix);
})
}),
);

@@ -34,0 +34,0 @@

@@ -10,3 +10,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -22,5 +22,5 @@

return this.childNodeParser.createType(item, context);
})
}),
);
}
}

@@ -13,3 +13,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -16,0 +16,0 @@

@@ -15,3 +15,3 @@ import ts, { MethodSignature, PropertySignature } from "typescript";

protected childNodeParser: NodeParser,
protected readonly additionalProperties: boolean
protected readonly additionalProperties: boolean,
) {}

@@ -44,3 +44,3 @@

(element): element is PropertySignature | MethodSignature =>
ts.isPropertySignature(element) || ts.isMethodSignature(element)
ts.isPropertySignature(element) || ts.isMethodSignature(element),
)

@@ -53,4 +53,4 @@ .filter((propertyNode) => !isNodeHidden(propertyNode))

this.childNodeParser.createType(propertyNode.type!, context),
!propertyNode.questionToken
)
!propertyNode.questionToken,
),
)

@@ -57,0 +57,0 @@ .filter((prop) => {

@@ -16,3 +16,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -19,0 +19,0 @@

@@ -19,3 +19,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -77,3 +77,3 @@

typeSymbol.declarations!.filter((n: ts.Declaration) => !invalidTypes[n.kind])[0],
this.createSubContext(node, context)
this.createSubContext(node, context),
);

@@ -80,0 +80,0 @@ }

@@ -12,3 +12,3 @@ import ts from "typescript";

protected typeChecker: ts.TypeChecker,
protected childNodeParser: NodeParser
protected childNodeParser: NodeParser,
) {}

@@ -15,0 +15,0 @@

@@ -20,3 +20,3 @@ import ts from "typescript";

protected readonly typeFormatter: TypeFormatter,
protected readonly config?: Config
protected readonly config?: Config,
) {}

@@ -136,3 +136,3 @@

typeChecker: ts.TypeChecker,
types: Map<string, ts.Node>
types: Map<string, ts.Node>,
): void {

@@ -139,0 +139,0 @@ for (const sourceFile of sourceFiles) {

@@ -10,3 +10,3 @@ import ts from "typescript";

protected fullName: string | undefined,
protected topRef: boolean
protected topRef: boolean,
) {}

@@ -13,0 +13,0 @@

@@ -6,3 +6,3 @@ import { BaseType } from "./BaseType.js";

private id: string,
private type: BaseType
private type: BaseType,
) {

@@ -9,0 +9,0 @@ super();

@@ -12,3 +12,3 @@ import { BaseType } from "./BaseType.js";

private annotations: Annotations,
private nullable: boolean
private nullable: boolean,
) {

@@ -15,0 +15,0 @@ super();

@@ -10,3 +10,3 @@ import ts from "typescript";

node?: ts.ConstructorTypeNode,
protected namedArguments?: ObjectType
protected namedArguments?: ObjectType,
) {

@@ -13,0 +13,0 @@ super();

@@ -6,3 +6,3 @@ import { BaseType } from "./BaseType.js";

private name: string | undefined,
private type: BaseType
private type: BaseType,
) {

@@ -9,0 +9,0 @@ super();

@@ -12,3 +12,3 @@ import { BaseType } from "./BaseType.js";

private id: string,
private values: readonly EnumValue[]
private values: readonly EnumValue[],
) {

@@ -15,0 +15,0 @@ super();

@@ -10,3 +10,3 @@ import ts from "typescript";

node?: ts.FunctionTypeNode | ts.FunctionExpression | ts.FunctionDeclaration | ts.ArrowFunction,
protected namedArguments?: ObjectType
protected namedArguments?: ObjectType,
) {

@@ -13,0 +13,0 @@ super();

@@ -17,2 +17,6 @@ import { BaseType } from "./BaseType.js";

}
public isString(): boolean {
return typeof this.value === "string";
}
}

@@ -8,3 +8,3 @@ import { BaseType } from "./BaseType.js";

private type: BaseType,
private required: boolean
private required: boolean,
) {}

@@ -30,3 +30,3 @@

// whether the object is `object`
private nonPrimitive: boolean = false
private nonPrimitive: boolean = false,
) {

@@ -33,0 +33,0 @@ super();

@@ -9,3 +9,3 @@ import { ArrayType } from "./ArrayType.js";

private item: ArrayType | InferType | TupleType,
private title: string | null = null
private title: string | null = null,
) {

@@ -12,0 +12,0 @@ super();

import { PrimitiveType } from "./PrimitiveType.js";
export class StringType extends PrimitiveType {
constructor(protected preserveLiterals = false) {
super();
}
public getId(): string {
return "string";
}
public getPreserveLiterals(): boolean {
return this.preserveLiterals;
}
}

@@ -20,3 +20,3 @@ import { BaseType } from "./BaseType.js";

return flatTypes;
}, [] as BaseType[])
}, [] as BaseType[]),
);

@@ -23,0 +23,0 @@ }

@@ -64,5 +64,3 @@ import { Definition } from "../Schema/Definition.js";

throw new Error(
`Cannot assign discriminator tag to type: ${JSON.stringify(
derefed
)}. This tag can only be assigned to union types.`
`Cannot assign discriminator tag to type: ${derefed.getName()}. This tag can only be assigned to union types.`,
);

@@ -69,0 +67,0 @@ }

@@ -11,3 +11,3 @@ import { Definition } from "../Schema/Definition.js";

protected childTypeFormatter: TypeFormatter,
protected encodeRefs: boolean
protected encodeRefs: boolean,
) {}

@@ -14,0 +14,0 @@

@@ -11,3 +11,3 @@ import { FunctionOptions } from "../Config.js";

protected childTypeFormatter: TypeFormatter,
protected functions: FunctionOptions
protected functions: FunctionOptions,
) {}

@@ -14,0 +14,0 @@

@@ -38,3 +38,3 @@ import { Definition } from "../Schema/Definition.js";

additionalProperties: false,
})
}),
);

@@ -50,5 +50,5 @@ }

.getTypes()
.reduce((result: BaseType[], item) => [...result, ...this.childTypeFormatter.getChildren(item)], [])
.reduce((result: BaseType[], item) => [...result, ...this.childTypeFormatter.getChildren(item)], []),
);
}
}

@@ -5,5 +5,7 @@ import { Definition } from "../Schema/Definition.js";

import { BaseType } from "../Type/BaseType.js";
import { LiteralType } from "../Type/LiteralType.js";
import { LiteralType, LiteralValue } from "../Type/LiteralType.js";
import { NullType } from "../Type/NullType.js";
import { StringType } from "../Type/StringType.js";
import { UnionType } from "../Type/UnionType.js";
import { derefAliasedType, isHiddenType } from "../Utils/derefType.js";
import { typeName } from "../Utils/typeName.js";

@@ -14,19 +16,54 @@ import { uniqueArray } from "../Utils/uniqueArray.js";

public supportsType(type: BaseType): boolean {
return type instanceof UnionType && type.getTypes().length > 0 && this.isLiteralUnion(type);
return type instanceof UnionType && type.getTypes().length > 0 && isLiteralUnion(type);
}
public getDefinition(type: UnionType): Definition {
const values = uniqueArray(type.getTypes().map((item: LiteralType | NullType) => this.getLiteralValue(item)));
const types = uniqueArray(type.getTypes().map((item: LiteralType | NullType) => this.getLiteralType(item)));
let hasString = false;
let preserveLiterals = false;
let allStrings = true;
let hasNull = false;
if (types.length === 1) {
const flattenedTypes = flattenTypes(type);
// filter out String types since we need to be more careful about them
const types = flattenedTypes.filter((t) => {
if (t instanceof StringType) {
hasString = true;
preserveLiterals = preserveLiterals || t.getPreserveLiterals();
return false;
} else if (t instanceof NullType) {
hasNull = true;
return true;
} else if (t instanceof LiteralType && !t.isString()) {
allStrings = false;
}
return true;
});
if (allStrings && hasString && !preserveLiterals) {
return {
type: types[0],
enum: values,
type: hasNull ? ["string", "null"] : "string",
};
} else {
}
const values = uniqueArray(types.map(getLiteralValue));
const typeNames = uniqueArray(types.map(getLiteralType));
const ret = {
type: typeNames.length === 1 ? typeNames[0] : typeNames,
enum: values,
};
if (preserveLiterals) {
return {
type: types,
enum: values,
anyOf: [
{
type: "string",
},
ret,
],
};
}
return ret;
}

@@ -36,12 +73,29 @@ public getChildren(type: UnionType): BaseType[] {

}
}
protected isLiteralUnion(type: UnionType): boolean {
return type.getTypes().every((item) => item instanceof LiteralType || item instanceof NullType);
}
protected getLiteralValue(value: LiteralType | NullType): string | number | boolean | null {
return value instanceof LiteralType ? value.getValue() : null;
}
protected getLiteralType(value: LiteralType | NullType): RawTypeName {
return value instanceof LiteralType ? typeName(value.getValue()) : "null";
}
function flattenTypes(type: UnionType): (StringType | LiteralType | NullType)[] {
return type
.getTypes()
.filter((t) => !isHiddenType(t))
.map(derefAliasedType)
.flatMap((t) => {
if (t instanceof UnionType) {
return flattenTypes(t);
}
return t as StringType | LiteralType | NullType;
});
}
function isLiteralUnion(type: UnionType): boolean {
return flattenTypes(type).every(
(item) => item instanceof LiteralType || item instanceof NullType || item instanceof StringType,
);
}
function getLiteralValue(value: LiteralType | NullType): LiteralValue | null {
return value instanceof LiteralType ? value.getValue() : null;
}
function getLiteralType(value: LiteralType | NullType): RawTypeName {
return value instanceof LiteralType ? typeName(value.getValue()) : "null";
}

@@ -42,3 +42,3 @@ import { Definition } from "../Schema/Definition.js";

(result: BaseType[], baseType) => [...result, ...this.childTypeFormatter.getChildren(baseType)],
[]
[],
);

@@ -69,3 +69,3 @@

objectProperties = objectProperties.filter(
(property) => !(derefType(property.getType()) instanceof NeverType)
(property) => !(derefType(property.getType()) instanceof NeverType),
);

@@ -72,0 +72,0 @@ }

@@ -11,3 +11,3 @@ import { Definition } from "../Schema/Definition.js";

protected childTypeFormatter: TypeFormatter,
protected encodeRefs: boolean
protected encodeRefs: boolean,
) {}

@@ -14,0 +14,0 @@

@@ -87,5 +87,5 @@ import { Definition } from "../Schema/Definition.js";

.filter(notNever)
.reduce((result: BaseType[], item) => [...result, ...this.childTypeFormatter.getChildren(item)], [])
.reduce((result: BaseType[], item) => [...result, ...this.childTypeFormatter.getChildren(item)], []),
);
}
}

@@ -18,3 +18,3 @@ import { JSONSchema7 } from "json-schema";

protected childTypeFormatter: TypeFormatter,
private discriminatorType?: DiscriminatorType
private discriminatorType?: DiscriminatorType,
) {}

@@ -44,5 +44,3 @@

throw new Error(
`Cannot find discriminator keyword "${discriminator}" in type ${JSON.stringify(
type.getTypes()[undefinedIndex]
)}.`
`Cannot find discriminator keyword "${discriminator}" in type ${type.getTypes()[undefinedIndex].getName()}.`,
);

@@ -71,3 +69,3 @@ }

throw new Error(
`Duplicate discriminator values: ${duplicates.join(", ")} in type ${JSON.stringify(type.getName())}.`
`Duplicate discriminator values: ${duplicates.join(", ")} in type ${JSON.stringify(type.getName())}.`,
);

@@ -104,34 +102,2 @@ }

// TODO: why is this not covered by LiteralUnionTypeFormatter?
// special case for string literals | string -> string
let stringType = true;
let oneNotEnum = false;
for (const def of definitions) {
if (def.type !== "string") {
stringType = false;
break;
}
if (def.enum === undefined) {
oneNotEnum = true;
}
}
if (stringType && oneNotEnum) {
const values = [];
for (const def of definitions) {
if (def.enum) {
values.push(...def.enum);
} else if (def.const) {
values.push(def.const);
} else {
return {
type: "string",
};
}
}
return {
type: "string",
enum: values,
};
}
const flattenedDefinitions: JSONSchema7[] = [];

@@ -160,5 +126,5 @@

.getTypes()
.reduce((result: BaseType[], item) => [...result, ...this.childTypeFormatter.getChildren(item)], [])
.reduce((result: BaseType[], item) => [...result, ...this.childTypeFormatter.getChildren(item)], []),
);
}
}

@@ -36,3 +36,3 @@ import { Definition } from "../Schema/Definition.js";

additionalTypes = additionalTypes.concat(
Array.isArray(prop.type) ? prop.type : [prop.type]
Array.isArray(prop.type) ? prop.type : [prop.type],
);

@@ -45,3 +45,3 @@ } else {

additionalTypes = additionalTypes.concat(
Array.isArray(addProps.type) ? addProps.type : [addProps.type]
Array.isArray(addProps.type) ? addProps.type : [addProps.type],
);

@@ -48,0 +48,0 @@ } else {

@@ -16,3 +16,3 @@ import { JSONSchema7Definition } from "json-schema";

a: { [key: string]: JSONSchema7Definition },
b: { [key: string]: JSONSchema7Definition }
b: { [key: string]: JSONSchema7Definition },
): { [x: string]: JSONSchema7Definition } {

@@ -19,0 +19,0 @@ const output = { ...structuredClone(a), ...structuredClone(b) };

@@ -5,2 +5,4 @@ import { AliasType } from "../Type/AliasType.js";

import { DefinitionType } from "../Type/DefinitionType.js";
import { HiddenType } from "../Type/HiddenType.js";
import { NeverType } from "../Type/NeverType.js";
import { ReferenceType } from "../Type/ReferenceType.js";

@@ -29,1 +31,19 @@

}
export function isHiddenType(type: BaseType): boolean {
if (type instanceof HiddenType || type instanceof NeverType) {
return true;
} else if (type instanceof DefinitionType || type instanceof AliasType || type instanceof AnnotatedType) {
return isHiddenType(type.getType());
}
return false;
}
export function derefAliasedType(type: BaseType): BaseType {
if (type instanceof AliasType) {
return derefAliasedType(type.getType());
}
return type;
}

@@ -94,3 +94,3 @@ import { AnyType } from "../Type/AnyType.js";

inferMap: Map<string, BaseType> = new Map(),
insideTypes: Set<BaseType> = new Set()
insideTypes: Set<BaseType> = new Set(),
): boolean {

@@ -207,3 +207,3 @@ // Dereference source and target

const inCommon = targetMembers.some((targetMember) =>
sourceMembers.some((sourceMember) => targetMember.getName() === sourceMember.getName())
sourceMembers.some((sourceMember) => targetMember.getName() === sourceMember.getName()),
);

@@ -226,3 +226,3 @@

inferMap,
new Set(insideTypes).add(source).add(target)
new Set(insideTypes).add(source).add(target),
);

@@ -277,3 +277,3 @@ })

inferMap,
insideTypes
insideTypes,
);

@@ -280,0 +280,0 @@ }

@@ -23,3 +23,3 @@ import { BaseType } from "../Type/BaseType.js";

// eslint-disable-next-line no-shadow
predicate: (type: BaseType) => boolean
predicate: (type: BaseType) => boolean,
): BaseType {

@@ -26,0 +26,0 @@ const derefed = derefType(type);

@@ -17,3 +17,3 @@ import { BaseType } from "../Type/BaseType.js";

if (newType instanceof UndefinedType) {
numRemoved += 1;
numRemoved++;
} else if (newType instanceof UnionType) {

@@ -20,0 +20,0 @@ const result = removeUndefined(newType);

@@ -10,3 +10,3 @@ import { JSONSchema7Definition } from "json-schema";

definitions: StringMap<Definition>,
reachable: Set<string>
reachable: Set<string>,
) {

@@ -69,3 +69,3 @@ if (typeof definition === "boolean") {

rootTypeDefinition: Definition | undefined,
definitions: StringMap<Definition>
definitions: StringMap<Definition>,
): StringMap<Definition> {

@@ -72,0 +72,0 @@ if (!rootTypeDefinition) {

@@ -28,3 +28,3 @@ import { translate } from "../NodeParser/IntersectionNodeParser.js";

return uniqueLiterals(
type.getTypes().reduce((result: LiteralType[], subType) => [...result, ...getTypeKeys(subType)], [])
type.getTypes().reduce((result: LiteralType[], subType) => [...result, ...getTypeKeys(subType)], []),
);

@@ -43,4 +43,4 @@ }

(result: LiteralType[], parentType) => [...result, ...getTypeKeys(parentType)],
objectProperties
)
objectProperties,
),
);

@@ -52,3 +52,3 @@ }

export function getTypeByKey(type: BaseType, index: LiteralType | StringType): BaseType | undefined {
export function getTypeByKey(type: BaseType, index: LiteralType | StringType | NumberType): BaseType | undefined {
type = derefType(type);

@@ -55,0 +55,0 @@

export function uniqueArray<T>(array: readonly T[]): T[] {
return array.reduce((result: T[], item: T) => {
if (result.indexOf(item) < 0) {
if (!result.includes(item)) {
result.push(item);

@@ -5,0 +5,0 @@ }

@@ -17,3 +17,3 @@ import { Command, Option } from "commander";

.addOption(
new Option("-e, --expose <expose>", "Type exposing").choices(["all", "none", "export"]).default("export")
new Option("-e, --expose <expose>", "Type exposing").choices(["all", "none", "export"]).default("export"),
)

@@ -23,3 +23,3 @@ .addOption(

.choices(["none", "basic", "extended"])
.default("extended")
.default("extended"),
)

@@ -29,3 +29,3 @@ .addOption(

jsDoc: "extended",
})
}),
)

@@ -36,6 +36,6 @@ .addOption(

"How to handle functions. `fail` will throw an error. `comment` will add a comment. `hide` will treat the function like a NeverType or HiddenType."
"How to handle functions. `fail` will throw an error. `comment` will add a comment. `hide` will treat the function like a NeverType or HiddenType.",
)
.choices(["fail", "comment", "hide"])
.default("comment")
.default("comment"),
)

@@ -53,3 +53,3 @@ .option("--minify", "Minify generated schema", false)

(value: string, list: string[]) => list.concat(value),
[]
[],
)

@@ -56,0 +56,0 @@ .option("--additional-properties", "Allow additional properties for objects with no index signature", false)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc