jimpex 8.0.0 → 9.0.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.
- package/CHANGELOG.md +13 -0
- package/README.md +2 -2
- package/dist/app/index.d.mts +14 -0
- package/dist/app/index.d.ts +5 -4
- package/dist/app/index.js +4 -0
- package/dist/app/jimpex.d.mts +14 -0
- package/dist/app/jimpex.d.ts +3 -2
- package/dist/app/jimpex.js +225 -0
- package/dist/app/jimpex.js.map +1 -1
- package/dist/controllers/common/config.d.mts +79 -0
- package/dist/controllers/common/config.d.ts +3 -2
- package/dist/controllers/common/config.js +18 -0
- package/dist/controllers/common/config.js.map +1 -1
- package/dist/controllers/common/health.d.mts +83 -0
- package/dist/controllers/common/health.d.ts +4 -3
- package/dist/controllers/common/health.js +18 -0
- package/dist/controllers/common/health.js.map +1 -1
- package/dist/controllers/common/index.d.mts +21 -0
- package/dist/controllers/common/index.d.ts +4 -4
- package/dist/controllers/common/index.js +6 -0
- package/dist/controllers/common/statics.d.mts +215 -0
- package/dist/controllers/common/statics.d.ts +4 -4
- package/dist/controllers/common/statics.js +51 -0
- package/dist/controllers/common/statics.js.map +1 -1
- package/dist/controllers/index.d.mts +24 -0
- package/dist/controllers/index.d.ts +4 -4
- package/dist/controllers/index.js +5 -0
- package/dist/controllers/utils/gateway.d.mts +725 -0
- package/dist/controllers/utils/gateway.d.ts +4 -3
- package/dist/controllers/utils/gateway.js +152 -0
- package/dist/controllers/utils/gateway.js.map +1 -1
- package/dist/controllers/utils/index.d.mts +17 -0
- package/dist/controllers/utils/index.d.ts +4 -3
- package/dist/controllers/utils/index.js +4 -0
- package/dist/esm/app/jimpex.js +222 -1
- package/dist/esm/app/jimpex.js.map +1 -1
- package/dist/esm/{chunk-T2T6Q22Z.js → chunk-2B2CG5KL.js} +1 -1
- package/dist/esm/controllers/common/config.js +19 -1
- package/dist/esm/controllers/common/config.js.map +1 -1
- package/dist/esm/controllers/common/health.js +19 -1
- package/dist/esm/controllers/common/health.js.map +1 -1
- package/dist/esm/controllers/common/statics.js +48 -1
- package/dist/esm/controllers/common/statics.js.map +1 -1
- package/dist/esm/controllers/utils/gateway.js +153 -1
- package/dist/esm/controllers/utils/gateway.js.map +1 -1
- package/dist/esm/middlewares/common/errorHandler.js +25 -1
- package/dist/esm/middlewares/common/errorHandler.js.map +1 -1
- package/dist/esm/middlewares/common/forceHTTPS.js +13 -1
- package/dist/esm/middlewares/common/forceHTTPS.js.map +1 -1
- package/dist/esm/middlewares/common/hsts.js +22 -1
- package/dist/esm/middlewares/common/hsts.js.map +1 -1
- package/dist/esm/middlewares/html/fastHTML.js +55 -1
- package/dist/esm/middlewares/html/fastHTML.js.map +1 -1
- package/dist/esm/middlewares/html/showHTML.js +33 -1
- package/dist/esm/middlewares/html/showHTML.js.map +1 -1
- package/dist/esm/middlewares/utils/versionValidator.js +35 -1
- package/dist/esm/middlewares/utils/versionValidator.js.map +1 -1
- package/dist/esm/services/common/appError.js +48 -2
- package/dist/esm/services/common/appError.js.map +1 -1
- package/dist/esm/services/common/httpError.js +10 -1
- package/dist/esm/services/common/httpError.js.map +1 -1
- package/dist/esm/services/common/index.js +1 -1
- package/dist/esm/services/common/sendFile.js +1 -1
- package/dist/esm/services/frontend/frontendFs.js +29 -1
- package/dist/esm/services/frontend/frontendFs.js.map +1 -1
- package/dist/esm/services/frontend/index.js +1 -1
- package/dist/esm/services/html/htmlGenerator.js +51 -1
- package/dist/esm/services/html/htmlGenerator.js.map +1 -1
- package/dist/esm/services/html/index.js +1 -1
- package/dist/esm/services/http/apiClient.js +27 -1
- package/dist/esm/services/http/apiClient.js.map +1 -1
- package/dist/esm/services/http/http.js +50 -1
- package/dist/esm/services/http/http.js.map +1 -1
- package/dist/esm/services/http/index.js +1 -1
- package/dist/esm/services/http/responsesBuilder.js +49 -2
- package/dist/esm/services/http/responsesBuilder.js.map +1 -1
- package/dist/esm/services/utils/ensureBearerToken.js +17 -1
- package/dist/esm/services/utils/ensureBearerToken.js.map +1 -1
- package/dist/esm/services/utils/index.js +1 -1
- package/dist/esm/utils/fns/others.js +1 -1
- package/dist/esm/utils/fns/routes.js +1 -1
- package/dist/esm/utils/fns/routes.js.map +1 -1
- package/dist/esm/utils/fns/statuses.js +1 -1
- package/dist/esm/utils/fns/text.js +1 -1
- package/dist/esm/utils/wrappers.js +1 -1
- package/dist/{jimpex-7eaee271.d.ts → index-b2a04c78.d.ts} +9 -5
- package/dist/index-efeb437e.d.ts +1282 -0
- package/dist/index.d.mts +46 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +9 -0
- package/dist/middlewares/common/errorHandler.d.mts +132 -0
- package/dist/middlewares/common/errorHandler.d.ts +4 -3
- package/dist/middlewares/common/errorHandler.js +24 -0
- package/dist/middlewares/common/errorHandler.js.map +1 -1
- package/dist/middlewares/common/forceHTTPS.d.mts +69 -0
- package/dist/middlewares/common/forceHTTPS.d.ts +5 -4
- package/dist/middlewares/common/forceHTTPS.js +12 -0
- package/dist/middlewares/common/forceHTTPS.js.map +1 -1
- package/dist/middlewares/common/hsts.d.mts +110 -0
- package/dist/middlewares/common/hsts.d.ts +5 -4
- package/dist/middlewares/common/hsts.js +21 -0
- package/dist/middlewares/common/hsts.js.map +1 -1
- package/dist/middlewares/common/index.d.mts +22 -0
- package/dist/middlewares/common/index.d.ts +4 -3
- package/dist/middlewares/common/index.js +6 -0
- package/dist/middlewares/html/fastHTML.d.mts +180 -0
- package/dist/middlewares/html/fastHTML.d.ts +4 -4
- package/dist/middlewares/html/fastHTML.js +54 -0
- package/dist/middlewares/html/fastHTML.js.map +1 -1
- package/dist/middlewares/html/index.d.mts +21 -0
- package/dist/middlewares/html/index.d.ts +4 -4
- package/dist/middlewares/html/index.js +5 -0
- package/dist/middlewares/html/showHTML.d.mts +127 -0
- package/dist/middlewares/html/showHTML.d.ts +4 -4
- package/dist/middlewares/html/showHTML.js +32 -0
- package/dist/middlewares/html/showHTML.js.map +1 -1
- package/dist/middlewares/index.d.mts +30 -0
- package/dist/middlewares/index.d.ts +4 -4
- package/dist/middlewares/index.js +6 -0
- package/dist/middlewares/utils/index.d.mts +20 -0
- package/dist/middlewares/utils/index.d.ts +4 -3
- package/dist/middlewares/utils/index.js +4 -0
- package/dist/middlewares/utils/versionValidator.d.mts +215 -0
- package/dist/middlewares/utils/versionValidator.d.ts +4 -3
- package/dist/middlewares/utils/versionValidator.js +34 -0
- package/dist/middlewares/utils/versionValidator.js.map +1 -1
- package/dist/services/common/appError.d.mts +139 -0
- package/dist/services/common/appError.d.ts +4 -3
- package/dist/services/common/appError.js +47 -1
- package/dist/services/common/appError.js.map +1 -1
- package/dist/services/common/httpError.d.mts +80 -0
- package/dist/services/common/httpError.d.ts +4 -3
- package/dist/services/common/httpError.js +9 -0
- package/dist/services/common/httpError.js.map +1 -1
- package/dist/services/common/index.d.mts +47 -0
- package/dist/services/common/index.d.ts +4 -4
- package/dist/services/common/index.js +4 -1
- package/dist/services/common/sendFile.d.mts +102 -0
- package/dist/services/common/sendFile.d.ts +3 -3
- package/dist/services/frontend/frontendFs.d.mts +96 -0
- package/dist/services/frontend/frontendFs.d.ts +3 -3
- package/dist/services/frontend/frontendFs.js +32 -0
- package/dist/services/frontend/frontendFs.js.map +1 -1
- package/dist/services/frontend/index.d.mts +40 -0
- package/dist/services/frontend/index.d.ts +4 -4
- package/dist/services/frontend/index.js +2 -1
- package/dist/services/html/htmlGenerator.d.mts +237 -0
- package/dist/services/html/htmlGenerator.d.ts +2 -2
- package/dist/services/html/htmlGenerator.js +50 -0
- package/dist/services/html/htmlGenerator.js.map +1 -1
- package/dist/services/html/index.d.mts +43 -0
- package/dist/services/html/index.d.ts +4 -4
- package/dist/services/html/index.js +2 -1
- package/dist/services/http/apiClient.d.mts +170 -0
- package/dist/services/http/apiClient.d.ts +4 -3
- package/dist/services/http/apiClient.js +26 -0
- package/dist/services/http/apiClient.js.map +1 -1
- package/dist/services/http/http.d.mts +176 -0
- package/dist/services/http/http.d.ts +4 -3
- package/dist/services/http/http.js +53 -0
- package/dist/services/http/http.js.map +1 -1
- package/dist/services/http/index.d.mts +51 -0
- package/dist/services/http/index.d.ts +4 -3
- package/dist/services/http/index.js +4 -1
- package/dist/services/http/responsesBuilder.d.mts +179 -0
- package/dist/services/http/responsesBuilder.d.ts +3 -2
- package/dist/services/http/responsesBuilder.js +48 -1
- package/dist/services/http/responsesBuilder.js.map +1 -1
- package/dist/services/index.d.mts +33 -0
- package/dist/services/index.d.ts +4 -4
- package/dist/services/index.js +8 -0
- package/dist/services/utils/ensureBearerToken.d.mts +158 -0
- package/dist/services/utils/ensureBearerToken.d.ts +5 -4
- package/dist/services/utils/ensureBearerToken.js +16 -0
- package/dist/services/utils/ensureBearerToken.js.map +1 -1
- package/dist/services/utils/index.d.mts +44 -0
- package/dist/services/utils/index.d.ts +4 -3
- package/dist/services/utils/index.js +2 -1
- package/dist/types/events.d.mts +14 -0
- package/dist/types/events.d.ts +5 -4
- package/dist/types/express.d.mts +10 -0
- package/dist/types/http.d.mts +79 -0
- package/dist/types/index.d.mts +14 -0
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.js +9 -0
- package/dist/types/options.d.mts +14 -0
- package/dist/types/options.d.ts +4 -3
- package/dist/types/utils.d.mts +48 -0
- package/dist/types/wootils.d.mts +4 -0
- package/dist/utils/fns/index.d.mts +5 -0
- package/dist/utils/fns/index.js +7 -0
- package/dist/utils/fns/others.d.mts +17 -0
- package/dist/utils/fns/routes.d.mts +39 -0
- package/dist/utils/fns/routes.js.map +1 -1
- package/dist/utils/fns/statuses.d.mts +45 -0
- package/dist/utils/fns/statuses.js +4 -0
- package/dist/utils/fns/statuses.js.map +1 -1
- package/dist/utils/fns/text.d.mts +9 -0
- package/dist/utils/index.d.mts +19 -0
- package/dist/utils/index.d.ts +5 -4
- package/dist/utils/index.js +5 -0
- package/dist/utils/wrappers.d.mts +14 -0
- package/dist/utils/wrappers.d.ts +4 -3
- package/package.json +43 -43
- /package/dist/esm/{chunk-T2T6Q22Z.js.map → chunk-2B2CG5KL.js.map} +0 -0
|
@@ -19,6 +19,10 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
19
19
|
return to;
|
|
20
20
|
};
|
|
21
21
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
26
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
27
|
mod
|
|
24
28
|
));
|
|
@@ -38,8 +42,17 @@ var import_urijs = __toESM(require("urijs"));
|
|
|
38
42
|
var import_deep_assign = require("@homer0/deep-assign");
|
|
39
43
|
var import_utils = require("../../utils");
|
|
40
44
|
class HTTP {
|
|
45
|
+
/**
|
|
46
|
+
* @param options The options to construct the class.
|
|
47
|
+
*/
|
|
41
48
|
constructor({ inject: { logger }, ...options }) {
|
|
49
|
+
/**
|
|
50
|
+
* The service used to log information in the terminal.
|
|
51
|
+
*/
|
|
42
52
|
__publicField(this, "_logger");
|
|
53
|
+
/**
|
|
54
|
+
* The service customization options.
|
|
55
|
+
*/
|
|
43
56
|
__publicField(this, "_options");
|
|
44
57
|
this._logger = logger;
|
|
45
58
|
this._options = (0, import_deep_assign.deepAssignWithOverwrite)(
|
|
@@ -50,6 +63,12 @@ class HTTP {
|
|
|
50
63
|
);
|
|
51
64
|
this.fetch = this.fetch.bind(this);
|
|
52
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* Makes a fetch request.
|
|
68
|
+
*
|
|
69
|
+
* @param url The URL to fetch.
|
|
70
|
+
* @param options The custom options for the request.
|
|
71
|
+
*/
|
|
53
72
|
async fetch(url, options = {}) {
|
|
54
73
|
let useURL = url;
|
|
55
74
|
if (options.qs) {
|
|
@@ -84,6 +103,11 @@ class HTTP {
|
|
|
84
103
|
}
|
|
85
104
|
return response;
|
|
86
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* Tries to get the IP address from a given request.
|
|
108
|
+
*
|
|
109
|
+
* @param req The request from which it will try to obtain the IP address.
|
|
110
|
+
*/
|
|
87
111
|
getIPFromRequest(req) {
|
|
88
112
|
const headerValue = req.headers["x-forwarded-for"];
|
|
89
113
|
if (headerValue) {
|
|
@@ -91,6 +115,13 @@ class HTTP {
|
|
|
91
115
|
}
|
|
92
116
|
return req?.connection?.remoteAddress || req?.socket?.remoteAddress;
|
|
93
117
|
}
|
|
118
|
+
/**
|
|
119
|
+
* Creates a dictionary with all the custom headers a request has. By custom header it
|
|
120
|
+
* means all the headers which name start with `x-`.
|
|
121
|
+
*
|
|
122
|
+
* @param req The request from which it will try to get the headers.
|
|
123
|
+
* @param options The options to customize the behavior with certain headers.
|
|
124
|
+
*/
|
|
94
125
|
getCustomHeadersFromRequest(req, options = {}) {
|
|
95
126
|
const { includeXForwardedHeaders = false } = options;
|
|
96
127
|
return Object.keys(req.headers).reduce((acc, headerName) => {
|
|
@@ -100,6 +131,14 @@ class HTTP {
|
|
|
100
131
|
return acc;
|
|
101
132
|
}, {});
|
|
102
133
|
}
|
|
134
|
+
/**
|
|
135
|
+
* It takes a dictionary of headers and normalize the names so each word will start with
|
|
136
|
+
* an upper case character. This is helpful in case you added custom headers and didn't
|
|
137
|
+
* care about the casing, or when copying headers from a server request, as they all
|
|
138
|
+
* come tranformed into lower case.
|
|
139
|
+
*
|
|
140
|
+
* @param headers The dictionary of headers to normalize.
|
|
141
|
+
*/
|
|
103
142
|
normalizeHeaders(headers) {
|
|
104
143
|
return Object.keys(headers).reduce((acc, name) => {
|
|
105
144
|
const newName = name.split("-").map((part) => part.replace(/^(\w)/, (_, letter) => letter.toUpperCase())).join("-");
|
|
@@ -107,9 +146,18 @@ class HTTP {
|
|
|
107
146
|
return acc;
|
|
108
147
|
}, {});
|
|
109
148
|
}
|
|
149
|
+
/**
|
|
150
|
+
* The customization options.
|
|
151
|
+
*/
|
|
110
152
|
get options() {
|
|
111
153
|
return (0, import_deep_assign.deepAssignWithOverwrite)({}, this._options);
|
|
112
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* Logs a request information into the terminal.
|
|
157
|
+
*
|
|
158
|
+
* @param url The request URL.
|
|
159
|
+
* @param options The options for the request.
|
|
160
|
+
*/
|
|
113
161
|
_logRequest(url, options) {
|
|
114
162
|
const { method, headers } = options;
|
|
115
163
|
const prefix = "REQUEST> ";
|
|
@@ -125,6 +173,11 @@ class HTTP {
|
|
|
125
173
|
}
|
|
126
174
|
this._logger.info(lines);
|
|
127
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Logs a response information into the terminal.
|
|
178
|
+
*
|
|
179
|
+
* @param response The response to log.
|
|
180
|
+
*/
|
|
128
181
|
_logResponse(response) {
|
|
129
182
|
const prefix = "RESPONSE> ";
|
|
130
183
|
const lines = [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/http/http.ts"],"sourcesContent":["import fetch, { type RequestInit, type BodyInit } from 'node-fetch';\nimport urijs from 'urijs';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { provider } from '../../utils';\nimport { Logger, Request, HTTPResponse } from '../../types';\n/**\n * The options to customize the service.\n *\n * @group Services/HTTP\n */\nexport type HTTPOptions = {\n /**\n * Whether or not the service should log the requests and their responses.\n */\n logRequests?: boolean;\n};\n/**\n * The options to construct a {@link HTTP}.\n *\n * @group Services/HTTP\n */\nexport type HTTPContructorOptions = Partial<HTTPOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n logger: Logger;\n };\n};\n/**\n * The allowed formats for the body of a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchBody = string | Record<string | number, unknown> | BodyInit;\n/**\n * The options for a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchOptions = {\n /**\n * The HTTP method.\n *\n * @default 'GET'\n */\n method?: string;\n /**\n * The headers dictionary.\n */\n headers?: Record<string, string>;\n /**\n * The body of the request.\n */\n body?: HTTPFetchBody;\n /**\n * A dictionary of query string parameters.\n */\n qs?: Record<string, unknown>;\n /**\n * A request object generated by the application. This can be used to copy information\n * like custom headers or the IP (for the X-Forwarded-For header).\n */\n req?: Request;\n};\n/**\n * The options for the method that extracts custom headers from a request.\n *\n * @group Services/HTTP\n */\nexport type GetCustomHeadersFromRequestOptions = {\n /**\n * Since the method considers all headers that start with `x-` as custom headers,\n * setting this to `false` is the only way to exclude `x-forwarded-` headers from the\n * list.\n *\n * @default false\n */\n includeXForwardedHeaders?: boolean;\n};\n/**\n * A set of utilities to work with HTTP requests and responses.\n *\n * @group Services\n * @group Services/HTTP\n */\nexport class HTTP {\n /**\n * The service used to log information in the terminal.\n */\n protected readonly _logger: Logger;\n /**\n * The service customization options.\n */\n protected readonly _options: HTTPOptions;\n /**\n * @param options The options to construct the class.\n */\n constructor({ inject: { logger }, ...options }: HTTPContructorOptions) {\n this._logger = logger;\n this._options = deepAssignWithOverwrite(\n {\n logRequests: false,\n },\n options,\n );\n\n this.fetch = this.fetch.bind(this);\n }\n /**\n * Makes a fetch request.\n *\n * @param url The URL to fetch.\n * @param options The custom options for the request.\n */\n async fetch(url: string, options: HTTPFetchOptions = {}): Promise<HTTPResponse> {\n let useURL = url;\n if (options.qs) {\n useURL = urijs(url).query(options.qs).toString();\n }\n\n const fetchOptions: RequestInit = {\n method: (options.method || 'get').toUpperCase(),\n body: options.body as BodyInit,\n };\n\n let defaultHeaders: Record<string, string> | undefined;\n if (options.req) {\n defaultHeaders = this.getCustomHeadersFromRequest(options.req);\n const ip = this.getIPFromRequest(options.req);\n if (ip) {\n defaultHeaders['x-forwarded-for'] = ip;\n }\n }\n const headers = {\n ...defaultHeaders,\n ...options.headers,\n };\n\n if (Object.keys(headers).length) {\n fetchOptions.headers = this.normalizeHeaders(headers);\n }\n\n const { logRequests } = this._options;\n if (logRequests) {\n this._logRequest(useURL, fetchOptions);\n }\n\n const response = await fetch(useURL, fetchOptions);\n if (logRequests) {\n this._logResponse(response);\n }\n\n return response;\n }\n /**\n * Tries to get the IP address from a given request.\n *\n * @param req The request from which it will try to obtain the IP address.\n */\n getIPFromRequest(req: Request): string | undefined {\n const headerValue = req.headers['x-forwarded-for'];\n if (headerValue) {\n return String(headerValue);\n }\n\n return req?.connection?.remoteAddress || req?.socket?.remoteAddress;\n }\n /**\n * Creates a dictionary with all the custom headers a request has. By custom header it\n * means all the headers which name start with `x-`.\n *\n * @param req The request from which it will try to get the headers.\n * @param options The options to customize the behavior with certain headers.\n */\n getCustomHeadersFromRequest(\n req: Request,\n options: GetCustomHeadersFromRequestOptions = {},\n ): Record<string, string> {\n const { includeXForwardedHeaders = false } = options;\n return Object.keys(req.headers).reduce<Record<string, string>>((acc, headerName) => {\n if (\n headerName.startsWith('x-') &&\n (includeXForwardedHeaders || !headerName.startsWith('x-forwarded-'))\n ) {\n acc[headerName] = req.headers[headerName] as string;\n }\n return acc;\n }, {});\n }\n /**\n * It takes a dictionary of headers and normalize the names so each word will start with\n * an upper case character. This is helpful in case you added custom headers and didn't\n * care about the casing, or when copying headers from a server request, as they all\n * come tranformed into lower case.\n *\n * @param headers The dictionary of headers to normalize.\n */\n normalizeHeaders(headers: Record<string, string>): Record<string, string> {\n return Object.keys(headers).reduce<Record<string, string>>((acc, name) => {\n const newName = name\n .split('-')\n .map((part) => part.replace(/^(\\w)/, (_, letter) => letter.toUpperCase()))\n .join('-');\n\n acc[newName] = headers[name]!;\n return acc;\n }, {});\n }\n /**\n * The customization options.\n */\n get options(): Readonly<HTTPOptions> {\n return deepAssignWithOverwrite({}, this._options);\n }\n /**\n * Logs a request information into the terminal.\n *\n * @param url The request URL.\n * @param options The options for the request.\n */\n protected _logRequest(url: string, options: RequestInit): void {\n const { method, headers } = options;\n const prefix = 'REQUEST> ';\n const lines = ['--->>', `${prefix}${method} ${url}`];\n if (headers) {\n Object.keys(headers).forEach((header) => {\n const value = headers[header as keyof typeof headers];\n lines.push(`${prefix}${header}: ${value}`);\n });\n }\n\n if (options.body) {\n lines.push(`${prefix}body: \"${options.body}\"`);\n }\n\n this._logger.info(lines);\n }\n /**\n * Logs a response information into the terminal.\n *\n * @param response The response to log.\n */\n protected _logResponse(response: HTTPResponse) {\n const prefix = 'RESPONSE> ';\n const lines = [\n '<<---',\n `${prefix}${response.url}`,\n `${prefix}status: ${response.status}`,\n ];\n\n response.headers.forEach((value, header) => {\n lines.push(`${prefix}${header}: ${value}`);\n });\n\n this._logger.info(lines);\n }\n}\n/**\n * The service provider that once registered on the container will set an instance of\n * {@link HTTP} as the `http` service. The provider also checks the `debug.logRequests`\n * setting on the application configuration in order to enable or not the logging of\n * requests/responses.\n *\n * @example\n *\n * // Register it on the container\n * container.register(httpProvider);\n * // Getting access to the service instance\n * const http = container.get<HTTP>('http');\n *\n * @group Providers\n * @group Services/HTTP\n */\nexport const httpProvider = provider((app) => {\n app.set('http', () => {\n const config = app.getConfig();\n const logRequests = config.get<boolean | undefined>('debug.logRequests') === true;\n return new HTTP({\n inject: {\n logger: app.get('logger'),\n },\n logRequests,\n });\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAuD;AACvD,mBAAkB;AAClB,yBAAwC;AACxC,mBAAyB;AAmFlB,MAAM,KAAK;AAAA,EAYhB,YAAY,EAAE,QAAQ,EAAE,OAAO,MAAM,QAAQ,GAA0B;AARvE,wBAAmB;AAInB,wBAAmB;AAKjB,SAAK,UAAU;AACf,SAAK,eAAW;AAAA,MACd;AAAA,QACE,aAAa;AAAA,MACf;AAAA,MACA;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;AAAA,EACnC;AAAA,EAOA,MAAM,MAAM,KAAa,UAA4B,CAAC,GAA0B;AAC9E,QAAI,SAAS;AACb,QAAI,QAAQ,I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AAS,IAAI,UAAU;AAC7B,UAAM,cAAc,OAAO,IAAyB,mBAAmB,MAAM;AAC7E,WAAO,IAAI,KAAK;AAAA,MACd,QAAQ;AAAA,QACN,QAAQ,IAAI,IAAI,QAAQ;AAAA,MAC1B;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH,CAAC;","names":["urijs","fetch"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/http/http.ts"],"sourcesContent":["import fetch, { type RequestInit, type BodyInit } from 'node-fetch';\nimport urijs from 'urijs';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { provider } from '../../utils';\nimport { Logger, Request, HTTPResponse } from '../../types';\n/**\n * The options to customize the service.\n *\n * @group Services/HTTP\n */\nexport type HTTPOptions = {\n /**\n * Whether or not the service should log the requests and their responses.\n */\n logRequests?: boolean;\n};\n/**\n * The options to construct a {@link HTTP}.\n *\n * @group Services/HTTP\n */\nexport type HTTPContructorOptions = Partial<HTTPOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n logger: Logger;\n };\n};\n/**\n * The allowed formats for the body of a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchBody = string | Record<string | number, unknown> | BodyInit;\n/**\n * The options for a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchOptions = {\n /**\n * The HTTP method.\n *\n * @default 'GET'\n */\n method?: string;\n /**\n * The headers dictionary.\n */\n headers?: Record<string, string>;\n /**\n * The body of the request.\n */\n body?: HTTPFetchBody;\n /**\n * A dictionary of query string parameters.\n */\n qs?: Record<string, unknown>;\n /**\n * A request object generated by the application. This can be used to copy information\n * like custom headers or the IP (for the X-Forwarded-For header).\n */\n req?: Request;\n};\n/**\n * The options for the method that extracts custom headers from a request.\n *\n * @group Services/HTTP\n */\nexport type GetCustomHeadersFromRequestOptions = {\n /**\n * Since the method considers all headers that start with `x-` as custom headers,\n * setting this to `false` is the only way to exclude `x-forwarded-` headers from the\n * list.\n *\n * @default false\n */\n includeXForwardedHeaders?: boolean;\n};\n/**\n * A set of utilities to work with HTTP requests and responses.\n *\n * @group Services\n * @group Services/HTTP\n */\nexport class HTTP {\n /**\n * The service used to log information in the terminal.\n */\n protected readonly _logger: Logger;\n /**\n * The service customization options.\n */\n protected readonly _options: HTTPOptions;\n /**\n * @param options The options to construct the class.\n */\n constructor({ inject: { logger }, ...options }: HTTPContructorOptions) {\n this._logger = logger;\n this._options = deepAssignWithOverwrite(\n {\n logRequests: false,\n },\n options,\n );\n\n this.fetch = this.fetch.bind(this);\n }\n /**\n * Makes a fetch request.\n *\n * @param url The URL to fetch.\n * @param options The custom options for the request.\n */\n async fetch(url: string, options: HTTPFetchOptions = {}): Promise<HTTPResponse> {\n let useURL = url;\n if (options.qs) {\n useURL = urijs(url).query(options.qs).toString();\n }\n\n const fetchOptions: RequestInit = {\n method: (options.method || 'get').toUpperCase(),\n body: options.body as BodyInit,\n };\n\n let defaultHeaders: Record<string, string> | undefined;\n if (options.req) {\n defaultHeaders = this.getCustomHeadersFromRequest(options.req);\n const ip = this.getIPFromRequest(options.req);\n if (ip) {\n defaultHeaders['x-forwarded-for'] = ip;\n }\n }\n const headers = {\n ...defaultHeaders,\n ...options.headers,\n };\n\n if (Object.keys(headers).length) {\n fetchOptions.headers = this.normalizeHeaders(headers);\n }\n\n const { logRequests } = this._options;\n if (logRequests) {\n this._logRequest(useURL, fetchOptions);\n }\n\n const response = await fetch(useURL, fetchOptions);\n if (logRequests) {\n this._logResponse(response);\n }\n\n return response;\n }\n /**\n * Tries to get the IP address from a given request.\n *\n * @param req The request from which it will try to obtain the IP address.\n */\n getIPFromRequest(req: Request): string | undefined {\n const headerValue = req.headers['x-forwarded-for'];\n if (headerValue) {\n return String(headerValue);\n }\n\n return req?.connection?.remoteAddress || req?.socket?.remoteAddress;\n }\n /**\n * Creates a dictionary with all the custom headers a request has. By custom header it\n * means all the headers which name start with `x-`.\n *\n * @param req The request from which it will try to get the headers.\n * @param options The options to customize the behavior with certain headers.\n */\n getCustomHeadersFromRequest(\n req: Request,\n options: GetCustomHeadersFromRequestOptions = {},\n ): Record<string, string> {\n const { includeXForwardedHeaders = false } = options;\n return Object.keys(req.headers).reduce<Record<string, string>>((acc, headerName) => {\n if (\n headerName.startsWith('x-') &&\n (includeXForwardedHeaders || !headerName.startsWith('x-forwarded-'))\n ) {\n acc[headerName] = req.headers[headerName] as string;\n }\n return acc;\n }, {});\n }\n /**\n * It takes a dictionary of headers and normalize the names so each word will start with\n * an upper case character. This is helpful in case you added custom headers and didn't\n * care about the casing, or when copying headers from a server request, as they all\n * come tranformed into lower case.\n *\n * @param headers The dictionary of headers to normalize.\n */\n normalizeHeaders(headers: Record<string, string>): Record<string, string> {\n return Object.keys(headers).reduce<Record<string, string>>((acc, name) => {\n const newName = name\n .split('-')\n .map((part) => part.replace(/^(\\w)/, (_, letter) => letter.toUpperCase()))\n .join('-');\n\n acc[newName] = headers[name]!;\n return acc;\n }, {});\n }\n /**\n * The customization options.\n */\n get options(): Readonly<HTTPOptions> {\n return deepAssignWithOverwrite({}, this._options);\n }\n /**\n * Logs a request information into the terminal.\n *\n * @param url The request URL.\n * @param options The options for the request.\n */\n protected _logRequest(url: string, options: RequestInit): void {\n const { method, headers } = options;\n const prefix = 'REQUEST> ';\n const lines = ['--->>', `${prefix}${method} ${url}`];\n if (headers) {\n Object.keys(headers).forEach((header) => {\n const value = headers[header as keyof typeof headers];\n lines.push(`${prefix}${header}: ${value}`);\n });\n }\n\n if (options.body) {\n lines.push(`${prefix}body: \"${options.body}\"`);\n }\n\n this._logger.info(lines);\n }\n /**\n * Logs a response information into the terminal.\n *\n * @param response The response to log.\n */\n protected _logResponse(response: HTTPResponse) {\n const prefix = 'RESPONSE> ';\n const lines = [\n '<<---',\n `${prefix}${response.url}`,\n `${prefix}status: ${response.status}`,\n ];\n\n response.headers.forEach((value, header) => {\n lines.push(`${prefix}${header}: ${value}`);\n });\n\n this._logger.info(lines);\n }\n}\n/**\n * The service provider that once registered on the container will set an instance of\n * {@link HTTP} as the `http` service. The provider also checks the `debug.logRequests`\n * setting on the application configuration in order to enable or not the logging of\n * requests/responses.\n *\n * @example\n *\n * // Register it on the container\n * container.register(httpProvider);\n * // Getting access to the service instance\n * const http = container.get<HTTP>('http');\n *\n * @group Providers\n * @group Services/HTTP\n */\nexport const httpProvider = provider((app) => {\n app.set('http', () => {\n const config = app.getConfig();\n const logRequests = config.get<boolean | undefined>('debug.logRequests') === true;\n return new HTTP({\n inject: {\n logger: app.get('logger'),\n },\n logRequests,\n });\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAuD;AACvD,mBAAkB;AAClB,yBAAwC;AACxC,mBAAyB;AAmFlB,MAAM,KAAK;AAAA;AAAA;AAAA;AAAA,EAYhB,YAAY,EAAE,QAAQ,EAAE,OAAO,GAAG,GAAG,QAAQ,GAA0B;AARvE;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAmB;AAKjB,SAAK,UAAU;AACf,SAAK,eAAW;AAAA,MACd;AAAA,QACE,aAAa;AAAA,MACf;AAAA,MACA;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,MAAM,KAAa,UAA4B,CAAC,GAA0B;AAC9E,QAAI,SAAS;AACb,QAAI,QAAQ,IAAI;AACd,mBAAS,aAAAA,SAAM,GAAG,EAAE,MAAM,QAAQ,EAAE,EAAE,SAAS;AAAA,IACjD;AAEA,UAAM,eAA4B;AAAA,MAChC,SAAS,QAAQ,UAAU,OAAO,YAAY;AAAA,MAC9C,MAAM,QAAQ;AAAA,IAChB;AAEA,QAAI;AACJ,QAAI,QAAQ,KAAK;AACf,uBAAiB,KAAK,4BAA4B,QAAQ,GAAG;AAC7D,YAAM,KAAK,KAAK,iBAAiB,QAA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I,IAAI,QAAQ,MAAM;AACpB,UAAM,SAAS,IAAI,UAAU;AAC7B,UAAM,cAAc,OAAO,IAAyB,mBAAmB,MAAM;AAC7E,WAAO,IAAI,KAAK;AAAA,MACd,QAAQ;AAAA,QACN,QAAQ,IAAI,IAAI,QAAQ;AAAA,MAC1B;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH,CAAC;","names":["urijs","fetch"]}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import * as _homer0_jimple from '@homer0/jimple';
|
|
2
|
+
import { J as Jimpex } from '../../index-efeb437e.js';
|
|
3
|
+
export { ErrorResponse } from '@homer0/api-utils';
|
|
4
|
+
import { APIClientProviderOptions } from './apiClient.mjs';
|
|
5
|
+
export { APIClient, APIClientConfig, APIClientConstructorOptions, APIClientSettings, EndpointsType, apiClientProvider } from './apiClient.mjs';
|
|
6
|
+
export { GetCustomHeadersFromRequestOptions, HTTP, HTTPContructorOptions, HTTPFetchBody, HTTPFetchOptions, HTTPOptions, httpProvider } from './http.mjs';
|
|
7
|
+
export { HTMLPostMessageResponseOptions, JSONResponseOptions, ResponsesBuilder, ResponsesBuilderConstructorOptions, responsesBuilderProvider } from './responsesBuilder.mjs';
|
|
8
|
+
import '../../types/express.mjs';
|
|
9
|
+
import 'express';
|
|
10
|
+
import '../../types/http.mjs';
|
|
11
|
+
import 'https';
|
|
12
|
+
import 'http';
|
|
13
|
+
import 'spdy';
|
|
14
|
+
import 'node-fetch';
|
|
15
|
+
import '../../types/utils.mjs';
|
|
16
|
+
import '@homer0/path-utils';
|
|
17
|
+
import '@homer0/simple-logger';
|
|
18
|
+
import '@homer0/simple-config';
|
|
19
|
+
import '@homer0/events-hub';
|
|
20
|
+
import '../common/httpError.mjs';
|
|
21
|
+
import '../../utils/fns/statuses.mjs';
|
|
22
|
+
import 'statuses';
|
|
23
|
+
import '../common/appError.mjs';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Registers all the HTTP services on the container.
|
|
27
|
+
*
|
|
28
|
+
* - {@link APIClient | apiClient}
|
|
29
|
+
* - {@link HTTP | http}
|
|
30
|
+
* - {@link ResponsesBuilder | responsesBuilder}
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
*
|
|
34
|
+
* // Register the collection on the container
|
|
35
|
+
* container.register(httpServicesProvider);
|
|
36
|
+
* // Getting access to one the services instance
|
|
37
|
+
* const apiClient = container.get<APIClient>('apiClient');
|
|
38
|
+
*
|
|
39
|
+
* @group Providers
|
|
40
|
+
*/
|
|
41
|
+
declare const httpServicesProvider: {
|
|
42
|
+
apiClientProvider: _homer0_jimple.ResourceCreator<"provider", "register", (options?: APIClientProviderOptions) => (app: Jimpex) => void, _homer0_jimple.ProviderRegisterFn<Jimpex>>;
|
|
43
|
+
httpProvider: _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>;
|
|
44
|
+
responsesBuilderProvider: _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>;
|
|
45
|
+
} & Record<string, _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>> & {
|
|
46
|
+
provider: true;
|
|
47
|
+
} & {
|
|
48
|
+
register: _homer0_jimple.ProviderRegisterFn<Jimpex>;
|
|
49
|
+
} & Record<string, unknown>;
|
|
50
|
+
|
|
51
|
+
export { APIClientProviderOptions, httpServicesProvider };
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import * as _homer0_jimple from '@homer0/jimple';
|
|
2
|
-
import { J as Jimpex } from '../../
|
|
2
|
+
import { J as Jimpex } from '../../index-b2a04c78.js';
|
|
3
3
|
export { ErrorResponse } from '@homer0/api-utils';
|
|
4
4
|
import { APIClientProviderOptions } from './apiClient.js';
|
|
5
5
|
export { APIClient, APIClientConfig, APIClientConstructorOptions, APIClientSettings, EndpointsType, apiClientProvider } from './apiClient.js';
|
|
6
6
|
export { GetCustomHeadersFromRequestOptions, HTTP, HTTPContructorOptions, HTTPFetchBody, HTTPFetchOptions, HTTPOptions, httpProvider } from './http.js';
|
|
7
7
|
export { HTMLPostMessageResponseOptions, JSONResponseOptions, ResponsesBuilder, ResponsesBuilderConstructorOptions, responsesBuilderProvider } from './responsesBuilder.js';
|
|
8
|
-
import '@homer0/events-hub';
|
|
9
8
|
import '../../types/express.js';
|
|
10
9
|
import 'express';
|
|
11
10
|
import '../../types/http.js';
|
|
@@ -13,9 +12,11 @@ import 'https';
|
|
|
13
12
|
import 'http';
|
|
14
13
|
import 'spdy';
|
|
15
14
|
import 'node-fetch';
|
|
16
|
-
import '@homer0/simple-config';
|
|
17
15
|
import '../../types/utils.js';
|
|
16
|
+
import '@homer0/path-utils';
|
|
18
17
|
import '@homer0/simple-logger';
|
|
18
|
+
import '@homer0/simple-config';
|
|
19
|
+
import '@homer0/events-hub';
|
|
19
20
|
import '../common/httpError.js';
|
|
20
21
|
import '../../utils/fns/statuses.js';
|
|
21
22
|
import 'statuses';
|
|
@@ -36,6 +36,9 @@ const httpServicesProvider = (0, import_utils.providers)({
|
|
|
36
36
|
});
|
|
37
37
|
// Annotate the CommonJS export names for ESM import in node:
|
|
38
38
|
0 && (module.exports = {
|
|
39
|
-
httpServicesProvider
|
|
39
|
+
httpServicesProvider,
|
|
40
|
+
...require("./apiClient"),
|
|
41
|
+
...require("./http"),
|
|
42
|
+
...require("./responsesBuilder")
|
|
40
43
|
});
|
|
41
44
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import * as _homer0_jimple from '@homer0/jimple';
|
|
2
|
+
import { J as Jimpex } from '../../index-efeb437e.js';
|
|
3
|
+
import { Response } from 'express';
|
|
4
|
+
import { Statuses } from '../../utils/fns/statuses.mjs';
|
|
5
|
+
import { SimpleConfig } from '@homer0/simple-config';
|
|
6
|
+
import '../../types/express.mjs';
|
|
7
|
+
import '../../types/http.mjs';
|
|
8
|
+
import 'https';
|
|
9
|
+
import 'http';
|
|
10
|
+
import 'spdy';
|
|
11
|
+
import 'node-fetch';
|
|
12
|
+
import '../../types/utils.mjs';
|
|
13
|
+
import '@homer0/path-utils';
|
|
14
|
+
import '@homer0/simple-logger';
|
|
15
|
+
import '@homer0/events-hub';
|
|
16
|
+
import 'statuses';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The options to construct a {@link ResponsesBuilder}.
|
|
20
|
+
*
|
|
21
|
+
* @group Services/ResponsesBuilder
|
|
22
|
+
*/
|
|
23
|
+
type ResponsesBuilderConstructorOptions = {
|
|
24
|
+
/**
|
|
25
|
+
* A dictionary with the dependencies to inject.
|
|
26
|
+
*/
|
|
27
|
+
inject: {
|
|
28
|
+
config: SimpleConfig;
|
|
29
|
+
statuses: Statuses;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* The options to build a response for a post message.
|
|
34
|
+
*
|
|
35
|
+
* @group Services/ResponsesBuilder
|
|
36
|
+
*/
|
|
37
|
+
type HTMLPostMessageResponseOptions = {
|
|
38
|
+
/**
|
|
39
|
+
* The response object generated by the application.
|
|
40
|
+
*/
|
|
41
|
+
res: Response;
|
|
42
|
+
/**
|
|
43
|
+
* The title for the HTML.
|
|
44
|
+
*/
|
|
45
|
+
title: string;
|
|
46
|
+
/**
|
|
47
|
+
* The contents of the post message.
|
|
48
|
+
*/
|
|
49
|
+
message: string;
|
|
50
|
+
/**
|
|
51
|
+
* The status code for the response.
|
|
52
|
+
*
|
|
53
|
+
* @default 200
|
|
54
|
+
*/
|
|
55
|
+
status?: number | string;
|
|
56
|
+
/**
|
|
57
|
+
* From which object will the `postMessage` method called from.
|
|
58
|
+
*
|
|
59
|
+
* @default 'window.opener'
|
|
60
|
+
*/
|
|
61
|
+
target?: string;
|
|
62
|
+
/**
|
|
63
|
+
* Whether or not to call `window.close` after sending the message.
|
|
64
|
+
*
|
|
65
|
+
* @default true
|
|
66
|
+
*/
|
|
67
|
+
close?: boolean;
|
|
68
|
+
/**
|
|
69
|
+
* In case `close` is set to `true`, this option is to specify how many milliseconds
|
|
70
|
+
* should be waited before closing the window.
|
|
71
|
+
*
|
|
72
|
+
* @default 700
|
|
73
|
+
*/
|
|
74
|
+
closeDelay?: number;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* The options to build a reponse for JSON.
|
|
78
|
+
*
|
|
79
|
+
* @group Services/ResponsesBuilder
|
|
80
|
+
*/
|
|
81
|
+
type JSONResponseOptions = {
|
|
82
|
+
/**
|
|
83
|
+
* The response object generated by the application.
|
|
84
|
+
*/
|
|
85
|
+
res: Response;
|
|
86
|
+
/**
|
|
87
|
+
* The actual data for the response. It will be added in a `data` property.
|
|
88
|
+
*/
|
|
89
|
+
data: unknown;
|
|
90
|
+
/**
|
|
91
|
+
* The status code for the response.
|
|
92
|
+
*
|
|
93
|
+
* @default 200
|
|
94
|
+
*/
|
|
95
|
+
status?: number | string;
|
|
96
|
+
/**
|
|
97
|
+
* Extra information to include inside the `metadata` object.
|
|
98
|
+
*/
|
|
99
|
+
metadata?: object;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* A utility service to build responses.
|
|
103
|
+
*
|
|
104
|
+
* @group Services
|
|
105
|
+
* @group Services/ResponsesBuilder
|
|
106
|
+
*/
|
|
107
|
+
declare class ResponsesBuilder {
|
|
108
|
+
/**
|
|
109
|
+
* The application configuration, to get the `version` and the `postMessagesPrefix`.
|
|
110
|
+
*/
|
|
111
|
+
protected readonly _config: SimpleConfig;
|
|
112
|
+
/**
|
|
113
|
+
* The uility service to get HTTP status codes.
|
|
114
|
+
*/
|
|
115
|
+
protected readonly _statuses: Statuses;
|
|
116
|
+
/**
|
|
117
|
+
* @param options The options to construct the service.
|
|
118
|
+
*/
|
|
119
|
+
constructor({ inject: { config, statuses } }: ResponsesBuilderConstructorOptions);
|
|
120
|
+
/**
|
|
121
|
+
* Generates and send an HTML response that emits a post message.
|
|
122
|
+
* The post message will be prefixed with the value of the configuration setting
|
|
123
|
+
* `postMessagesPrefix`.
|
|
124
|
+
*
|
|
125
|
+
* @param options The options to customize how the HTML is generated.
|
|
126
|
+
*/
|
|
127
|
+
htmlPostMessage(options: HTMLPostMessageResponseOptions): void;
|
|
128
|
+
/**
|
|
129
|
+
* Generates and sends a JSON response.
|
|
130
|
+
*
|
|
131
|
+
* @param options The options to customize how the JSON is generated.
|
|
132
|
+
* @example
|
|
133
|
+
*
|
|
134
|
+
* <caption>The generated looks like this.</caption>
|
|
135
|
+
*
|
|
136
|
+
* {
|
|
137
|
+
* metadata: {
|
|
138
|
+
* version: 'dev',
|
|
139
|
+
* status: 200,
|
|
140
|
+
* },
|
|
141
|
+
* data: { foo: 'bar' },
|
|
142
|
+
* }
|
|
143
|
+
*
|
|
144
|
+
*/
|
|
145
|
+
json(options: JSONResponseOptions): void;
|
|
146
|
+
/**
|
|
147
|
+
* Generates a basic HTML template for the service to use when generating a post message
|
|
148
|
+
* response.
|
|
149
|
+
*
|
|
150
|
+
* @param title The HTML `<title />` attribute.
|
|
151
|
+
* @param code Javascript code to be wrapped on a `<script />` tag.
|
|
152
|
+
*/
|
|
153
|
+
protected _htmlTemplate(title: string, code: string): string;
|
|
154
|
+
/**
|
|
155
|
+
* Utility method used to make sure a recevied status is a valid status code. If the
|
|
156
|
+
* status is a string, the method will try to find the code from the `statuses` package.
|
|
157
|
+
*
|
|
158
|
+
* @param status The status to normalize.
|
|
159
|
+
* @returns If `status` is a string, but there's no valid code, it will return 200.
|
|
160
|
+
*/
|
|
161
|
+
protected _normalizeStatus(status: number | string): number;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* The service provider that once registered on the container will set an instance of
|
|
165
|
+
* {@link ResponsesBuilder} as the `responsesBuilder` service.
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
*
|
|
169
|
+
* // Register it on the container
|
|
170
|
+
* container.register(responsesBuilderProvider);
|
|
171
|
+
* // Getting access to the service instance
|
|
172
|
+
* const responsesBuilder = container.get<ResponsesBuilder>('responsesBuilder');
|
|
173
|
+
*
|
|
174
|
+
* @group Providers
|
|
175
|
+
* @group Services/ResponsesBuilder
|
|
176
|
+
*/
|
|
177
|
+
declare const responsesBuilderProvider: _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>;
|
|
178
|
+
|
|
179
|
+
export { HTMLPostMessageResponseOptions, JSONResponseOptions, ResponsesBuilder, ResponsesBuilderConstructorOptions, responsesBuilderProvider };
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import * as _homer0_jimple from '@homer0/jimple';
|
|
2
|
-
import { J as Jimpex } from '../../
|
|
2
|
+
import { J as Jimpex } from '../../index-b2a04c78.js';
|
|
3
3
|
import { Response } from 'express';
|
|
4
4
|
import { Statuses } from '../../utils/fns/statuses.js';
|
|
5
5
|
import { SimpleConfig } from '@homer0/simple-config';
|
|
6
|
-
import '@homer0/events-hub';
|
|
7
6
|
import '../../types/express.js';
|
|
8
7
|
import '../../types/http.js';
|
|
9
8
|
import 'https';
|
|
@@ -11,7 +10,9 @@ import 'http';
|
|
|
11
10
|
import 'spdy';
|
|
12
11
|
import 'node-fetch';
|
|
13
12
|
import '../../types/utils.js';
|
|
13
|
+
import '@homer0/path-utils';
|
|
14
14
|
import '@homer0/simple-logger';
|
|
15
|
+
import '@homer0/events-hub';
|
|
15
16
|
import 'statuses';
|
|
16
17
|
|
|
17
18
|
/**
|
|
@@ -30,12 +30,28 @@ module.exports = __toCommonJS(responsesBuilder_exports);
|
|
|
30
30
|
var import_utils = require("../../utils");
|
|
31
31
|
const DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE = 700;
|
|
32
32
|
class ResponsesBuilder {
|
|
33
|
+
/**
|
|
34
|
+
* @param options The options to construct the service.
|
|
35
|
+
*/
|
|
33
36
|
constructor({ inject: { config, statuses } }) {
|
|
37
|
+
/**
|
|
38
|
+
* The application configuration, to get the `version` and the `postMessagesPrefix`.
|
|
39
|
+
*/
|
|
34
40
|
__publicField(this, "_config");
|
|
41
|
+
/**
|
|
42
|
+
* The uility service to get HTTP status codes.
|
|
43
|
+
*/
|
|
35
44
|
__publicField(this, "_statuses");
|
|
36
45
|
this._config = config;
|
|
37
46
|
this._statuses = statuses;
|
|
38
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Generates and send an HTML response that emits a post message.
|
|
50
|
+
* The post message will be prefixed with the value of the configuration setting
|
|
51
|
+
* `postMessagesPrefix`.
|
|
52
|
+
*
|
|
53
|
+
* @param options The options to customize how the HTML is generated.
|
|
54
|
+
*/
|
|
39
55
|
htmlPostMessage(options) {
|
|
40
56
|
const {
|
|
41
57
|
res,
|
|
@@ -66,6 +82,23 @@ class ResponsesBuilder {
|
|
|
66
82
|
res.write(html);
|
|
67
83
|
res.end();
|
|
68
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* Generates and sends a JSON response.
|
|
87
|
+
*
|
|
88
|
+
* @param options The options to customize how the JSON is generated.
|
|
89
|
+
* @example
|
|
90
|
+
*
|
|
91
|
+
* <caption>The generated looks like this.</caption>
|
|
92
|
+
*
|
|
93
|
+
* {
|
|
94
|
+
* metadata: {
|
|
95
|
+
* version: 'dev',
|
|
96
|
+
* status: 200,
|
|
97
|
+
* },
|
|
98
|
+
* data: { foo: 'bar' },
|
|
99
|
+
* }
|
|
100
|
+
*
|
|
101
|
+
*/
|
|
69
102
|
json(options) {
|
|
70
103
|
const { res, data, status, metadata = {} } = options;
|
|
71
104
|
const useStatus = typeof status === "undefined" ? this._statuses("ok") : this._normalizeStatus(status);
|
|
@@ -80,6 +113,13 @@ class ResponsesBuilder {
|
|
|
80
113
|
});
|
|
81
114
|
res.end();
|
|
82
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Generates a basic HTML template for the service to use when generating a post message
|
|
118
|
+
* response.
|
|
119
|
+
*
|
|
120
|
+
* @param title The HTML `<title />` attribute.
|
|
121
|
+
* @param code Javascript code to be wrapped on a `<script />` tag.
|
|
122
|
+
*/
|
|
83
123
|
_htmlTemplate(title, code) {
|
|
84
124
|
return `
|
|
85
125
|
<!DOCTYPE html>
|
|
@@ -93,11 +133,18 @@ class ResponsesBuilder {
|
|
|
93
133
|
<body>
|
|
94
134
|
<script type="text/javascript">
|
|
95
135
|
${code}
|
|
96
|
-
|
|
136
|
+
</script>
|
|
97
137
|
</body>
|
|
98
138
|
</html>
|
|
99
139
|
`;
|
|
100
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* Utility method used to make sure a recevied status is a valid status code. If the
|
|
143
|
+
* status is a string, the method will try to find the code from the `statuses` package.
|
|
144
|
+
*
|
|
145
|
+
* @param status The status to normalize.
|
|
146
|
+
* @returns If `status` is a string, but there's no valid code, it will return 200.
|
|
147
|
+
*/
|
|
101
148
|
_normalizeStatus(status) {
|
|
102
149
|
let useStatus;
|
|
103
150
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/http/responsesBuilder.ts"],"sourcesContent":["import type { Config, Response } from '../../types';\nimport { provider, type Statuses } from '../../utils';\n/**\n * The options to construct a {@link ResponsesBuilder}.\n *\n * @group Services/ResponsesBuilder\n */\nexport type ResponsesBuilderConstructorOptions = {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n config: Config;\n statuses: Statuses;\n };\n};\n/**\n * The options to build a response for a post message.\n *\n * @group Services/ResponsesBuilder\n */\nexport type HTMLPostMessageResponseOptions = {\n /**\n * The response object generated by the application.\n */\n res: Response;\n /**\n * The title for the HTML.\n */\n title: string;\n /**\n * The contents of the post message.\n */\n message: string;\n /**\n * The status code for the response.\n *\n * @default 200\n */\n status?: number | string;\n /**\n * From which object will the `postMessage` method called from.\n *\n * @default 'window.opener'\n */\n target?: string;\n /**\n * Whether or not to call `window.close` after sending the message.\n *\n * @default true\n */\n close?: boolean;\n /**\n * In case `close` is set to `true`, this option is to specify how many milliseconds\n * should be waited before closing the window.\n *\n * @default 700\n */\n closeDelay?: number;\n};\n/**\n * The options to build a reponse for JSON.\n *\n * @group Services/ResponsesBuilder\n */\nexport type JSONResponseOptions = {\n /**\n * The response object generated by the application.\n */\n res: Response;\n /**\n * The actual data for the response. It will be added in a `data` property.\n */\n data: unknown;\n /**\n * The status code for the response.\n *\n * @default 200\n */\n status?: number | string;\n /**\n * Extra information to include inside the `metadata` object.\n */\n metadata?: object;\n};\n/**\n * The default time to wait before closing a window, in case it's enabled.\n */\nconst DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE = 700;\n/**\n * A utility service to build responses.\n *\n * @group Services\n * @group Services/ResponsesBuilder\n */\nexport class ResponsesBuilder {\n /**\n * The application configuration, to get the `version` and the `postMessagesPrefix`.\n */\n protected readonly _config: Config;\n /**\n * The uility service to get HTTP status codes.\n */\n protected readonly _statuses: Statuses;\n /**\n * @param options The options to construct the service.\n */\n constructor({ inject: { config, statuses } }: ResponsesBuilderConstructorOptions) {\n this._config = config;\n this._statuses = statuses;\n }\n /**\n * Generates and send an HTML response that emits a post message.\n * The post message will be prefixed with the value of the configuration setting\n * `postMessagesPrefix`.\n *\n * @param options The options to customize how the HTML is generated.\n */\n htmlPostMessage(options: HTMLPostMessageResponseOptions): void {\n const {\n res,\n title,\n message,\n status,\n target = 'window.opener',\n close = true,\n closeDelay = DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE,\n } = options;\n const prefix = this._config.get<string | undefined>('postMessagesPrefix') ?? '';\n const closeCode = close\n ? `setTimeout(function() { window.close(); }, ${closeDelay});`\n : '';\n\n const html = this._htmlTemplate(\n title,\n `\n (function() {\n if (${target}) {\n ${target}.postMessage('${prefix}${message}', '*');\n ${closeCode}\n }\n })();\n `,\n );\n\n const useStatus =\n typeof status === 'undefined'\n ? (this._statuses('ok') as number)\n : this._normalizeStatus(status);\n\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store');\n res.status(useStatus);\n res.write(html);\n res.end();\n }\n /**\n * Generates and sends a JSON response.\n *\n * @param options The options to customize how the JSON is generated.\n * @example\n *\n * <caption>The generated looks like this.</caption>\n *\n * {\n * metadata: {\n * version: 'dev',\n * status: 200,\n * },\n * data: { foo: 'bar' },\n * }\n *\n */\n json(options: JSONResponseOptions): void {\n const { res, data, status, metadata = {} } = options;\n const useStatus =\n typeof status === 'undefined'\n ? (this._statuses('ok') as number)\n : this._normalizeStatus(status);\n\n res.status(useStatus);\n res.json({\n metadata: {\n version: this._config.get<string>('version'),\n status: useStatus,\n ...metadata,\n },\n data,\n });\n res.end();\n }\n /**\n * Generates a basic HTML template for the service to use when generating a post message\n * response.\n *\n * @param title The HTML `<title />` attribute.\n * @param code Javascript code to be wrapped on a `<script />` tag.\n */\n protected _htmlTemplate(title: string, code: string): string {\n return `\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\" />\n <meta http-equiv=\"x-ua-compatible\" content=\"ie=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${title}</title>\n </head>\n <body>\n <script type=\"text/javascript\">\n ${code}\n </script>\n </body>\n </html>\n `;\n }\n /**\n * Utility method used to make sure a recevied status is a valid status code. If the\n * status is a string, the method will try to find the code from the `statuses` package.\n *\n * @param status The status to normalize.\n * @returns If `status` is a string, but there's no valid code, it will return 200.\n */\n protected _normalizeStatus(status: number | string): number {\n let useStatus: number;\n try {\n if (typeof status === 'string') {\n useStatus = this._statuses(status) as number;\n } else {\n this._statuses(status);\n useStatus = status;\n }\n } catch (_) {\n useStatus = this._statuses('ok') as number;\n }\n\n return useStatus;\n }\n}\n/**\n * The service provider that once registered on the container will set an instance of\n * {@link ResponsesBuilder} as the `responsesBuilder` service.\n *\n * @example\n *\n * // Register it on the container\n * container.register(responsesBuilderProvider);\n * // Getting access to the service instance\n * const responsesBuilder = container.get<ResponsesBuilder>('responsesBuilder');\n *\n * @group Providers\n * @group Services/ResponsesBuilder\n */\nexport const responsesBuilderProvider = provider((app) => {\n app.set(\n 'responsesBuilder',\n () =>\n new ResponsesBuilder({\n inject: {\n config: app.getConfig(),\n statuses: app.get('statuses'),\n },\n }),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAwC;AAuFxC,MAAM,uCAAuC;AAOtC,MAAM,iBAAiB;AAAA,EAY5B,YAAY,EAAE,QAAQ,EAAE,QAAQ,SAAS,EAAE,GAAuC;AARlF,wBAAmB;AAInB,wBAAmB;AAKjB,SAAK,UAAU;AACf,SAAK,YAAY;AAAA,EACnB;AAAA,EAQA,gBAAgB,SAA+C;AAC7D,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,aAAa;AAAA,IACf,IAAI;AACJ,UAAM,SAAS,KAAK,QAAQ,IAAwB,oBAAoB,KAAK;AAC7E,UAAM,YAAY,QACd,8CAA8C,
|
|
1
|
+
{"version":3,"sources":["../../../src/services/http/responsesBuilder.ts"],"sourcesContent":["import type { Config, Response } from '../../types';\nimport { provider, type Statuses } from '../../utils';\n/**\n * The options to construct a {@link ResponsesBuilder}.\n *\n * @group Services/ResponsesBuilder\n */\nexport type ResponsesBuilderConstructorOptions = {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n config: Config;\n statuses: Statuses;\n };\n};\n/**\n * The options to build a response for a post message.\n *\n * @group Services/ResponsesBuilder\n */\nexport type HTMLPostMessageResponseOptions = {\n /**\n * The response object generated by the application.\n */\n res: Response;\n /**\n * The title for the HTML.\n */\n title: string;\n /**\n * The contents of the post message.\n */\n message: string;\n /**\n * The status code for the response.\n *\n * @default 200\n */\n status?: number | string;\n /**\n * From which object will the `postMessage` method called from.\n *\n * @default 'window.opener'\n */\n target?: string;\n /**\n * Whether or not to call `window.close` after sending the message.\n *\n * @default true\n */\n close?: boolean;\n /**\n * In case `close` is set to `true`, this option is to specify how many milliseconds\n * should be waited before closing the window.\n *\n * @default 700\n */\n closeDelay?: number;\n};\n/**\n * The options to build a reponse for JSON.\n *\n * @group Services/ResponsesBuilder\n */\nexport type JSONResponseOptions = {\n /**\n * The response object generated by the application.\n */\n res: Response;\n /**\n * The actual data for the response. It will be added in a `data` property.\n */\n data: unknown;\n /**\n * The status code for the response.\n *\n * @default 200\n */\n status?: number | string;\n /**\n * Extra information to include inside the `metadata` object.\n */\n metadata?: object;\n};\n/**\n * The default time to wait before closing a window, in case it's enabled.\n */\nconst DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE = 700;\n/**\n * A utility service to build responses.\n *\n * @group Services\n * @group Services/ResponsesBuilder\n */\nexport class ResponsesBuilder {\n /**\n * The application configuration, to get the `version` and the `postMessagesPrefix`.\n */\n protected readonly _config: Config;\n /**\n * The uility service to get HTTP status codes.\n */\n protected readonly _statuses: Statuses;\n /**\n * @param options The options to construct the service.\n */\n constructor({ inject: { config, statuses } }: ResponsesBuilderConstructorOptions) {\n this._config = config;\n this._statuses = statuses;\n }\n /**\n * Generates and send an HTML response that emits a post message.\n * The post message will be prefixed with the value of the configuration setting\n * `postMessagesPrefix`.\n *\n * @param options The options to customize how the HTML is generated.\n */\n htmlPostMessage(options: HTMLPostMessageResponseOptions): void {\n const {\n res,\n title,\n message,\n status,\n target = 'window.opener',\n close = true,\n closeDelay = DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE,\n } = options;\n const prefix = this._config.get<string | undefined>('postMessagesPrefix') ?? '';\n const closeCode = close\n ? `setTimeout(function() { window.close(); }, ${closeDelay});`\n : '';\n\n const html = this._htmlTemplate(\n title,\n `\n (function() {\n if (${target}) {\n ${target}.postMessage('${prefix}${message}', '*');\n ${closeCode}\n }\n })();\n `,\n );\n\n const useStatus =\n typeof status === 'undefined'\n ? (this._statuses('ok') as number)\n : this._normalizeStatus(status);\n\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store');\n res.status(useStatus);\n res.write(html);\n res.end();\n }\n /**\n * Generates and sends a JSON response.\n *\n * @param options The options to customize how the JSON is generated.\n * @example\n *\n * <caption>The generated looks like this.</caption>\n *\n * {\n * metadata: {\n * version: 'dev',\n * status: 200,\n * },\n * data: { foo: 'bar' },\n * }\n *\n */\n json(options: JSONResponseOptions): void {\n const { res, data, status, metadata = {} } = options;\n const useStatus =\n typeof status === 'undefined'\n ? (this._statuses('ok') as number)\n : this._normalizeStatus(status);\n\n res.status(useStatus);\n res.json({\n metadata: {\n version: this._config.get<string>('version'),\n status: useStatus,\n ...metadata,\n },\n data,\n });\n res.end();\n }\n /**\n * Generates a basic HTML template for the service to use when generating a post message\n * response.\n *\n * @param title The HTML `<title />` attribute.\n * @param code Javascript code to be wrapped on a `<script />` tag.\n */\n protected _htmlTemplate(title: string, code: string): string {\n return `\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\" />\n <meta http-equiv=\"x-ua-compatible\" content=\"ie=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${title}</title>\n </head>\n <body>\n <script type=\"text/javascript\">\n ${code}\n </script>\n </body>\n </html>\n `;\n }\n /**\n * Utility method used to make sure a recevied status is a valid status code. If the\n * status is a string, the method will try to find the code from the `statuses` package.\n *\n * @param status The status to normalize.\n * @returns If `status` is a string, but there's no valid code, it will return 200.\n */\n protected _normalizeStatus(status: number | string): number {\n let useStatus: number;\n try {\n if (typeof status === 'string') {\n useStatus = this._statuses(status) as number;\n } else {\n this._statuses(status);\n useStatus = status;\n }\n } catch (_) {\n useStatus = this._statuses('ok') as number;\n }\n\n return useStatus;\n }\n}\n/**\n * The service provider that once registered on the container will set an instance of\n * {@link ResponsesBuilder} as the `responsesBuilder` service.\n *\n * @example\n *\n * // Register it on the container\n * container.register(responsesBuilderProvider);\n * // Getting access to the service instance\n * const responsesBuilder = container.get<ResponsesBuilder>('responsesBuilder');\n *\n * @group Providers\n * @group Services/ResponsesBuilder\n */\nexport const responsesBuilderProvider = provider((app) => {\n app.set(\n 'responsesBuilder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AAE,KAAK,MAAM,QAAQ,WAAW,CAAC,EAAE,IAAI;AAC7C,UAAM,YACJ,OAAO,WAAW,cACb,KAAK,UAAU,IAAI,IACpB,KAAK,iBAAiB,MAAM;AAElC,QAAI,OAAO,SAAS;AACpB,QAAI,KAAK;AAAA,MACP,UAAU;AAAA,QACR,SAAS,KAAK,QAAQ,IAAY,SAAS;AAAA,QAC3C,QAAQ;AAAA,QACR,GAAG;AAAA,MACL;AAAA,MACA;AAAA,IACF,CAAC;AACD,QAAI,IAAI;AAAA,EACV;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQU,cAAc,OAAe,MAAsB;AAC3D,WAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAOQ,KAAK;AAAA;AAAA;AAAA;AAAA,YAIZ,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA,EAKd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQU,iBAAiB,QAAiC;AAC1D,QAAI;AACJ,QAAI;AACF,UAAI,OAAO,WAAW,UAAU;AAC9B,oBAAY,KAAK,UAAU,MAAM;AAAA,MACnC,OAAO;AACL,aAAK,UAAU,MAAM;AACrB,oBAAY;AAAA,MACd;AAAA,IACF,SAAS,GAAG;AACV,kBAAY,KAAK,UAAU,IAAI;AAAA,IACjC;AAEA,WAAO;AAAA,EACT;AACF;AAeO,MAAM,+BAA2B,uBAAS,CAAC,QAAQ;AACxD,MAAI;AAAA,IACF;AAAA,IACA,MACE,IAAI,iBAAiB;AAAA,MACnB,QAAQ;AAAA,QACN,QAAQ,IAAI,UAAU;AAAA,QACtB,UAAU,IAAI,IAAI,UAAU;AAAA,MAC9B;AAAA,IACF,CAAC;AAAA,EACL;AACF,CAAC;","names":[]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export { commonServicesProvider } from './common/index.mjs';
|
|
2
|
+
export { frontendServicesProvider } from './frontend/index.mjs';
|
|
3
|
+
export { htmlServicesProvider } from './html/index.mjs';
|
|
4
|
+
export { httpServicesProvider } from './http/index.mjs';
|
|
5
|
+
export { utilsServicesProvider } from './utils/index.mjs';
|
|
6
|
+
export { AppError, AppErrorClass, AppErrorContext, CreateAppErrorFn, appErrorProvider, createAppError } from './common/appError.mjs';
|
|
7
|
+
export { CreateHTTPErrorFn, HTTPError, HTTPErrorClass, createHTTPError, httpErrorProvider } from './common/httpError.mjs';
|
|
8
|
+
export { SendFile, SendFileGeneratorOptions, SendFileOptions, sendFile, sendFileProvider } from './common/sendFile.mjs';
|
|
9
|
+
export { FrontendFs, FrontendFsOptions, frontendFsProvider } from './frontend/frontendFs.mjs';
|
|
10
|
+
export { HTMLGenerator, HTMLGeneratorConstructorOptions, HTMLGeneratorOptions, HTMLGeneratorProviderOptions, HTMLGeneratorValuesService, htmlGeneratorProvider } from './html/htmlGenerator.mjs';
|
|
11
|
+
export { ErrorResponse } from '@homer0/api-utils';
|
|
12
|
+
export { APIClient, APIClientConfig, APIClientConstructorOptions, APIClientProviderOptions, APIClientSettings, EndpointsType, apiClientProvider } from './http/apiClient.mjs';
|
|
13
|
+
export { GetCustomHeadersFromRequestOptions, HTTP, HTTPContructorOptions, HTTPFetchBody, HTTPFetchOptions, HTTPOptions, httpProvider } from './http/http.mjs';
|
|
14
|
+
export { HTMLPostMessageResponseOptions, JSONResponseOptions, ResponsesBuilder, ResponsesBuilderConstructorOptions, responsesBuilderProvider } from './http/responsesBuilder.mjs';
|
|
15
|
+
export { EnsureBearerConstructorOptions, EnsureBearerToken, EnsureBearerTokenErrorOptions, EnsureBearerTokenOptions, EnsureBearerTokenProviderOptions, ensureBearerTokenProvider } from './utils/ensureBearerToken.mjs';
|
|
16
|
+
import '@homer0/jimple';
|
|
17
|
+
import '../index-efeb437e.js';
|
|
18
|
+
import '../types/express.mjs';
|
|
19
|
+
import 'express';
|
|
20
|
+
import '../types/http.mjs';
|
|
21
|
+
import 'https';
|
|
22
|
+
import 'http';
|
|
23
|
+
import 'spdy';
|
|
24
|
+
import 'node-fetch';
|
|
25
|
+
import '../types/utils.mjs';
|
|
26
|
+
import '@homer0/path-utils';
|
|
27
|
+
import '@homer0/simple-logger';
|
|
28
|
+
import '@homer0/simple-config';
|
|
29
|
+
import '@homer0/events-hub';
|
|
30
|
+
import '../utils/fns/statuses.mjs';
|
|
31
|
+
import 'statuses';
|
|
32
|
+
import 'fs/promises';
|
|
33
|
+
import '@homer0/deferred';
|
package/dist/services/index.d.ts
CHANGED
|
@@ -14,8 +14,7 @@ export { GetCustomHeadersFromRequestOptions, HTTP, HTTPContructorOptions, HTTPFe
|
|
|
14
14
|
export { HTMLPostMessageResponseOptions, JSONResponseOptions, ResponsesBuilder, ResponsesBuilderConstructorOptions, responsesBuilderProvider } from './http/responsesBuilder.js';
|
|
15
15
|
export { EnsureBearerConstructorOptions, EnsureBearerToken, EnsureBearerTokenErrorOptions, EnsureBearerTokenOptions, EnsureBearerTokenProviderOptions, ensureBearerTokenProvider } from './utils/ensureBearerToken.js';
|
|
16
16
|
import '@homer0/jimple';
|
|
17
|
-
import '../
|
|
18
|
-
import '@homer0/events-hub';
|
|
17
|
+
import '../index-b2a04c78.js';
|
|
19
18
|
import '../types/express.js';
|
|
20
19
|
import 'express';
|
|
21
20
|
import '../types/http.js';
|
|
@@ -23,11 +22,12 @@ import 'https';
|
|
|
23
22
|
import 'http';
|
|
24
23
|
import 'spdy';
|
|
25
24
|
import 'node-fetch';
|
|
26
|
-
import '@homer0/simple-config';
|
|
27
25
|
import '../types/utils.js';
|
|
26
|
+
import '@homer0/path-utils';
|
|
28
27
|
import '@homer0/simple-logger';
|
|
28
|
+
import '@homer0/simple-config';
|
|
29
|
+
import '@homer0/events-hub';
|
|
29
30
|
import '../utils/fns/statuses.js';
|
|
30
31
|
import 'statuses';
|
|
31
|
-
import '@homer0/path-utils';
|
|
32
32
|
import 'fs/promises';
|
|
33
33
|
import '@homer0/deferred';
|