Skip to content
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
5 changes: 4 additions & 1 deletion src/CircularReferenceTypeFormatter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Definition } from "./Schema/Definition.js";
import type { SubTypeFormatter } from "./SubTypeFormatter.js";
import type { BaseType } from "./Type/BaseType.js";
import { copySchemaSource } from "./Utils/schemaSource.js";
import { uniqueArray } from "./Utils/uniqueArray.js";

export class CircularReferenceTypeFormatter implements SubTypeFormatter {
Expand All @@ -19,7 +20,9 @@ export class CircularReferenceTypeFormatter implements SubTypeFormatter {

const definition: Definition = {};
this.definition.set(type, definition);
Object.assign(definition, this.childTypeFormatter.getDefinition(type));
const childDefinition = this.childTypeFormatter.getDefinition(type);
Object.assign(definition, childDefinition);
copySchemaSource(childDefinition, definition);
return definition;
}
public getChildren(type: BaseType): BaseType[] {
Expand Down
34 changes: 18 additions & 16 deletions src/NodeParser/InterfaceAndClassNodeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { BaseType } from "../Type/BaseType.js";
import { NeverType } from "../Type/NeverType.js";
import { ObjectProperty, ObjectType } from "../Type/ObjectType.js";
import type { ReferenceType } from "../Type/ReferenceType.js";
import { resolveIndexSignatures } from "../Utils/indexSignature.js";
import { isNodeHidden } from "../Utils/isHidden.js";
import { isPublic, isStatic } from "../Utils/modifiers.js";
import { getKey } from "../Utils/nodeKey.js";
Expand Down Expand Up @@ -51,17 +52,30 @@ export class InterfaceAndClassNodeParser implements SubNodeParser {
return new NeverType();
}

const additionalProperties = this.getAdditionalProperties(node, context);
const { additionalProperties, patternProperties } = resolveIndexSignatures(
node.members,
this.typeChecker,
(typeNode) => this.childNodeParser.createType(typeNode, context),
this.additionalProperties,
);

// When type only extends Array or ReadonlyArray then create an array type instead of an object type
if (properties.length === 0 && additionalProperties === false) {
// When type only extends Array or ReadonlyArray then create an array type instead of an object type.
// A numeric index is not an additionalProperties constraint, so it must not be treated as "no index".
if (properties.length === 0 && additionalProperties === false && !patternProperties) {
const arrayItemType = this.getArrayItemType(node);
if (arrayItemType) {
return new ArrayType(this.childNodeParser.createType(arrayItemType, context));
}
}

return new ObjectType(id, this.getBaseTypes(node, context), properties, additionalProperties);
return new ObjectType(
id,
this.getBaseTypes(node, context),
properties,
additionalProperties,
false,
patternProperties,
);
}

/**
Expand Down Expand Up @@ -171,18 +185,6 @@ export class InterfaceAndClassNodeParser implements SubNodeParser {
return properties;
}

protected getAdditionalProperties(
node: ts.InterfaceDeclaration | ts.ClassDeclaration,
context: Context,
): BaseType | boolean {
const indexSignature = (node.members as ts.NodeArray<ts.NamedDeclaration>).find(ts.isIndexSignatureDeclaration);
if (!indexSignature) {
return this.additionalProperties;
}

return this.childNodeParser.createType(indexSignature.type, context) ?? this.additionalProperties;
}

protected getTypeId(node: ts.Node, context: Context): string {
const nodeType = ts.isInterfaceDeclaration(node) ? "interface" : "class";
return `${nodeType}-${getKey(node, context)}`;
Expand Down
8 changes: 7 additions & 1 deletion src/NodeParser/IntersectionNodeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,13 @@ export class IntersectionNodeParser implements SubNodeParser {

function isEmptyObject(x: BaseType) {
const t = derefType(x);
return t instanceof ObjectType && !t.getAdditionalProperties() && !t.getProperties().length;
const patternProperties = t instanceof ObjectType ? t.getPatternProperties() : undefined;
return (
t instanceof ObjectType &&
!t.getAdditionalProperties() &&
!t.getProperties().length &&
(!patternProperties || Object.keys(patternProperties).length === 0)
);
}

function derefAndFlattenUnions(type: BaseType): BaseType[] {
Expand Down
38 changes: 34 additions & 4 deletions src/NodeParser/MappedTypeNodeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { StringType } from "../Type/StringType.js";
import { SymbolType } from "../Type/SymbolType.js";
import { UnionType } from "../Type/UnionType.js";
import { derefAnnotatedType, derefType, isDeepLiteralUnion } from "../Utils/derefType.js";
import { NUMERIC_INDEX_PATTERN } from "../Utils/indexSignature.js";
import { getKey } from "../Utils/nodeKey.js";
import { preserveAnnotation } from "../Utils/preserveAnnotation.js";
import { removeUndefined } from "../Utils/removeUndefined.js";
Expand Down Expand Up @@ -57,8 +58,13 @@ export class MappedTypeNodeParser implements SubNodeParser {
node.type!,
this.createSubContext(node, keyListType, context),
);
if (maybeUnionType instanceof UnionType && constraintType?.getId() === "number") {
// Then we turn it into an array
// A direct numeric key (`Record<number, string | number>`, `keyof` an array) is an array.
// `keyof` of a numeric index signature is also a number, but mapping over it stays an object.
if (
maybeUnionType instanceof UnionType &&
constraintType?.getId() === "number" &&
!this.isMappedNumericIndexKey(node, context)
) {
return maybeUnionType instanceof NeverType ? new NeverType() : new ArrayType(maybeUnionType);
}

Expand All @@ -68,10 +74,16 @@ export class MappedTypeNodeParser implements SubNodeParser {
keyListType instanceof SymbolType ||
keyListType instanceof AnyType
) {
// Key type widens to `string`
// String, symbol, and any keys widen to additionalProperties.
// A numeric key is only the numeric pattern, not an open additional-properties constraint.
const type = this.childNodeParser.createType(node.type!, this.createSubContext(node, keyListType, context));
// const resultType = type instanceof NeverType ? new NeverType() : new ObjectType(id, [], [], type);
const resultType = new ObjectType(id, [], [], type);
const resultType =
keyListType instanceof NumberType
? new ObjectType(id, [], [], this.additionalProperties, false, {
[NUMERIC_INDEX_PATTERN]: type,
})
: new ObjectType(id, [], [], type);
if (resultType) {
let annotations;

Expand Down Expand Up @@ -195,6 +207,24 @@ export class MappedTypeNodeParser implements SubNodeParser {
return this.additionalProperties;
}

/**
* True when the mapped constraint is `keyof` an object that has a numeric index signature.
* That key is a `number`, but the mapped type is still an object with numeric pattern properties.
*/
protected isMappedNumericIndexKey(node: ts.MappedTypeNode, context: Context): boolean {
const constraint = node.typeParameter.constraint;
if (
constraint === undefined ||
!ts.isTypeOperatorNode(constraint) ||
constraint.operator !== ts.SyntaxKind.KeyOfKeyword
) {
return false;
}

const target = derefType(this.childNodeParser.createType(constraint.type, context));
return target instanceof ObjectType && target.getPatternProperties()?.[NUMERIC_INDEX_PATTERN] != null;
}

protected createSubContext(
node: ts.MappedTypeNode,
key: LiteralType | StringType | NumberType,
Expand Down
19 changes: 9 additions & 10 deletions src/NodeParser/TypeLiteralNodeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { BaseType } from "../Type/BaseType.js";
import { NeverType } from "../Type/NeverType.js";
import { ObjectProperty, ObjectType } from "../Type/ObjectType.js";
import type { ReferenceType } from "../Type/ReferenceType.js";
import { resolveIndexSignatures } from "../Utils/indexSignature.js";
import { isNodeHidden } from "../Utils/isHidden.js";
import { getKey } from "../Utils/nodeKey.js";

Expand All @@ -32,7 +33,14 @@ export class TypeLiteralNodeParser implements SubNodeParser {
return new NeverType();
}

return new ObjectType(id, [], properties, this.getAdditionalProperties(node, context));
const { additionalProperties, patternProperties } = resolveIndexSignatures(
node.members,
this.typeChecker,
(typeNode) => this.childNodeParser.createType(typeNode, context),
this.additionalProperties,
);

return new ObjectType(id, [], properties, additionalProperties, false, patternProperties);
}

protected getProperties(node: ts.TypeLiteralNode, context: Context): ObjectProperty[] | undefined {
Expand Down Expand Up @@ -67,15 +75,6 @@ export class TypeLiteralNodeParser implements SubNodeParser {
return properties;
}

protected getAdditionalProperties(node: ts.TypeLiteralNode, context: Context): BaseType | boolean {
const indexSignature = node.members.find(ts.isIndexSignatureDeclaration);
if (!indexSignature) {
return this.additionalProperties;
}

return this.childNodeParser.createType(indexSignature.type, context) ?? this.additionalProperties;
}

protected getTypeId(node: ts.Node, context: Context): string {
return `structure-${getKey(node, context)}`;
}
Expand Down
6 changes: 6 additions & 0 deletions src/NodeParser/TypeOperatorNodeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { ObjectType } from "../Type/ObjectType.js";
import { StringType } from "../Type/StringType.js";
import { UnionType } from "../Type/UnionType.js";
import { derefType } from "../Utils/derefType.js";
import { NUMERIC_INDEX_PATTERN } from "../Utils/indexSignature.js";
import { getTypeKeys } from "../Utils/typeKeys.js";

export class TypeOperatorNodeParser implements SubNodeParser {
Expand All @@ -32,6 +33,11 @@ export class TypeOperatorNodeParser implements SubNodeParser {
return new UnionType([...keys, new StringType()]);
}

if (derefed instanceof ObjectType && derefed.getPatternProperties()?.[NUMERIC_INDEX_PATTERN]) {
const numericKeys = [...keys, new NumberType()];
return numericKeys.length === 1 ? numericKeys[0] : new UnionType(numericKeys);
}

if (keys.length === 1) {
return keys[0];
}
Expand Down
4 changes: 4 additions & 0 deletions src/Type/ObjectType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export class ObjectType extends BaseType {
private additionalProperties: BaseType | boolean,
// whether the object is `object`
private nonPrimitive: boolean = false,
private patternProperties?: Readonly<Record<string, BaseType>>,
) {
super();
}
Expand All @@ -44,6 +45,9 @@ export class ObjectType extends BaseType {
public getAdditionalProperties(): BaseType | boolean {
return this.additionalProperties;
}
public getPatternProperties(): Readonly<Record<string, BaseType>> | undefined {
return this.patternProperties;
}
public getNonPrimitive(): boolean {
return this.nonPrimitive;
}
Expand Down
5 changes: 4 additions & 1 deletion src/TypeFormatter/DefinitionTypeFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { SubTypeFormatter } from "../SubTypeFormatter.js";
import type { BaseType } from "../Type/BaseType.js";
import { DefinitionType } from "../Type/DefinitionType.js";
import type { TypeFormatter } from "../TypeFormatter.js";
import { attachSchemaSource } from "../Utils/schemaSource.js";
import { uniqueArray } from "../Utils/uniqueArray.js";

export class DefinitionTypeFormatter implements SubTypeFormatter {
Expand All @@ -16,7 +17,9 @@ export class DefinitionTypeFormatter implements SubTypeFormatter {
}
public getDefinition(type: DefinitionType): Definition {
const ref = type.getName();
return { $ref: `#/definitions/${this.encodeRefs ? encodeURIComponent(ref) : ref}` };
const schema: Definition = { $ref: `#/definitions/${this.encodeRefs ? encodeURIComponent(ref) : ref}` };
attachSchemaSource(schema, type);
return schema;
}
public getChildren(type: DefinitionType): BaseType[] {
return uniqueArray([type, ...this.childTypeFormatter.getChildren(type.getType())]);
Expand Down
25 changes: 24 additions & 1 deletion src/TypeFormatter/ObjectTypeFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ export class ObjectTypeFormatter implements SubTypeFormatter {
const childrenOfAdditionalProps =
additionalProperties instanceof BaseType ? this.childTypeFormatter.getChildren(additionalProperties) : [];

const patternProperties = type.getPatternProperties();
const childrenOfPatternProps = patternProperties
? Object.values(patternProperties).flatMap((patternType) =>
this.childTypeFormatter.getChildren(patternType),
)
: [];

const childrenOfProps = properties.reduce((result: BaseType[], property) => {
const propertyType = property.getType();
if (propertyType instanceof NeverType) {
Expand All @@ -54,7 +61,12 @@ export class ObjectTypeFormatter implements SubTypeFormatter {
return [...result, ...this.childTypeFormatter.getChildren(propertyType)];
}, []);

const children = [...childrenOfBase, ...childrenOfAdditionalProps, ...childrenOfProps];
const children = [
...childrenOfBase,
...childrenOfAdditionalProps,
...childrenOfPatternProps,
...childrenOfProps,
];

return uniqueArray(children);
}
Expand All @@ -80,10 +92,21 @@ export class ObjectTypeFormatter implements SubTypeFormatter {
return result;
}, {});

const patternProperties = type.getPatternProperties();
const preparedPatternProperties = patternProperties
? Object.entries(patternProperties).reduce((result: StringMap<Definition>, [pattern, patternType]) => {
result[pattern] = this.childTypeFormatter.getDefinition(patternType);
return result;
}, {})
: undefined;

return {
type: "object",
...(Object.keys(properties).length > 0 ? { properties } : {}),
...(required.length > 0 ? { required } : {}),
...(preparedPatternProperties && Object.keys(preparedPatternProperties).length > 0
? { patternProperties: preparedPatternProperties }
: {}),
...(additionalProperties === true ||
additionalProperties instanceof AnyType ||
additionalProperties instanceof SymbolType
Expand Down
5 changes: 4 additions & 1 deletion src/TypeFormatter/ReferenceTypeFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { BaseType } from "../Type/BaseType.js";
import { DefinitionType } from "../Type/DefinitionType.js";
import { ReferenceType } from "../Type/ReferenceType.js";
import type { TypeFormatter } from "../TypeFormatter.js";
import { attachSchemaSource } from "../Utils/schemaSource.js";

export class ReferenceTypeFormatter implements SubTypeFormatter {
public constructor(
Expand All @@ -16,7 +17,9 @@ export class ReferenceTypeFormatter implements SubTypeFormatter {
}
public getDefinition(type: ReferenceType): Definition {
const ref = type.getName();
return { $ref: `#/definitions/${this.encodeRefs ? encodeURIComponent(ref) : ref}` };
const schema: Definition = { $ref: `#/definitions/${this.encodeRefs ? encodeURIComponent(ref) : ref}` };
attachSchemaSource(schema, type);
return schema;
}
public getChildren(type: ReferenceType): BaseType[] {
const referredType = type.getType();
Expand Down
Loading
Loading