@trapi/metadata 0.1.1 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cache/driver.js +1 -2
  3. package/dist/cache/driver.js.map +1 -1
  4. package/dist/cache/utils.d.ts.map +1 -1
  5. package/dist/cache/utils.js +12 -12
  6. package/dist/cache/utils.js.map +1 -1
  7. package/dist/decorator/mapper/index.js +1 -2
  8. package/dist/decorator/mapper/index.js.map +1 -1
  9. package/dist/decorator/representation/index.js +2 -4
  10. package/dist/decorator/representation/index.js.map +1 -1
  11. package/dist/decorator/representation/property/utils.js +4 -3
  12. package/dist/decorator/representation/property/utils.js.map +1 -1
  13. package/dist/generator/controller.js +1 -1
  14. package/dist/generator/controller.js.map +1 -1
  15. package/dist/generator/endpoint.js +0 -3
  16. package/dist/generator/endpoint.js.map +1 -1
  17. package/dist/generator/index.js +3 -9
  18. package/dist/generator/index.js.map +1 -1
  19. package/dist/generator/method.js +0 -2
  20. package/dist/generator/method.js.map +1 -1
  21. package/dist/generator/parameter.js +1 -9
  22. package/dist/generator/parameter.js.map +1 -1
  23. package/dist/resolver/type-node.js +28 -61
  24. package/dist/resolver/type-node.js.map +1 -1
  25. package/dist/resolver/utils/initializer.d.ts.map +1 -1
  26. package/dist/resolver/utils/initializer.js +2 -1
  27. package/dist/resolver/utils/initializer.js.map +1 -1
  28. package/dist/resolver/utils/validator.js +2 -1
  29. package/dist/resolver/utils/validator.js.map +1 -1
  30. package/dist/utils/generator.js +1 -1
  31. package/dist/utils/generator.js.map +1 -1
  32. package/dist/utils/js-doc.js +1 -1
  33. package/dist/utils/js-doc.js.map +1 -1
  34. package/package.json +18 -12
  35. package/src/cache/driver.ts +0 -97
  36. package/src/cache/index.ts +0 -10
  37. package/src/cache/type.ts +0 -43
  38. package/src/cache/utils.ts +0 -51
  39. package/src/config/index.ts +0 -8
  40. package/src/config/path.ts +0 -29
  41. package/src/decorator/functions.ts +0 -142
  42. package/src/decorator/index.ts +0 -13
  43. package/src/decorator/mapper/index.ts +0 -153
  44. package/src/decorator/mapper/maps/decorators-express.ts +0 -117
  45. package/src/decorator/mapper/maps/internal.ts +0 -95
  46. package/src/decorator/mapper/maps/typescript-rest.ts +0 -150
  47. package/src/decorator/mapper/utils.ts +0 -88
  48. package/src/decorator/representation/index.ts +0 -82
  49. package/src/decorator/representation/property/utils.ts +0 -146
  50. package/src/decorator/type.ts +0 -235
  51. package/src/decorator/utils/index.ts +0 -9
  52. package/src/decorator/utils/node.ts +0 -59
  53. package/src/decorator/utils/validator.ts +0 -104
  54. package/src/generator/controller.ts +0 -65
  55. package/src/generator/endpoint.ts +0 -212
  56. package/src/generator/index.ts +0 -219
  57. package/src/generator/method.ts +0 -198
  58. package/src/generator/parameter.ts +0 -392
  59. package/src/index.ts +0 -13
  60. package/src/resolver/error.ts +0 -38
  61. package/src/resolver/index.ts +0 -11
  62. package/src/resolver/type-node.ts +0 -1287
  63. package/src/resolver/type.ts +0 -257
  64. package/src/resolver/utils/index.ts +0 -9
  65. package/src/resolver/utils/initializer.ts +0 -81
  66. package/src/resolver/utils/validator.ts +0 -144
  67. package/src/type.ts +0 -185
  68. package/src/utils/generator.ts +0 -42
  69. package/src/utils/index.ts +0 -10
  70. package/src/utils/js-doc.ts +0 -125
  71. package/src/utils/validator.ts +0 -43
  72. package/test/data/library/@decorators-express/decorators.ts +0 -7
  73. package/test/data/library/self/api.ts +0 -37
  74. package/test/data/library/type.ts +0 -138
  75. package/test/data/library/typescript-rest/api.ts +0 -366
  76. package/test/data/library/typescript-rest/decorators/index.ts +0 -10
  77. package/test/data/library/typescript-rest/decorators/methods.ts +0 -34
  78. package/test/data/library/typescript-rest/decorators/parameters.ts +0 -62
  79. package/test/data/library/typescript-rest/decorators/services.ts +0 -47
  80. package/test/data/library/typescript-rest/return-types.ts +0 -94
  81. package/test/data/library/utils.ts +0 -7
  82. package/test/jest.config.js +0 -49
  83. package/test/unit/cache.spec.ts +0 -48
  84. package/test/unit/decorator/mapper/index.spec.ts +0 -83
  85. package/test/unit/decorator/representation/index.spec.ts +0 -102
  86. package/test/unit/decorator/utils/node.spec.ts +0 -47
  87. package/test/unit/library/typescript-rest.spec.ts +0 -342
  88. package/test/unit/resolver/type.spec.ts +0 -134
  89. package/test/unit/utils/generator.spec.ts +0 -41
  90. package/test/unit/utils/js-doc.spec.ts +0 -95
  91. package/tsconfig.build.json +0 -11
  92. package/tsconfig.json +0 -9
  93. package/writable/.gitignore +0 -3
@@ -1,219 +0,0 @@
1
- /*
2
- * Copyright (c) 2021.
3
- * Author Peter Placzek (tada5hi)
4
- * For the full copyright and license information,
5
- * view the LICENSE file that was distributed with this source code.
6
- */
7
-
8
- import {sync} from 'glob';
9
- import {
10
- ClassDeclaration,
11
- CompilerOptions,
12
- createProgram,
13
- forEachChild,
14
- InterfaceDeclaration,
15
- isModuleBlock,
16
- isModuleDeclaration,
17
- Node,
18
- NodeFlags,
19
- Program,
20
- SourceFile,
21
- SyntaxKind,
22
- TypeChecker
23
- } from 'typescript';
24
- import {Config, Controller, GeneratorOutput} from "../type";
25
- import {DecoratorMapper} from "../decorator/mapper";
26
- import {ControllerGenerator} from './controller';
27
- import {TypeNodeResolver} from "../resolver";
28
- import {Resolver} from "../resolver";
29
- import {CacheDriver} from "../cache/driver";
30
-
31
- const minimatch = require("minimatch");
32
-
33
- export class MetadataGenerator {
34
- public readonly nodes = new Array<Node>();
35
- public readonly typeChecker: TypeChecker;
36
-
37
- public readonly decoratorMapper: DecoratorMapper;
38
-
39
- public readonly config: Config;
40
-
41
- private readonly program: Program;
42
-
43
- private cache : CacheDriver;
44
- private controllers: Controller[];
45
- private referenceTypes: Resolver.ReferenceTypes = {};
46
-
47
- private circularDependencyResolvers = new Array<Resolver.DependencyResolver>();
48
-
49
- // -------------------------------------------------------------------------
50
-
51
- constructor(
52
- config: Config,
53
- compilerOptions: CompilerOptions
54
- ) {
55
- this.config = config;
56
-
57
- this.cache = new CacheDriver(config.cache);
58
- this.decoratorMapper = new DecoratorMapper(config.decorator);
59
-
60
- TypeNodeResolver.clearCache();
61
-
62
- const sourceFiles = this.scanSourceFiles(config.entryFile);
63
- this.program = createProgram(sourceFiles, compilerOptions);
64
- this.typeChecker = this.program.getTypeChecker();
65
- }
66
-
67
- // -------------------------------------------------------------------------
68
-
69
- public generate(): GeneratorOutput {
70
- const sourceFileSize : number = this.buildNodesFromSourceFiles();
71
-
72
- let cache = this.cache.get(sourceFileSize);
73
-
74
- if(!cache) {
75
- this.buildControllers();
76
-
77
- this.circularDependencyResolvers.forEach(resolve => resolve(this.referenceTypes));
78
-
79
- cache = {
80
- controllers: this.controllers,
81
- referenceTypes: this.referenceTypes,
82
- sourceFilesSize: sourceFileSize
83
- };
84
-
85
- this.cache.save(cache);
86
- }
87
-
88
- return {
89
- controllers: cache.controllers,
90
- referenceTypes: cache.referenceTypes
91
- };
92
- }
93
-
94
- protected buildNodesFromSourceFiles() : number {
95
- let endSize : number = 0;
96
-
97
- this.program.getSourceFiles().forEach((sf: SourceFile) => {
98
- const isIgnored : boolean = this.isIgnoredPath(sf.fileName);
99
- if(isIgnored) {
100
- return;
101
- }
102
-
103
- endSize += sf.end;
104
-
105
- forEachChild(sf, (node: any) => {
106
- if (isModuleDeclaration(node)) {
107
- /**
108
- * For some reason unknown to me, TS resolves both `declare module` and `namespace` to
109
- * the same kind (`ModuleDeclaration`). In order to figure out whether it's one or the other,
110
- * we check the node flags. They tell us whether it is a namespace or not.
111
- */
112
-
113
- // tslint:disable-next-line:no-bitwise
114
- if ((node.flags & NodeFlags.Namespace) === 0 && node.body && isModuleBlock(node.body)) {
115
- node.body.statements.forEach(statement => {
116
- this.nodes.push(statement);
117
- });
118
- return;
119
- }
120
- }
121
-
122
-
123
- this.nodes.push(node);
124
- });
125
- });
126
-
127
- return endSize;
128
- }
129
-
130
- // -------------------------------------------------------------------------
131
-
132
- /**
133
- * Check if the source file path is in the ignored path list.
134
- *
135
- * @param filePath
136
- * @protected
137
- */
138
- protected isIgnoredPath(filePath: string) : boolean {
139
- if(typeof this.config.ignore === 'undefined') {
140
- return false;
141
- }
142
-
143
- return this.config.ignore.some(item => minimatch(filePath, item));
144
- }
145
-
146
- // -------------------------------------------------------------------------
147
-
148
- public isExportedNode(node: Node) {
149
- return true;
150
- }
151
-
152
- // -------------------------------------------------------------------------
153
-
154
- public addReferenceType(referenceType: Resolver.ReferenceType) {
155
- if (!referenceType.refName) {
156
- return;
157
- }
158
-
159
- this.referenceTypes[referenceType.refName] = referenceType;
160
- }
161
-
162
- public getReferenceType(refName: string) {
163
- return this.referenceTypes[refName];
164
- }
165
-
166
- public registerDependencyResolver(callback: Resolver.DependencyResolver) {
167
- this.circularDependencyResolvers.push(callback);
168
- }
169
-
170
- public getClassDeclaration(className: string) {
171
- const found = this.nodes
172
- .filter(node => {
173
- const classDeclaration = (node as ClassDeclaration);
174
- return (node.kind === SyntaxKind.ClassDeclaration && classDeclaration.name && classDeclaration.name.text === className);
175
- });
176
- if (found && found.length) {
177
- return found[0];
178
- }
179
- return undefined;
180
- }
181
-
182
- public getInterfaceDeclaration(className: string) {
183
- const found = this.nodes
184
- .filter(node => {
185
- const interfaceDeclaration = (node as InterfaceDeclaration);
186
- return (node.kind === SyntaxKind.InterfaceDeclaration && interfaceDeclaration.name && interfaceDeclaration.name.text === className);
187
- });
188
- if (found && found.length) {
189
- return found[0];
190
- }
191
- return undefined;
192
- }
193
-
194
- private scanSourceFiles(sourceFiles: string | string[]) {
195
- const sourceFilesExpressions = Array.isArray(sourceFiles) ? sourceFiles : [sourceFiles];
196
- const result: Set<string> = new Set<string>();
197
- const options = { cwd: process.cwd() };
198
- sourceFilesExpressions.forEach(pattern => {
199
- const matches = sync(pattern, options);
200
- matches.forEach(file => {result.add(file); });
201
- });
202
-
203
- return Array.from(result);
204
- }
205
-
206
- private buildControllers() : void {
207
- this.controllers = this.nodes
208
- .filter(node => node.kind === SyntaxKind.ClassDeclaration)
209
- .filter(node => {
210
- const isHidden = this.decoratorMapper.match('HIDDEN', node);
211
-
212
- return typeof isHidden === 'undefined';
213
- })
214
- .filter(node => typeof this.decoratorMapper.match('CLASS_PATH', node) !== 'undefined')
215
- .map((classDeclaration: ClassDeclaration) => new ControllerGenerator(classDeclaration, this))
216
- .filter(generator => generator.isValid())
217
- .map(generator => generator.generate());
218
- }
219
- }
@@ -1,198 +0,0 @@
1
- /*
2
- * Copyright (c) 2021.
3
- * Author Peter Placzek (tada5hi)
4
- * For the full copyright and license information,
5
- * view the LICENSE file that was distributed with this source code.
6
- */
7
-
8
- import * as pathUtil from 'path';
9
- import * as ts from 'typescript';
10
- import {Decorator} from "../decorator";
11
- import {EndpointGenerator} from './endpoint';
12
- import {MetadataGenerator} from './index';
13
- import {ParameterGenerator} from './parameter';
14
- import {Resolver, TypeNodeResolver} from "../resolver";
15
- import {hasOwnProperty} from "@trapi/metadata-utils";
16
- import {Method, MethodType, Parameter, Response} from "../type";
17
- import {getJSDocDescription, getJSDocTagComment} from '../utils';
18
- import MethodHttpVerbKey = Decorator.MethodHttpVerbType;
19
- import {getNodeDecorators} from "../decorator";
20
-
21
-
22
- export class MethodGenerator extends EndpointGenerator<ts.MethodDeclaration> {
23
- private method: MethodType;
24
-
25
- // --------------------------------------------------------------------
26
-
27
- constructor(
28
- node: ts.MethodDeclaration,
29
- current: MetadataGenerator,
30
- private readonly controllerPath: string
31
- ) {
32
- super(node, current);
33
- this.processMethodDecorators();
34
- }
35
-
36
- // --------------------------------------------------------------------
37
-
38
- public isValid() {
39
- return !!this.method;
40
- }
41
-
42
- public getMethodName() {
43
- const identifier = this.node.name as ts.Identifier;
44
- return identifier.text;
45
- }
46
-
47
- public generate(): Method {
48
- if (!this.isValid()) { throw new Error('This isn\'t a valid controller method.'); }
49
-
50
- let nodeType = this.node.type;
51
- if (!nodeType) {
52
- const typeChecker = this.current.typeChecker;
53
- const signature = typeChecker.getSignatureFromDeclaration(this.node);
54
- const implicitType = typeChecker.getReturnTypeOfSignature(signature!);
55
- nodeType = typeChecker.typeToTypeNode(implicitType, undefined, ts.NodeBuilderFlags.NoTruncation) as ts.TypeNode;
56
- }
57
-
58
- const type = new TypeNodeResolver(nodeType, this.current).resolve();
59
- const responses = this.mergeResponses(this.getResponses(), this.getMethodSuccessResponse(type));
60
-
61
- return {
62
- // todo: implement extensions
63
- consumes: this.getConsumes(),
64
- deprecated: this.isDeprecated(this.node),
65
- description: getJSDocDescription(this.node),
66
- extensions: [],
67
- hidden: this.isHidden(this.node),
68
- method: this.method,
69
- name: (this.node.name as ts.Identifier).text,
70
- parameters: this.buildParameters(),
71
- path: this.path,
72
- produces: this.getProduces(),
73
- responses: responses,
74
- security: this.getSecurity(),
75
- summary: getJSDocTagComment(this.node, 'summary'),
76
- tags: this.getTags(),
77
- type: type
78
- };
79
- }
80
-
81
- protected getCurrentLocation() {
82
- const methodId = this.node.name as ts.Identifier;
83
- const controllerId = (this.node.parent as ts.ClassDeclaration).name as ts.Identifier;
84
- return `${controllerId.text}.${methodId.text}`;
85
- }
86
-
87
- private buildParameters() {
88
- const parameters = this.node.parameters.map((p: ts.ParameterDeclaration) => {
89
- try {
90
- const path = pathUtil.posix.join('/', (this.controllerPath ? this.controllerPath : ''), this.path);
91
-
92
- return new ParameterGenerator(p, this.method, path, this.current).generate();
93
- } catch (e) {
94
- const methodId = this.node.name as ts.Identifier;
95
- const controllerId = (this.node.parent as ts.ClassDeclaration).name as ts.Identifier;
96
- const parameterId = p.name as ts.Identifier;
97
- throw new Error(`Error generate parameter method: '${controllerId.text}.${methodId.text}' argument: ${parameterId.text} ${e}`);
98
- }
99
- }).filter((p: Parameter) => (p.in !== 'context') && (p.in !== 'cookie'));
100
-
101
- const bodyParameters = parameters.filter((p: Parameter) => p.in === 'body');
102
- const formParameters = parameters.filter((p: Parameter) => p.in === 'formData');
103
-
104
- if (bodyParameters.length > 1) {
105
- throw new Error(`Only one body parameter allowed in '${this.getCurrentLocation()}' method.`);
106
- }
107
-
108
- if (bodyParameters.length > 0 && formParameters.length > 0) {
109
- throw new Error(`Choose either during @FormParam and @FileParam or body parameter in '${this.getCurrentLocation()}' method.`);
110
- }
111
-
112
- return parameters;
113
- }
114
-
115
- private processMethodDecorators() {
116
- const httpMethodDecorators = getNodeDecorators(this.node, decorator => this.supportsPathMethod(decorator.text));
117
-
118
- if (!httpMethodDecorators || !httpMethodDecorators.length) { return; }
119
- if (httpMethodDecorators.length > 1) {
120
- throw new Error(`Only one HTTP Method decorator in '${this.getCurrentLocation}' method is acceptable, Found: ${httpMethodDecorators.map(d => d.text).join(', ')}`);
121
- }
122
-
123
- const methodDecorator = httpMethodDecorators[0];
124
- this.method = methodDecorator.text.toLowerCase() as MethodType;
125
-
126
- this.generatePath('METHOD_PATH');
127
- }
128
-
129
- private getMethodSuccessResponse(type: Resolver.BaseType): Response {
130
- type = this.getMethodSuccessResponseType(type);
131
-
132
- return {
133
- description: Resolver.isVoidType(type) ? 'No content' : 'Ok',
134
- examples: this.getMethodSuccessExamples(),
135
- schema: type,
136
- status: Resolver.isVoidType(type) ? '204' : '200',
137
- name: Resolver.isVoidType(type) ? '204' : '200'
138
- };
139
- }
140
-
141
- private getMethodSuccessResponseType(type: Resolver.BaseType) : Resolver.BaseType {
142
- if(!Resolver.isVoidType(type)) {
143
- return type;
144
- }
145
-
146
- const representation = this.current.decoratorMapper.match('RESPONSE_EXAMPLE', this.node);
147
- if(typeof representation === 'undefined') {
148
- return type;
149
- }
150
-
151
- const value = representation.getPropertyValue('TYPE');
152
-
153
- if(
154
- typeof value !== 'undefined' &&
155
- hasOwnProperty(value, 'kind') &&
156
- ts.isTypeNode(value as ts.Node)
157
- ) {
158
- type = new TypeNodeResolver(value as ts.TypeNode, this.current).resolve();
159
- }
160
-
161
- return type;
162
- }
163
-
164
- private getMethodSuccessExamples() {
165
- const representation = this.current.decoratorMapper.match('RESPONSE_EXAMPLE', this.node);
166
- if(typeof representation === 'undefined') {
167
- return [];
168
- }
169
-
170
- let value : unknown = representation.getPropertyValue('PAYLOAD');
171
- if(typeof value === 'undefined') {
172
- return [];
173
- }
174
-
175
- return value;
176
- }
177
-
178
- private mergeResponses(responses: Response[], defaultResponse: Response) {
179
- if (!responses || !responses.length) {
180
- return [defaultResponse];
181
- }
182
-
183
- const index = responses.findIndex((resp) => resp.status === defaultResponse.status);
184
-
185
- if (index >= 0) {
186
- if (defaultResponse.examples && !responses[index].examples) {
187
- responses[index].examples = defaultResponse.examples;
188
- }
189
- } else {
190
- responses.push(defaultResponse);
191
- }
192
- return responses;
193
- }
194
-
195
- private supportsPathMethod(method: string) : boolean {
196
- return (['ALL', 'GET', 'POST', 'PATCH', 'DELETE', 'PUT', 'OPTIONS', 'HEAD'] as MethodHttpVerbKey[]).some(m => m.toLowerCase() === method.toLowerCase());
197
- }
198
- }