@miqro/core 4.0.1 → 5.0.2

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 (220) hide show
  1. package/build/app.d.ts +15 -11
  2. package/build/app.js +22 -20
  3. package/build/app.js.map +1 -1
  4. package/build/common.d.ts +106 -0
  5. package/build/common.js +477 -0
  6. package/build/common.js.map +1 -0
  7. package/build/lib.d.ts +7 -38
  8. package/build/lib.js +6 -33
  9. package/build/lib.js.map +1 -1
  10. package/build/middleware/body-parser.d.ts +78 -0
  11. package/build/middleware/body-parser.js +552 -0
  12. package/build/middleware/body-parser.js.map +1 -0
  13. package/build/middleware/router.d.ts +114 -0
  14. package/build/middleware/router.js +704 -0
  15. package/build/middleware/router.js.map +1 -0
  16. package/build/middleware/session.d.ts +27 -3
  17. package/build/middleware/session.js +238 -18
  18. package/build/middleware/session.js.map +1 -1
  19. package/build/types.d.ts +309 -0
  20. package/build/types.js +455 -0
  21. package/build/types.js.map +1 -0
  22. package/build/{websocket/cluster.d.ts → websocket.d.ts} +13 -2
  23. package/build/websocket.js +316 -0
  24. package/build/websocket.js.map +1 -0
  25. package/package.json +7 -7
  26. package/src/app.ts +36 -32
  27. package/src/common.ts +528 -0
  28. package/src/lib.ts +63 -101
  29. package/src/middleware/body-parser.ts +597 -0
  30. package/src/middleware/router.ts +840 -0
  31. package/src/middleware/session.ts +249 -19
  32. package/src/types.ts +785 -0
  33. package/src/websocket.ts +356 -0
  34. package/build/api-router.d.ts +0 -34
  35. package/build/api-router.js +0 -48
  36. package/build/api-router.js.map +0 -1
  37. package/build/app-utils.d.ts +0 -13
  38. package/build/app-utils.js +0 -78
  39. package/build/app-utils.js.map +0 -1
  40. package/build/common/api-router-types.d.ts +0 -28
  41. package/build/common/api-router-types.js +0 -24
  42. package/build/common/api-router-types.js.map +0 -1
  43. package/build/common/api-router-utils.d.ts +0 -3
  44. package/build/common/api-router-utils.js +0 -118
  45. package/build/common/api-router-utils.js.map +0 -1
  46. package/build/common/config/config.d.ts +0 -15
  47. package/build/common/config/config.js +0 -38
  48. package/build/common/config/config.js.map +0 -1
  49. package/build/common/config/featuretoggle.d.ts +0 -1
  50. package/build/common/config/featuretoggle.js +0 -6
  51. package/build/common/config/featuretoggle.js.map +0 -1
  52. package/build/common/config/loader.d.ts +0 -13
  53. package/build/common/config/loader.js +0 -64
  54. package/build/common/config/loader.js.map +0 -1
  55. package/build/common/context.d.ts +0 -57
  56. package/build/common/context.js +0 -137
  57. package/build/common/context.js.map +0 -1
  58. package/build/common/error/badrequesterror.d.ts +0 -3
  59. package/build/common/error/badrequesterror.js +0 -7
  60. package/build/common/error/badrequesterror.js.map +0 -1
  61. package/build/common/error/configfilenotfound.d.ts +0 -3
  62. package/build/common/error/configfilenotfound.js +0 -7
  63. package/build/common/error/configfilenotfound.js.map +0 -1
  64. package/build/common/error/forbiddenerror.d.ts +0 -3
  65. package/build/common/error/forbiddenerror.js +0 -7
  66. package/build/common/error/forbiddenerror.js.map +0 -1
  67. package/build/common/error/notfound.d.ts +0 -3
  68. package/build/common/error/notfound.js +0 -7
  69. package/build/common/error/notfound.js.map +0 -1
  70. package/build/common/error/notimplemented.d.ts +0 -3
  71. package/build/common/error/notimplemented.js +0 -7
  72. package/build/common/error/notimplemented.js.map +0 -1
  73. package/build/common/error/unauthorizederror.d.ts +0 -3
  74. package/build/common/error/unauthorizederror.js +0 -7
  75. package/build/common/error/unauthorizederror.js.map +0 -1
  76. package/build/common/logger/constants.d.ts +0 -14
  77. package/build/common/logger/constants.js +0 -22
  78. package/build/common/logger/constants.js.map +0 -1
  79. package/build/common/logger/factory.d.ts +0 -16
  80. package/build/common/logger/factory.js +0 -47
  81. package/build/common/logger/factory.js.map +0 -1
  82. package/build/common/logger/interfaces.d.ts +0 -18
  83. package/build/common/logger/interfaces.js +0 -2
  84. package/build/common/logger/interfaces.js.map +0 -1
  85. package/build/common/logger/logger.d.ts +0 -35
  86. package/build/common/logger/logger.js +0 -95
  87. package/build/common/logger/logger.js.map +0 -1
  88. package/build/common/logger/transport/console.d.ts +0 -5
  89. package/build/common/logger/transport/console.js +0 -37
  90. package/build/common/logger/transport/console.js.map +0 -1
  91. package/build/common/logger/transport/file.d.ts +0 -2
  92. package/build/common/logger/transport/file.js +0 -25
  93. package/build/common/logger/transport/file.js.map +0 -1
  94. package/build/common/parser.d.ts +0 -7
  95. package/build/common/parser.js +0 -44
  96. package/build/common/parser.js.map +0 -1
  97. package/build/common/router-default-logger-factory.d.ts +0 -4
  98. package/build/common/router-default-logger-factory.js +0 -38
  99. package/build/common/router-default-logger-factory.js.map +0 -1
  100. package/build/common/router-handler.d.ts +0 -20
  101. package/build/common/router-handler.js +0 -154
  102. package/build/common/router-handler.js.map +0 -1
  103. package/build/common/router-types.d.ts +0 -63
  104. package/build/common/router-types.js +0 -86
  105. package/build/common/router-types.js.map +0 -1
  106. package/build/common/router-utils.d.ts +0 -3
  107. package/build/common/router-utils.js +0 -46
  108. package/build/common/router-utils.js.map +0 -1
  109. package/build/common/session/common.d.ts +0 -37
  110. package/build/common/session/common.js +0 -2
  111. package/build/common/session/common.js.map +0 -1
  112. package/build/common/session/service.d.ts +0 -26
  113. package/build/common/session/service.js +0 -154
  114. package/build/common/session/service.js.map +0 -1
  115. package/build/common/tokenize-match.d.ts +0 -19
  116. package/build/common/tokenize-match.js +0 -73
  117. package/build/common/tokenize-match.js.map +0 -1
  118. package/build/common/url-utils.d.ts +0 -6
  119. package/build/common/url-utils.js +0 -48
  120. package/build/common/url-utils.js.map +0 -1
  121. package/build/middleware/buffer.d.ts +0 -6
  122. package/build/middleware/buffer.js +0 -78
  123. package/build/middleware/buffer.js.map +0 -1
  124. package/build/middleware/cookie.d.ts +0 -4
  125. package/build/middleware/cookie.js +0 -15
  126. package/build/middleware/cookie.js.map +0 -1
  127. package/build/middleware/cors.d.ts +0 -8
  128. package/build/middleware/cors.js +0 -89
  129. package/build/middleware/cors.js.map +0 -1
  130. package/build/middleware/form.d.ts +0 -6
  131. package/build/middleware/form.js +0 -58
  132. package/build/middleware/form.js.map +0 -1
  133. package/build/middleware/group.d.ts +0 -3
  134. package/build/middleware/group.js +0 -77
  135. package/build/middleware/group.js.map +0 -1
  136. package/build/middleware/json.d.ts +0 -6
  137. package/build/middleware/json.js +0 -55
  138. package/build/middleware/json.js.map +0 -1
  139. package/build/middleware/logger.d.ts +0 -4
  140. package/build/middleware/logger.js +0 -16
  141. package/build/middleware/logger.js.map +0 -1
  142. package/build/middleware/parse.d.ts +0 -14
  143. package/build/middleware/parse.js +0 -88
  144. package/build/middleware/parse.js.map +0 -1
  145. package/build/middleware/result.d.ts +0 -9
  146. package/build/middleware/result.js +0 -62
  147. package/build/middleware/result.js.map +0 -1
  148. package/build/middleware/tag.d.ts +0 -4
  149. package/build/middleware/tag.js +0 -10
  150. package/build/middleware/tag.js.map +0 -1
  151. package/build/middleware/text.d.ts +0 -5
  152. package/build/middleware/text.js +0 -46
  153. package/build/middleware/text.js.map +0 -1
  154. package/build/proxy.d.ts +0 -19
  155. package/build/proxy.js +0 -74
  156. package/build/proxy.js.map +0 -1
  157. package/build/router.d.ts +0 -26
  158. package/build/router.js +0 -116
  159. package/build/router.js.map +0 -1
  160. package/build/static.d.ts +0 -14
  161. package/build/static.js +0 -211
  162. package/build/static.js.map +0 -1
  163. package/build/websocket/cluster.js +0 -114
  164. package/build/websocket/cluster.js.map +0 -1
  165. package/build/websocket/server.d.ts +0 -15
  166. package/build/websocket/server.js +0 -127
  167. package/build/websocket/server.js.map +0 -1
  168. package/build/websocket/types.d.ts +0 -39
  169. package/build/websocket/types.js +0 -2
  170. package/build/websocket/types.js.map +0 -1
  171. package/build/websocket/utils.d.ts +0 -8
  172. package/build/websocket/utils.js +0 -77
  173. package/build/websocket/utils.js.map +0 -1
  174. package/src/api-router.ts +0 -50
  175. package/src/app-utils.ts +0 -82
  176. package/src/common/api-router-types.ts +0 -52
  177. package/src/common/api-router-utils.ts +0 -126
  178. package/src/common/config/config.ts +0 -49
  179. package/src/common/config/featuretoggle.ts +0 -6
  180. package/src/common/config/loader.ts +0 -81
  181. package/src/common/context.ts +0 -192
  182. package/src/common/error/badrequesterror.ts +0 -6
  183. package/src/common/error/configfilenotfound.ts +0 -6
  184. package/src/common/error/forbiddenerror.ts +0 -6
  185. package/src/common/error/notfound.ts +0 -6
  186. package/src/common/error/notimplemented.ts +0 -6
  187. package/src/common/error/unauthorizederror.ts +0 -6
  188. package/src/common/logger/constants.ts +0 -28
  189. package/src/common/logger/factory.ts +0 -53
  190. package/src/common/logger/interfaces.ts +0 -19
  191. package/src/common/logger/logger.ts +0 -136
  192. package/src/common/logger/transport/console.ts +0 -36
  193. package/src/common/logger/transport/file.ts +0 -26
  194. package/src/common/parser.ts +0 -50
  195. package/src/common/router-default-logger-factory.ts +0 -44
  196. package/src/common/router-handler.ts +0 -186
  197. package/src/common/router-types.ts +0 -153
  198. package/src/common/router-utils.ts +0 -47
  199. package/src/common/session/common.ts +0 -40
  200. package/src/common/session/service.ts +0 -175
  201. package/src/common/tokenize-match.ts +0 -98
  202. package/src/common/url-utils.ts +0 -46
  203. package/src/middleware/buffer.ts +0 -82
  204. package/src/middleware/cookie.ts +0 -20
  205. package/src/middleware/cors.ts +0 -98
  206. package/src/middleware/form.ts +0 -61
  207. package/src/middleware/group.ts +0 -74
  208. package/src/middleware/json.ts +0 -57
  209. package/src/middleware/logger.ts +0 -18
  210. package/src/middleware/parse.ts +0 -105
  211. package/src/middleware/result.ts +0 -73
  212. package/src/middleware/tag.ts +0 -15
  213. package/src/middleware/text.ts +0 -47
  214. package/src/proxy.ts +0 -99
  215. package/src/router.ts +0 -140
  216. package/src/static.ts +0 -242
  217. package/src/websocket/cluster.ts +0 -128
  218. package/src/websocket/server.ts +0 -135
  219. package/src/websocket/types.ts +0 -41
  220. package/src/websocket/utils.ts +0 -95
@@ -0,0 +1,840 @@
1
+ import { IncomingMessage, RequestListener } from "http";
2
+ import {
3
+ Logger,
4
+ routerDefaultLoggerFactory
5
+ } from "../common.js";
6
+ import {
7
+ Request,
8
+ Response,
9
+ ErrorHandler,
10
+ Handler,
11
+ Method,
12
+ HandlerWithOptions,
13
+ HandlerWithOptionsSchema,
14
+ MinimalRouter,
15
+ RouterHandlerOptions,
16
+ RouterHandlerOptionsSchema,
17
+ RouterJSONDoc,
18
+ RouterOptions,
19
+ isMinimalRouter,
20
+ normalizePath,
21
+ PathParams,
22
+ PathPart,
23
+ PathPartToken,
24
+ matchTokenizePath,
25
+ splitPath,
26
+ tokenizePath,
27
+ APIRouterOptions,
28
+ APIRouterOptionsSchema,
29
+ APIRoute,
30
+ APIRouteSchema,
31
+ MinimalLogger,
32
+ } from "../types.js";
33
+ import { ServerOptions } from "http";
34
+ import { SessionHandler, GroupPolicyHandler } from "./session.js";
35
+ import { DEFAULT_PARSER, assertNotUndefined, ResponseHandler, ResultParser, ParseRequest } from "./body-parser.js";
36
+ import { RequestOptions, request } from "@miqro/request";
37
+ import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "fs";
38
+ import { basename, extname, join, parse, resolve } from "path";
39
+
40
+ /**
41
+ * Router Public
42
+ */
43
+
44
+ export class Router implements MinimalRouter {
45
+ protected readonly handlers: RouterHandler[] = [];
46
+ protected readonly errorHandlers: ErrorHandler[] = [];
47
+ public readonly listener: RequestListener<typeof Request, typeof Response>;
48
+ public serverOptions: ServerOptions<typeof Request, typeof Response> = {
49
+ IncomingMessage: Request,
50
+ ServerResponse: Response
51
+ }
52
+
53
+ constructor(protected config?: RouterOptions) {
54
+ const loggerFactory = this.config && this.config.loggerFactory ? this.config.loggerFactory : routerDefaultLoggerFactory;
55
+ this.listener = async (req, res) => {
56
+ req.logger = loggerFactory(req.uuid, req);
57
+ req.logger.trace(`request received`);
58
+ await this.run(req, res);
59
+ };
60
+ }
61
+
62
+ public get(path: string | undefined, handler: Array<Handler> | Handler | MinimalRouter | HandlerWithOptions, options?: RouterHandlerOptions): Router {
63
+ return this.use(handler, path, "get", options);
64
+ }
65
+
66
+ public post(path: string | undefined, handler: Array<Handler> | Handler | MinimalRouter | HandlerWithOptions, options?: RouterHandlerOptions): Router {
67
+ return this.use(handler, path, "post", options);
68
+ }
69
+
70
+ public patch(path: string | undefined, handler: Array<Handler> | Handler | MinimalRouter | HandlerWithOptions, options?: RouterHandlerOptions): Router {
71
+ return this.use(handler, path, "patch", options);
72
+ }
73
+
74
+ public delete(path: string | undefined, handler: Array<Handler> | Handler | MinimalRouter | HandlerWithOptions, options?: RouterHandlerOptions): Router {
75
+ return this.use(handler, path, "delete", options);
76
+ }
77
+
78
+ public put(path: string | undefined, handler: Array<Handler> | Handler | MinimalRouter | HandlerWithOptions, options?: RouterHandlerOptions): Router {
79
+ return this.use(handler, path, "put", options);
80
+ }
81
+
82
+ public options(path: string | undefined, handler: Array<Handler> | Handler | MinimalRouter | HandlerWithOptions, options?: RouterHandlerOptions): Router {
83
+ return this.use(handler, path, "options", options);
84
+ }
85
+
86
+ public use(handler: Array<Handler> | HandlerWithOptions | Handler | MinimalRouter, path?: string, method?: Method, options?: RouterHandlerOptions): Router {
87
+ const nPath = path !== undefined ? normalizePath(path) : undefined;
88
+ const nMethod = method ? method.toLowerCase() as Method : method;
89
+ this.handlers.push(new RouterHandler(handler, nPath, nMethod, options));
90
+ return this;
91
+ }
92
+
93
+ public catch(errorHandler: Array<ErrorHandler> | ErrorHandler): Router {
94
+ const errorHandlers = errorHandler instanceof Array ? errorHandler : [errorHandler];
95
+ for (const e of errorHandlers) {
96
+ if (typeof e !== "function") {
97
+ throw new Error(`errorHandler ${e} not a function!`);
98
+ }
99
+ this.errorHandlers.push(e);
100
+ }
101
+ return this;
102
+ }
103
+
104
+ public async run(req: Request, res: Response, pathTokens?: PathPart[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
105
+ //console.log("run(%s, %o)", req.path, pathTokens);
106
+ pathTokens = pathTokens ? pathTokens : splitPath(req.path);
107
+ //console.log("run(%s, %o)", req.path, pathTokens);
108
+ try {
109
+ for (const h of this.handlers) {
110
+ if (res.headersSent) {
111
+ break;
112
+ }
113
+ const isMatch = h.isMatch(req.method, pathTokens, prePathTokens);
114
+ //console.log("h.isMatch(%s, %o, %o)=%s", h.path, pathTokens, prePathTokens, isMatch);
115
+ if (isMatch.match) {
116
+ if (isMatch.params) {
117
+ req.params = req.params ? {
118
+ ...req.params,
119
+ ...isMatch.params
120
+ } : isMatch.params;
121
+ }
122
+ const shouldContinue = await h.invoke(req, res, pathTokens, prePathTokens);
123
+ if (!shouldContinue) {
124
+ break;
125
+ }
126
+ }
127
+ }
128
+ return !res.headersSent;
129
+ } catch (e: any) {
130
+ for (const eH of this.errorHandlers) {
131
+ const ret = await eH(e, req, res);
132
+ if (ret === false || res.headersSent) {
133
+ return false;
134
+ }
135
+ }
136
+ throw e; // pass the error along
137
+ }
138
+ }
139
+
140
+ public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
141
+ for (const h of this.handlers) {
142
+ doc = h.getJSONDoc(doc, prePath);
143
+ }
144
+ return doc;
145
+ }
146
+
147
+ public logPaths(logger: MinimalLogger): void {
148
+ this.toString().split("\n").forEach(l => logger.info(l));
149
+ }
150
+
151
+ public toString(): string {
152
+ let ret = "";
153
+ const doc = this.getJSONDoc();
154
+ const paths = Object.keys(doc);
155
+
156
+ for (const path of paths) {
157
+ if (path) {
158
+ const pathData = doc[path];
159
+
160
+ const methods = Object.keys(pathData);
161
+
162
+ for (const method of methods) {
163
+ if (method) {
164
+ const methodData = pathData[method];
165
+ ret += `${ret === "" ? "" : "\n"}${method}:${path}\n\t${methodData.identifier}${methodData.name ? `\n\t\t${methodData.name}` : ""}${methodData.description ? `\n\t\t${methodData.description}` : ""}`;
166
+ }
167
+ }
168
+ }
169
+ }
170
+ return ret;
171
+ }
172
+ }
173
+
174
+ class RouterHandler {
175
+
176
+ private readonly tokens: PathPartToken[];
177
+ private readonly handler: Array<Handler | MinimalRouter>;
178
+ private readonly isRouter: boolean;
179
+ private readonly options?: RouterHandlerOptions;
180
+
181
+ public constructor(
182
+ private readonly originalHandler: Array<Handler> | HandlerWithOptions | Handler | MinimalRouter,
183
+ public readonly path: string | undefined,
184
+ private readonly method: Method | undefined,
185
+ options?: RouterHandlerOptions) {
186
+ this.tokens = tokenizePath(path);
187
+
188
+ if (options) {
189
+ options = assertNotUndefined(DEFAULT_PARSER.parse(options, RouterHandlerOptionsSchema, "options"), "bad options");
190
+ }
191
+
192
+ let handlers: Array<Handler | MinimalRouter> = []
193
+ this.isRouter = isMinimalRouter(originalHandler); //handler instanceof Router;
194
+
195
+ if (!this.isRouter && !(originalHandler instanceof Array) && typeof originalHandler === "object") {
196
+ // HandlerWithOptions
197
+ if (options) {
198
+ throw new Error("bad arguments. cannot send options with HandlerWithOptions");
199
+ }
200
+ //console.dir(handler);
201
+ const handlerWithOptions = assertNotUndefined(DEFAULT_PARSER.parse(originalHandler, HandlerWithOptionsSchema, "handler"), "bad options");
202
+ this.originalHandler = handlerWithOptions.handler;
203
+ this.options = handlerWithOptions;
204
+ } else {
205
+ this.options = options;
206
+ }
207
+ const routeHandlers = this.originalHandler instanceof Array ? this.originalHandler : [this.originalHandler] as Array<Handler | MinimalRouter>;
208
+
209
+ //if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && this.options)) {
210
+ if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length)) {
211
+ throw new Error(`bad arguments isRouter[${this.isRouter}]`);
212
+ }
213
+
214
+ if (this.options && this.options.middleware) {
215
+ handlers = handlers.concat(this.options.middleware);
216
+ }
217
+ if (this.options && this.options.session) {
218
+ handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
219
+ }
220
+ if (this.options && this.options.policy) {
221
+ handlers.push(GroupPolicyHandler(this.options.policy));
222
+ }
223
+ if (this.options && this.options.request) {
224
+ handlers.push(ParseRequest(this.options.request, this.options.parser));
225
+ }
226
+
227
+ handlers = handlers.concat(routeHandlers);
228
+
229
+ if (this.options && this.options.response && !this.isRouter) {
230
+
231
+ const responseMiddleware = typeof this.options.response === "boolean" ? [ResponseHandler] : this.options.response.middleware ? (
232
+ this.options.response.middleware instanceof Array ?
233
+ this.options.response.middleware :
234
+ [this.options.response.middleware]
235
+ ) :
236
+ [ResponseHandler];
237
+
238
+ if (typeof this.options.response !== "boolean") {
239
+ handlers.push(ResultParser(this.options.response, this.options.parser));
240
+ }
241
+ handlers = handlers.concat(responseMiddleware);
242
+ }
243
+ this.handler = handlers;
244
+ }
245
+
246
+ public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
247
+ const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
248
+ const nMethod = this.method ? this.method : "";
249
+
250
+ if (this.isRouter) {
251
+ const router: MinimalRouter = this.originalHandler as MinimalRouter;
252
+ router.getJSONDoc(doc, `${prePath}${nPath}`);
253
+ } else {
254
+ if (!doc[`${prePath}${nPath}`]) {
255
+ doc[`${prePath}${nPath}`] = Object.create(null);
256
+ }
257
+ if (doc[`${prePath}${nPath}`][nMethod]) {
258
+ throw new Error("cannot create doc routes override each other");
259
+ }
260
+ if (this.options) {
261
+ doc[`${prePath}${nPath}`][nMethod] = {
262
+ description: this.options.description,
263
+ name: this.options.name,
264
+ identifier: this.options.identifier ? this.options.identifier : `${prePath}${nPath}${this.options.name ? this.options.name : ""}${nMethod ? `_${nMethod}` : ""}`.replace(/[^a-z0-9+]+/gi, '_').split("_").map(s => s.trim()).filter(s => s).join("_").toUpperCase(),
265
+ policy: this.options.policy,
266
+ request: this.options.request ? {
267
+ body: this.options.request.body,
268
+ headers: this.options.request.headers,
269
+ params: this.options.request.params,
270
+ query: this.options.request.query,
271
+ } : undefined,
272
+ response: typeof this.options.response === "boolean" ? this.options.response : this.options.response ? {
273
+ body: this.options.response.body
274
+ } : undefined
275
+ };
276
+ } else {
277
+ doc[`${prePath}${nPath}`][nMethod] = {
278
+ description: undefined,
279
+ name: undefined,
280
+ identifier: `${prePath}${nPath}${nMethod ? `_${nMethod}` : ""}`.replace(/[^a-z0-9+]+/gi, '_').split("_").map(s => s.trim()).filter(s => s).join("_").toUpperCase(),
281
+ policy: undefined,
282
+ request: undefined,
283
+ response: undefined
284
+ };
285
+ }
286
+ }
287
+ return doc;
288
+ }
289
+
290
+ public async invoke(req: Request, res: Response, pathTokens: PathPart[], prePathTokens: PathPartToken[]): Promise<boolean> {
291
+ for (let i = 0; i < this.handler.length; i++) {
292
+ const h = this.handler[i];
293
+ if (isMinimalRouter(h)) {
294
+ //if (h instanceof Router) {
295
+ if (!RouterHandler.pushResults(await (h as MinimalRouter).run(req, res, pathTokens, prePathTokens.concat(this.tokens)), req)) {
296
+ return false;
297
+ }
298
+ } else {
299
+ if (!RouterHandler.pushResults(await (h as Handler)(req, res), req)) {
300
+ return false;
301
+ }
302
+ }
303
+ }
304
+ return true;
305
+ }
306
+
307
+ public isMatch(
308
+ method: string | undefined,
309
+ requestParts: PathPart[],
310
+ prePathTokens: PathPartToken[]): {
311
+ match: boolean;
312
+ params?: PathParams
313
+ } {
314
+ if ((this.method === undefined || this.method === method)) {
315
+ if (this.path === undefined) {
316
+ //console.log("isMatch(%s, %s, %s)=%s", method, this.method, this.path, true);
317
+ return {
318
+ match: true
319
+ };
320
+ }
321
+ const ret = matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), requestParts);
322
+ //console.log("isMatch(%s, %s, %s)=%s", method, this.method, this.path, ret);
323
+ return ret;
324
+ }
325
+ //console.log("isMatch(%s, %s, %s)=%s", method, this.method, this.path, false);
326
+ return {
327
+ match: false
328
+ };
329
+ }
330
+
331
+ private static pushResults(result: any, req: Request): boolean {
332
+ if (result === false) {
333
+ // ctx.logger.debug(`avoiding next handlers because handler returned false.`);
334
+ return false;
335
+ } else if (result !== true && result !== undefined) {
336
+ req.logger.trace("pushing to results [%o]", result);
337
+ req.results.push(result);
338
+ }
339
+ return true;
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Proxy
345
+ */
346
+
347
+ export interface ProxyRouterOptions extends RouterOptions {
348
+ url: string;
349
+ rejectUnauthorized?: boolean;
350
+ }
351
+
352
+ class ProxyRouter extends Router {
353
+ private readonly proxyURL: URL;
354
+ private readonly rejectUnauthorized?: boolean;
355
+
356
+ constructor(options: ProxyRouterOptions) {
357
+ super(options);
358
+ const proxyURL = new URL(options.url);
359
+ proxyURL.pathname = normalizePath(proxyURL.pathname);
360
+ this.proxyURL = proxyURL;
361
+ this.rejectUnauthorized = options.rejectUnauthorized;
362
+ }
363
+
364
+ async run(req: Request, res: Response, pathTokens?: { value: string; lower: string }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
365
+
366
+ const level = prePathTokens.length;
367
+ const shouldContinue = await super.run(req, res, pathTokens, prePathTokens);
368
+
369
+ if (shouldContinue) {
370
+ const relative = req.path.split("/").map(s => s.trim()).filter(s => s).slice(level).join("/");
371
+
372
+ const nUrl = new URL(this.proxyURL.toString());
373
+ nUrl.pathname = nUrl.pathname + relative;
374
+ const url = nUrl.toString();
375
+
376
+ const headers = {
377
+ ...req.headers
378
+ };
379
+
380
+ delete headers["connection"];
381
+ delete headers["keep-alive"];
382
+
383
+ let responseHeaders;
384
+
385
+ const requestArgs: RequestOptions = {
386
+ url: url.toString(),
387
+ query: req.query,
388
+ disableThrow: true,
389
+ rejectUnauthorized: this.rejectUnauthorized,
390
+ disableUserAgent: true,
391
+ method: req.method,
392
+ headers,
393
+ onChunk: async function (chunk: Buffer, chunkReq: IncomingMessage): Promise<void> {
394
+ const responseHeaders = {
395
+ ...chunkReq.headers
396
+ };
397
+ delete responseHeaders["connection"];
398
+ delete responseHeaders["keep-alive"];
399
+ if (!res.headersSent) {
400
+ const headerNames = Object.keys(responseHeaders);
401
+ for (const name of headerNames) {
402
+ res.setHeader(name, responseHeaders[name] as any);
403
+ }
404
+ }
405
+ if (chunkReq.statusCode !== undefined) {
406
+ res.statusCode = chunkReq.statusCode
407
+ }
408
+ await res.asyncWrite(chunk);
409
+ },
410
+ data: req.method !== "GET" ? req.buffer : undefined
411
+ };
412
+
413
+ req.logger.info("proxy to %s", url.toString());
414
+ req.logger.debug("proxy with %o", requestArgs);
415
+
416
+ const response = await request(requestArgs);
417
+
418
+ if (!res.headersSent) {
419
+ const responseHeaders = {
420
+ ...response.headers
421
+ };
422
+ const headerNames = Object.keys(responseHeaders);
423
+ for (const name of headerNames) {
424
+ res.setHeader(name, responseHeaders[name] as any);
425
+ }
426
+ }
427
+
428
+ await res.end();
429
+ }
430
+ return !res.headersSent;
431
+ }
432
+ }
433
+
434
+ export function Proxy(options: ProxyRouterOptions) {
435
+ return new ProxyRouter(options);
436
+ }
437
+
438
+ /**
439
+ * Static Router
440
+ */
441
+
442
+ async function outputFile(path: string, contentType: string, req: Request, res: Response, allowGetJSON: boolean, status = 200) {
443
+ const buffer = readFileSync(path);
444
+ return allowGetJSON && req.query.format && req.query.format === "json" ?
445
+ res.json({
446
+ buffer
447
+ }) :
448
+ res.asyncEnd({
449
+ status,
450
+ headers: {
451
+ ["Content-Type"]: contentType
452
+ },
453
+ body: buffer
454
+ });
455
+ }
456
+
457
+ async function generateList(path: string, req: Request, res: Response, allowListJSON: boolean) {
458
+ const files = readdirSync(path);
459
+ return allowListJSON && req.query.format && req.query.format === "json" ?
460
+ res.json({ files: files.map(f => `${req.path}${f}`) }) :
461
+ res.html(`<html><body><ul>${files.map(f => `<li><a href="${req.path}${f}">${f}</a></li>`).join("")}</ul></body></html>`);
462
+ }
463
+
464
+ export interface StaticRouterOptions extends RouterOptions {
465
+ directory: string;
466
+ list?: boolean;
467
+ allowListJSON?: boolean;
468
+ allowGetJSON?: boolean;
469
+ index?: string;
470
+ index404?: string;
471
+ index404Status?: number;
472
+ contentTypes?: any;
473
+ defaultContentType?: string;
474
+ }
475
+
476
+ export function Static(options: StaticRouterOptions): Router {
477
+ return new StaticRouter(options);
478
+ }
479
+
480
+ class StaticRouter extends Router {
481
+
482
+ private readonly staticOptions: {
483
+ directory: string;
484
+ list: boolean;
485
+ allowListJSON: boolean;
486
+ allowGetJSON: boolean;
487
+ index: string;
488
+ index404: string;
489
+ index404Status: number;
490
+ contentTypes: any;
491
+ defaultContentType: string;
492
+ };
493
+
494
+ constructor(options: StaticRouterOptions) {
495
+ super(options);
496
+ this.staticOptions = assertNotUndefined(DEFAULT_PARSER.parse(options, {
497
+ type: "object",
498
+ properties: {
499
+ loggerFactory: {
500
+ required: false,
501
+ type: "any"
502
+ },
503
+ directory: {
504
+ type: "string",
505
+ required: true
506
+ },
507
+ list: {
508
+ type: "boolean",
509
+ required: false,
510
+ defaultValue: false
511
+ },
512
+ allowListJSON: {
513
+ type: "boolean",
514
+ required: false,
515
+ defaultValue: false
516
+ },
517
+ allowGetJSON: {
518
+ type: "boolean",
519
+ required: false,
520
+ defaultValue: false
521
+ },
522
+ index: {
523
+ type: "string",
524
+ required: false,
525
+ defaultValue: "index.html"
526
+ },
527
+ index404: {
528
+ type: "string",
529
+ required: false
530
+ },
531
+ index404Status: {
532
+ type: "number",
533
+ required: false,
534
+ defaultValue: 404
535
+ },
536
+ contentTypes: {
537
+ type: "object",
538
+ required: false,
539
+ defaultValue: {
540
+ ".aac": "audio/aac",
541
+ ".abw": "application/x-abiword",
542
+ ".arc": "application/x-freearc",
543
+ ".avif": "image/avif",
544
+ ".avi": "video/x-msvideo",
545
+ ".azw": "application/vnd.amazon.ebook",
546
+ ".bin": "application/octet-stream",
547
+ ".bmp": "image/bmp",
548
+ ".bz": "application/x-bzip",
549
+ ".bz2": "application/x-bzip2",
550
+ ".cda": "application/x-cdf",
551
+ ".csh": "application/x-csh",
552
+ ".css": "text/css",
553
+ ".csv": "text/csv",
554
+ ".doc": "application/msword",
555
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
556
+ ".eot": "application/vnd.ms-fontobject",
557
+ ".epub": "application/epub+zip",
558
+ ".gz": "application/gzip",
559
+ ".gif": "image/gif",
560
+ ".htm": "text/html",
561
+ ".html": "text/html",
562
+ ".ico": "image/vnd.microsoft.icon",
563
+ ".ics": "text/calendar",
564
+ ".jar": "application/java-archive",
565
+ ".jpeg": "image/jpeg",
566
+ ".jpg": "image/jpeg",
567
+ ".js": "text/javascript",
568
+ ".json": "application/json",
569
+ ".jsonld": "application/ld+json",
570
+ ".mid": "audio/midi audio/x-midi",
571
+ ".midi": "audio/midi audio/x-midi",
572
+ ".mjs": "text/javascript",
573
+ ".mp3": "audio/mpeg",
574
+ ".mp4": "video/mp4",
575
+ ".mpeg": "video/mpeg",
576
+ ".mpkg": "application/vnd.apple.installer+xml",
577
+ ".odp": "application/vnd.oasis.opendocument.presentation",
578
+ ".ods": "application/vnd.oasis.opendocument.spreadsheet",
579
+ ".odt": "application/vnd.oasis.opendocument.text",
580
+ ".oga": "audio/ogg",
581
+ ".ogv": "video/ogg",
582
+ ".ogx": "application/ogg",
583
+ ".opus": "audio/opus",
584
+ ".otf": "font/otf",
585
+ ".png": "image/png",
586
+ ".pdf": "application/pdf",
587
+ ".php": "application/x-httpd-php",
588
+ ".ppt": "application/vnd.ms-powerpoint",
589
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
590
+ ".rar": "application/vnd.rar",
591
+ ".rtf": "application/rtf",
592
+ ".sh": "application/x-sh",
593
+ ".svg": "image/svg+xml",
594
+ ".swf": "application/x-shockwave-flash",
595
+ ".tar": "application/x-tar",
596
+ ".tif": "image/tiff",
597
+ ".tiff": "image/tiff",
598
+ ".ts": "video/mp2t",
599
+ ".ttf": "font/ttf",
600
+ ".txt": "text/plain",
601
+ ".vsd": "application/vnd.visio",
602
+ ".wav": "audio/wav",
603
+ ".weba": "audio/webm",
604
+ ".webm": "video/webm",
605
+ ".webp": "image/webp",
606
+ ".woff": "font/woff",
607
+ ".woff2": "font/woff2",
608
+ ".xhtml": "application/xhtml+xml",
609
+ ".xls": "application/vnd.ms-excel",
610
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
611
+ ".xml": "application/xml",
612
+ ".xul": "application/vnd.mozilla.xul+xml",
613
+ ".zip": "application/zip",
614
+ ".3gp": "video/3gpp; audio/3gpp",
615
+ ".3g2": "video/3gpp2; audio/3gpp2",
616
+ ".7z": "application/x-7z-compressed"
617
+ }
618
+ },
619
+ defaultContentType: {
620
+ type: "string",
621
+ required: false,
622
+ defaultValue: "application/octet-stream"
623
+ }
624
+ }
625
+ }, "options"), "bad options");
626
+ if (!statSync(this.staticOptions.directory).isDirectory()) {
627
+ throw new Error(`options.directory ${this.staticOptions.directory} not a directory`);
628
+ }
629
+ if (this.staticOptions.index404 && !existsSync(resolve(this.staticOptions.directory, this.staticOptions.index404))) {
630
+ throw new Error(`options.index404 ${this.staticOptions.index404} not a found`);
631
+ }
632
+ }
633
+
634
+ public async run(req: Request, res: Response, pathTokens?: { value: string; lower: string; }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
635
+ const { directory, allowGetJSON, allowListJSON, list, index, contentTypes, defaultContentType } = this.staticOptions;
636
+ const level = prePathTokens.length;
637
+ if (String(req.method).toLowerCase() === "get") {
638
+ const realPath = resolve(directory, req.path.split("/").map(s => s.trim()).filter(s => s).slice(level).join("/"));
639
+ req.logger.debug("static get %s", realPath);
640
+
641
+ if (existsSync(realPath)) {
642
+ if (statSync(realPath).isDirectory()) {
643
+ // directory
644
+ const indexPath = resolve(realPath, index);
645
+ if (index && existsSync(indexPath) && statSync(indexPath).isFile()) {
646
+ // index file exists
647
+ const ext = extname(indexPath);
648
+ const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
649
+ await outputFile(indexPath, contentType, req, res, allowGetJSON);
650
+ } else {
651
+ // index doesn't exists
652
+ if (list) {
653
+ // generate list
654
+ await generateList(realPath, req, res, allowListJSON);
655
+ }
656
+ }
657
+ } else {
658
+ // direct file access
659
+ const ext = extname(realPath);
660
+ const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
661
+ await outputFile(realPath, contentType, req, res, allowGetJSON);
662
+ }
663
+ }
664
+ }
665
+ if (this.staticOptions.index404) {
666
+ const realPath = resolve(this.staticOptions.directory, this.staticOptions.index404);
667
+ if (existsSync(realPath)) {
668
+ const ext = extname(realPath);
669
+ const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
670
+ await outputFile(realPath, contentType, req, res, allowGetJSON, this.staticOptions.index404Status);
671
+ }
672
+ }
673
+ return !res.headersSent ? super.run(req, res, pathTokens, prePathTokens) : false;
674
+ }
675
+ }
676
+
677
+ /**
678
+ * # APIRouter
679
+ *
680
+ * src/server.js
681
+ * ```typescript
682
+ *import { App, APIRouter } from "@miqro/core";
683
+ *const app = new App();
684
+ *app.use(APIRouter({ dirname: resolve(__dirname, "api") }));
685
+ *app.listen(8080);
686
+ * ```
687
+ *
688
+ * src/api/user/post.js
689
+ *
690
+ * ```typescript
691
+ *import { ReadBuffer, JSONParser, APIRoute } from "@miqro/core";
692
+ *
693
+ *const route: APIRoute = {
694
+ * middleware: [ReadBuffer(), JSONParser()],
695
+ * request: {
696
+ * query: { ... },
697
+ * body: { ... },
698
+ * ...
699
+ * },
700
+ * response: {
701
+ * ...
702
+ * },
703
+ * handler: async (ctx: Context) => {
704
+ * return {
705
+ * status: 200,
706
+ * body: {
707
+ * status: "OK"
708
+ * }
709
+ * };
710
+ * }
711
+ *}
712
+ *export default route;
713
+ * ```
714
+ */
715
+ export async function APIRouter(options: APIRouterOptions, logger?: Logger): Promise<MinimalRouter> {
716
+ const { dirname } = assertNotUndefined(DEFAULT_PARSER.parse(options, APIRouterOptionsSchema, "options"), "bad options");
717
+ if (typeof dirname !== "string") {
718
+ throw new Error(`options.dirname must be defined!`);
719
+ }
720
+ if (!existsSync(dirname) || !lstatSync(dirname).isDirectory()) {
721
+ throw new Error(`${dirname} not a directory!`);
722
+ }
723
+ const apiName = options.apiName !== undefined ? options.apiName : basename(dirname);
724
+ const apiPath = options.path !== undefined ? options.path : "";
725
+ return await traverseAPIRouteDir(apiName.toUpperCase(), dirname, apiPath, undefined, logger);
726
+ }
727
+
728
+ type UseCallArg = [Handler | Handler[] | MinimalRouter, string | undefined, Method | undefined, RouterHandlerOptions];
729
+
730
+ async function traverseAPIRouteDir(
731
+ featureName: string,
732
+ dirname: string,
733
+ basePath = "/",
734
+ router: Router = new Router(), logger?: Logger): Promise<Router> {
735
+ if (logger) {
736
+ logger.trace("loading routes from [%s]", dirname);
737
+ }
738
+ const files = readdirSync(dirname);
739
+ const dirs = files.filter(f => lstatSync(join(dirname, f)).isDirectory());
740
+ const methods = files.filter(f => !lstatSync(join(dirname, f)).isDirectory());
741
+
742
+ const postFolder: UseCallArg[] = [];
743
+
744
+ for (const f of methods) {
745
+ const { name, ext } = parse(f);
746
+ if (name !== "index" && ((ext === ".ts" || ext === ".js") && name.slice(-2) !== ".d")) {
747
+ const filePath = join(dirname, f);
748
+ //console.log("dirname=%s f=%s", dirname, f);
749
+ let route: APIRoute = await import(filePath);
750
+ //if ((route as any).default && (route as any).__esModule === true) {
751
+ if ((route as any).default) {
752
+ route = (route as any).default;
753
+ // ugly hack when import is importing a commonjs that exports default
754
+ if ((route as any).default) {
755
+ route = (route as any).default;
756
+ }
757
+ }
758
+ //const ___filePath = filePath + ext;
759
+ const ___filePath = filePath;
760
+ //let routeMethods: Method[] = [name] as Method[];
761
+ let routeMethod: Method | "use" | "USE" = name as Method;
762
+ if (typeof route === "function") {
763
+ route = {
764
+ handler: route
765
+ } as any;
766
+ } else {
767
+ if (typeof route.method !== "undefined" && (/*!(route.method instanceof Array) &&*/ (typeof route.method !== "string"))) {
768
+ //throw new Error(`${resolve(dirname, name)} doesn't export method as a string or string array`);
769
+ throw new Error(`${resolve(dirname, name)} doesnt export method as a string`);
770
+ } else if (typeof route.method !== "undefined") {
771
+ routeMethod = route.method;//route.method instanceof Array ? route.method : [route.method];
772
+ }
773
+ if (typeof route.path !== "string" && typeof route.path !== "undefined"/* && !(route.path instanceof Array)*/) {
774
+ //throw new Error(`${resolve(dirname, name)} doesn't export path as a string or a string array`);
775
+ throw new Error(`${resolve(dirname, name)} doesnt export path as a string`);
776
+ }
777
+ if ((!(route.handler instanceof Array) && typeof route.handler !== "function" && !isMinimalRouter(route.handler)) || typeof route.handler === "undefined") {
778
+ throw new Error(`${resolve(dirname, name)} doesnt export handler as a function or an array`);
779
+ }
780
+ if (typeof route.name !== "string" && typeof route.name !== "undefined") {
781
+ throw new Error(`${resolve(dirname, name)} doesnt export name as a string`);
782
+ }
783
+ }
784
+ try {
785
+ route = assertNotUndefined(DEFAULT_PARSER.parse(route, APIRouteSchema, ___filePath), `error parsing [${___filePath}]`);
786
+ } catch (e) {
787
+ console.error("error parsing " + ___filePath);
788
+ throw e;
789
+ }
790
+ //const paths = route.path instanceof Array ? route.path : route.path === undefined ? [route.method && route.method.indexOf(name as Method) === -1 ? `/${name}` : "/"] : [route.path];
791
+ const p = route.path === undefined ? route.method && route.method.indexOf(name as Method) === -1 ? `/${name}` : "/" : route.path;
792
+ //for (let i = 0; i < paths.length; i++) {
793
+ //const p = paths[i];
794
+ if (typeof p !== "string" || !p) {
795
+ throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
796
+ }
797
+ const path = normalizePath(`${basePath}${p && p !== "/" ? `${p}` : p}`)
798
+
799
+ const subName = (p.charAt(0) === "/" ? p.substring(1) : p).replace(/[^a-z0-9+]+/gi, '_');
800
+ const routeName = route.name ? route.name : name;
801
+
802
+ //const identifier = route.identifier ? route.identifier : getPathIdentifier(path, routeMethod);
803
+
804
+ /*let newFeatureSubPath = `${featureName}_${route.name ? route.name : name}${routeName !== subName ? `_${subName}` : ""}`.toUpperCase();
805
+
806
+ newFeatureSubPath = newFeatureSubPath.length > 1 && newFeatureSubPath.charAt(newFeatureSubPath.length - 1) === "_" ? newFeatureSubPath.substring(0, newFeatureSubPath.length - 1) : newFeatureSubPath;*/
807
+ /*if (features[identifier]) {
808
+ throw new Error(`${___filePath} feature name collides with ${(features[identifier] as any).___filePath}`)
809
+ }*/
810
+ if (route.identifier && route.identifier === "__prototype__" || route.identifier === "__proto__") {
811
+ throw new Error(`invalid feature name ${route.identifier}`);
812
+ }
813
+ const useCallArgs: UseCallArg = [route.handler, path, routeMethod !== "use" && routeMethod !== "USE" ? routeMethod : undefined, {
814
+ identifier: route.identifier,
815
+ apiName: route.apiName,
816
+ name: route.name,
817
+ description: route.description,
818
+ parser: route.parser,
819
+ middleware: route.middleware,
820
+ session: route.session,
821
+ policy: route.policy,
822
+ request: route.request,
823
+ response: route.response ? route.response : true // ResponseHandler added by default to an APIRoute
824
+ }];
825
+ if (route.postFolder) {
826
+ postFolder.push(useCallArgs);
827
+ } else {
828
+ router.use(...useCallArgs);
829
+ }
830
+ }
831
+ }
832
+ for (const f of dirs) {
833
+ const { name } = parse(f);
834
+ router = await traverseAPIRouteDir(`${featureName}_${name}`.toUpperCase(), join(dirname, f), `${basePath}/${name}`, router, logger);
835
+ }
836
+ for (const post of postFolder) {
837
+ router.use(...post);
838
+ }
839
+ return router;
840
+ };