@miqro/core 1.2.5 → 1.3.4

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 (304) hide show
  1. package/README.md +34 -18
  2. package/dist/handler/api-handler.d.ts +16 -0
  3. package/dist/handler/api-handler.js +30 -5
  4. package/dist/handler/api-handler.js.map +1 -0
  5. package/dist/handler/api-router-utils.js +11 -2
  6. package/dist/handler/api-router-utils.js.map +1 -0
  7. package/dist/handler/api-router.d.ts +30 -2
  8. package/dist/handler/api-router.js +30 -0
  9. package/dist/handler/api-router.js.map +1 -0
  10. package/dist/handler/app.d.ts +1 -2
  11. package/dist/handler/app.js +96 -13
  12. package/dist/handler/app.js.map +1 -0
  13. package/dist/handler/common/context.d.ts +57 -0
  14. package/dist/handler/common/context.js +123 -0
  15. package/dist/handler/common/context.js.map +1 -0
  16. package/dist/handler/common/helpers.js +5 -0
  17. package/dist/handler/common/helpers.js.map +1 -0
  18. package/dist/handler/common/index.d.ts +2 -45
  19. package/dist/handler/common/index.js +13 -109
  20. package/dist/handler/common/index.js.map +1 -0
  21. package/dist/handler/common/router-utils.d.ts +26 -0
  22. package/dist/handler/common/router-utils.js +59 -0
  23. package/dist/handler/common/router-utils.js.map +1 -0
  24. package/dist/handler/{router.d.ts → common/router.d.ts} +7 -16
  25. package/dist/handler/common/router.js +76 -0
  26. package/dist/handler/common/router.js.map +1 -0
  27. package/dist/handler/common/tokenize-match.d.ts +18 -9
  28. package/dist/handler/common/tokenize-match.js +42 -30
  29. package/dist/handler/common/tokenize-match.js.map +1 -0
  30. package/dist/handler/feature-router.d.ts +1 -2
  31. package/dist/handler/feature-router.js +3 -2
  32. package/dist/handler/feature-router.js.map +1 -0
  33. package/dist/handler/index.d.ts +1 -5
  34. package/dist/handler/index.js +2 -5
  35. package/dist/handler/index.js.map +1 -0
  36. package/dist/{middleware → handler/middleware}/buffer.d.ts +1 -1
  37. package/dist/{middleware → handler/middleware}/buffer.js +3 -2
  38. package/dist/handler/middleware/buffer.js.map +1 -0
  39. package/dist/handler/middleware/cookie.d.ts +4 -0
  40. package/dist/handler/middleware/cookie.js +18 -0
  41. package/dist/handler/middleware/cookie.js.map +1 -0
  42. package/dist/{middleware → handler/middleware}/cors.d.ts +1 -1
  43. package/dist/{middleware → handler/middleware}/cors.js +10 -2
  44. package/dist/handler/middleware/cors.js.map +1 -0
  45. package/dist/{middleware → handler/middleware}/form.d.ts +1 -1
  46. package/dist/{middleware → handler/middleware}/form.js +8 -5
  47. package/dist/handler/middleware/form.js.map +1 -0
  48. package/dist/handler/middleware/group.d.ts +3 -0
  49. package/dist/handler/{group.js → middleware/group.js} +4 -2
  50. package/dist/handler/middleware/group.js.map +1 -0
  51. package/dist/handler/middleware/index.d.ts +13 -0
  52. package/dist/handler/middleware/index.js +64 -0
  53. package/dist/handler/middleware/index.js.map +1 -0
  54. package/dist/{middleware → handler/middleware}/json.d.ts +1 -1
  55. package/dist/{middleware → handler/middleware}/json.js +3 -2
  56. package/dist/handler/middleware/json.js.map +1 -0
  57. package/dist/{middleware → handler/middleware}/logger.d.ts +1 -1
  58. package/dist/{middleware → handler/middleware}/logger.js +1 -0
  59. package/dist/handler/middleware/logger.js.map +1 -0
  60. package/dist/handler/{parse.d.ts → middleware/parse.d.ts} +4 -3
  61. package/dist/handler/{parse.js → middleware/parse.js} +17 -7
  62. package/dist/handler/middleware/parse.js.map +1 -0
  63. package/dist/handler/middleware/session.d.ts +21 -0
  64. package/dist/handler/middleware/session.js +140 -0
  65. package/dist/handler/middleware/session.js.map +1 -0
  66. package/dist/handler/middleware/tag.d.ts +4 -0
  67. package/dist/handler/middleware/tag.js +14 -0
  68. package/dist/handler/middleware/tag.js.map +1 -0
  69. package/dist/{middleware → handler/middleware}/text.d.ts +1 -1
  70. package/dist/{middleware → handler/middleware}/text.js +3 -2
  71. package/dist/handler/middleware/text.js.map +1 -0
  72. package/dist/handler/proxy.js +5 -11
  73. package/dist/handler/proxy.js.map +1 -0
  74. package/dist/handler/{html.d.ts → response/html.d.ts} +1 -1
  75. package/dist/handler/{html.js → response/html.js} +1 -0
  76. package/dist/handler/response/html.js.map +1 -0
  77. package/dist/handler/response/index.d.ts +3 -0
  78. package/dist/{middleware → handler/response}/index.js +3 -7
  79. package/dist/handler/response/index.js.map +1 -0
  80. package/dist/handler/{response.d.ts → response/json.d.ts} +1 -1
  81. package/dist/handler/{response.js → response/json.js} +3 -2
  82. package/dist/handler/response/json.js.map +1 -0
  83. package/dist/handler/response/result.d.ts +4 -0
  84. package/dist/handler/{result.js → response/result.js} +8 -8
  85. package/dist/handler/response/result.js.map +1 -0
  86. package/dist/index.d.ts +0 -1
  87. package/dist/index.js +1 -1
  88. package/dist/index.js.map +1 -0
  89. package/dist/util/cli/index.js +3 -0
  90. package/dist/util/cli/index.js.map +1 -0
  91. package/dist/util/config/browser.js +3 -0
  92. package/dist/util/config/browser.js.map +1 -0
  93. package/dist/util/config/config.js +6 -1
  94. package/dist/util/config/config.js.map +1 -0
  95. package/dist/util/config/featuretoggle.js +1 -0
  96. package/dist/util/config/featuretoggle.js.map +1 -0
  97. package/dist/util/config/index.js +1 -0
  98. package/dist/util/config/index.js.map +1 -0
  99. package/dist/util/cookie/cookie.d.ts +50 -0
  100. package/dist/util/cookie/cookie.js +168 -0
  101. package/dist/util/cookie/cookie.js.map +1 -0
  102. package/dist/util/cookie/index.d.ts +16 -0
  103. package/dist/util/cookie/index.js +9 -0
  104. package/dist/util/cookie/index.js.map +1 -0
  105. package/dist/util/error/configfilenotfound.js +1 -0
  106. package/dist/util/error/configfilenotfound.js.map +1 -0
  107. package/dist/util/error/forbiddenerror.js +1 -0
  108. package/dist/util/error/forbiddenerror.js.map +1 -0
  109. package/dist/util/error/index.js +1 -0
  110. package/dist/util/error/index.js.map +1 -0
  111. package/dist/util/error/named.js +1 -0
  112. package/dist/util/error/named.js.map +1 -0
  113. package/dist/util/error/notfound.js +1 -0
  114. package/dist/util/error/notfound.js.map +1 -0
  115. package/dist/util/error/notimplemented.js +1 -0
  116. package/dist/util/error/notimplemented.js.map +1 -0
  117. package/dist/util/error/parsererror.js +1 -0
  118. package/dist/util/error/parsererror.js.map +1 -0
  119. package/dist/util/error/unauthorizederror.js +1 -0
  120. package/dist/util/error/unauthorizederror.js.map +1 -0
  121. package/dist/util/index.js +3 -0
  122. package/dist/util/index.js.map +1 -0
  123. package/dist/util/loader/index.js +1 -0
  124. package/dist/util/loader/index.js.map +1 -0
  125. package/dist/util/logger/common.js +1 -0
  126. package/dist/util/logger/common.js.map +1 -0
  127. package/dist/util/logger/factory.js +1 -0
  128. package/dist/util/logger/factory.js.map +1 -0
  129. package/dist/util/logger/formatter.js +1 -0
  130. package/dist/util/logger/formatter.js.map +1 -0
  131. package/dist/util/logger/index.js +1 -0
  132. package/dist/util/logger/index.js.map +1 -0
  133. package/dist/util/logger/logger.js +12 -2
  134. package/dist/util/logger/logger.js.map +1 -0
  135. package/dist/util/logger/transport.js +1 -0
  136. package/dist/util/logger/transport.js.map +1 -0
  137. package/dist/util/parser/common.d.ts +5 -5
  138. package/dist/util/parser/common.js +1 -0
  139. package/dist/util/parser/common.js.map +1 -0
  140. package/dist/util/parser/get.js +11 -1
  141. package/dist/util/parser/get.js.map +1 -0
  142. package/dist/util/parser/index.js +1 -0
  143. package/dist/util/parser/index.js.map +1 -0
  144. package/dist/util/parser/parser.d.ts +24 -3
  145. package/dist/util/parser/parser.js +46 -11
  146. package/dist/util/parser/parser.js.map +1 -0
  147. package/dist/util/parser/types/any.js +1 -0
  148. package/dist/util/parser/types/any.js.map +1 -0
  149. package/dist/util/parser/types/array.js +1 -0
  150. package/dist/util/parser/types/array.js.map +1 -0
  151. package/dist/util/parser/types/boolean.js +1 -0
  152. package/dist/util/parser/types/boolean.js.map +1 -0
  153. package/dist/util/parser/types/email.js +1 -0
  154. package/dist/util/parser/types/email.js.map +1 -0
  155. package/dist/util/parser/types/enum.js +1 -0
  156. package/dist/util/parser/types/enum.js.map +1 -0
  157. package/dist/util/parser/types/index.js +1 -0
  158. package/dist/util/parser/types/index.js.map +1 -0
  159. package/dist/util/parser/types/multiple.js +6 -2
  160. package/dist/util/parser/types/multiple.js.map +1 -0
  161. package/dist/util/parser/types/nested.js +1 -0
  162. package/dist/util/parser/types/nested.js.map +1 -0
  163. package/dist/util/parser/types/number.js +1 -0
  164. package/dist/util/parser/types/number.js.map +1 -0
  165. package/dist/util/parser/types/object.js +1 -0
  166. package/dist/util/parser/types/object.js.map +1 -0
  167. package/dist/util/parser/types/regex.js +1 -0
  168. package/dist/util/parser/types/regex.js.map +1 -0
  169. package/dist/util/parser/types/string.js +1 -0
  170. package/dist/util/parser/types/string.js.map +1 -0
  171. package/dist/util/parser/types/url.js +1 -0
  172. package/dist/util/parser/types/url.js.map +1 -0
  173. package/dist/util/request/common.d.ts +9 -0
  174. package/dist/util/request/common.js +101 -1
  175. package/dist/util/request/common.js.map +1 -0
  176. package/dist/util/request/index.js +143 -185
  177. package/dist/util/request/index.js.map +1 -0
  178. package/dist/util/session/common.d.ts +16 -0
  179. package/dist/util/session/common.js +49 -0
  180. package/dist/util/session/common.js.map +1 -0
  181. package/dist/util/session/index.d.ts +2 -16
  182. package/dist/util/session/index.js +13 -46
  183. package/dist/util/session/index.js.map +1 -0
  184. package/dist/util/session/service.d.ts +26 -0
  185. package/dist/util/session/service.js +143 -0
  186. package/dist/util/session/service.js.map +1 -0
  187. package/dist/util/test/app.js +5 -1
  188. package/dist/util/test/app.js.map +1 -0
  189. package/dist/util/test/common.js +1 -0
  190. package/dist/util/test/common.js.map +1 -0
  191. package/dist/util/test/index.js +1 -0
  192. package/dist/util/test/index.js.map +1 -0
  193. package/dist/util/uuid/index.d.ts +7 -0
  194. package/dist/util/uuid/index.js +8 -0
  195. package/dist/util/uuid/index.js.map +1 -0
  196. package/dist/util/uuid/regex.d.ts +2 -0
  197. package/dist/util/uuid/regex.js +5 -0
  198. package/dist/util/uuid/regex.js.map +1 -0
  199. package/dist/util/uuid/rng.d.ts +1 -0
  200. package/dist/util/uuid/rng.js +18 -0
  201. package/dist/util/uuid/rng.js.map +1 -0
  202. package/dist/util/uuid/stringify.d.ts +2 -0
  203. package/dist/util/uuid/stringify.js +50 -0
  204. package/dist/util/uuid/stringify.js.map +1 -0
  205. package/dist/util/uuid/v4.d.ts +5 -0
  206. package/dist/util/uuid/v4.js +27 -0
  207. package/dist/util/uuid/v4.js.map +1 -0
  208. package/dist/util/uuid/validate.d.ts +2 -0
  209. package/dist/util/uuid/validate.js +12 -0
  210. package/dist/util/uuid/validate.js.map +1 -0
  211. package/package.json +11 -13
  212. package/src/handler/api-handler.ts +56 -0
  213. package/src/handler/api-router-utils.ts +101 -0
  214. package/src/handler/api-router.ts +60 -0
  215. package/src/handler/app.ts +138 -0
  216. package/src/handler/common/context.ts +161 -0
  217. package/src/handler/common/helpers.ts +11 -0
  218. package/src/handler/common/index.ts +3 -0
  219. package/src/handler/common/router-utils.ts +67 -0
  220. package/src/handler/common/router.ts +70 -0
  221. package/src/handler/common/tokenize-match.ts +152 -0
  222. package/src/handler/feature-router.ts +90 -0
  223. package/src/handler/index.ts +8 -0
  224. package/src/handler/middleware/buffer.ts +79 -0
  225. package/src/handler/middleware/cookie.ts +19 -0
  226. package/src/handler/middleware/cors.ts +98 -0
  227. package/src/handler/middleware/form.ts +53 -0
  228. package/src/handler/middleware/group.ts +28 -0
  229. package/src/handler/middleware/index.ts +52 -0
  230. package/src/handler/middleware/json.ts +50 -0
  231. package/src/handler/middleware/logger.ts +18 -0
  232. package/src/handler/middleware/parse.ts +93 -0
  233. package/src/handler/middleware/session.ts +155 -0
  234. package/src/handler/middleware/tag.ts +15 -0
  235. package/src/handler/middleware/text.ts +40 -0
  236. package/src/handler/proxy.ts +44 -0
  237. package/src/handler/response/html.ts +36 -0
  238. package/src/handler/response/index.ts +3 -0
  239. package/src/handler/response/json.ts +19 -0
  240. package/src/handler/response/result.ts +40 -0
  241. package/src/index.ts +2 -0
  242. package/src/util/cli/index.ts +57 -0
  243. package/src/util/config/browser.ts +5 -0
  244. package/src/util/config/config.ts +93 -0
  245. package/src/util/config/featuretoggle.ts +6 -0
  246. package/src/util/config/index.ts +3 -0
  247. package/src/util/cookie/cookie.ts +207 -0
  248. package/src/util/cookie/index.ts +6 -0
  249. package/src/util/error/configfilenotfound.ts +8 -0
  250. package/src/util/error/forbiddenerror.ts +8 -0
  251. package/src/util/error/index.ts +6 -0
  252. package/src/util/error/named.ts +3 -0
  253. package/src/util/error/notfound.ts +8 -0
  254. package/src/util/error/notimplemented.ts +8 -0
  255. package/src/util/error/parsererror.ts +10 -0
  256. package/src/util/error/unauthorizederror.ts +8 -0
  257. package/src/util/index.ts +11 -0
  258. package/src/util/loader/index.ts +67 -0
  259. package/src/util/logger/common.ts +6 -0
  260. package/src/util/logger/factory.ts +45 -0
  261. package/src/util/logger/formatter.ts +9 -0
  262. package/src/util/logger/index.ts +6 -0
  263. package/src/util/logger/logger.ts +114 -0
  264. package/src/util/logger/transport.ts +69 -0
  265. package/src/util/parser/common.ts +81 -0
  266. package/src/util/parser/get.ts +42 -0
  267. package/src/util/parser/index.ts +6 -0
  268. package/src/util/parser/parser.ts +235 -0
  269. package/src/util/parser/types/any.ts +8 -0
  270. package/src/util/parser/types/array.ts +73 -0
  271. package/src/util/parser/types/boolean.ts +13 -0
  272. package/src/util/parser/types/email.ts +26 -0
  273. package/src/util/parser/types/enum.ts +29 -0
  274. package/src/util/parser/types/index.ts +12 -0
  275. package/src/util/parser/types/multiple.ts +36 -0
  276. package/src/util/parser/types/nested.ts +19 -0
  277. package/src/util/parser/types/number.ts +34 -0
  278. package/src/util/parser/types/object.ts +10 -0
  279. package/src/util/parser/types/regex.ts +17 -0
  280. package/src/util/parser/types/string.ts +23 -0
  281. package/src/util/parser/types/url.ts +35 -0
  282. package/src/util/request/common.ts +193 -0
  283. package/src/util/request/index.ts +230 -0
  284. package/src/util/session/common.ts +63 -0
  285. package/src/util/session/index.ts +2 -0
  286. package/src/util/session/service.ts +154 -0
  287. package/src/util/test/app.ts +44 -0
  288. package/src/util/test/common.ts +17 -0
  289. package/src/util/test/index.ts +2 -0
  290. package/src/util/uuid/index.ts +5 -0
  291. package/src/util/uuid/regex.ts +2 -0
  292. package/src/util/uuid/rng.ts +14 -0
  293. package/src/util/uuid/stringify.ts +53 -0
  294. package/src/util/uuid/v4.ts +30 -0
  295. package/src/util/uuid/validate.ts +8 -0
  296. package/tsconfig.json +32 -0
  297. package/dist/handler/common/response.d.ts +0 -13
  298. package/dist/handler/common/response.js +0 -54
  299. package/dist/handler/error.d.ts +0 -2
  300. package/dist/handler/error.js +0 -46
  301. package/dist/handler/group.d.ts +0 -3
  302. package/dist/handler/result.d.ts +0 -4
  303. package/dist/handler/router.js +0 -116
  304. package/dist/middleware/index.d.ts +0 -6
@@ -0,0 +1,101 @@
1
+ import { lstatSync, readdirSync } from "fs";
2
+ import { join, parse, resolve } from "path";
3
+ import { Logger } from "../util/logger";
4
+ import { APIHandler } from "./api-handler";
5
+ import { APIRoute } from "./api-router";
6
+ import { Method } from "./common";
7
+ import { normalizePath } from "./common/tokenize-match";
8
+ import { FeatureRouterOptions } from "./feature-router";
9
+
10
+ interface TraversedAPIRoute extends APIRoute {
11
+ method: Method | Method[];
12
+ path: string | string[];
13
+ }
14
+
15
+ export const traverseAPIRouteDir = (
16
+ featureName: string,
17
+ dirname: string,
18
+ basePath = "/",
19
+ features: FeatureRouterOptions<TraversedAPIRoute> = {}, logger?: Logger): FeatureRouterOptions<TraversedAPIRoute> => {
20
+ if (logger) {
21
+ logger.trace("loading routes from [%s]", dirname);
22
+ }
23
+ const files = readdirSync(dirname);
24
+ const dirs = files.filter(f => lstatSync(join(dirname, f)).isDirectory());
25
+ const methods = files.filter(f => !lstatSync(join(dirname, f)).isDirectory());
26
+ for (const f of dirs) {
27
+ const { name } = parse(f);
28
+ features = traverseAPIRouteDir(`${featureName}_${name}`.toUpperCase(), join(dirname, f), `${basePath}/${name}`, features, logger);
29
+ }
30
+ for (const f of methods) {
31
+ const { name, ext } = parse(f);
32
+ if (name !== "index" && ((ext === ".ts" || ext === ".js") && name.slice(-2) !== ".d")) {
33
+ const filePath = join(dirname, name);
34
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
35
+ let route: APIRoute = require(filePath);
36
+ if ((route as any).default && (route as any).__esModule === true) {
37
+ route = (route as any).default;
38
+ }
39
+ const ___filePath = filePath + ext;
40
+ let routeMethods: Method[] = [name] as Method[];
41
+ if (typeof route === "function") {
42
+ route = {
43
+ handler: route
44
+ } as any;
45
+ } else {
46
+ if (typeof route.method !== "undefined" && (!(route.method instanceof Array) && (typeof route.method !== "string"))) {
47
+ throw new Error(`${resolve(dirname, name)} doesnt export method as a string or string array`);
48
+ } else if (typeof route.method !== "undefined") {
49
+ routeMethods = route.method instanceof Array ? route.method : [route.method];
50
+ }
51
+ if (typeof route.path !== "string" && typeof route.path !== "undefined" && !(route.path instanceof Array)) {
52
+ throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
53
+ }
54
+ if ((!(route.handler instanceof Array) && typeof route.handler !== "function") || typeof route.handler === "undefined") {
55
+ throw new Error(`${resolve(dirname, name)} doesnt export handler as a function or an array`);
56
+ }
57
+ if (typeof route.name !== "string" && typeof route.name !== "undefined") {
58
+ throw new Error(`${resolve(dirname, name)} doesnt export name as a string`);
59
+ }
60
+ }
61
+
62
+ const paths = route.path instanceof Array ? route.path : route.path === undefined ? [route.method && route.method.indexOf(name as Method) === -1 ? `/${name}` : "/"] : [route.path];
63
+ for (let i = 0; i < paths.length; i++) {
64
+ const p = paths[i];
65
+ if (typeof p !== "string" || !p) {
66
+ throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
67
+ }
68
+ const path = normalizePath(`${basePath}${p && p !== "/" ? `${p}` : ""}`)
69
+
70
+ const subName = (p.charAt(0) === "/" ? p.substring(1) : p).replace(/[^a-z0-9+]+/gi, '_');
71
+ const routeName = route.name ? route.name : name;
72
+
73
+ let newFeatureSubPath = `${featureName}_${route.name ? route.name : name}${routeName !== subName ? `_${subName}` : ""}`.toUpperCase();
74
+
75
+ newFeatureSubPath = newFeatureSubPath.length > 1 && newFeatureSubPath.charAt(newFeatureSubPath.length - 1) === "_" ? newFeatureSubPath.substring(0, newFeatureSubPath.length - 1) : newFeatureSubPath;
76
+ if (features[newFeatureSubPath]) {
77
+ throw new Error(`${___filePath} feature name collides with ${(features[newFeatureSubPath] as any).___filePath}`)
78
+ }
79
+ features[newFeatureSubPath] = {
80
+ ...route,
81
+ path,
82
+ method: routeMethods,
83
+ handler: APIHandler({
84
+ session: route.session,
85
+ policy: route.policy,
86
+ middleware: route.middleware,
87
+ body: route.body,
88
+ params: route.params,
89
+ parser: route.parser,
90
+ query: route.query,
91
+ result: route.result,
92
+ handler: route.handler,
93
+ responseHandler: route.responseHandler
94
+ })
95
+ };
96
+ (features[newFeatureSubPath] as any).___filePath = ___filePath;
97
+ }
98
+ }
99
+ }
100
+ return features;
101
+ };
@@ -0,0 +1,60 @@
1
+ import { existsSync, lstatSync } from "fs";
2
+ import { basename } from "path";
3
+ import { Logger } from "../util";
4
+ import { APIHandlerOptions } from "./api-handler";
5
+ import { traverseAPIRouteDir } from "./api-router-utils";
6
+ import { Router, Method } from "./common";
7
+ import { FeatureRouter } from "./feature-router";
8
+
9
+ export interface APIRoute extends APIHandlerOptions {
10
+ name?: string;
11
+ description?: string;
12
+ method?: Method | Method[];
13
+ path?: string | string[];
14
+ }
15
+
16
+ /**
17
+ * # APIRouter
18
+ *
19
+ * src/server.js
20
+ * ```typescript
21
+ *import { App, APIRouter } from "@miqro/core";
22
+ *const app = new App();
23
+ *app.use(APIRouter({ dirname: resolve(__dirname, "api") }));
24
+ *app.listen(8080);
25
+ * ```
26
+ *
27
+ * src/api/user/post.js
28
+ *
29
+ * ```typescript
30
+ *import { ReadBuffer, JSONParser, APIRoute } from "@miqro/core";
31
+ *
32
+ *const route: APIRoute = {
33
+ * middleware: [ReadBuffer(), JSONParser()]
34
+ * query: { ... },
35
+ * body: { ... },
36
+ * result: { ... },
37
+ * handler: async (ctx: Context) => {
38
+ * return {
39
+ * status: "OK"
40
+ * };
41
+ * }
42
+ *}
43
+ * ```
44
+ */
45
+ export const APIRouter = (options: {
46
+ dirname: string;
47
+ apiName?: string;
48
+ path?: string;
49
+ }, logger?: Logger): Router => {
50
+ const { dirname } = options;
51
+ if (typeof dirname !== "string") {
52
+ throw new Error(`options.dirname must be defined!`);
53
+ }
54
+ if (!existsSync(dirname) || !lstatSync(dirname).isDirectory()) {
55
+ throw new Error(`${dirname} not a directory!`);
56
+ }
57
+ const apiName = options.apiName !== undefined ? options.apiName : basename(dirname);
58
+ const apiPath = options.path !== undefined ? options.path : `/${apiName}`;
59
+ return FeatureRouter(traverseAPIRouteDir(apiName.toUpperCase(), dirname, apiPath, undefined, logger), logger);
60
+ };
@@ -0,0 +1,138 @@
1
+ import { createServer, IncomingMessage, RequestListener, Server, ServerResponse } from "http";
2
+ import { Logger } from "../util";
3
+ import { Router, Context, ErrorHandler } from "./common";
4
+
5
+ export interface AppOptions {
6
+ newRequestLogger?: (req: IncomingMessage) => Logger;
7
+ newContext?: (req: IncomingMessage, res: ServerResponse) => Context;
8
+ }
9
+
10
+ export class App extends Router {
11
+ public readonly listener: RequestListener;
12
+
13
+ constructor(private appOptions?: AppOptions) {
14
+ super();
15
+ const errorHandler = DefaultErrorHandler();
16
+ this.listener = async (req, res) => {
17
+ const ctx = this.appOptions && this.appOptions.newContext ?
18
+ this.appOptions.newContext(req, res) :
19
+ new Context(
20
+ req,
21
+ res,
22
+ this.appOptions && this.appOptions.newRequestLogger ?
23
+ this.appOptions.newRequestLogger(req) :
24
+ undefined);
25
+ ctx.logger.trace(`request received`);
26
+ try {
27
+ await this.run(ctx);
28
+ if (!ctx.res.headersSent) {
29
+ ctx.end({
30
+ headers: TEXT_HEADERS,
31
+ status: STATUS.NOT_FOUND,
32
+ body: "NOT FOUND"
33
+ });
34
+ }
35
+ } catch (e: any) {
36
+ try {
37
+ if (!ctx.res.headersSent) {
38
+ await errorHandler(e, ctx);
39
+ if (!ctx.res.headersSent) {
40
+ ctx.logger.error(e);
41
+ ctx.end({
42
+ headers: TEXT_HEADERS,
43
+ status: STATUS.ERROR,
44
+ body: "SERVER ERROR"
45
+ });
46
+ }
47
+ }
48
+ } catch (e3) {
49
+ ctx.logger.error(e3);
50
+ }
51
+ }
52
+ };
53
+ }
54
+ public listen(...args: any[]): Server {
55
+ return createServer(this.listener).listen(...args)
56
+ }
57
+ }
58
+
59
+ const TEXT_HEADERS = {
60
+ ["Content-Type"]: "plain/text; charset=utf-8"
61
+ }
62
+
63
+ const STATUS = {
64
+ ERROR: 503,
65
+ BAD_REQUEST: 400,
66
+ NOT_FOUND: 404,
67
+ NOT_IMPLEMENTED: 501,
68
+ FORBIDDEN: 403,
69
+ UNAUTHORIZED: 401,
70
+ };
71
+
72
+ const DefaultErrorHandler = (): ErrorHandler<boolean> => {
73
+ return async (e: any, ctx: Context): Promise<boolean> => {
74
+ if (!e || !e.name || e.name === "Error") {
75
+ if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
76
+ ctx.logger.error(e);
77
+ await ctx.end({
78
+ headers: TEXT_HEADERS,
79
+ status: STATUS.ERROR,
80
+ body: `${e && e.message ? e.message : String(e)}. You are seeing this message because NODE_ENV === "development" || NODE_ENV === "test"${e && e.stack ? ` ${e.stack}` : ""}`
81
+ });
82
+ return false;
83
+ }
84
+ } else {
85
+ ctx.logger.error(e);
86
+ const name = e && e.name ? e.name : undefined;
87
+ switch (name) {
88
+ case "NotFoundError":
89
+ await ctx.end({
90
+ headers: TEXT_HEADERS,
91
+ status: STATUS.NOT_FOUND,
92
+ body: e.message ? e.message : "NOT FOUND"
93
+ });
94
+ break;
95
+ case "MethodNotImplementedError":
96
+ await ctx.end({
97
+ headers: TEXT_HEADERS,
98
+ status: STATUS.NOT_IMPLEMENTED,
99
+ body: e.message ? e.message : "NOT IMPLEMENTED"
100
+ });
101
+ break;
102
+ case "ForbiddenError":
103
+ await ctx.end({
104
+ headers: TEXT_HEADERS,
105
+ status: STATUS.FORBIDDEN,
106
+ body: e.message ? e.message : "FORBIDDEN"
107
+ });
108
+ break;
109
+ case "UnAuthorizedError":
110
+ await ctx.end({
111
+ headers: TEXT_HEADERS,
112
+ status: STATUS.UNAUTHORIZED,
113
+ body: e.message ? e.message : "UNAUTHORIZED"
114
+ });
115
+ break;
116
+ case "ParseOptionsError":
117
+ case "SequelizeValidationError":
118
+ case "SequelizeEagerLoadingError":
119
+ case "SequelizeUniqueConstraintError":
120
+ await ctx.end({
121
+ headers: TEXT_HEADERS,
122
+ status: STATUS.BAD_REQUEST,
123
+ body: e.message ? e.message : "BAD REQUEST"
124
+ });
125
+ break;
126
+ default:
127
+ await ctx.end({
128
+ headers: TEXT_HEADERS,
129
+ status: STATUS.ERROR,
130
+ body: e.message ? e.message : "SERVER ERROR"
131
+ });
132
+ break;
133
+ }
134
+ return false;
135
+ }
136
+ return true;
137
+ };
138
+ };
@@ -0,0 +1,161 @@
1
+ import { getLogger, Logger } from "../../util/logger";
2
+ import { Session } from "../../util/session";
3
+ import { IncomingHttpHeaders, IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "http";
4
+ import { normalizePath, parseSearchParams } from "./tokenize-match";
5
+ import { URL } from "url";
6
+ import { defaultLoggerFormatter } from "../../util/logger/formatter";
7
+ import { newURL } from "./helpers";
8
+ import { UUID } from "../../util/uuid";
9
+ import { COOKIE } from "../../util/cookie";
10
+
11
+ export type Method = "get" | "post" | "put" | "delete" | "patch" | "options" | "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS";
12
+
13
+ //export { BAD_REQUEST, METHOD_NOT_IMPLEMENTED, NOT_FOUND, ERROR_RESPONSE, FORBIDDEN, Response, UNAUTHORIZED } from "./response";
14
+
15
+ export type Handler<T = boolean | void | any> = ((ctx: Context) => Promise<T>) | ((ctx: Context) => T);
16
+
17
+ export type ErrorHandler<T = boolean | void | any> = ((e: unknown, ctx: Context) => Promise<T>) | ((e: unknown, ctx: Context) => T);
18
+
19
+ export class Context {
20
+ public readonly url: URL; // new URL(req.url ? req.url : "/", `http://${req.headers.host}`)
21
+ public readonly logger: Logger; // new Logger(...)
22
+ public readonly startMS: number; // Date.now()
23
+ public uuid: string; // a middleware will fill this
24
+ public session?: Session; // a middleware will fill this
25
+ public results: any[]; // handlers will fill this
26
+ public readonly path: string; // normalized path
27
+ public readonly hash: string; // from this.url.hash
28
+ public readonly method: string; // from this.url.method
29
+ public headers: IncomingHttpHeaders; // from this.req.headers
30
+ public readonly cookies: { [name: string]: string }; // a middleware will fill this
31
+ public query: { [name: string]: string | string[] }; // parseSearchParams will fill this with this.url.searchParams
32
+ public params: { [name: string]: string | undefined } = {}; // the router will fill this
33
+ public buffer: Buffer; // empty buffer. middleware must read it
34
+ public readonly remoteAddress?: string;
35
+ public body: any; // a middleware will fill this reading the buffer
36
+ constructor(public readonly req: IncomingMessage, public readonly res: ServerResponse, logger?: Logger) {
37
+ this.body = undefined as any;
38
+ this.res.removeHeader("Date");
39
+ this.url = newURL(req.url ? req.url : "/", `http://${req.headers.host}`) as URL;
40
+ this.method = req.method ? req.method.toUpperCase() as string : "GET";
41
+ this.path = normalizePath(this.url.pathname); // normalized path
42
+ this.hash = this.url.hash;
43
+ this.query = parseSearchParams(this.url.searchParams);
44
+ this.buffer = Buffer.from("");
45
+ this.remoteAddress = req.socket.remoteAddress;
46
+ this.cookies = {}; // a middleware will fill
47
+ this.headers = req.headers;
48
+ this.startMS = Date.now();
49
+ this.uuid = UUID.v4().toString("utf-8");
50
+ this.results = []; // handlers will fill this
51
+ const pathToEnv = this.path.replace(/\//ig, "_").toUpperCase();
52
+ const identifier = `${pathToEnv === "_" ? "" : pathToEnv.substring(1)}${this.method.toUpperCase()}`;
53
+ this.logger = logger ? logger : getLogger(identifier, {
54
+ formatter: ({
55
+ identifier,
56
+ level,
57
+ message,
58
+ }) => defaultLoggerFormatter({
59
+ identifier,
60
+ level,
61
+ message: `${this.method} ${this.url}${this.uuid ? ` [${this.uuid}]` : ""}${this.remoteAddress ? ` (${this.remoteAddress})` : ""}${this.session ?
62
+ ` session[${this.session.username}:${this.session.account}]` :
63
+ ""
64
+ } ${message}`
65
+ })
66
+ }, false);
67
+ }
68
+ public async close(): Promise<void> {
69
+ return this.end({
70
+ status: 400,
71
+ headers: {
72
+ connection: "close"
73
+ }
74
+ });
75
+ }
76
+ public addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse {
77
+ const c = this.res.getHeader("Vary");
78
+ const current = c ? c instanceof Array ? c.join(", ") : String(c) : "";
79
+ const nV = value instanceof Array ? value.join(", ") : String(value);
80
+ const newValue = current ? `${current}, ${nV}` : nV;
81
+ return this.res.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
82
+ }
83
+ public setHeader(name: string, value: number | string | ReadonlyArray<string>): ServerResponse {
84
+ return this.res.setHeader(name, value);
85
+ }
86
+ public setCookie(name: string, value: string, options?: {
87
+ encode?: (uriComponent: string | number | boolean) => string;
88
+ maxAge?: number | null;
89
+ domain?: string;
90
+ httpOnly?: boolean;
91
+ secure?: boolean;
92
+ path?: string;
93
+ expires?: Date;
94
+ sameSite?: "lax" | "strict" | "none" | true;
95
+ }): ServerResponse {
96
+ return this.setHeader('Set-Cookie', COOKIE.serialize(name, String(value), options));
97
+ }
98
+ public async end({ status, headers, body }: {
99
+ body?: any;
100
+ status: number;
101
+ headers: OutgoingHttpHeaders;
102
+ }): Promise<void> {
103
+ return new Promise<void>((resolve, reject) => {
104
+ try {
105
+ this.res.statusCode = status;
106
+ const keys = Object.keys(headers);
107
+ for (const key of keys) {
108
+ if (headers[key] !== undefined) {
109
+ this.res.setHeader(key, headers[key] as any);
110
+ }
111
+ }
112
+ this.res.end(body !== undefined ? String(body) : undefined, () => {
113
+ resolve();
114
+ });
115
+ } catch (e) {
116
+ reject(e);
117
+ }
118
+ });
119
+ }
120
+ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
121
+ public async json(body: any, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
122
+ return this.end({
123
+ status: status !== undefined ? status : 200,
124
+ headers: {
125
+ ['Content-Type']: 'application/json; charset=utf-8',
126
+ ...headers,
127
+ },
128
+ body: JSON.stringify(body)
129
+ })
130
+ }
131
+ public async text(text: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
132
+ return this.end({
133
+ status: status !== undefined ? status : 200,
134
+ headers: {
135
+ ['Content-Type']: 'plain/text; charset=utf-8',
136
+ ...headers
137
+ },
138
+ body: text
139
+ });
140
+ }
141
+ public async html(html: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
142
+ return this.end({
143
+ status: status !== undefined ? status : 200,
144
+ headers: {
145
+ ['Content-Type']: 'text/html; charset=utf-8',
146
+ ...headers
147
+ },
148
+ body: html
149
+ })
150
+ }
151
+ public async redirect(url: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
152
+ return this.end({
153
+ status: status !== undefined ? status : 302,
154
+ headers: {
155
+ ['Location']: url,
156
+ ...headers
157
+ }
158
+ })
159
+ }
160
+ }
161
+
@@ -0,0 +1,11 @@
1
+ export const newURL = (input: string, base?: string | any): any => {
2
+ /* eslint-disable @typescript-eslint/ban-ts-comment */
3
+ // @ts-ignore
4
+ return new URL(input, base)
5
+ }
6
+
7
+ export const newURLSearchParams = (arg?: string | any): any => {
8
+ /* eslint-disable @typescript-eslint/ban-ts-comment */
9
+ // @ts-ignore
10
+ return new URLSearchParams(arg);
11
+ }
@@ -0,0 +1,3 @@
1
+
2
+ export * from "./router";
3
+ export * from "./context";
@@ -0,0 +1,67 @@
1
+ import { Router } from "./router";
2
+ import { Context, Handler } from "./context";
3
+ import { Method } from "./context";
4
+ import { matchTokenizePath, PathPartToken, tokenizePath } from "./tokenize-match";
5
+
6
+ export class RouterHandler {
7
+
8
+ private readonly tokens: PathPartToken[];
9
+ private readonly handler: Array<Handler | Handler | Router>;
10
+ private readonly isRouter: boolean;
11
+
12
+ public constructor(handler: Array<Handler> | Handler | Router, private readonly path: string | undefined, private readonly method: Method | undefined) {
13
+ this.tokens = tokenizePath(path);
14
+ this.handler = handler instanceof Array ? handler : [handler];
15
+ this.isRouter = handler instanceof Router;
16
+ if (!this.isRouter && this.handler.length !== this.handler.filter(h => typeof h === "function").length) {
17
+ throw new Error("bad arguments handler must be an array of Handler or a Router");
18
+ }
19
+ }
20
+
21
+ public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
22
+ for (let i = 0; i < this.handler.length; i++) {
23
+ const h = this.handler[i];
24
+ if (h instanceof Router) {
25
+ if (!this.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
26
+ return false;
27
+ }
28
+ } else {
29
+ if (!this.pushResults(await h(ctx), ctx)) {
30
+ return false;
31
+ }
32
+ }
33
+ }
34
+ return true;
35
+ }
36
+
37
+ public isMatch(
38
+ method: string,
39
+ pathTokens: { value: string; lower: string; }[],
40
+ prePathTokens: PathPartToken[]): {
41
+ match: boolean;
42
+ params?: { [name: string]: string | undefined }
43
+ } {
44
+ if ((this.method === undefined || this.method === method)) {
45
+ if (this.path === undefined) {
46
+ return {
47
+ match: true
48
+ };
49
+ }
50
+ return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
51
+ }
52
+ return {
53
+ match: false
54
+ };
55
+ }
56
+
57
+ private pushResults(shouldContinue: boolean, ctx: Context): boolean {
58
+ if (shouldContinue === false) {
59
+ // ctx.logger.debug(`avoiding next handlers because handler returned false.`);
60
+ return false;
61
+ } else if (shouldContinue !== true && shouldContinue !== undefined) {
62
+ ctx.logger.trace("pushing to results [%o]", shouldContinue);
63
+ ctx.results.push(shouldContinue);
64
+ }
65
+ return true;
66
+ }
67
+ }
@@ -0,0 +1,70 @@
1
+ import { Method, Handler, Context, ErrorHandler } from "./context";
2
+ import { RouterHandler } from "./router-utils";
3
+ import { normalizePath, PathPartToken, splitPath } from "./tokenize-match";
4
+
5
+ export class Router {
6
+ protected readonly handlers: RouterHandler[] = [];
7
+ protected readonly errorHandlers: ErrorHandler[] = [];
8
+ public get(path: string, handler: Array<Handler> | Handler | Router): Router {
9
+ return this.use(handler, path, "get");
10
+ }
11
+ public post(path: string, handler: Array<Handler> | Handler | Router): Router {
12
+ return this.use(handler, path, "post");
13
+ }
14
+ public patch(path: string, handler: Array<Handler> | Handler | Router): Router {
15
+ return this.use(handler, path, "patch");
16
+ }
17
+ public delete(path: string, handler: Array<Handler> | Handler | Router): Router {
18
+ return this.use(handler, path, "delete");
19
+ }
20
+ public put(path: string, handler: Array<Handler> | Handler | Router): Router {
21
+ return this.use(handler, path, "put");
22
+ }
23
+ public options(path: string, handler: Array<Handler> | Handler | Router): Router {
24
+ return this.use(handler, path, "options");
25
+ }
26
+ public use(handler: Array<Handler> | Handler | Router, path?: string, method?: Method): Router {
27
+ const nPath = path !== undefined ? normalizePath(path) : undefined;
28
+ const nMethod = method ? method.toUpperCase() as Method : method;
29
+ this.handlers.push(new RouterHandler(handler, nPath, nMethod));
30
+ return this;
31
+ }
32
+ public catch(errorHandler: Array<ErrorHandler> | ErrorHandler): Router {
33
+ const errorHandlers = errorHandler instanceof Array ? errorHandler : [errorHandler];
34
+ for (const e of errorHandlers) {
35
+ this.errorHandlers.push(e);
36
+ }
37
+ return this;
38
+ }
39
+ public async run(ctx: Context, pathTokens?: { value: string; lower: string; }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
40
+ pathTokens = pathTokens ? pathTokens : splitPath(ctx.path);
41
+ try {
42
+ let shouldContinue = true;
43
+ for (const h of this.handlers) {
44
+ if (!shouldContinue || ctx.res.headersSent) {
45
+ shouldContinue = false;
46
+ break;
47
+ }
48
+ const isMatch = h.isMatch(ctx.method, pathTokens, prePathTokens);
49
+ if (isMatch.match) {
50
+ if (isMatch.params) {
51
+ ctx.params = ctx.params ? {
52
+ ...ctx.params,
53
+ ...isMatch.params
54
+ } : isMatch.params;
55
+ }
56
+ shouldContinue = await h.invoke(ctx, pathTokens, prePathTokens);
57
+ }
58
+ }
59
+ return !ctx.res.headersSent;
60
+ } catch (e: any) {
61
+ for (const eH of this.errorHandlers) {
62
+ const ret = await eH(e, ctx);
63
+ if (ret === false || ctx.res.headersSent) {
64
+ return false;
65
+ }
66
+ }
67
+ throw e; // pass the error along
68
+ }
69
+ }
70
+ }