@adaas/a-server 0.0.19 → 0.0.20

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 (172) hide show
  1. package/dist/index.d.mts +739 -0
  2. package/dist/index.d.ts +739 -36
  3. package/dist/index.js +1904 -102
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +1862 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/package.json +5 -3
  8. package/src/components/A-ServerLogger/A_ServerLogger.component.ts +1 -1
  9. package/src/index.ts +75 -0
  10. package/tsconfig.build.json +9 -43
  11. package/tsconfig.json +1 -1
  12. package/tsup.config.ts +15 -0
  13. package/dist/src/channels/A-Http/A-Http.channel.constants.d.ts +0 -5
  14. package/dist/src/channels/A-Http/A-Http.channel.constants.js +0 -10
  15. package/dist/src/channels/A-Http/A-Http.channel.constants.js.map +0 -1
  16. package/dist/src/channels/A-Http/A-Http.channel.d.ts +0 -29
  17. package/dist/src/channels/A-Http/A-Http.channel.error.d.ts +0 -4
  18. package/dist/src/channels/A-Http/A-Http.channel.error.js +0 -9
  19. package/dist/src/channels/A-Http/A-Http.channel.error.js.map +0 -1
  20. package/dist/src/channels/A-Http/A-Http.channel.js +0 -154
  21. package/dist/src/channels/A-Http/A-Http.channel.js.map +0 -1
  22. package/dist/src/channels/A-Http/A-Http.channel.types.d.ts +0 -59
  23. package/dist/src/channels/A-Http/A-Http.channel.types.js +0 -3
  24. package/dist/src/channels/A-Http/A-Http.channel.types.js.map +0 -1
  25. package/dist/src/channels/A-Websockets/A-Websockets.channel.d.ts +0 -4
  26. package/dist/src/channels/A-Websockets/A-Websockets.channel.js +0 -22
  27. package/dist/src/channels/A-Websockets/A-Websockets.channel.js.map +0 -1
  28. package/dist/src/components/A-CommandController/A-CommandController.component.d.ts +0 -8
  29. package/dist/src/components/A-CommandController/A-CommandController.component.js +0 -55
  30. package/dist/src/components/A-CommandController/A-CommandController.component.js.map +0 -1
  31. package/dist/src/components/A-Controller/A-Controller.component.d.ts +0 -9
  32. package/dist/src/components/A-Controller/A-Controller.component.js +0 -60
  33. package/dist/src/components/A-Controller/A-Controller.component.js.map +0 -1
  34. package/dist/src/components/A-Controller/A-Controller.component.types.d.ts +0 -0
  35. package/dist/src/components/A-Controller/A-Controller.component.types.js +0 -2
  36. package/dist/src/components/A-Controller/A-Controller.component.types.js.map +0 -1
  37. package/dist/src/components/A-EntityController/A-EntityController.component.d.ts +0 -26
  38. package/dist/src/components/A-EntityController/A-EntityController.component.js +0 -226
  39. package/dist/src/components/A-EntityController/A-EntityController.component.js.map +0 -1
  40. package/dist/src/components/A-EntityController/A-EntityController.component.types.d.ts +0 -0
  41. package/dist/src/components/A-EntityController/A-EntityController.component.types.js +0 -2
  42. package/dist/src/components/A-EntityController/A-EntityController.component.types.js.map +0 -1
  43. package/dist/src/components/A-EntityRepository/A-EntityRepository.component.d.ts +0 -9
  44. package/dist/src/components/A-EntityRepository/A-EntityRepository.component.js +0 -118
  45. package/dist/src/components/A-EntityRepository/A-EntityRepository.component.js.map +0 -1
  46. package/dist/src/components/A-EntityRepository/A-EntityRepository.error.d.ts +0 -0
  47. package/dist/src/components/A-EntityRepository/A-EntityRepository.error.js +0 -2
  48. package/dist/src/components/A-EntityRepository/A-EntityRepository.error.js.map +0 -1
  49. package/dist/src/components/A-EntityRepository/A-EntityRepository.types.d.ts +0 -0
  50. package/dist/src/components/A-EntityRepository/A-EntityRepository.types.js +0 -2
  51. package/dist/src/components/A-EntityRepository/A-EntityRepository.types.js.map +0 -1
  52. package/dist/src/components/A-ListingController/A-ListingController.component.d.ts +0 -10
  53. package/dist/src/components/A-ListingController/A-ListingController.component.js +0 -72
  54. package/dist/src/components/A-ListingController/A-ListingController.component.js.map +0 -1
  55. package/dist/src/components/A-ListingController/A-ListingController.component.types.d.ts +0 -0
  56. package/dist/src/components/A-ListingController/A-ListingController.component.types.js +0 -2
  57. package/dist/src/components/A-ListingController/A-ListingController.component.types.js.map +0 -1
  58. package/dist/src/components/A-Router/A-Router.component.d.ts +0 -63
  59. package/dist/src/components/A-Router/A-Router.component.js +0 -221
  60. package/dist/src/components/A-Router/A-Router.component.js.map +0 -1
  61. package/dist/src/components/A-Router/A-Router.component.types.d.ts +0 -26
  62. package/dist/src/components/A-Router/A-Router.component.types.js +0 -17
  63. package/dist/src/components/A-Router/A-Router.component.types.js.map +0 -1
  64. package/dist/src/components/A-ServerCORS/A_ServerCORS.component.d.ts +0 -9
  65. package/dist/src/components/A-ServerCORS/A_ServerCORS.component.defaults.d.ts +0 -2
  66. package/dist/src/components/A-ServerCORS/A_ServerCORS.component.defaults.js +0 -11
  67. package/dist/src/components/A-ServerCORS/A_ServerCORS.component.defaults.js.map +0 -1
  68. package/dist/src/components/A-ServerCORS/A_ServerCORS.component.js +0 -70
  69. package/dist/src/components/A-ServerCORS/A_ServerCORS.component.js.map +0 -1
  70. package/dist/src/components/A-ServerCORS/A_ServerCORS.component.types.d.ts +0 -7
  71. package/dist/src/components/A-ServerCORS/A_ServerCORS.component.types.js +0 -3
  72. package/dist/src/components/A-ServerCORS/A_ServerCORS.component.types.js.map +0 -1
  73. package/dist/src/components/A-ServerError/A-ServerError.class.d.ts +0 -7
  74. package/dist/src/components/A-ServerError/A-ServerError.class.js +0 -88
  75. package/dist/src/components/A-ServerError/A-ServerError.class.js.map +0 -1
  76. package/dist/src/components/A-ServerError/A-ServerError.constants.d.ts +0 -0
  77. package/dist/src/components/A-ServerError/A-ServerError.constants.js +0 -2
  78. package/dist/src/components/A-ServerError/A-ServerError.constants.js.map +0 -1
  79. package/dist/src/components/A-ServerError/A-ServerError.types.d.ts +0 -13
  80. package/dist/src/components/A-ServerError/A-ServerError.types.js +0 -3
  81. package/dist/src/components/A-ServerError/A-ServerError.types.js.map +0 -1
  82. package/dist/src/components/A-ServerHealthMonitor/A-ServerHealthMonitor.component.d.ts +0 -7
  83. package/dist/src/components/A-ServerHealthMonitor/A-ServerHealthMonitor.component.js +0 -81
  84. package/dist/src/components/A-ServerHealthMonitor/A-ServerHealthMonitor.component.js.map +0 -1
  85. package/dist/src/components/A-ServerHealthMonitor/A-ServerHealthMonitor.component.types.d.ts +0 -0
  86. package/dist/src/components/A-ServerHealthMonitor/A-ServerHealthMonitor.component.types.js +0 -2
  87. package/dist/src/components/A-ServerHealthMonitor/A-ServerHealthMonitor.component.types.js.map +0 -1
  88. package/dist/src/components/A-ServerLogger/A-ServerLogger.constants.d.ts +0 -22
  89. package/dist/src/components/A-ServerLogger/A-ServerLogger.constants.js +0 -31
  90. package/dist/src/components/A-ServerLogger/A-ServerLogger.constants.js.map +0 -1
  91. package/dist/src/components/A-ServerLogger/A_ServerLogger.component.d.ts +0 -43
  92. package/dist/src/components/A-ServerLogger/A_ServerLogger.component.js +0 -167
  93. package/dist/src/components/A-ServerLogger/A_ServerLogger.component.js.map +0 -1
  94. package/dist/src/components/A-ServerLogger/A_ServerLogger.component.types.d.ts +0 -9
  95. package/dist/src/components/A-ServerLogger/A_ServerLogger.component.types.js +0 -3
  96. package/dist/src/components/A-ServerLogger/A_ServerLogger.component.types.js.map +0 -1
  97. package/dist/src/components/A-ServerProxy/A-ServerProxy.component.d.ts +0 -9
  98. package/dist/src/components/A-ServerProxy/A-ServerProxy.component.js +0 -88
  99. package/dist/src/components/A-ServerProxy/A-ServerProxy.component.js.map +0 -1
  100. package/dist/src/components/A-StaticLoader/A-StaticLoader.component.d.ts +0 -12
  101. package/dist/src/components/A-StaticLoader/A-StaticLoader.component.js +0 -126
  102. package/dist/src/components/A-StaticLoader/A-StaticLoader.component.js.map +0 -1
  103. package/dist/src/components/A-StaticLoader/A-StaticLoader.component.types.d.ts +0 -10
  104. package/dist/src/components/A-StaticLoader/A-StaticLoader.component.types.js +0 -109
  105. package/dist/src/components/A-StaticLoader/A-StaticLoader.component.types.js.map +0 -1
  106. package/dist/src/constants/env.constants.d.ts +0 -10
  107. package/dist/src/constants/env.constants.js +0 -20
  108. package/dist/src/constants/env.constants.js.map +0 -1
  109. package/dist/src/containers/A-Service/A-Service.container.d.ts +0 -30
  110. package/dist/src/containers/A-Service/A-Service.container.js +0 -200
  111. package/dist/src/containers/A-Service/A-Service.container.js.map +0 -1
  112. package/dist/src/containers/A-Service/A-Service.container.types.d.ts +0 -36
  113. package/dist/src/containers/A-Service/A-Service.container.types.js +0 -27
  114. package/dist/src/containers/A-Service/A-Service.container.types.js.map +0 -1
  115. package/dist/src/context/A-EntityFactory/A-EntityFactory.context.d.ts +0 -39
  116. package/dist/src/context/A-EntityFactory/A-EntityFactory.context.js +0 -69
  117. package/dist/src/context/A-EntityFactory/A-EntityFactory.context.js.map +0 -1
  118. package/dist/src/context/A-EntityFactory/A-EntityFactory.context.types.d.ts +0 -5
  119. package/dist/src/context/A-EntityFactory/A-EntityFactory.context.types.js +0 -3
  120. package/dist/src/context/A-EntityFactory/A-EntityFactory.context.types.js.map +0 -1
  121. package/dist/src/context/A-HttpChannel/A-HttpChannel.context.d.ts +0 -12
  122. package/dist/src/context/A-HttpChannel/A-HttpChannel.context.js +0 -16
  123. package/dist/src/context/A-HttpChannel/A-HttpChannel.context.js.map +0 -1
  124. package/dist/src/context/A-ListQueryFilter/A_ListQueryFilter.context.d.ts +0 -10
  125. package/dist/src/context/A-ListQueryFilter/A_ListQueryFilter.context.js +0 -30
  126. package/dist/src/context/A-ListQueryFilter/A_ListQueryFilter.context.js.map +0 -1
  127. package/dist/src/context/A-ProxyConfig/A_ProxyConfig.constants.d.ts +0 -2
  128. package/dist/src/context/A-ProxyConfig/A_ProxyConfig.constants.js +0 -12
  129. package/dist/src/context/A-ProxyConfig/A_ProxyConfig.constants.js.map +0 -1
  130. package/dist/src/context/A-ProxyConfig/A_ProxyConfig.context.d.ts +0 -29
  131. package/dist/src/context/A-ProxyConfig/A_ProxyConfig.context.js +0 -60
  132. package/dist/src/context/A-ProxyConfig/A_ProxyConfig.context.js.map +0 -1
  133. package/dist/src/context/A-ProxyConfig/A_ProxyConfig.types.d.ts +0 -18
  134. package/dist/src/context/A-ProxyConfig/A_ProxyConfig.types.js +0 -3
  135. package/dist/src/context/A-ProxyConfig/A_ProxyConfig.types.js.map +0 -1
  136. package/dist/src/context/A-Server/A_Server.context.d.ts +0 -17
  137. package/dist/src/context/A-Server/A_Server.context.js +0 -22
  138. package/dist/src/context/A-Server/A_Server.context.js.map +0 -1
  139. package/dist/src/context/A-Server/A_Server.context.types.d.ts +0 -7
  140. package/dist/src/context/A-Server/A_Server.context.types.js +0 -3
  141. package/dist/src/context/A-Server/A_Server.context.types.js.map +0 -1
  142. package/dist/src/context/A-StaticConfig/A-StaticConfig.context.d.ts +0 -16
  143. package/dist/src/context/A-StaticConfig/A-StaticConfig.context.js +0 -28
  144. package/dist/src/context/A-StaticConfig/A-StaticConfig.context.js.map +0 -1
  145. package/dist/src/context/A-StaticConfig/A-StaticConfig.context.types.d.ts +0 -0
  146. package/dist/src/context/A-StaticConfig/A-StaticConfig.context.types.js +0 -2
  147. package/dist/src/context/A-StaticConfig/A-StaticConfig.context.types.js.map +0 -1
  148. package/dist/src/entities/A-Request/A-Request.entity.d.ts +0 -31
  149. package/dist/src/entities/A-Request/A-Request.entity.js +0 -125
  150. package/dist/src/entities/A-Request/A-Request.entity.js.map +0 -1
  151. package/dist/src/entities/A-Request/A-Request.entity.types.d.ts +0 -21
  152. package/dist/src/entities/A-Request/A-Request.entity.types.js +0 -12
  153. package/dist/src/entities/A-Request/A-Request.entity.types.js.map +0 -1
  154. package/dist/src/entities/A-Response/A-Response.entity.d.ts +0 -28
  155. package/dist/src/entities/A-Response/A-Response.entity.js +0 -141
  156. package/dist/src/entities/A-Response/A-Response.entity.js.map +0 -1
  157. package/dist/src/entities/A-Response/A-Response.entity.types.d.ts +0 -19
  158. package/dist/src/entities/A-Response/A-Response.entity.types.js +0 -12
  159. package/dist/src/entities/A-Response/A-Response.entity.types.js.map +0 -1
  160. package/dist/src/entities/A-Route/A-Route.entity.d.ts +0 -17
  161. package/dist/src/entities/A-Route/A-Route.entity.js +0 -76
  162. package/dist/src/entities/A-Route/A-Route.entity.js.map +0 -1
  163. package/dist/src/entities/A-Route/A-Route.entity.types.d.ts +0 -0
  164. package/dist/src/entities/A-Route/A-Route.entity.types.js +0 -2
  165. package/dist/src/entities/A-Route/A-Route.entity.types.js.map +0 -1
  166. package/dist/src/entities/A_EntityList/A_EntityList.entity.d.ts +0 -46
  167. package/dist/src/entities/A_EntityList/A_EntityList.entity.js +0 -91
  168. package/dist/src/entities/A_EntityList/A_EntityList.entity.js.map +0 -1
  169. package/dist/src/entities/A_EntityList/A_EntityList.entity.types.d.ts +0 -21
  170. package/dist/src/entities/A_EntityList/A_EntityList.entity.types.js +0 -8
  171. package/dist/src/entities/A_EntityList/A_EntityList.entity.types.js.map +0 -1
  172. package/index.ts +0 -75
package/dist/index.mjs ADDED
@@ -0,0 +1,1862 @@
1
+ import { A_Concept, A_Feature, A_Inject, A_Scope, A_Container, A_Caller, A_Error, A_Entity, ASEID, A_Context, A_IdentityHelper, A_Fragment, A_Component, A_Feature_Define, A_Feature_Extend, A_TypeGuards } from '@adaas/a-concept';
2
+ import { A_Config, A_Logger, A_Channel, A_Manifest } from '@adaas/a-utils';
3
+ import http, { createServer } from 'http';
4
+ import crypto from 'crypto';
5
+ import https from 'https';
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { URL as URL$1 } from 'url';
9
+ import { A_TYPES__EntityFeatures } from '@adaas/a-concept/dist/src/global/A-Entity/A-Entity.constants';
10
+
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __decorateClass = (decorators, target, key, kind) => {
14
+ var result = __getOwnPropDesc(target, key) ;
15
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
16
+ if (decorator = decorators[i])
17
+ result = (decorator(target, key, result) ) || result;
18
+ if (result) __defProp(target, key, result);
19
+ return result;
20
+ };
21
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
22
+
23
+ // src/containers/A-Service/A-Service.container.types.ts
24
+ var A_SERVER_TYPES__ServerFeature = /* @__PURE__ */ ((A_SERVER_TYPES__ServerFeature2) => {
25
+ A_SERVER_TYPES__ServerFeature2["beforeStart"] = "beforeStart";
26
+ A_SERVER_TYPES__ServerFeature2["afterStart"] = "afterStart";
27
+ A_SERVER_TYPES__ServerFeature2["beforeStop"] = "beforeStop";
28
+ A_SERVER_TYPES__ServerFeature2["afterStop"] = "afterStop";
29
+ A_SERVER_TYPES__ServerFeature2["beforeRequest"] = "beforeRequest";
30
+ A_SERVER_TYPES__ServerFeature2["onRequest"] = "onRequest";
31
+ A_SERVER_TYPES__ServerFeature2["afterRequest"] = "afterRequest";
32
+ return A_SERVER_TYPES__ServerFeature2;
33
+ })(A_SERVER_TYPES__ServerFeature || {});
34
+ var A_SERVER_TYPES__ServerMethod = /* @__PURE__ */ ((A_SERVER_TYPES__ServerMethod2) => {
35
+ A_SERVER_TYPES__ServerMethod2["GET"] = "GET";
36
+ A_SERVER_TYPES__ServerMethod2["POST"] = "POST";
37
+ A_SERVER_TYPES__ServerMethod2["PUT"] = "PUT";
38
+ A_SERVER_TYPES__ServerMethod2["DELETE"] = "DELETE";
39
+ A_SERVER_TYPES__ServerMethod2["PATCH"] = "PATCH";
40
+ A_SERVER_TYPES__ServerMethod2["OPTIONS"] = "OPTIONS";
41
+ A_SERVER_TYPES__ServerMethod2["HEAD"] = "HEAD";
42
+ A_SERVER_TYPES__ServerMethod2["CONNECT"] = "CONNECT";
43
+ A_SERVER_TYPES__ServerMethod2["TRACE"] = "TRACE";
44
+ A_SERVER_TYPES__ServerMethod2["DEFAULT"] = "DEFAULT";
45
+ return A_SERVER_TYPES__ServerMethod2;
46
+ })(A_SERVER_TYPES__ServerMethod || {});
47
+ var A_HTTPChannel_RequestContext = class extends A_Fragment {
48
+ constructor(params) {
49
+ super();
50
+ const {
51
+ method,
52
+ url,
53
+ data,
54
+ config
55
+ } = params;
56
+ this.url = url;
57
+ this.method = method;
58
+ this.data = data;
59
+ this.config = config;
60
+ }
61
+ };
62
+
63
+ // src/channels/A-Http/A-Http.channel.constants.ts
64
+ var A_SERVER_CONSTANTS__A_HttpChannel_Lifecycle = /* @__PURE__ */ ((A_SERVER_CONSTANTS__A_HttpChannel_Lifecycle2) => {
65
+ A_SERVER_CONSTANTS__A_HttpChannel_Lifecycle2["onAfterRequest"] = "onAfterHttpChannelRequest";
66
+ A_SERVER_CONSTANTS__A_HttpChannel_Lifecycle2["onError"] = "onHttpChannelError";
67
+ A_SERVER_CONSTANTS__A_HttpChannel_Lifecycle2["onBeforeRequest"] = "onBeforeHttpChannelRequest";
68
+ return A_SERVER_CONSTANTS__A_HttpChannel_Lifecycle2;
69
+ })(A_SERVER_CONSTANTS__A_HttpChannel_Lifecycle || {});
70
+ var A_ServerError = class extends A_Error {
71
+ constructor() {
72
+ super(...arguments);
73
+ this.status = 500;
74
+ }
75
+ // constructor(
76
+ // /**
77
+ // * A_Error Constructor params
78
+ // */
79
+ // params: A_SERVER_TYPES__ServerError_Init
80
+ // )
81
+ // constructor(
82
+ // /**
83
+ // * HTTP Status Code of the error
84
+ // */
85
+ // status: number,
86
+ // /**
87
+ // * Error message
88
+ // */
89
+ // message: string
90
+ // )
91
+ // constructor(
92
+ // /**
93
+ // * Original JS Error
94
+ // */
95
+ // error: Error
96
+ // )
97
+ // constructor(
98
+ // /**
99
+ // * HTTP Status Code of the error
100
+ // */
101
+ // status: number,
102
+ // /**
103
+ // * Error message
104
+ // */
105
+ // title: string,
106
+ // /**
107
+ // * Detailed description of the error
108
+ // */
109
+ // description: string
110
+ // )
111
+ // constructor(
112
+ // param1: A_SERVER_TYPES__ServerError_Init | Error | string | A_Error | number,
113
+ // param2?: string | A_Error,
114
+ // param3?: string
115
+ // ) {
116
+ // switch (true) {
117
+ // case typeof param1 === 'number':
118
+ // if (typeof param2 === 'string' && param3) {
119
+ // super({
120
+ // title: param2,
121
+ // description: param3
122
+ // });
123
+ // }
124
+ // else if (param2 instanceof A_Error) {
125
+ // super(param2);
126
+ // }
127
+ // else {
128
+ // super();
129
+ // }
130
+ // this.status = param1;
131
+ // break;
132
+ // case param1 instanceof A_Error:
133
+ // super (param1);
134
+ // break;
135
+ // case param1 instanceof Error:
136
+ // super (param1);
137
+ // break;
138
+ // default:
139
+ // break;
140
+ // }
141
+ // }
142
+ fromConstructor(params) {
143
+ super.fromConstructor(params);
144
+ if (params.status) {
145
+ this.status = params.status;
146
+ }
147
+ }
148
+ toJSON() {
149
+ return {
150
+ ...super.toJSON(),
151
+ status: this.status
152
+ };
153
+ }
154
+ };
155
+ var A_HTTPChannelError = class extends A_Error {
156
+ };
157
+ A_HTTPChannelError.HttpRequestError = "HTTP Channel Request Error";
158
+
159
+ // src/channels/A-Http/A-Http.channel.ts
160
+ var A_HTTPChannel = class extends A_Channel {
161
+ async connect() {
162
+ return;
163
+ }
164
+ /**
165
+ * Allows to send an HTTP request without expecting a response
166
+ *
167
+ * @param params
168
+ */
169
+ async send(params) {
170
+ this.request(params);
171
+ }
172
+ /**
173
+ * Makes an HTTP request
174
+ *
175
+ * @param params
176
+ * @returns
177
+ */
178
+ async request(params) {
179
+ const { method, url, data, config } = params;
180
+ await this.initialize;
181
+ this._processing = true;
182
+ const fullUrl = this.buildURL(url, config?.params);
183
+ const requestScope = new A_Scope({ name: `a-http-channel-request-scope-${method}-${url}-${Date.now()}` });
184
+ const context = new A_HTTPChannel_RequestContext({
185
+ method,
186
+ url,
187
+ data,
188
+ config
189
+ });
190
+ requestScope.inherit(A_Context.scope(this));
191
+ requestScope.register(context);
192
+ try {
193
+ await this.call("onBeforeHttpChannelRequest" /* onBeforeRequest */, requestScope);
194
+ const headers = {
195
+ "Content-Type": "application/json",
196
+ ...config?.headers
197
+ };
198
+ const options = {
199
+ method,
200
+ headers
201
+ };
202
+ if (data && method !== "GET" /* GET */) {
203
+ options.body = JSON.stringify(data);
204
+ }
205
+ const response = await fetch(fullUrl, options);
206
+ if (!response.ok) {
207
+ throw new A_ServerError({
208
+ status: response.status,
209
+ title: response.statusText,
210
+ description: `HTTP request to ${fullUrl} failed with status ${response.status}`
211
+ });
212
+ }
213
+ context.result = config?.params?.responseType === "text" ? await response.text() : config?.params?.responseType === "blob" ? await response.blob() : await response.json();
214
+ await this.call("onAfterHttpChannelRequest" /* onAfterRequest */, requestScope);
215
+ this._processing = false;
216
+ return context;
217
+ } catch (error) {
218
+ this._processing = false;
219
+ context.error = error;
220
+ await this.call("onHttpChannelError" /* onError */, requestScope);
221
+ if (config?.throwOnError === false)
222
+ return context;
223
+ else
224
+ throw error;
225
+ }
226
+ }
227
+ async post(url, body, config) {
228
+ return this.request(
229
+ {
230
+ method: "POST" /* POST */,
231
+ url,
232
+ data: body,
233
+ config
234
+ }
235
+ );
236
+ }
237
+ async get(url, params, config) {
238
+ return this.request(
239
+ {
240
+ method: "GET" /* GET */,
241
+ url,
242
+ config: {
243
+ ...config,
244
+ params
245
+ }
246
+ }
247
+ );
248
+ }
249
+ async put(url, body, config) {
250
+ return this.request({
251
+ method: "PUT" /* PUT */,
252
+ url,
253
+ data: body,
254
+ config
255
+ });
256
+ }
257
+ async delete(url, params, config) {
258
+ return this.request({
259
+ method: "DELETE" /* DELETE */,
260
+ url,
261
+ data: params,
262
+ config
263
+ });
264
+ }
265
+ buildURL(path2 = "", params = {}) {
266
+ if (!this.baseUrl)
267
+ throw new A_HTTPChannelError(
268
+ A_HTTPChannelError.HttpRequestError,
269
+ "Base URL is not set for HTTP Channel"
270
+ );
271
+ const url = new URL(`${this.baseUrl}${path2.startsWith("/") ? path2 : `/${path2}`}`);
272
+ Object.keys(params).forEach((key) => {
273
+ if (params[key] !== void 0 && params[key] !== null) {
274
+ url.searchParams.append(key, params[key]);
275
+ }
276
+ });
277
+ return url.toString();
278
+ }
279
+ };
280
+
281
+ // src/constants/env.constants.ts
282
+ var A_SERVER_CONSTANTS__DEFAULT_ENV_VARIABLES = {
283
+ // ----------------------------------------------------------
284
+ // A-Server Environment Variables
285
+ // ----------------------------------------------------------
286
+ // These environment variables are used by A-Server to configure the application
287
+ // ----------------------------------------------------------
288
+ /**
289
+ * Port for the server to listen on
290
+ * [!] Default is 3000
291
+ * @default 3000
292
+ */
293
+ A_SERVER_PORT: "A_SERVER_PORT"
294
+ };
295
+ var A_SERVER_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY = [
296
+ A_SERVER_CONSTANTS__DEFAULT_ENV_VARIABLES.A_SERVER_PORT
297
+ ];
298
+ var A_Server = class extends A_Fragment {
299
+ constructor(params) {
300
+ super(params);
301
+ this._routes = [];
302
+ this.port = params.port;
303
+ this.name = params.name;
304
+ this.version = params.version || "v1";
305
+ this._routes = params.routes || this._routes;
306
+ }
307
+ /**
308
+ * A list of routes that the server will listen to
309
+ */
310
+ get routes() {
311
+ return this._routes;
312
+ }
313
+ };
314
+
315
+ // src/entities/A-Request/A-Request.entity.types.ts
316
+ var A_SERVER_TYPES__RequestEvent = /* @__PURE__ */ ((A_SERVER_TYPES__RequestEvent2) => {
317
+ A_SERVER_TYPES__RequestEvent2["Error"] = "error";
318
+ A_SERVER_TYPES__RequestEvent2["Finish"] = "finish";
319
+ A_SERVER_TYPES__RequestEvent2["Data"] = "data";
320
+ A_SERVER_TYPES__RequestEvent2["End"] = "end";
321
+ A_SERVER_TYPES__RequestEvent2["Close"] = "close";
322
+ return A_SERVER_TYPES__RequestEvent2;
323
+ })(A_SERVER_TYPES__RequestEvent || {});
324
+
325
+ // src/entities/A-Route/A-Route.entity.ts
326
+ var A_Route = class {
327
+ constructor(param1, param2) {
328
+ this.url = param1 instanceof RegExp ? param1.source : param1;
329
+ this.method = param2 || "GET";
330
+ }
331
+ /**
332
+ * returns path only without query and hash
333
+ */
334
+ get path() {
335
+ const p = this.url.split("?")[0].split("#")[0];
336
+ return p.endsWith("/") ? p.slice(0, -1) : p;
337
+ }
338
+ get params() {
339
+ return this.path.match(/:([^\/]+)/g)?.map((param) => param.slice(1)) || [];
340
+ }
341
+ extractParams(url) {
342
+ const cleanUrl = url.split("?")[0];
343
+ const urlSegments = cleanUrl.split("/").filter(Boolean);
344
+ const maskSegments = this.path.split("/").filter(Boolean);
345
+ const params = {};
346
+ for (let i = 0; i < maskSegments.length; i++) {
347
+ const maskSegment = maskSegments[i];
348
+ const urlSegment = urlSegments[i];
349
+ if (maskSegment.startsWith(":")) {
350
+ const paramName = maskSegment.slice(1);
351
+ params[paramName] = urlSegment;
352
+ } else if (maskSegment !== urlSegment) {
353
+ return {};
354
+ }
355
+ }
356
+ return params;
357
+ }
358
+ extractQuery(url) {
359
+ const query = {};
360
+ const queryString = url.split("?")[1];
361
+ if (!queryString) return query;
362
+ const cleanQuery = queryString.split("#")[0];
363
+ for (const pair of cleanQuery.split("&")) {
364
+ if (!pair) continue;
365
+ const [key, value = ""] = pair.split("=");
366
+ query[decodeURIComponent(key)] = decodeURIComponent(value);
367
+ }
368
+ return query;
369
+ }
370
+ toString() {
371
+ return `${this.method}::${this.path}`;
372
+ }
373
+ toRegExp() {
374
+ return new RegExp(`^${this.method}::${this.path.replace(/\/:([^\/]+)/g, "/([^/]+)")}$`);
375
+ }
376
+ toAFeatureExtension(extensionScope = []) {
377
+ return new RegExp(`^${extensionScope.length ? `(${extensionScope.join("|")})` : ".*"}\\.${this.method}::${this.path.replace(/\/:([^\/]+)/g, "/([^/]+)")}$`);
378
+ }
379
+ };
380
+
381
+ // src/entities/A-Request/A-Request.entity.ts
382
+ var A_Request = class extends A_Entity {
383
+ constructor() {
384
+ super(...arguments);
385
+ this.body = {};
386
+ this.params = {};
387
+ this.query = {};
388
+ /**
389
+ * Duration of the request in milliseconds
390
+ */
391
+ this.duration = 0;
392
+ }
393
+ static get namespace() {
394
+ return "a-server";
395
+ }
396
+ fromNew(newEntity) {
397
+ this.req = newEntity.request;
398
+ this.aseid = new ASEID({
399
+ concept: A_Context.root.name,
400
+ scope: newEntity.scope,
401
+ entity: this.constructor.entity,
402
+ id: newEntity.id
403
+ });
404
+ }
405
+ get startedAt() {
406
+ const timeId = A_IdentityHelper.parseTimeId(this.aseid.id.split("-")[0]);
407
+ return timeId ? new Date(timeId.timestamp) : void 0;
408
+ }
409
+ // Getter for request URL
410
+ get url() {
411
+ return this.req.url;
412
+ }
413
+ // Getter for request method
414
+ get method() {
415
+ return String(this.req.method).toUpperCase() || "DEFAULT";
416
+ }
417
+ get headers() {
418
+ return this.req.headers;
419
+ }
420
+ get route() {
421
+ return new A_Route(this.url, this.method);
422
+ }
423
+ pipe(destination, options) {
424
+ return this.req.pipe(destination, options);
425
+ }
426
+ async init() {
427
+ this.req.on("error", async (err) => {
428
+ this.error = new A_ServerError(err);
429
+ await this.call("error" /* Error */);
430
+ });
431
+ this.params = this.extractParams(this.url);
432
+ this.query = this.extractQuery(this.url);
433
+ }
434
+ extractParams(url) {
435
+ const cleanUrl = url.split("?")[0];
436
+ const urlSegments = cleanUrl.split("/").filter(Boolean);
437
+ const maskSegments = this.url.split("/").filter(Boolean);
438
+ const params = {};
439
+ for (let i = 0; i < maskSegments.length; i++) {
440
+ const maskSegment = maskSegments[i];
441
+ const urlSegment = urlSegments[i];
442
+ if (maskSegment.startsWith(":")) {
443
+ const paramName = maskSegment.slice(1);
444
+ params[paramName] = urlSegment;
445
+ } else if (maskSegment !== urlSegment) {
446
+ return {};
447
+ }
448
+ }
449
+ return params;
450
+ }
451
+ extractQuery(url) {
452
+ const query = {};
453
+ const queryString = url.split("?")[1];
454
+ if (!queryString) return query;
455
+ const cleanQuery = queryString.split("#")[0];
456
+ for (const pair of cleanQuery.split("&")) {
457
+ if (!pair) continue;
458
+ const [key, value = ""] = pair.split("=");
459
+ query[decodeURIComponent(key)] = decodeURIComponent(value);
460
+ }
461
+ return query;
462
+ }
463
+ parseBody() {
464
+ return new Promise((resolve, reject) => {
465
+ let body = "";
466
+ this.req.on("data", (chunk) => body += chunk);
467
+ this.req.on("end", () => {
468
+ try {
469
+ resolve(JSON.parse(body));
470
+ } catch (err) {
471
+ reject(err);
472
+ }
473
+ });
474
+ this.req.on("error", reject);
475
+ });
476
+ }
477
+ };
478
+
479
+ // src/entities/A-Response/A-Response.entity.types.ts
480
+ var A_SERVER_TYPES__ResponseEvent = /* @__PURE__ */ ((A_SERVER_TYPES__ResponseEvent2) => {
481
+ A_SERVER_TYPES__ResponseEvent2["Error"] = "error";
482
+ A_SERVER_TYPES__ResponseEvent2["Finish"] = "finish";
483
+ A_SERVER_TYPES__ResponseEvent2["Data"] = "data";
484
+ A_SERVER_TYPES__ResponseEvent2["End"] = "end";
485
+ A_SERVER_TYPES__ResponseEvent2["Close"] = "close";
486
+ return A_SERVER_TYPES__ResponseEvent2;
487
+ })(A_SERVER_TYPES__ResponseEvent || {});
488
+ var A_Response = class extends A_Entity {
489
+ constructor() {
490
+ super(...arguments);
491
+ /**
492
+ * Duration of the request in milliseconds
493
+ */
494
+ this.duration = 0;
495
+ this.data = /* @__PURE__ */ new Map();
496
+ }
497
+ fromNew(newEntity) {
498
+ this.res = newEntity.response;
499
+ this.aseid = new ASEID({
500
+ concept: A_Context.root.name,
501
+ scope: newEntity.scope,
502
+ entity: this.constructor.entity,
503
+ id: newEntity.id
504
+ });
505
+ }
506
+ get headersSent() {
507
+ return this.res.headersSent;
508
+ }
509
+ get original() {
510
+ return this.res;
511
+ }
512
+ get statusCode() {
513
+ return this.res.statusCode;
514
+ }
515
+ async init() {
516
+ const startTime = process.hrtime();
517
+ this.res.on("finish", async () => {
518
+ const elapsedTime = process.hrtime(startTime);
519
+ const elapsedMilliseconds = elapsedTime[0] * 1e3 + elapsedTime[1] / 1e6;
520
+ this.duration = elapsedMilliseconds;
521
+ await this.call("finish" /* Finish */);
522
+ });
523
+ this.res.on("close", async () => {
524
+ await this.call("close" /* Close */);
525
+ });
526
+ }
527
+ failed(error) {
528
+ switch (true) {
529
+ case error instanceof A_ServerError:
530
+ this.error = error;
531
+ break;
532
+ case error instanceof A_Error:
533
+ this.error = new A_ServerError(error);
534
+ break;
535
+ default:
536
+ this.error = new A_ServerError(error);
537
+ break;
538
+ }
539
+ return this.status(this.error.status).json(this.error);
540
+ }
541
+ // Send a plain text or JSON response
542
+ send(data = this.toResponse()) {
543
+ const logger = A_Context.scope(this).resolve(A_Logger);
544
+ if (this.headersSent) {
545
+ logger.warning("Response headers already sent, cannot send response again.");
546
+ return;
547
+ }
548
+ try {
549
+ switch (true) {
550
+ case (!!data && typeof data === "object"):
551
+ return this.json(data);
552
+ case (!!data && typeof data === "string"):
553
+ this.res.setHeader("Content-Type", "text/plain");
554
+ this.res.writeHead(this.statusCode);
555
+ this.res.end(data);
556
+ return;
557
+ default:
558
+ this.res.writeHead(this.statusCode);
559
+ this.res.end(data);
560
+ return;
561
+ }
562
+ } catch (error) {
563
+ logger.warning("Response send error:", error);
564
+ }
565
+ }
566
+ destroy(error, scope) {
567
+ this.res.end();
568
+ return super.destroy(scope);
569
+ }
570
+ // Explicit JSON response
571
+ json(data = this.toResponse()) {
572
+ const logger = A_Context.scope(this).resolve(A_Logger);
573
+ if (this.headersSent) {
574
+ logger.warning("Response headers already sent, cannot send response again.");
575
+ return;
576
+ }
577
+ this.res.setHeader("Content-Type", "application/json");
578
+ this.res.writeHead(this.statusCode);
579
+ this.res.end(JSON.stringify(data));
580
+ }
581
+ // Set HTTP status code
582
+ status(code) {
583
+ this.res.statusCode = code;
584
+ return this;
585
+ }
586
+ writeHead(statusCode, headers) {
587
+ this.res.writeHead(statusCode, headers);
588
+ }
589
+ setHeader(key, value) {
590
+ this.res.setHeader(key, value);
591
+ }
592
+ getHeader(key) {
593
+ return this.res.getHeader(key);
594
+ }
595
+ add(key, data) {
596
+ this.data.set(key, data);
597
+ }
598
+ toResponse() {
599
+ return Array.from(this.data.entries()).reduce((acc, [key, value]) => {
600
+ if (value instanceof A_Entity)
601
+ acc[key] = value.toJSON();
602
+ else
603
+ acc[key] = value;
604
+ return acc;
605
+ }, {});
606
+ }
607
+ };
608
+ var A_Service = class extends A_Container {
609
+ async load() {
610
+ let config;
611
+ if (!this.scope.has(A_Config)) {
612
+ const config2 = new A_Config({
613
+ variables: [...Array.from(A_SERVER_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY)],
614
+ defaults: {
615
+ A_SERVER_PORT: 3e3
616
+ }
617
+ });
618
+ this.scope.register(config2);
619
+ }
620
+ config = this.scope.resolve(A_Config);
621
+ if (!this.scope.has(A_Server)) {
622
+ new A_Server({
623
+ port: config.get("A_SERVER_PORT"),
624
+ name: this.name,
625
+ version: "v1"
626
+ });
627
+ }
628
+ this.port = config.get("A_SERVER_PORT");
629
+ this.server = createServer(this.onRequest.bind(this));
630
+ }
631
+ listen() {
632
+ return new Promise((resolve, reject) => {
633
+ this.server.listen(this.port, () => {
634
+ resolve();
635
+ });
636
+ });
637
+ }
638
+ close() {
639
+ return new Promise((resolve, reject) => {
640
+ this.server.close(() => {
641
+ resolve();
642
+ });
643
+ });
644
+ }
645
+ /**
646
+ * Start the server
647
+ */
648
+ async start() {
649
+ await this.beforeStart();
650
+ await this.listen();
651
+ await this.afterStart();
652
+ }
653
+ async beforeStart() {
654
+ }
655
+ async afterStart() {
656
+ }
657
+ /**
658
+ * Stop service
659
+ */
660
+ async stop() {
661
+ await this.call("beforeStop" /* beforeStop */);
662
+ await this.server.close();
663
+ await this.call("afterStop" /* afterStop */);
664
+ }
665
+ async beforeRequest(scope) {
666
+ }
667
+ async afterRequest(scope) {
668
+ }
669
+ async onRequest(request, response) {
670
+ const scope = new A_Scope({
671
+ name: `a-server-request::${Date.now()}`
672
+ });
673
+ const { req, res } = await this.convertToAServer(request, response);
674
+ try {
675
+ scope.register(req);
676
+ scope.register(res);
677
+ scope.inherit(this.scope);
678
+ await this.beforeRequest(scope);
679
+ await this.call("onRequest" /* onRequest */, scope);
680
+ await this.afterRequest(scope);
681
+ await res.status(200).send();
682
+ } catch (error) {
683
+ const logger = this.scope.resolve(A_Logger);
684
+ logger.error(error);
685
+ return res.failed(error);
686
+ }
687
+ }
688
+ async convertToAServer(request, response) {
689
+ if (!request.method || !request.url)
690
+ throw new Error("Request method or url is missing");
691
+ const id = this.generateRequestId(request.method, request.url);
692
+ const req = new A_Request({ id, request, scope: this.scope.name });
693
+ const res = new A_Response({ id, response, scope: this.scope.name });
694
+ await req.init();
695
+ await res.init();
696
+ return { req, res };
697
+ }
698
+ generateRequestId(method, url) {
699
+ const hash = crypto.createHash("sha256");
700
+ const timeId = A_IdentityHelper.generateTimeId();
701
+ const randomValue = Math.random().toString();
702
+ hash.update(`${timeId}-${method}-${url}-${randomValue}`);
703
+ return `${timeId}-${hash.digest("hex")}`;
704
+ }
705
+ async beforeStop() {
706
+ }
707
+ async afterStop() {
708
+ }
709
+ };
710
+ __decorateClass([
711
+ A_Concept.Load()
712
+ ], A_Service.prototype, "load");
713
+ __decorateClass([
714
+ A_Concept.Start()
715
+ ], A_Service.prototype, "start");
716
+ __decorateClass([
717
+ A_Feature.Define({ invoke: true })
718
+ ], A_Service.prototype, "beforeStart");
719
+ __decorateClass([
720
+ A_Feature.Define({ invoke: true })
721
+ ], A_Service.prototype, "afterStart");
722
+ __decorateClass([
723
+ A_Concept.Stop()
724
+ ], A_Service.prototype, "stop");
725
+ __decorateClass([
726
+ A_Feature.Define({
727
+ name: "beforeRequest" /* beforeRequest */,
728
+ invoke: true
729
+ })
730
+ ], A_Service.prototype, "beforeRequest");
731
+ __decorateClass([
732
+ A_Feature.Define({
733
+ name: "beforeRequest" /* beforeRequest */,
734
+ invoke: true
735
+ })
736
+ ], A_Service.prototype, "afterRequest");
737
+ __decorateClass([
738
+ A_Feature.Define({
739
+ name: "onRequest" /* onRequest */,
740
+ invoke: false
741
+ })
742
+ ], A_Service.prototype, "onRequest");
743
+ __decorateClass([
744
+ A_Feature.Define({ invoke: true })
745
+ ], A_Service.prototype, "beforeStop");
746
+ __decorateClass([
747
+ A_Feature.Define({ invoke: true })
748
+ ], A_Service.prototype, "afterStop");
749
+
750
+ // src/context/A-ProxyConfig/A_ProxyConfig.constants.ts
751
+ var PROXY_CONFIG_DEFAULTS = {
752
+ path: "/",
753
+ hostname: "localhost",
754
+ port: 80,
755
+ method: "GET",
756
+ headers: {},
757
+ protocol: "http"
758
+ };
759
+
760
+ // src/context/A-ProxyConfig/A_ProxyConfig.context.ts
761
+ var A_ProxyConfig = class extends A_Fragment {
762
+ constructor(configs = {}) {
763
+ super();
764
+ this._configs = Object.entries(configs).map(([path2, config]) => {
765
+ const targetUrl = new URL(typeof config === "string" ? config : config.hostname || "");
766
+ const port = targetUrl.port || (targetUrl.protocol === "https:" ? "443" : "80");
767
+ const prepared = {
768
+ ...PROXY_CONFIG_DEFAULTS,
769
+ ...typeof config === "string" ? {
770
+ path: path2,
771
+ port: parseInt(port),
772
+ protocol: targetUrl.protocol,
773
+ hostname: targetUrl.hostname
774
+ } : config
775
+ };
776
+ return {
777
+ route: new A_Route(prepared.path, prepared.method),
778
+ hostname: prepared.hostname,
779
+ port: prepared.port,
780
+ headers: prepared.headers,
781
+ protocol: prepared.protocol
782
+ };
783
+ });
784
+ }
785
+ /**
786
+ * Returns all configured proxy configs
787
+ *
788
+ */
789
+ get configs() {
790
+ return this._configs;
791
+ }
792
+ /**
793
+ * Checks if a given path is configured in the proxy
794
+ *
795
+ * @param path
796
+ * @returns
797
+ */
798
+ has(path2) {
799
+ return this._configs.some((route) => route.route.toRegExp().test(path2));
800
+ }
801
+ /**
802
+ * Returns the proxy configuration for a given path, if exists
803
+ *
804
+ * @param path
805
+ * @returns
806
+ */
807
+ config(path2) {
808
+ return this._configs.find((route) => route.route.toRegExp().test(path2));
809
+ }
810
+ };
811
+ var A_StaticConfig = class extends A_Fragment {
812
+ constructor(directories = []) {
813
+ super();
814
+ this.directories = directories;
815
+ }
816
+ /**
817
+ * Checks if a given path is configured in the proxy
818
+ *
819
+ * @param path
820
+ * @returns
821
+ */
822
+ has(path2) {
823
+ const found = this.directories.find((dir) => {
824
+ return new RegExp(`^/${dir.startsWith("/") ? dir.slice(1) : dir}/?.*`).test(path2);
825
+ });
826
+ return !!found && found;
827
+ }
828
+ };
829
+ var A_ListQueryFilter = class extends A_Fragment {
830
+ constructor(_query = {}, defaults = {}) {
831
+ super();
832
+ this._query = _query;
833
+ this.defaults = defaults;
834
+ this.parsedQuery = this.parseQueryString(_query);
835
+ }
836
+ get query() {
837
+ return this._query;
838
+ }
839
+ get(property, defaultValue = "") {
840
+ return this.parsedQuery[property] || this.defaults[property] || defaultValue;
841
+ }
842
+ parseQueryString(value = {}) {
843
+ if (typeof value === "string") {
844
+ return value.split("&").reduce((acc, part) => {
845
+ const [key, val] = part.split("=");
846
+ acc[decodeURIComponent(key)] = decodeURIComponent(val || "");
847
+ return acc;
848
+ }, {});
849
+ }
850
+ return value;
851
+ }
852
+ };
853
+ var A_EntityFactory = class extends A_Fragment {
854
+ constructor(param1, param2) {
855
+ super();
856
+ this._entities = /* @__PURE__ */ new Map();
857
+ this._setEntities(param1);
858
+ this._setEntities(param2);
859
+ }
860
+ _setEntities(entities = []) {
861
+ if (Array.isArray(entities)) {
862
+ entities.forEach((entity) => {
863
+ this._entities.set(entity.entity, entity);
864
+ });
865
+ } else {
866
+ Object.keys(entities).forEach((key) => {
867
+ this._entities.set(key, entities[key]);
868
+ });
869
+ }
870
+ }
871
+ add(param1, param2) {
872
+ switch (true) {
873
+ case (typeof param1 === "string" && !!param2):
874
+ this._entities.set(param1, param2);
875
+ break;
876
+ case typeof param1 !== "string":
877
+ this._entities.set(param1.entity, param1);
878
+ break;
879
+ }
880
+ }
881
+ has(param1) {
882
+ let name;
883
+ switch (true) {
884
+ case param1 instanceof ASEID:
885
+ name = param1.entity;
886
+ break;
887
+ case (!(param1 instanceof ASEID) && ASEID.isASEID(param1)):
888
+ name = new ASEID(param1).entity;
889
+ break;
890
+ default:
891
+ name = param1;
892
+ break;
893
+ }
894
+ return this._entities.has(name);
895
+ }
896
+ resolve(param1) {
897
+ let name;
898
+ switch (true) {
899
+ case param1 instanceof ASEID:
900
+ name = param1.entity;
901
+ break;
902
+ case (typeof param1 === "string" && ASEID.isASEID(param1)):
903
+ name = new ASEID(param1).entity;
904
+ break;
905
+ default:
906
+ name = param1;
907
+ break;
908
+ }
909
+ return this._entities.get(name);
910
+ }
911
+ resolveByName(name) {
912
+ return this._entities.get(name);
913
+ }
914
+ };
915
+ var A_EntityList = class extends A_Entity {
916
+ constructor() {
917
+ super(...arguments);
918
+ this._items = [];
919
+ this._pagination = {
920
+ total: 0,
921
+ page: 1,
922
+ pageSize: 10
923
+ };
924
+ }
925
+ static get scope() {
926
+ return "a-server";
927
+ }
928
+ /**
929
+ * Returns the entity constructor used for the list
930
+ */
931
+ get entityConstructor() {
932
+ return this._entityConstructor;
933
+ }
934
+ /**
935
+ * Returns the list of items contained in the entity list
936
+ */
937
+ get items() {
938
+ return this._items;
939
+ }
940
+ /**
941
+ * Returns pagination information about the entity list
942
+ */
943
+ get pagination() {
944
+ return this._pagination;
945
+ }
946
+ /**
947
+ * Creates a new instance of A_EntityList
948
+ *
949
+ * @param newEntity
950
+ */
951
+ fromNew(newEntity) {
952
+ this.aseid = new ASEID({
953
+ concept: A_Context.root.name,
954
+ scope: "default",
955
+ entity: "a-list" + (newEntity.name ? `.${newEntity.name}` : ""),
956
+ id: (/* @__PURE__ */ new Date()).getTime().toString()
957
+ });
958
+ this._entityConstructor = newEntity.constructor;
959
+ }
960
+ /**
961
+ * Allows to convert Repository Response data to EntityList instance
962
+ *
963
+ * [!] This method does not load the data from the repository, it only converts the data to the EntityList instance
964
+ *
965
+ * @param items
966
+ * @param pagination
967
+ */
968
+ fromList(items, pagination) {
969
+ this._items = items.map((item) => {
970
+ if (item instanceof A_Entity) {
971
+ return item;
972
+ } else {
973
+ const entity = new this._entityConstructor(item);
974
+ return entity;
975
+ }
976
+ });
977
+ if (pagination) {
978
+ this._pagination = {
979
+ total: pagination.total,
980
+ page: pagination.page,
981
+ pageSize: pagination.pageSize
982
+ };
983
+ }
984
+ }
985
+ /**
986
+ * Serializes the EntityList to a JSON object
987
+ *
988
+ * @returns
989
+ */
990
+ toJSON() {
991
+ return {
992
+ ...super.toJSON(),
993
+ items: this._items.map((i) => i.toJSON()),
994
+ pagination: this._pagination
995
+ };
996
+ }
997
+ };
998
+ var A_ServerLogger = class extends A_Logger {
999
+ async onRequestEnd(request, response) {
1000
+ this.route({
1001
+ method: request.method,
1002
+ url: request.url,
1003
+ status: response.statusCode,
1004
+ responseTime: response.duration
1005
+ });
1006
+ }
1007
+ async onRequestError(request) {
1008
+ }
1009
+ logStart(container) {
1010
+ this.serverReady({
1011
+ port: container.port,
1012
+ app: {
1013
+ name: container.name
1014
+ }
1015
+ });
1016
+ }
1017
+ logStop(server) {
1018
+ this.log("red", `Server ${server.name} stopped`);
1019
+ }
1020
+ metrics() {
1021
+ }
1022
+ routes(routes) {
1023
+ const time = this.getTime();
1024
+ console.log(`\x1B[36m[${this.scope.name}] |${time}| Exposed Routes:
1025
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
1026
+ ${routes.map((route) => `${" ".repeat(this.scopeLength + 3)}| [${route.method.toUpperCase()}]${" ".repeat(7 - route.method.length)} ${route.path}`).join("\n")}
1027
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------\x1B[0m`);
1028
+ }
1029
+ /**
1030
+ * Logs the route information based on status code
1031
+ *
1032
+ * @param route
1033
+ */
1034
+ route(route) {
1035
+ switch (route.status) {
1036
+ case 200:
1037
+ this.log200(route);
1038
+ break;
1039
+ case 404:
1040
+ this.log404(route);
1041
+ break;
1042
+ case 500:
1043
+ this.log500(route);
1044
+ break;
1045
+ case 400:
1046
+ this.log400(route);
1047
+ break;
1048
+ default:
1049
+ this.logDefault(route);
1050
+ break;
1051
+ }
1052
+ }
1053
+ log200(route) {
1054
+ if (this.config.get("SERVER_IGNORE_LOG_200"))
1055
+ return;
1056
+ console.log(`\x1B[32m[${this.scope.name}] |${this.getTime()}| ${route.status} | [${route.method.toUpperCase()}]${" ".repeat(7 - route.method.length)} ${route.url} | ${route.responseTime}ms\x1B[0m`);
1057
+ }
1058
+ log404(route) {
1059
+ if (this.config.get("SERVER_IGNORE_LOG_404"))
1060
+ return;
1061
+ console.log(`\x1B[33m[${this.scope.name}] |${this.getTime()}| ${route.status} | [${route.method.toUpperCase()}]${" ".repeat(7 - route.method.length)} ${route.url} | ${route.responseTime}ms\x1B[0m`);
1062
+ }
1063
+ log500(route) {
1064
+ if (this.config.get("SERVER_IGNORE_LOG_500"))
1065
+ return;
1066
+ console.log(`\x1B[31m[${this.scope.name}] |${this.getTime()}| ${route.status} | [${route.method.toUpperCase()}]${" ".repeat(7 - route.method.length)} ${route.url} | ${route.responseTime}ms\x1B[0m`);
1067
+ }
1068
+ log400(route) {
1069
+ if (this.config.get("SERVER_IGNORE_LOG_400"))
1070
+ return;
1071
+ console.log(`\x1B[33m[${this.scope.name}] |${this.getTime()}| ${route.status} | [${route.method.toUpperCase()}]${" ".repeat(7 - route.method.length)} ${route.url} | ${route.responseTime}ms\x1B[0m`);
1072
+ }
1073
+ logDefault(route) {
1074
+ if (this.config.get("SERVER_IGNORE_LOG_DEFAULT"))
1075
+ return;
1076
+ console.log(`\x1B[36m[${this.scope.name}] |${this.getTime()}| ${route.status} | [${route.method.toUpperCase()}]${" ".repeat(7 - route.method.length)} ${route.url} | ${route.responseTime}ms\x1B[0m`);
1077
+ }
1078
+ serverReady(params) {
1079
+ const processId = process.pid;
1080
+ console.log(`\x1B[36m[${this.scope.name}] |${this.getTime()}| Server Ready:
1081
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
1082
+ ${" ".repeat(this.scopeLength + 3)}| ${params.app.name} v${params.app.version || "0.0.1"} is running on port ${params.port}
1083
+ ${" ".repeat(this.scopeLength + 3)}| Process ID: ${processId}
1084
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
1085
+ ${" ".repeat(this.scopeLength + 3)}| ==============================
1086
+ ${" ".repeat(this.scopeLength + 3)}| LISTENING...
1087
+ ${" ".repeat(this.scopeLength + 3)}| ==============================
1088
+ \x1B[0m`);
1089
+ }
1090
+ /**
1091
+ * Displays a proxy routes
1092
+ *
1093
+ * @param params
1094
+ */
1095
+ proxy(params) {
1096
+ console.log(`\x1B[35m[${this.scope.name}] |${this.getTime()}| Proxy:
1097
+ ${" ".repeat(this.scopeLength + 3)}| ${params.original} -> ${params.destination}
1098
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------\x1B[0m`);
1099
+ }
1100
+ };
1101
+ __decorateClass([
1102
+ A_Feature.Extend({
1103
+ name: "finish" /* Finish */,
1104
+ scope: [A_Response]
1105
+ }),
1106
+ __decorateParam(0, A_Inject(A_Request)),
1107
+ __decorateParam(1, A_Inject(A_Response))
1108
+ ], A_ServerLogger.prototype, "onRequestEnd");
1109
+ __decorateClass([
1110
+ A_Feature.Extend({
1111
+ name: "error" /* Error */
1112
+ }),
1113
+ __decorateParam(0, A_Inject(A_Request))
1114
+ ], A_ServerLogger.prototype, "onRequestError");
1115
+ __decorateClass([
1116
+ A_Feature.Extend({
1117
+ name: "afterStart" /* afterStart */,
1118
+ scope: [A_Service]
1119
+ }),
1120
+ __decorateParam(0, A_Inject(A_Service))
1121
+ ], A_ServerLogger.prototype, "logStart");
1122
+ __decorateClass([
1123
+ A_Feature.Extend({
1124
+ name: "afterStop" /* afterStop */,
1125
+ scope: [A_Service]
1126
+ }),
1127
+ __decorateParam(0, A_Inject(A_Server))
1128
+ ], A_ServerLogger.prototype, "logStop");
1129
+
1130
+ // src/components/A-Router/A-Router.component.types.ts
1131
+ var A_SERVER_TYPES__RouterMethod = /* @__PURE__ */ ((A_SERVER_TYPES__RouterMethod2) => {
1132
+ A_SERVER_TYPES__RouterMethod2["POST"] = "POST";
1133
+ A_SERVER_TYPES__RouterMethod2["GET"] = "GET";
1134
+ A_SERVER_TYPES__RouterMethod2["PUT"] = "PUT";
1135
+ A_SERVER_TYPES__RouterMethod2["DELETE"] = "DELETE";
1136
+ A_SERVER_TYPES__RouterMethod2["PATCH"] = "PATCH";
1137
+ A_SERVER_TYPES__RouterMethod2["DEFAULT"] = "DEFAULT";
1138
+ return A_SERVER_TYPES__RouterMethod2;
1139
+ })(A_SERVER_TYPES__RouterMethod || {});
1140
+ var A_SERVER_TYPES__ARouterComponentMetaKey = /* @__PURE__ */ ((A_SERVER_TYPES__ARouterComponentMetaKey2) => {
1141
+ A_SERVER_TYPES__ARouterComponentMetaKey2["ROUTES"] = "ROUTES";
1142
+ return A_SERVER_TYPES__ARouterComponentMetaKey2;
1143
+ })(A_SERVER_TYPES__ARouterComponentMetaKey || {});
1144
+ var _A_Router = class _A_Router extends A_Component {
1145
+ // =======================================================
1146
+ // ================ Method Definition=====================
1147
+ // =======================================================
1148
+ /**
1149
+ * Allows to define a custom route for POST requests
1150
+ *
1151
+ * @param path
1152
+ * @returns
1153
+ */
1154
+ static Post(path2) {
1155
+ return this.defineRoute({
1156
+ method: "POST" /* POST */,
1157
+ path: typeof path2 === "object" && "path" in path2 ? path2.path : path2,
1158
+ version: typeof path2 === "object" && "version" in path2 && path2.version ? path2.version : "v1",
1159
+ prefix: typeof path2 === "object" && "prefix" in path2 && path2.prefix ? path2.prefix : "api"
1160
+ });
1161
+ }
1162
+ /**
1163
+ * Allows to define a custom route for GET requests
1164
+ *
1165
+ * @param path
1166
+ * @returns
1167
+ */
1168
+ static Get(path2) {
1169
+ return this.defineRoute({
1170
+ method: "GET" /* GET */,
1171
+ path: typeof path2 === "object" && "path" in path2 ? path2.path : path2,
1172
+ version: typeof path2 === "object" && "version" in path2 && path2.version ? path2.version : "v1",
1173
+ prefix: typeof path2 === "object" && "prefix" in path2 && path2.prefix ? path2.prefix : "api"
1174
+ });
1175
+ }
1176
+ /**
1177
+ * Allows to define a custom route for PUT requests
1178
+ *
1179
+ * @param path
1180
+ * @returns
1181
+ */
1182
+ static Put(path2) {
1183
+ return this.defineRoute({
1184
+ method: "PUT" /* PUT */,
1185
+ path: typeof path2 === "object" && "path" in path2 ? path2.path : path2,
1186
+ version: typeof path2 === "object" && "version" in path2 && path2.version ? path2.version : "v1",
1187
+ prefix: typeof path2 === "object" && "prefix" in path2 && path2.prefix ? path2.prefix : "api"
1188
+ });
1189
+ }
1190
+ /**
1191
+ * Allows to define a custom route for DELETE requests
1192
+ *
1193
+ * @param path
1194
+ * @returns
1195
+ */
1196
+ static Delete(path2) {
1197
+ return this.defineRoute({
1198
+ method: "DELETE" /* DELETE */,
1199
+ path: typeof path2 === "object" && "path" in path2 ? path2.path : path2,
1200
+ version: typeof path2 === "object" && "version" in path2 && path2.version ? path2.version : "v1",
1201
+ prefix: typeof path2 === "object" && "prefix" in path2 && path2.prefix ? path2.prefix : "api"
1202
+ });
1203
+ }
1204
+ /**
1205
+ * Allows to define a custom route for PATCH requests
1206
+ *
1207
+ * @param path
1208
+ * @returns
1209
+ */
1210
+ static Patch(path2) {
1211
+ return this.defineRoute({
1212
+ method: "PATCH" /* PATCH */,
1213
+ path: typeof path2 === "object" && "path" in path2 ? path2.path : path2,
1214
+ version: typeof path2 === "object" && "version" in path2 && path2.version ? path2.version : "v1",
1215
+ prefix: typeof path2 === "object" && "prefix" in path2 && path2.prefix ? path2.prefix : "api"
1216
+ });
1217
+ }
1218
+ /**
1219
+ * Allows to define a custom route for DEFAULT requests
1220
+ *
1221
+ * @param path
1222
+ * @returns
1223
+ */
1224
+ static Default(path2) {
1225
+ return this.defineRoute({
1226
+ method: "DEFAULT" /* DEFAULT */,
1227
+ path: typeof path2 === "object" && "path" in path2 ? path2.path : path2,
1228
+ version: typeof path2 === "object" && "version" in path2 && path2.version ? path2.version : "v1",
1229
+ prefix: typeof path2 === "object" && "prefix" in path2 && path2.prefix ? path2.prefix : "api"
1230
+ });
1231
+ }
1232
+ /**
1233
+ * Private method to have the same signature for all route methods
1234
+ *
1235
+ * @param method
1236
+ * @param path
1237
+ * @returns
1238
+ */
1239
+ static defineRoute(config) {
1240
+ const route = typeof config.path === "string" || config.path instanceof RegExp ? new A_Route(
1241
+ `/${config.prefix}/${config.version}${config.path instanceof RegExp ? config.path.source : config.path.startsWith("/") ? config.path : `/${config.path}`}`,
1242
+ config.method
1243
+ ) : config.path;
1244
+ this.routes.push(route);
1245
+ return function decorator(target, propertyKey, descriptor) {
1246
+ const meta = A_Context.meta(target);
1247
+ const routes = meta.get("ROUTES" /* ROUTES */) || /* @__PURE__ */ new Map();
1248
+ const searchKey = route.toAFeatureExtension(["A_Router", "A_Service"]);
1249
+ routes.set(searchKey.source, {
1250
+ component: target,
1251
+ handler: propertyKey,
1252
+ route
1253
+ });
1254
+ meta.set("ROUTES" /* ROUTES */, routes);
1255
+ A_Feature_Define({
1256
+ name: searchKey.source,
1257
+ invoke: false
1258
+ })(target, propertyKey, descriptor);
1259
+ return A_Feature_Extend(searchKey)(target, propertyKey, descriptor);
1260
+ };
1261
+ }
1262
+ async load(logger) {
1263
+ logger.routes(_A_Router.routes);
1264
+ }
1265
+ async identifyRoute(request, response, scope, config, logger) {
1266
+ const route = request.route;
1267
+ if (config.get("A_CONCEPT_ENVIRONMENT") === "development") {
1268
+ logger.log(`Incoming request: ${request.method} ${request.url}`);
1269
+ logger.log(`Identified route: ${route.toString()}`);
1270
+ }
1271
+ const feature = new A_Feature({
1272
+ name: route.toString(),
1273
+ component: this
1274
+ });
1275
+ for (const stage of feature) {
1276
+ if (A_TypeGuards.isComponentConstructor(stage.definition.component)) {
1277
+ const meta = A_Context.meta(stage.definition.component);
1278
+ const routes = meta.get("ROUTES" /* ROUTES */);
1279
+ if (routes) {
1280
+ const currentRoute = routes.get(stage.definition.name || "");
1281
+ if (currentRoute) {
1282
+ request.params = {
1283
+ ...request.params,
1284
+ ...currentRoute.route.extractParams(request.url)
1285
+ };
1286
+ }
1287
+ }
1288
+ }
1289
+ const stageScope = new A_Scope({
1290
+ name: `a-route--${A_IdentityHelper.generateTimeId()}`,
1291
+ entities: [request]
1292
+ }, {
1293
+ parent: scope
1294
+ });
1295
+ await stage.process(stageScope);
1296
+ }
1297
+ console.log("Finished processing route for request:", request.method, request.url);
1298
+ }
1299
+ };
1300
+ _A_Router.routes = [];
1301
+ __decorateClass([
1302
+ A_Concept.Load(),
1303
+ __decorateParam(0, A_Inject(A_ServerLogger))
1304
+ ], _A_Router.prototype, "load");
1305
+ __decorateClass([
1306
+ A_Feature.Extend({
1307
+ name: "onRequest" /* onRequest */,
1308
+ scope: [A_Service]
1309
+ }),
1310
+ __decorateParam(0, A_Inject(A_Request)),
1311
+ __decorateParam(1, A_Inject(A_Response)),
1312
+ __decorateParam(2, A_Inject(A_Scope)),
1313
+ __decorateParam(3, A_Inject(A_Config)),
1314
+ __decorateParam(4, A_Inject(A_Logger))
1315
+ ], _A_Router.prototype, "identifyRoute");
1316
+ var A_Router = _A_Router;
1317
+ var A_EntityController = class extends A_Component {
1318
+ async list(request, response, factory, scope, config) {
1319
+ const constructor = factory.resolveByName(request.params.type);
1320
+ if (constructor) {
1321
+ const entityList = new A_EntityList({
1322
+ name: request.params.type,
1323
+ scope: scope.name,
1324
+ constructor
1325
+ });
1326
+ scope.register(entityList);
1327
+ const queryFilter = new A_ListQueryFilter(request.query, {
1328
+ itemsPerPage: String(config.get("A_LIST_ITEMS_PER_PAGE") || "10"),
1329
+ page: String(config.get("A_LIST_PAGE") || "1")
1330
+ });
1331
+ const queryScope = new A_Scope({
1332
+ fragments: [queryFilter]
1333
+ }).inherit(scope);
1334
+ await entityList.load(queryScope);
1335
+ response.add("items", entityList.items);
1336
+ response.add("pagination", entityList.pagination);
1337
+ }
1338
+ }
1339
+ async load(request, response, scope) {
1340
+ if (!ASEID.isASEID(request.params.aseid)) {
1341
+ response.add("A_EntityController.load", "Invalid ASEID");
1342
+ return;
1343
+ }
1344
+ const aseid = new ASEID(request.params.aseid);
1345
+ const constructor = scope.resolveConstructor(aseid.entity);
1346
+ if (constructor) {
1347
+ const entity = new constructor(request.params.aseid);
1348
+ scope.register(entity);
1349
+ await entity.load();
1350
+ return response.status(200).json(entity.toJSON());
1351
+ } else
1352
+ throw new A_ServerError({
1353
+ title: "Entity Not Found",
1354
+ description: `Entity constructor for ASEID ${request.params.aseid} not found`,
1355
+ status: 404
1356
+ });
1357
+ }
1358
+ async create(request, factory, scope) {
1359
+ const constructor = factory.resolve(request.params.aseid);
1360
+ if (constructor) {
1361
+ const entity = new constructor(request.body);
1362
+ scope.register(entity);
1363
+ await entity.save();
1364
+ }
1365
+ }
1366
+ async update(request, response, factory, scope) {
1367
+ if (!ASEID.isASEID(request.params.aseid)) {
1368
+ response.add("A_EntityController.update", "Invalid ASEID");
1369
+ return;
1370
+ }
1371
+ const constructor = factory.resolve(request.params.aseid);
1372
+ if (constructor) {
1373
+ const entity = new constructor(request.body);
1374
+ scope.register(entity);
1375
+ await entity.save();
1376
+ }
1377
+ }
1378
+ async delete(request, response, factory, scope) {
1379
+ if (!ASEID.isASEID(request.params.aseid)) {
1380
+ response.add("A_EntityController.delete", "Invalid ASEID");
1381
+ return;
1382
+ }
1383
+ const constructor = factory.resolve(request.params.aseid);
1384
+ if (constructor) {
1385
+ const entity = new constructor(request.params.aseid);
1386
+ scope.register(entity);
1387
+ await entity.destroy();
1388
+ }
1389
+ }
1390
+ async callEntity(request, response, factory, scope) {
1391
+ if (!ASEID.isASEID(request.params.aseid)) {
1392
+ response.add("A_EntityController.callEntity", "Invalid ASEID");
1393
+ return;
1394
+ }
1395
+ const constructor = factory.resolve(request.params.aseid);
1396
+ if (!constructor) {
1397
+ response.add("A_EntityController.callEntity", "Entity not found");
1398
+ return;
1399
+ }
1400
+ const meta = A_Context.meta(constructor);
1401
+ const targetFeature = meta.features().find((f) => f.name === `${constructor.name}.${request.params.action}`);
1402
+ if (!targetFeature) {
1403
+ response.add("A_EntityController.callEntity", "Feature not found");
1404
+ return;
1405
+ }
1406
+ const entity = new constructor(request.params.aseid);
1407
+ scope.register(entity);
1408
+ await entity.load(scope);
1409
+ await entity[targetFeature.handler](scope);
1410
+ response.add("result", scope.toJSON());
1411
+ response.add("entity", entity);
1412
+ response.add("type", entity.aseid.entity);
1413
+ }
1414
+ };
1415
+ __decorateClass([
1416
+ A_Router.Get({
1417
+ path: "/:type",
1418
+ version: "v1",
1419
+ prefix: "a-list"
1420
+ }),
1421
+ __decorateParam(0, A_Inject(A_Request)),
1422
+ __decorateParam(1, A_Inject(A_Response)),
1423
+ __decorateParam(2, A_Inject(A_EntityFactory)),
1424
+ __decorateParam(3, A_Inject(A_Scope)),
1425
+ __decorateParam(4, A_Inject(A_Config))
1426
+ ], A_EntityController.prototype, "list");
1427
+ __decorateClass([
1428
+ A_Feature.Define({
1429
+ name: "getEntity",
1430
+ invoke: false
1431
+ }),
1432
+ A_Router.Get({
1433
+ path: "/:aseid",
1434
+ version: "v1",
1435
+ prefix: "a-entity"
1436
+ }),
1437
+ __decorateParam(0, A_Inject(A_Request)),
1438
+ __decorateParam(1, A_Inject(A_Response)),
1439
+ __decorateParam(2, A_Inject(A_Scope))
1440
+ ], A_EntityController.prototype, "load");
1441
+ __decorateClass([
1442
+ A_Router.Post({
1443
+ path: "/",
1444
+ version: "v1",
1445
+ prefix: "a-entity"
1446
+ }),
1447
+ __decorateParam(0, A_Inject(A_Request)),
1448
+ __decorateParam(1, A_Inject(A_EntityFactory)),
1449
+ __decorateParam(2, A_Inject(A_Scope))
1450
+ ], A_EntityController.prototype, "create");
1451
+ __decorateClass([
1452
+ A_Router.Put({
1453
+ path: "/:aseid",
1454
+ version: "v1",
1455
+ prefix: "a-entity"
1456
+ }),
1457
+ __decorateParam(0, A_Inject(A_Request)),
1458
+ __decorateParam(1, A_Inject(A_Response)),
1459
+ __decorateParam(2, A_Inject(A_EntityFactory)),
1460
+ __decorateParam(3, A_Inject(A_Scope))
1461
+ ], A_EntityController.prototype, "update");
1462
+ __decorateClass([
1463
+ A_Router.Delete({
1464
+ path: "/:aseid",
1465
+ version: "v1",
1466
+ prefix: "a-entity"
1467
+ }),
1468
+ __decorateParam(0, A_Inject(A_Request)),
1469
+ __decorateParam(1, A_Inject(A_Response)),
1470
+ __decorateParam(2, A_Inject(A_EntityFactory)),
1471
+ __decorateParam(3, A_Inject(A_Scope))
1472
+ ], A_EntityController.prototype, "delete");
1473
+ __decorateClass([
1474
+ A_Router.Post({
1475
+ path: "/:aseid/:action",
1476
+ version: "v1",
1477
+ prefix: "a-entity"
1478
+ }),
1479
+ __decorateParam(0, A_Inject(A_Request)),
1480
+ __decorateParam(1, A_Inject(A_Response)),
1481
+ __decorateParam(2, A_Inject(A_EntityFactory)),
1482
+ __decorateParam(3, A_Inject(A_Scope))
1483
+ ], A_EntityController.prototype, "callEntity");
1484
+ var A_ServerHealthMonitor = class extends A_Component {
1485
+ async get(config, request, response, logger) {
1486
+ logger.log("Health check requested", config.get("A_CONCEPT_ROOT_FOLDER"));
1487
+ const packageJSON = await import(`${config.get("A_CONCEPT_ROOT_FOLDER")}/package.json`);
1488
+ const exposedProperties = config.get("EXPOSED_PROPERTIES")?.split(",") || [
1489
+ "name",
1490
+ "version",
1491
+ "description"
1492
+ ];
1493
+ exposedProperties.forEach((prop) => response.add(prop, packageJSON[prop]));
1494
+ console.log(`Health check accessed: ${request.method} ${request.url}`);
1495
+ }
1496
+ };
1497
+ __decorateClass([
1498
+ A_Router.Get({
1499
+ path: "/",
1500
+ prefix: "health",
1501
+ version: "v1"
1502
+ }),
1503
+ __decorateParam(0, A_Inject(A_Config)),
1504
+ __decorateParam(1, A_Inject(A_Request)),
1505
+ __decorateParam(2, A_Inject(A_Response)),
1506
+ __decorateParam(3, A_Inject(A_Logger))
1507
+ ], A_ServerHealthMonitor.prototype, "get");
1508
+ var A_ServerProxy = class extends A_Component {
1509
+ async load(logger, config) {
1510
+ logger.log(
1511
+ "pink",
1512
+ `Proxy routes configured:`,
1513
+ config.configs.map((c) => c.route).join("\n")
1514
+ );
1515
+ }
1516
+ async onRequest(req, res, proxyConfig, logger) {
1517
+ return new Promise((resolve, reject) => {
1518
+ const { method, url } = req;
1519
+ const route = new A_Route(url, method);
1520
+ const config = proxyConfig.config(route.toString());
1521
+ if (!config) {
1522
+ return resolve();
1523
+ }
1524
+ logger.log(
1525
+ "yellow",
1526
+ `Proxying request ${method} ${url} to ${config.hostname}`,
1527
+ config
1528
+ );
1529
+ const client = config.protocol === "https:" ? https : http;
1530
+ const proxyReq = client.request(
1531
+ {
1532
+ method: config.route.method,
1533
+ hostname: config.hostname,
1534
+ port: config.port,
1535
+ headers: config.headers,
1536
+ path: route.path
1537
+ },
1538
+ (proxyRes) => {
1539
+ if (!res.headersSent) {
1540
+ res.writeHead(proxyRes.statusCode || 200, proxyRes.headers);
1541
+ }
1542
+ proxyRes.on("end", () => {
1543
+ logger.log("green", `Proxy request to ${config?.hostname} completed`);
1544
+ resolve();
1545
+ });
1546
+ proxyRes.pipe(res.original);
1547
+ }
1548
+ );
1549
+ proxyReq.on("error", (err) => reject(err));
1550
+ req.pipe(proxyReq);
1551
+ });
1552
+ }
1553
+ };
1554
+ __decorateClass([
1555
+ A_Concept.Load(),
1556
+ __decorateParam(0, A_Inject(A_Logger)),
1557
+ __decorateParam(1, A_Inject(A_ProxyConfig))
1558
+ ], A_ServerProxy.prototype, "load");
1559
+ __decorateClass([
1560
+ A_Feature.Extend({
1561
+ name: "onRequest" /* onRequest */
1562
+ }),
1563
+ __decorateParam(0, A_Inject(A_Request)),
1564
+ __decorateParam(1, A_Inject(A_Response)),
1565
+ __decorateParam(2, A_Inject(A_ProxyConfig)),
1566
+ __decorateParam(3, A_Inject(A_Logger))
1567
+ ], A_ServerProxy.prototype, "onRequest");
1568
+
1569
+ // src/components/A-ServerCORS/A_ServerCORS.component.defaults.ts
1570
+ var A_SERVER_DEFAULTS__CorsConfig = {
1571
+ origin: "*",
1572
+ // Default to allow all origins
1573
+ methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
1574
+ headers: ["Content-Type"],
1575
+ credentials: false,
1576
+ maxAge: 0
1577
+ };
1578
+ var A_ServerCORS = class extends A_Component {
1579
+ async init(config) {
1580
+ this.config = {
1581
+ origin: config.get("ORIGIN") || A_SERVER_DEFAULTS__CorsConfig.origin,
1582
+ methods: config.get("METHODS") || A_SERVER_DEFAULTS__CorsConfig.methods,
1583
+ headers: config.get("HEADERS") || A_SERVER_DEFAULTS__CorsConfig.headers,
1584
+ credentials: config.get("CREDENTIALS") || A_SERVER_DEFAULTS__CorsConfig.credentials,
1585
+ maxAge: config.get("MAX_AGE") || A_SERVER_DEFAULTS__CorsConfig.maxAge
1586
+ };
1587
+ }
1588
+ apply(aReq, aRes) {
1589
+ aRes.setHeader("Access-Control-Allow-Origin", this.config.origin);
1590
+ aRes.setHeader("Access-Control-Allow-Methods", this.config.methods.join(", "));
1591
+ aRes.setHeader("Access-Control-Allow-Headers", this.config.headers.join(", "));
1592
+ if (this.config.credentials) {
1593
+ aRes.setHeader("Access-Control-Allow-Credentials", "true");
1594
+ }
1595
+ if (this.config.maxAge) {
1596
+ aRes.setHeader("Access-Control-Max-Age", this.config.maxAge.toString());
1597
+ }
1598
+ if (aReq.req.method === "OPTIONS") {
1599
+ aRes.status(204).send();
1600
+ }
1601
+ }
1602
+ };
1603
+ __decorateClass([
1604
+ A_Feature.Extend({
1605
+ name: "beforeStart" /* beforeStart */
1606
+ }),
1607
+ __decorateParam(0, A_Inject(A_Config))
1608
+ ], A_ServerCORS.prototype, "init");
1609
+ __decorateClass([
1610
+ A_Feature.Extend({
1611
+ name: "beforeRequest" /* beforeRequest */
1612
+ }),
1613
+ __decorateParam(0, A_Inject(A_Request)),
1614
+ __decorateParam(1, A_Inject(A_Response))
1615
+ ], A_ServerCORS.prototype, "apply");
1616
+ var A_StaticLoader = class extends A_Component {
1617
+ async load(logger, config) {
1618
+ logger.log(
1619
+ "pink",
1620
+ `Static directories configured:`,
1621
+ config.directories.join("\n")
1622
+ );
1623
+ }
1624
+ async onRequest(req, res, logger, config) {
1625
+ if (req.method !== "GET" && req.method !== "HEAD") {
1626
+ return;
1627
+ }
1628
+ const { method, url } = req;
1629
+ const route = new A_Route(url, method);
1630
+ const staticDirConfig = config.has(route.path);
1631
+ if (!staticDirConfig) {
1632
+ return;
1633
+ }
1634
+ const staticDir = path.resolve(process.cwd(), staticDirConfig);
1635
+ if (!fs.existsSync(staticDir) || !fs.statSync(staticDir).isDirectory()) {
1636
+ logger.log("red", `Static directory ${staticDir} does not exist or is not a directory.`);
1637
+ return;
1638
+ }
1639
+ await this.serveFile(route.path.startsWith("/") ? route.path.slice(1) : route.path, res);
1640
+ }
1641
+ getMimeType(ext) {
1642
+ const mimeTypes = {
1643
+ ".html": "text/html",
1644
+ ".js": "application/javascript",
1645
+ ".css": "text/css",
1646
+ ".json": "application/json",
1647
+ ".png": "image/png",
1648
+ ".jpg": "image/jpeg",
1649
+ ".jpeg": "image/jpeg",
1650
+ ".gif": "image/gif",
1651
+ ".svg": "image/svg+xml",
1652
+ ".ico": "image/x-icon",
1653
+ ".txt": "text/plain"
1654
+ };
1655
+ return mimeTypes[ext.toLowerCase()] || "application/octet-stream";
1656
+ }
1657
+ safeFilePath(staticDir, reqUrl, host) {
1658
+ const parsedUrl = new URL$1(reqUrl || "/", `http://${host || "localhost"}`);
1659
+ let pathname = decodeURIComponent(parsedUrl.pathname);
1660
+ pathname = pathname.replace(/\.\.[\/\\]/g, "");
1661
+ let filePath = path.join(staticDir, pathname);
1662
+ if (!fs.existsSync(filePath))
1663
+ throw new Error(`File not found: ${filePath}`);
1664
+ return filePath;
1665
+ }
1666
+ serveFile(filePath, res) {
1667
+ return new Promise((resolve, reject) => {
1668
+ if (fs.existsSync(filePath)) {
1669
+ const ext = path.extname(filePath);
1670
+ const contentType = this.getMimeType(ext);
1671
+ res.writeHead(200, { "Content-Type": contentType });
1672
+ const stream = fs.createReadStream(filePath);
1673
+ stream.pipe(res.original);
1674
+ stream.on("end", () => {
1675
+ resolve();
1676
+ });
1677
+ stream.on("error", (err) => {
1678
+ reject(new Error(`File stream error: ${err.message}`));
1679
+ });
1680
+ } else {
1681
+ reject(new Error(`File not found: ${filePath}`));
1682
+ }
1683
+ resolve();
1684
+ });
1685
+ }
1686
+ };
1687
+ __decorateClass([
1688
+ A_Concept.Load(),
1689
+ __decorateParam(0, A_Inject(A_Logger)),
1690
+ __decorateParam(1, A_Inject(A_StaticConfig))
1691
+ ], A_StaticLoader.prototype, "load");
1692
+ __decorateClass([
1693
+ A_Feature.Extend({
1694
+ name: "onRequest" /* onRequest */
1695
+ }),
1696
+ __decorateParam(0, A_Inject(A_Request)),
1697
+ __decorateParam(1, A_Inject(A_Response)),
1698
+ __decorateParam(2, A_Inject(A_Logger)),
1699
+ __decorateParam(3, A_Inject(A_StaticConfig))
1700
+ ], A_StaticLoader.prototype, "onRequest");
1701
+ var A_Controller = class extends A_Component {
1702
+ async callEntityMethod(request, response, scope) {
1703
+ if (!scope.has(request.params.component))
1704
+ return;
1705
+ if (!request.params.operation || typeof request.params.operation !== "string")
1706
+ return;
1707
+ const possibleComponent = scope.resolve(request.params.component);
1708
+ if (!possibleComponent || ![A_Component, A_Container].some((c) => possibleComponent instanceof c))
1709
+ return;
1710
+ const component = possibleComponent;
1711
+ const meta = A_Context.meta(component);
1712
+ const targetFeature = meta.features().find((f) => f.name === `${component.constructor.name}.${request.params.operation}`);
1713
+ if (!targetFeature)
1714
+ return;
1715
+ await component.call(request.params.operation, scope);
1716
+ }
1717
+ };
1718
+ __decorateClass([
1719
+ A_Router.Post({
1720
+ path: "/:component/:operation",
1721
+ version: "v1",
1722
+ prefix: "a-component"
1723
+ }),
1724
+ __decorateParam(0, A_Inject(A_Request)),
1725
+ __decorateParam(1, A_Inject(A_Response)),
1726
+ __decorateParam(2, A_Inject(A_Scope))
1727
+ ], A_Controller.prototype, "callEntityMethod");
1728
+ var A_ListingController = class extends A_Component {
1729
+ async list(request, response, factory, scope, config) {
1730
+ const constructor = factory.resolveByName(request.params.type);
1731
+ if (constructor) {
1732
+ const entityList = new A_EntityList({
1733
+ name: request.params.type,
1734
+ scope: scope.name,
1735
+ constructor
1736
+ });
1737
+ scope.register(entityList);
1738
+ const queryFilter = new A_ListQueryFilter(request.query, {
1739
+ itemsPerPage: String(config.get("A_LIST_ITEMS_PER_PAGE") || "10"),
1740
+ page: String(config.get("A_LIST_PAGE") || "1")
1741
+ });
1742
+ const queryScope = new A_Scope({
1743
+ fragments: [queryFilter]
1744
+ }).inherit(scope);
1745
+ await entityList.load(queryScope);
1746
+ response.add("items", entityList.items);
1747
+ response.add("pagination", entityList.pagination);
1748
+ }
1749
+ }
1750
+ };
1751
+ __decorateClass([
1752
+ A_Router.Get({
1753
+ path: "/:type",
1754
+ version: "v1",
1755
+ prefix: "a-list"
1756
+ }),
1757
+ __decorateParam(0, A_Inject(A_Request)),
1758
+ __decorateParam(1, A_Inject(A_Response)),
1759
+ __decorateParam(2, A_Inject(A_EntityFactory)),
1760
+ __decorateParam(3, A_Inject(A_Scope)),
1761
+ __decorateParam(4, A_Inject(A_Config))
1762
+ ], A_ListingController.prototype, "list");
1763
+ var A_CommandController = class extends A_Component {
1764
+ async handleCommand(req, res, scope, container) {
1765
+ const commandName = req.params.command;
1766
+ const CommandConstructor = scope.resolveConstructor(commandName);
1767
+ if (!CommandConstructor) {
1768
+ res.status(404);
1769
+ throw new Error(`Command ${commandName} not found`);
1770
+ }
1771
+ const command = new CommandConstructor(req.body);
1772
+ container.scope.register(command);
1773
+ await command.execute();
1774
+ const serialized = command.toJSON();
1775
+ return res.status(200).json(serialized);
1776
+ }
1777
+ };
1778
+ __decorateClass([
1779
+ A_Router.Get({
1780
+ path: "/:command/execute",
1781
+ version: "v1",
1782
+ prefix: "a-command"
1783
+ }),
1784
+ __decorateParam(0, A_Inject(A_Request)),
1785
+ __decorateParam(1, A_Inject(A_Response)),
1786
+ __decorateParam(2, A_Inject(A_Scope)),
1787
+ __decorateParam(3, A_Inject(A_Container))
1788
+ ], A_CommandController.prototype, "handleCommand");
1789
+ var A_EntityRepository = class extends A_Component {
1790
+ async list(channel, entity, scope) {
1791
+ if (scope.has(A_Manifest) && !scope.resolve(A_Manifest).isAllowed(entity.constructor, "load").for(entity.constructor))
1792
+ return;
1793
+ const response = await channel.get(`/a-list/${entity.aseid.entity}`);
1794
+ entity.fromJSON(response.data);
1795
+ }
1796
+ async load(channel, entity, scope) {
1797
+ if (scope.has(A_Manifest) && !scope.resolve(A_Manifest).isAllowed(entity.constructor, "load").for(entity.constructor))
1798
+ return;
1799
+ const response = await channel.get(`/a-entity/${entity.aseid.toString()}`);
1800
+ entity.fromJSON(response.data);
1801
+ }
1802
+ async save(channel, entity, scope) {
1803
+ if (scope.has(A_Manifest) && !scope.resolve(A_Manifest).isAllowed(entity.constructor, "save").for(entity.constructor))
1804
+ return;
1805
+ const response = await channel.post(`/a-entity/${entity.aseid.toString()}`, entity.toJSON());
1806
+ entity.fromJSON(response.data);
1807
+ }
1808
+ async destroy(channel, entity, scope) {
1809
+ if (scope.has(A_Manifest) && !scope.resolve(A_Manifest).isAllowed(entity.constructor, "destroy").for(entity.constructor))
1810
+ return;
1811
+ const response = await channel.delete(`/a-entity/${entity.aseid.toString()}`);
1812
+ entity.fromJSON(response.data);
1813
+ }
1814
+ };
1815
+ __decorateClass([
1816
+ A_Feature.Extend({
1817
+ name: A_TYPES__EntityFeatures.LOAD,
1818
+ scope: {
1819
+ include: [A_EntityList]
1820
+ }
1821
+ }),
1822
+ __decorateParam(0, A_Inject(A_HTTPChannel)),
1823
+ __decorateParam(1, A_Inject(A_Caller)),
1824
+ __decorateParam(2, A_Inject(A_Scope))
1825
+ ], A_EntityRepository.prototype, "list");
1826
+ __decorateClass([
1827
+ A_Feature.Extend({
1828
+ name: A_TYPES__EntityFeatures.LOAD,
1829
+ scope: {
1830
+ exclude: [A_EntityList]
1831
+ }
1832
+ }),
1833
+ __decorateParam(0, A_Inject(A_HTTPChannel)),
1834
+ __decorateParam(1, A_Inject(A_Caller)),
1835
+ __decorateParam(2, A_Inject(A_Scope))
1836
+ ], A_EntityRepository.prototype, "load");
1837
+ __decorateClass([
1838
+ A_Feature.Extend({
1839
+ name: A_TYPES__EntityFeatures.SAVE,
1840
+ scope: {
1841
+ exclude: [A_EntityList]
1842
+ }
1843
+ }),
1844
+ __decorateParam(0, A_Inject(A_HTTPChannel)),
1845
+ __decorateParam(1, A_Inject(A_Caller)),
1846
+ __decorateParam(2, A_Inject(A_Scope))
1847
+ ], A_EntityRepository.prototype, "save");
1848
+ __decorateClass([
1849
+ A_Feature.Extend({
1850
+ name: A_TYPES__EntityFeatures.DESTROY,
1851
+ scope: {
1852
+ exclude: [A_EntityList]
1853
+ }
1854
+ }),
1855
+ __decorateParam(0, A_Inject(A_HTTPChannel)),
1856
+ __decorateParam(1, A_Inject(A_Caller)),
1857
+ __decorateParam(2, A_Inject(A_Scope))
1858
+ ], A_EntityRepository.prototype, "destroy");
1859
+
1860
+ export { A_CommandController, A_Controller, A_EntityController, A_EntityFactory, A_EntityList, A_EntityRepository, A_HTTPChannel, A_HTTPChannelError, A_HTTPChannel_RequestContext, A_ListQueryFilter, A_ListingController, A_ProxyConfig, A_Request, A_Response, A_Route, A_Router, A_SERVER_CONSTANTS__A_HttpChannel_Lifecycle, A_SERVER_CONSTANTS__DEFAULT_ENV_VARIABLES, A_SERVER_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY, A_SERVER_TYPES__ARouterComponentMetaKey, A_SERVER_TYPES__RequestEvent, A_SERVER_TYPES__ResponseEvent, A_SERVER_TYPES__RouterMethod, A_SERVER_TYPES__ServerFeature, A_SERVER_TYPES__ServerMethod, A_Server, A_ServerCORS, A_ServerError, A_ServerHealthMonitor, A_ServerLogger, A_ServerProxy, A_Service, A_StaticConfig, A_StaticLoader };
1861
+ //# sourceMappingURL=index.mjs.map
1862
+ //# sourceMappingURL=index.mjs.map