@logtape/express 2.2.0-dev.688 → 2.2.0-dev.690

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/dist/mod.cjs CHANGED
@@ -329,7 +329,7 @@ function expressLogger(options = {}) {
329
329
  if (isPromiseLike(requestContext)) {
330
330
  Promise.resolve(requestContext).then((resolvedContext) => {
331
331
  (0, __logtape_logtape.withContext)(resolvedContext, () => handleRequest(resolvedContext));
332
- }, next);
332
+ }).catch(next);
333
333
  return;
334
334
  }
335
335
  (0, __logtape_logtape.withContext)(requestContext, () => handleRequest(requestContext));
package/dist/mod.js CHANGED
@@ -328,7 +328,7 @@ function expressLogger(options = {}) {
328
328
  if (isPromiseLike(requestContext)) {
329
329
  Promise.resolve(requestContext).then((resolvedContext) => {
330
330
  withContext(resolvedContext, () => handleRequest(resolvedContext));
331
- }, next);
331
+ }).catch(next);
332
332
  return;
333
333
  }
334
334
  withContext(requestContext, () => handleRequest(requestContext));
package/dist/mod.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mod.js","names":["options: boolean | RequestContextOptions | undefined","options: boolean | RequestIdOptions | undefined","value: string","req: ExpressRequest","res: ExpressResponse","options: RequestIdOptions","responseHeader","resolvedRequestId: { property: string; value: string } | undefined","include: readonly RequestContextField[]","context: Record<string, unknown>","value: unknown","options: RequestContextOptions","result: string | Record<string, unknown>","responseTime: number","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: ExpressLogTapeOptions","formatFn: FormatFunction","next: ExpressNextFunction","requestContext: Record<string, unknown>","requestContext","requestContext:\n | Record<string, unknown>\n | Promise<Record<string, unknown>>"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel, withContext } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n// Use minimal type definitions for Express compatibility across Express 4.x and 5.x\n// These are compatible with both versions and avoid strict type checking issues\n\n/**\n * Minimal Express Request interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressRequest {\n method: string;\n url: string;\n originalUrl?: string;\n path?: string;\n httpVersion: string;\n ip?: string;\n socket?: { remoteAddress?: string };\n get(header: string): string | undefined;\n}\n\n/**\n * Minimal Express Response interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressResponse {\n statusCode: number;\n on(event: string, listener: () => void): void;\n getHeader(name: string): string | number | string[] | undefined;\n setHeader?(name: string, value: string): void;\n}\n\n/**\n * Express NextFunction type.\n * @since 1.3.0\n */\nexport type ExpressNextFunction = (err?: unknown) => void;\n\n/**\n * Express middleware function type.\n * @since 1.3.0\n */\nexport type ExpressMiddleware = (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n) => void;\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 1.3.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param req The Express request object.\n * @param res The Express response object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 1.3.0\n */\nexport type FormatFunction = (\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 1.3.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: string;\n /** HTTP response status code */\n status: number;\n /** Response time in milliseconds */\n responseTime: number;\n /** Response content-length header value */\n contentLength: string | undefined;\n /** Remote client address */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n /** HTTP version (e.g., \"1.1\") */\n httpVersion: string;\n}\n\n/**\n * Request fields that can be added to the implicit request context.\n * @since 2.2.0\n */\nexport type RequestContextField =\n | \"requestId\"\n | \"method\"\n | \"url\"\n | \"path\"\n | \"userAgent\"\n | \"remoteAddr\"\n | \"referrer\"\n | \"httpVersion\";\n\n/**\n * Options for extracting, generating, and propagating a request ID.\n * @since 2.2.0\n */\nexport interface RequestIdOptions {\n /**\n * The property name used in implicit context and request log records.\n * @default \"requestId\"\n */\n readonly property?: string;\n\n /**\n * Incoming request headers to inspect in order.\n * @default [\"x-request-id\"]\n */\n readonly headerNames?: readonly string[];\n\n /**\n * Response header that receives the resolved request ID.\n * Set to `false` to disable response header propagation.\n * @default \"x-request-id\"\n */\n readonly responseHeader?: string | false;\n\n /**\n * Generates a request ID when no incoming header is present.\n * @default crypto.randomUUID()\n */\n readonly generate?: () => string;\n\n /**\n * Normalizes an incoming request ID. Return `null` to reject the value and\n * keep looking for another header or generate a new ID.\n */\n readonly normalize?: (value: string) => string | null;\n}\n\n/**\n * Options for request-scoped implicit context.\n * @since 2.2.0\n */\nexport interface RequestContextOptions {\n /**\n * Enables request ID extraction, generation, and response propagation.\n * @default true\n */\n readonly requestId?: boolean | RequestIdOptions;\n\n /**\n * Fields to add to the implicit context.\n * @default [\"requestId\"]\n */\n readonly include?: readonly RequestContextField[];\n\n /**\n * Adds application-specific fields to the implicit request context.\n */\n readonly enrich?: (\n req: ExpressRequest,\n res: ExpressResponse,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n}\n\n/**\n * Options for configuring the Express LogTape middleware.\n * @since 1.3.0\n */\nexport interface ExpressLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"express\"]\n */\n readonly category?: string | readonly string[];\n\n /**\n * The log level to use for request logging.\n * @default \"info\"\n */\n readonly level?: LogLevel;\n\n /**\n * The format for log output.\n * Can be a predefined format name or a custom format function.\n *\n * Predefined formats:\n * - `\"combined\"` - Apache Combined Log Format (structured, default)\n * - `\"common\"` - Apache Common Log Format (structured, no referrer/userAgent)\n * - `\"dev\"` - Concise colored output for development (string)\n * - `\"short\"` - Shorter than common (string)\n * - `\"tiny\"` - Minimal output (string)\n *\n * @default \"combined\"\n */\n readonly format?: PredefinedFormat | FormatFunction;\n\n /**\n * Function to determine whether logging should be skipped.\n * Return `true` to skip logging for a request.\n *\n * @example Skip logging for successful requests\n * ```typescript\n * app.use(expressLogger({\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (req: ExpressRequest, res: ExpressResponse) => boolean;\n\n /**\n * If `true`, logs are written immediately when the request is received.\n * If `false` (default), logs are written after the response is sent.\n *\n * Note: When `immediate` is `true`, response-related properties\n * (status, responseTime, contentLength) will not be available.\n *\n * @default false\n */\n readonly immediate?: boolean;\n\n /**\n * Enables request-scoped implicit context and request ID correlation.\n *\n * When set to `true`, the middleware reads the `x-request-id` header,\n * generates one when it is absent, writes it to the `x-request-id` response\n * header, and adds `requestId` to all LogTape records emitted while handling\n * the request.\n *\n * @default false\n * @since 2.2.0\n */\n readonly context?: boolean | RequestContextOptions;\n}\n\nconst defaultRequestIdHeader = \"x-request-id\";\n\n/**\n * Normalize request context options.\n */\nfunction normalizeRequestContextOptions(\n options: boolean | RequestContextOptions | undefined,\n): RequestContextOptions | undefined {\n if (options === true) return {};\n if (options === false || options == null) return undefined;\n return options;\n}\n\n/**\n * Normalize request ID options.\n */\nfunction normalizeRequestIdOptions(\n options: boolean | RequestIdOptions | undefined,\n): RequestIdOptions | undefined {\n if (options === false) return undefined;\n if (options === true || options == null) return {};\n return options;\n}\n\n/**\n * Generate a request ID with Web Crypto when possible.\n */\nfunction generateRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Normalize an incoming request ID.\n */\nfunction defaultNormalizeRequestId(value: string): string | null {\n const trimmed = value.trim();\n return trimmed === \"\" ? null : trimmed;\n}\n\n/**\n * Resolve the request ID for a request.\n */\nfunction resolveRequestId(\n req: ExpressRequest,\n res: ExpressResponse,\n options: RequestIdOptions,\n): { property: string; value: string } {\n const property = options.property ?? \"requestId\";\n const normalize = options.normalize ?? defaultNormalizeRequestId;\n const headerNames = options.headerNames ?? [defaultRequestIdHeader];\n for (const headerName of headerNames) {\n const headerValue = req.get(headerName);\n if (headerValue == null) continue;\n const normalized = normalize(headerValue);\n if (normalized != null) {\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) res.setHeader?.(responseHeader, normalized);\n return { property, value: normalized };\n }\n }\n const generated = (options.generate ?? generateRequestId)();\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) res.setHeader?.(responseHeader, generated);\n return { property, value: generated };\n}\n\n/**\n * Build request context fields from a request.\n */\nfunction buildIncludedContext(\n req: ExpressRequest,\n resolvedRequestId: { property: string; value: string } | undefined,\n include: readonly RequestContextField[],\n): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n for (const field of include) {\n switch (field) {\n case \"requestId\":\n if (resolvedRequestId != null) {\n context[resolvedRequestId.property] = resolvedRequestId.value;\n }\n break;\n case \"method\":\n context.method = req.method;\n break;\n case \"url\":\n context.url = req.originalUrl || req.url;\n break;\n case \"path\":\n context.path = req.path;\n break;\n case \"userAgent\":\n context.userAgent = getUserAgent(req);\n break;\n case \"remoteAddr\":\n context.remoteAddr = getRemoteAddr(req);\n break;\n case \"referrer\":\n context.referrer = getReferrer(req);\n break;\n case \"httpVersion\":\n context.httpVersion = req.httpVersion;\n break;\n }\n }\n return context;\n}\n\n/**\n * Check whether a value is a promise-like object.\n */\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return value != null && typeof value === \"object\" &&\n typeof (value as PromiseLike<T>).then === \"function\";\n}\n\n/**\n * Build the implicit context for a request.\n */\nfunction buildRequestContext(\n req: ExpressRequest,\n res: ExpressResponse,\n options: RequestContextOptions,\n): Record<string, unknown> | Promise<Record<string, unknown>> {\n const requestIdOptions = normalizeRequestIdOptions(options.requestId);\n const resolvedRequestId = requestIdOptions == null\n ? undefined\n : resolveRequestId(req, res, requestIdOptions);\n const include = options.include ??\n (resolvedRequestId == null ? [] : [\"requestId\"] as const);\n const context = buildIncludedContext(req, resolvedRequestId, include);\n if (options.enrich == null) return context;\n const enriched = options.enrich(req, res);\n if (isPromiseLike<Record<string, unknown>>(enriched)) {\n return Promise.resolve(enriched).then((extraContext) => ({\n ...context,\n ...extraContext,\n }));\n }\n return { ...context, ...enriched };\n}\n\n/**\n * Add request context fields to a request log result.\n */\nfunction withRequestLogContext(\n result: string | Record<string, unknown>,\n context: Record<string, unknown>,\n): string | Record<string, unknown> {\n if (typeof result === \"string\") return result;\n return { ...result, ...context };\n}\n\n/**\n * Get remote address from request.\n */\nfunction getRemoteAddr(req: ExpressRequest): string | undefined {\n return req.ip || req.socket?.remoteAddress;\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(res: ExpressResponse): string | undefined {\n const contentLength = res.getHeader(\"content-length\");\n if (contentLength === undefined || contentLength === null) return undefined;\n return String(contentLength);\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(req: ExpressRequest): string | undefined {\n return req.get(\"referrer\") || req.get(\"referer\");\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(req: ExpressRequest): string | undefined {\n return req.get(\"user-agent\");\n}\n\n/**\n * Build structured log properties from request/response.\n */\nfunction buildProperties(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: req.method,\n url: req.originalUrl || req.url,\n status: res.statusCode,\n responseTime,\n contentLength: getContentLength(res),\n remoteAddr: getRemoteAddr(req),\n userAgent: getUserAgent(req),\n referrer: getReferrer(req),\n httpVersion: req.httpVersion,\n };\n}\n\n/**\n * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(req, res, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(req, res, responseTime);\n const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;\n return rest;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :url :status :response-time ms - :res[content-length]\n */\nfunction formatDev(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms\n */\nfunction formatShort(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const remoteAddr = getRemoteAddr(req) ?? \"-\";\n const contentLength = getContentLength(res) ?? \"-\";\n return `${remoteAddr} ${req.method} ${\n req.originalUrl || req.url\n } HTTP/${req.httpVersion} ${res.statusCode} ${contentLength} - ${\n responseTime.toFixed(3)\n } ms`;\n}\n\n/**\n * Tiny format (minimal output).\n * :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatTiny(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${\n req.originalUrl || req.url\n } ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;\n}\n\n/**\n * Map of predefined format functions.\n */\nconst predefinedFormats: Record<PredefinedFormat, FormatFunction> = {\n combined: formatCombined,\n common: formatCommon,\n dev: formatDev,\n short: formatShort,\n tiny: formatTiny,\n};\n\n/**\n * Normalize category to array format.\n */\nfunction normalizeCategory(\n category: string | readonly string[],\n): readonly string[] {\n return typeof category === \"string\" ? [category] : category;\n}\n\n/**\n * Creates Express middleware for HTTP request logging using LogTape.\n *\n * This middleware provides Morgan-compatible request logging with LogTape\n * as the backend, supporting structured logging and customizable formats.\n *\n * @example Basic usage\n * ```typescript\n * import express from \"express\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { expressLogger } from \"@logtape/express\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"express\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = express();\n * app.use(expressLogger());\n *\n * app.get(\"/\", (req, res) => {\n * res.json({ hello: \"world\" });\n * });\n *\n * app.listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(expressLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(expressLogger({\n * format: (req, res, responseTime) => ({\n * method: req.method,\n * path: req.path,\n * status: res.statusCode,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Express middleware function.\n * @since 1.3.0\n */\nexport function expressLogger(\n options: ExpressLogTapeOptions = {},\n): ExpressMiddleware {\n const category = normalizeCategory(options.category ?? [\"express\"]);\n const logger = getLogger(category);\n const level = options.level ?? \"info\";\n const formatOption = options.format ?? \"combined\";\n const skip = options.skip ?? (() => false);\n const immediate = options.immediate ?? false;\n const contextOptions = normalizeRequestContextOptions(options.context);\n\n // Resolve format function\n const formatFn: FormatFunction = typeof formatOption === \"string\"\n ? predefinedFormats[formatOption]\n : formatOption;\n\n const logMethod = logger[level].bind(logger);\n\n return (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n ): void => {\n const startTime = Date.now();\n\n const handleRequest = (requestContext: Record<string, unknown>): void => {\n // For immediate logging, log when request arrives\n if (immediate) {\n if (!skip(req, res)) {\n const result = withRequestLogContext(\n formatFn(req, res, 0),\n requestContext,\n );\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n next();\n return;\n }\n\n // Log after response is sent\n const logRequest = (): void => {\n if (skip(req, res)) return;\n\n const responseTime = Date.now() - startTime;\n const result = withRequestLogContext(\n formatFn(req, res, responseTime),\n requestContext,\n );\n\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n };\n\n // Listen for response finish event\n res.on(\"finish\", logRequest);\n\n next();\n };\n\n if (contextOptions == null) {\n handleRequest({});\n return;\n }\n\n let requestContext:\n | Record<string, unknown>\n | Promise<Record<string, unknown>>;\n try {\n requestContext = buildRequestContext(req, res, contextOptions);\n } catch (error) {\n next(error);\n return;\n }\n if (isPromiseLike<Record<string, unknown>>(requestContext)) {\n Promise.resolve(requestContext).then((resolvedContext) => {\n withContext(resolvedContext, () => handleRequest(resolvedContext));\n }, next);\n return;\n }\n\n withContext(requestContext, () => handleRequest(requestContext));\n };\n}\n"],"mappings":";;;AAoPA,MAAM,yBAAyB;;;;AAK/B,SAAS,+BACPA,SACmC;AACnC,KAAI,YAAY,KAAM,QAAO,CAAE;AAC/B,KAAI,YAAY,SAAS,WAAW,KAAM;AAC1C,QAAO;AACR;;;;AAKD,SAAS,0BACPC,SAC8B;AAC9B,KAAI,YAAY,MAAO;AACvB,KAAI,YAAY,QAAQ,WAAW,KAAM,QAAO,CAAE;AAClD,QAAO;AACR;;;;AAKD,SAAS,oBAA4B;AACnC,YAAW,WAAW,QAAQ,eAAe,WAC3C,QAAO,WAAW,OAAO,YAAY;AAEvC,SAAQ,EAAE,KAAK,KAAK,CAAC,SAAS,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC;AAC1E;;;;AAKD,SAAS,0BAA0BC,OAA8B;CAC/D,MAAM,UAAU,MAAM,MAAM;AAC5B,QAAO,YAAY,KAAK,OAAO;AAChC;;;;AAKD,SAAS,iBACPC,KACAC,KACAC,SACqC;CACrC,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,cAAc,QAAQ,eAAe,CAAC,sBAAuB;AACnE,MAAK,MAAM,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"file":"mod.js","names":["options: boolean | RequestContextOptions | undefined","options: boolean | RequestIdOptions | undefined","value: string","req: ExpressRequest","res: ExpressResponse","options: RequestIdOptions","responseHeader","resolvedRequestId: { property: string; value: string } | undefined","include: readonly RequestContextField[]","context: Record<string, unknown>","value: unknown","options: RequestContextOptions","result: string | Record<string, unknown>","responseTime: number","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: ExpressLogTapeOptions","formatFn: FormatFunction","next: ExpressNextFunction","requestContext: Record<string, unknown>","requestContext","requestContext:\n | Record<string, unknown>\n | Promise<Record<string, unknown>>"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel, withContext } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n// Use minimal type definitions for Express compatibility across Express 4.x and 5.x\n// These are compatible with both versions and avoid strict type checking issues\n\n/**\n * Minimal Express Request interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressRequest {\n method: string;\n url: string;\n originalUrl?: string;\n path?: string;\n httpVersion: string;\n ip?: string;\n socket?: { remoteAddress?: string };\n get(header: string): string | undefined;\n}\n\n/**\n * Minimal Express Response interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressResponse {\n statusCode: number;\n on(event: string, listener: () => void): void;\n getHeader(name: string): string | number | string[] | undefined;\n setHeader?(name: string, value: string): void;\n}\n\n/**\n * Express NextFunction type.\n * @since 1.3.0\n */\nexport type ExpressNextFunction = (err?: unknown) => void;\n\n/**\n * Express middleware function type.\n * @since 1.3.0\n */\nexport type ExpressMiddleware = (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n) => void;\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 1.3.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param req The Express request object.\n * @param res The Express response object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 1.3.0\n */\nexport type FormatFunction = (\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 1.3.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: string;\n /** HTTP response status code */\n status: number;\n /** Response time in milliseconds */\n responseTime: number;\n /** Response content-length header value */\n contentLength: string | undefined;\n /** Remote client address */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n /** HTTP version (e.g., \"1.1\") */\n httpVersion: string;\n}\n\n/**\n * Request fields that can be added to the implicit request context.\n * @since 2.2.0\n */\nexport type RequestContextField =\n | \"requestId\"\n | \"method\"\n | \"url\"\n | \"path\"\n | \"userAgent\"\n | \"remoteAddr\"\n | \"referrer\"\n | \"httpVersion\";\n\n/**\n * Options for extracting, generating, and propagating a request ID.\n * @since 2.2.0\n */\nexport interface RequestIdOptions {\n /**\n * The property name used in implicit context and request log records.\n * @default \"requestId\"\n */\n readonly property?: string;\n\n /**\n * Incoming request headers to inspect in order.\n * @default [\"x-request-id\"]\n */\n readonly headerNames?: readonly string[];\n\n /**\n * Response header that receives the resolved request ID.\n * Set to `false` to disable response header propagation.\n * @default \"x-request-id\"\n */\n readonly responseHeader?: string | false;\n\n /**\n * Generates a request ID when no incoming header is present.\n * @default crypto.randomUUID()\n */\n readonly generate?: () => string;\n\n /**\n * Normalizes an incoming request ID. Return `null` to reject the value and\n * keep looking for another header or generate a new ID.\n */\n readonly normalize?: (value: string) => string | null;\n}\n\n/**\n * Options for request-scoped implicit context.\n * @since 2.2.0\n */\nexport interface RequestContextOptions {\n /**\n * Enables request ID extraction, generation, and response propagation.\n * @default true\n */\n readonly requestId?: boolean | RequestIdOptions;\n\n /**\n * Fields to add to the implicit context.\n * @default [\"requestId\"]\n */\n readonly include?: readonly RequestContextField[];\n\n /**\n * Adds application-specific fields to the implicit request context.\n */\n readonly enrich?: (\n req: ExpressRequest,\n res: ExpressResponse,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n}\n\n/**\n * Options for configuring the Express LogTape middleware.\n * @since 1.3.0\n */\nexport interface ExpressLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"express\"]\n */\n readonly category?: string | readonly string[];\n\n /**\n * The log level to use for request logging.\n * @default \"info\"\n */\n readonly level?: LogLevel;\n\n /**\n * The format for log output.\n * Can be a predefined format name or a custom format function.\n *\n * Predefined formats:\n * - `\"combined\"` - Apache Combined Log Format (structured, default)\n * - `\"common\"` - Apache Common Log Format (structured, no referrer/userAgent)\n * - `\"dev\"` - Concise colored output for development (string)\n * - `\"short\"` - Shorter than common (string)\n * - `\"tiny\"` - Minimal output (string)\n *\n * @default \"combined\"\n */\n readonly format?: PredefinedFormat | FormatFunction;\n\n /**\n * Function to determine whether logging should be skipped.\n * Return `true` to skip logging for a request.\n *\n * @example Skip logging for successful requests\n * ```typescript\n * app.use(expressLogger({\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (req: ExpressRequest, res: ExpressResponse) => boolean;\n\n /**\n * If `true`, logs are written immediately when the request is received.\n * If `false` (default), logs are written after the response is sent.\n *\n * Note: When `immediate` is `true`, response-related properties\n * (status, responseTime, contentLength) will not be available.\n *\n * @default false\n */\n readonly immediate?: boolean;\n\n /**\n * Enables request-scoped implicit context and request ID correlation.\n *\n * When set to `true`, the middleware reads the `x-request-id` header,\n * generates one when it is absent, writes it to the `x-request-id` response\n * header, and adds `requestId` to all LogTape records emitted while handling\n * the request.\n *\n * @default false\n * @since 2.2.0\n */\n readonly context?: boolean | RequestContextOptions;\n}\n\nconst defaultRequestIdHeader = \"x-request-id\";\n\n/**\n * Normalize request context options.\n */\nfunction normalizeRequestContextOptions(\n options: boolean | RequestContextOptions | undefined,\n): RequestContextOptions | undefined {\n if (options === true) return {};\n if (options === false || options == null) return undefined;\n return options;\n}\n\n/**\n * Normalize request ID options.\n */\nfunction normalizeRequestIdOptions(\n options: boolean | RequestIdOptions | undefined,\n): RequestIdOptions | undefined {\n if (options === false) return undefined;\n if (options === true || options == null) return {};\n return options;\n}\n\n/**\n * Generate a request ID with Web Crypto when possible.\n */\nfunction generateRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Normalize an incoming request ID.\n */\nfunction defaultNormalizeRequestId(value: string): string | null {\n const trimmed = value.trim();\n return trimmed === \"\" ? null : trimmed;\n}\n\n/**\n * Resolve the request ID for a request.\n */\nfunction resolveRequestId(\n req: ExpressRequest,\n res: ExpressResponse,\n options: RequestIdOptions,\n): { property: string; value: string } {\n const property = options.property ?? \"requestId\";\n const normalize = options.normalize ?? defaultNormalizeRequestId;\n const headerNames = options.headerNames ?? [defaultRequestIdHeader];\n for (const headerName of headerNames) {\n const headerValue = req.get(headerName);\n if (headerValue == null) continue;\n const normalized = normalize(headerValue);\n if (normalized != null) {\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) res.setHeader?.(responseHeader, normalized);\n return { property, value: normalized };\n }\n }\n const generated = (options.generate ?? generateRequestId)();\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) res.setHeader?.(responseHeader, generated);\n return { property, value: generated };\n}\n\n/**\n * Build request context fields from a request.\n */\nfunction buildIncludedContext(\n req: ExpressRequest,\n resolvedRequestId: { property: string; value: string } | undefined,\n include: readonly RequestContextField[],\n): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n for (const field of include) {\n switch (field) {\n case \"requestId\":\n if (resolvedRequestId != null) {\n context[resolvedRequestId.property] = resolvedRequestId.value;\n }\n break;\n case \"method\":\n context.method = req.method;\n break;\n case \"url\":\n context.url = req.originalUrl || req.url;\n break;\n case \"path\":\n context.path = req.path;\n break;\n case \"userAgent\":\n context.userAgent = getUserAgent(req);\n break;\n case \"remoteAddr\":\n context.remoteAddr = getRemoteAddr(req);\n break;\n case \"referrer\":\n context.referrer = getReferrer(req);\n break;\n case \"httpVersion\":\n context.httpVersion = req.httpVersion;\n break;\n }\n }\n return context;\n}\n\n/**\n * Check whether a value is a promise-like object.\n */\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return value != null && typeof value === \"object\" &&\n typeof (value as PromiseLike<T>).then === \"function\";\n}\n\n/**\n * Build the implicit context for a request.\n */\nfunction buildRequestContext(\n req: ExpressRequest,\n res: ExpressResponse,\n options: RequestContextOptions,\n): Record<string, unknown> | Promise<Record<string, unknown>> {\n const requestIdOptions = normalizeRequestIdOptions(options.requestId);\n const resolvedRequestId = requestIdOptions == null\n ? undefined\n : resolveRequestId(req, res, requestIdOptions);\n const include = options.include ??\n (resolvedRequestId == null ? [] : [\"requestId\"] as const);\n const context = buildIncludedContext(req, resolvedRequestId, include);\n if (options.enrich == null) return context;\n const enriched = options.enrich(req, res);\n if (isPromiseLike<Record<string, unknown>>(enriched)) {\n return Promise.resolve(enriched).then((extraContext) => ({\n ...context,\n ...extraContext,\n }));\n }\n return { ...context, ...enriched };\n}\n\n/**\n * Add request context fields to a request log result.\n */\nfunction withRequestLogContext(\n result: string | Record<string, unknown>,\n context: Record<string, unknown>,\n): string | Record<string, unknown> {\n if (typeof result === \"string\") return result;\n return { ...result, ...context };\n}\n\n/**\n * Get remote address from request.\n */\nfunction getRemoteAddr(req: ExpressRequest): string | undefined {\n return req.ip || req.socket?.remoteAddress;\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(res: ExpressResponse): string | undefined {\n const contentLength = res.getHeader(\"content-length\");\n if (contentLength === undefined || contentLength === null) return undefined;\n return String(contentLength);\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(req: ExpressRequest): string | undefined {\n return req.get(\"referrer\") || req.get(\"referer\");\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(req: ExpressRequest): string | undefined {\n return req.get(\"user-agent\");\n}\n\n/**\n * Build structured log properties from request/response.\n */\nfunction buildProperties(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: req.method,\n url: req.originalUrl || req.url,\n status: res.statusCode,\n responseTime,\n contentLength: getContentLength(res),\n remoteAddr: getRemoteAddr(req),\n userAgent: getUserAgent(req),\n referrer: getReferrer(req),\n httpVersion: req.httpVersion,\n };\n}\n\n/**\n * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(req, res, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(req, res, responseTime);\n const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;\n return rest;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :url :status :response-time ms - :res[content-length]\n */\nfunction formatDev(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms\n */\nfunction formatShort(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const remoteAddr = getRemoteAddr(req) ?? \"-\";\n const contentLength = getContentLength(res) ?? \"-\";\n return `${remoteAddr} ${req.method} ${\n req.originalUrl || req.url\n } HTTP/${req.httpVersion} ${res.statusCode} ${contentLength} - ${\n responseTime.toFixed(3)\n } ms`;\n}\n\n/**\n * Tiny format (minimal output).\n * :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatTiny(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${\n req.originalUrl || req.url\n } ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;\n}\n\n/**\n * Map of predefined format functions.\n */\nconst predefinedFormats: Record<PredefinedFormat, FormatFunction> = {\n combined: formatCombined,\n common: formatCommon,\n dev: formatDev,\n short: formatShort,\n tiny: formatTiny,\n};\n\n/**\n * Normalize category to array format.\n */\nfunction normalizeCategory(\n category: string | readonly string[],\n): readonly string[] {\n return typeof category === \"string\" ? [category] : category;\n}\n\n/**\n * Creates Express middleware for HTTP request logging using LogTape.\n *\n * This middleware provides Morgan-compatible request logging with LogTape\n * as the backend, supporting structured logging and customizable formats.\n *\n * @example Basic usage\n * ```typescript\n * import express from \"express\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { expressLogger } from \"@logtape/express\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"express\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = express();\n * app.use(expressLogger());\n *\n * app.get(\"/\", (req, res) => {\n * res.json({ hello: \"world\" });\n * });\n *\n * app.listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(expressLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(expressLogger({\n * format: (req, res, responseTime) => ({\n * method: req.method,\n * path: req.path,\n * status: res.statusCode,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Express middleware function.\n * @since 1.3.0\n */\nexport function expressLogger(\n options: ExpressLogTapeOptions = {},\n): ExpressMiddleware {\n const category = normalizeCategory(options.category ?? [\"express\"]);\n const logger = getLogger(category);\n const level = options.level ?? \"info\";\n const formatOption = options.format ?? \"combined\";\n const skip = options.skip ?? (() => false);\n const immediate = options.immediate ?? false;\n const contextOptions = normalizeRequestContextOptions(options.context);\n\n // Resolve format function\n const formatFn: FormatFunction = typeof formatOption === \"string\"\n ? predefinedFormats[formatOption]\n : formatOption;\n\n const logMethod = logger[level].bind(logger);\n\n return (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n ): void => {\n const startTime = Date.now();\n\n const handleRequest = (requestContext: Record<string, unknown>): void => {\n // For immediate logging, log when request arrives\n if (immediate) {\n if (!skip(req, res)) {\n const result = withRequestLogContext(\n formatFn(req, res, 0),\n requestContext,\n );\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n next();\n return;\n }\n\n // Log after response is sent\n const logRequest = (): void => {\n if (skip(req, res)) return;\n\n const responseTime = Date.now() - startTime;\n const result = withRequestLogContext(\n formatFn(req, res, responseTime),\n requestContext,\n );\n\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n };\n\n // Listen for response finish event\n res.on(\"finish\", logRequest);\n\n next();\n };\n\n if (contextOptions == null) {\n handleRequest({});\n return;\n }\n\n let requestContext:\n | Record<string, unknown>\n | Promise<Record<string, unknown>>;\n try {\n requestContext = buildRequestContext(req, res, contextOptions);\n } catch (error) {\n next(error);\n return;\n }\n if (isPromiseLike<Record<string, unknown>>(requestContext)) {\n Promise.resolve(requestContext)\n .then((resolvedContext) => {\n withContext(resolvedContext, () => handleRequest(resolvedContext));\n })\n .catch(next);\n return;\n }\n\n withContext(requestContext, () => handleRequest(requestContext));\n };\n}\n"],"mappings":";;;AAoPA,MAAM,yBAAyB;;;;AAK/B,SAAS,+BACPA,SACmC;AACnC,KAAI,YAAY,KAAM,QAAO,CAAE;AAC/B,KAAI,YAAY,SAAS,WAAW,KAAM;AAC1C,QAAO;AACR;;;;AAKD,SAAS,0BACPC,S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AAS,sBACb,SAAS,KAAK,KAAK,aAAa,EAChCA,iBACD;AAED,eAAW,WAAW,SACpB,WAAU,QAAQA,iBAAe;QAEjC,WAAU,+CAA+C,OAAO;GAEnE;AAGD,OAAI,GAAG,UAAU,WAAW;AAE5B,SAAM;EACP;AAED,MAAI,kBAAkB,MAAM;AAC1B,iBAAc,CAAE,EAAC;AACjB;EACD;EAED,IAAIC;AAGJ,MAAI;AACF,oBAAiB,oBAAoB,KAAK,KAAK,eAAe;EAC/D,SAAQ,OAAO;AACd,QAAK,MAAM;AACX;EACD;AACD,MAAI,cAAuC,eAAe,EAAE;AAC1D,WAAQ,QAAQ,eAAe,CAC5B,KAAK,CAAC,oBAAoB;AACzB,gBAAY,iBAAiB,MAAM,cAAc,gBAAgB,CAAC;GACnE,EAAC,CACD,MAAM,KAAK;AACd;EACD;AAED,cAAY,gBAAgB,MAAM,cAAc,eAAe,CAAC;CACjE;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logtape/express",
3
- "version": "2.2.0-dev.688+20e7145c",
3
+ "version": "2.2.0-dev.690+9c439afd",
4
4
  "description": "Express adapter for LogTape logging library",
5
5
  "keywords": [
6
6
  "logging",
@@ -53,7 +53,7 @@
53
53
  ],
54
54
  "peerDependencies": {
55
55
  "express": "^4.0.0 || ^5.0.0",
56
- "@logtape/logtape": "^2.2.0-dev.688+20e7145c"
56
+ "@logtape/logtape": "^2.2.0-dev.690+9c439afd"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@alinea/suite": "^0.6.3",