@miqro/core 1.3.6 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.md +36 -112
  2. package/dist/handler/api-router-utils.d.ts +12 -1
  3. package/dist/handler/api-router-utils.js +86 -1
  4. package/dist/handler/api-router-utils.js.map +1 -1
  5. package/dist/handler/api-router.d.ts +29 -2
  6. package/dist/handler/api-router.js +2 -2
  7. package/dist/handler/api-router.js.map +1 -1
  8. package/dist/handler/app.js +1 -0
  9. package/dist/handler/app.js.map +1 -1
  10. package/dist/handler/common/context.d.ts +3 -11
  11. package/dist/handler/common/context.js +18 -13
  12. package/dist/handler/common/context.js.map +1 -1
  13. package/dist/handler/common/index.js.map +1 -1
  14. package/dist/handler/common/router-utils.js +60 -5
  15. package/dist/handler/common/router-utils.js.map +1 -1
  16. package/dist/handler/index.d.ts +0 -3
  17. package/dist/handler/index.js +0 -3
  18. package/dist/handler/index.js.map +1 -1
  19. package/dist/handler/middleware/cookie.js +2 -2
  20. package/dist/handler/middleware/cookie.js.map +1 -1
  21. package/dist/handler/middleware/form.js +7 -1
  22. package/dist/handler/middleware/form.js.map +1 -1
  23. package/dist/handler/middleware/group.js +44 -2
  24. package/dist/handler/middleware/group.js.map +1 -1
  25. package/dist/handler/middleware/index.js +2 -6
  26. package/dist/handler/middleware/index.js.map +1 -1
  27. package/dist/handler/middleware/json.js +8 -2
  28. package/dist/handler/middleware/json.js.map +1 -1
  29. package/dist/handler/middleware/session.js.map +1 -1
  30. package/dist/handler/middleware/text.js +8 -1
  31. package/dist/handler/middleware/text.js.map +1 -1
  32. package/dist/handler/proxy.d.ts +2 -5
  33. package/dist/handler/proxy.js +2 -3
  34. package/dist/handler/proxy.js.map +1 -1
  35. package/dist/util/cli/index.d.ts +6 -1
  36. package/dist/util/cli/index.js +26 -0
  37. package/dist/util/cli/index.js.map +1 -1
  38. package/dist/util/error/configfilenotfound.js.map +1 -1
  39. package/dist/util/error/forbiddenerror.js.map +1 -1
  40. package/dist/util/error/notfound.js.map +1 -1
  41. package/dist/util/error/notimplemented.js.map +1 -1
  42. package/dist/util/error/parsererror.d.ts +2 -1
  43. package/dist/util/error/parsererror.js +5 -1
  44. package/dist/util/error/parsererror.js.map +1 -1
  45. package/dist/util/error/unauthorizederror.js.map +1 -1
  46. package/dist/util/index.d.ts +0 -1
  47. package/dist/util/index.js +0 -3
  48. package/dist/util/index.js.map +1 -1
  49. package/dist/util/loader/index.d.ts +0 -3
  50. package/dist/util/loader/index.js +2 -9
  51. package/dist/util/loader/index.js.map +1 -1
  52. package/dist/util/logger/formatter.js +1 -1
  53. package/dist/util/logger/formatter.js.map +1 -1
  54. package/dist/util/request/index.d.ts +1 -1
  55. package/dist/util/request/index.js +1 -3
  56. package/dist/util/request/index.js.map +1 -1
  57. package/dist/util/session/common.d.ts +0 -1
  58. package/dist/util/session/common.js +0 -46
  59. package/dist/util/session/common.js.map +1 -1
  60. package/dist/util/session/service.js +2 -2
  61. package/dist/util/session/service.js.map +1 -1
  62. package/package.json +14 -11
  63. package/src/handler/api-router-utils.ts +91 -2
  64. package/src/handler/api-router.ts +30 -4
  65. package/src/handler/app.ts +2 -1
  66. package/src/handler/common/context.ts +19 -24
  67. package/src/handler/common/index.ts +1 -2
  68. package/src/handler/common/router-utils.ts +194 -146
  69. package/src/handler/index.ts +0 -3
  70. package/src/handler/middleware/cookie.ts +12 -12
  71. package/src/handler/middleware/form.ts +8 -2
  72. package/src/handler/middleware/group.ts +44 -2
  73. package/src/handler/middleware/index.ts +24 -28
  74. package/src/handler/middleware/json.ts +9 -3
  75. package/src/handler/middleware/session.ts +128 -128
  76. package/src/handler/middleware/text.ts +8 -1
  77. package/src/handler/proxy.ts +3 -8
  78. package/src/util/cli/index.ts +25 -1
  79. package/src/util/error/configfilenotfound.ts +1 -1
  80. package/src/util/error/forbiddenerror.ts +1 -1
  81. package/src/util/error/notfound.ts +1 -1
  82. package/src/util/error/notimplemented.ts +1 -1
  83. package/src/util/error/parsererror.ts +7 -2
  84. package/src/util/error/unauthorizederror.ts +1 -1
  85. package/src/util/index.ts +0 -3
  86. package/src/util/loader/index.ts +1 -7
  87. package/src/util/logger/formatter.ts +1 -1
  88. package/src/util/parser/common.ts +1 -1
  89. package/src/util/parser/index.ts +0 -3
  90. package/src/util/request/index.ts +2 -2
  91. package/src/util/session/common.ts +0 -43
  92. package/src/util/session/index.ts +1 -1
  93. package/src/util/session/service.ts +126 -126
  94. package/dist/handler/api-handler.d.ts +0 -29
  95. package/dist/handler/api-handler.js +0 -42
  96. package/dist/handler/api-handler.js.map +0 -1
  97. package/dist/handler/feature-router.d.ts +0 -12
  98. package/dist/handler/feature-router.js +0 -90
  99. package/dist/handler/feature-router.js.map +0 -1
  100. package/dist/handler/response/html.d.ts +0 -10
  101. package/dist/handler/response/html.js +0 -34
  102. package/dist/handler/response/html.js.map +0 -1
  103. package/dist/handler/response/index.d.ts +0 -3
  104. package/dist/handler/response/index.js +0 -16
  105. package/dist/handler/response/index.js.map +0 -1
  106. package/dist/handler/response/json.d.ts +0 -2
  107. package/dist/handler/response/json.js +0 -21
  108. package/dist/handler/response/json.js.map +0 -1
  109. package/dist/handler/response/result.d.ts +0 -4
  110. package/dist/handler/response/result.js +0 -46
  111. package/dist/handler/response/result.js.map +0 -1
  112. package/dist/util/client.d.ts +0 -17
  113. package/dist/util/client.js +0 -55
  114. package/dist/util/client.js.map +0 -1
  115. package/dist/util/cookie/cookie.d.ts +0 -50
  116. package/dist/util/cookie/cookie.js +0 -168
  117. package/dist/util/cookie/cookie.js.map +0 -1
  118. package/dist/util/cookie/index.d.ts +0 -16
  119. package/dist/util/cookie/index.js +0 -9
  120. package/dist/util/cookie/index.js.map +0 -1
  121. package/dist/util/test/app.d.ts +0 -3
  122. package/dist/util/test/app.js +0 -50
  123. package/dist/util/test/app.js.map +0 -1
  124. package/dist/util/test/common.d.ts +0 -6
  125. package/dist/util/test/common.js +0 -15
  126. package/dist/util/test/common.js.map +0 -1
  127. package/dist/util/test/index.d.ts +0 -2
  128. package/dist/util/test/index.js +0 -15
  129. package/dist/util/test/index.js.map +0 -1
  130. package/dist/util/uuid/index.d.ts +0 -7
  131. package/dist/util/uuid/index.js +0 -8
  132. package/dist/util/uuid/index.js.map +0 -1
  133. package/dist/util/uuid/regex.d.ts +0 -2
  134. package/dist/util/uuid/regex.js +0 -5
  135. package/dist/util/uuid/regex.js.map +0 -1
  136. package/dist/util/uuid/rng.d.ts +0 -1
  137. package/dist/util/uuid/rng.js +0 -18
  138. package/dist/util/uuid/rng.js.map +0 -1
  139. package/dist/util/uuid/stringify.d.ts +0 -2
  140. package/dist/util/uuid/stringify.js +0 -50
  141. package/dist/util/uuid/stringify.js.map +0 -1
  142. package/dist/util/uuid/v4.d.ts +0 -5
  143. package/dist/util/uuid/v4.js +0 -27
  144. package/dist/util/uuid/v4.js.map +0 -1
  145. package/dist/util/uuid/validate.d.ts +0 -2
  146. package/dist/util/uuid/validate.js +0 -12
  147. package/dist/util/uuid/validate.js.map +0 -1
  148. package/src/handler/api-handler.ts +0 -55
  149. package/src/handler/feature-router.ts +0 -92
  150. package/src/handler/response/html.ts +0 -36
  151. package/src/handler/response/index.ts +0 -3
  152. package/src/handler/response/json.ts +0 -19
  153. package/src/handler/response/result.ts +0 -40
  154. package/src/util/client.ts +0 -64
  155. package/src/util/cookie/cookie.ts +0 -207
  156. package/src/util/cookie/index.ts +0 -6
  157. package/src/util/test/app.ts +0 -44
  158. package/src/util/test/common.ts +0 -17
  159. package/src/util/test/index.ts +0 -2
  160. package/src/util/uuid/index.ts +0 -5
  161. package/src/util/uuid/regex.ts +0 -2
  162. package/src/util/uuid/rng.ts +0 -14
  163. package/src/util/uuid/stringify.ts +0 -53
  164. package/src/util/uuid/v4.ts +0 -30
  165. package/src/util/uuid/validate.ts +0 -8
@@ -3,182 +3,230 @@ import { Context, Handler } from "./context";
3
3
  import { Method } from "./context";
4
4
  import { matchTokenizePath, PathPartToken, tokenizePath } from "./tokenize-match"
5
5
  import { ParseRequest } from "../middleware/parse";
6
- import { Parser, ParseOptions } from "../../util/parser";
6
+ import { Parser, ParseOptions, parse } from "../../util/parser";
7
7
  import { SessionHandler, SessionHandlerOptions } from "../middleware/session";
8
8
  import { GroupPolicyHandler } from "../middleware/group";
9
- import { ResultParser } from "../response/result";
10
- import { ResponseHandler } from "../response/json";
11
9
  import { GroupPolicy } from "../../util/session";
12
10
 
11
+ const ResultParser = (options: ParseOptions | ParseOptions[], parser?: Parser): Handler<any> => async (ctx: Context): Promise<any> => {
12
+ if (!ctx.results || ctx.results.length === 0) {
13
+ ctx.logger.debug(`not parsing results`);
14
+ return undefined;
15
+ } else {
16
+ const index = ctx.results.length - 1;
17
+ const lastResult = ctx.results[index];
18
+ ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
19
+ try {
20
+ if (options instanceof Array) {
21
+ for (let i = 0; i < options.length; i++) {
22
+ const o = options[i];
23
+ try {
24
+ const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, o.options, o.mode, o.ignoreUndefined);
25
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
26
+ return mappedResults;
27
+ } catch (e) {
28
+ if (i === options.length - 1) {
29
+ throw e;
30
+ } else {
31
+ continue;
32
+ }
33
+ }
34
+ }
35
+ } else {
36
+ const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, options.options, options.mode, options.ignoreUndefined);
37
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
38
+ return mappedResults;
39
+ }
40
+ } catch (e) {
41
+ ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
42
+ throw e;
43
+ }
44
+ }
45
+ };
46
+
47
+ const ResponseHandler = (): Handler<void> => async (ctx: Context): Promise<void> => {
48
+ ctx.logger.trace("results [%o]", ctx.results);
49
+ if (!ctx.results || ctx.results.length === 0) {
50
+ throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
51
+ } else {
52
+ const lastResult = ctx.results[ctx.results.length - 1];
53
+ ctx.logger.debug("response [%o]", lastResult);
54
+ if (lastResult !== undefined) {
55
+ await ctx.json(lastResult);
56
+ } else {
57
+ throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
58
+ }
59
+ }
60
+ };
61
+
13
62
  export interface HandlerWithOptions extends RouterHandlerOptions {
14
- handler: Handler | Array<Handler>;
63
+ handler: Handler | Array<Handler>;
15
64
  }
16
65
 
17
66
  export interface RouteOptions {
18
- name?: string;
19
- description?: string;
20
- policy?: GroupPolicy;
21
- request?: {
22
- headers?: ParseOptions | ParseOptions[];
23
- query?: ParseOptions | false | ParseOptions[];
24
- params?: ParseOptions | false | ParseOptions[];
25
- body?: ParseOptions | false | ParseOptions[];
26
- };
27
- response?: true | ParseOptions | ParseOptions[];
67
+ name?: string;
68
+ description?: string;
69
+ policy?: GroupPolicy;
70
+ request?: {
71
+ headers?: ParseOptions | ParseOptions[];
72
+ query?: ParseOptions | false | ParseOptions[];
73
+ params?: ParseOptions | false | ParseOptions[];
74
+ body?: ParseOptions | false | ParseOptions[];
75
+ };
76
+ response?: true | ParseOptions | ParseOptions[];
28
77
  }
29
78
 
30
79
  export interface RouteJSONDoc extends RouteOptions {
31
- identifier: string;
80
+ identifier: string;
32
81
  }
33
82
 
34
83
  export interface RouterJSONDoc {
35
- [path: string]: {
36
- [method: string]: RouteJSONDoc
37
- }
84
+ [path: string]: {
85
+ [method: string]: RouteJSONDoc
86
+ }
38
87
  }
39
88
 
40
89
  export interface RouterHandlerOptions extends RouteOptions {
41
- parser?: Parser;
42
- middleware?: Handler | Handler[];
43
- session?: SessionHandlerOptions | Handler;
90
+ parser?: Parser;
91
+ middleware?: Handler | Handler[];
92
+ session?: SessionHandlerOptions | Handler;
44
93
  }
45
94
 
46
95
  export class RouterHandler {
47
96
 
48
- private readonly tokens: PathPartToken[];
49
- private readonly handler: Array<Handler | Handler | Router>;
50
- private readonly isRouter: boolean;
51
- private readonly options?: RouterHandlerOptions;
52
-
53
- public constructor(handler: Array<Handler> | HandlerWithOptions | Handler | Router, private readonly path: string | undefined, private readonly method: Method | undefined, options?: RouterHandlerOptions) {
54
- this.tokens = tokenizePath(path);
55
-
56
- let handlers: Array<Handler | Router> = []
57
- this.isRouter = handler instanceof Router;
58
-
59
- if (!this.isRouter && !(handler instanceof Array) && typeof handler === "object") {
60
- // HandlerWithOptions
61
- if (options) {
62
- throw new Error("bad arguments. cannot send options with HandlerWithOptions");
63
- }
64
- const realHandler = (handler as HandlerWithOptions).handler;
65
- const newOptions = {
66
- ...(handler as HandlerWithOptions)
67
- };
68
- delete (newOptions as any).handler;
69
- handler = realHandler;
70
- this.options = newOptions;
71
- } else {
72
- this.options = options;
73
- }
74
- const routeHandlers = handler instanceof Array ? handler : [handler] as Array<Handler | Router>;
75
-
76
- if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && this.options)) {
77
- throw new Error("bad arguments");
78
- }
79
-
80
-
81
- if (this.options && this.options.middleware) {
82
- handlers = handlers.concat(this.options.middleware);
83
- }
84
- if (this.options && this.options.session) {
85
- handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
86
- }
87
- if (this.options && this.options.policy) {
88
- handlers.push(GroupPolicyHandler(this.options.policy));
89
- }
90
- if (this.options && this.options.request) {
91
- handlers.push(ParseRequest(this.options.request));
92
- }
97
+ private readonly tokens: PathPartToken[];
98
+ private readonly handler: Array<Handler | Handler | Router>;
99
+ private readonly isRouter: boolean;
100
+ private readonly options?: RouterHandlerOptions;
101
+
102
+ public constructor(handler: Array<Handler> | HandlerWithOptions | Handler | Router, private readonly path: string | undefined, private readonly method: Method | undefined, options?: RouterHandlerOptions) {
103
+ this.tokens = tokenizePath(path);
104
+
105
+ let handlers: Array<Handler | Router> = []
106
+ this.isRouter = handler instanceof Router;
107
+
108
+ if (!this.isRouter && !(handler instanceof Array) && typeof handler === "object") {
109
+ // HandlerWithOptions
110
+ if (options) {
111
+ throw new Error("bad arguments. cannot send options with HandlerWithOptions");
112
+ }
113
+ const realHandler = (handler as HandlerWithOptions).handler;
114
+ const newOptions = {
115
+ ...(handler as HandlerWithOptions)
116
+ };
117
+ delete (newOptions as any).handler;
118
+ handler = realHandler;
119
+ this.options = newOptions;
120
+ } else {
121
+ this.options = options;
122
+ }
123
+ const routeHandlers = handler instanceof Array ? handler : [handler] as Array<Handler | Router>;
93
124
 
94
- handlers = handlers.concat(routeHandlers);
125
+ if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && this.options)) {
126
+ throw new Error("bad arguments");
127
+ }
95
128
 
96
- if (this.options && this.options.response) {
97
- if (typeof this.options.response === "boolean") {
98
- (handlers as Handler[]).push(ResponseHandler());
99
- } else {
100
- (handlers as Handler[]).push(ResultParser(this.options.response, this.options.parser));
101
- (handlers as Handler[]).push(ResponseHandler());
102
- }
103
- }
104
- this.handler = handlers;
129
+ if (this.options && this.options.middleware) {
130
+ handlers = handlers.concat(this.options.middleware);
131
+ }
132
+ if (this.options && this.options.session) {
133
+ handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
134
+ }
135
+ if (this.options && this.options.policy) {
136
+ handlers.push(GroupPolicyHandler(this.options.policy));
137
+ }
138
+ if (this.options && this.options.request) {
139
+ handlers.push(ParseRequest(this.options.request));
105
140
  }
106
141
 
107
- public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
108
- const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
109
- const nMethod = this.method ? this.method : "";
142
+ handlers = handlers.concat(routeHandlers);
110
143
 
111
- if (this.isRouter) {
112
- const router: Router = this.handler[0] as Router;
113
- router.getJSONDoc(doc, `${prePath}${nPath}`);
114
- } else if (this.options) {
115
- if (!doc[`${prePath}${nPath}`]) {
116
- doc[`${prePath}${nPath}`] = {};
117
- }
118
- if (doc[`${prePath}${nPath}`][nMethod]) {
119
- throw new Error("cannot create doc routes override each other");
120
- }
121
- doc[`${prePath}${nPath}`][nMethod] = {
122
- description: this.options.description,
123
- name: this.options.name,
124
- 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(),
125
- policy: this.options.policy,
126
- request: this.options.request ? {
127
- body: this.options.request.body,
128
- headers: this.options.request.headers,
129
- params: this.options.request.params,
130
- query: this.options.request.query,
131
- } : undefined,
132
- response: this.options.response
133
- };
134
- }
135
- return doc;
144
+ if (this.options && this.options.response) {
145
+ if (typeof this.options.response === "boolean") {
146
+ (handlers as Handler[]).push(ResponseHandler());
147
+ } else {
148
+ (handlers as Handler[]).push(ResultParser(this.options.response, this.options.parser));
149
+ (handlers as Handler[]).push(ResponseHandler());
150
+ }
136
151
  }
137
-
138
- public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
139
- for (let i = 0; i < this.handler.length; i++) {
140
- const h = this.handler[i];
141
- if (h instanceof Router) {
142
- if (!this.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
143
- return false;
144
- }
145
- } else {
146
- if (!this.pushResults(await h(ctx), ctx)) {
147
- return false;
148
- }
149
- }
150
- }
151
- return true;
152
+ this.handler = handlers;
153
+ }
154
+
155
+ public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
156
+ const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
157
+ const nMethod = this.method ? this.method : "";
158
+
159
+ if (this.isRouter) {
160
+ const router: Router = this.handler[0] as Router;
161
+ router.getJSONDoc(doc, `${prePath}${nPath}`);
162
+ } else if (this.options) {
163
+ if (!doc[`${prePath}${nPath}`]) {
164
+ doc[`${prePath}${nPath}`] = {};
165
+ }
166
+ if (doc[`${prePath}${nPath}`][nMethod]) {
167
+ throw new Error("cannot create doc routes override each other");
168
+ }
169
+ doc[`${prePath}${nPath}`][nMethod] = {
170
+ description: this.options.description,
171
+ name: this.options.name,
172
+ 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(),
173
+ policy: this.options.policy,
174
+ request: this.options.request ? {
175
+ body: this.options.request.body,
176
+ headers: this.options.request.headers,
177
+ params: this.options.request.params,
178
+ query: this.options.request.query,
179
+ } : undefined,
180
+ response: this.options.response
181
+ };
152
182
  }
153
-
154
- public isMatch(
155
- method: string,
156
- pathTokens: { value: string; lower: string; }[],
157
- prePathTokens: PathPartToken[]): {
158
- match: boolean;
159
- params?: { [name: string]: string | undefined }
160
- } {
161
- if ((this.method === undefined || this.method === method)) {
162
- if (this.path === undefined) {
163
- return {
164
- match: true
165
- };
166
- }
167
- return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
183
+ return doc;
184
+ }
185
+
186
+ public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
187
+ for (let i = 0; i < this.handler.length; i++) {
188
+ const h = this.handler[i];
189
+ if (h instanceof Router) {
190
+ if (!this.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
191
+ return false;
192
+ }
193
+ } else {
194
+ if (!this.pushResults(await h(ctx), ctx)) {
195
+ return false;
168
196
  }
197
+ }
198
+ }
199
+ return true;
200
+ }
201
+
202
+ public isMatch(
203
+ method: string,
204
+ pathTokens: { value: string; lower: string; }[],
205
+ prePathTokens: PathPartToken[]): {
206
+ match: boolean;
207
+ params?: { [name: string]: string | undefined }
208
+ } {
209
+ if ((this.method === undefined || this.method === method)) {
210
+ if (this.path === undefined) {
169
211
  return {
170
- match: false
212
+ match: true
171
213
  };
214
+ }
215
+ return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
172
216
  }
173
-
174
- private pushResults(result: boolean, ctx: Context): boolean {
175
- if (result === false) {
176
- // ctx.logger.debug(`avoiding next handlers because handler returned false.`);
177
- return false;
178
- } else if (result !== true && result !== undefined) {
179
- ctx.logger.trace("pushing to results [%o]", result);
180
- ctx.results.push(result);
181
- }
182
- return true;
217
+ return {
218
+ match: false
219
+ };
220
+ }
221
+
222
+ private pushResults(result: boolean, ctx: Context): boolean {
223
+ if (result === false) {
224
+ // ctx.logger.debug(`avoiding next handlers because handler returned false.`);
225
+ return false;
226
+ } else if (result !== true && result !== undefined) {
227
+ ctx.logger.trace("pushing to results [%o]", result);
228
+ ctx.results.push(result);
183
229
  }
184
- }
230
+ return true;
231
+ }
232
+ }
@@ -1,8 +1,5 @@
1
1
  export * from "./app";
2
- export * from "./api-handler";
3
2
  export * from "./api-router";
4
- export * from "./response";
5
3
  export * from "./common";
6
- export * from "./feature-router";
7
4
  export * from "./proxy";
8
5
  export * from "./middleware";
@@ -1,19 +1,19 @@
1
1
  import { Handler, Context } from "../common";
2
2
 
3
- import { COOKIE } from "../../util/cookie";
3
+ import { parse } from "cookie";
4
4
 
5
5
  export const CookieParser = (options?: {
6
- decode?(value: string): string;
6
+ decode?(value: string): string;
7
7
  }): Handler<void> => {
8
- return async (ctx: Context): Promise<void> => {
9
- const cookies = COOKIE.parse(ctx.headers.cookie || '', options);
10
- const cookieList = Object.keys(cookies);
11
- for (const name of cookieList) {
12
- const value = cookies[name];
13
- if (value) {
14
- ctx.cookies[name] = value;
15
- }
16
- }
17
- };
8
+ return async (ctx: Context): Promise<void> => {
9
+ const cookies = parse(ctx.headers.cookie || '', options);
10
+ const cookieList = Object.keys(cookies);
11
+ for (const name of cookieList) {
12
+ const value = cookies[name];
13
+ if (value) {
14
+ ctx.cookies[name] = value;
15
+ }
16
+ }
17
+ };
18
18
  }
19
19
 
@@ -2,7 +2,7 @@ import { parse as queryParse } from "querystring";
2
2
  import { Context, Handler } from "../common";
3
3
  import { BadRequestError } from "../../util/error";
4
4
  import { checkEnvVariables } from "../../util/config";
5
- import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
5
+ import { ReadBuffer, DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
6
6
 
7
7
  const DEFAULT_FORM_MAX_KEYS = undefined;
8
8
 
@@ -25,9 +25,15 @@ export const URLEncodedParser = (options?: {
25
25
  type = typeS;
26
26
  maxKeys = maxKeysS !== "undefined" ? parseInt(maxKeysS, 10) : DEFAULT_FORM_MAX_KEYS;
27
27
  }
28
+ const readBuffer = ReadBuffer({
29
+ limit
30
+ });
28
31
  return async (ctx: Context): Promise<void> => {
29
32
  try {
30
33
  const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
34
+ if (isType && !ctx.buffer) {
35
+ await readBuffer(ctx);
36
+ }
31
37
  if (isType && ctx.buffer && ctx.buffer.length <= limit) {
32
38
  const string = ctx.buffer.toString();
33
39
  if (string) {
@@ -42,7 +48,7 @@ export const URLEncodedParser = (options?: {
42
48
  throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
43
49
  }
44
50
  } catch (e: any) {
45
- if (e && e.name === "ParseOptionsError") {
51
+ if (e && e.name === "BadRequestError") {
46
52
  throw e;
47
53
  } else {
48
54
  ctx.logger.error(e);
@@ -1,7 +1,49 @@
1
- import { GroupPolicy, policyCheck } from "../../util/session";
2
- import { ForbiddenError, UnAuthorizedError } from "../../util/error";
1
+ import { GroupPolicy, Session } from "../../util/session";
2
+ import { ForbiddenError, UnAuthorizedError, ParseOptionsError } from "../../util/error";
3
3
  import { Context, Handler } from "../common";
4
4
 
5
+ const policyCheck = (session: Session, options: GroupPolicy): boolean => {
6
+ switch (options.groupPolicy) {
7
+ case "at_least_one":
8
+ for (const group of options.groups) {
9
+ if (group instanceof Array) {
10
+ let ret = true;
11
+ for (const g of group) {
12
+ if (session.groups.indexOf(g) === -1) {
13
+ ret = false;
14
+ break;
15
+ }
16
+ }
17
+ if (ret) {
18
+ return true;
19
+ }
20
+ } else {
21
+ if (session.groups.indexOf(group) !== -1) {
22
+ return true;
23
+ }
24
+ }
25
+ }
26
+ return false;
27
+ case "all":
28
+ for (const group of options.groups) {
29
+ if (group instanceof Array) {
30
+ for (const g of group) {
31
+ if (session.groups.indexOf(g) === -1) {
32
+ return false;
33
+ }
34
+ }
35
+ } else {
36
+ if (session.groups.indexOf(group) === -1) {
37
+ return false;
38
+ }
39
+ }
40
+ }
41
+ return true;
42
+ default:
43
+ throw new ParseOptionsError(`policy [${options.groupPolicy}] not implemented!!`);
44
+ }
45
+ };
46
+
5
47
  export const GroupPolicyHandler = (options: GroupPolicy): Handler<void> => {
6
48
  return async (ctx: Context): Promise<void> => {
7
49
  try {
@@ -5,7 +5,6 @@ import { LoggerHandler } from "./logger";
5
5
  import { TagResponse } from "./tag";
6
6
  import { CORS } from "./cors";
7
7
  import { CookieParser } from "./cookie";
8
- import { ReadBuffer } from "./buffer";
9
8
  import { JSONParser } from "./json";
10
9
  import { TextParser } from "./text";
11
10
  import { URLEncodedParser } from "./form";
@@ -23,30 +22,27 @@ export * from "./cookie";
23
22
  export { ReadBuffer } from "./buffer";
24
23
 
25
24
  export const middleware = (): Handler[] => {
26
- const ret: Handler[] = [];
27
- if (isFeatureEnabled("REQUEST_LOGGER", true)) {
28
- ret.push(LoggerHandler());
29
- }
30
- if (isFeatureEnabled("TAG_RESPONSE", false)) {
31
- ret.push(TagResponse());
32
- }
33
- if (isFeatureEnabled("CORS", false)) {
34
- ret.push(CORS());
35
- }
36
- if (isFeatureEnabled("READ_BUFFER", true)) {
37
- ret.push(ReadBuffer());
38
- }
39
- if (isFeatureEnabled("COOKIE_PARSER", true)) {
40
- ret.push(CookieParser());
41
- }
42
- if (isFeatureEnabled("JSON_PARSER", true)) {
43
- ret.push(JSONParser());
44
- }
45
- if (isFeatureEnabled("URL_ENCODED_PARSER", true)) {
46
- ret.push(URLEncodedParser());
47
- }
48
- if (isFeatureEnabled("TEXT_PARSER", true)) {
49
- ret.push(TextParser());
50
- }
51
- return ret;
52
- };
25
+ const ret: Handler[] = [];
26
+ if (isFeatureEnabled("REQUEST_LOGGER", true)) {
27
+ ret.push(LoggerHandler());
28
+ }
29
+ if (isFeatureEnabled("TAG_RESPONSE", false)) {
30
+ ret.push(TagResponse());
31
+ }
32
+ if (isFeatureEnabled("CORS", false)) {
33
+ ret.push(CORS());
34
+ }
35
+ if (isFeatureEnabled("COOKIE_PARSER", true)) {
36
+ ret.push(CookieParser());
37
+ }
38
+ if (isFeatureEnabled("JSON_PARSER", true)) {
39
+ ret.push(JSONParser());
40
+ }
41
+ if (isFeatureEnabled("URL_ENCODED_PARSER", true)) {
42
+ ret.push(URLEncodedParser());
43
+ }
44
+ if (isFeatureEnabled("TEXT_PARSER", true)) {
45
+ ret.push(TextParser());
46
+ }
47
+ return ret;
48
+ };
@@ -1,7 +1,7 @@
1
1
  import { Context, Handler } from "../common";
2
2
  import { BadRequestError } from "../../util/error";
3
3
  import { checkEnvVariables } from "../../util/config";
4
- import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
4
+ import { DEFAULT_READ_BUFFER_LIMIT, ReadBuffer } from "./buffer";
5
5
 
6
6
  export const JSONParser = (options?: {
7
7
  limit?: number;
@@ -22,15 +22,21 @@ export const JSONParser = (options?: {
22
22
  limit = parseInt(limitS, 10);
23
23
  type = typeS;
24
24
  }
25
+ const readBuffer = ReadBuffer({
26
+ limit
27
+ });
25
28
  return async (ctx: Context): Promise<void> => {
26
29
  try {
27
30
  const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
31
+ if (isType && !ctx.buffer) {
32
+ await readBuffer(ctx);
33
+ }
28
34
  if (isType && ctx.buffer && ctx.buffer.length <= limit) {
29
35
  const string = ctx.buffer.toString();
30
36
  if (string) {
31
37
  const parsed = JSON.parse(string);
32
38
  if (parsed instanceof Array && strict) {
33
- throw new BadRequestError(`body cannot be an array`, 'body');
39
+ throw new BadRequestError(`body cannot be an array`);
34
40
  }
35
41
  ctx.body = parsed;
36
42
  }
@@ -39,7 +45,7 @@ export const JSONParser = (options?: {
39
45
  throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
40
46
  }
41
47
  } catch (e: any) {
42
- if (e && e.name === "ParseOptionsError") {
48
+ if (e && e.name === "BadRequestError") {
43
49
  throw e;
44
50
  } else {
45
51
  ctx.logger.error(e);