@wthek/koa-middleware 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Himanshu Bansal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md CHANGED
@@ -1,3 +1,192 @@
1
- # Temporary Holding Version
1
+ # Official @wthek Extension – Koa Middleware for `http-error-kit`
2
+
3
+ **Seamless Koa Error Handling with @wthek**
4
+
5
+ _Built for applications powered by [http-error-kit][http-error-kit], this middleware ensures that all `http-error-kit` errors are properly formatted and returned with the correct HTTP status codes in Koa._
6
+
7
+ > 💡 What the HEK?! Need a hassle-free way to manage error responses for `http-error-kit` errors in Koa? `@wthek/koa-middleware` has got you covered!
8
+
9
+ ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/skillnter/wthek-koa-middleware/main.yml)
10
+ [![npm version](https://img.shields.io/npm/v/%40wthek%2Fkoa-middleware?color=brightgreen)](https://www.npmjs.com/package/@wthek/koa-middleware)
11
+ [![GitHub license](https://img.shields.io/github/license/skillnter/wthek-koa-middleware?color=brightgreen)](LICENSE)
12
+ ![NPM Type Definitions](https://img.shields.io/npm/types/%40wthek%2Fkoa-middleware)
13
+ [![GitHub Issues](https://img.shields.io/github/issues/Skillnter/wthek-koa-middleware)](https://github.com/Skillnter/wthek-koa-middleware/issues)
14
+ ![npm](https://img.shields.io/npm/dy/%40wthek%2Fkoa-middleware)
15
+ [![Bundle Size](https://img.shields.io/bundlephobia/minzip/%40wthek%2Fkoa-middleware)](https://bundlephobia.com/package/%40wthek%2Fkoa-middleware)
16
+ [![Codacy Badge](https://app.codacy.com/project/badge/Grade/8cb84abac51c4e67b0e8c7a0730d1a40)](https://app.codacy.com/gh/Skillnter/wthek-koa-middleware/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)
17
+ [![Codacy Badge](https://app.codacy.com/project/badge/Coverage/8cb84abac51c4e67b0e8c7a0730d1a40)](https://app.codacy.com/gh/Skillnter/wthek-koa-middleware/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage)
18
+ [![Socket Badge](https://socket.dev/api/badge/npm/package/@wthek/koa-middleware/)](https://socket.dev/npm/package/@wthek/koa-middleware/overview/)
19
+ [![Github Sponsors](https://img.shields.io/badge/GitHub%20Sponsors-30363D?&logo=GitHub-Sponsors&logoColor=EA4AAA)](https://github.com/sponsors/Skillnter)
20
+ [![Open Collective](https://img.shields.io/badge/Open%20Collective-3385FF?logo=open-collective&logoColor=white)](https://opencollective.com/skillnter)
21
+ [![Buy Me A Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-ffdd00?&logo=buy-me-a-coffee&logoColor=black)](https://www.buymeacoffee.com/skillnter)
22
+ [![Patreon](https://img.shields.io/badge/Patreon-F96854?logo=patreon&logoColor=white)](https://www.patreon.com/skillnter)
23
+ [![PayPal](https://img.shields.io/badge/PayPal-003087?logo=paypal&logoColor=fff)](https://www.paypal.me/skillnte)
24
+
25
+ ## Features
26
+
27
+ - **Official `http-error-kit` Extension** – The idiomatic error-handling middleware for Koa applications.
28
+ - **Onion Architecture First** – Wraps downstream middleware in `try ... catch` at the top of your Koa stack.
29
+ - **Auto-sets HTTP Status & Body** – Automatically sets `ctx.status` and `ctx.body` from `KitHttpError` or `KitGeneralError`.
30
+ - **Streaming & Header Safety** – Automatically avoids double writes if `ctx.headerSent` is true.
31
+ - **Configurable Logging** – Support for boolean logging or custom logger callbacks (Pino, Winston).
32
+ - **`handleUnknownErrors` Option** – Catch unexpected errors and return structured 500 JSON responses.
33
+ - **`emitAppError` Option** – Optionally trigger Koa's application-level `app.emit('error', err, ctx)` for central monitoring.
34
+
35
+ ## Table of Contents
36
+
37
+ - [Installation](#installation)
38
+ - [Usage](#usage)
39
+ - [Options](#options)
40
+ - [Custom Formatting with KitHttpErrorConfig](#custom-formatting-with-kithttperrorconfig)
41
+ - [AI Agent Integration](#ai-agent-integration)
42
+ - [Explore More WTHek Extensions](#explore-more-wthek-extensions)
43
+ - [People](#people)
44
+ - [Donations](#donations)
45
+ - [License](#license)
46
+
47
+ ## Installation
48
+
49
+ ```console
50
+ npm install @wthek/koa-middleware
51
+ ```
52
+
53
+ ## Usage
54
+
55
+ `KitKoaMiddleware` supports both **direct registration** (passing `app` as first argument, like Fastify & Hono) and the **middleware factory pattern** (passing returned middleware into `app.use()`, like Express & standard Koa).
56
+
57
+ Place it **near or at the very top** of your Koa stack so it wraps all downstream middleware in `try ... catch`.
58
+
59
+ ### Pattern 1: Direct Registration (Recommended)
60
+
61
+ ```typescript
62
+ import Koa from "koa";
63
+ import { KitKoaMiddleware } from "@wthek/koa-middleware";
64
+ import { KitHttpError } from "http-error-kit";
65
+ import { NOT_FOUND } from "http-response-status-code";
66
+
67
+ const app = new Koa();
68
+
69
+ // 1. Direct registration at the top of the stack
70
+ KitKoaMiddleware(app, {
71
+ log: true,
72
+ handleUnknownErrors: true,
73
+ emitAppError: true,
74
+ });
75
+
76
+ // 2. Downstream routes / middleware
77
+ app.use(async (ctx) => {
78
+ if (ctx.path === "/user") {
79
+ throw new KitHttpError(NOT_FOUND, "User Not Found", {
80
+ userId: ctx.query.id,
81
+ });
82
+ }
83
+ ctx.body = { message: "Hello Koa" };
84
+ });
85
+
86
+ app.listen(3000);
87
+ ```
88
+
89
+ ### Pattern 2: Middleware Factory (`app.use`)
90
+
91
+ ```typescript
92
+ // Alternatively, pass into app.use() directly:
93
+ app.use(
94
+ KitKoaMiddleware({
95
+ log: true,
96
+ handleUnknownErrors: true,
97
+ emitAppError: true,
98
+ }),
99
+ );
100
+ ```
101
+
102
+ ### Custom Logging Example
103
+
104
+ ```typescript
105
+ import Koa from "koa";
106
+ import { KitKoaMiddleware } from "@wthek/koa-middleware";
107
+ import pino from "pino";
108
+
109
+ const logger = pino();
110
+ const app = new Koa();
111
+
112
+ app.use(
113
+ KitKoaMiddleware({
114
+ log: (error, ctx) => {
115
+ logger.error({ err: error, url: ctx.url, method: ctx.method }, "Request failed");
116
+ },
117
+ handleUnknownErrors: true,
118
+ }),
119
+ );
120
+ ```
121
+
122
+ ## Options
123
+
124
+ | Option | Type | Default | Description |
125
+ | :--- | :--- | :--- | :--- |
126
+ | `log` | `boolean \| ((error: unknown, ctx: Context) => void)` | `false` | When `true`, logs via `console.error`. When a function is provided, receives `(error, ctx)` for custom logging. |
127
+ | `handleUnknownErrors` | `boolean` | `false` | When `true`, unhandled non-Kit errors return a structured 500 JSON response instead of re-throwing. |
128
+ | `emitAppError` | `boolean` | `false` | When `true`, emits `ctx.app.emit("error", error, ctx)` so central Koa error listeners can monitor errors. |
129
+
130
+ ## Custom Formatting with `KitHttpErrorConfig`
131
+
132
+ Customize the output JSON payload across all errors globally:
133
+
134
+ ```typescript
135
+ import { KitHttpErrorConfig } from "http-error-kit";
136
+
137
+ KitHttpErrorConfig.configureFormatter(
138
+ (statusCode, message, details, ...args) => ({
139
+ timestamp: new Date().toISOString(),
140
+ status: statusCode,
141
+ error: message,
142
+ details,
143
+ }),
144
+ );
145
+ ```
146
+
147
+ ## AI Agent Integration
148
+
149
+ When building with AI coding assistants (Claude Code, Cursor, GitHub Copilot, Antigravity, Devin), add the following directive to your project's `.cursorrules`, `.github/copilot-instructions.md`, or system prompt:
150
+
151
+ ```markdown
152
+ ### Koa Error Handling Rule
153
+ - Always throw semantic error classes from `http-error-kit` (e.g., `BadRequestError`, `NotFoundError`, `UnauthorizedError`) inside downstream Koa middleware and routes.
154
+ - In Koa bootstrap, register `@wthek/koa-middleware` at the top of the middleware stack: `KitKoaMiddleware(app, { handleUnknownErrors: true })`.
155
+ - If using centralized monitoring (Sentry, Datadog), enable `emitAppError: true` so `app.on("error")` continues to receive errors.
156
+ ```
157
+
158
+ ## Explore More WTHek Extensions
159
+
160
+ The WTHek ecosystem continues to grow with new extensions to simplify error handling across various frameworks and libraries. Stay updated with the latest tools that integrate seamlessly with `http-error-kit`.
161
+
162
+ **Check out the official list of extensions**: [Official Extensions List](https://github.com/Skillnter/http-error-kit/wiki/Official-Extensions-List)
163
+
164
+ ## People
165
+
166
+ The original author of the project is [Himanshu Bansal][skillnter]
167
+
168
+ ## Donations
169
+
170
+ **This is all voluntary work**, so if you want to support my efforts you can:
171
+
172
+ - [Buy Me A Coffee](https://www.buymeacoffee.com/skillnter)
173
+ - [PayPal](https://www.paypal.me/skillnte)
174
+ - [GitHub Sponsors](https://github.com/sponsors/Skillnter)
175
+ - [Patreon](https://www.patreon.com/skillnter)
176
+ - [Open Collective](https://opencollective.com/skillnter)
177
+
178
+ You can also use crypto:
179
+
180
+ ![BNB: 0x1D59a291391a3CE17C63D5dC50F258Dc0Ab62889](https://img.shields.io/badge/BNB-0x1D59a291391a3CE17C63D5dC50F258Dc0Ab62889-brightgreen)
181
+
182
+ ![BTC: bc1p22h4nsad5d8ketyhuvf0vyva6unttxwzzqvkty5r839as0mlclgs72d3mf](https://img.shields.io/badge/BTC-bc1p22h4nsad5d8ketyhuvf0vyva6unttxwzzqvkty5r839as0mlclgs72d3mf-brightgreen)
183
+
184
+ ![ETH: 0x1D59a291391a3CE17C63D5dC50F258Dc0Ab62889](https://img.shields.io/badge/ETH-0x1D59a291391a3CE17C63D5dC50F258Dc0Ab62889-brightgreen)
185
+
186
+ ## License
187
+
188
+ `@wthek/koa-middleware` project is open-sourced software licensed under the [MIT license](LICENSE) by [Himanshu Bansal][skillnter].
189
+
190
+ [skillnter]: https://github.com/Skillnter/
191
+ [http-error-kit]: https://www.npmjs.com/package/http-error-kit
2
192
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
@@ -0,0 +1,68 @@
1
+ import type { Context, default as Koa, Middleware } from "koa";
2
+ /**
3
+ * Configuration options for KitKoaMiddleware.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * const options: IKitKoaMiddlewareOptions = {
8
+ * log: true,
9
+ * handleUnknownErrors: true,
10
+ * emitAppError: true,
11
+ * };
12
+ * ```
13
+ */
14
+ export interface IKitKoaMiddlewareOptions {
15
+ /**
16
+ * Optional logger callback or boolean flag.
17
+ * When set to `true`, errors are logged via `console.error`.
18
+ * When set to a function, the function receives the error and context
19
+ * for custom logging (e.g. Pino, Winston).
20
+ *
21
+ * @default false
22
+ */
23
+ log?: boolean | ((error: unknown, ctx: Context) => void);
24
+ /**
25
+ * If true, catches non-Kit errors and returns a structured 500 JSON response
26
+ * instead of re-throwing them downstream.
27
+ *
28
+ * @default false
29
+ */
30
+ handleUnknownErrors?: boolean;
31
+ /**
32
+ * Optional flag to emit Koa application error events via
33
+ * `ctx.app.emit("error", error, ctx)`. Useful for centralized error monitoring
34
+ * tools (such as Sentry or Datadog) that listen on `app.on("error")`.
35
+ *
36
+ * @default false
37
+ */
38
+ emitAppError?: boolean;
39
+ }
40
+ /**
41
+ * Koa error-handling middleware for applications powered by `http-error-kit`.
42
+ * Supports two usage patterns:
43
+ * 1. Direct registration: `KitKoaMiddleware(app, options)` (like Fastify & Hono)
44
+ * 2. Middleware factory: `app.use(KitKoaMiddleware(options))` (like Express & Koa idioms)
45
+ *
46
+ * In accordance with Koa's onion architecture, this middleware wraps downstream
47
+ * handlers in a `try ... catch` block.
48
+ *
49
+ * @param {Koa | IKitKoaMiddlewareOptions} [appOrOptions] Koa application instance or options object.
50
+ * @param {IKitKoaMiddlewareOptions} [options] Options when app is passed as first argument.
51
+ * @returns {Middleware} A Koa-compatible middleware function.
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * import Koa from "koa";
56
+ * import { KitKoaMiddleware } from "@wthek/koa-middleware";
57
+ *
58
+ * const app = new Koa();
59
+ *
60
+ * // Pattern 1: Direct registration (Hono / Fastify style)
61
+ * KitKoaMiddleware(app, { log: true, handleUnknownErrors: true });
62
+ *
63
+ * // Pattern 2: Middleware factory (Express / Koa app.use style)
64
+ * app.use(KitKoaMiddleware({ log: true, handleUnknownErrors: true }));
65
+ * ```
66
+ */
67
+ export declare const KitKoaMiddleware: (appOrOptions?: Koa | IKitKoaMiddlewareOptions, options?: IKitKoaMiddlewareOptions) => Middleware;
68
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.KitKoaMiddleware = void 0;
40
+ var http_error_kit_1 = require("http-error-kit");
41
+ var http_response_status_code_1 = require("http-response-status-code");
42
+ /**
43
+ * Helper to log errors according to options.
44
+ */
45
+ var logError = function (error, ctx, log) {
46
+ if (!log) {
47
+ return;
48
+ }
49
+ if (typeof log === "function") {
50
+ log(error, ctx);
51
+ return;
52
+ }
53
+ console.error(error);
54
+ };
55
+ /**
56
+ * Helper to emit application error events if configured.
57
+ */
58
+ var emitError = function (error, ctx, emitAppError) {
59
+ if (emitAppError && ctx.app && typeof ctx.app.emit === "function") {
60
+ ctx.app.emit("error", error, ctx);
61
+ }
62
+ };
63
+ /**
64
+ * Helper to format and assign Kit error payloads to context.
65
+ */
66
+ var handleKitError = function (error, ctx) {
67
+ var _a;
68
+ var inputs = error.getInputs();
69
+ var statusCode = ((_a = inputs === null || inputs === void 0 ? void 0 : inputs.statusCode) !== null && _a !== void 0 ? _a : http_response_status_code_1.INTERNAL_SERVER_ERROR);
70
+ var payload = typeof error.toJSON === "function" ? error.toJSON() : error;
71
+ ctx.status = statusCode;
72
+ ctx.body = payload;
73
+ };
74
+ /**
75
+ * Helper to format structured 500 response for unknown errors.
76
+ */
77
+ var handleUnknownError = function (ctx) {
78
+ ctx.status = http_response_status_code_1.INTERNAL_SERVER_ERROR;
79
+ ctx.body = {
80
+ message: (0, http_response_status_code_1.getStatusDescription)(http_response_status_code_1.INTERNAL_SERVER_ERROR),
81
+ statusCode: http_response_status_code_1.INTERNAL_SERVER_ERROR,
82
+ };
83
+ };
84
+ /**
85
+ * Koa error-handling middleware for applications powered by `http-error-kit`.
86
+ * Supports two usage patterns:
87
+ * 1. Direct registration: `KitKoaMiddleware(app, options)` (like Fastify & Hono)
88
+ * 2. Middleware factory: `app.use(KitKoaMiddleware(options))` (like Express & Koa idioms)
89
+ *
90
+ * In accordance with Koa's onion architecture, this middleware wraps downstream
91
+ * handlers in a `try ... catch` block.
92
+ *
93
+ * @param {Koa | IKitKoaMiddlewareOptions} [appOrOptions] Koa application instance or options object.
94
+ * @param {IKitKoaMiddlewareOptions} [options] Options when app is passed as first argument.
95
+ * @returns {Middleware} A Koa-compatible middleware function.
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * import Koa from "koa";
100
+ * import { KitKoaMiddleware } from "@wthek/koa-middleware";
101
+ *
102
+ * const app = new Koa();
103
+ *
104
+ * // Pattern 1: Direct registration (Hono / Fastify style)
105
+ * KitKoaMiddleware(app, { log: true, handleUnknownErrors: true });
106
+ *
107
+ * // Pattern 2: Middleware factory (Express / Koa app.use style)
108
+ * app.use(KitKoaMiddleware({ log: true, handleUnknownErrors: true }));
109
+ * ```
110
+ */
111
+ var KitKoaMiddleware = function (appOrOptions, options) {
112
+ var _a;
113
+ if (appOrOptions && typeof appOrOptions.use === "function") {
114
+ var middleware = (0, exports.KitKoaMiddleware)(options);
115
+ appOrOptions.use(middleware);
116
+ return middleware;
117
+ }
118
+ var _b = (_a = appOrOptions) !== null && _a !== void 0 ? _a : {}, _c = _b.log, log = _c === void 0 ? false : _c, _d = _b.handleUnknownErrors, handleUnknownErrors = _d === void 0 ? false : _d, _e = _b.emitAppError, emitAppError = _e === void 0 ? false : _e;
119
+ return function (ctx, next) { return __awaiter(void 0, void 0, void 0, function () {
120
+ var error_1;
121
+ return __generator(this, function (_a) {
122
+ switch (_a.label) {
123
+ case 0:
124
+ _a.trys.push([0, 2, , 3]);
125
+ return [4 /*yield*/, next()];
126
+ case 1:
127
+ _a.sent();
128
+ return [3 /*break*/, 3];
129
+ case 2:
130
+ error_1 = _a.sent();
131
+ logError(error_1, ctx, log);
132
+ emitError(error_1, ctx, emitAppError);
133
+ if (ctx.headerSent) {
134
+ return [2 /*return*/];
135
+ }
136
+ if (error_1 instanceof http_error_kit_1.KitHttpError || error_1 instanceof http_error_kit_1.KitGeneralError) {
137
+ handleKitError(error_1, ctx);
138
+ return [2 /*return*/];
139
+ }
140
+ if (handleUnknownErrors) {
141
+ handleUnknownError(ctx);
142
+ return [2 /*return*/];
143
+ }
144
+ throw error_1;
145
+ case 3: return [2 /*return*/];
146
+ }
147
+ });
148
+ }); };
149
+ };
150
+ exports.KitKoaMiddleware = KitKoaMiddleware;
package/llms.txt ADDED
@@ -0,0 +1,56 @@
1
+ # @wthek/koa-middleware
2
+
3
+ > Production-safe Koa error-handling middleware for `http-error-kit`.
4
+
5
+ ## Overview
6
+ `@wthek/koa-middleware` catches `KitHttpError` and `KitGeneralError` instances thrown in Koa downstream middleware and routes, automatically setting the HTTP status code and serializing the error into a structured JSON payload. It respects Koa's onion architecture, guards against header-sent errors (`ctx.headerSent`), provides configurable logging, optionally emits Koa `error` events for central telemetry, and handles unknown exceptions.
7
+
8
+ ## Installation
9
+ ```bash
10
+ npm install @wthek/koa-middleware http-error-kit http-response-status-code
11
+ ```
12
+
13
+ ## Quick Start
14
+ ```typescript
15
+ import Koa from "koa";
16
+ import { KitKoaMiddleware } from "@wthek/koa-middleware";
17
+ import { BadRequestError, NotFoundError } from "http-error-kit";
18
+
19
+ const app = new Koa();
20
+
21
+ // Pattern 1: Direct registration (app passed as first argument)
22
+ KitKoaMiddleware(app, { log: true, handleUnknownErrors: true, emitAppError: true });
23
+
24
+ // Pattern 2: Standard Koa app.use()
25
+ // app.use(KitKoaMiddleware({ log: true, handleUnknownErrors: true }));
26
+
27
+ app.use(async (ctx) => {
28
+ if (ctx.path === "/api/users") {
29
+ throw new BadRequestError("Query parameter missing");
30
+ }
31
+ throw new NotFoundError("Route not found");
32
+ });
33
+
34
+ app.listen(3000);
35
+ ```
36
+
37
+ ## API Reference
38
+
39
+ ### `KitKoaMiddleware(appOrOptions?: Koa | IKitKoaMiddlewareOptions, options?: IKitKoaMiddlewareOptions)`
40
+ Returns or registers a Koa middleware: `(ctx: Context, next: Next) => Promise<void>`.
41
+ - If a Koa app is passed as the first parameter, it calls `app.use()` automatically.
42
+ - Otherwise, returns standard middleware for `app.use(KitKoaMiddleware(options))`.
43
+
44
+ #### Options (`IKitKoaMiddlewareOptions`)
45
+ - `log` (`boolean | ((error: unknown, ctx: Context) => void)`, default: `false`):
46
+ When `true`, logs via `console.error`. When a function is provided, calls custom logger.
47
+ - `handleUnknownErrors` (`boolean`, default: `false`):
48
+ When `true`, catches non-Kit errors and assigns a structured 500 JSON response instead of re-throwing downstream.
49
+ - `emitAppError` (`boolean`, default: `false`):
50
+ When `true`, emits `ctx.app.emit("error", error, ctx)` for central error listeners (Sentry, Datadog).
51
+
52
+ ## Safety Rules for AI Agents
53
+ 1. Place `app.use(KitKoaMiddleware(...))` at the very beginning of the middleware pipeline to wrap all downstream handlers.
54
+ 2. Throw errors directly from `http-error-kit` (e.g., `throw new NotFoundError(...)`) inside downstream handlers.
55
+ 3. Koa async functions automatically catch thrown errors and return control up the onion stack.
56
+
package/package.json CHANGED
@@ -1,6 +1,119 @@
1
1
  {
2
2
  "name": "@wthek/koa-middleware",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Production-safe Koa error-handling middleware for http-error-kit. Maps KitHttpError instances to structured JSON responses with correct HTTP status codes and optional logging.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "sideEffects": false,
15
+ "scripts": {
16
+ "test": "jest --config jest.config.ts",
17
+ "build": "tsc --build",
18
+ "coverage": "jest --coverage --config jest.config.ts",
19
+ "prepublishOnly": "npm run test && npm run build"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/Skillnter/wthek-koa-middleware.git"
24
+ },
25
+ "keywords": [
26
+ "http",
27
+ "error",
28
+ "kit",
29
+ "http-errors",
30
+ "custom-errors",
31
+ "error-handling",
32
+ "koa",
33
+ "koa2",
34
+ "koa-middleware",
35
+ "koa-error-handler",
36
+ "koajs",
37
+ "rest-api",
38
+ "status-codes",
39
+ "api-error",
40
+ "json-error",
41
+ "rfc-7807",
42
+ "rfc-9457",
43
+ "structured-errors",
44
+ "api-error-response",
45
+ "ai-agent",
46
+ "agent-skill",
47
+ "antigravity",
48
+ "cursor",
49
+ "copilot",
50
+ "typescript",
51
+ "middleware",
52
+ "wthek",
53
+ "skillnter"
54
+ ],
55
+ "author": "Himanshu Bansal <skillhimanshubansal@gmail.com>",
56
+ "license": "MIT",
57
+ "engines": {
58
+ "node": ">=18"
59
+ },
60
+ "bugs": {
61
+ "url": "https://github.com/Skillnter/wthek-koa-middleware/issues"
62
+ },
63
+ "homepage": "https://github.com/Skillnter/wthek-koa-middleware#readme",
64
+ "dependencies": {
65
+ "http-error-kit": "^1.5.0",
66
+ "http-response-status-code": "^1.9.0"
67
+ },
68
+ "peerDependencies": {
69
+ "koa": "^2.0.0 || ^3.0.0"
70
+ },
71
+ "devDependencies": {
72
+ "@types/jest": "^29.5.14",
73
+ "@types/koa": "^2.15.0",
74
+ "@types/node": "^22.13.4",
75
+ "@types/supertest": "^6.0.2",
76
+ "@typescript-eslint/eslint-plugin": "^8.22.0",
77
+ "eslint": "^8.57.1",
78
+ "eslint-plugin-security": "^3.0.1",
79
+ "jest": "^29.7.0",
80
+ "koa": "^2.15.3",
81
+ "supertest": "^7.0.0",
82
+ "ts-jest": "^29.2.5",
83
+ "ts-node": "^10.9.2",
84
+ "tslib": "^2.8.1",
85
+ "typescript": "^5.7.3"
86
+ },
87
+ "publishConfig": {
88
+ "@skillnter:registry": "https://npm.pkg.github.com/"
89
+ },
90
+ "files": [
91
+ "dist/index.js",
92
+ "dist/index.d.ts",
93
+ "llms.txt",
94
+ "LICENSE"
95
+ ],
96
+ "funding": [
97
+ {
98
+ "type": "github",
99
+ "url": "https://github.com/sponsors/Skillnter"
100
+ },
101
+ {
102
+ "type": "patreon",
103
+ "url": "https://www.patreon.com/skillnter"
104
+ },
105
+ {
106
+ "type": "open_collective",
107
+ "url": "https://opencollective.com/skillnter"
108
+ },
109
+ {
110
+ "type": "buy_me_a_coffee",
111
+ "url": "https://buymeacoffee.com/skillnter"
112
+ },
113
+ {
114
+ "type": "paypal",
115
+ "url": "https://paypal.me/skillhimanshubansal"
116
+ }
117
+ ]
118
+ }
119
+