@miqro/core 1.3.4 → 1.3.9

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 (135) hide show
  1. package/README.md +81 -253
  2. package/dist/handler/api-router-utils.d.ts +11 -7
  3. package/dist/handler/api-router-utils.js +102 -15
  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.d.ts +4 -9
  9. package/dist/handler/app.js +10 -9
  10. package/dist/handler/app.js.map +1 -1
  11. package/dist/handler/common/context.d.ts +1 -1
  12. package/dist/handler/common/context.js +14 -9
  13. package/dist/handler/common/context.js.map +1 -1
  14. package/dist/handler/common/router-utils.d.ts +34 -1
  15. package/dist/handler/common/router-utils.js +139 -9
  16. package/dist/handler/common/router-utils.js.map +1 -1
  17. package/dist/handler/common/router.d.ts +19 -8
  18. package/dist/handler/common/router.js +32 -15
  19. package/dist/handler/common/router.js.map +1 -1
  20. package/dist/handler/index.d.ts +0 -3
  21. package/dist/handler/index.js +0 -3
  22. package/dist/handler/index.js.map +1 -1
  23. package/dist/handler/middleware/form.js +7 -1
  24. package/dist/handler/middleware/form.js.map +1 -1
  25. package/dist/handler/middleware/group.js +44 -2
  26. package/dist/handler/middleware/group.js.map +1 -1
  27. package/dist/handler/middleware/index.js +2 -6
  28. package/dist/handler/middleware/index.js.map +1 -1
  29. package/dist/handler/middleware/json.js +8 -2
  30. package/dist/handler/middleware/json.js.map +1 -1
  31. package/dist/handler/middleware/text.js +8 -1
  32. package/dist/handler/middleware/text.js.map +1 -1
  33. package/dist/handler/proxy.d.ts +2 -5
  34. package/dist/handler/proxy.js +2 -3
  35. package/dist/handler/proxy.js.map +1 -1
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.js +1 -0
  38. package/dist/index.js.map +1 -1
  39. package/dist/{util/test → test/common}/app.d.ts +2 -2
  40. package/dist/{util/test → test/common}/app.js +3 -2
  41. package/dist/test/common/app.js.map +1 -0
  42. package/dist/{util/test → test/common}/common.d.ts +0 -0
  43. package/dist/{util/test → test/common}/common.js +0 -0
  44. package/dist/test/common/common.js.map +1 -0
  45. package/dist/{util/test → test/common}/index.d.ts +1 -0
  46. package/dist/{util/test → test/common}/index.js +1 -0
  47. package/dist/test/common/index.js.map +1 -0
  48. package/dist/test/common/runner.d.ts +28 -0
  49. package/dist/test/common/runner.js +88 -0
  50. package/dist/test/common/runner.js.map +1 -0
  51. package/dist/test/index.d.ts +1 -0
  52. package/dist/{handler/response → test}/index.js +1 -3
  53. package/dist/test/index.js.map +1 -0
  54. package/dist/test/main.d.ts +1 -0
  55. package/dist/test/main.js +31 -0
  56. package/dist/test/main.js.map +1 -0
  57. package/dist/util/cli/index.d.ts +5 -1
  58. package/dist/util/cli/index.js +26 -0
  59. package/dist/util/cli/index.js.map +1 -1
  60. package/dist/util/error/parsererror.d.ts +2 -1
  61. package/dist/util/error/parsererror.js +5 -1
  62. package/dist/util/error/parsererror.js.map +1 -1
  63. package/dist/util/index.d.ts +0 -1
  64. package/dist/util/index.js +0 -1
  65. package/dist/util/index.js.map +1 -1
  66. package/dist/util/loader/index.d.ts +0 -3
  67. package/dist/util/loader/index.js +2 -9
  68. package/dist/util/loader/index.js.map +1 -1
  69. package/dist/util/logger/formatter.js +1 -1
  70. package/dist/util/logger/formatter.js.map +1 -1
  71. package/dist/util/parser/get.js +3 -6
  72. package/dist/util/parser/get.js.map +1 -1
  73. package/dist/util/request/index.d.ts +1 -1
  74. package/dist/util/request/index.js +1 -3
  75. package/dist/util/request/index.js.map +1 -1
  76. package/dist/util/session/common.d.ts +0 -1
  77. package/dist/util/session/common.js +0 -46
  78. package/dist/util/session/common.js.map +1 -1
  79. package/package.json +7 -11
  80. package/src/handler/api-router-utils.ts +108 -22
  81. package/src/handler/api-router.ts +30 -4
  82. package/src/handler/app.ts +10 -15
  83. package/src/handler/common/context.ts +14 -10
  84. package/src/handler/common/router-utils.ts +221 -49
  85. package/src/handler/common/router.ts +43 -15
  86. package/src/handler/index.ts +0 -3
  87. package/src/handler/middleware/form.ts +8 -2
  88. package/src/handler/middleware/group.ts +44 -2
  89. package/src/handler/middleware/index.ts +0 -4
  90. package/src/handler/middleware/json.ts +9 -3
  91. package/src/handler/middleware/text.ts +8 -1
  92. package/src/handler/proxy.ts +3 -8
  93. package/src/index.ts +1 -0
  94. package/src/{util/test → test/common}/app.ts +6 -5
  95. package/src/{util/test → test/common}/common.ts +0 -0
  96. package/src/{util/test → test/common}/index.ts +1 -0
  97. package/src/test/common/runner.ts +116 -0
  98. package/src/test/index.ts +1 -0
  99. package/src/test/main.ts +32 -0
  100. package/src/util/cli/index.ts +24 -1
  101. package/src/util/error/parsererror.ts +6 -1
  102. package/src/util/index.ts +0 -1
  103. package/src/util/loader/index.ts +1 -7
  104. package/src/util/logger/formatter.ts +1 -1
  105. package/src/util/parser/get.ts +3 -5
  106. package/src/util/request/index.ts +1 -1
  107. package/src/util/session/common.ts +0 -43
  108. package/test.md +0 -0
  109. package/tsconfig-test.json +13 -0
  110. package/dist/handler/api-handler.d.ts +0 -30
  111. package/dist/handler/api-handler.js +0 -42
  112. package/dist/handler/api-handler.js.map +0 -1
  113. package/dist/handler/feature-router.d.ts +0 -10
  114. package/dist/handler/feature-router.js +0 -90
  115. package/dist/handler/feature-router.js.map +0 -1
  116. package/dist/handler/response/html.d.ts +0 -10
  117. package/dist/handler/response/html.js +0 -34
  118. package/dist/handler/response/html.js.map +0 -1
  119. package/dist/handler/response/index.d.ts +0 -3
  120. package/dist/handler/response/index.js.map +0 -1
  121. package/dist/handler/response/json.d.ts +0 -2
  122. package/dist/handler/response/json.js +0 -21
  123. package/dist/handler/response/json.js.map +0 -1
  124. package/dist/handler/response/result.d.ts +0 -4
  125. package/dist/handler/response/result.js +0 -46
  126. package/dist/handler/response/result.js.map +0 -1
  127. package/dist/util/test/app.js.map +0 -1
  128. package/dist/util/test/common.js.map +0 -1
  129. package/dist/util/test/index.js.map +0 -1
  130. package/src/handler/api-handler.ts +0 -56
  131. package/src/handler/feature-router.ts +0 -90
  132. package/src/handler/response/html.ts +0 -36
  133. package/src/handler/response/index.ts +0 -3
  134. package/src/handler/response/json.ts +0 -19
  135. package/src/handler/response/result.ts +0 -40
@@ -0,0 +1,116 @@
1
+ import { Console, count } from "console";
2
+ import { format } from "util";
3
+ import { Logger } from "../../util";
4
+
5
+ export type TestFunction = () => void | Promise<void>;
6
+ const DEFAULT_TIMEOUT = 2000;
7
+
8
+ interface Test { run: TestFunction; title: string; category?: string; fullName: string; }
9
+
10
+ const tests: Test[] = [];
11
+
12
+ export const getTestCount = () => tests.length;
13
+
14
+ export const it = (title: string, impl: TestFunction, options?: {
15
+ category?: string;
16
+ timeout?: number;
17
+ before?: TestFunction;
18
+ after?: TestFunction;
19
+ }, logger: Logger | Console = new Console(process.stdout)): void => {
20
+ const category = options && options.category ? options.category : undefined;
21
+ const fullName = `${category ? `${category} [` : ""}${title}${category ? "]" : ""}`;
22
+ tests.push({
23
+ run: () => new Promise((resolve, reject) => {
24
+ const timeoutMS = options && options.timeout ? options.timeout : DEFAULT_TIMEOUT;
25
+ const timeout = setTimeout(() => {
26
+ reject(new Error(format("%s failed\x1b[31m\n%s timeout %o\x1b", fullName, fullName, timeoutMS)));
27
+ }, timeoutMS);
28
+ try {
29
+ (async () => {
30
+ if (options && options.before) {
31
+ await options.before();
32
+ }
33
+ const startMS = Date.now();
34
+ await impl();
35
+ const took = Date.now() - startMS;
36
+ if (options && options.after) {
37
+ await options.after();
38
+ }
39
+ return took;
40
+ })().then((took) => {
41
+ clearTimeout(timeout);
42
+ logger.log("\x1b[32mpassed %s (took %sms)\x1b[0m", fullName, took);
43
+ resolve();
44
+ }).catch(e => {
45
+ clearTimeout(timeout);
46
+ reject(new Error(format("%s failed\n%s finished with errors %o", fullName, fullName, e)));
47
+ });
48
+ } catch (e) {
49
+ clearTimeout(timeout);
50
+ reject(new Error(format("%s failed\n%s finished with errors %o", fullName, fullName, e)));
51
+ }
52
+ }), title,
53
+ category,
54
+ fullName
55
+ });
56
+ };
57
+
58
+ export const runTests = async (title?: string | string[], logger: Logger | Console = new Console(process.stdout)): Promise<{
59
+ passed: number;
60
+ total: number;
61
+ ignored: number;
62
+ failed: {
63
+ error: any;
64
+ fullName: string;
65
+ }[];
66
+ }> => {
67
+ const titles = title ? title instanceof Array ? title : [title] : [undefined];
68
+ const ret: {
69
+ passed: number;
70
+ total: number;
71
+ ignored: number;
72
+ failed: {
73
+ error: any;
74
+ fullName: string;
75
+ }[];
76
+ } = {
77
+ total: tests.length,
78
+ ignored: 0,
79
+ passed: 0,
80
+ failed: []
81
+ };
82
+ for (const test of tests) {
83
+ for (const title of titles) {
84
+ if (title && test.fullName.indexOf(title) !== -1 || !title) {
85
+ try {
86
+ await test.run();
87
+ ret.passed++;
88
+ } catch (e) {
89
+ logger.error("\x1b[31m%s\x1b[0m", e);
90
+ ret.failed.push({
91
+ error: e,
92
+ fullName: test.fullName
93
+ })
94
+ }
95
+ } else {
96
+ ret.ignored++;
97
+ }
98
+ }
99
+ }
100
+ return ret;
101
+ };
102
+
103
+ export const runTestModules = async (modules: string[], title?: string | string[], logger: Logger | Console = new Console(process.stdout)): Promise<{
104
+ passed: number;
105
+ total: number;
106
+ ignored: number;
107
+ failed: {
108
+ error: any;
109
+ fullName: string;
110
+ }[];
111
+ }> => {
112
+ for (const path of modules) {
113
+ require(path);
114
+ }
115
+ return await runTests(title, logger);
116
+ }
@@ -0,0 +1 @@
1
+ export * from "./common";
@@ -0,0 +1,32 @@
1
+ import { resolve } from "path";
2
+ import { CLIUtil, getLogger } from "../util";
3
+ import { runTestModules } from "./common";
4
+
5
+ const startMS = Date.now();
6
+
7
+ const args = CLIUtil.extractFlags(process.argv.slice(2));
8
+ const name = args.flags.n ? args.flags.n : "all";
9
+
10
+ const logger = console;
11
+
12
+ const modules = args.cmds;
13
+ runTestModules(modules.map(m => resolve(process.cwd(), m)), typeof name === "string" && name.toLowerCase() === "all" ? undefined : name, console).then((ret) => {
14
+ const took = Date.now() - startMS;
15
+ logger.log("");
16
+ logger.log("");
17
+ logger.log(ret.passed + " tests pased");
18
+ logger.log(ret.failed.length + " failed");
19
+ logger.log("took " + took + "ms");
20
+ logger.log("");
21
+ logger.log("");
22
+ if (ret.failed.length > 0) {
23
+ ret.failed.forEach(e => {
24
+ logger.error("\x1b[31m%s\x1b[0m", e.fullName);
25
+ logger.error("\x1b[31m%s\x1b[0m", e.error);
26
+ });
27
+ process.exit(1);
28
+ }
29
+ }).catch(e => {
30
+ logger.error(e);
31
+ process.exit(1);
32
+ });
@@ -1,6 +1,6 @@
1
1
  import { SimpleMap } from "../parser/common";
2
2
  import { Logger } from "../logger";
3
- import { Callback } from "../test";
3
+ import { Callback } from "../../test/common";
4
4
 
5
5
  // noinspection SpellCheckingInspection
6
6
  const routeCMDModule = async (cmdArg: string | undefined, cmds: CMDMapType, logger: Logger | Console, exit = true): Promise<void> => {
@@ -28,6 +28,29 @@ const routeCMDModule = async (cmdArg: string | undefined, cmds: CMDMapType, logg
28
28
  export type CMDMapType = SimpleMap<{ cb: Callback<void> | Callback<Promise<void>>; description: string; section?: string; }>
29
29
 
30
30
  export abstract class CLIUtil {
31
+ public static extractFlags(args: string[]): { flags: SimpleMap<string | string[]>; cmds: string[]; } {
32
+ const flags: SimpleMap<string | string[]> = {};
33
+ const cmds: string[] = [];
34
+ for (let i = 0; i < args.length; i++) {
35
+ const arg = args[i];
36
+ if (arg.indexOf("-") === 0) {
37
+ const argName = arg.substring(arg.indexOf("--") === 0 ? 2 : 1);
38
+ const argValue = args.length > i + 1 && args[i + 1] && args[i + 1].indexOf("-") != 0 ? args[i + 1] : "";
39
+ const flag = flags[argName];
40
+ if (flag instanceof Array) {
41
+ flag.push(argValue);
42
+ } else if (flag) {
43
+ flags[argName] = [flag, argValue];
44
+ } else {
45
+ flags[argName] = argValue;
46
+ }
47
+ i++;
48
+ } else {
49
+ cmds.push(arg);
50
+ }
51
+ }
52
+ return { flags, cmds };
53
+ }
31
54
  // noinspection SpellCheckingInspection
32
55
  public static cliFlow(cmds: CMDMapType, usage: string, logger: Logger | Console, cmdArg = process.argv[2], exit = true): void {
33
56
  const flow = async () => {
@@ -7,4 +7,9 @@ export class ParseOptionsError extends NamedError {
7
7
  }
8
8
  }
9
9
 
10
- export class BadRequestError extends ParseOptionsError { }
10
+ export class BadRequestError extends NamedError {
11
+ constructor(message = "BAD REQUEST") {
12
+ super(message);
13
+ this.name = "BadRequestError";
14
+ }
15
+ }
package/src/util/index.ts CHANGED
@@ -6,6 +6,5 @@ export * from "./config";
6
6
  export * from "./logger";
7
7
  export * from "./session";
8
8
  export * from "./loader";
9
- export * from "./test";
10
9
  //export * from "./uuid";
11
10
  //export * from "./cookie";
@@ -3,9 +3,8 @@ import { Logger } from "../logger";
3
3
  import { existsSync, readdirSync, readFileSync } from "fs";
4
4
  import { ConfigOutput, ConfigPathResolver, ConfigStore, LoadConfigOut } from "../config";
5
5
  import { ConfigFileNotFoundError } from "../error";
6
- import { RequestOptions, request } from "../request";
7
6
 
8
- export const loadConfigString = (envFileContent: string, combined?: ConfigOutput): ConfigOutput => {
7
+ const loadConfigString = (envFileContent: string, combined?: ConfigOutput): ConfigOutput => {
9
8
  const ret: ConfigOutput = {};
10
9
  envFileContent.split("\n")
11
10
  .filter(value => value && value.length > 0 && value.substr(0, 1) !== "#")
@@ -26,11 +25,6 @@ export const loadConfigString = (envFileContent: string, combined?: ConfigOutput
26
25
  return ret;
27
26
  }
28
27
 
29
- export const loadRemoteConfigFile = async (options: RequestOptions, logger?: Logger): Promise<ConfigOutput> => {
30
- const { data } = await request(options, logger);
31
- return loadConfigString(data);
32
- }
33
-
34
28
  export const loadConfigFile = (envFilePath: string, combined?: ConfigOutput, logger?: Logger): ConfigOutput => {
35
29
  if (!existsSync(envFilePath)) {
36
30
  throw new ConfigFileNotFoundError(`config file [${envFilePath}] doesnt exists!`);
@@ -4,6 +4,6 @@ export type LoggerFormatter = (args: { identifier: string, level: LogLevel, mess
4
4
 
5
5
  export const defaultLoggerFormatter: LoggerFormatter =
6
6
  ({ identifier, level, message }) => `${new Date().toISOString()} ${process.pid} ` +
7
- `[${identifier}] ` +
7
+ `${identifier ? `[${identifier}] ` : ""}` +
8
8
  `${level !== "info" ? (level === "error" || level === "warn" ? `[${level.toUpperCase()}] ` : `[${level}] `) : ""}` +
9
9
  `${message}`;
@@ -3,14 +3,12 @@ import { ParseOptionsError } from "../error";
3
3
  import { BasicParseOption, ParseValueArgs } from "./common";
4
4
 
5
5
  /*
6
- usage const name = get(obj, "user.info.name", {type: "string"});
6
+ usage const name = get(obj, "user.info.name", defaultValue, {type: "string"}, parser);
7
7
  */
8
8
  /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
9
9
  export const get = (obj: any, attrPath: string, defaultValue?: any, option?: BasicParseOption, parser?: Parser): any | undefined => {
10
- if (typeof obj !== "object" && defaultValue === undefined) {
11
- throw new Error(`obj must be typeof object`);
12
- } else if (!obj && defaultValue !== undefined) {
13
- return defaultValue;
10
+ if (!obj || typeof obj !== "object") {
11
+ return defaultValue !== undefined ? defaultValue : undefined
14
12
  }
15
13
  if (typeof attrPath !== "string") {
16
14
  throw new Error(`attrPath must be typeof string`);
@@ -5,7 +5,7 @@ import { parseRedirectLocation, RequestOptions, RequestResponse, ResponseError,
5
5
  import { gunzipSync } from "zlib";
6
6
  import { isBrowser } from "../config/browser";
7
7
 
8
- export { RequestOptions, RequestResponse, ResponseError } from "./common";
8
+ export { RequestOptions, RequestResponse } from "./common";
9
9
 
10
10
  const DEFAULT_USER_AGENT = "curl/7.69.1";
11
11
  const CONTENT_TYPE_HEADER = "Content-Type";
@@ -1,4 +1,3 @@
1
- import { ParseOptionsError } from "../error";
2
1
  import { SimpleMap, SimpleTypes } from "../parser/common";
3
2
 
4
3
  export interface NoTokenSession extends SimpleMap<SimpleTypes> {
@@ -19,45 +18,3 @@ export interface GroupPolicy {
19
18
  groups: GroupPolicyGroups[];
20
19
  groupPolicy: GroupPolicyType;
21
20
  }
22
-
23
- export const policyCheck = (session: Session, options: GroupPolicy): boolean => {
24
- switch (options.groupPolicy) {
25
- case "at_least_one":
26
- for (const group of options.groups) {
27
- if (group instanceof Array) {
28
- let ret = true;
29
- for (const g of group) {
30
- if (session.groups.indexOf(g) === -1) {
31
- ret = false;
32
- break;
33
- }
34
- }
35
- if (ret) {
36
- return true;
37
- }
38
- } else {
39
- if (session.groups.indexOf(group) !== -1) {
40
- return true;
41
- }
42
- }
43
- }
44
- return false;
45
- case "all":
46
- for (const group of options.groups) {
47
- if (group instanceof Array) {
48
- for (const g of group) {
49
- if (session.groups.indexOf(g) === -1) {
50
- return false;
51
- }
52
- }
53
- } else {
54
- if (session.groups.indexOf(group) === -1) {
55
- return false;
56
- }
57
- }
58
- }
59
- return true;
60
- default:
61
- throw new ParseOptionsError(`policy [${options.groupPolicy}] not implemented!!`);
62
- }
63
- };
package/test.md ADDED
File without changes
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "./test-dist/",
5
+ },
6
+ "include": [
7
+ "src/**/*",
8
+ "test/**/*"
9
+ ],
10
+ "exclude": [
11
+ "node_modules/"
12
+ ]
13
+ }
@@ -1,30 +0,0 @@
1
- import { GroupPolicy } from "../util/session";
2
- import { SessionHandlerOptions } from "./middleware/session";
3
- import { Parser } from "../util/parser";
4
- import { ParseOptions } from "../util/parser/common";
5
- import { Handler } from "./common";
6
- export interface APIHandlerOptions {
7
- parser?: Parser;
8
- headers?: ParseOptions | ParseOptions[];
9
- query?: ParseOptions | false | ParseOptions[];
10
- params?: ParseOptions | false | ParseOptions[];
11
- body?: ParseOptions | false | ParseOptions[];
12
- result?: ParseOptions | ParseOptions[];
13
- handler: Array<Handler> | Handler;
14
- middleware?: Handler[];
15
- session?: SessionHandlerOptions | Handler;
16
- policy?: GroupPolicy;
17
- responseHandler?: Handler;
18
- }
19
- /**
20
- * APIHandler
21
- *
22
- * ```typescript
23
- *app.use(APIHandler({
24
- * query: { ... },
25
- * body: { ... },
26
- * result: { ... }
27
- *}));
28
- * ```
29
- */
30
- export declare const APIHandler: (options: APIHandlerOptions) => Array<Handler>;
@@ -1,42 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.APIHandler = void 0;
4
- const session_1 = require("./middleware/session");
5
- const group_1 = require("./middleware/group");
6
- const parse_1 = require("./middleware/parse");
7
- const json_1 = require("./response/json");
8
- const result_1 = require("./response/result");
9
- /**
10
- * APIHandler
11
- *
12
- * ```typescript
13
- *app.use(APIHandler({
14
- * query: { ... },
15
- * body: { ... },
16
- * result: { ... }
17
- *}));
18
- * ```
19
- */
20
- const APIHandler = (options) =>
21
- // setup options.middleware
22
- (options.middleware ? options.middleware : [])
23
- // setup session
24
- .concat(options.session ? typeof options.session === "function" ? [options.session] : [(0, session_1.SessionHandler)(options.session)] : [])
25
- // setup policy
26
- .concat(options.policy ? [(0, group_1.GroupPolicyHandler)(options.policy)] : [])
27
- // setup request parse
28
- .concat([(0, parse_1.ParseRequest)({
29
- headers: options.headers,
30
- query: options.query,
31
- params: options.params,
32
- body: options.body,
33
- parser: options.parser
34
- })])
35
- // setup options.handler
36
- .concat(options.handler instanceof Array ? options.handler : [options.handler])
37
- // setup response parse
38
- .concat(options.result ? (0, result_1.ResultParser)(options.result, options.parser) : [])
39
- // setup response handler
40
- .concat([options.responseHandler ? options.responseHandler : (0, json_1.ResponseHandler)()]);
41
- exports.APIHandler = APIHandler;
42
- //# sourceMappingURL=api-handler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"api-handler.js","sourceRoot":"","sources":["../../src/handler/api-handler.ts"],"names":[],"mappings":";;;AACA,kDAA6E;AAC7E,8CAAwD;AAIxD,8CAAkD;AAClD,0CAAkD;AAClD,8CAAiD;AAgBjD;;;;;;;;;;GAUG;AACI,MAAM,UAAU,GAAG,CAAC,O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C,IAAA,sBAAe,GAAE,CAAC,CAAC,CAAC;AApBxE,QAAA,UAAU,cAoB8D"}
@@ -1,10 +0,0 @@
1
- import { SimpleMap } from "../util/parser/common";
2
- import { Logger } from "../util/logger";
3
- import { Router, Handler, Method } from "./common";
4
- export interface FeatureRouterPathOptions {
5
- path: string | string[];
6
- method: Method | Method[];
7
- handler: Array<Handler> | Handler;
8
- }
9
- export declare type FeatureRouterOptions<T extends FeatureRouterPathOptions = FeatureRouterPathOptions> = SimpleMap<T>;
10
- export declare const FeatureRouter: (options: FeatureRouterOptions<FeatureRouterPathOptions>, logger?: Logger | undefined) => Router;
@@ -1,90 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FeatureRouter = void 0;
4
- const featuretoggle_1 = require("../util/config/featuretoggle");
5
- const tokenize_match_1 = require("./common/tokenize-match");
6
- const common_1 = require("./common");
7
- const FEATURE_ROUTER_METHODS = ["get", "post", "put", "delete", "patch", "options"];
8
- const FeatureRouter = (options, logger) => {
9
- const router = new common_1.Router();
10
- const toSetup = Object.keys(options);
11
- const enabled = [];
12
- const disabled = [];
13
- const enabledPaths = {};
14
- for (const featureName of toSetup) {
15
- const handlerOptions = options[featureName];
16
- if (!handlerOptions) {
17
- throw new Error(`no handler options for feature [${featureName}]`);
18
- }
19
- else {
20
- const { path, handler: implementation, method } = handlerOptions;
21
- if (!method) {
22
- throw new Error(`no methods for feature [${featureName}]`);
23
- }
24
- else if (!implementation) {
25
- throw new Error(`no implementation for feature [${featureName}]`);
26
- }
27
- else if (!path) {
28
- throw new Error(`no path for feature [${featureName}]`);
29
- }
30
- else {
31
- if (method instanceof Array) {
32
- for (const m of method) {
33
- if (FEATURE_ROUTER_METHODS.indexOf(m.toLowerCase()) === -1) {
34
- throw new Error(`feature [${featureName}] method [${m.toUpperCase()}] not defined! use only [${FEATURE_ROUTER_METHODS.join(",")}]`);
35
- }
36
- }
37
- }
38
- else if (FEATURE_ROUTER_METHODS.indexOf(method.toLowerCase()) === -1) {
39
- throw new Error(`feature [${featureName}] method [${method.toUpperCase()}] not defined! use only [${FEATURE_ROUTER_METHODS.join(",")}]`);
40
- }
41
- const methods = method instanceof Array ? method : [method];
42
- if ((0, featuretoggle_1.isFeatureEnabled)(featureName)) {
43
- if (logger) {
44
- logger.trace(`feature [${featureName}] enabled`);
45
- }
46
- enabled.push(featureName);
47
- const paths = path instanceof Array ? path : [path];
48
- for (const nnP of paths) {
49
- const p = (0, tokenize_match_1.normalizePath)(nnP);
50
- for (const m of methods) {
51
- if (logger) {
52
- logger.info("%s", featureName);
53
- logger.info("\t%s:%s", m.toUpperCase(), p);
54
- if (handlerOptions.___filePath) {
55
- logger.info("\t%s", handlerOptions.___filePath);
56
- }
57
- }
58
- if (enabledPaths[`${p}${m}`] !== undefined) {
59
- throw new Error(`${featureName} collides with feature ${enabledPaths[`${p}${m}`]} on path ${p} method ${m}`);
60
- }
61
- enabledPaths[`${p}${m}`] = featureName;
62
- router.use(implementation, p, m.toLocaleLowerCase());
63
- }
64
- }
65
- }
66
- else {
67
- if (logger) {
68
- logger.debug("feature [%s] disabled", featureName);
69
- }
70
- disabled.push(featureName);
71
- }
72
- }
73
- }
74
- }
75
- if (logger && enabled.length > 0) {
76
- logger.debug("enabled features [%s]", enabled.join(","));
77
- }
78
- if (logger) {
79
- if (disabled.length > 0) {
80
- logger.warn("disabled features [%s]", disabled.join(","));
81
- logger.warn(`to enable them just add the env var <feature>=true`);
82
- }
83
- else {
84
- logger.debug(`no features disabled`);
85
- }
86
- }
87
- return router;
88
- };
89
- exports.FeatureRouter = FeatureRouter;
90
- //# sourceMappingURL=feature-router.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"feature-router.js","sourceRoot":"","sources":["../../src/handler/feature-router.ts"],"names":[],"mappings":";;;AAEA,gEAAgE;AAChE,4DAAwD;AACxD,qCAAmD;AAUnD,MAAM,sBAAsB,GAAa,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,QA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AAI,KAAK,CAAC,GAAG,WAAW,0BAA0B,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,YAAY,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;6BAC7G;4BACD,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,CAAC;4BACvC,MAAM,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC,EAAE,CAAC,CAAC,iBAAiB,EAAY,CAAC,CAAC;yBAChE;qBACF;iBACF;qBAAM;oBACL,IAAI,MAAM,EAAE;wBACV,MAAM,CAAC,KAAK,CAAC,uBAAuB,EAAE,WAAW,CAAC,CAAC;qBACpD;oBACD,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;iBAC5B;aACF;SACF;KACF;IACD,IAAI,MAAM,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;QAChC,MAAM,CAAC,KAAK,CAAC,uBAAuB,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;KAC1D;IACD,IAAI,MAAM,EAAE;QACV,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YACvB,MAAM,CAAC,IAAI,CAAC,wBAAwB,EAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;YAC1D,MAAM,CAAC,IAAI,CAAC,oDAAoD,CAAC,CAAC;SACnE;aAAM;YACL,MAAM,CAAC,KAAK,CAAC,sBAAsB,CAAC,CAAC;SACtC;KACF;IACD,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAzEW,QAAA,aAAa,iBAyExB"}
@@ -1,10 +0,0 @@
1
- /// <reference types="node" />
2
- import { OutgoingHttpHeaders } from "http";
3
- import { Context, Handler } from "../common";
4
- export declare type HTMLResponseResult = string | {
5
- status?: number;
6
- headers?: OutgoingHttpHeaders;
7
- body?: string;
8
- template: (ctx: Context) => Promise<string>;
9
- };
10
- export declare const HTMLResponseHandler: () => Handler<void>;
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HTMLResponseHandler = void 0;
4
- const HTMLResponseHandler = () => async (ctx) => {
5
- const results = ctx.results;
6
- const lastResult = results[results.length - 1];
7
- ctx.logger.trace(`last result is [${lastResult}]`);
8
- if (lastResult && typeof lastResult === "string" ||
9
- ((typeof lastResult.headers === "object" || lastResult.headers === undefined) &&
10
- (typeof lastResult.status === "number" || lastResult.status === undefined) &&
11
- (typeof lastResult.body === "string" || typeof lastResult.template === "function"))) {
12
- const status = typeof lastResult.status === "number" ? lastResult.status : 200;
13
- const headers = typeof lastResult.headers === "object" ? lastResult.headers : {
14
- "content-type": "text/html; charset=utf-8"
15
- };
16
- const toSend = lastResult.template ? await lastResult.template(ctx) : (typeof lastResult.body === "string" ? lastResult.body : lastResult);
17
- if (typeof toSend === "string") {
18
- ctx.logger.debug(`sending [${toSend}]`);
19
- await ctx.end({
20
- status,
21
- headers,
22
- body: toSend
23
- });
24
- }
25
- else {
26
- throw new Error("html result from HTMLResponseResult not string so last result not valid");
27
- }
28
- }
29
- else {
30
- throw new Error("html result from HTMLResponseResult not string so last result not valid");
31
- }
32
- };
33
- exports.HTMLResponseHandler = HTMLResponseHandler;
34
- //# sourceMappingURL=html.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"html.js","sourceRoot":"","sources":["../../../src/handler/response/html.ts"],"names":[],"mappings":";;;AAKO,MAAM,mBAAmB,GAAG,GAAkB,EAAE,CACrD,KAAK,EAAE,GAAY,EAAiB,EAAE;IACpC,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;IAC5B,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC/C,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,mBAAmB,UAAU,GAAG,CAAC,CAAC;IACnD,IAAI,UAAU,IAAI,OAAO,UAAU,KAAK,QAAQ;QAC9C,CAC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0 @@
1
- export * from "./html";
2
- export * from "./json";
3
- export * from "./result";
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/handler/response/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,yCAAuB;AACvB,yCAAuB;AACvB,2CAAyB"}
@@ -1,2 +0,0 @@
1
- import { Handler } from "../common";
2
- export declare const ResponseHandler: () => Handler<void>;
@@ -1,21 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ResponseHandler = void 0;
4
- const ResponseHandler = () => async (ctx) => {
5
- ctx.logger.trace("results [%o]", ctx.results);
6
- if (!ctx.results || ctx.results.length === 0) {
7
- throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
8
- }
9
- else {
10
- const lastResult = ctx.results[ctx.results.length - 1];
11
- ctx.logger.debug("response [%o]", lastResult);
12
- if (lastResult !== undefined) {
13
- await ctx.json(lastResult);
14
- }
15
- else {
16
- throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
17
- }
18
- }
19
- };
20
- exports.ResponseHandler = ResponseHandler;
21
- //# sourceMappingURL=json.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"json.js","sourceRoot":"","sources":["../../../src/handler/response/json.ts"],"names":[],"mappings":";;;AAEO,MAAM,eAAe,GAAG,GAAkB,EAAE,CACjD,KAAK,EAAE,GAAY,EAAiB,EAAE;IACpC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,cAAc,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IAC9C,IAAI,CAAC,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;QAC5C,MAAM,IAAI,KAAK,CAAC,+FAA+F,CAAC,CAAC;KAClH;SAAM;QACL,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QACvD,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,eAAe,EAAE,UAAU,CAAC,CAAC;QAC9C,IAAI,UAAU,KAAK,SAAS,EAAE;YAC5B,MAAM,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;SAC5B;aAAM;YACL,MAAM,IAAI,KAAK,CAAC,+FAA+F,CAAC,CAAC;SAClH;KACF;AACH,CAAC,CAAC;AAdS,QAAA,eAAe,mBAcxB"}
@@ -1,4 +0,0 @@
1
- import { Parser } from "../../util";
2
- import { ParseOptions } from "../../util/parser/common";
3
- import { Handler } from "../common";
4
- export declare const ResultParser: (options: ParseOptions | ParseOptions[], parser?: Parser | undefined) => Handler<any>;