@emmett-community/emmett-expressjs-with-openapi 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +223 -25
- package/dist/chunk-BY65ZALY.cjs +12 -0
- package/dist/chunk-BY65ZALY.cjs.map +1 -0
- package/dist/chunk-I46UH36B.js +12 -0
- package/dist/chunk-I46UH36B.js.map +1 -0
- package/dist/{handler-importer-OJGFQON5.js → handler-importer-6A237UML.js} +21 -2
- package/dist/handler-importer-6A237UML.js.map +1 -0
- package/dist/{handler-importer-4BVBIZX3.cjs → handler-importer-UFV7TKBN.cjs} +21 -2
- package/dist/handler-importer-UFV7TKBN.cjs.map +1 -0
- package/dist/index.cjs +129 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +119 -1
- package/dist/index.d.ts +119 -1
- package/dist/index.js +116 -21
- package/dist/index.js.map +1 -1
- package/dist/{openapi-parser-NFUD7ZGZ.cjs → openapi-parser-PW5USNZ4.cjs} +27 -8
- package/dist/openapi-parser-PW5USNZ4.cjs.map +1 -0
- package/dist/{openapi-parser-CCYU636U.js → openapi-parser-QYXNHNSZ.js} +27 -7
- package/dist/openapi-parser-QYXNHNSZ.js.map +1 -0
- package/package.json +9 -2
- package/dist/handler-importer-4BVBIZX3.cjs.map +0 -1
- package/dist/handler-importer-OJGFQON5.js.map +0 -1
- package/dist/openapi-parser-CCYU636U.js.map +0 -1
- package/dist/openapi-parser-NFUD7ZGZ.cjs.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -3,12 +3,16 @@
|
|
|
3
3
|
var _chunkMRSGTROWcjs = require('./chunk-MRSGTROW.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
+
var _chunkBY65ZALYcjs = require('./chunk-BY65ZALY.cjs');
|
|
7
|
+
|
|
8
|
+
|
|
6
9
|
var _chunkGS7T56RPcjs = require('./chunk-GS7T56RP.cjs');
|
|
7
10
|
|
|
8
11
|
// src/index.ts
|
|
9
12
|
require('express-async-errors');
|
|
10
13
|
|
|
11
14
|
// src/application.ts
|
|
15
|
+
var _api = require('@opentelemetry/api');
|
|
12
16
|
|
|
13
17
|
|
|
14
18
|
var _express = require('express'); var _express2 = _interopRequireDefault(_express);
|
|
@@ -18,7 +22,8 @@ var _module = require('module');
|
|
|
18
22
|
|
|
19
23
|
// src/middlewares/problemDetailsMiddleware.ts
|
|
20
24
|
var _httpproblemdetails = require('http-problem-details');
|
|
21
|
-
var problemDetailsMiddleware = (mapError) => (error, request, response, _next) => {
|
|
25
|
+
var problemDetailsMiddleware = (mapError, logger) => (error, request, response, _next) => {
|
|
26
|
+
_chunkBY65ZALYcjs.safeLog.error(logger, "Request error", error);
|
|
22
27
|
let problemDetails;
|
|
23
28
|
if (mapError) problemDetails = mapError(error, request);
|
|
24
29
|
problemDetails = _nullishCoalesce(problemDetails, () => ( defaultErrorToProblemDetailsMapping(error)));
|
|
@@ -42,6 +47,7 @@ var defaultErrorToProblemDetailsMapping = (error) => {
|
|
|
42
47
|
};
|
|
43
48
|
|
|
44
49
|
// src/application.ts
|
|
50
|
+
var tracer = _api.trace.getTracer("@emmett-community/emmett-expressjs-with-openapi");
|
|
45
51
|
var getApplication = async (options) => {
|
|
46
52
|
const app = _express2.default.call(void 0, );
|
|
47
53
|
const {
|
|
@@ -51,10 +57,39 @@ var getApplication = async (options) => {
|
|
|
51
57
|
disableJsonMiddleware,
|
|
52
58
|
disableUrlEncodingMiddleware,
|
|
53
59
|
disableProblemDetailsMiddleware,
|
|
54
|
-
|
|
60
|
+
pinoHttp,
|
|
61
|
+
openApiValidator,
|
|
62
|
+
observability
|
|
55
63
|
} = options;
|
|
64
|
+
const logger = _optionalChain([observability, 'optionalAccess', _ => _.logger]);
|
|
65
|
+
_chunkBY65ZALYcjs.safeLog.debug(logger, "Initializing Express application", {
|
|
66
|
+
hasApis: !!_optionalChain([apis, 'optionalAccess', _2 => _2.length]),
|
|
67
|
+
hasOpenApiValidator: !!openApiValidator,
|
|
68
|
+
hasPinoHttp: !!pinoHttp
|
|
69
|
+
});
|
|
56
70
|
const router = _express.Router.call(void 0, );
|
|
57
71
|
app.set("etag", _nullishCoalesce(enableDefaultExpressEtag, () => ( false)));
|
|
72
|
+
if (pinoHttp !== void 0 && pinoHttp !== false) {
|
|
73
|
+
try {
|
|
74
|
+
const require2 = _module.createRequire.call(void 0, _chunkGS7T56RPcjs.importMetaUrl);
|
|
75
|
+
const mod = require2("pino-http");
|
|
76
|
+
const provider = _nullishCoalesce(mod.default, () => ( mod));
|
|
77
|
+
if (typeof provider !== "function") {
|
|
78
|
+
throw new Error("Invalid pino-http module: missing default export");
|
|
79
|
+
}
|
|
80
|
+
const options2 = pinoHttp === true ? void 0 : pinoHttp;
|
|
81
|
+
const middleware = provider(options2);
|
|
82
|
+
app.use(middleware);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
_chunkBY65ZALYcjs.safeLog.warn(
|
|
85
|
+
logger,
|
|
86
|
+
"Pino HTTP configuration provided but pino-http package is not installed. Install it with: npm install pino-http"
|
|
87
|
+
);
|
|
88
|
+
throw new Error(
|
|
89
|
+
"pino-http package is required when pinoHttp option is used"
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
58
93
|
if (!disableJsonMiddleware) app.use(_express2.default.json());
|
|
59
94
|
if (!disableUrlEncodingMiddleware)
|
|
60
95
|
app.use(
|
|
@@ -68,20 +103,52 @@ var getApplication = async (options) => {
|
|
|
68
103
|
activateESMResolver();
|
|
69
104
|
const handlersBasePath = typeof openApiValidator.operationHandlers === "string" ? openApiValidator.operationHandlers : openApiValidator.operationHandlers.basePath;
|
|
70
105
|
if (handlersBasePath) {
|
|
71
|
-
const { extractHandlerModules } = await Promise.resolve().then(() => _interopRequireWildcard(require("./openapi-parser-
|
|
72
|
-
const { importAndRegisterHandlers } = await Promise.resolve().then(() => _interopRequireWildcard(require("./handler-importer-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
106
|
+
const { extractHandlerModules } = await Promise.resolve().then(() => _interopRequireWildcard(require("./openapi-parser-PW5USNZ4.cjs")));
|
|
107
|
+
const { importAndRegisterHandlers } = await Promise.resolve().then(() => _interopRequireWildcard(require("./handler-importer-UFV7TKBN.cjs")));
|
|
108
|
+
const modules = await tracer.startActiveSpan(
|
|
109
|
+
"emmett.openapi.parse_spec",
|
|
110
|
+
async (span) => {
|
|
111
|
+
try {
|
|
112
|
+
const result = await extractHandlerModules(
|
|
113
|
+
openApiValidator.apiSpec,
|
|
114
|
+
handlersBasePath,
|
|
115
|
+
logger
|
|
116
|
+
);
|
|
117
|
+
span.setAttribute("emmett.handlers.count", result.length);
|
|
118
|
+
span.setStatus({ code: _api.SpanStatusCode.OK });
|
|
119
|
+
return result;
|
|
120
|
+
} catch (error) {
|
|
121
|
+
span.recordException(error);
|
|
122
|
+
span.setStatus({ code: _api.SpanStatusCode.ERROR });
|
|
123
|
+
throw error;
|
|
124
|
+
} finally {
|
|
125
|
+
span.end();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
);
|
|
129
|
+
const importedHandlers = await tracer.startActiveSpan(
|
|
130
|
+
"emmett.http.import_handlers",
|
|
131
|
+
async (span) => {
|
|
132
|
+
try {
|
|
133
|
+
const result = await importAndRegisterHandlers(modules, logger);
|
|
134
|
+
span.setAttribute(
|
|
135
|
+
"emmett.handlers.count",
|
|
136
|
+
Object.keys(result).length
|
|
137
|
+
);
|
|
138
|
+
span.setStatus({ code: _api.SpanStatusCode.OK });
|
|
139
|
+
return result;
|
|
140
|
+
} catch (error) {
|
|
141
|
+
_chunkBY65ZALYcjs.safeLog.error(logger, "Failed to auto-import handler modules", error);
|
|
142
|
+
span.recordException(error);
|
|
143
|
+
span.setStatus({ code: _api.SpanStatusCode.ERROR });
|
|
144
|
+
throw error;
|
|
145
|
+
} finally {
|
|
146
|
+
span.end();
|
|
147
|
+
}
|
|
81
148
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
149
|
+
);
|
|
150
|
+
if (openApiValidator.initializeHandlers) {
|
|
151
|
+
await openApiValidator.initializeHandlers(importedHandlers);
|
|
85
152
|
}
|
|
86
153
|
}
|
|
87
154
|
} else {
|
|
@@ -117,8 +184,9 @@ var getApplication = async (options) => {
|
|
|
117
184
|
} else {
|
|
118
185
|
app.use(middleware);
|
|
119
186
|
}
|
|
120
|
-
} catch (
|
|
121
|
-
|
|
187
|
+
} catch (error) {
|
|
188
|
+
_chunkBY65ZALYcjs.safeLog.warn(
|
|
189
|
+
logger,
|
|
122
190
|
"OpenAPI validator configuration provided but express-openapi-validator package is not installed. Install it with: npm install express-openapi-validator"
|
|
123
191
|
);
|
|
124
192
|
throw new Error(
|
|
@@ -133,14 +201,15 @@ var getApplication = async (options) => {
|
|
|
133
201
|
app.use(router);
|
|
134
202
|
}
|
|
135
203
|
if (!disableProblemDetailsMiddleware)
|
|
136
|
-
app.use(problemDetailsMiddleware(mapError));
|
|
204
|
+
app.use(problemDetailsMiddleware(mapError, logger));
|
|
205
|
+
_chunkBY65ZALYcjs.safeLog.info(logger, "Express application initialized");
|
|
137
206
|
return app;
|
|
138
207
|
};
|
|
139
208
|
var startAPI = (app, options = { port: 3e3 }) => {
|
|
140
|
-
const { port } = options;
|
|
209
|
+
const { port, logger } = options;
|
|
141
210
|
const server = _http2.default.createServer(app);
|
|
142
211
|
server.on("listening", () => {
|
|
143
|
-
|
|
212
|
+
_chunkBY65ZALYcjs.safeLog.info(logger, "Server up listening", { port });
|
|
144
213
|
});
|
|
145
214
|
return server.listen(port);
|
|
146
215
|
};
|
|
@@ -194,10 +263,34 @@ var getETagValueFromIfMatch = (request) => {
|
|
|
194
263
|
};
|
|
195
264
|
|
|
196
265
|
// src/handler.ts
|
|
266
|
+
|
|
267
|
+
var tracer2 = _api.trace.getTracer("@emmett-community/emmett-expressjs-with-openapi");
|
|
197
268
|
var on = (handle) => async (request, response, _next) => {
|
|
198
269
|
const setResponse = await Promise.resolve(handle(request));
|
|
199
270
|
return setResponse(response);
|
|
200
271
|
};
|
|
272
|
+
var tracedOn = (handle, options) => async (request, response, _next) => {
|
|
273
|
+
const spanName = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.spanName]), () => ( "emmett.http.handle_request"));
|
|
274
|
+
return tracer2.startActiveSpan(spanName, async (span) => {
|
|
275
|
+
try {
|
|
276
|
+
span.setAttribute("http.method", request.method);
|
|
277
|
+
const route = (_nullishCoalesce(request.baseUrl, () => ( ""))) + (_nullishCoalesce(_optionalChain([request, 'access', _4 => _4.route, 'optionalAccess', _5 => _5.path]), () => ( request.path)));
|
|
278
|
+
span.setAttribute("http.route", route);
|
|
279
|
+
const setResponse = await Promise.resolve(handle(request));
|
|
280
|
+
setResponse(response);
|
|
281
|
+
span.setAttribute("http.status_code", response.statusCode);
|
|
282
|
+
span.setStatus({
|
|
283
|
+
code: response.statusCode >= 400 ? _api.SpanStatusCode.ERROR : _api.SpanStatusCode.OK
|
|
284
|
+
});
|
|
285
|
+
} catch (error) {
|
|
286
|
+
span.recordException(error);
|
|
287
|
+
span.setStatus({ code: _api.SpanStatusCode.ERROR });
|
|
288
|
+
throw error;
|
|
289
|
+
} finally {
|
|
290
|
+
span.end();
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
};
|
|
201
294
|
var OK = (options) => (response) => {
|
|
202
295
|
send(response, 200, options);
|
|
203
296
|
};
|
|
@@ -271,7 +364,7 @@ var createFirebaseAuthSecurityHandlers = (options = {}) => {
|
|
|
271
364
|
const isAuthenticated = await runMiddleware(middleware, req);
|
|
272
365
|
if (!isAuthenticated) return false;
|
|
273
366
|
if (!scopes.length) return true;
|
|
274
|
-
const roles = _optionalChain([req, 'optionalAccess',
|
|
367
|
+
const roles = _optionalChain([req, 'optionalAccess', _6 => _6.auth, 'optionalAccess', _7 => _7.token, 'optionalAccess', _8 => _8[roleClaim]]);
|
|
275
368
|
if (!Array.isArray(roles)) return false;
|
|
276
369
|
return scopes.every((scope) => roles.includes(scope));
|
|
277
370
|
}
|
|
@@ -282,24 +375,24 @@ var createFirebaseAuthSecurityHandlers = (options = {}) => {
|
|
|
282
375
|
var createOpenApiValidatorOptions = (apiSpec, options) => {
|
|
283
376
|
return {
|
|
284
377
|
apiSpec,
|
|
285
|
-
validateRequests: _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
286
|
-
validateResponses: _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
287
|
-
validateSecurity: _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
288
|
-
validateFormats: _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
289
|
-
operationHandlers: _optionalChain([options, 'optionalAccess',
|
|
290
|
-
ignorePaths: _optionalChain([options, 'optionalAccess',
|
|
291
|
-
validateApiSpec: _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
292
|
-
$refParser: _optionalChain([options, 'optionalAccess',
|
|
293
|
-
serveSpec: _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
294
|
-
fileUploader: _optionalChain([options, 'optionalAccess',
|
|
295
|
-
initializeHandlers: _optionalChain([options, 'optionalAccess',
|
|
378
|
+
validateRequests: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _9 => _9.validateRequests]), () => ( true)),
|
|
379
|
+
validateResponses: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _10 => _10.validateResponses]), () => ( false)),
|
|
380
|
+
validateSecurity: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _11 => _11.validateSecurity]), () => ( true)),
|
|
381
|
+
validateFormats: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _12 => _12.validateFormats]), () => ( true)),
|
|
382
|
+
operationHandlers: _optionalChain([options, 'optionalAccess', _13 => _13.operationHandlers]),
|
|
383
|
+
ignorePaths: _optionalChain([options, 'optionalAccess', _14 => _14.ignorePaths]),
|
|
384
|
+
validateApiSpec: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _15 => _15.validateApiSpec]), () => ( true)),
|
|
385
|
+
$refParser: _optionalChain([options, 'optionalAccess', _16 => _16.$refParser]),
|
|
386
|
+
serveSpec: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _17 => _17.serveSpec]), () => ( false)),
|
|
387
|
+
fileUploader: _optionalChain([options, 'optionalAccess', _18 => _18.fileUploader]),
|
|
388
|
+
initializeHandlers: _optionalChain([options, 'optionalAccess', _19 => _19.initializeHandlers])
|
|
296
389
|
};
|
|
297
390
|
};
|
|
298
391
|
var isOpenApiValidatorAvailable = async () => {
|
|
299
392
|
try {
|
|
300
393
|
await Promise.resolve().then(() => _interopRequireWildcard(require("express-openapi-validator")));
|
|
301
394
|
return true;
|
|
302
|
-
} catch (
|
|
395
|
+
} catch (e) {
|
|
303
396
|
return false;
|
|
304
397
|
}
|
|
305
398
|
};
|
|
@@ -483,5 +576,7 @@ var ApiSpecification = {
|
|
|
483
576
|
|
|
484
577
|
|
|
485
578
|
|
|
486
|
-
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
exports.Accepted = Accepted; exports.ApiE2ESpecification = ApiE2ESpecification; exports.ApiSpecification = ApiSpecification; exports.BadRequest = BadRequest; exports.Conflict = Conflict; exports.Created = Created; exports.DefaultHttpProblemResponseOptions = DefaultHttpProblemResponseOptions; exports.DefaultHttpResponseOptions = DefaultHttpResponseOptions; exports.ETagErrors = ETagErrors; exports.Forbidden = Forbidden; exports.HeaderNames = HeaderNames; exports.HttpProblem = HttpProblem; exports.HttpResponse = HttpResponse; exports.NoContent = NoContent; exports.NotFound = NotFound; exports.OK = OK; exports.PreconditionFailed = PreconditionFailed; exports.WeakETagRegex = WeakETagRegex; exports.createFirebaseAuthSecurityHandlers = createFirebaseAuthSecurityHandlers; exports.createOpenApiValidatorOptions = createOpenApiValidatorOptions; exports.existingStream = existingStream; exports.expect = expect; exports.expectError = expectError; exports.expectNewEvents = expectNewEvents; exports.expectResponse = expectResponse; exports.getApplication = getApplication; exports.getETagFromIfMatch = getETagFromIfMatch; exports.getETagFromIfNotMatch = getETagFromIfNotMatch; exports.getETagValueFromIfMatch = getETagValueFromIfMatch; exports.getWeakETagValue = getWeakETagValue; exports.isOpenApiValidatorAvailable = isOpenApiValidatorAvailable; exports.isWeakETag = isWeakETag; exports.on = on; exports.registerHandlerModule = _chunkMRSGTROWcjs.registerHandlerModule; exports.safeLog = _chunkBY65ZALYcjs.safeLog; exports.send = send; exports.sendAccepted = sendAccepted; exports.sendCreated = sendCreated; exports.sendProblem = sendProblem; exports.setETag = setETag; exports.startAPI = startAPI; exports.toWeakETag = toWeakETag; exports.tracedOn = tracedOn;
|
|
487
582
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/emmett-expressjs-with-openapi/emmett-expressjs-with-openapi/dist/index.cjs","../src/index.ts","../src/application.ts","../src/middlewares/problemDetailsMiddleware.ts","../src/etag.ts","../src/handler.ts","../src/openapi/firebase-auth.ts","../src/openapi/index.ts","../src/responses.ts","../src/testing/apiE2ESpecification.ts","../src/testing/apiSpecification.ts"],"names":["require","ETagErrors"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACPA,gCAAO;ADSP;AACA;AEVA;AACE;AAAA,oFAGK;AACP;AACA,wEAAiB;AACjB,gCAA8B;AFU9B;AACA;AGjBA,0DAAgC;AAGzB,IAAM,yBAAA,EACX,CAAC,QAAA,EAAA,GACD,CACE,KAAA,EACA,OAAA,EACA,QAAA,EACA,KAAA,EAAA,GACS;AACT,EAAA,IAAI,cAAA;AAEJ,EAAA,GAAA,CAAI,QAAA,EAAU,eAAA,EAAiB,QAAA,CAAS,KAAA,EAAO,OAAO,CAAA;AAEtD,EAAA,eAAA,mBACE,cAAA,UAAkB,mCAAA,CAAoC,KAAK,GAAA;AAE7D,EAAA,WAAA,CAAY,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A;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/emmett-expressjs-with-openapi/emmett-expressjs-with-openapi/dist/index.cjs","sourcesContent":[null,"import 'express-async-errors';\n\nexport * from './application';\nexport * from './etag';\nexport * from './handler';\nexport * from './openapi';\nexport * from './responses';\nexport * from './testing';\nexport { registerHandlerModule } from './internal/esm-resolver';\n","import express, {\n Router,\n type Application,\n type RequestHandler,\n} from 'express';\nimport 'express-async-errors';\nimport http from 'http';\nimport { createRequire } from 'node:module';\nimport { problemDetailsMiddleware } from './middlewares/problemDetailsMiddleware';\nimport type { OpenApiValidatorOptions } from './openapi';\nimport type { ErrorToProblemDetailsMapping } from './responses';\n\n// #region web-api-setup\nexport type WebApiSetup = (router: Router) => void;\n// #endregion web-api-setup\n\nexport type ApplicationOptions = {\n apis?: WebApiSetup[];\n mapError?: ErrorToProblemDetailsMapping;\n enableDefaultExpressEtag?: boolean;\n disableJsonMiddleware?: boolean;\n disableUrlEncodingMiddleware?: boolean;\n disableProblemDetailsMiddleware?: boolean;\n /**\n * Optional OpenAPI validator configuration.\n * When provided, enables request/response validation against an OpenAPI specification.\n * Requires the 'express-openapi-validator' package to be installed.\n *\n * @see https://github.com/cdimascio/express-openapi-validator\n * @example\n * ```typescript\n * import { getApplication, createOpenApiValidatorOptions } from '@event-driven-io/emmett-expressjs';\n *\n * type AppDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * };\n *\n * const app = await getApplication({\n * openApiValidator: createOpenApiValidatorOptions<AppDeps>('./openapi.yaml', {\n * validateResponses: true,\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(deps.eventStore, deps.messageBus);\n * }\n * })\n * });\n * ```\n */\n openApiValidator?: OpenApiValidatorOptions;\n};\n\nexport const getApplication = async (options: ApplicationOptions) => {\n const app: Application = express();\n\n const {\n apis,\n mapError,\n enableDefaultExpressEtag,\n disableJsonMiddleware,\n disableUrlEncodingMiddleware,\n disableProblemDetailsMiddleware,\n openApiValidator,\n } = options;\n\n const router = Router();\n\n // disabling default etag behaviour\n // to use etags in if-match and if-not-match headers\n app.set('etag', enableDefaultExpressEtag ?? false);\n\n // add json middleware\n if (!disableJsonMiddleware) app.use(express.json());\n\n // enable url encoded urls and bodies\n if (!disableUrlEncodingMiddleware)\n app.use(\n express.urlencoded({\n extended: true,\n }),\n );\n\n // add OpenAPI validator middleware if configured\n if (openApiValidator) {\n // Activate ESM resolver if operationHandlers are configured\n // This ensures handler modules are loaded via ESM import() instead of CJS require(),\n // preventing dual module loading issues when using TypeScript runtimes (tsx, ts-node)\n if (openApiValidator.operationHandlers) {\n const { activateESMResolver } = await import(\n './internal/esm-resolver.js'\n );\n activateESMResolver();\n\n // NEW: Auto-discover and import handler modules from OpenAPI spec\n const handlersBasePath =\n typeof openApiValidator.operationHandlers === 'string'\n ? openApiValidator.operationHandlers\n : openApiValidator.operationHandlers.basePath;\n\n if (handlersBasePath) {\n const { extractHandlerModules } = await import(\n './internal/openapi-parser.js'\n );\n const { importAndRegisterHandlers } = await import(\n './internal/handler-importer.js'\n );\n\n try {\n // Parse OpenAPI spec to find handler modules\n const modules = await extractHandlerModules(\n openApiValidator.apiSpec,\n handlersBasePath,\n );\n\n // Dynamically import and register all handler modules\n const importedHandlers = await importAndRegisterHandlers(modules);\n\n // Call user's initializeHandlers callback with imported modules\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers(importedHandlers);\n }\n } catch (error) {\n console.error('Failed to auto-import handler modules:', error);\n throw error;\n }\n }\n } else {\n // No operationHandlers, just call initializeHandlers if provided\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers();\n }\n }\n\n try {\n const require = createRequire(import.meta.url);\n // express-openapi-validator exports a default with .middleware (ESM/CJS compatibility)\n const mod = require('express-openapi-validator') as Record<\n string,\n unknown\n >;\n const provider = (mod.default ?? mod) as Record<string, unknown>;\n\n if (typeof provider.middleware !== 'function') {\n throw new Error(\n 'Invalid express-openapi-validator module: missing middleware export',\n );\n }\n\n // Serve OpenAPI spec if configured\n if (openApiValidator.serveSpec) {\n if (typeof openApiValidator.apiSpec === 'string') {\n // If apiSpec is a file path, serve it as a static file\n app.use(\n openApiValidator.serveSpec,\n express.static(openApiValidator.apiSpec),\n );\n } else {\n // If apiSpec is an object, serve it as JSON\n app.get(openApiValidator.serveSpec, (_req, res) => {\n res.json(openApiValidator.apiSpec);\n });\n }\n }\n\n const factory = provider.middleware as (\n opts: OpenApiValidatorOptions,\n ) => RequestHandler | RequestHandler[];\n const middleware = factory(openApiValidator);\n if (Array.isArray(middleware)) {\n for (const m of middleware) app.use(m);\n } else {\n app.use(middleware);\n }\n } catch {\n console.warn(\n 'OpenAPI validator configuration provided but express-openapi-validator package is not installed. ' +\n 'Install it with: npm install express-openapi-validator',\n );\n throw new Error(\n 'express-openapi-validator package is required when openApiValidator option is used',\n );\n }\n }\n\n // Register API routes if provided\n if (apis) {\n for (const api of apis) {\n api(router);\n }\n app.use(router);\n }\n\n // add problem details middleware\n if (!disableProblemDetailsMiddleware)\n app.use(problemDetailsMiddleware(mapError));\n\n return app;\n};\n\nexport type StartApiOptions = {\n port?: number;\n};\n\nexport const startAPI = (\n app: Application,\n options: StartApiOptions = { port: 3000 },\n) => {\n const { port } = options;\n const server = http.createServer(app);\n\n server.on('listening', () => {\n console.info('server up listening');\n });\n\n return server.listen(port);\n};\n","import type { NextFunction, Request, Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { sendProblem, type ErrorToProblemDetailsMapping } from '..';\n\nexport const problemDetailsMiddleware =\n (mapError?: ErrorToProblemDetailsMapping) =>\n (\n error: Error,\n request: Request,\n response: Response,\n _next: NextFunction,\n ): void => {\n let problemDetails: ProblemDocument | undefined;\n\n if (mapError) problemDetails = mapError(error, request);\n\n problemDetails =\n problemDetails ?? defaultErrorToProblemDetailsMapping(error);\n\n sendProblem(response, problemDetails.status, { problem: problemDetails });\n };\n\nexport const defaultErrorToProblemDetailsMapping = (\n error: Error,\n): ProblemDocument => {\n let statusCode = 500;\n\n // Prefer standard `status` code if present (e.g., express-openapi-validator)\n const errObj = error as unknown as Record<string, unknown>;\n const maybeStatus = errObj['status'];\n if (\n typeof maybeStatus === 'number' &&\n maybeStatus >= 100 &&\n maybeStatus < 600\n ) {\n statusCode = maybeStatus;\n }\n\n const maybeErrorCode = errObj['errorCode'];\n if (\n typeof maybeErrorCode === 'number' &&\n maybeErrorCode >= 100 &&\n maybeErrorCode < 600\n ) {\n statusCode = maybeErrorCode;\n }\n\n return new ProblemDocument({\n detail: error.message,\n status: statusCode,\n });\n};\n","import { type Brand } from '@event-driven-io/emmett';\nimport type { Request, Response } from 'express';\n\n//////////////////////////////////////\n/// ETAG\n//////////////////////////////////////\n\nexport const HeaderNames = {\n IF_MATCH: 'if-match',\n IF_NOT_MATCH: 'if-not-match',\n ETag: 'etag',\n};\n\nexport type WeakETag = Brand<`W/${string}`, 'ETag'>;\nexport type ETag = Brand<string, 'ETag'>;\n\nexport const WeakETagRegex = /W\\/\"(-?\\d+.*)\"/;\n\nexport const enum ETagErrors {\n WRONG_WEAK_ETAG_FORMAT = 'WRONG_WEAK_ETAG_FORMAT',\n MISSING_IF_MATCH_HEADER = 'MISSING_IF_MATCH_HEADER',\n MISSING_IF_NOT_MATCH_HEADER = 'MISSING_IF_NOT_MATCH_HEADER',\n}\n\nexport const isWeakETag = (etag: ETag): etag is WeakETag => {\n return WeakETagRegex.test(etag as string);\n};\n\nexport const getWeakETagValue = (etag: ETag): string => {\n const result = WeakETagRegex.exec(etag as string);\n if (result === null || result.length === 0) {\n throw new Error(ETagErrors.WRONG_WEAK_ETAG_FORMAT);\n }\n return result[1]!;\n};\n\nexport const toWeakETag = (value: number | bigint | string): WeakETag => {\n return `W/\"${value}\"` as WeakETag;\n};\n\nexport const getETagFromIfMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return etag as ETag;\n};\n\nexport const getETagFromIfNotMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_NOT_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return (Array.isArray(etag) ? etag[0] : etag) as ETag;\n};\n\nexport const setETag = (response: Response, etag: ETag): void => {\n response.setHeader(HeaderNames.ETag, etag as string);\n};\n\nexport const getETagValueFromIfMatch = (request: Request): string => {\n const eTagValue: ETag = getETagFromIfMatch(request);\n\n return isWeakETag(eTagValue)\n ? getWeakETagValue(eTagValue)\n : (eTagValue as string);\n};\n","import { type NextFunction, type Request, type Response } from 'express';\nimport {\n send,\n sendAccepted,\n sendCreated,\n sendProblem,\n type AcceptedHttpResponseOptions,\n type CreatedHttpResponseOptions,\n type HttpProblemResponseOptions,\n type HttpResponseOptions,\n type NoContentHttpResponseOptions,\n} from '.';\n\n// #region httpresponse-on\nexport type HttpResponse = (response: Response) => void;\n\nexport type HttpHandler<RequestType extends Request> = (\n request: RequestType,\n) => Promise<HttpResponse> | HttpResponse;\n\nexport const on =\n <RequestType extends Request>(handle: HttpHandler<RequestType>) =>\n async (\n request: RequestType,\n response: Response,\n _next: NextFunction,\n ): Promise<void> => {\n const setResponse = await Promise.resolve(handle(request));\n\n return setResponse(response);\n };\n// #endregion httpresponse-on\n\nexport const OK =\n (options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, 200, options);\n };\n\nexport const Created =\n (options: CreatedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendCreated(response, options);\n };\n\nexport const Accepted =\n (options: AcceptedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendAccepted(response, options);\n };\n\nexport const NoContent = (\n options?: NoContentHttpResponseOptions,\n): HttpResponse => HttpResponse(204, options);\n\nexport const HttpResponse =\n (statusCode: number, options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, statusCode, options);\n };\n\n/////////////////////\n// ERRORS\n/////////////////////\n\nexport const BadRequest = (\n options?: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(400, options);\n\nexport const Forbidden = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(403, options);\n\nexport const NotFound = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(404, options);\n\nexport const Conflict = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(409, options);\n\nexport const PreconditionFailed = (\n options: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(412, options);\n\nexport const HttpProblem =\n (statusCode: number, options?: HttpProblemResponseOptions): HttpResponse =>\n (response: Response) => {\n sendProblem(response, statusCode, options);\n };\n","import type { SecurityHandlers } from './index';\n\ntype AuthClient = {\n verifyIdToken: (token: string) => Promise<unknown>;\n};\n\nexport type FirebaseAuthSecurityOptions = {\n /**\n * Name of the OpenAPI security scheme to attach the handler to.\n * Defaults to \"bearerAuth\".\n */\n securitySchemeName?: string;\n /**\n * Custom auth client for tests or alternate Firebase auth instances.\n */\n authClient?: AuthClient;\n /**\n * Token claim used for role-based checks when scopes are defined.\n * Defaults to \"roles\".\n */\n roleClaim?: string;\n};\n\ntype FirebaseAuthModule = {\n firebaseAuthMiddleware: (options?: { authClient?: AuthClient }) => (\n req: unknown,\n res: unknown,\n next: () => void,\n ) => Promise<void> | void;\n};\n\nconst loadFirebaseAuth = async (): Promise<FirebaseAuthModule> => {\n try {\n const mod = await import('@my-f-startup/firebase-auth-express');\n const provider = (mod as unknown as Record<string, unknown>).default ?? mod;\n const firebaseAuthMiddleware =\n (provider as Record<string, unknown>).firebaseAuthMiddleware;\n\n if (typeof firebaseAuthMiddleware !== 'function') {\n throw new Error(\n 'Invalid @my-f-startup/firebase-auth-express module: missing firebaseAuthMiddleware export',\n );\n }\n\n return provider as FirebaseAuthModule;\n } catch (error) {\n const message =\n '@my-f-startup/firebase-auth-express is required for createFirebaseAuthSecurityHandlers. ' +\n 'Install it with: npm install @my-f-startup/firebase-auth-express';\n throw new Error(message, { cause: error as Error });\n }\n};\n\nconst createNullResponse = () => {\n const res: Record<string, unknown> = {};\n res.status = () => res;\n res.json = () => res;\n res.send = () => res;\n res.end = () => res;\n res.set = () => res;\n return res;\n};\n\nconst runMiddleware = async (\n middleware: (req: unknown, res: unknown, next: () => void) => Promise<void> | void,\n req: unknown,\n): Promise<boolean> => {\n return new Promise((resolve) => {\n let nextCalled = false;\n const res = createNullResponse();\n const next = () => {\n nextCalled = true;\n resolve(true);\n };\n\n Promise.resolve(middleware(req, res, next))\n .then(() => {\n if (!nextCalled) resolve(false);\n })\n .catch(() => resolve(false));\n });\n};\n\nexport const createFirebaseAuthSecurityHandlers = (\n options: FirebaseAuthSecurityOptions = {},\n): SecurityHandlers => {\n const securitySchemeName = options.securitySchemeName ?? 'bearerAuth';\n const roleClaim = options.roleClaim ?? 'roles';\n\n return {\n [securitySchemeName]: async (req, scopes, _schema) => {\n const { firebaseAuthMiddleware } = await loadFirebaseAuth();\n const middleware = firebaseAuthMiddleware({\n authClient: options.authClient,\n });\n\n const isAuthenticated = await runMiddleware(middleware, req);\n if (!isAuthenticated) return false;\n\n if (!scopes.length) return true;\n\n const roles = (req as Record<string, any>)?.auth?.token?.[roleClaim];\n if (!Array.isArray(roles)) return false;\n\n return scopes.every((scope: string) => roles.includes(scope));\n },\n };\n};\n","/**\n * OpenAPI v3 Document type (to avoid requiring express-openapi-validator types directly)\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type OpenAPIV3Document = any;\n\n/**\n * Imported handler modules, keyed by module name.\n * Automatically populated by the framework when operationHandlers is configured.\n */\nexport type ImportedHandlerModules = Record<string, any>;\n\n/**\n * Security handlers for custom authentication/authorization logic.\n * Maps security scheme names to handler functions.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n\nexport type SecurityHandlers = Record<\n string,\n (req: any, scopes: string[], schema: any) => boolean | Promise<boolean>\n>;\n\nexport * from './firebase-auth';\n\n/**\n * Configuration options for express-openapi-validator middleware.\n * This allows optional validation of API requests and responses against an OpenAPI specification.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/\n */\nexport type OpenApiValidatorOptions = {\n /**\n * Path to the OpenAPI specification file (JSON or YAML)\n * or an OpenAPI specification object.\n */\n apiSpec: string | OpenAPIV3Document;\n\n /**\n * Determines whether the validator should validate requests.\n * Can be a boolean or an object with detailed request validation options.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-requests/\n */\n validateRequests?:\n | boolean\n | {\n /**\n * Allow unknown query parameters (not defined in the spec).\n * @default false\n */\n allowUnknownQueryParameters?: boolean;\n /**\n * Coerce types in request parameters.\n * @default true\n */\n coerceTypes?: boolean | 'array';\n /**\n * Remove additional properties not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n };\n\n /**\n * Determines whether the validator should validate responses.\n * Can be a boolean or an object with detailed response validation options.\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-responses/\n */\n validateResponses?:\n | boolean\n | {\n /**\n * Remove additional properties from responses not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n /**\n * Coerce types in responses.\n * @default true\n */\n coerceTypes?: boolean;\n /**\n * Callback to handle response validation errors.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onError?: (error: any, body: any, req: any) => void;\n };\n\n /**\n * Determines whether the validator should validate security.\n * Can be a boolean or an object with security handlers.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n validateSecurity?:\n | boolean\n | {\n /**\n * Custom security handlers for authentication/authorization.\n */\n handlers?: SecurityHandlers;\n };\n\n /**\n * Defines how the validator should validate formats.\n * When true, uses ajv-formats for format validation.\n * When false, format validation is disabled.\n * Can also be 'fast' or 'full' for different validation modes.\n * @default true\n */\n validateFormats?: boolean | 'fast' | 'full';\n\n /**\n * The base path to the operation handlers directory.\n * When set to a path, automatically wires OpenAPI operations to handler functions\n * based on operationId or x-eov-operation-id.\n * When false, operation handlers are disabled (manual routing required).\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/guide-operation-handlers/\n */\n operationHandlers?:\n | string\n | false\n | {\n /**\n * Base path to operation handlers directory.\n */\n basePath?: string;\n /**\n * Resolver function to map operationId to handler module path.\n */\n resolver?: (\n handlersPath: string,\n route: string,\n apiDoc: OpenAPIV3Document,\n ) => string;\n };\n\n /**\n * Paths or pattern to ignore during validation.\n * @default undefined\n */\n ignorePaths?: RegExp | ((path: string) => boolean);\n\n /**\n * Validate the OpenAPI specification itself.\n * @default true\n */\n validateApiSpec?: boolean;\n\n /**\n * $ref parser configuration for handling OpenAPI references.\n * @default undefined\n */\n $refParser?: {\n mode: 'bundle' | 'dereference';\n };\n\n /**\n * Serve the OpenAPI specification at a specific path.\n * When set to a string, the spec will be served at that path.\n * When false, the spec will not be served.\n * @default false\n * @example '/api-docs/openapi.json'\n */\n serveSpec?: string | false;\n\n /**\n * File upload configuration options.\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-file-uploads/\n */\n fileUploader?:\n | boolean\n | {\n /**\n * Destination directory for uploaded files.\n */\n dest?: string;\n /**\n * File size limit in bytes.\n */\n limits?: {\n fileSize?: number;\n files?: number;\n };\n };\n\n /**\n * Optional callback to initialize operation handlers with dependencies.\n * Called before the OpenAPI validator middleware is configured.\n *\n * The framework automatically imports handler modules referenced in your\n * OpenAPI spec (via x-eov-operation-handler) and passes them as the first parameter.\n *\n * @param handlers - Auto-imported handler modules, keyed by module name\n * @returns void or a Promise that resolves when initialization is complete\n *\n * @example\n * ```typescript\n * // With automatic import (recommended)\n * initializeHandlers: async (handlers) => {\n * handlers.shoppingCarts.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n *\n * // Manual import (still supported for backward compatibility)\n * import * as handlersModule from './handlers/shoppingCarts';\n * import { registerHandlerModule } from '@emmett-community/emmett-expressjs-with-openapi';\n * initializeHandlers: () => {\n * const handlersPath = path.join(__dirname, './handlers/shoppingCarts');\n * registerHandlerModule(handlersPath, handlersModule);\n * handlersModule.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n * ```\n */\n initializeHandlers?: (\n handlers?: ImportedHandlerModules,\n ) => void | Promise<void>;\n};\n\n/**\n * Helper function to create OpenAPI validator configuration with sensible defaults.\n *\n * @param apiSpec - Path to OpenAPI spec file or OpenAPI document object\n * @param options - Additional validator options\n * @returns Complete OpenApiValidatorOptions configuration\n *\n * @example\n * ```typescript\n * // Basic usage with default options\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml');\n *\n * // With response validation enabled\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateResponses: true\n * });\n *\n * // With custom security handlers\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateSecurity: {\n * handlers: {\n * bearerAuth: async (req, scopes) => {\n * // Custom authentication logic\n * return true;\n * }\n * }\n * }\n * });\n *\n * // Serving the spec at /api-docs\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * serveSpec: '/api-docs/openapi.json'\n * });\n *\n * // With dependency injection for operation handlers\n * type ShoppingCartDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * getUnitPrice: (productId: string) => Promise<number>;\n * getCurrentTime: () => Date;\n * };\n *\n * const validatorOptions = createOpenApiValidatorOptions<ShoppingCartDeps>(\n * './openapi.yaml',\n * {\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(\n * deps.eventStore,\n * deps.messageBus,\n * deps.getUnitPrice,\n * deps.getCurrentTime\n * );\n * }\n * }\n * );\n *\n * const app = getApplication({\n * apis: [myApi],\n * openApiValidator: validatorOptions\n * });\n * ```\n */\nexport const createOpenApiValidatorOptions = (\n apiSpec: string | OpenAPIV3Document,\n options?: Partial<Omit<OpenApiValidatorOptions, 'apiSpec'>>,\n): OpenApiValidatorOptions => {\n return {\n apiSpec,\n validateRequests: options?.validateRequests ?? true,\n validateResponses: options?.validateResponses ?? false,\n validateSecurity: options?.validateSecurity ?? true,\n validateFormats: options?.validateFormats ?? true,\n operationHandlers: options?.operationHandlers,\n ignorePaths: options?.ignorePaths,\n validateApiSpec: options?.validateApiSpec ?? true,\n $refParser: options?.$refParser,\n serveSpec: options?.serveSpec ?? false,\n fileUploader: options?.fileUploader,\n initializeHandlers: options?.initializeHandlers,\n };\n};\n\n/**\n * Type guard to check if express-openapi-validator is available\n */\nexport const isOpenApiValidatorAvailable = async (): Promise<boolean> => {\n try {\n await import('express-openapi-validator');\n return true;\n } catch {\n return false;\n }\n};\n","import { type Request, type Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { setETag, type ETag } from './etag';\n\nexport type ErrorToProblemDetailsMapping = (\n error: Error,\n request: Request,\n) => ProblemDocument | undefined;\n\nexport type HttpResponseOptions = {\n body?: unknown;\n location?: string;\n eTag?: ETag;\n};\nexport const DefaultHttpResponseOptions: HttpResponseOptions = {};\n\nexport type HttpProblemResponseOptions = {\n location?: string;\n eTag?: ETag;\n} & Omit<HttpResponseOptions, 'body'> &\n (\n | {\n problem: ProblemDocument;\n }\n | { problemDetails: string }\n );\nexport const DefaultHttpProblemResponseOptions: HttpProblemResponseOptions = {\n problemDetails: 'Error occured!',\n};\n\nexport type CreatedHttpResponseOptions = (\n | {\n createdId: string;\n }\n | {\n createdId?: string;\n url: string;\n }\n) &\n HttpResponseOptions;\n\nexport const sendCreated = (\n response: Response,\n { eTag, ...options }: CreatedHttpResponseOptions,\n): void =>\n send(response, 201, {\n location:\n 'url' in options\n ? options.url\n : `${response.req.url}/${options.createdId}`,\n body: 'createdId' in options ? { id: options.createdId } : undefined,\n eTag,\n });\n\nexport type AcceptedHttpResponseOptions = {\n location: string;\n} & HttpResponseOptions;\n\nexport const sendAccepted = (\n response: Response,\n options: AcceptedHttpResponseOptions,\n): void => send(response, 202, options);\n\nexport type NoContentHttpResponseOptions = Omit<HttpResponseOptions, 'body'>;\n\nexport const send = (\n response: Response,\n statusCode: number,\n options?: HttpResponseOptions,\n): void => {\n const { location, body, eTag } = options ?? DefaultHttpResponseOptions;\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n if (body) {\n response.statusCode = statusCode;\n response.send(body);\n } else {\n response.sendStatus(statusCode);\n }\n};\n\nexport const sendProblem = (\n response: Response,\n statusCode: number,\n options?: HttpProblemResponseOptions,\n): void => {\n options = options ?? DefaultHttpProblemResponseOptions;\n\n const { location, eTag } = options;\n\n const problemDetails =\n 'problem' in options\n ? options.problem\n : new ProblemDocument({\n detail: options.problemDetails,\n status: statusCode,\n });\n\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n response.setHeader('Content-Type', 'application/problem+json');\n\n response.statusCode = statusCode;\n response.json(problemDetails);\n};\n","import supertest, { type Response } from 'supertest';\n\nimport type { EventStore } from '@event-driven-io/emmett';\nimport assert from 'assert';\nimport type { Application } from 'express';\nimport type { TestRequest } from './apiSpecification';\n\nexport type E2EResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiE2ESpecificationAssert = [E2EResponseAssert];\n\nexport type ApiE2ESpecification = (...givenRequests: TestRequest[]) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiE2ESpecificationAssert) => Promise<void>;\n };\n};\n\nexport const ApiE2ESpecification = {\n for: <Store extends EventStore = EventStore>(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiE2ESpecification => {\n {\n return (...givenRequests: TestRequest[]) => {\n const eventStore = getEventStore();\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const requestFn of givenRequests) {\n await requestFn(supertest(application));\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiE2ESpecificationAssert,\n ): Promise<void> => {\n const response = await handle();\n\n verify.forEach((assertion) => {\n const succeeded = assertion(response);\n\n if (succeeded === false) assert.fail();\n });\n },\n };\n },\n };\n };\n }\n },\n};\n","import {\n WrapEventStore,\n assertEqual,\n assertFails,\n assertMatches,\n type Event,\n type EventStore,\n type TestEventStream,\n} from '@event-driven-io/emmett';\nimport { type Application } from 'express';\nimport type { ProblemDocument } from 'http-problem-details';\nimport type { Response, Test } from 'supertest';\nimport supertest from 'supertest';\nimport type TestAgent from 'supertest/lib/agent';\n\n////////////////////////////////\n/////////// Setup\n////////////////////////////////\n\nexport type TestRequest = (request: TestAgent<supertest.Test>) => Test;\n\nexport const existingStream = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\n////////////////////////////////\n/////////// Asserts\n////////////////////////////////\n\nexport type ResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiSpecificationAssert<EventType extends Event = Event> =\n | TestEventStream<EventType>[]\n | ResponseAssert\n | [ResponseAssert, ...TestEventStream<EventType>[]];\n\nexport const expect = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectNewEvents = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectResponse =\n <Body = unknown>(\n statusCode: number,\n options?: { body?: Body; headers?: { [index: string]: string } },\n ) =>\n (response: Response): void => {\n const { body, headers } = options ?? {};\n assertEqual(statusCode, response.statusCode, \"Response code doesn't match\");\n if (body) assertMatches(response.body, body);\n if (headers) assertMatches(response.headers, headers);\n };\n\nexport const expectError = (\n errorCode: number,\n problemDetails?: Partial<ProblemDocument>,\n) =>\n expectResponse(\n errorCode,\n problemDetails ? { body: problemDetails } : undefined,\n );\n\n////////////////////////////////\n/////////// Api Specification\n////////////////////////////////\n\nexport type ApiSpecification<EventType extends Event = Event> = (\n ...givenStreams: TestEventStream<EventType>[]\n) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiSpecificationAssert<EventType>) => Promise<void>;\n };\n};\n\nexport const ApiSpecification = {\n for: <\n EventType extends Event = Event,\n Store extends EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition> = EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition>\n >(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiSpecification<EventType> => {\n {\n return (...givenStreams: TestEventStream<EventType>[]) => {\n const eventStore = WrapEventStore(getEventStore());\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const [streamName, events] of givenStreams) {\n await eventStore.setup(streamName, events);\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiSpecificationAssert<EventType>,\n ): Promise<void> => {\n const response = await handle();\n\n if (typeof verify === 'function') {\n const succeeded = verify(response);\n\n if (succeeded === false) assertFails();\n } else if (Array.isArray(verify)) {\n const [first, ...rest] = verify;\n\n if (typeof first === 'function') {\n const succeeded = first(response);\n\n if (succeeded === false) assertFails();\n }\n\n const events = typeof first === 'function' ? rest : verify;\n\n assertMatches(\n Array.from(eventStore.appendedEvents.values()),\n events,\n );\n }\n },\n };\n },\n };\n };\n }\n },\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/emmett-expressjs-with-openapi/emmett-expressjs-with-openapi/dist/index.cjs","../src/index.ts","../src/application.ts","../src/middlewares/problemDetailsMiddleware.ts","../src/etag.ts","../src/handler.ts","../src/openapi/firebase-auth.ts","../src/openapi/index.ts","../src/responses.ts","../src/testing/apiE2ESpecification.ts","../src/testing/apiSpecification.ts"],"names":["require","options","ETagErrors","tracer","trace","SpanStatusCode"],"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A;AACF,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACF;AT4Z8C;AACA;AUrd9C;AACE;AACA;AACA;AACA;AAIK;AAIe;AAYW;AACP,EAAA;AAC1B;AAgBiC;AACP,EAAA;AAC1B;AAKiC;AACP,EAAA;AAC1B;AAOE;AACwC,EAAA;AACL,EAAA;AACU,EAAA;AACP,EAAA;AACtC;AAIA;AAGE,EAAA;AAC4C,EAAA;AAC9C;AAc8B;AAOI,EAAA;AAChC,IAAA;AAC4D,MAAA;AACtB,QAAA;AAE3B,QAAA;AACgC,UAAA;AACR,YAAA;AACC,cAAA;AAEI,cAAA;AACL,gBAAA;AACzB,cAAA;AAE8B,cAAA;AAChC,YAAA;AAEO,YAAA;AAGe,cAAA;AACY,gBAAA;AAER,gBAAA;AACK,kBAAA;AAEA,kBAAA;AACF,gBAAA;AACE,kBAAA;AAEJ,kBAAA;AACK,oBAAA;AAEC,oBAAA;AAC3B,kBAAA;AAEsB,kBAAA;AAEtB,kBAAA;AACwB,oBAAA;AACtB,oBAAA;AACF,kBAAA;AACF,gBAAA;AACF,cAAA;AACF,YAAA;AACF,UAAA;AACF,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACF;AVyY8C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/emmett-expressjs-with-openapi/emmett-expressjs-with-openapi/dist/index.cjs","sourcesContent":[null,"import 'express-async-errors';\n\nexport * from './application';\nexport * from './etag';\nexport * from './handler';\nexport * from './observability';\nexport * from './openapi';\nexport * from './responses';\nexport * from './testing';\nexport { registerHandlerModule } from './internal/esm-resolver';\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport express, {\n Router,\n type Application,\n type RequestHandler,\n} from 'express';\nimport 'express-async-errors';\nimport http from 'http';\nimport { createRequire } from 'node:module';\nimport { problemDetailsMiddleware } from './middlewares/problemDetailsMiddleware';\nimport { type Logger, type ObservabilityOptions, safeLog } from './observability';\nimport type { OpenApiValidatorOptions } from './openapi';\nimport type { ErrorToProblemDetailsMapping } from './responses';\n\nconst tracer = trace.getTracer('@emmett-community/emmett-expressjs-with-openapi');\n\n// #region web-api-setup\nexport type WebApiSetup = (router: Router) => void;\n// #endregion web-api-setup\n\n/**\n * Options forwarded to pino-http. Typed loosely to avoid hard dependency.\n *\n * @see https://github.com/pinojs/pino-http\n */\nexport type PinoHttpOptions = Record<string, unknown>;\n\nexport type ApplicationOptions = {\n apis?: WebApiSetup[];\n mapError?: ErrorToProblemDetailsMapping;\n enableDefaultExpressEtag?: boolean;\n disableJsonMiddleware?: boolean;\n disableUrlEncodingMiddleware?: boolean;\n disableProblemDetailsMiddleware?: boolean;\n /**\n * Optional Pino HTTP logger configuration.\n * When true, enables pino-http with defaults.\n * When an object, forwards the options to pino-http.\n * Requires the 'pino-http' package to be installed.\n *\n * @see https://github.com/pinojs/pino-http\n * @example\n * ```typescript\n * const app = await getApplication({\n * pinoHttp: true,\n * });\n *\n * const app = await getApplication({\n * pinoHttp: { autoLogging: false },\n * });\n * ```\n */\n pinoHttp?: boolean | PinoHttpOptions;\n /**\n * Optional OpenAPI validator configuration.\n * When provided, enables request/response validation against an OpenAPI specification.\n * Requires the 'express-openapi-validator' package to be installed.\n *\n * @see https://github.com/cdimascio/express-openapi-validator\n * @example\n * ```typescript\n * import { getApplication, createOpenApiValidatorOptions } from '@event-driven-io/emmett-expressjs';\n *\n * type AppDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * };\n *\n * const app = await getApplication({\n * openApiValidator: createOpenApiValidatorOptions<AppDeps>('./openapi.yaml', {\n * validateResponses: true,\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(deps.eventStore, deps.messageBus);\n * }\n * })\n * });\n * ```\n */\n openApiValidator?: OpenApiValidatorOptions;\n /**\n * Optional observability configuration for logging.\n * When not provided, the library operates silently (no logs).\n *\n * @example\n * ```typescript\n * import pino from 'pino';\n *\n * const logger = pino();\n *\n * const app = await getApplication({\n * observability: { logger },\n * });\n * ```\n */\n observability?: ObservabilityOptions;\n};\n\nexport const getApplication = async (options: ApplicationOptions) => {\n const app: Application = express();\n\n const {\n apis,\n mapError,\n enableDefaultExpressEtag,\n disableJsonMiddleware,\n disableUrlEncodingMiddleware,\n disableProblemDetailsMiddleware,\n pinoHttp,\n openApiValidator,\n observability,\n } = options;\n\n const logger = observability?.logger;\n\n safeLog.debug(logger, 'Initializing Express application', {\n hasApis: !!apis?.length,\n hasOpenApiValidator: !!openApiValidator,\n hasPinoHttp: !!pinoHttp,\n });\n\n const router = Router();\n\n // disabling default etag behaviour\n // to use etags in if-match and if-not-match headers\n app.set('etag', enableDefaultExpressEtag ?? false);\n\n // add Pino HTTP logger middleware if configured\n if (pinoHttp !== undefined && pinoHttp !== false) {\n try {\n const require = createRequire(import.meta.url);\n const mod = require('pino-http') as Record<string, unknown>;\n const provider = (mod.default ?? mod) as unknown;\n\n if (typeof provider !== 'function') {\n throw new Error('Invalid pino-http module: missing default export');\n }\n\n const options = pinoHttp === true ? undefined : pinoHttp;\n const middleware = (\n provider as (opts?: PinoHttpOptions) => RequestHandler\n )(options);\n app.use(middleware);\n } catch (error) {\n safeLog.warn(\n logger,\n 'Pino HTTP configuration provided but pino-http package is not installed. Install it with: npm install pino-http',\n );\n throw new Error(\n 'pino-http package is required when pinoHttp option is used',\n );\n }\n }\n\n // add json middleware\n if (!disableJsonMiddleware) app.use(express.json());\n\n // enable url encoded urls and bodies\n if (!disableUrlEncodingMiddleware)\n app.use(\n express.urlencoded({\n extended: true,\n }),\n );\n\n // add OpenAPI validator middleware if configured\n if (openApiValidator) {\n // Activate ESM resolver if operationHandlers are configured\n // This ensures handler modules are loaded via ESM import() instead of CJS require(),\n // preventing dual module loading issues when using TypeScript runtimes (tsx, ts-node)\n if (openApiValidator.operationHandlers) {\n const { activateESMResolver } = await import(\n './internal/esm-resolver.js'\n );\n activateESMResolver();\n\n // NEW: Auto-discover and import handler modules from OpenAPI spec\n const handlersBasePath =\n typeof openApiValidator.operationHandlers === 'string'\n ? openApiValidator.operationHandlers\n : openApiValidator.operationHandlers.basePath;\n\n if (handlersBasePath) {\n const { extractHandlerModules } = await import(\n './internal/openapi-parser.js'\n );\n const { importAndRegisterHandlers } = await import(\n './internal/handler-importer.js'\n );\n\n // Parse OpenAPI spec to find handler modules\n const modules = await tracer.startActiveSpan(\n 'emmett.openapi.parse_spec',\n async (span) => {\n try {\n const result = await extractHandlerModules(\n openApiValidator.apiSpec,\n handlersBasePath,\n logger,\n );\n span.setAttribute('emmett.handlers.count', result.length);\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n },\n );\n\n // Dynamically import and register all handler modules\n const importedHandlers = await tracer.startActiveSpan(\n 'emmett.http.import_handlers',\n async (span) => {\n try {\n const result = await importAndRegisterHandlers(modules, logger);\n span.setAttribute(\n 'emmett.handlers.count',\n Object.keys(result).length,\n );\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n safeLog.error(logger, 'Failed to auto-import handler modules', error);\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n },\n );\n\n // Call user's initializeHandlers callback with imported modules\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers(importedHandlers);\n }\n }\n } else {\n // No operationHandlers, just call initializeHandlers if provided\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers();\n }\n }\n\n try {\n const require = createRequire(import.meta.url);\n // express-openapi-validator exports a default with .middleware (ESM/CJS compatibility)\n const mod = require('express-openapi-validator') as Record<\n string,\n unknown\n >;\n const provider = (mod.default ?? mod) as Record<string, unknown>;\n\n if (typeof provider.middleware !== 'function') {\n throw new Error(\n 'Invalid express-openapi-validator module: missing middleware export',\n );\n }\n\n // Serve OpenAPI spec if configured\n if (openApiValidator.serveSpec) {\n if (typeof openApiValidator.apiSpec === 'string') {\n // If apiSpec is a file path, serve it as a static file\n app.use(\n openApiValidator.serveSpec,\n express.static(openApiValidator.apiSpec),\n );\n } else {\n // If apiSpec is an object, serve it as JSON\n app.get(openApiValidator.serveSpec, (_req, res) => {\n res.json(openApiValidator.apiSpec);\n });\n }\n }\n\n const factory = provider.middleware as (\n opts: OpenApiValidatorOptions,\n ) => RequestHandler | RequestHandler[];\n const middleware = factory(openApiValidator);\n if (Array.isArray(middleware)) {\n for (const m of middleware) app.use(m);\n } else {\n app.use(middleware);\n }\n } catch (error) {\n safeLog.warn(\n logger,\n 'OpenAPI validator configuration provided but express-openapi-validator package is not installed. Install it with: npm install express-openapi-validator',\n );\n throw new Error(\n 'express-openapi-validator package is required when openApiValidator option is used',\n );\n }\n }\n\n // Register API routes if provided\n if (apis) {\n for (const api of apis) {\n api(router);\n }\n app.use(router);\n }\n\n // add problem details middleware\n if (!disableProblemDetailsMiddleware)\n app.use(problemDetailsMiddleware(mapError, logger));\n\n safeLog.info(logger, 'Express application initialized');\n\n return app;\n};\n\nexport type StartApiOptions = {\n port?: number;\n /**\n * Optional logger for lifecycle events.\n */\n logger?: Logger;\n};\n\nexport const startAPI = (\n app: Application,\n options: StartApiOptions = { port: 3000 },\n) => {\n const { port, logger } = options;\n const server = http.createServer(app);\n\n server.on('listening', () => {\n safeLog.info(logger, 'Server up listening', { port });\n });\n\n return server.listen(port);\n};\n","import type { NextFunction, Request, Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { sendProblem, type ErrorToProblemDetailsMapping } from '..';\nimport { type Logger, safeLog } from '../observability';\n\nexport const problemDetailsMiddleware =\n (mapError?: ErrorToProblemDetailsMapping, logger?: Logger) =>\n (\n error: Error,\n request: Request,\n response: Response,\n _next: NextFunction,\n ): void => {\n safeLog.error(logger, 'Request error', error);\n\n let problemDetails: ProblemDocument | undefined;\n\n if (mapError) problemDetails = mapError(error, request);\n\n problemDetails =\n problemDetails ?? defaultErrorToProblemDetailsMapping(error);\n\n sendProblem(response, problemDetails.status, { problem: problemDetails });\n };\n\nexport const defaultErrorToProblemDetailsMapping = (\n error: Error,\n): ProblemDocument => {\n let statusCode = 500;\n\n // Prefer standard `status` code if present (e.g., express-openapi-validator)\n const errObj = error as unknown as Record<string, unknown>;\n const maybeStatus = errObj['status'];\n if (\n typeof maybeStatus === 'number' &&\n maybeStatus >= 100 &&\n maybeStatus < 600\n ) {\n statusCode = maybeStatus;\n }\n\n const maybeErrorCode = errObj['errorCode'];\n if (\n typeof maybeErrorCode === 'number' &&\n maybeErrorCode >= 100 &&\n maybeErrorCode < 600\n ) {\n statusCode = maybeErrorCode;\n }\n\n return new ProblemDocument({\n detail: error.message,\n status: statusCode,\n });\n};\n","import { type Brand } from '@event-driven-io/emmett';\nimport type { Request, Response } from 'express';\n\n//////////////////////////////////////\n/// ETAG\n//////////////////////////////////////\n\nexport const HeaderNames = {\n IF_MATCH: 'if-match',\n IF_NOT_MATCH: 'if-not-match',\n ETag: 'etag',\n};\n\nexport type WeakETag = Brand<`W/${string}`, 'ETag'>;\nexport type ETag = Brand<string, 'ETag'>;\n\nexport const WeakETagRegex = /W\\/\"(-?\\d+.*)\"/;\n\nexport const enum ETagErrors {\n WRONG_WEAK_ETAG_FORMAT = 'WRONG_WEAK_ETAG_FORMAT',\n MISSING_IF_MATCH_HEADER = 'MISSING_IF_MATCH_HEADER',\n MISSING_IF_NOT_MATCH_HEADER = 'MISSING_IF_NOT_MATCH_HEADER',\n}\n\nexport const isWeakETag = (etag: ETag): etag is WeakETag => {\n return WeakETagRegex.test(etag as string);\n};\n\nexport const getWeakETagValue = (etag: ETag): string => {\n const result = WeakETagRegex.exec(etag as string);\n if (result === null || result.length === 0) {\n throw new Error(ETagErrors.WRONG_WEAK_ETAG_FORMAT);\n }\n return result[1]!;\n};\n\nexport const toWeakETag = (value: number | bigint | string): WeakETag => {\n return `W/\"${value}\"` as WeakETag;\n};\n\nexport const getETagFromIfMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return etag as ETag;\n};\n\nexport const getETagFromIfNotMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_NOT_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return (Array.isArray(etag) ? etag[0] : etag) as ETag;\n};\n\nexport const setETag = (response: Response, etag: ETag): void => {\n response.setHeader(HeaderNames.ETag, etag as string);\n};\n\nexport const getETagValueFromIfMatch = (request: Request): string => {\n const eTagValue: ETag = getETagFromIfMatch(request);\n\n return isWeakETag(eTagValue)\n ? getWeakETagValue(eTagValue)\n : (eTagValue as string);\n};\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { type NextFunction, type Request, type Response } from 'express';\nimport {\n send,\n sendAccepted,\n sendCreated,\n sendProblem,\n type AcceptedHttpResponseOptions,\n type CreatedHttpResponseOptions,\n type HttpProblemResponseOptions,\n type HttpResponseOptions,\n type NoContentHttpResponseOptions,\n} from '.';\n\nconst tracer = trace.getTracer('@emmett-community/emmett-expressjs-with-openapi');\n\n// #region httpresponse-on\nexport type HttpResponse = (response: Response) => void;\n\nexport type HttpHandler<RequestType extends Request> = (\n request: RequestType,\n) => Promise<HttpResponse> | HttpResponse;\n\nexport const on =\n <RequestType extends Request>(handle: HttpHandler<RequestType>) =>\n async (\n request: RequestType,\n response: Response,\n _next: NextFunction,\n ): Promise<void> => {\n const setResponse = await Promise.resolve(handle(request));\n\n return setResponse(response);\n };\n// #endregion httpresponse-on\n\n/**\n * Options for the traced handler wrapper.\n */\nexport type TracedHandlerOptions = {\n /**\n * Custom span name. Defaults to 'emmett.http.handle_request'.\n */\n spanName?: string;\n};\n\n/**\n * Wraps an HTTP handler with OpenTelemetry tracing.\n * Creates a span that captures request method, route, and response status.\n *\n * If OpenTelemetry is not initialized by the application, spans are no-ops\n * with zero overhead.\n *\n * @example\n * ```typescript\n * router.post('/carts', tracedOn(async (req) => {\n * // Your handler logic\n * return Created({ createdId: cartId });\n * }));\n * ```\n */\nexport const tracedOn =\n <RequestType extends Request>(\n handle: HttpHandler<RequestType>,\n options?: TracedHandlerOptions,\n ) =>\n async (\n request: RequestType,\n response: Response,\n _next: NextFunction,\n ): Promise<void> => {\n const spanName = options?.spanName ?? 'emmett.http.handle_request';\n\n return tracer.startActiveSpan(spanName, async (span) => {\n try {\n span.setAttribute('http.method', request.method);\n\n const route =\n (request.baseUrl ?? '') +\n ((request.route as { path?: string })?.path ?? request.path);\n span.setAttribute('http.route', route);\n\n const setResponse = await Promise.resolve(handle(request));\n setResponse(response);\n\n span.setAttribute('http.status_code', response.statusCode);\n span.setStatus({\n code:\n response.statusCode >= 400 ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n });\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n });\n };\n\nexport const OK =\n (options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, 200, options);\n };\n\nexport const Created =\n (options: CreatedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendCreated(response, options);\n };\n\nexport const Accepted =\n (options: AcceptedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendAccepted(response, options);\n };\n\nexport const NoContent = (\n options?: NoContentHttpResponseOptions,\n): HttpResponse => HttpResponse(204, options);\n\nexport const HttpResponse =\n (statusCode: number, options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, statusCode, options);\n };\n\n/////////////////////\n// ERRORS\n/////////////////////\n\nexport const BadRequest = (\n options?: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(400, options);\n\nexport const Forbidden = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(403, options);\n\nexport const NotFound = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(404, options);\n\nexport const Conflict = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(409, options);\n\nexport const PreconditionFailed = (\n options: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(412, options);\n\nexport const HttpProblem =\n (statusCode: number, options?: HttpProblemResponseOptions): HttpResponse =>\n (response: Response) => {\n sendProblem(response, statusCode, options);\n };\n","import type { SecurityHandlers } from './index';\n\ntype AuthClient = {\n verifyIdToken: (token: string) => Promise<unknown>;\n};\n\nexport type FirebaseAuthSecurityOptions = {\n /**\n * Name of the OpenAPI security scheme to attach the handler to.\n * Defaults to \"bearerAuth\".\n */\n securitySchemeName?: string;\n /**\n * Custom auth client for tests or alternate Firebase auth instances.\n */\n authClient?: AuthClient;\n /**\n * Token claim used for role-based checks when scopes are defined.\n * Defaults to \"roles\".\n */\n roleClaim?: string;\n};\n\ntype FirebaseAuthModule = {\n firebaseAuthMiddleware: (options?: { authClient?: AuthClient }) => (\n req: unknown,\n res: unknown,\n next: () => void,\n ) => Promise<void> | void;\n};\n\nconst loadFirebaseAuth = async (): Promise<FirebaseAuthModule> => {\n try {\n const mod = await import('@my-f-startup/firebase-auth-express');\n const provider = (mod as unknown as Record<string, unknown>).default ?? mod;\n const firebaseAuthMiddleware =\n (provider as Record<string, unknown>).firebaseAuthMiddleware;\n\n if (typeof firebaseAuthMiddleware !== 'function') {\n throw new Error(\n 'Invalid @my-f-startup/firebase-auth-express module: missing firebaseAuthMiddleware export',\n );\n }\n\n return provider as FirebaseAuthModule;\n } catch (error) {\n const message =\n '@my-f-startup/firebase-auth-express is required for createFirebaseAuthSecurityHandlers. ' +\n 'Install it with: npm install @my-f-startup/firebase-auth-express';\n throw new Error(message, { cause: error as Error });\n }\n};\n\nconst createNullResponse = () => {\n const res: Record<string, unknown> = {};\n res.status = () => res;\n res.json = () => res;\n res.send = () => res;\n res.end = () => res;\n res.set = () => res;\n return res;\n};\n\nconst runMiddleware = async (\n middleware: (req: unknown, res: unknown, next: () => void) => Promise<void> | void,\n req: unknown,\n): Promise<boolean> => {\n return new Promise((resolve) => {\n let nextCalled = false;\n const res = createNullResponse();\n const next = () => {\n nextCalled = true;\n resolve(true);\n };\n\n Promise.resolve(middleware(req, res, next))\n .then(() => {\n if (!nextCalled) resolve(false);\n })\n .catch(() => resolve(false));\n });\n};\n\nexport const createFirebaseAuthSecurityHandlers = (\n options: FirebaseAuthSecurityOptions = {},\n): SecurityHandlers => {\n const securitySchemeName = options.securitySchemeName ?? 'bearerAuth';\n const roleClaim = options.roleClaim ?? 'roles';\n\n return {\n [securitySchemeName]: async (req, scopes, _schema) => {\n const { firebaseAuthMiddleware } = await loadFirebaseAuth();\n const middleware = firebaseAuthMiddleware({\n authClient: options.authClient,\n });\n\n const isAuthenticated = await runMiddleware(middleware, req);\n if (!isAuthenticated) return false;\n\n if (!scopes.length) return true;\n\n const roles = (req as Record<string, any>)?.auth?.token?.[roleClaim];\n if (!Array.isArray(roles)) return false;\n\n return scopes.every((scope: string) => roles.includes(scope));\n },\n };\n};\n","/**\n * OpenAPI v3 Document type (to avoid requiring express-openapi-validator types directly)\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type OpenAPIV3Document = any;\n\n/**\n * Imported handler modules, keyed by module name.\n * Automatically populated by the framework when operationHandlers is configured.\n */\nexport type ImportedHandlerModules = Record<string, any>;\n\n/**\n * Security handlers for custom authentication/authorization logic.\n * Maps security scheme names to handler functions.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n\nexport type SecurityHandlers = Record<\n string,\n (req: any, scopes: string[], schema: any) => boolean | Promise<boolean>\n>;\n\nexport * from './firebase-auth';\n\n/**\n * Configuration options for express-openapi-validator middleware.\n * This allows optional validation of API requests and responses against an OpenAPI specification.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/\n */\nexport type OpenApiValidatorOptions = {\n /**\n * Path to the OpenAPI specification file (JSON or YAML)\n * or an OpenAPI specification object.\n */\n apiSpec: string | OpenAPIV3Document;\n\n /**\n * Determines whether the validator should validate requests.\n * Can be a boolean or an object with detailed request validation options.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-requests/\n */\n validateRequests?:\n | boolean\n | {\n /**\n * Allow unknown query parameters (not defined in the spec).\n * @default false\n */\n allowUnknownQueryParameters?: boolean;\n /**\n * Coerce types in request parameters.\n * @default true\n */\n coerceTypes?: boolean | 'array';\n /**\n * Remove additional properties not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n };\n\n /**\n * Determines whether the validator should validate responses.\n * Can be a boolean or an object with detailed response validation options.\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-responses/\n */\n validateResponses?:\n | boolean\n | {\n /**\n * Remove additional properties from responses not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n /**\n * Coerce types in responses.\n * @default true\n */\n coerceTypes?: boolean;\n /**\n * Callback to handle response validation errors.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onError?: (error: any, body: any, req: any) => void;\n };\n\n /**\n * Determines whether the validator should validate security.\n * Can be a boolean or an object with security handlers.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n validateSecurity?:\n | boolean\n | {\n /**\n * Custom security handlers for authentication/authorization.\n */\n handlers?: SecurityHandlers;\n };\n\n /**\n * Defines how the validator should validate formats.\n * When true, uses ajv-formats for format validation.\n * When false, format validation is disabled.\n * Can also be 'fast' or 'full' for different validation modes.\n * @default true\n */\n validateFormats?: boolean | 'fast' | 'full';\n\n /**\n * The base path to the operation handlers directory.\n * When set to a path, automatically wires OpenAPI operations to handler functions\n * based on operationId or x-eov-operation-id.\n * When false, operation handlers are disabled (manual routing required).\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/guide-operation-handlers/\n */\n operationHandlers?:\n | string\n | false\n | {\n /**\n * Base path to operation handlers directory.\n */\n basePath?: string;\n /**\n * Resolver function to map operationId to handler module path.\n */\n resolver?: (\n handlersPath: string,\n route: string,\n apiDoc: OpenAPIV3Document,\n ) => string;\n };\n\n /**\n * Paths or pattern to ignore during validation.\n * @default undefined\n */\n ignorePaths?: RegExp | ((path: string) => boolean);\n\n /**\n * Validate the OpenAPI specification itself.\n * @default true\n */\n validateApiSpec?: boolean;\n\n /**\n * $ref parser configuration for handling OpenAPI references.\n * @default undefined\n */\n $refParser?: {\n mode: 'bundle' | 'dereference';\n };\n\n /**\n * Serve the OpenAPI specification at a specific path.\n * When set to a string, the spec will be served at that path.\n * When false, the spec will not be served.\n * @default false\n * @example '/api-docs/openapi.json'\n */\n serveSpec?: string | false;\n\n /**\n * File upload configuration options.\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-file-uploads/\n */\n fileUploader?:\n | boolean\n | {\n /**\n * Destination directory for uploaded files.\n */\n dest?: string;\n /**\n * File size limit in bytes.\n */\n limits?: {\n fileSize?: number;\n files?: number;\n };\n };\n\n /**\n * Optional callback to initialize operation handlers with dependencies.\n * Called before the OpenAPI validator middleware is configured.\n *\n * The framework automatically imports handler modules referenced in your\n * OpenAPI spec (via x-eov-operation-handler) and passes them as the first parameter.\n *\n * @param handlers - Auto-imported handler modules, keyed by module name\n * @returns void or a Promise that resolves when initialization is complete\n *\n * @example\n * ```typescript\n * // With automatic import (recommended)\n * initializeHandlers: async (handlers) => {\n * handlers.shoppingCarts.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n *\n * // Manual import (still supported for backward compatibility)\n * import * as handlersModule from './handlers/shoppingCarts';\n * import { registerHandlerModule } from '@emmett-community/emmett-expressjs-with-openapi';\n * initializeHandlers: () => {\n * const handlersPath = path.join(__dirname, './handlers/shoppingCarts');\n * registerHandlerModule(handlersPath, handlersModule);\n * handlersModule.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n * ```\n */\n initializeHandlers?: (\n handlers?: ImportedHandlerModules,\n ) => void | Promise<void>;\n};\n\n/**\n * Helper function to create OpenAPI validator configuration with sensible defaults.\n *\n * @param apiSpec - Path to OpenAPI spec file or OpenAPI document object\n * @param options - Additional validator options\n * @returns Complete OpenApiValidatorOptions configuration\n *\n * @example\n * ```typescript\n * // Basic usage with default options\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml');\n *\n * // With response validation enabled\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateResponses: true\n * });\n *\n * // With custom security handlers\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateSecurity: {\n * handlers: {\n * bearerAuth: async (req, scopes) => {\n * // Custom authentication logic\n * return true;\n * }\n * }\n * }\n * });\n *\n * // Serving the spec at /api-docs\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * serveSpec: '/api-docs/openapi.json'\n * });\n *\n * // With dependency injection for operation handlers\n * type ShoppingCartDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * getUnitPrice: (productId: string) => Promise<number>;\n * getCurrentTime: () => Date;\n * };\n *\n * const validatorOptions = createOpenApiValidatorOptions<ShoppingCartDeps>(\n * './openapi.yaml',\n * {\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(\n * deps.eventStore,\n * deps.messageBus,\n * deps.getUnitPrice,\n * deps.getCurrentTime\n * );\n * }\n * }\n * );\n *\n * const app = getApplication({\n * apis: [myApi],\n * openApiValidator: validatorOptions\n * });\n * ```\n */\nexport const createOpenApiValidatorOptions = (\n apiSpec: string | OpenAPIV3Document,\n options?: Partial<Omit<OpenApiValidatorOptions, 'apiSpec'>>,\n): OpenApiValidatorOptions => {\n return {\n apiSpec,\n validateRequests: options?.validateRequests ?? true,\n validateResponses: options?.validateResponses ?? false,\n validateSecurity: options?.validateSecurity ?? true,\n validateFormats: options?.validateFormats ?? true,\n operationHandlers: options?.operationHandlers,\n ignorePaths: options?.ignorePaths,\n validateApiSpec: options?.validateApiSpec ?? true,\n $refParser: options?.$refParser,\n serveSpec: options?.serveSpec ?? false,\n fileUploader: options?.fileUploader,\n initializeHandlers: options?.initializeHandlers,\n };\n};\n\n/**\n * Type guard to check if express-openapi-validator is available\n */\nexport const isOpenApiValidatorAvailable = async (): Promise<boolean> => {\n try {\n await import('express-openapi-validator');\n return true;\n } catch {\n return false;\n }\n};\n","import { type Request, type Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { setETag, type ETag } from './etag';\n\nexport type ErrorToProblemDetailsMapping = (\n error: Error,\n request: Request,\n) => ProblemDocument | undefined;\n\nexport type HttpResponseOptions = {\n body?: unknown;\n location?: string;\n eTag?: ETag;\n};\nexport const DefaultHttpResponseOptions: HttpResponseOptions = {};\n\nexport type HttpProblemResponseOptions = {\n location?: string;\n eTag?: ETag;\n} & Omit<HttpResponseOptions, 'body'> &\n (\n | {\n problem: ProblemDocument;\n }\n | { problemDetails: string }\n );\nexport const DefaultHttpProblemResponseOptions: HttpProblemResponseOptions = {\n problemDetails: 'Error occured!',\n};\n\nexport type CreatedHttpResponseOptions = (\n | {\n createdId: string;\n }\n | {\n createdId?: string;\n url: string;\n }\n) &\n HttpResponseOptions;\n\nexport const sendCreated = (\n response: Response,\n { eTag, ...options }: CreatedHttpResponseOptions,\n): void =>\n send(response, 201, {\n location:\n 'url' in options\n ? options.url\n : `${response.req.url}/${options.createdId}`,\n body: 'createdId' in options ? { id: options.createdId } : undefined,\n eTag,\n });\n\nexport type AcceptedHttpResponseOptions = {\n location: string;\n} & HttpResponseOptions;\n\nexport const sendAccepted = (\n response: Response,\n options: AcceptedHttpResponseOptions,\n): void => send(response, 202, options);\n\nexport type NoContentHttpResponseOptions = Omit<HttpResponseOptions, 'body'>;\n\nexport const send = (\n response: Response,\n statusCode: number,\n options?: HttpResponseOptions,\n): void => {\n const { location, body, eTag } = options ?? DefaultHttpResponseOptions;\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n if (body) {\n response.statusCode = statusCode;\n response.send(body);\n } else {\n response.sendStatus(statusCode);\n }\n};\n\nexport const sendProblem = (\n response: Response,\n statusCode: number,\n options?: HttpProblemResponseOptions,\n): void => {\n options = options ?? DefaultHttpProblemResponseOptions;\n\n const { location, eTag } = options;\n\n const problemDetails =\n 'problem' in options\n ? options.problem\n : new ProblemDocument({\n detail: options.problemDetails,\n status: statusCode,\n });\n\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n response.setHeader('Content-Type', 'application/problem+json');\n\n response.statusCode = statusCode;\n response.json(problemDetails);\n};\n","import supertest, { type Response } from 'supertest';\n\nimport type { EventStore } from '@event-driven-io/emmett';\nimport assert from 'assert';\nimport type { Application } from 'express';\nimport type { TestRequest } from './apiSpecification';\n\nexport type E2EResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiE2ESpecificationAssert = [E2EResponseAssert];\n\nexport type ApiE2ESpecification = (...givenRequests: TestRequest[]) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiE2ESpecificationAssert) => Promise<void>;\n };\n};\n\nexport const ApiE2ESpecification = {\n for: <Store extends EventStore = EventStore>(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiE2ESpecification => {\n {\n return (...givenRequests: TestRequest[]) => {\n const eventStore = getEventStore();\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const requestFn of givenRequests) {\n await requestFn(supertest(application));\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiE2ESpecificationAssert,\n ): Promise<void> => {\n const response = await handle();\n\n verify.forEach((assertion) => {\n const succeeded = assertion(response);\n\n if (succeeded === false) assert.fail();\n });\n },\n };\n },\n };\n };\n }\n },\n};\n","import {\n WrapEventStore,\n assertEqual,\n assertFails,\n assertMatches,\n type Event,\n type EventStore,\n type TestEventStream,\n} from '@event-driven-io/emmett';\nimport { type Application } from 'express';\nimport type { ProblemDocument } from 'http-problem-details';\nimport type { Response, Test } from 'supertest';\nimport supertest from 'supertest';\nimport type TestAgent from 'supertest/lib/agent';\n\n////////////////////////////////\n/////////// Setup\n////////////////////////////////\n\nexport type TestRequest = (request: TestAgent<supertest.Test>) => Test;\n\nexport const existingStream = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\n////////////////////////////////\n/////////// Asserts\n////////////////////////////////\n\nexport type ResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiSpecificationAssert<EventType extends Event = Event> =\n | TestEventStream<EventType>[]\n | ResponseAssert\n | [ResponseAssert, ...TestEventStream<EventType>[]];\n\nexport const expect = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectNewEvents = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectResponse =\n <Body = unknown>(\n statusCode: number,\n options?: { body?: Body; headers?: { [index: string]: string } },\n ) =>\n (response: Response): void => {\n const { body, headers } = options ?? {};\n assertEqual(statusCode, response.statusCode, \"Response code doesn't match\");\n if (body) assertMatches(response.body, body);\n if (headers) assertMatches(response.headers, headers);\n };\n\nexport const expectError = (\n errorCode: number,\n problemDetails?: Partial<ProblemDocument>,\n) =>\n expectResponse(\n errorCode,\n problemDetails ? { body: problemDetails } : undefined,\n );\n\n////////////////////////////////\n/////////// Api Specification\n////////////////////////////////\n\nexport type ApiSpecification<EventType extends Event = Event> = (\n ...givenStreams: TestEventStream<EventType>[]\n) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiSpecificationAssert<EventType>) => Promise<void>;\n };\n};\n\nexport const ApiSpecification = {\n for: <\n EventType extends Event = Event,\n Store extends EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition> = EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition>\n >(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiSpecification<EventType> => {\n {\n return (...givenStreams: TestEventStream<EventType>[]) => {\n const eventStore = WrapEventStore(getEventStore());\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const [streamName, events] of givenStreams) {\n await eventStore.setup(streamName, events);\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiSpecificationAssert<EventType>,\n ): Promise<void> => {\n const response = await handle();\n\n if (typeof verify === 'function') {\n const succeeded = verify(response);\n\n if (succeeded === false) assertFails();\n } else if (Array.isArray(verify)) {\n const [first, ...rest] = verify;\n\n if (typeof first === 'function') {\n const succeeded = first(response);\n\n if (succeeded === false) assertFails();\n }\n\n const events = typeof first === 'function' ? rest : verify;\n\n assertMatches(\n Array.from(eventStore.appendedEvents.values()),\n events,\n );\n }\n },\n };\n },\n };\n };\n }\n },\n};\n"]}
|