@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
@@ -1,55 +0,0 @@
1
- import { GroupPolicy } from "../util/session";
2
- import { SessionHandler, SessionHandlerOptions } from "./middleware/session";
3
- import { GroupPolicyHandler } from "./middleware/group";
4
- import { Parser } from "../util/parser";
5
- import { ParseOptions } from "../util/parser/common";
6
- import { Handler } from "./common";
7
- import { ParseRequest } from "./middleware/parse";
8
- import { ResponseHandler } from "./response/json";
9
- import { ResultParser } from "./response/result";
10
-
11
- export interface APIHandlerOptions {
12
- parser?: Parser;
13
- headers?: ParseOptions | ParseOptions[];
14
- query?: ParseOptions | false | ParseOptions[];
15
- params?: ParseOptions | false | ParseOptions[];
16
- body?: ParseOptions | false | ParseOptions[];
17
- result?: ParseOptions | ParseOptions[];
18
- handler: Array<Handler> | Handler;
19
- middleware?: Handler[];
20
- session?: SessionHandlerOptions | Handler;
21
- policy?: GroupPolicy;
22
- }
23
-
24
- /**
25
- * APIHandler
26
- *
27
- * ```typescript
28
- *app.use(APIHandler({
29
- * query: { ... },
30
- * body: { ... },
31
- * result: { ... }
32
- *}));
33
- * ```
34
- */
35
- export const APIHandler = (options: APIHandlerOptions): Array<Handler> =>
36
- // setup options.middleware
37
- (options.middleware ? options.middleware : [])
38
- // setup session
39
- .concat(options.session ? typeof options.session === "function" ? [options.session] : [SessionHandler(options.session)] : [])
40
- // setup policy
41
- .concat(options.policy ? [GroupPolicyHandler(options.policy)] : [])
42
- // setup request parse
43
- .concat([ParseRequest({
44
- headers: options.headers,
45
- query: options.query,
46
- params: options.params,
47
- body: options.body,
48
- parser: options.parser
49
- })])
50
- // setup options.handler
51
- .concat(options.handler instanceof Array ? options.handler : [options.handler])
52
- // setup response parse
53
- .concat(options.result ? ResultParser(options.result, options.parser) : [])
54
- // setup response handler
55
- .concat(ResponseHandler());
@@ -1,92 +0,0 @@
1
- import { SimpleMap } from "../util/parser/common";
2
- import { Logger } from "../util/logger";
3
- import { isFeatureEnabled } from "../util/config/featuretoggle";
4
- import { normalizePath } from "./common/tokenize-match";
5
- import { Router, Handler, Method } from "./common";
6
- import { RouterHandlerOptions } from "./common/router-utils";
7
-
8
- export interface FeatureRouterPathOptions {
9
- path: string | string[];
10
- method: Method | Method[];
11
- handler: Array<Handler> | Handler;
12
- options?: RouterHandlerOptions;
13
- }
14
-
15
- export type FeatureRouterOptions = SimpleMap<FeatureRouterPathOptions>;
16
-
17
- const FEATURE_ROUTER_METHODS: Method[] = ["get", "post", "put", "delete", "patch", "options"];
18
-
19
- export const FeatureRouter = (options: FeatureRouterOptions, logger?: Logger): Router => {
20
- const router: Router = new Router();
21
- const toSetup = Object.keys(options);
22
- const enabled: string[] = [];
23
- const disabled: string[] = [];
24
- const enabledPaths: SimpleMap<string> = {};
25
- for (const featureName of toSetup) {
26
- const handlerOptions = options[featureName];
27
- if (!handlerOptions) {
28
- throw new Error(`no handler options for feature [${featureName}]`);
29
- } else {
30
- const { path, handler: implementation, method } = handlerOptions;
31
- if (!method) {
32
- throw new Error(`no methods for feature [${featureName}]`);
33
- } else if (!implementation) {
34
- throw new Error(`no implementation for feature [${featureName}]`);
35
- } else if (!path) {
36
- throw new Error(`no path for feature [${featureName}]`);
37
- } else {
38
- if (method instanceof Array) {
39
- for (const m of method) {
40
- if (FEATURE_ROUTER_METHODS.indexOf(m.toLowerCase() as Method) === -1) {
41
- throw new Error(`feature [${featureName}] method [${m.toUpperCase()}] not defined! use only [${FEATURE_ROUTER_METHODS.join(",")}]`);
42
- }
43
- }
44
- } else if (FEATURE_ROUTER_METHODS.indexOf(method.toLowerCase() as Method) === -1) {
45
- throw new Error(`feature [${featureName}] method [${method.toUpperCase()}] not defined! use only [${FEATURE_ROUTER_METHODS.join(",")}]`);
46
- }
47
- const methods = method instanceof Array ? method : [method];
48
- if (isFeatureEnabled(featureName)) {
49
- if (logger) {
50
- logger.trace(`feature [${featureName}] enabled`);
51
- }
52
- enabled.push(featureName);
53
- const paths = path instanceof Array ? path : [path];
54
- for (const nnP of paths) {
55
- const p = normalizePath(nnP);
56
- for (const m of methods) {
57
- if (logger) {
58
- logger.info("%s", featureName);
59
- logger.info("\t%s:%s", m.toUpperCase(), p);
60
- if ((handlerOptions as any).___filePath) {
61
- logger.info("\t%s", (handlerOptions as any).___filePath);
62
- }
63
- }
64
- if (enabledPaths[`${p}${m}`] !== undefined) {
65
- throw new Error(`${featureName} collides with feature ${enabledPaths[`${p}${m}`]} on path ${p} method ${m}`)
66
- }
67
- enabledPaths[`${p}${m}`] = featureName;
68
- router.use(implementation, p, m.toLocaleLowerCase() as Method, handlerOptions.options);
69
- }
70
- }
71
- } else {
72
- if (logger) {
73
- logger.debug("feature [%s] disabled", featureName);
74
- }
75
- disabled.push(featureName);
76
- }
77
- }
78
- }
79
- }
80
- if (logger && enabled.length > 0) {
81
- logger.debug("enabled features [%s]", enabled.join(","));
82
- }
83
- if (logger) {
84
- if (disabled.length > 0) {
85
- logger.warn("disabled features [%s]", disabled.join(","));
86
- logger.warn(`to enable them just add the env var <feature>=true`);
87
- } else {
88
- logger.debug(`no features disabled`);
89
- }
90
- }
91
- return router;
92
- };
@@ -1,36 +0,0 @@
1
- import { OutgoingHttpHeaders } from "http";
2
- import { Context, Handler } from "../common";
3
-
4
- export type HTMLResponseResult = string | { status?: number; headers?: OutgoingHttpHeaders, body?: string; template: (ctx: Context) => Promise<string>; }
5
-
6
- export const HTMLResponseHandler = (): Handler<void> =>
7
- async (ctx: Context): Promise<void> => {
8
- const results = ctx.results;
9
- const lastResult = results[results.length - 1];
10
- ctx.logger.trace(`last result is [${lastResult}]`);
11
- if (lastResult && typeof lastResult === "string" ||
12
- (
13
- (typeof lastResult.headers === "object" || lastResult.headers === undefined) &&
14
- (typeof lastResult.status === "number" || lastResult.status === undefined) &&
15
- (typeof lastResult.body === "string" || typeof lastResult.template === "function")
16
- )
17
- ) {
18
- const status = typeof lastResult.status === "number" ? lastResult.status : 200;
19
- const headers = typeof lastResult.headers === "object" ? lastResult.headers : {
20
- "content-type": "text/html; charset=utf-8"
21
- };
22
- const toSend = lastResult.template ? await lastResult.template(ctx) : (typeof lastResult.body === "string" ? lastResult.body : lastResult);
23
- if (typeof toSend === "string") {
24
- ctx.logger.debug(`sending [${toSend}]`);
25
- await ctx.end({
26
- status,
27
- headers,
28
- body: toSend
29
- });
30
- } else {
31
- throw new Error("html result from HTMLResponseResult not string so last result not valid");
32
- }
33
- } else {
34
- throw new Error("html result from HTMLResponseResult not string so last result not valid");
35
- }
36
- }
@@ -1,3 +0,0 @@
1
- export * from "./html";
2
- export * from "./json";
3
- export * from "./result";
@@ -1,19 +0,0 @@
1
- import { Context, Handler } from "../common";
2
-
3
- export const ResponseHandler = (): Handler<void> =>
4
- async (ctx: Context): Promise<void> => {
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
- } else {
9
- const lastResult = ctx.results[ctx.results.length - 1];
10
- ctx.logger.debug("response [%o]", lastResult);
11
- if (lastResult !== undefined) {
12
- await ctx.json(lastResult);
13
- } else {
14
- throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
15
- }
16
- }
17
- };
18
-
19
-
@@ -1,40 +0,0 @@
1
- import { parse, Parser } from "../../util";
2
- import { ParseOptions } from "../../util/parser/common";
3
- import { Context, Handler } from "../common";
4
-
5
- export const ResultParser = (options: ParseOptions | ParseOptions[], parser?: Parser): Handler<any> =>
6
- async (ctx: Context): Promise<any> => {
7
- if (!ctx.results || ctx.results.length === 0) {
8
- ctx.logger.debug(`not parsing results`);
9
- return undefined;
10
- } else {
11
- const index = ctx.results.length - 1;
12
- const lastResult = ctx.results[index];
13
- ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
14
- try {
15
- if (options instanceof Array) {
16
- for (let i = 0; i < options.length; i++) {
17
- const o = options[i];
18
- try {
19
- const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, o.options, o.mode, o.ignoreUndefined);
20
- ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
21
- return mappedResults;
22
- } catch (e) {
23
- if (i === options.length - 1) {
24
- throw e;
25
- } else {
26
- continue;
27
- }
28
- }
29
- }
30
- } else {
31
- const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, options.options, options.mode, options.ignoreUndefined);
32
- ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
33
- return mappedResults;
34
- }
35
- } catch (e) {
36
- ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
37
- throw e;
38
- }
39
- }
40
- };
@@ -1,64 +0,0 @@
1
- import { request, RequestOptions, RequestResponse } from "./request";
2
- import { Logger, LogLevel } from "./logger";
3
- import { SimpleMap } from "./parser";
4
-
5
- export type RequestMapEndpoint = (args: Partial<RequestOptions>, logger?: Logger) => Promise<RequestResponse>;
6
-
7
- export type RequestMapEndpointMap = SimpleMap<RequestMapEndpoint>
8
-
9
- const SEPARATOR = "_";
10
-
11
- export class RequestMap {
12
-
13
- public endpoints: RequestMapEndpointMap = {};
14
- constructor(endpoints: {
15
- [path: string]: {
16
- [method: string]: {
17
- name?: string;
18
- description?: string;
19
- }
20
- }
21
- }, hostname: string, private readonly logger?: Logger, baseOptions?: Partial<RequestOptions>) {
22
- const paths = Object.keys(endpoints);
23
- for (const p of paths) {
24
- const methods = Object.keys(endpoints[p]);
25
- for (const m of methods) {
26
- const mL = m.toLocaleLowerCase();
27
- const endpointPath = `${p.split("/").map(p => p.trim()).map(p => p.replaceAll(":", "").replaceAll("?", "")).filter(p => p).map(p => p.toLocaleLowerCase()).join(SEPARATOR)}${SEPARATOR}${mL}`;
28
- //const routerOptions: RouterHandlerOptions = doc[p][m];
29
- if (!this.endpoints[endpointPath]) {
30
- this.endpoints[endpointPath] = async (args: Partial<RequestOptions>, logger?: Logger) => {
31
- const log = (level: LogLevel, text: string, ...optionalParams: any[]) => {
32
- if (this.logger) {
33
- this.logger[level](text, ...optionalParams);
34
- }
35
- if (logger) {
36
- logger[level](text, ...optionalParams);
37
- }
38
- }
39
- try {
40
-
41
- const realOptions = {
42
- ...baseOptions,
43
- url: `${hostname}${p}`,
44
- method: m,
45
- ...args
46
- };
47
- log("trace", "request to %o", realOptions);
48
- log("debug", "request to %s %s", realOptions.method, realOptions.url);
49
- const response = await request(realOptions);
50
- log("trace", "response from %s %s %o", realOptions.method, realOptions.url, response);
51
- log("debug", "response from %s %s", realOptions.method, realOptions.url);
52
- return response;
53
- } catch (e: any) {
54
- log("error", "request failed with message %s", e.message);
55
- throw e;
56
- }
57
- }
58
- } else {
59
- throw new Error("two methods for same endpoint");
60
- }
61
- }
62
- }
63
- }
64
- }
@@ -1,207 +0,0 @@
1
- // https://github.com/jshttp/cookie/blob/master/index.js
2
- /*!
3
- * cookie
4
- * Copyright(c) 2012-2014 Roman Shtylman
5
- * Copyright(c) 2015 Douglas Christopher Wilson
6
- * MIT Licensed
7
- */
8
-
9
- 'use strict';
10
-
11
- /**
12
- * Module exports.
13
- * @public
14
- */
15
-
16
- /**
17
- * Parse a cookie header.
18
- *
19
- * Parse the given cookie header string into an object
20
- * The object has the various cookies as keys(names) => values
21
- *
22
- * @param {string} str
23
- * @param {object} [options]
24
- * @return {object}
25
- * @public
26
- */
27
- export const parse = (str: string, options?: {
28
- decode?: (value: string) => string;
29
- }): NodeJS.Dict<string> => {
30
- if (typeof str !== 'string') {
31
- throw new TypeError('argument str must be a string');
32
- }
33
-
34
- const obj: NodeJS.Dict<string> = {}
35
- const opt = options || {};
36
- const pairs = str.split(pairSplitRegExp);
37
- const dec = opt.decode || decode;
38
-
39
- for (let i = 0; i < pairs.length; i++) {
40
- const pair = pairs[i];
41
- let eq_idx = pair.indexOf('=');
42
-
43
- // skip things that don't look like key=value
44
- if (eq_idx < 0) {
45
- continue;
46
- }
47
-
48
- const key = pair.substr(0, eq_idx).trim()
49
- let val = pair.substr(++eq_idx, pair.length).trim();
50
-
51
- // quoted values
52
- if ('"' == val[0]) {
53
- val = val.slice(1, -1);
54
- }
55
- // only assign once
56
- if (undefined == obj[key]) {
57
- obj[key] = tryDecode(val, dec);
58
- }
59
- }
60
-
61
- return obj;
62
- }
63
-
64
- /**
65
- * Serialize data into a cookie header.
66
- *
67
- * Serialize the a name value pair into a cookie string suitable for
68
- * http headers. An optional options object specified cookie parameters.
69
- *
70
- * serialize('foo', 'bar', { httpOnly: true })
71
- * => "foo=bar; httpOnly"
72
- *
73
- * @param {string} name
74
- * @param {string} val
75
- * @param {object} [options]
76
- * @return {string}
77
- * @public
78
- */
79
- export const serialize = (name: string, val: string, options?: {
80
- encode?: (uriComponent: string | number | boolean) => string;
81
- maxAge?: number | null;
82
- domain?: string;
83
- httpOnly?: boolean;
84
- secure?: boolean;
85
- path?: string;
86
- expires?: Date;
87
- sameSite?: "lax" | "strict" | "none" | true;
88
- }): string => {
89
- const opt = options || {};
90
- const enc = opt.encode || encode;
91
-
92
- if (typeof enc !== 'function') {
93
- throw new TypeError('option encode is invalid');
94
- }
95
-
96
- if (!fieldContentRegExp.test(name)) {
97
- throw new TypeError('argument name is invalid');
98
- }
99
-
100
- const value = enc(val);
101
-
102
- if (value && !fieldContentRegExp.test(value)) {
103
- throw new TypeError('argument val is invalid');
104
- }
105
-
106
- let str = name + '=' + value;
107
-
108
- if (null != opt.maxAge) {
109
- const maxAge = opt.maxAge - 0;
110
-
111
- if (isNaN(maxAge) || !isFinite(maxAge)) {
112
- throw new TypeError('option maxAge is invalid')
113
- }
114
-
115
- str += '; Max-Age=' + Math.floor(maxAge);
116
- }
117
-
118
- if (opt.domain) {
119
- if (!fieldContentRegExp.test(opt.domain)) {
120
- throw new TypeError('option domain is invalid');
121
- }
122
-
123
- str += '; Domain=' + opt.domain;
124
- }
125
-
126
- if (opt.path) {
127
- if (!fieldContentRegExp.test(opt.path)) {
128
- throw new TypeError('option path is invalid');
129
- }
130
-
131
- str += '; Path=' + opt.path;
132
- }
133
-
134
- if (opt.expires) {
135
- if (typeof opt.expires.toUTCString !== 'function') {
136
- throw new TypeError('option expires is invalid');
137
- }
138
-
139
- str += '; Expires=' + opt.expires.toUTCString();
140
- }
141
-
142
- if (opt.httpOnly) {
143
- str += '; HttpOnly';
144
- }
145
-
146
- if (opt.secure) {
147
- str += '; Secure';
148
- }
149
-
150
- if (opt.sameSite) {
151
- const sameSite = typeof opt.sameSite === 'string'
152
- ? opt.sameSite.toLowerCase() : opt.sameSite;
153
-
154
- switch (sameSite) {
155
- case true:
156
- str += '; SameSite=Strict';
157
- break;
158
- case 'lax':
159
- str += '; SameSite=Lax';
160
- break;
161
- case 'strict':
162
- str += '; SameSite=Strict';
163
- break;
164
- case 'none':
165
- str += '; SameSite=None';
166
- break;
167
- default:
168
- throw new TypeError('option sameSite is invalid');
169
- }
170
- }
171
-
172
- return str;
173
- }
174
-
175
- /**
176
- * Module variables.
177
- * @private
178
- */
179
-
180
- const decode = decodeURIComponent;
181
- const encode = encodeURIComponent;
182
- const pairSplitRegExp = /; */;
183
-
184
- /**
185
- * RegExp to match field-content in RFC 7230 sec 3.2
186
- *
187
- * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
188
- * field-vchar = VCHAR / obs-text
189
- * obs-text = %x80-FF
190
- */
191
-
192
- const fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
193
-
194
- /**
195
- * Try decoding a string using a decoding function.
196
- *
197
- * @param {string} str
198
- * @param {function} decode
199
- * @private
200
- */
201
- const tryDecode = (str: string, decode: (str: string) => string): string => {
202
- try {
203
- return decode(str);
204
- } catch (e) {
205
- return str;
206
- }
207
- }
@@ -1,6 +0,0 @@
1
- import { parse, serialize } from "./cookie";
2
-
3
- export const COOKIE = {
4
- parse,
5
- serialize
6
- }
@@ -1,44 +0,0 @@
1
- import { request, RequestOptions, RequestResponse, ResponseError } from "../request";
2
- import { App } from "../../handler/app";
3
- import { existsSync, unlinkSync } from "fs";
4
- import { createServer } from "http";
5
-
6
- export const TestHelper = async (app: App, options: RequestOptions, cb?: (response: RequestResponse) => void): Promise<RequestResponse | void> => {
7
- const unixSocket = `/tmp/socket.test.helper${Date.now()}`;
8
- if (existsSync(unixSocket)) {
9
- unlinkSync(unixSocket);
10
- }
11
- const server = createServer(app.listener);
12
- return new Promise<RequestResponse | void>((resolve, reject) => {
13
- server.listen(unixSocket, () => {
14
- request({
15
- ...options,
16
- socketPath: unixSocket
17
- }).then((response) => {
18
- server.close(() => {
19
- if (cb) {
20
- try {
21
- cb(response);
22
- } catch (ee) {
23
- reject(ee);
24
- }
25
- }
26
- resolve(response);
27
- });
28
- }).catch((e: ResponseError) => {
29
- server.close(() => {
30
- if (cb) {
31
- try {
32
- cb(e as any);
33
- } catch (ee) {
34
- reject(ee);
35
- }
36
- resolve();
37
- } else {
38
- reject(e);
39
- }
40
- });
41
- });
42
- });
43
- });
44
- }
@@ -1,17 +0,0 @@
1
- export type Callback<T = any> = (...args: any[]) => T;
2
-
3
- export interface FakeCallback<T = any> extends Callback<T> {
4
- callCount: number;
5
- callArgs: T[];
6
- }
7
-
8
- export const fake = (cb: Callback): FakeCallback => {
9
- const ret = (...args: any[]) => {
10
- ret.callCount++;
11
- ret.callArgs.push(args);
12
- return cb(...args);
13
- };
14
- ret.callCount = 0;
15
- ret.callArgs = [] as any;
16
- return ret;
17
- }
@@ -1,2 +0,0 @@
1
- export * from "./common";
2
- export * from "./app";
@@ -1,5 +0,0 @@
1
- import { v4 } from './v4';
2
-
3
- export const UUID = {
4
- v4
5
- };
@@ -1,2 +0,0 @@
1
- // https://github.com/uuidjs/uuid/blob/main/src/regex.js
2
- export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
@@ -1,14 +0,0 @@
1
- // https://github.com/uuidjs/uuid/blob/main/src/rng.js
2
-
3
- import crypto from 'crypto';
4
-
5
- const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate
6
- let poolPtr = rnds8Pool.length;
7
-
8
- export default function rng() {
9
- if (poolPtr > rnds8Pool.length - 16) {
10
- crypto.randomFillSync(rnds8Pool);
11
- poolPtr = 0;
12
- }
13
- return rnds8Pool.slice(poolPtr, (poolPtr += 16));
14
- }
@@ -1,53 +0,0 @@
1
- // https://github.com/uuidjs/uuid/blob/main/src/stringify.js
2
-
3
- import validate from './validate';
4
-
5
- /**
6
- * Convert array of 16 byte values to UUID string format of the form:
7
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
8
- */
9
- const byteToHex: string[] = [];
10
-
11
- for (let i = 0; i < 256; ++i) {
12
- byteToHex.push((i + 0x100).toString(16).substr(1));
13
- }
14
-
15
- const stringify = (arr: Uint8Array, offset = 0): string => {
16
- // Note: Be careful editing this code! It's been tuned for performance
17
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
18
- const uuid = (
19
- byteToHex[arr[offset + 0]] +
20
- byteToHex[arr[offset + 1]] +
21
- byteToHex[arr[offset + 2]] +
22
- byteToHex[arr[offset + 3]] +
23
- '-' +
24
- byteToHex[arr[offset + 4]] +
25
- byteToHex[arr[offset + 5]] +
26
- '-' +
27
- byteToHex[arr[offset + 6]] +
28
- byteToHex[arr[offset + 7]] +
29
- '-' +
30
- byteToHex[arr[offset + 8]] +
31
- byteToHex[arr[offset + 9]] +
32
- '-' +
33
- byteToHex[arr[offset + 10]] +
34
- byteToHex[arr[offset + 11]] +
35
- byteToHex[arr[offset + 12]] +
36
- byteToHex[arr[offset + 13]] +
37
- byteToHex[arr[offset + 14]] +
38
- byteToHex[arr[offset + 15]]
39
- ).toLowerCase();
40
-
41
- // Consistency check for valid UUID. If this throws, it's likely due to one
42
- // of the following:
43
- // - One or more input array values don't map to a hex octet (leading to
44
- // "undefined" in the uuid)
45
- // - Invalid input values for the RFC `version` or `variant` fields
46
- if (!validate(uuid)) {
47
- throw TypeError('Stringified UUID is invalid');
48
- }
49
-
50
- return uuid;
51
- }
52
-
53
- export default stringify;