@nestia/core 0.1.0

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 (118) hide show
  1. package/LICENSE +21 -0
  2. package/lib/decorators/EncryptedBody.d.ts +22 -0
  3. package/lib/decorators/EncryptedBody.js +125 -0
  4. package/lib/decorators/EncryptedBody.js.map +1 -0
  5. package/lib/decorators/EncryptedController.d.ts +31 -0
  6. package/lib/decorators/EncryptedController.js +42 -0
  7. package/lib/decorators/EncryptedController.js.map +1 -0
  8. package/lib/decorators/EncryptedModule.d.ts +48 -0
  9. package/lib/decorators/EncryptedModule.js +270 -0
  10. package/lib/decorators/EncryptedModule.js.map +1 -0
  11. package/lib/decorators/EncryptedRoute.d.ts +78 -0
  12. package/lib/decorators/EncryptedRoute.js +191 -0
  13. package/lib/decorators/EncryptedRoute.js.map +1 -0
  14. package/lib/decorators/PlainBody.d.ts +22 -0
  15. package/lib/decorators/PlainBody.js +83 -0
  16. package/lib/decorators/PlainBody.js.map +1 -0
  17. package/lib/decorators/TypedBody.d.ts +14 -0
  18. package/lib/decorators/TypedBody.js +93 -0
  19. package/lib/decorators/TypedBody.js.map +1 -0
  20. package/lib/decorators/TypedParam.d.ts +25 -0
  21. package/lib/decorators/TypedParam.js +62 -0
  22. package/lib/decorators/TypedParam.js.map +1 -0
  23. package/lib/decorators/TypedRoute.d.ts +71 -0
  24. package/lib/decorators/TypedRoute.js +159 -0
  25. package/lib/decorators/TypedRoute.js.map +1 -0
  26. package/lib/decorators/internal/EncryptedConstant.d.ts +1 -0
  27. package/lib/decorators/internal/EncryptedConstant.js +8 -0
  28. package/lib/decorators/internal/EncryptedConstant.js.map +1 -0
  29. package/lib/decorators/internal/get_path_and_stringify.d.ts +1 -0
  30. package/lib/decorators/internal/get_path_and_stringify.js +75 -0
  31. package/lib/decorators/internal/get_path_and_stringify.js.map +1 -0
  32. package/lib/decorators/internal/headers_to_object.d.ts +1 -0
  33. package/lib/decorators/internal/headers_to_object.js +53 -0
  34. package/lib/decorators/internal/headers_to_object.js.map +1 -0
  35. package/lib/decorators/internal/route_error.d.ts +1 -0
  36. package/lib/decorators/internal/route_error.js +90 -0
  37. package/lib/decorators/internal/route_error.js.map +1 -0
  38. package/lib/decorators/internal/validate_request_body.d.ts +2 -0
  39. package/lib/decorators/internal/validate_request_body.js +56 -0
  40. package/lib/decorators/internal/validate_request_body.js.map +1 -0
  41. package/lib/index.d.ts +3 -0
  42. package/lib/index.js +32 -0
  43. package/lib/index.js.map +1 -0
  44. package/lib/module.d.ts +9 -0
  45. package/lib/module.js +26 -0
  46. package/lib/module.js.map +1 -0
  47. package/lib/options/INestiaTransformOptions.d.ts +5 -0
  48. package/lib/options/INestiaTransformOptions.js +3 -0
  49. package/lib/options/INestiaTransformOptions.js.map +1 -0
  50. package/lib/options/INestiaTransformProject.d.ts +5 -0
  51. package/lib/options/INestiaTransformProject.js +3 -0
  52. package/lib/options/INestiaTransformProject.js.map +1 -0
  53. package/lib/options/IRequestBodyValidator.d.ts +16 -0
  54. package/lib/options/IRequestBodyValidator.js +3 -0
  55. package/lib/options/IRequestBodyValidator.js.map +1 -0
  56. package/lib/options/IResponseBodyStringifier.d.ts +20 -0
  57. package/lib/options/IResponseBodyStringifier.js +3 -0
  58. package/lib/options/IResponseBodyStringifier.js.map +1 -0
  59. package/lib/transform.d.ts +3 -0
  60. package/lib/transform.js +21 -0
  61. package/lib/transform.js.map +1 -0
  62. package/lib/transformers/BodyTransformer.d.ts +5 -0
  63. package/lib/transformers/BodyTransformer.js +69 -0
  64. package/lib/transformers/BodyTransformer.js.map +1 -0
  65. package/lib/transformers/FileTransformer.d.ts +5 -0
  66. package/lib/transformers/FileTransformer.js +33 -0
  67. package/lib/transformers/FileTransformer.js.map +1 -0
  68. package/lib/transformers/MethodTransformer.d.ts +5 -0
  69. package/lib/transformers/MethodTransformer.js +55 -0
  70. package/lib/transformers/MethodTransformer.js.map +1 -0
  71. package/lib/transformers/NodeTransformer.d.ts +5 -0
  72. package/lib/transformers/NodeTransformer.js +21 -0
  73. package/lib/transformers/NodeTransformer.js.map +1 -0
  74. package/lib/transformers/ParameterTransformer.d.ts +5 -0
  75. package/lib/transformers/ParameterTransformer.js +31 -0
  76. package/lib/transformers/ParameterTransformer.js.map +1 -0
  77. package/lib/transformers/RouteTransformer.d.ts +5 -0
  78. package/lib/transformers/RouteTransformer.js +115 -0
  79. package/lib/transformers/RouteTransformer.js.map +1 -0
  80. package/lib/typings/Creator.d.ts +3 -0
  81. package/lib/typings/Creator.js +3 -0
  82. package/lib/typings/Creator.js.map +1 -0
  83. package/lib/utils/ExceptionManager.d.ts +64 -0
  84. package/lib/utils/ExceptionManager.js +113 -0
  85. package/lib/utils/ExceptionManager.js.map +1 -0
  86. package/lib/utils/Singleton.d.ts +1 -0
  87. package/lib/utils/Singleton.js +24 -0
  88. package/lib/utils/Singleton.js.map +1 -0
  89. package/package.json +66 -0
  90. package/src/decorators/EncryptedBody.ts +102 -0
  91. package/src/decorators/EncryptedController.ts +43 -0
  92. package/src/decorators/EncryptedModule.ts +127 -0
  93. package/src/decorators/EncryptedRoute.ts +200 -0
  94. package/src/decorators/PlainBody.ts +38 -0
  95. package/src/decorators/TypedBody.ts +49 -0
  96. package/src/decorators/TypedParam.ts +70 -0
  97. package/src/decorators/TypedRoute.ts +149 -0
  98. package/src/decorators/internal/EncryptedConstant.ts +4 -0
  99. package/src/decorators/internal/get_path_and_stringify.ts +76 -0
  100. package/src/decorators/internal/headers_to_object.ts +13 -0
  101. package/src/decorators/internal/route_error.ts +41 -0
  102. package/src/decorators/internal/validate_request_body.ts +58 -0
  103. package/src/index.ts +5 -0
  104. package/src/module.ts +9 -0
  105. package/src/options/INestiaTransformOptions.ts +6 -0
  106. package/src/options/INestiaTransformProject.ts +6 -0
  107. package/src/options/IRequestBodyValidator.ts +20 -0
  108. package/src/options/IResponseBodyStringifier.ts +25 -0
  109. package/src/transform.ts +20 -0
  110. package/src/transformers/BodyTransformer.ts +106 -0
  111. package/src/transformers/FileTransformer.ts +49 -0
  112. package/src/transformers/MethodTransformer.ts +91 -0
  113. package/src/transformers/NodeTransformer.ts +18 -0
  114. package/src/transformers/ParameterTransformer.ts +45 -0
  115. package/src/transformers/RouteTransformer.ts +134 -0
  116. package/src/typings/Creator.ts +3 -0
  117. package/src/utils/ExceptionManager.ts +126 -0
  118. package/src/utils/Singleton.ts +20 -0
@@ -0,0 +1,91 @@
1
+ import ts from "typescript";
2
+
3
+ import { INestiaTransformProject } from "../options/INestiaTransformProject";
4
+ import { RouteTransformer } from "./RouteTransformer";
5
+
6
+ export namespace MethodTransformer {
7
+ export function transform(
8
+ project: INestiaTransformProject,
9
+ method: ts.MethodDeclaration,
10
+ ): ts.MethodDeclaration {
11
+ const decorators: readonly ts.Decorator[] | undefined = ts.getDecorators
12
+ ? ts.getDecorators(method)
13
+ : (method as any).decorators;
14
+ if (!decorators?.length) return method;
15
+
16
+ const signature: ts.Signature | undefined =
17
+ project.checker.getSignatureFromDeclaration(method);
18
+ const original: ts.Type | undefined =
19
+ signature && project.checker.getReturnTypeOfSignature(signature);
20
+ const escaped: ts.Type | undefined =
21
+ original && get_escaped_type(project.checker, original);
22
+
23
+ if (escaped === undefined) return method;
24
+
25
+ if (ts.getDecorators !== undefined)
26
+ return ts.factory.updateMethodDeclaration(
27
+ method,
28
+ (method.modifiers || []).map((mod) =>
29
+ ts.isDecorator(mod)
30
+ ? RouteTransformer.transform(project, escaped, mod)
31
+ : mod,
32
+ ),
33
+ method.asteriskToken,
34
+ method.name,
35
+ method.questionToken,
36
+ method.typeParameters,
37
+ method.parameters,
38
+ method.type,
39
+ method.body,
40
+ );
41
+ // eslint-disable-next-line
42
+ return ts.factory.updateMethodDeclaration(
43
+ method,
44
+ decorators.map((deco) =>
45
+ RouteTransformer.transform(project, escaped, deco),
46
+ ),
47
+ (method as any).modifiers,
48
+ method.asteriskToken,
49
+ method.name,
50
+ method.questionToken,
51
+ method.typeParameters,
52
+ method.parameters,
53
+ method.type,
54
+ method.body,
55
+ );
56
+ }
57
+ }
58
+
59
+ function get_escaped_type(checker: ts.TypeChecker, type: ts.Type): ts.Type {
60
+ const symbol: ts.Symbol | undefined = type.getSymbol() || type.aliasSymbol;
61
+ return symbol && get_name(symbol) === "Promise"
62
+ ? escape_promise(checker, type)
63
+ : type;
64
+ }
65
+
66
+ function escape_promise(checker: ts.TypeChecker, type: ts.Type): ts.Type {
67
+ const generic: readonly ts.Type[] = checker.getTypeArguments(
68
+ type as ts.TypeReference,
69
+ );
70
+ if (generic.length !== 1)
71
+ throw new Error(
72
+ "Error on ImportAnalyzer.analyze(): invalid promise type.",
73
+ );
74
+ return generic[0];
75
+ }
76
+
77
+ function get_name(symbol: ts.Symbol): string {
78
+ return explore_name(
79
+ symbol.escapedName.toString(),
80
+ symbol.getDeclarations()![0].parent,
81
+ );
82
+ }
83
+
84
+ function explore_name(name: string, decl: ts.Node): string {
85
+ return ts.isModuleBlock(decl)
86
+ ? explore_name(
87
+ `${decl.parent.name.getText()}.${name}`,
88
+ decl.parent.parent,
89
+ )
90
+ : name;
91
+ }
@@ -0,0 +1,18 @@
1
+ import ts from "typescript";
2
+
3
+ import { INestiaTransformProject } from "../options/INestiaTransformProject";
4
+ import { MethodTransformer } from "./MethodTransformer";
5
+ import { ParameterTransformer } from "./ParameterTransformer";
6
+
7
+ export namespace NodeTransformer {
8
+ export function transform(
9
+ project: INestiaTransformProject,
10
+ node: ts.Node,
11
+ ): ts.Node {
12
+ if (ts.isMethodDeclaration(node))
13
+ return MethodTransformer.transform(project, node);
14
+ else if (ts.isParameter(node))
15
+ return ParameterTransformer.transform(project, node);
16
+ return node;
17
+ }
18
+ }
@@ -0,0 +1,45 @@
1
+ import ts from "typescript";
2
+
3
+ import { INestiaTransformProject } from "../options/INestiaTransformProject";
4
+ import { BodyTransformer } from "./BodyTransformer";
5
+
6
+ export namespace ParameterTransformer {
7
+ export function transform(
8
+ project: INestiaTransformProject,
9
+ param: ts.ParameterDeclaration,
10
+ ): ts.ParameterDeclaration {
11
+ const decorators: readonly ts.Decorator[] | undefined = ts.getDecorators
12
+ ? ts.getDecorators(param)
13
+ : (param as any).decorators;
14
+ if (!decorators?.length) return param;
15
+
16
+ const type: ts.Type = project.checker.getTypeAtLocation(param);
17
+ if (ts.getDecorators !== undefined)
18
+ return ts.factory.updateParameterDeclaration(
19
+ param,
20
+ (param.modifiers || []).map((mod) =>
21
+ ts.isDecorator(mod)
22
+ ? BodyTransformer.transform(project, type, mod)
23
+ : mod,
24
+ ),
25
+ param.dotDotDotToken,
26
+ param.name,
27
+ param.questionToken,
28
+ param.type,
29
+ param.initializer,
30
+ );
31
+ // eslint-disable-next-line
32
+ return ts.factory.updateParameterDeclaration(
33
+ param,
34
+ decorators.map((deco) =>
35
+ BodyTransformer.transform(project, type, deco),
36
+ ),
37
+ (param as any).modifiers,
38
+ param.dotDotDotToken,
39
+ param.name,
40
+ param.questionToken,
41
+ param.type,
42
+ param.initializer,
43
+ );
44
+ }
45
+ }
@@ -0,0 +1,134 @@
1
+ import path from "path";
2
+ import ts from "typescript";
3
+ import { AssertStringifyProgrammer } from "typia/lib/programmers/AssertStringifyProgrammer";
4
+ import { IsStringifyProgrammer } from "typia/lib/programmers/IsStringifyProgrammer";
5
+ import { StringifyProgrammer } from "typia/lib/programmers/StringifyProgrammer";
6
+ import { ValidateStringifyProgrammer } from "typia/lib/programmers/ValidateStringifyProgrammer";
7
+ import { IProject } from "typia/lib/transformers/IProject";
8
+
9
+ import { INestiaTransformProject } from "../options/INestiaTransformProject";
10
+
11
+ export namespace RouteTransformer {
12
+ export function transform(
13
+ project: INestiaTransformProject,
14
+ type: ts.Type,
15
+ decorator: ts.Decorator,
16
+ ): ts.Decorator {
17
+ if (!ts.isCallExpression(decorator.expression)) return decorator;
18
+ return ts.factory.createDecorator(
19
+ stringify(project, type, decorator.expression),
20
+ );
21
+ }
22
+
23
+ function stringify(
24
+ project: INestiaTransformProject,
25
+ type: ts.Type,
26
+ expression: ts.CallExpression,
27
+ ): ts.LeftHandSideExpression {
28
+ //----
29
+ // VALIDATIONS
30
+ //----
31
+ // CHECK SIGNATURE
32
+ const signature: ts.Signature | undefined =
33
+ project.checker.getResolvedSignature(expression);
34
+ if (!signature || !signature.declaration) return expression;
35
+
36
+ // CHECK TO BE TRANSFORMED
37
+ const validate: boolean = (() => {
38
+ // CHECK FILENAME
39
+ const location: string = path.resolve(
40
+ signature.declaration.getSourceFile().fileName,
41
+ );
42
+ if (
43
+ LIB_PATHS.every((str) => location.indexOf(str) === -1) &&
44
+ SRC_PATHS.every((str) => location !== str)
45
+ )
46
+ return false;
47
+
48
+ // CHECK DUPLICATE BOOSTER
49
+ if (expression.arguments.length >= 2) return false;
50
+ else if (expression.arguments.length === 1) {
51
+ const last: ts.Expression =
52
+ expression.arguments[expression.arguments.length - 1];
53
+ const type: ts.Type = project.checker.getTypeAtLocation(last);
54
+ if (isObject(project.checker, type)) return false;
55
+ }
56
+ return true;
57
+ })();
58
+ if (validate === false) return expression;
59
+
60
+ // CHECK TYPE NODE
61
+ const typeNode: ts.TypeNode | undefined =
62
+ project.checker.typeToTypeNode(type, undefined, undefined);
63
+ if (typeNode === undefined) return expression;
64
+
65
+ //----
66
+ // TRANSFORMATION
67
+ //----
68
+ // GENERATE STRINGIFY PLAN
69
+ const parameter = (
70
+ key: string,
71
+ programmer: (
72
+ project: IProject,
73
+ modulo: ts.LeftHandSideExpression,
74
+ ) => (type: ts.Type) => ts.ArrowFunction,
75
+ ) =>
76
+ ts.factory.createObjectLiteralExpression([
77
+ ts.factory.createPropertyAssignment(
78
+ ts.factory.createIdentifier("type"),
79
+ ts.factory.createStringLiteral(key),
80
+ ),
81
+ ts.factory.createPropertyAssignment(
82
+ ts.factory.createIdentifier(key),
83
+ programmer(project, expression.expression)(type),
84
+ ),
85
+ ]);
86
+ const stringify: ts.ObjectLiteralExpression = (() => {
87
+ if (project.options.stringify === "stringify")
88
+ return parameter("stringify", StringifyProgrammer.generate);
89
+ else if (
90
+ project.options.stringify === undefined ||
91
+ project.options.stringify === "assert"
92
+ )
93
+ return parameter("assert", AssertStringifyProgrammer.generate);
94
+ else if (project.options.stringify === "validate")
95
+ return parameter(
96
+ "validate",
97
+ ValidateStringifyProgrammer.generate,
98
+ );
99
+ return parameter("is", IsStringifyProgrammer.generate);
100
+ })();
101
+
102
+ // UPDATE DECORATOR FUNCTION CALL
103
+ return ts.factory.updateCallExpression(
104
+ expression,
105
+ expression.expression,
106
+ expression.typeArguments,
107
+ [...expression.arguments, stringify],
108
+ );
109
+ }
110
+
111
+ function isObject(checker: ts.TypeChecker, type: ts.Type): boolean {
112
+ return (
113
+ (type.getFlags() & ts.TypeFlags.Object) !== 0 &&
114
+ !(checker as any).isTupleType(type) &&
115
+ !(checker as any).isArrayType(type) &&
116
+ !(checker as any).isArrayLikeType(type)
117
+ );
118
+ }
119
+
120
+ const CLASSES = ["EncryptedRoute", "TypedRoute"];
121
+ const LIB_PATHS = CLASSES.map((cla) =>
122
+ path.join(
123
+ "node_modules",
124
+ "@nestia",
125
+ "core",
126
+ "lib",
127
+ "decorators",
128
+ `${cla}.d.ts`,
129
+ ),
130
+ );
131
+ const SRC_PATHS = CLASSES.map((cla) =>
132
+ path.resolve(path.join(__dirname, "..", "decorators", `${cla}.ts`)),
133
+ );
134
+ }
@@ -0,0 +1,3 @@
1
+ export type Creator<T extends object> = {
2
+ new (...args: any[]): T;
3
+ };
@@ -0,0 +1,126 @@
1
+ import { HttpError } from "@nestia/fetcher";
2
+ import { HttpException } from "@nestjs/common";
3
+ import { TypeGuardError } from "typia";
4
+
5
+ import { Creator } from "../typings/Creator";
6
+
7
+ /**
8
+ * Exception manager for HTTP server.
9
+ *
10
+ * `ExceptionManager` is an utility class who can insert or erase custom error class with
11
+ * its convertion method to a regular {@link nest.HttpException} instance.
12
+ *
13
+ * If you define an API function through {@link TypedRoute} or {@link EncryptedRoute}
14
+ * instead of the basic router decorator functions like {@link nest.Get} or
15
+ * {@link nest.Post} and the API function throws a custom error whose class has been
16
+ * {@link ExceptionManager.insert inserted} in this `EntityManager`, the error would be
17
+ * automatically converted to the regular {@link nest.HttpException} instance by the
18
+ * {@link ExceptionManager.Closure} function.
19
+ *
20
+ * Therefore, with this `ExceptionManager` and {@link TypedRoute} or {@link EncryptedRoute},
21
+ * you can manage your custom error classes much systemtically. You can avoid 500 internal
22
+ * server error or hard coding implementation about the custom error classes.
23
+ *
24
+ * Below error classes are defaultly configured in this `ExceptionManager`
25
+ *
26
+ * - `typia.TypeGuardError`
27
+ * - `@nestia/fetcher.HttpError`
28
+ *
29
+ * @author Jeongho Nam - https://github.com/samchon
30
+ */
31
+ export namespace ExceptionManager {
32
+ /**
33
+ * Insert an error class with converter.
34
+ *
35
+ * If you've inserted an duplicated error class, the closure would be overwritten.
36
+ *
37
+ * @param creator Target error class
38
+ * @param closure A closure function converting to the `HttpException` class
39
+ */
40
+ export function insert<T extends Error>(
41
+ creator: Creator<T>,
42
+ closure: Closure<T>,
43
+ ): void {
44
+ const index: number = tuples.findIndex((tuple) => tuple[0] === creator);
45
+ if (index !== -1) tuples.splice(index, 1);
46
+
47
+ tuples.push([creator, closure]);
48
+ tuples.sort(([x], [y]) => (x.prototype instanceof y ? -1 : 1));
49
+ }
50
+
51
+ /**
52
+ * Erase an error class.
53
+ *
54
+ * @param creator Target error class
55
+ * @returns Whether be erased or not
56
+ */
57
+ export function erase<T extends Error>(creator: Creator<T>): boolean {
58
+ const index: number = tuples.findIndex((tuple) => tuple[0] === creator);
59
+ if (index === -1) return false;
60
+
61
+ tuples.splice(index, 1);
62
+ return true;
63
+ }
64
+
65
+ export function on(closure: (error: any) => any): void {
66
+ listeners.add(closure);
67
+ }
68
+
69
+ export function off(closure: (error: any) => any): void {
70
+ listeners.delete(closure);
71
+ }
72
+
73
+ /**
74
+ * Type of a closure function converting to the regular {@link nest.HttpException}.
75
+ *
76
+ * `ExceptionManager.Closure` is a type of closure function who are converting from
77
+ * custom error to the regular {@link nest.HttpException} instance. It would be used
78
+ * in the {@link ExceptionManager} with {@link TypedRoute} or {@link EncryptedRoute}.
79
+ */
80
+ export interface Closure<T extends Error> {
81
+ /**
82
+ * Error converter.
83
+ *
84
+ * Convert from custom error to the regular {@link nest.HttpException} instance.
85
+ *
86
+ * @param exception Custom error instance
87
+ * @return Regular {@link nest.HttpException} instance
88
+ */
89
+ (exception: T): HttpException;
90
+ }
91
+
92
+ /**
93
+ * @internal
94
+ */
95
+ export const tuples: Array<[Creator<any>, Closure<any>]> = [];
96
+
97
+ /**
98
+ * @internal
99
+ */
100
+ export const listeners: Set<(error: any) => any> = new Set();
101
+ }
102
+
103
+ ExceptionManager.insert(
104
+ TypeGuardError,
105
+ (error) =>
106
+ new HttpException(
107
+ {
108
+ path: error.path,
109
+ reason: error.message,
110
+ message: "Request message is not following the promised type.",
111
+ },
112
+ 400,
113
+ ),
114
+ );
115
+
116
+ ExceptionManager.insert(
117
+ HttpError,
118
+ (error) =>
119
+ new HttpException(
120
+ {
121
+ path: error.path,
122
+ message: error.message,
123
+ },
124
+ error.status,
125
+ ),
126
+ );
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @internal
3
+ */
4
+ export class Singleton<T> {
5
+ private value_: T | object;
6
+
7
+ public constructor(private readonly closure_: () => T) {
8
+ this.value_ = NOT_MOUNTED_YET;
9
+ }
10
+
11
+ public get(): T {
12
+ if (this.value_ === NOT_MOUNTED_YET) this.value_ = this.closure_();
13
+ return this.value_ as T;
14
+ }
15
+ }
16
+
17
+ /**
18
+ * @internal
19
+ */
20
+ const NOT_MOUNTED_YET = {};