@emmett-community/emmett-expressjs-with-openapi 0.1.0 → 0.3.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/axcosta/Git/pessoal/oss/emmett-community/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/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,QAAA,EAAU,cAAA,CAAe,MAAA,EAAQ,EAAE,OAAA,EAAS,eAAe,CAAC,CAAA;AAC1E,CAAA;AAEK,IAAM,oCAAA,EAAsC,CACjD,KAAA,EAAA,GACoB;AACpB,EAAA,IAAI,WAAA,EAAa,GAAA;AAGjB,EAAA,MAAM,OAAA,EAAS,KAAA;AACf,EAAA,MAAM,YAAA,EAAc,MAAA,CAAO,QAAQ,CAAA;AACnC,EAAA,GAAA,CACE,OAAO,YAAA,IAAgB,SAAA,GACvB,YAAA,GAAe,IAAA,GACf,YAAA,EAAc,GAAA,EACd;AACA,IAAA,WAAA,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;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;ATkP8C;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":"/Users/axcosta/Git/pessoal/oss/emmett-community/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","/**\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\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"],"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,QAAA,EAAU,cAAA,CAAe,MAAA,EAAQ,EAAE,OAAA,EAAS,eAAe,CAAC,CAAA;AAC1E,CAAA;AAEK,IAAM,oCAAA,EAAsC,CACjD,KAAA,EAAA,GACoB;AACpB,EAAA,IAAI,WAAA,EAAa,GAAA;AAGjB,EAAA,MAAM,OAAA,EAAS,KAAA;AACf,EAAA,MAAM,YAAA,EAAc,MAAA,CAAO,QAAQ,CAAA;AACnC,EAAA,GAAA,CACE,OAAO,YAAA,IAAgB,SAAA,GACvB,YAAA,GAAe,IAAA,GACf,YAAA,EAAc,GAAA,EACd;AACA,IAAA,WAAA,EAAa,WAAA;AAAA,EACf;AAEA,EAAA,MAAM,eAAA,EAAiB,MAAA,CAAO,WAAW,CAAA;AACzC,EAAA,GAAA,CACE,OAAO,eAAA,IAAmB,SAAA,GAC1B,eAAA,GAAkB,IAAA,GAClB,eAAA,EAAiB,GAAA,EACjB;AACA,IAAA,WAAA,EAAa,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kBAAA;AACwB,oBAAA;AACtB,oBAAA;AACF,kBAAA;AACF,gBAAA;AACF,cAAA;AACF,YAAA;AACF,UAAA;AACF,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACF;AViU8C;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 './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\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\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 } = 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 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 {\n console.warn(\n 'Pino HTTP configuration provided but pino-http package is not installed. ' +\n '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 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"]}
package/dist/index.d.cts CHANGED
@@ -6,6 +6,27 @@ import { Brand, Event, TestEventStream, EventStore } from '@event-driven-io/emme
6
6
  import supertest, { Test, Response as Response$1 } from 'supertest';
7
7
  import TestAgent from 'supertest/lib/agent';
8
8
 
9
+ type AuthClient = {
10
+ verifyIdToken: (token: string) => Promise<unknown>;
11
+ };
12
+ type FirebaseAuthSecurityOptions = {
13
+ /**
14
+ * Name of the OpenAPI security scheme to attach the handler to.
15
+ * Defaults to "bearerAuth".
16
+ */
17
+ securitySchemeName?: string;
18
+ /**
19
+ * Custom auth client for tests or alternate Firebase auth instances.
20
+ */
21
+ authClient?: AuthClient;
22
+ /**
23
+ * Token claim used for role-based checks when scopes are defined.
24
+ * Defaults to "roles".
25
+ */
26
+ roleClaim?: string;
27
+ };
28
+ declare const createFirebaseAuthSecurityHandlers: (options?: FirebaseAuthSecurityOptions) => SecurityHandlers;
29
+
9
30
  /**
10
31
  * OpenAPI v3 Document type (to avoid requiring express-openapi-validator types directly)
11
32
  */
@@ -22,6 +43,7 @@ type ImportedHandlerModules = Record<string, any>;
22
43
  * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/
23
44
  */
24
45
  type SecurityHandlers = Record<string, (req: any, scopes: string[], schema: any) => boolean | Promise<boolean>>;
46
+
25
47
  /**
26
48
  * Configuration options for express-openapi-validator middleware.
27
49
  * This allows optional validation of API requests and responses against an OpenAPI specification.
@@ -310,6 +332,12 @@ declare const send: (response: Response, statusCode: number, options?: HttpRespo
310
332
  declare const sendProblem: (response: Response, statusCode: number, options?: HttpProblemResponseOptions) => void;
311
333
 
312
334
  type WebApiSetup = (router: Router) => void;
335
+ /**
336
+ * Options forwarded to pino-http. Typed loosely to avoid hard dependency.
337
+ *
338
+ * @see https://github.com/pinojs/pino-http
339
+ */
340
+ type PinoHttpOptions = Record<string, unknown>;
313
341
  type ApplicationOptions = {
314
342
  apis?: WebApiSetup[];
315
343
  mapError?: ErrorToProblemDetailsMapping;
@@ -317,6 +345,25 @@ type ApplicationOptions = {
317
345
  disableJsonMiddleware?: boolean;
318
346
  disableUrlEncodingMiddleware?: boolean;
319
347
  disableProblemDetailsMiddleware?: boolean;
348
+ /**
349
+ * Optional Pino HTTP logger configuration.
350
+ * When true, enables pino-http with defaults.
351
+ * When an object, forwards the options to pino-http.
352
+ * Requires the 'pino-http' package to be installed.
353
+ *
354
+ * @see https://github.com/pinojs/pino-http
355
+ * @example
356
+ * ```typescript
357
+ * const app = await getApplication({
358
+ * pinoHttp: true,
359
+ * });
360
+ *
361
+ * const app = await getApplication({
362
+ * pinoHttp: { autoLogging: false },
363
+ * });
364
+ * ```
365
+ */
366
+ pinoHttp?: boolean | PinoHttpOptions;
320
367
  /**
321
368
  * Optional OpenAPI validator configuration.
322
369
  * When provided, enables request/response validation against an OpenAPI specification.
@@ -437,4 +484,4 @@ declare const ApiE2ESpecification: {
437
484
  */
438
485
  declare const registerHandlerModule: (modulePath: string, moduleExports: any) => void;
439
486
 
440
- export { Accepted, type AcceptedHttpResponseOptions, ApiE2ESpecification, type ApiE2ESpecificationAssert, ApiSpecification, type ApiSpecificationAssert, type ApplicationOptions, BadRequest, Conflict, Created, type CreatedHttpResponseOptions, DefaultHttpProblemResponseOptions, DefaultHttpResponseOptions, type E2EResponseAssert, type ETag, ETagErrors, type ErrorToProblemDetailsMapping, Forbidden, HeaderNames, type HttpHandler, HttpProblem, type HttpProblemResponseOptions, HttpResponse, type HttpResponseOptions, type ImportedHandlerModules, NoContent, type NoContentHttpResponseOptions, NotFound, OK, type OpenAPIV3Document, type OpenApiValidatorOptions, PreconditionFailed, type ResponseAssert, type SecurityHandlers, type StartApiOptions, type TestRequest, type WeakETag, WeakETagRegex, type WebApiSetup, createOpenApiValidatorOptions, existingStream, expect, expectError, expectNewEvents, expectResponse, getApplication, getETagFromIfMatch, getETagFromIfNotMatch, getETagValueFromIfMatch, getWeakETagValue, isOpenApiValidatorAvailable, isWeakETag, on, registerHandlerModule, send, sendAccepted, sendCreated, sendProblem, setETag, startAPI, toWeakETag };
487
+ export { Accepted, type AcceptedHttpResponseOptions, ApiE2ESpecification, type ApiE2ESpecificationAssert, ApiSpecification, type ApiSpecificationAssert, type ApplicationOptions, BadRequest, Conflict, Created, type CreatedHttpResponseOptions, DefaultHttpProblemResponseOptions, DefaultHttpResponseOptions, type E2EResponseAssert, type ETag, ETagErrors, type ErrorToProblemDetailsMapping, type FirebaseAuthSecurityOptions, Forbidden, HeaderNames, type HttpHandler, HttpProblem, type HttpProblemResponseOptions, HttpResponse, type HttpResponseOptions, type ImportedHandlerModules, NoContent, type NoContentHttpResponseOptions, NotFound, OK, type OpenAPIV3Document, type OpenApiValidatorOptions, type PinoHttpOptions, PreconditionFailed, type ResponseAssert, type SecurityHandlers, type StartApiOptions, type TestRequest, type WeakETag, WeakETagRegex, type WebApiSetup, createFirebaseAuthSecurityHandlers, createOpenApiValidatorOptions, existingStream, expect, expectError, expectNewEvents, expectResponse, getApplication, getETagFromIfMatch, getETagFromIfNotMatch, getETagValueFromIfMatch, getWeakETagValue, isOpenApiValidatorAvailable, isWeakETag, on, registerHandlerModule, send, sendAccepted, sendCreated, sendProblem, setETag, startAPI, toWeakETag };
package/dist/index.d.ts CHANGED
@@ -6,6 +6,27 @@ import { Brand, Event, TestEventStream, EventStore } from '@event-driven-io/emme
6
6
  import supertest, { Test, Response as Response$1 } from 'supertest';
7
7
  import TestAgent from 'supertest/lib/agent';
8
8
 
9
+ type AuthClient = {
10
+ verifyIdToken: (token: string) => Promise<unknown>;
11
+ };
12
+ type FirebaseAuthSecurityOptions = {
13
+ /**
14
+ * Name of the OpenAPI security scheme to attach the handler to.
15
+ * Defaults to "bearerAuth".
16
+ */
17
+ securitySchemeName?: string;
18
+ /**
19
+ * Custom auth client for tests or alternate Firebase auth instances.
20
+ */
21
+ authClient?: AuthClient;
22
+ /**
23
+ * Token claim used for role-based checks when scopes are defined.
24
+ * Defaults to "roles".
25
+ */
26
+ roleClaim?: string;
27
+ };
28
+ declare const createFirebaseAuthSecurityHandlers: (options?: FirebaseAuthSecurityOptions) => SecurityHandlers;
29
+
9
30
  /**
10
31
  * OpenAPI v3 Document type (to avoid requiring express-openapi-validator types directly)
11
32
  */
@@ -22,6 +43,7 @@ type ImportedHandlerModules = Record<string, any>;
22
43
  * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/
23
44
  */
24
45
  type SecurityHandlers = Record<string, (req: any, scopes: string[], schema: any) => boolean | Promise<boolean>>;
46
+
25
47
  /**
26
48
  * Configuration options for express-openapi-validator middleware.
27
49
  * This allows optional validation of API requests and responses against an OpenAPI specification.
@@ -310,6 +332,12 @@ declare const send: (response: Response, statusCode: number, options?: HttpRespo
310
332
  declare const sendProblem: (response: Response, statusCode: number, options?: HttpProblemResponseOptions) => void;
311
333
 
312
334
  type WebApiSetup = (router: Router) => void;
335
+ /**
336
+ * Options forwarded to pino-http. Typed loosely to avoid hard dependency.
337
+ *
338
+ * @see https://github.com/pinojs/pino-http
339
+ */
340
+ type PinoHttpOptions = Record<string, unknown>;
313
341
  type ApplicationOptions = {
314
342
  apis?: WebApiSetup[];
315
343
  mapError?: ErrorToProblemDetailsMapping;
@@ -317,6 +345,25 @@ type ApplicationOptions = {
317
345
  disableJsonMiddleware?: boolean;
318
346
  disableUrlEncodingMiddleware?: boolean;
319
347
  disableProblemDetailsMiddleware?: boolean;
348
+ /**
349
+ * Optional Pino HTTP logger configuration.
350
+ * When true, enables pino-http with defaults.
351
+ * When an object, forwards the options to pino-http.
352
+ * Requires the 'pino-http' package to be installed.
353
+ *
354
+ * @see https://github.com/pinojs/pino-http
355
+ * @example
356
+ * ```typescript
357
+ * const app = await getApplication({
358
+ * pinoHttp: true,
359
+ * });
360
+ *
361
+ * const app = await getApplication({
362
+ * pinoHttp: { autoLogging: false },
363
+ * });
364
+ * ```
365
+ */
366
+ pinoHttp?: boolean | PinoHttpOptions;
320
367
  /**
321
368
  * Optional OpenAPI validator configuration.
322
369
  * When provided, enables request/response validation against an OpenAPI specification.
@@ -437,4 +484,4 @@ declare const ApiE2ESpecification: {
437
484
  */
438
485
  declare const registerHandlerModule: (modulePath: string, moduleExports: any) => void;
439
486
 
440
- export { Accepted, type AcceptedHttpResponseOptions, ApiE2ESpecification, type ApiE2ESpecificationAssert, ApiSpecification, type ApiSpecificationAssert, type ApplicationOptions, BadRequest, Conflict, Created, type CreatedHttpResponseOptions, DefaultHttpProblemResponseOptions, DefaultHttpResponseOptions, type E2EResponseAssert, type ETag, ETagErrors, type ErrorToProblemDetailsMapping, Forbidden, HeaderNames, type HttpHandler, HttpProblem, type HttpProblemResponseOptions, HttpResponse, type HttpResponseOptions, type ImportedHandlerModules, NoContent, type NoContentHttpResponseOptions, NotFound, OK, type OpenAPIV3Document, type OpenApiValidatorOptions, PreconditionFailed, type ResponseAssert, type SecurityHandlers, type StartApiOptions, type TestRequest, type WeakETag, WeakETagRegex, type WebApiSetup, createOpenApiValidatorOptions, existingStream, expect, expectError, expectNewEvents, expectResponse, getApplication, getETagFromIfMatch, getETagFromIfNotMatch, getETagValueFromIfMatch, getWeakETagValue, isOpenApiValidatorAvailable, isWeakETag, on, registerHandlerModule, send, sendAccepted, sendCreated, sendProblem, setETag, startAPI, toWeakETag };
487
+ export { Accepted, type AcceptedHttpResponseOptions, ApiE2ESpecification, type ApiE2ESpecificationAssert, ApiSpecification, type ApiSpecificationAssert, type ApplicationOptions, BadRequest, Conflict, Created, type CreatedHttpResponseOptions, DefaultHttpProblemResponseOptions, DefaultHttpResponseOptions, type E2EResponseAssert, type ETag, ETagErrors, type ErrorToProblemDetailsMapping, type FirebaseAuthSecurityOptions, Forbidden, HeaderNames, type HttpHandler, HttpProblem, type HttpProblemResponseOptions, HttpResponse, type HttpResponseOptions, type ImportedHandlerModules, NoContent, type NoContentHttpResponseOptions, NotFound, OK, type OpenAPIV3Document, type OpenApiValidatorOptions, type PinoHttpOptions, PreconditionFailed, type ResponseAssert, type SecurityHandlers, type StartApiOptions, type TestRequest, type WeakETag, WeakETagRegex, type WebApiSetup, createFirebaseAuthSecurityHandlers, createOpenApiValidatorOptions, existingStream, expect, expectError, expectNewEvents, expectResponse, getApplication, getETagFromIfMatch, getETagFromIfNotMatch, getETagValueFromIfMatch, getWeakETagValue, isOpenApiValidatorAvailable, isWeakETag, on, registerHandlerModule, send, sendAccepted, sendCreated, sendProblem, setETag, startAPI, toWeakETag };
package/dist/index.js CHANGED
@@ -48,10 +48,31 @@ var getApplication = async (options) => {
48
48
  disableJsonMiddleware,
49
49
  disableUrlEncodingMiddleware,
50
50
  disableProblemDetailsMiddleware,
51
+ pinoHttp,
51
52
  openApiValidator
52
53
  } = options;
53
54
  const router = Router();
54
55
  app.set("etag", enableDefaultExpressEtag ?? false);
56
+ if (pinoHttp !== void 0 && pinoHttp !== false) {
57
+ try {
58
+ const require2 = createRequire(import.meta.url);
59
+ const mod = require2("pino-http");
60
+ const provider = mod.default ?? mod;
61
+ if (typeof provider !== "function") {
62
+ throw new Error("Invalid pino-http module: missing default export");
63
+ }
64
+ const options2 = pinoHttp === true ? void 0 : pinoHttp;
65
+ const middleware = provider(options2);
66
+ app.use(middleware);
67
+ } catch {
68
+ console.warn(
69
+ "Pino HTTP configuration provided but pino-http package is not installed. Install it with: npm install pino-http"
70
+ );
71
+ throw new Error(
72
+ "pino-http package is required when pinoHttp option is used"
73
+ );
74
+ }
75
+ }
55
76
  if (!disableJsonMiddleware) app.use(express.json());
56
77
  if (!disableUrlEncodingMiddleware)
57
78
  app.use(
@@ -65,7 +86,7 @@ var getApplication = async (options) => {
65
86
  activateESMResolver();
66
87
  const handlersBasePath = typeof openApiValidator.operationHandlers === "string" ? openApiValidator.operationHandlers : openApiValidator.operationHandlers.basePath;
67
88
  if (handlersBasePath) {
68
- const { extractHandlerModules } = await import("./openapi-parser-6EGURSGG.js");
89
+ const { extractHandlerModules } = await import("./openapi-parser-CCYU636U.js");
69
90
  const { importAndRegisterHandlers } = await import("./handler-importer-OJGFQON5.js");
70
91
  try {
71
92
  const modules = await extractHandlerModules(
@@ -217,6 +238,64 @@ var HttpProblem = (statusCode, options) => (response) => {
217
238
  sendProblem(response, statusCode, options);
218
239
  };
219
240
 
241
+ // src/openapi/firebase-auth.ts
242
+ var loadFirebaseAuth = async () => {
243
+ try {
244
+ const mod = await import("@my-f-startup/firebase-auth-express");
245
+ const provider = mod.default ?? mod;
246
+ const firebaseAuthMiddleware = provider.firebaseAuthMiddleware;
247
+ if (typeof firebaseAuthMiddleware !== "function") {
248
+ throw new Error(
249
+ "Invalid @my-f-startup/firebase-auth-express module: missing firebaseAuthMiddleware export"
250
+ );
251
+ }
252
+ return provider;
253
+ } catch (error) {
254
+ const message = "@my-f-startup/firebase-auth-express is required for createFirebaseAuthSecurityHandlers. Install it with: npm install @my-f-startup/firebase-auth-express";
255
+ throw new Error(message, { cause: error });
256
+ }
257
+ };
258
+ var createNullResponse = () => {
259
+ const res = {};
260
+ res.status = () => res;
261
+ res.json = () => res;
262
+ res.send = () => res;
263
+ res.end = () => res;
264
+ res.set = () => res;
265
+ return res;
266
+ };
267
+ var runMiddleware = async (middleware, req) => {
268
+ return new Promise((resolve) => {
269
+ let nextCalled = false;
270
+ const res = createNullResponse();
271
+ const next = () => {
272
+ nextCalled = true;
273
+ resolve(true);
274
+ };
275
+ Promise.resolve(middleware(req, res, next)).then(() => {
276
+ if (!nextCalled) resolve(false);
277
+ }).catch(() => resolve(false));
278
+ });
279
+ };
280
+ var createFirebaseAuthSecurityHandlers = (options = {}) => {
281
+ const securitySchemeName = options.securitySchemeName ?? "bearerAuth";
282
+ const roleClaim = options.roleClaim ?? "roles";
283
+ return {
284
+ [securitySchemeName]: async (req, scopes, _schema) => {
285
+ const { firebaseAuthMiddleware } = await loadFirebaseAuth();
286
+ const middleware = firebaseAuthMiddleware({
287
+ authClient: options.authClient
288
+ });
289
+ const isAuthenticated = await runMiddleware(middleware, req);
290
+ if (!isAuthenticated) return false;
291
+ if (!scopes.length) return true;
292
+ const roles = req?.auth?.token?.[roleClaim];
293
+ if (!Array.isArray(roles)) return false;
294
+ return scopes.every((scope) => roles.includes(scope));
295
+ }
296
+ };
297
+ };
298
+
220
299
  // src/openapi/index.ts
221
300
  var createOpenApiValidatorOptions = (apiSpec, options) => {
222
301
  return {
@@ -399,6 +478,7 @@ export {
399
478
  OK,
400
479
  PreconditionFailed,
401
480
  WeakETagRegex,
481
+ createFirebaseAuthSecurityHandlers,
402
482
  createOpenApiValidatorOptions,
403
483
  existingStream,
404
484
  expect,