@webpieces/http-server 0.3.316 → 0.3.320
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/package.json +5 -5
- package/src/WebpiecesMiddleware.d.ts +14 -1
- package/src/WebpiecesMiddleware.js +24 -10
- package/src/WebpiecesMiddleware.js.map +1 -1
- package/src/filters/LogApiFilter.d.ts +0 -2
- package/src/filters/LogApiFilter.js +3 -10
- package/src/filters/LogApiFilter.js.map +1 -1
- package/src/filters/RecordingFilter.d.ts +0 -1
- package/src/filters/RecordingFilter.js +1 -2
- package/src/filters/RecordingFilter.js.map +1 -1
- package/src/headers/WebpiecesCoreHeaders.d.ts +1 -1
- package/src/headers/WebpiecesCoreHeaders.js +1 -1
- package/src/headers/WebpiecesCoreHeaders.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/http-server",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.320",
|
|
4
4
|
"description": "WebPieces server with filter chain and dependency injection",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -22,10 +22,10 @@
|
|
|
22
22
|
"access": "public"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@webpieces/core-context": "0.3.
|
|
26
|
-
"@webpieces/core-util": "0.3.
|
|
27
|
-
"@webpieces/gcp-identity": "0.3.
|
|
28
|
-
"@webpieces/http-routing": "0.3.
|
|
25
|
+
"@webpieces/core-context": "0.3.320",
|
|
26
|
+
"@webpieces/core-util": "0.3.320",
|
|
27
|
+
"@webpieces/gcp-identity": "0.3.320",
|
|
28
|
+
"@webpieces/http-routing": "0.3.320",
|
|
29
29
|
"cors": "2.8.5",
|
|
30
30
|
"express": "5.1.0",
|
|
31
31
|
"inversify": "7.10.4"
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Request, Response, NextFunction, RequestHandler } from 'express';
|
|
2
|
+
import { RequestContextHeaders } from '@webpieces/core-context';
|
|
2
3
|
/**
|
|
3
4
|
* Express route handler function type. Lives in http-server (the express adapter),
|
|
4
5
|
* NOT in the node-only http-routing package, so http-routing stays express-free.
|
|
@@ -8,7 +9,11 @@ export type ExpressRouteHandler = (req: Request, res: Response, next: NextFuncti
|
|
|
8
9
|
export declare class ExpressWrapper {
|
|
9
10
|
private clientMethod;
|
|
10
11
|
private path;
|
|
11
|
-
|
|
12
|
+
/** Owns the wire<->context transfer, both directions. Stateless framework singleton. */
|
|
13
|
+
private headers;
|
|
14
|
+
constructor(clientMethod: (requestDto: unknown) => Promise<unknown>, path: string,
|
|
15
|
+
/** Owns the wire<->context transfer, both directions. Stateless framework singleton. */
|
|
16
|
+
headers: RequestContextHeaders);
|
|
12
17
|
execute(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
13
18
|
executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
14
19
|
executeImpl(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
@@ -18,6 +23,12 @@ export declare class ExpressWrapper {
|
|
|
18
23
|
*
|
|
19
24
|
* HTTP spec allows multiple values for same header name.
|
|
20
25
|
*/
|
|
26
|
+
/**
|
|
27
|
+
* express Request -> webpieces {@link HttpRequest}. THE translation layer: below this line the
|
|
28
|
+
* filter chain and controllers never see express, which is what lets the same chain run
|
|
29
|
+
* in-process with no transport at all.
|
|
30
|
+
*/
|
|
31
|
+
private toWebpiecesRequest;
|
|
21
32
|
private readExpressHeaders;
|
|
22
33
|
/**
|
|
23
34
|
* Read raw request body as text.
|
|
@@ -68,6 +79,8 @@ export declare class ExpressWrapper {
|
|
|
68
79
|
* - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)
|
|
69
80
|
*/
|
|
70
81
|
export declare class WebpiecesMiddleware {
|
|
82
|
+
/** The ONE wire<->context transfer, handed to every route's ExpressWrapper. Stateless. */
|
|
83
|
+
private readonly headers;
|
|
71
84
|
/**
|
|
72
85
|
* Global error handler middleware - catches ALL unhandled errors.
|
|
73
86
|
* Returns HTML 500 error page for any errors that escape the filter chain.
|
|
@@ -13,11 +13,15 @@ const log = core_util_3.LogManager.getLogger('WebpiecesMiddleware');
|
|
|
13
13
|
class ExpressWrapper {
|
|
14
14
|
clientMethod;
|
|
15
15
|
path;
|
|
16
|
+
headers;
|
|
16
17
|
constructor(
|
|
17
18
|
// webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary
|
|
18
|
-
clientMethod, path
|
|
19
|
+
clientMethod, path,
|
|
20
|
+
/** Owns the wire<->context transfer, both directions. Stateless framework singleton. */
|
|
21
|
+
headers) {
|
|
19
22
|
this.clientMethod = clientMethod;
|
|
20
23
|
this.path = path;
|
|
24
|
+
this.headers = headers;
|
|
21
25
|
}
|
|
22
26
|
async execute(req, res, next) {
|
|
23
27
|
// MOVED: Wrap entire request in RequestContext.run()
|
|
@@ -38,8 +42,8 @@ class ExpressWrapper {
|
|
|
38
42
|
}
|
|
39
43
|
}
|
|
40
44
|
async executeImpl(req, res, next) {
|
|
41
|
-
// 1.
|
|
42
|
-
const
|
|
45
|
+
// 1. Translate express's request into the transport-neutral HttpRequest webpieces speaks.
|
|
46
|
+
const httpRequest = this.toWebpiecesRequest(req);
|
|
43
47
|
// 2. Parse JSON request body manually (SYMMETRIC with client's JSON.stringify)
|
|
44
48
|
let requestDto = {};
|
|
45
49
|
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
|
@@ -48,13 +52,13 @@ class ExpressWrapper {
|
|
|
48
52
|
// Parse JSON
|
|
49
53
|
requestDto = bodyText ? JSON.parse(bodyText) : {};
|
|
50
54
|
}
|
|
51
|
-
// 3. Publish the transport-neutral HttpRequest
|
|
52
|
-
//
|
|
53
|
-
|
|
54
|
-
|
|
55
|
+
// 3. Publish the transport-neutral HttpRequest, then move its headers into the context and
|
|
56
|
+
// mint a request id if the caller sent none. BOTH happen above the api boundary, because
|
|
57
|
+
// http-routing requires an already-established, already-filled request scope — it never
|
|
58
|
+
// builds one for you. This is the "translation layer" every transport must provide.
|
|
59
|
+
this.headers.fillFromRequest(httpRequest);
|
|
55
60
|
// 4. Invoke the api CLIENT method — the SAME proxy tests use. Its filter chain + controller
|
|
56
|
-
// run here
|
|
57
|
-
// not re-synthesize one). So HTTP and in-process share one invocation path.
|
|
61
|
+
// run here, reading the context filled above; the chain never touches express `req`.
|
|
58
62
|
const result = await this.clientMethod(requestDto);
|
|
59
63
|
// 5. Serialize the response DTO to JSON (SYMMETRIC with client's response.json())
|
|
60
64
|
const responseJson = JSON.stringify(result);
|
|
@@ -66,6 +70,14 @@ class ExpressWrapper {
|
|
|
66
70
|
*
|
|
67
71
|
* HTTP spec allows multiple values for same header name.
|
|
68
72
|
*/
|
|
73
|
+
/**
|
|
74
|
+
* express Request -> webpieces {@link HttpRequest}. THE translation layer: below this line the
|
|
75
|
+
* filter chain and controllers never see express, which is what lets the same chain run
|
|
76
|
+
* in-process with no transport at all.
|
|
77
|
+
*/
|
|
78
|
+
toWebpiecesRequest(req) {
|
|
79
|
+
return new core_context_1.HttpRequest(req.method, this.path, this.readExpressHeaders(req));
|
|
80
|
+
}
|
|
69
81
|
readExpressHeaders(req) {
|
|
70
82
|
const headers = new Map();
|
|
71
83
|
// Express stores headers in req.headers as Record<string, string | string[]>
|
|
@@ -203,6 +215,8 @@ exports.ExpressWrapper = ExpressWrapper;
|
|
|
203
215
|
* - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)
|
|
204
216
|
*/
|
|
205
217
|
let WebpiecesMiddleware = class WebpiecesMiddleware {
|
|
218
|
+
/** The ONE wire<->context transfer, handed to every route's ExpressWrapper. Stateless. */
|
|
219
|
+
headers = new core_context_1.RequestContextHeaders();
|
|
206
220
|
/**
|
|
207
221
|
* Global error handler middleware - catches ALL unhandled errors.
|
|
208
222
|
* Returns HTML 500 error page for any errors that escape the filter chain.
|
|
@@ -297,7 +311,7 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
|
|
|
297
311
|
createExpressWrapper(
|
|
298
312
|
// webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary
|
|
299
313
|
clientMethod, path) {
|
|
300
|
-
return new ExpressWrapper(clientMethod, path);
|
|
314
|
+
return new ExpressWrapper(clientMethod, path, this.headers);
|
|
301
315
|
}
|
|
302
316
|
};
|
|
303
317
|
exports.WebpiecesMiddleware = WebpiecesMiddleware;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,yCAAuC;AACvC,0DAAiF;AACjF,oDAa8B;AAC9B,oDAA+C;AAC/C,0DAAsE;AACtE,oDAAkD;AAElD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAaxD,MAAa,cAAc;IAGX;IACA;IAHZ;IACI,+FAA+F;IACvF,YAAuD,EACvD,IAAY;QADZ,iBAAY,GAAZ,YAAY,CAA2C;QACvD,SAAI,GAAJ,IAAI,CAAQ;IAExB,CAAC;IAEM,KAAK,CAAC,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QAChE,qDAAqD;QACrD,6DAA6D;QAC7D,MAAM,6BAAc,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;YAChC,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;IACP,CAAC;IAEM,KAAK,CAAC,eAAe,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QACxE,8HAA8H;QAC9H,IAAI,CAAC;YACD,MAAM,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK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C;IAClD,CAAC;CACJ,CAAA;AAhHY,kDAAmB;8BAAnB,mBAAmB;IAF/B,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;GACA,mBAAmB,CAgH/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { injectable } from 'inversify';\nimport { provideFrameworkSingleton, fillContext } from '@webpieces/http-routing';\nimport {\n ProtocolError,\n HttpError,\n HttpBadRequestError,\n HttpVendorError,\n HttpUserError,\n HttpNotFoundError,\n HttpTimeoutError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpInternalServerError,\n HttpBadGatewayError,\n HttpGatewayTimeoutError,\n} from '@webpieces/core-util';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContext, HttpRequest } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\n\n/**\n * Express route handler function type. Lives in http-server (the express adapter),\n * NOT in the node-only http-routing package, so http-routing stays express-free.\n * Used by WebpiecesExpressRouter to register handlers Express can call.\n */\nexport type ExpressRouteHandler = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => Promise<void>;\n\nexport class ExpressWrapper {\n constructor(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n private clientMethod: (requestDto: unknown) => Promise<unknown>,\n private path: string\n ) {\n }\n\n public async execute(req: Request, res: Response, next: NextFunction) {\n // MOVED: Wrap entire request in RequestContext.run()\n // This establishes AsyncLocalStorage context for the request\n await RequestContext.run(async () => {\n await this.executeTryCatch(req, res, next);\n });\n }\n\n public async executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- ExpressWrapper catches errors to translate to HTTP responses\n try {\n await this.executeImpl(req, res, next);\n } catch (err: unknown) {\n const error = toError(err);\n // 5. Handle errors\n this.handleError(res, error);\n }\n }\n\n public async executeImpl(req: Request, res: Response, next: NextFunction): Promise<void> {\n // 1. Read HTTP headers from Express request\n const requestHeaders = this.readExpressHeaders(req);\n\n // 2. Parse JSON request body manually (SYMMETRIC with client's JSON.stringify)\n let requestDto: unknown = {};\n if (['POST', 'PUT', 'PATCH'].includes(req.method)) {\n // Read raw body as text\n const bodyText = await this.readRequestBody(req);\n // Parse JSON\n requestDto = bodyText ? JSON.parse(bodyText) : {};\n }\n\n // 3. Publish the transport-neutral HttpRequest + fill the context (platform-header\n // transfer + request id) ABOVE the boundary — the chain reads it, never express req.\n RequestContext.setRequest(new HttpRequest(req.method, this.path, requestHeaders));\n fillContext();\n\n // 4. Invoke the api CLIENT method — the SAME proxy tests use. Its filter chain + controller\n // run here; because the request is already published above, the proxy uses it (it does\n // not re-synthesize one). So HTTP and in-process share one invocation path.\n const result = await this.clientMethod(requestDto);\n\n // 5. Serialize the response DTO to JSON (SYMMETRIC with client's response.json())\n const responseJson = JSON.stringify(result);\n res.status(200).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n\n /**\n * Read HTTP headers from Express request.\n * Returns Map of header name (lowercase) -> array of values.\n *\n * HTTP spec allows multiple values for same header name.\n */\n private readExpressHeaders(req: Request): Map<string, string[]> {\n const headers = new Map<string, string[]>();\n\n // Express stores headers in req.headers as Record<string, string | string[]>\n for (const [name, value] of Object.entries(req.headers)) {\n const lowerName = name.toLowerCase();\n\n if (typeof value === 'string') {\n headers.set(lowerName, [value]);\n } else if (Array.isArray(value)) {\n headers.set(lowerName, value);\n }\n }\n\n return headers;\n }\n\n /**\n * Read raw request body as text.\n * Used to manually parse JSON (instead of express.json() middleware).\n */\n private async readRequestBody(req: Request): Promise<string> {\n return new Promise((resolve, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Handle errors - translate to JSON ProtocolError (SYMMETRIC with ClientErrorTranslator).\n * PUBLIC so wrapExpress can call it for symmetric error handling.\n * Maps HttpError subclasses to appropriate HTTP status codes and ProtocolError response.\n *\n * Maps all HttpError types (must match ClientErrorTranslator.translateError()):\n * - HttpUserError → 266 (with errorCode)\n * - HttpBadRequestError → 400 (with field, guiAlertMessage)\n * - HttpUnauthorizedError → 401\n * - HttpForbiddenError → 403\n * - HttpNotFoundError → 404\n * - HttpTimeoutError → 408\n * - HttpInternalServerError → 500\n * - HttpBadGatewayError → 502\n * - HttpGatewayTimeoutError → 504\n * - HttpVendorError → 598 (with waitSeconds)\n */\n public handleError(res: Response, error: unknown): void {\n if (res.headersSent) {\n return;\n }\n\n const protocolError = new ProtocolError();\n\n if (error instanceof HttpError) {\n // Set common fields for all HttpError types\n protocolError.message = error.message;\n protocolError.subType = error.subType;\n protocolError.name = error.name;\n\n // Set type-specific fields (MUST match ClientErrorTranslator)\n if (error instanceof HttpUserError) {\n log.info(`[ExpressWrapper] User Error: ${error.message}`);\n protocolError.errorCode = error.errorCode;\n } else if (error instanceof HttpBadRequestError) {\n log.info(`[ExpressWrapper] Bad Request: ${error.message}`);\n protocolError.field = error.field;\n protocolError.guiAlertMessage = error.guiMessage;\n } else if (error instanceof HttpNotFoundError) {\n log.info(`[ExpressWrapper] Not Found: ${error.message}`);\n } else if (error instanceof HttpTimeoutError) {\n log.error(`[ExpressWrapper] Timeout Error: ${error.message}`);\n } else if (error instanceof HttpVendorError) {\n log.error(`[ExpressWrapper] Vendor Error: ${error.message}`);\n protocolError.waitSeconds = error.waitSeconds;\n } else if (error instanceof HttpUnauthorizedError) {\n log.info(`[ExpressWrapper] Unauthorized: ${error.message}`);\n } else if (error instanceof HttpForbiddenError) {\n log.info(`[ExpressWrapper] Forbidden: ${error.message}`);\n } else if (error instanceof HttpInternalServerError) {\n log.error(`[ExpressWrapper] Internal Server Error: ${error.message}`);\n } else if (error instanceof HttpBadGatewayError) {\n log.error(`[ExpressWrapper] Bad Gateway: ${error.message}`);\n } else if (error instanceof HttpGatewayTimeoutError) {\n log.error(`[ExpressWrapper] Gateway Timeout: ${error.message}`);\n } else {\n log.info(`[ExpressWrapper] Generic HttpError: ${error.message}`);\n }\n\n // Serialize ProtocolError to JSON (SYMMETRIC with client)\n const responseJson = JSON.stringify(protocolError);\n res.status(error.code).setHeader('Content-Type', 'application/json').send(responseJson);\n } else {\n // Unknown error - 500\n const err = toError(error);\n protocolError.message = 'Internal Server Error';\n log.error('[ExpressWrapper] Unexpected error:', err);\n const responseJson = JSON.stringify(protocolError);\n res.status(500).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n }\n}\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. globalErrorHandler - Outermost error handler, returns HTML 500 page\n * 2. logNextLayer - Request/response logging\n * 3. jsonTranslator - JSON Content-Type validation and error translation\n *\n * The middleware is injected into WebpiecesServerImpl and registered with Express\n * in the start() method.\n *\n * IMPORTANT: jsonTranslator does NOT dispatch routes - route dispatch happens via\n * Express's registered route handlers (created by RouteBuilder.createHandler()).\n * jsonTranslator only validates Content-Type and translates errors to JSON.\n *\n * NEW: ExpressWrapper simplified - no longer handles JSON or headers\n * - JSON parsing/serialization moved to JsonFilter\n * - Header transfer moved to ContextFilter (injects PlatformHeadersExtension directly)\n * - ExpressWrapper just creates RouterReqResp and invokes filter chain\n *\n * Extension vs Plugin pattern:\n * - Extensions (DI-level): Contribute capabilities to framework (headers, converters, etc.)\n * - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)\n */\n@provideFrameworkSingleton()\n@injectable()\nexport class WebpiecesMiddleware {\n\n /**\n * Global error handler middleware - catches ALL unhandled errors.\n * Returns HTML 500 error page for any errors that escape the filter chain.\n *\n * This is the outermost safety net - JsonTranslator catches JSON API errors,\n * this catches everything else.\n */\n async globalErrorHandler(\n req: Request,\n res: Response,\n next: NextFunction,\n ): Promise<void> {\n log.info(`🔴 [Layer 1: GlobalErrorHandler] Request START: ${req.method} ${req.path}`);\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- Global error handler IS the top-level catch-all\n try {\n // await next() catches BOTH:\n // 1. Synchronous throws from next() itself\n // 2. Rejected promises from downstream async middleware\n await next();\n log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (success): ${req.method} ${req.path}`,\n );\n } catch (err: unknown) {\n const error = toError(err);\n log.error('🔴 [Layer 1: GlobalErrorHandler] Caught unhandled error:', error);\n if (!res.headersSent) {\n // Return HTML error page (not JSON - JsonTranslator handles JSON errors)\n res.status(500).send(`\n <!DOCTYPE html>\n <html>\n <head><title>Server Error</title></head>\n <body>\n <h1>You hit a server error</h1>\n <p>An unexpected error occurred while processing your request.</p>\n <pre>${error.message}</pre>\n </body>\n </html>\n `);\n }\n log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (error): ${req.method} ${req.path}`,\n );\n }\n }\n\n /**\n * Logging middleware - logs request/response flow.\n * Demonstrates middleware execution order.\n * IMPORTANT: Must be async and await next() to properly chain with async middleware.\n */\n async logNextLayer(req: Request, res: Response, next: NextFunction): Promise<void> {\n log.info(`🟡 [Layer 2: LogNextLayer] Before next() - ${req.method} ${req.path}`);\n await next();\n log.info(`🟡 [Layer 2: LogNextLayer] After next() - ${req.method} ${req.path}`);\n }\n\n /**\n * CORS middleware for localhost development.\n * Only enables CORS when request origin is localhost:*.\n *\n * Wide open for all headers/methods in dev mode.\n * Non-localhost origins are blocked.\n *\n * @returns Express middleware handler for CORS\n */\n corsForLocalhost(): RequestHandler {\n log.info('[WebpiecesMiddleware] CORS enabled for localhost:* origins');\n\n return cors({\n origin: function (origin, callback) {\n // Allow requests with no origin (same-origin, Postman, curl)\n if (!origin) {\n callback(null, true);\n return;\n }\n\n // Only allow localhost origins\n if (origin.startsWith('http://localhost:') || origin.startsWith('https://localhost:')) {\n callback(null, true);\n } else {\n log.info(`[CORS] Blocked origin: ${origin} (only localhost:* allowed)`);\n callback(new Error(`CORS not allowed for origin: ${origin}`));\n }\n },\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: '*', // Wide open for dev\n exposedHeaders: '*', // Expose all response headers to browser JS\n maxAge: 3600,\n });\n }\n\n /**\n * Create an ExpressWrapper for a route.\n * The wrapper handles the full request/response cycle (symmetric design): it publishes the\n * HttpRequest + fills the context, then invokes the api client method (the proxy).\n *\n * @param clientMethod - The api client's method for this route (dto → response); the proxy\n * runs the filter chain + controller.\n * @param path - The route path (used to build the HttpRequest).\n * @returns ExpressWrapper instance\n */\n createExpressWrapper(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n clientMethod: (requestDto: unknown) => Promise<unknown>,\n path: string,\n ): ExpressWrapper {\n return new ExpressWrapper(clientMethod, path);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,yCAAuC;AACvC,0DAAoE;AACpE,oDAa8B;AAC9B,oDAA+C;AAC/C,0DAA6F;AAC7F,oDAAkD;AAElD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAaxD,MAAa,cAAc;IAGX;IACA;IAEA;IALZ;IACI,+FAA+F;IACvF,YAAuD,EACvD,IAAY;IACpB,wFAAwF;IAChF,OAA8B;QAH9B,iBAAY,GAAZ,YAAY,CAA2C;QACvD,SAAI,GAAJ,IAAI,CAAQ;QAEZ,YAAO,GAAP,OAAO,CAAuB;IAE1C,CAAC;IAEM,KAAK,CAAC,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QAChE,qDAAqD;QACrD,6DAA6D;QAC7D,MAAM,6BAAc,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;YAChC,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;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C;gBAClE,CAAC;YACL,CAAC;YACD,WAAW,EAAE,IAAI;YACjB,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC;YAC7D,cAAc,EAAE,GAAG,EAAE,oBAAoB;YACzC,cAAc,EAAE,GAAG,EAAE,4CAA4C;YACjE,MAAM,EAAE,IAAI;SACf,CAAC,CAAC;IACP,CAAC;IAED;;;;;;;;;OASG;IACH,oBAAoB;IAChB,+FAA+F;IAC/F,YAAuD,EACvD,IAAY;QAEZ,OAAO,IAAI,cAAc,CAAC,YAAY,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAChE,CAAC;CACJ,CAAA;AAnHY,kDAAmB;8BAAnB,mBAAmB;IAF/B,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;GACA,mBAAmB,CAmH/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { injectable } from 'inversify';\nimport { provideFrameworkSingleton } from '@webpieces/http-routing';\nimport {\n ProtocolError,\n HttpError,\n HttpBadRequestError,\n HttpVendorError,\n HttpUserError,\n HttpNotFoundError,\n HttpTimeoutError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpInternalServerError,\n HttpBadGatewayError,\n HttpGatewayTimeoutError,\n} from '@webpieces/core-util';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContext, HttpRequest, RequestContextHeaders } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\n\n/**\n * Express route handler function type. Lives in http-server (the express adapter),\n * NOT in the node-only http-routing package, so http-routing stays express-free.\n * Used by WebpiecesExpressRouter to register handlers Express can call.\n */\nexport type ExpressRouteHandler = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => Promise<void>;\n\nexport class ExpressWrapper {\n constructor(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n private clientMethod: (requestDto: unknown) => Promise<unknown>,\n private path: string,\n /** Owns the wire<->context transfer, both directions. Stateless framework singleton. */\n private headers: RequestContextHeaders,\n ) {\n }\n\n public async execute(req: Request, res: Response, next: NextFunction) {\n // MOVED: Wrap entire request in RequestContext.run()\n // This establishes AsyncLocalStorage context for the request\n await RequestContext.run(async () => {\n await this.executeTryCatch(req, res, next);\n });\n }\n\n public async executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- ExpressWrapper catches errors to translate to HTTP responses\n try {\n await this.executeImpl(req, res, next);\n } catch (err: unknown) {\n const error = toError(err);\n // 5. Handle errors\n this.handleError(res, error);\n }\n }\n\n public async executeImpl(req: Request, res: Response, next: NextFunction): Promise<void> {\n // 1. Translate express's request into the transport-neutral HttpRequest webpieces speaks.\n const httpRequest = this.toWebpiecesRequest(req);\n\n // 2. Parse JSON request body manually (SYMMETRIC with client's JSON.stringify)\n let requestDto: unknown = {};\n if (['POST', 'PUT', 'PATCH'].includes(req.method)) {\n // Read raw body as text\n const bodyText = await this.readRequestBody(req);\n // Parse JSON\n requestDto = bodyText ? JSON.parse(bodyText) : {};\n }\n\n // 3. Publish the transport-neutral HttpRequest, then move its headers into the context and\n // mint a request id if the caller sent none. BOTH happen above the api boundary, because\n // http-routing requires an already-established, already-filled request scope — it never\n // builds one for you. This is the \"translation layer\" every transport must provide.\n this.headers.fillFromRequest(httpRequest);\n\n // 4. Invoke the api CLIENT method — the SAME proxy tests use. Its filter chain + controller\n // run here, reading the context filled above; the chain never touches express `req`.\n const result = await this.clientMethod(requestDto);\n\n // 5. Serialize the response DTO to JSON (SYMMETRIC with client's response.json())\n const responseJson = JSON.stringify(result);\n res.status(200).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n\n /**\n * Read HTTP headers from Express request.\n * Returns Map of header name (lowercase) -> array of values.\n *\n * HTTP spec allows multiple values for same header name.\n */\n /**\n * express Request -> webpieces {@link HttpRequest}. THE translation layer: below this line the\n * filter chain and controllers never see express, which is what lets the same chain run\n * in-process with no transport at all.\n */\n private toWebpiecesRequest(req: Request): HttpRequest {\n return new HttpRequest(req.method, this.path, this.readExpressHeaders(req));\n }\n\n private readExpressHeaders(req: Request): Map<string, string[]> {\n const headers = new Map<string, string[]>();\n\n // Express stores headers in req.headers as Record<string, string | string[]>\n for (const [name, value] of Object.entries(req.headers)) {\n const lowerName = name.toLowerCase();\n\n if (typeof value === 'string') {\n headers.set(lowerName, [value]);\n } else if (Array.isArray(value)) {\n headers.set(lowerName, value);\n }\n }\n\n return headers;\n }\n\n /**\n * Read raw request body as text.\n * Used to manually parse JSON (instead of express.json() middleware).\n */\n private async readRequestBody(req: Request): Promise<string> {\n return new Promise((resolve, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Handle errors - translate to JSON ProtocolError (SYMMETRIC with ClientErrorTranslator).\n * PUBLIC so wrapExpress can call it for symmetric error handling.\n * Maps HttpError subclasses to appropriate HTTP status codes and ProtocolError response.\n *\n * Maps all HttpError types (must match ClientErrorTranslator.translateError()):\n * - HttpUserError → 266 (with errorCode)\n * - HttpBadRequestError → 400 (with field, guiAlertMessage)\n * - HttpUnauthorizedError → 401\n * - HttpForbiddenError → 403\n * - HttpNotFoundError → 404\n * - HttpTimeoutError → 408\n * - HttpInternalServerError → 500\n * - HttpBadGatewayError → 502\n * - HttpGatewayTimeoutError → 504\n * - HttpVendorError → 598 (with waitSeconds)\n */\n public handleError(res: Response, error: unknown): void {\n if (res.headersSent) {\n return;\n }\n\n const protocolError = new ProtocolError();\n\n if (error instanceof HttpError) {\n // Set common fields for all HttpError types\n protocolError.message = error.message;\n protocolError.subType = error.subType;\n protocolError.name = error.name;\n\n // Set type-specific fields (MUST match ClientErrorTranslator)\n if (error instanceof HttpUserError) {\n log.info(`[ExpressWrapper] User Error: ${error.message}`);\n protocolError.errorCode = error.errorCode;\n } else if (error instanceof HttpBadRequestError) {\n log.info(`[ExpressWrapper] Bad Request: ${error.message}`);\n protocolError.field = error.field;\n protocolError.guiAlertMessage = error.guiMessage;\n } else if (error instanceof HttpNotFoundError) {\n log.info(`[ExpressWrapper] Not Found: ${error.message}`);\n } else if (error instanceof HttpTimeoutError) {\n log.error(`[ExpressWrapper] Timeout Error: ${error.message}`);\n } else if (error instanceof HttpVendorError) {\n log.error(`[ExpressWrapper] Vendor Error: ${error.message}`);\n protocolError.waitSeconds = error.waitSeconds;\n } else if (error instanceof HttpUnauthorizedError) {\n log.info(`[ExpressWrapper] Unauthorized: ${error.message}`);\n } else if (error instanceof HttpForbiddenError) {\n log.info(`[ExpressWrapper] Forbidden: ${error.message}`);\n } else if (error instanceof HttpInternalServerError) {\n log.error(`[ExpressWrapper] Internal Server Error: ${error.message}`);\n } else if (error instanceof HttpBadGatewayError) {\n log.error(`[ExpressWrapper] Bad Gateway: ${error.message}`);\n } else if (error instanceof HttpGatewayTimeoutError) {\n log.error(`[ExpressWrapper] Gateway Timeout: ${error.message}`);\n } else {\n log.info(`[ExpressWrapper] Generic HttpError: ${error.message}`);\n }\n\n // Serialize ProtocolError to JSON (SYMMETRIC with client)\n const responseJson = JSON.stringify(protocolError);\n res.status(error.code).setHeader('Content-Type', 'application/json').send(responseJson);\n } else {\n // Unknown error - 500\n const err = toError(error);\n protocolError.message = 'Internal Server Error';\n log.error('[ExpressWrapper] Unexpected error:', err);\n const responseJson = JSON.stringify(protocolError);\n res.status(500).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n }\n}\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. globalErrorHandler - Outermost error handler, returns HTML 500 page\n * 2. logNextLayer - Request/response logging\n * 3. jsonTranslator - JSON Content-Type validation and error translation\n *\n * The middleware is injected into WebpiecesServerImpl and registered with Express\n * in the start() method.\n *\n * IMPORTANT: jsonTranslator does NOT dispatch routes - route dispatch happens via\n * Express's registered route handlers (created by RouteBuilder.createHandler()).\n * jsonTranslator only validates Content-Type and translates errors to JSON.\n *\n * NEW: ExpressWrapper simplified - no longer handles JSON or headers\n * - JSON parsing/serialization moved to JsonFilter\n * - Header transfer moved to ContextFilter (injects PlatformHeadersExtension directly)\n * - ExpressWrapper just creates RouterReqResp and invokes filter chain\n *\n * Extension vs Plugin pattern:\n * - Extensions (DI-level): Contribute capabilities to framework (headers, converters, etc.)\n * - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)\n */\n@provideFrameworkSingleton()\n@injectable()\nexport class WebpiecesMiddleware {\n /** The ONE wire<->context transfer, handed to every route's ExpressWrapper. Stateless. */\n private readonly headers = new RequestContextHeaders();\n\n\n /**\n * Global error handler middleware - catches ALL unhandled errors.\n * Returns HTML 500 error page for any errors that escape the filter chain.\n *\n * This is the outermost safety net - JsonTranslator catches JSON API errors,\n * this catches everything else.\n */\n async globalErrorHandler(\n req: Request,\n res: Response,\n next: NextFunction,\n ): Promise<void> {\n log.info(`🔴 [Layer 1: GlobalErrorHandler] Request START: ${req.method} ${req.path}`);\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- Global error handler IS the top-level catch-all\n try {\n // await next() catches BOTH:\n // 1. Synchronous throws from next() itself\n // 2. Rejected promises from downstream async middleware\n await next();\n log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (success): ${req.method} ${req.path}`,\n );\n } catch (err: unknown) {\n const error = toError(err);\n log.error('🔴 [Layer 1: GlobalErrorHandler] Caught unhandled error:', error);\n if (!res.headersSent) {\n // Return HTML error page (not JSON - JsonTranslator handles JSON errors)\n res.status(500).send(`\n <!DOCTYPE html>\n <html>\n <head><title>Server Error</title></head>\n <body>\n <h1>You hit a server error</h1>\n <p>An unexpected error occurred while processing your request.</p>\n <pre>${error.message}</pre>\n </body>\n </html>\n `);\n }\n log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (error): ${req.method} ${req.path}`,\n );\n }\n }\n\n /**\n * Logging middleware - logs request/response flow.\n * Demonstrates middleware execution order.\n * IMPORTANT: Must be async and await next() to properly chain with async middleware.\n */\n async logNextLayer(req: Request, res: Response, next: NextFunction): Promise<void> {\n log.info(`🟡 [Layer 2: LogNextLayer] Before next() - ${req.method} ${req.path}`);\n await next();\n log.info(`🟡 [Layer 2: LogNextLayer] After next() - ${req.method} ${req.path}`);\n }\n\n /**\n * CORS middleware for localhost development.\n * Only enables CORS when request origin is localhost:*.\n *\n * Wide open for all headers/methods in dev mode.\n * Non-localhost origins are blocked.\n *\n * @returns Express middleware handler for CORS\n */\n corsForLocalhost(): RequestHandler {\n log.info('[WebpiecesMiddleware] CORS enabled for localhost:* origins');\n\n return cors({\n origin: function (origin, callback) {\n // Allow requests with no origin (same-origin, Postman, curl)\n if (!origin) {\n callback(null, true);\n return;\n }\n\n // Only allow localhost origins\n if (origin.startsWith('http://localhost:') || origin.startsWith('https://localhost:')) {\n callback(null, true);\n } else {\n log.info(`[CORS] Blocked origin: ${origin} (only localhost:* allowed)`);\n callback(new Error(`CORS not allowed for origin: ${origin}`));\n }\n },\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: '*', // Wide open for dev\n exposedHeaders: '*', // Expose all response headers to browser JS\n maxAge: 3600,\n });\n }\n\n /**\n * Create an ExpressWrapper for a route.\n * The wrapper handles the full request/response cycle (symmetric design): it publishes the\n * HttpRequest + fills the context, then invokes the api client method (the proxy).\n *\n * @param clientMethod - The api client's method for this route (dto → response); the proxy\n * runs the filter chain + controller.\n * @param path - The route path (used to build the HttpRequest).\n * @returns ExpressWrapper instance\n */\n createExpressWrapper(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n clientMethod: (requestDto: unknown) => Promise<unknown>,\n path: string,\n ): ExpressWrapper {\n return new ExpressWrapper(clientMethod, path, this.headers);\n }\n}\n"]}
|
|
@@ -2,8 +2,6 @@ import { MethodMeta } from '@webpieces/http-routing';
|
|
|
2
2
|
import { Filter, WpResponse, Service } from '@webpieces/http-routing';
|
|
3
3
|
export declare class LogApiFilter extends Filter<MethodMeta, WpResponse<unknown>> {
|
|
4
4
|
private logApiCall;
|
|
5
|
-
private headerMethods;
|
|
6
|
-
private loggedKeys;
|
|
7
5
|
constructor();
|
|
8
6
|
filter(meta: MethodMeta, nextFilter: Service<MethodMeta, WpResponse<unknown>>): Promise<WpResponse<unknown>>;
|
|
9
7
|
}
|
|
@@ -26,26 +26,19 @@ const core_util_2 = require("@webpieces/core-util");
|
|
|
26
26
|
const log = core_util_1.LogManager.getLogger('LogApiFilter');
|
|
27
27
|
let LogApiFilter = class LogApiFilter extends http_routing_2.Filter {
|
|
28
28
|
logApiCall;
|
|
29
|
-
headerMethods = new core_util_2.HeaderMethods();
|
|
30
|
-
loggedKeys;
|
|
31
29
|
constructor() {
|
|
32
30
|
super();
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
this.loggedKeys = core_util_2.HeaderRegistry.get().getLoggedKeys();
|
|
36
|
-
log.info(`[LogApiFilter] Using ${this.loggedKeys.length} logged context keys from HeaderRegistry`);
|
|
31
|
+
// Context fields are stamped onto each record by the logging BACKEND (bunyan/winston read
|
|
32
|
+
// RequestContext.buildLogFields()); this filter no longer collects them.
|
|
37
33
|
this.logApiCall = new core_util_2.LogApiCall();
|
|
38
34
|
}
|
|
39
35
|
async filter(meta, nextFilter) {
|
|
40
|
-
// Build log map from RequestContext (keys already transferred by ContextFilter)
|
|
41
|
-
const contextReader = new http_routing_1.RequestContextReader();
|
|
42
|
-
const headers = this.headerMethods.buildSecureMapForLogs(this.loggedKeys, contextReader);
|
|
43
36
|
// Wrap nextFilter.invoke in a method that returns the response
|
|
44
37
|
const method = async () => {
|
|
45
38
|
const wpResponse = await nextFilter.invoke(meta);
|
|
46
39
|
return wpResponse.response;
|
|
47
40
|
};
|
|
48
|
-
const response = await this.logApiCall.execute("SVR", meta.routeMeta, meta.requestDto,
|
|
41
|
+
const response = await this.logApiCall.execute("SVR", meta.routeMeta, meta.requestDto, method);
|
|
49
42
|
return new http_routing_2.WpResponse(response);
|
|
50
43
|
}
|
|
51
44
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LogApiFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/filters/LogApiFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAAuC;AACvC,
|
|
1
|
+
{"version":3,"file":"LogApiFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/filters/LogApiFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAAuC;AACvC,0DAA8E;AAC9E,0DAAsE;AACtE,oDAAkD;AAClD,oDAE8B;AAE9B;;;;;;;;;;;;;;;GAeG;AACH,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC;AAI1C,IAAM,YAAY,GAAlB,MAAM,YAAa,SAAQ,qBAAuC;IAC7D,UAAU,CAAa;IAE/B;QACI,KAAK,EAAE,CAAC;QACR,0FAA0F;QAC1F,yEAAyE;QACzE,IAAI,CAAC,UAAU,GAAG,IAAI,sBAAU,EAAE,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,MAAM,CACR,IAAgB,EAChB,UAAoD;QAEpD,+DAA+D;QAC/D,MAAM,MAAM,GAAG,KAAK,IAAsB,EAAE;YACxC,MAAM,UAAU,GAAG,MAAM,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACjD,OAAO,UAAU,CAAC,QAAQ,CAAC;QAC/B,CAAC,CAAC;QAEF,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;QAC/F,OAAO,IAAI,yBAAU,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC;CACJ,CAAA;AAvBY,oCAAY;uBAAZ,YAAY;IAFxB,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;;GACA,YAAY,CAuBxB","sourcesContent":["import { injectable } from 'inversify';\nimport {provideFrameworkSingleton, MethodMeta} from '@webpieces/http-routing';\nimport { Filter, WpResponse, Service } from '@webpieces/http-routing';\nimport { LogManager } from '@webpieces/core-util';\nimport {\n LogApiCall,\n} from '@webpieces/core-util';\n\n/**\n * LogApiFilter - Structured API logging for all requests/responses.\n * Priority: 1800 (after ContextFilter at 2000, before custom filters)\n *\n * Logging patterns (via LogApiCall):\n * - [API-SVR-req] Class.method /url request={...} headers={...}\n * - [API-SVR-resp-SUCCESS] Class.method response={...}\n * - [API-SVR-resp-FAIL] Class.method error=... (server errors: 500, 502, 504)\n * - [API-SVR-resp-OTHER] Class.method errorType=... (user errors: 400, 401, 403, 404, 266)\n *\n * Headers are read from RequestContext (NOT from meta.requestHeaders which is undefined\n * after ContextFilter runs at priority 2000).\n *\n * User errors (HttpBadRequestError, etc.) are logged as OTHER, not FAIL,\n * because they are expected behavior from the server's perspective.\n */\nconst log = LogManager.getLogger('LogApiFilter');\n\n@provideFrameworkSingleton()\n@injectable()\nexport class LogApiFilter extends Filter<MethodMeta, WpResponse<unknown>> {\n private logApiCall: LogApiCall;\n\n constructor() {\n super();\n // Context fields are stamped onto each record by the logging BACKEND (bunyan/winston read\n // RequestContext.buildLogFields()); this filter no longer collects them.\n this.logApiCall = new LogApiCall();\n }\n\n async filter(\n meta: MethodMeta,\n nextFilter: Service<MethodMeta, WpResponse<unknown>>,\n ): Promise<WpResponse<unknown>> {\n // Wrap nextFilter.invoke in a method that returns the response\n const method = async (): Promise<unknown> => {\n const wpResponse = await nextFilter.invoke(meta);\n return wpResponse.response;\n };\n\n const response = await this.logApiCall.execute(\"SVR\", meta.routeMeta, meta.requestDto, method);\n return new WpResponse(response);\n }\n}\n"]}
|
|
@@ -20,7 +20,6 @@ import { Filter, WpResponse, Service } from '@webpieces/http-routing';
|
|
|
20
20
|
*/
|
|
21
21
|
export declare class RecordingFilter extends Filter<MethodMeta, WpResponse<unknown>> {
|
|
22
22
|
private config;
|
|
23
|
-
private headerMethods;
|
|
24
23
|
constructor(config: WebpiecesConfig);
|
|
25
24
|
filter(meta: MethodMeta, nextFilter: Service<MethodMeta, WpResponse<unknown>>): Promise<WpResponse<unknown>>;
|
|
26
25
|
private isRecordingRequested;
|
|
@@ -28,7 +28,6 @@ const TestCaseRecorderImpl_1 = require("../recorder/TestCaseRecorderImpl");
|
|
|
28
28
|
*/
|
|
29
29
|
let RecordingFilter = class RecordingFilter extends http_routing_2.Filter {
|
|
30
30
|
config;
|
|
31
|
-
headerMethods = new core_util_1.HeaderMethods();
|
|
32
31
|
constructor(config) {
|
|
33
32
|
super();
|
|
34
33
|
this.config = config;
|
|
@@ -66,7 +65,7 @@ let RecordingFilter = class RecordingFilter extends http_routing_2.Filter {
|
|
|
66
65
|
}
|
|
67
66
|
buildServerEndpoint(meta) {
|
|
68
67
|
// Masked snapshot of the magic context (secured values masked, keyed by name)
|
|
69
|
-
const logMap =
|
|
68
|
+
const logMap = core_context_1.RequestContext.buildLogFields();
|
|
70
69
|
const ctxSnapshot = {};
|
|
71
70
|
for (const entry of logMap.entries()) {
|
|
72
71
|
ctxSnapshot[entry[0]] = entry[1];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RecordingFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/filters/RecordingFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAA+C;AAC/C,
|
|
1
|
+
{"version":3,"file":"RecordingFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/filters/RecordingFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAA+C;AAC/C,0DAKiC;AACjC,0DAAyD;AACzD,0DAAsE;AACtE,oDAM8B;AAE9B,2EAAwE;AAExE;;;;;;;;;;;;;;;;;GAiBG;AAII,IA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CAAC;YAChC,OAAO,IAAI,CAAC;QAChB,CAAC;QACD,4EAA4E;QAC5E,OAAO,6BAAc,CAAC,SAAS,CAAC,gCAAoB,CAAC,SAAS,CAAC,CAAC;IACpE,CAAC;IAEO,mBAAmB,CAAC,IAAgB;QACxC,8EAA8E;QAC9E,MAAM,MAAM,GAAG,6BAAc,CAAC,cAAc,EAAE,CAAC;QAC/C,MAAM,WAAW,GAA2B,EAAE,CAAC;QAC/C,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;YACnC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACrC,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,mBAAmB,IAAI,YAAY,CAAC;QAC7F,OAAO,IAAI,4BAAgB,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,WAAW,CAAC,CAAC;IAC1F,CAAC;CACJ,CAAA;AAxDY,0CAAe;0BAAf,eAAe;IAH3B,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;IACb,sGAAsG;;IAI7F,mBAAA,IAAA,kBAAM,EAAC,qCAAsB,CAAC,CAAA;6CAAiB,8BAAe;GAH1D,eAAe,CAwD3B","sourcesContent":["import { inject, injectable } from 'inversify';\nimport {\n provideFrameworkSingleton,\n MethodMeta,\n WebpiecesConfig,\n WEBPIECES_CONFIG_TOKEN,\n} from '@webpieces/http-routing';\nimport { RequestContext } from '@webpieces/core-context';\nimport { Filter, WpResponse, Service } from '@webpieces/http-routing';\nimport {\n RecordedEndpoint,\n RecordedError,\n RecorderKeys,\n WebpiecesCoreHeaders,\n toError,\n} from '@webpieces/core-util';\n\nimport { TestCaseRecorderImpl } from '../recorder/TestCaseRecorderImpl';\n\n/**\n * RecordingFilter - Records a request as a replayable test case (port of Java\n * RecordingFilter).\n *\n * Suggested priority: 1850 (after ContextFilter 2000 so the RECORDING header\n * has been transferred to the context, after AuthFilter 1900 so only real\n * authorized flows are recorded, before LogApiFilter 1800).\n *\n * Activates when WebpiecesConfig.recordingAlwaysOn is set OR the request\n * carries WebpiecesCoreHeaders.RECORDING (x-webpieces-recording). While\n * active, a TestCaseRecorderImpl travels in the RequestContext under\n * RecorderKeys.RECORDER; the http-client proxy and recordable() wrappers add\n * every downstream call. On completion the fixture + generated spec are\n * logged (and written to config.recordingDir when set).\n *\n * Recording NEVER alters the response - failures inside the recorder are\n * caught and logged.\n */\n@provideFrameworkSingleton()\n@injectable()\n// webpieces-disable no-any-unknown -- Filter generic params use unknown for response type flexibility\nexport class RecordingFilter extends Filter<MethodMeta, WpResponse<unknown>> {\n\n constructor(\n @inject(WEBPIECES_CONFIG_TOKEN) private config: WebpiecesConfig,\n ) {\n super();\n }\n\n // webpieces-disable no-any-unknown -- Filter generic params use unknown for response type flexibility\n async filter(\n meta: MethodMeta,\n nextFilter: Service<MethodMeta, WpResponse<unknown>>,\n ): Promise<WpResponse<unknown>> {\n if (!this.isRecordingRequested()) {\n return await nextFilter.invoke(meta);\n }\n\n const recorder = new TestCaseRecorderImpl();\n RequestContext.putHeader(RecorderKeys.RECORDER, recorder);\n\n const serverEndpoint = this.buildServerEndpoint(meta);\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- capture failure into the recording, then rethrow unchanged\n try {\n const response = await nextFilter.invoke(meta);\n serverEndpoint.successResponse = response.response;\n return response;\n } catch (err: unknown) {\n const error = toError(err);\n serverEndpoint.failureResponse = new RecordedError(error.name, error.message);\n throw err;\n } finally {\n RequestContext.remove(RecorderKeys.RECORDER.name);\n recorder.spitOutTestCase(serverEndpoint, this.config.recordingDir);\n }\n }\n\n private isRecordingRequested(): boolean {\n if (this.config.recordingAlwaysOn) {\n return true;\n }\n // ContextFilter (priority 2000) already transferred the header into context\n return RequestContext.hasHeader(WebpiecesCoreHeaders.RECORDING);\n }\n\n private buildServerEndpoint(meta: MethodMeta): RecordedEndpoint {\n // Masked snapshot of the magic context (secured values masked, keyed by name)\n const logMap = RequestContext.buildLogFields();\n const ctxSnapshot: Record<string, string> = {};\n for (const entry of logMap.entries()) {\n ctxSnapshot[entry[0]] = entry[1];\n }\n\n const apiName = meta.routeMeta.apiName ?? meta.routeMeta.controllerClassName ?? 'UnknownApi';\n return new RecordedEndpoint(apiName, meta.methodName, [meta.requestDto], ctxSnapshot);\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* WebpiecesCoreHeaders moved to @webpieces/core-util (browser-safe) so the
|
|
3
|
-
* http
|
|
3
|
+
* http clients can reference REQUEST_ID for request-id
|
|
4
4
|
* chaining. Re-exported here for backward compatibility with existing imports.
|
|
5
5
|
*/
|
|
6
6
|
export { WebpiecesCoreHeaders } from '@webpieces/core-util';
|
|
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.WebpiecesCoreHeaders = void 0;
|
|
4
4
|
/**
|
|
5
5
|
* WebpiecesCoreHeaders moved to @webpieces/core-util (browser-safe) so the
|
|
6
|
-
* http
|
|
6
|
+
* http clients can reference REQUEST_ID for request-id
|
|
7
7
|
* chaining. Re-exported here for backward compatibility with existing imports.
|
|
8
8
|
*/
|
|
9
9
|
var core_util_1 = require("@webpieces/core-util");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebpiecesCoreHeaders.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/headers/WebpiecesCoreHeaders.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,kDAA4D;AAAnD,iHAAA,oBAAoB,OAAA","sourcesContent":["/**\n * WebpiecesCoreHeaders moved to @webpieces/core-util (browser-safe) so the\n * http
|
|
1
|
+
{"version":3,"file":"WebpiecesCoreHeaders.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/headers/WebpiecesCoreHeaders.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,kDAA4D;AAAnD,iHAAA,oBAAoB,OAAA","sourcesContent":["/**\n * WebpiecesCoreHeaders moved to @webpieces/core-util (browser-safe) so the\n * http clients can reference REQUEST_ID for request-id\n * chaining. Re-exported here for backward compatibility with existing imports.\n */\nexport { WebpiecesCoreHeaders } from '@webpieces/core-util';\n"]}
|