@darksheep/express 2.1.1 → 2.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.1.4](https://github.com/DarkSheepSoftware/node-packages/compare/express-v2.1.3...express-v2.1.4) (2026-09-20)
4
+
5
+
6
+ ### 🩹 Fixes
7
+
8
+ * **express:** correct JSDoc types that broke the prepack typecheck ([#1005](https://github.com/DarkSheepSoftware/node-packages/issues/1005)) ([d21cd6f](https://github.com/DarkSheepSoftware/node-packages/commit/d21cd6fffe02ad1ed13a0d67c6c19e32eeff5a85))
9
+
10
+ ## [2.1.3](https://github.com/DarkSheepSoftware/node-packages/compare/express-v2.1.2...express-v2.1.3) (2026-09-20)
11
+
12
+
13
+ ### Dependencies
14
+
15
+ * The following workspace dependencies were updated
16
+ * devDependencies
17
+ * @darksheep/logger bumped from 1.3.1 to 1.4.0
18
+ * peerDependencies
19
+ * @darksheep/logger bumped from >=1.0.10 to >=1.4.0
20
+
21
+ ## [2.1.2](https://github.com/DarkSheepSoftware/node-packages/compare/express-v2.1.1...express-v2.1.2) (2026-04-17)
22
+
23
+
24
+ ### 🩹 Fixes
25
+
26
+ * **express:** make @darksheep/logger optional, always log errors ([#836](https://github.com/DarkSheepSoftware/node-packages/issues/836)) ([f29fef9](https://github.com/DarkSheepSoftware/node-packages/commit/f29fef9453b78ef03b6903bcc0b1ccd3af4e2baa))
27
+
28
+
29
+ ### 📚 Documentation
30
+
31
+ * Update the READMEs ([#824](https://github.com/DarkSheepSoftware/node-packages/issues/824)) ([9d282b7](https://github.com/DarkSheepSoftware/node-packages/commit/9d282b724fe056ec275578088bf495985e22c25f))
32
+
33
+
34
+ ### Dependencies
35
+
36
+ * The following workspace dependencies were updated
37
+ * dependencies
38
+ * @darksheep/errors bumped from 1.2.0 to 1.2.1
39
+ * devDependencies
40
+ * @darksheep/json-schema bumped to 0.1.2
41
+ * @darksheep/logger bumped from 1.3.0 to 1.3.1
42
+ * peerDependencies
43
+ * @darksheep/json-schema bumped to 0.1.2
44
+ * @darksheep/logger bumped from >=1.0.10 to >=1.3.1
45
+
3
46
  ## [2.1.1](https://github.com/DarkSheepSoftware/node-packages/compare/express-v2.1.0...express-v2.1.1) (2025-12-04)
4
47
 
5
48
 
package/README.md CHANGED
@@ -1,2 +1,109 @@
1
1
  # @darksheep/express
2
- Automatically log your express requests.
2
+ Express middleware for the stuff you end up wiring up in every service.
3
+
4
+ ## Installation
5
+ ```sh
6
+ yarn add @darksheep/express express
7
+ ```
8
+
9
+ ## Example
10
+ ```js
11
+ import express from 'express';
12
+ import {
13
+ createRequestIdMiddleware,
14
+ createRequestLoggerMiddleware,
15
+ errorHandlerMiddleware,
16
+ notFoundMiddleware,
17
+ HttpErrorHandler,
18
+ } from '@darksheep/express';
19
+
20
+ const app = express();
21
+
22
+ app.use(createRequestIdMiddleware());
23
+ app.use(createRequestLoggerMiddleware());
24
+
25
+ // your routes here
26
+
27
+ app.use(notFoundMiddleware);
28
+ app.errorHandlers = [ HttpErrorHandler ];
29
+ app.use(errorHandlerMiddleware);
30
+ ```
31
+
32
+ ## Detailed Docs
33
+
34
+ ### Middleware
35
+
36
+ ```js
37
+ /**
38
+ * Adds a unique request ID to req.id and the X-Request-Id response header.
39
+ */
40
+ createRequestIdMiddleware(options?)
41
+
42
+ /**
43
+ * Logs each request. Requires @darksheep/logger.
44
+ */
45
+ createRequestLoggerMiddleware(options?)
46
+
47
+ /**
48
+ * Returns 404 JSON for any unmatched route.
49
+ */
50
+ notFoundMiddleware
51
+
52
+ /**
53
+ * Catches errors, sets the status code from error.statusCode, and returns JSON.
54
+ * Checks app.errorHandlers to format the error body.
55
+ */
56
+ errorHandlerMiddleware
57
+ ```
58
+
59
+ ### Content type
60
+
61
+ `createContentTypeMiddleware` checks the incoming `Content-Type` header and either continues or throws `UnsupportedMediaType`:
62
+
63
+ ```js
64
+ import { createContentTypeMiddleware } from '@darksheep/express';
65
+
66
+ // Only allow JSON bodies on this route
67
+ app.post('/data', createContentTypeMiddleware('application/json'), (req, res) => {
68
+ res.json({ ok: true });
69
+ });
70
+
71
+ // Allow multiple content types
72
+ app.post('/upload', createContentTypeMiddleware(['application/json', 'multipart/form-data']), handler);
73
+
74
+ // Pass false to skip to the next route instead of throwing
75
+ app.post('/maybe', createContentTypeMiddleware('application/json', false), jsonHandler);
76
+ ```
77
+
78
+ `createContentTypeRouter` is a shorthand that builds a sub-router dispatching by `Content-Type`:
79
+
80
+ ```js
81
+ import { createContentTypeRouter } from '@darksheep/express';
82
+
83
+ app.post('/data', createContentTypeRouter({
84
+ 'application/json': jsonHandler,
85
+ 'multipart/form-data': formHandler,
86
+ }));
87
+ // Throws UnsupportedMediaType for anything else
88
+ ```
89
+
90
+ ### Error handlers
91
+ `app.errorHandlers` is an array of `{ test, format }` objects. The first matching handler formats the error response.
92
+
93
+ ```js
94
+ /**
95
+ * Handles @darksheep/errors HttpError instances.
96
+ * Returns the error name and message.
97
+ */
98
+ HttpErrorHandler
99
+
100
+ /**
101
+ * Handles @darksheep/json-schema validation errors.
102
+ */
103
+ SchemaErrorHandler
104
+
105
+ /**
106
+ * Handles Zod validation errors.
107
+ */
108
+ ZodErrorHandler
109
+ ```
package/express.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /* eslint @typescript-eslint/consistent-type-definitions: 0 */
2
- import { type Logger } from '@darksheep/logger';
2
+ import type { Logger } from '@darksheep/logger';
3
3
 
4
4
  export interface ApiError {
5
5
  message?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@darksheep/express",
3
- "version": "2.1.1",
3
+ "version": "2.1.4",
4
4
  "description": "express utilites and other bits",
5
5
  "license": "UNLICENCED",
6
6
  "type": "module",
@@ -22,13 +22,13 @@
22
22
  "test:watch": "node --watch --test src/**/*.test.js"
23
23
  },
24
24
  "dependencies": {
25
- "@darksheep/errors": "1.2.0",
25
+ "@darksheep/errors": "1.2.1",
26
26
  "@darksheep/prune": "1.1.0",
27
27
  "on-finished": "2.4.1"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@darksheep/json-schema": "",
31
- "@darksheep/logger": "1.3.0",
31
+ "@darksheep/logger": "1.4.0",
32
32
  "@types/express": "~5.0.0",
33
33
  "@types/on-finished": "^2",
34
34
  "express": "~5.2.0"
@@ -48,5 +48,8 @@
48
48
  },
49
49
  "engines": {
50
50
  "node": "^20.13.1 || >=22.2.0"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
51
54
  }
52
55
  }
@@ -17,7 +17,7 @@ export function createContentTypeMiddleware(targetContentTypes, shouldThrow = tr
17
17
  );
18
18
 
19
19
  return (request, response, next) => {
20
- const provided = request.headers['content-type']?.split(';').at(0);
20
+ const provided = request.headers['content-type']?.split(';', 1).at(0);
21
21
  if (
22
22
  provided != null &&
23
23
  contentTypes.has(provided)
@@ -35,9 +35,9 @@ export function createContentTypeMiddleware(targetContentTypes, shouldThrow = tr
35
35
  }
36
36
 
37
37
  /** @type {Handler} */
38
- export function unsupportedMediaType(request) {
38
+ export function unsupportedMediaType(request, _response, _next) {
39
39
  const { method } = request;
40
- const url = request.originalUrl.split('?').at(0) ?? '/';
40
+ const url = request.originalUrl.split('?', 1).at(0) ?? '/';
41
41
  const contentType = request.headers['content-type'];
42
42
 
43
43
  throw new UnsupportedMediaType(
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  /**
8
- * @type {JsonSchema}
8
+ * @type {typeof JsonSchema | undefined}
9
9
  */
10
10
  let schema;
11
11
  try {
@@ -21,7 +21,8 @@ export function errorHandlerMiddleware(error, request, response, _next) {
21
21
  : 500,
22
22
  );
23
23
 
24
- for (const { format, test } of request.app.errorHandlers ?? []) {
24
+ const errorHandlers = request.app.errorHandlers ?? [];
25
+ for (const { format, test } of errorHandlers) {
25
26
  if (test(error)) {
26
27
  response.json({
27
28
  errors: format(error),
@@ -10,11 +10,15 @@ const fallbackFilters = [
10
10
  */
11
11
 
12
12
  /**
13
- * @param {string} requestPath - The path to test.
13
+ * @param {string | undefined | null} [requestPath] - The path to test.
14
14
  * @param {Filter[]} [filters] - A list of paths to filter out.
15
15
  * @returns {boolean}
16
16
  */
17
17
  export function shouldFilterOutRequest(requestPath, filters = fallbackFilters) {
18
+ if (requestPath == null) {
19
+ return false;
20
+ }
21
+
18
22
  for (const filter of filters) {
19
23
  if (filter instanceof RegExp && filter.test(requestPath)) {
20
24
  return true;
@@ -1,20 +1,34 @@
1
1
  /**
2
2
  * @import { Socket } from 'node:net'
3
+ * @import { Logger as LoggerType } from '@darksheep/logger'
3
4
  * @import { Handler } from '../../express.js'
4
5
  * @import { Filter } from './filter.js'
5
6
  */
6
7
 
7
- import { Logger } from '@darksheep/logger';
8
8
  import { pruneShallow } from '@darksheep/prune';
9
9
  import onFinished from 'on-finished';
10
10
 
11
11
  import { shouldFilterOutRequest } from './filter.js';
12
12
 
13
+ async function getLogger() {
14
+ try {
15
+ const { Logger } = await import('@darksheep/logger');
16
+
17
+ return Logger;
18
+ } catch {
19
+ // optional peer dependency
20
+ }
21
+ }
22
+
23
+ const Logger = await getLogger();
24
+
13
25
  /** @type {WeakMap<Socket, number>} */
14
26
  const sockets = new WeakMap();
15
27
 
28
+ const wrap = Logger?.wrap ?? ((_ctx, fn) => fn());
29
+
16
30
  /**
17
- * @param {Logger} logger - A callback that can be bound to the request.
31
+ * @param {LoggerType} logger - A callback that can be bound to the request.
18
32
  * @param {Filter[]} [filters] - A list of requests to not log.
19
33
  * @returns {Handler}
20
34
  */
@@ -25,25 +39,25 @@ export function createRequestLoggerMiddleware(
25
39
  return (request, response, next) => {
26
40
  request.logger = logger;
27
41
 
28
- Logger.wrap({
42
+ wrap({
29
43
  request: request,
30
44
  trail: request.trail,
31
45
  }, () => {
32
- const [ requestPath ] = request.originalUrl.split('?', 1);
33
- if (
34
- requestPath == null ||
35
- shouldFilterOutRequest(requestPath, filters)
36
- ) {
37
- next();
38
- return;
39
- }
40
-
41
46
  const startBytesRead = sockets.get(request.socket) ?? 0;
42
47
  const startBytesWritten = request.socket.bytesWritten;
43
48
 
44
49
  const requestStartMs = Date.now();
45
50
  onFinished(response, (error) => {
46
51
  sockets.set(request.socket, request.socket.bytesRead);
52
+ const [ requestPath ] = request.originalUrl.split('?', 1);
53
+
54
+ if (
55
+ shouldFilterOutRequest(requestPath, filters) === true &&
56
+ response.statusCode < 400 &&
57
+ error == null
58
+ ) {
59
+ return;
60
+ }
47
61
 
48
62
  const message = `${request.method} ${requestPath} ${response.statusCode}`;
49
63
  const context = pruneShallow({
@@ -1,8 +1,10 @@
1
+ /**
2
+ * @import { Handler } from '../../express.js'
3
+ */
4
+ import type { Handler } from '../../express.js';
1
5
  /**
2
6
  * @param {string | string[]} targetContentTypes - The permitted content types.
3
7
  * @param {boolean} [shouldThrow] - Should the middleware throw an error.
4
8
  * @returns {Handler}
5
9
  */
6
- export function createContentTypeMiddleware(targetContentTypes: string | string[], shouldThrow?: boolean): Handler;
7
- export function unsupportedMediaType(req: import(".store/@types-express-serve-static-core-npm-5.1.0-227fccbb7d/package").Request<import(".store/@types-express-serve-static-core-npm-5.1.0-227fccbb7d/package").ParamsDictionary, any, any, import(".store/@types-qs-npm-6.14.0-e27d9ca044/package").ParsedQs, Record<string, any>>, res: import(".store/@types-express-serve-static-core-npm-5.1.0-227fccbb7d/package").Response<any, Record<string, any>, number>, next: import(".store/@types-express-serve-static-core-npm-5.1.0-227fccbb7d/package").NextFunction): unknown;
8
- import type { Handler } from '../../express.js';
10
+ export declare function createContentTypeMiddleware(targetContentTypes: string | string[], shouldThrow?: boolean): Handler;
@@ -1,7 +1,10 @@
1
1
  /**
2
- * @param {Record<string, Handler | Handler[]>} contentTypeRoutes - An object containing the contentType and routes.
3
- * @returns {Router}
2
+ * @import { Handler } from '../../express.js'
4
3
  */
5
- export function createContentTypeRouter(contentTypeRoutes: Record<string, Handler | Handler[]>): Router;
6
4
  import type { Handler } from '../../express.js';
7
5
  import { Router } from 'express';
6
+ /**
7
+ * @param {Record<string, Handler | Handler[]>} contentTypeRoutes - An object containing the contentType and routes.
8
+ * @returns {Router}
9
+ */
10
+ export declare function createContentTypeRouter(contentTypeRoutes: Record<string, Handler | Handler[]>): Router;
@@ -1,17 +1,7 @@
1
1
  /**
2
2
  * @import { ErrorHandler } from '../../express.js';
3
3
  */
4
- /**
5
- * @typedef HttpErrorExtra
6
- * @property {boolean} expose - Should the error message be sent to the client.
7
- * @property {Record<string, string> | undefined} headers - Additional headers to send.
8
- * @property {number} statusCode - The response status code.
9
- */
10
- /**
11
- * @typedef {Error & HttpErrorExtra} HttpError
12
- */
13
- /** @type {ErrorHandler<HttpError>} */
14
- export const HttpErrorHandler: ErrorHandler<HttpError>;
4
+ import type { ErrorHandler } from '../../express.js';
15
5
  export type HttpErrorExtra = {
16
6
  /**
17
7
  * - Should the error message be sent to the client.
@@ -27,4 +17,14 @@ export type HttpErrorExtra = {
27
17
  statusCode: number;
28
18
  };
29
19
  export type HttpError = Error & HttpErrorExtra;
30
- import type { ErrorHandler } from '../../express.js';
20
+ /**
21
+ * @typedef HttpErrorExtra
22
+ * @property {boolean} expose - Should the error message be sent to the client.
23
+ * @property {Record<string, string> | undefined} headers - Additional headers to send.
24
+ * @property {number} statusCode - The response status code.
25
+ */
26
+ /**
27
+ * @typedef {Error & HttpErrorExtra} HttpError
28
+ */
29
+ /** @type {ErrorHandler<HttpError>} */
30
+ export declare const HttpErrorHandler: ErrorHandler<HttpError>;
@@ -1,4 +1,9 @@
1
- /** @type {ErrorHandler<RequestSchemaError | ResponseSchemaError>} */
2
- export const SchemaErrorHandler: ErrorHandler<JsonSchema.RequestSchemaError | JsonSchema.ResponseSchemaError>;
3
- import type * as JsonSchema from '@darksheep/json-schema';
1
+ /**
2
+ * @import * as JsonSchema from '@darksheep/json-schema';
3
+ * @import { ErrorHandler } from '../../express.js';
4
+ * @import { RequestSchemaError, ResponseSchemaError } from '@darksheep/json-schema';
5
+ */
4
6
  import type { ErrorHandler } from '../../express.js';
7
+ import type { RequestSchemaError, ResponseSchemaError } from '@darksheep/json-schema';
8
+ /** @type {ErrorHandler<RequestSchemaError | ResponseSchemaError>} */
9
+ export declare const SchemaErrorHandler: ErrorHandler<RequestSchemaError | ResponseSchemaError>;
@@ -1 +1,6 @@
1
- export function errorHandlerMiddleware(err: any, req: import(".store/@types-express-serve-static-core-npm-5.1.0-227fccbb7d/package").Request<import(".store/@types-express-serve-static-core-npm-5.1.0-227fccbb7d/package").ParamsDictionary, any, any, import(".store/@types-qs-npm-6.14.0-e27d9ca044/package").ParsedQs, Record<string, any>>, res: import(".store/@types-express-serve-static-core-npm-5.1.0-227fccbb7d/package").Response<any, Record<string, any>, number>, next: import(".store/@types-express-serve-static-core-npm-5.1.0-227fccbb7d/package").NextFunction): unknown;
1
+ /**
2
+ * @import {
3
+ * ErrorRequestHandler,
4
+ * } from '../../express.js'
5
+ */
6
+ export {};
@@ -1,17 +1,7 @@
1
1
  /**
2
2
  * @import { ErrorHandler } from '../../express.js';
3
3
  */
4
- /**
5
- * @typedef ZodIssue
6
- * @property {string} message - The error message for the path.
7
- * @property {string} code - The zod error code text.
8
- * @property {string} path - The path to the error in zod.
9
- */
10
- /**
11
- * @typedef {Error & { errors: ZodIssue[] }} ZodError
12
- */
13
- /** @type {ErrorHandler<ZodError>} */
14
- export const ZodErrorHandler: ErrorHandler<ZodError>;
4
+ import type { ErrorHandler } from '../../express.js';
15
5
  export type ZodIssue = {
16
6
  /**
17
7
  * - The error message for the path.
@@ -29,4 +19,14 @@ export type ZodIssue = {
29
19
  export type ZodError = Error & {
30
20
  errors: ZodIssue[];
31
21
  };
32
- import type { ErrorHandler } from '../../express.js';
22
+ /**
23
+ * @typedef ZodIssue
24
+ * @property {string} message - The error message for the path.
25
+ * @property {string} code - The zod error code text.
26
+ * @property {string} path - The path to the error in zod.
27
+ */
28
+ /**
29
+ * @typedef {Error & { errors: ZodIssue[] }} ZodError
30
+ */
31
+ /** @type {ErrorHandler<ZodError>} */
32
+ export declare const ZodErrorHandler: ErrorHandler<ZodError>;
package/types/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- export { createContentTypeMiddleware } from "./content-type/middleware.js";
2
- export { createContentTypeRouter } from "./content-type/router.js";
3
- export { createRequestLoggerMiddleware } from "./logger/middleware.js";
4
- export { createRequestIdMiddleware } from "./request-id/middleware.js";
5
- export { errorHandlerMiddleware } from "./error-handler/middleware.js";
6
- export { notFoundMiddleware } from "./not-found/middleware.js";
7
- export { HttpErrorHandler } from "./error-handler/http.handler.js";
8
- export { SchemaErrorHandler } from "./error-handler/json-schema.handler.js";
9
- export { ZodErrorHandler } from "./error-handler/zod.handler.js";
1
+ export { createContentTypeMiddleware } from './content-type/middleware.js';
2
+ export { createContentTypeRouter } from './content-type/router.js';
3
+ export { createRequestLoggerMiddleware } from './logger/middleware.js';
4
+ export { createRequestIdMiddleware } from './request-id/middleware.js';
5
+ export { errorHandlerMiddleware } from './error-handler/middleware.js';
6
+ export { notFoundMiddleware } from './not-found/middleware.js';
7
+ export { HttpErrorHandler } from './error-handler/http.handler.js';
8
+ export { SchemaErrorHandler } from './error-handler/json-schema.handler.js';
9
+ export { ZodErrorHandler } from './error-handler/zod.handler.js';
@@ -1,10 +1,10 @@
1
+ export type Filter = string | RegExp;
1
2
  /**
2
3
  * @typedef {string|RegExp} Filter
3
4
  */
4
5
  /**
5
- * @param {string} requestPath - The path to test.
6
+ * @param {string | undefined | null} [requestPath] - The path to test.
6
7
  * @param {Filter[]} [filters] - A list of paths to filter out.
7
8
  * @returns {boolean}
8
9
  */
9
- export function shouldFilterOutRequest(requestPath: string, filters?: Filter[]): boolean;
10
- export type Filter = string | RegExp;
10
+ export declare function shouldFilterOutRequest(requestPath?: string | undefined | null, filters?: Filter[]): boolean;
@@ -1,9 +1,15 @@
1
1
  /**
2
- * @param {Logger} logger - A callback that can be bound to the request.
2
+ * @import { Socket } from 'node:net'
3
+ * @import { Logger as LoggerType } from '@darksheep/logger'
4
+ * @import { Handler } from '../../express.js'
5
+ * @import { Filter } from './filter.js'
6
+ */
7
+ import type { Logger as LoggerType } from '@darksheep/logger';
8
+ import type { Handler } from '../../express.js';
9
+ import type { Filter } from './filter.js';
10
+ /**
11
+ * @param {LoggerType} logger - A callback that can be bound to the request.
3
12
  * @param {Filter[]} [filters] - A list of requests to not log.
4
13
  * @returns {Handler}
5
14
  */
6
- export function createRequestLoggerMiddleware(logger: Logger, filters?: Filter[]): Handler;
7
- import { Logger } from '@darksheep/logger';
8
- import type { Filter } from './filter.js';
9
- import type { Handler } from '../../express.js';
15
+ export declare function createRequestLoggerMiddleware(logger: LoggerType, filters?: Filter[]): Handler;
@@ -1,10 +1,9 @@
1
+ import type { NextFunction } from 'express';
2
+ import type { Request, Response } from '../../express.js';
1
3
  /**
2
4
  * @param {Request} request - The express request.
3
5
  * @param {Response} _response - The express response.
4
6
  * @param {NextFunction} next - The next handler.
5
7
  * @returns {void}
6
8
  */
7
- export function notFoundMiddleware(request: Request, _response: Response, next: NextFunction): void;
8
- import type { Request } from '../../express.js';
9
- import type { Response } from '../../express.js';
10
- import type { NextFunction } from 'express';
9
+ export declare function notFoundMiddleware(request: Request, _response: Response, next: NextFunction): void;
@@ -1,13 +1,12 @@
1
+ import type { Handler, Request } from '../../express.js';
1
2
  /**
2
3
  * @param {Request} request - The express request.
3
4
  * @param {string} [headerName] - The name of the header used in correlation.
4
5
  * @returns {string}
5
6
  */
6
- export function getTrail(request: Request, headerName?: string): string;
7
+ export declare function getTrail(request: Request, headerName?: string): string;
7
8
  /**
8
9
  * @param {string} [headerName] - The name of a header to include in the response with the trail.
9
10
  * @returns {Handler}
10
11
  */
11
- export function createRequestIdMiddleware(headerName?: string): Handler;
12
- import type { Request } from '../../express.js';
13
- import type { Handler } from '../../express.js';
12
+ export declare function createRequestIdMiddleware(headerName?: string): Handler;