@ts-ast-parser/core
Version:
Reflects a simplified version of the TypeScript AST for generating documentation
96 lines • 3.44 kB
JavaScript
import { tryAddProperty } from '../utils/try-add-property.js';
import { TypeParameterNode } from './type-parameter-node.js';
import { createType } from '../factories/create-type.js';
import { ParameterNode } from './parameter-node.js';
import { CommentNode } from './comment-node.js';
import ts from 'typescript';
/**
* Represents the reflected node of a signature declaration
*/
export class SignatureNode {
constructor(node, context) {
Object.defineProperty(this, "_node", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "_context", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "_jsDoc", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this._node = node;
this._context = context;
this._jsDoc = new CommentNode(this._node.getDeclaration());
}
getContext() {
return this._context;
}
getTSNode() {
return this._node;
}
getLine() {
return this._context.getLinePosition(this._node.getDeclaration());
}
getPath() {
const fileName = this._node.getDeclaration().getSourceFile().fileName ?? '';
return fileName ? this._context.getSystem().realpath(fileName) : fileName;
}
getJSDoc() {
return this._jsDoc;
}
getReturnType() {
const jsDocType = ts.getJSDocReturnType(this._node.getDeclaration());
if (jsDocType) {
return createType(jsDocType, this._context);
}
const returnTypeOfSignature = this._context.getTypeChecker().getReturnTypeOfSignature(this._node);
return createType(returnTypeOfSignature, this._context);
}
getTypeParameters() {
return this._node.getDeclaration().typeParameters?.map(tp => new TypeParameterNode(tp, this._context)) ?? [];
}
getParameters() {
const symbolParameters = this._node.parameters ?? [];
const declarationParameters = this._node.getDeclaration().parameters ?? [];
const result = [];
for (let index = 0; index < declarationParameters.length; index++) {
const paramNode = declarationParameters[index];
const node = new ParameterNode(paramNode, symbolParameters[index] ?? null, this._context);
if (node.getJSDoc().isIgnored()) {
continue;
}
result.push(node);
}
return result;
}
getParameterByName(name) {
return this.getParameters().find(param => param.getName() === name) ?? null;
}
/**
* Serializes the reflected node
*
* @returns The reflected node as a serializable object
*/
serialize() {
const tmpl = {
return: {
type: this.getReturnType().serialize(),
},
};
tryAddProperty(tmpl, 'line', this.getLine());
tryAddProperty(tmpl, 'jsDoc', this.getJSDoc().serialize());
tryAddProperty(tmpl, 'typeParameters', this.getTypeParameters().map(tp => tp.serialize()));
tryAddProperty(tmpl, 'parameters', this.getParameters().map(param => param.serialize()));
return tmpl;
}
}
//# sourceMappingURL=signature-node.js.map