expressentials 0.0.1
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 +21 -0
- package/README.md +116 -0
- package/dist/index.cjs +530 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +268 -0
- package/dist/index.d.ts +268 -0
- package/dist/index.js +467 -0
- package/dist/index.js.map +1 -0
- package/package.json +61 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gautam Suthar
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# expressentials
|
|
2
|
+
|
|
3
|
+
Essential Express.js helpers — status codes, errors, logging, validation, and more.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { status, NotFound, errorHandler, requestId } from "expressentials";
|
|
7
|
+
|
|
8
|
+
app.use(requestId());
|
|
9
|
+
app.use(errorHandler());
|
|
10
|
+
|
|
11
|
+
app.get("/users/:id", (req, res) => {
|
|
12
|
+
throw new NotFound("User not found");
|
|
13
|
+
});
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
npm install expressentials
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Requires `express` as a peer dependency.
|
|
23
|
+
|
|
24
|
+
## Features
|
|
25
|
+
|
|
26
|
+
| Module | Description |
|
|
27
|
+
|--------|-------------|
|
|
28
|
+
| [status](./FEATURES.md#status--http-status-code-constants) | HTTP status code constants (`status.ok` → `200`) |
|
|
29
|
+
| [message](./FEATURES.md#message--human-readable-status-messages) | Human-readable messages (`message.created` → `"Created successfully"`) |
|
|
30
|
+
| [ApiError](./FEATURES.md#apierror--base-error-class) | Base error class with HTTP status codes |
|
|
31
|
+
| [Http Errors](./FEATURES.md#predefined-error-classes) | `NotFound`, `BadRequest`, `Forbidden`, etc. |
|
|
32
|
+
| [errorHandler](./FEATURES.md#errorhandler--express-error-handling-middleware) | Express error-handling middleware |
|
|
33
|
+
| [requestId](./FEATURES.md#requestid--request-id-middleware) | Request ID middleware (UUID, configurable header) |
|
|
34
|
+
| [requestContext](./FEATURES.md#requestcontext--request-scoped-logger--asynclocalstorage) | Request-scoped logger + AsyncLocalStorage context |
|
|
35
|
+
| [httpLogger](./FEATURES.md#httplogger--http-request-logging-middleware) | Auto-log requests with method, path, status, duration |
|
|
36
|
+
| [validate](./FEATURES.md#validate--request-validation-middleware-schema-adapter) | Request validation (Zod/Yup/ArkType adapter) |
|
|
37
|
+
| [asyncHandler](./FEATURES.md#asynchandler--async-route-handler-wrapper) | Async route handler wrapper |
|
|
38
|
+
| [timeout](./FEATURES.md#timeout--request-timeout-middleware) | Request timeout middleware (504 Gateway Timeout) |
|
|
39
|
+
| [healthCheck](./FEATURES.md#healthcheck--health-endpoint-helper) | Health check endpoint |
|
|
40
|
+
| [Logger](./FEATURES.md#logger--structured-json-logger) | Structured JSON logger |
|
|
41
|
+
| [Context](./FEATURES.md#context--asynclocalstorage-accessors) | AsyncLocalStorage accessors (`getLogger`, `getRequestId`) |
|
|
42
|
+
|
|
43
|
+
See [FEATURES.md](./FEATURES.md) for full documentation with all options and usage examples.
|
|
44
|
+
|
|
45
|
+
## Quick start
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import express from "express";
|
|
49
|
+
import {
|
|
50
|
+
requestId,
|
|
51
|
+
requestContext,
|
|
52
|
+
httpLogger,
|
|
53
|
+
validate,
|
|
54
|
+
asyncHandler,
|
|
55
|
+
errorHandler,
|
|
56
|
+
NotFound,
|
|
57
|
+
} from "expressentials";
|
|
58
|
+
import { z } from "zod";
|
|
59
|
+
|
|
60
|
+
const app = express();
|
|
61
|
+
|
|
62
|
+
app.use(express.json());
|
|
63
|
+
app.use(requestId());
|
|
64
|
+
app.use(requestContext());
|
|
65
|
+
app.use(httpLogger({ skip: (req) => req.url === "/health" }));
|
|
66
|
+
|
|
67
|
+
const createUserSchema = z.object({
|
|
68
|
+
name: z.string(),
|
|
69
|
+
email: z.string().email(),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
app.post(
|
|
73
|
+
"/users",
|
|
74
|
+
validate({ body: createUserSchema }),
|
|
75
|
+
asyncHandler(async (req, res) => {
|
|
76
|
+
req.log.info({ email: req.body.email }, "Creating user");
|
|
77
|
+
// ...
|
|
78
|
+
res.status(201).json({ id: "abc" });
|
|
79
|
+
}),
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
app.get("/health", (_req, res) => {
|
|
83
|
+
res.json({ status: "ok" });
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
app.use("*", () => {
|
|
87
|
+
throw new NotFound("Route not found");
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
app.use(errorHandler());
|
|
91
|
+
|
|
92
|
+
app.listen(3000);
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Scripts
|
|
96
|
+
|
|
97
|
+
| Script | Description |
|
|
98
|
+
|--------|-------------|
|
|
99
|
+
| `npm run build` | Build with tsup (ESM + CJS + types) |
|
|
100
|
+
| `npm run dev` | Watch mode |
|
|
101
|
+
| `npm test` | Run tests |
|
|
102
|
+
| `npm run typecheck` | TypeScript check |
|
|
103
|
+
| `npm run format` | Check formatting with Prettier |
|
|
104
|
+
| `npm run format:fix` | Fix formatting |
|
|
105
|
+
|
|
106
|
+
## Contributing
|
|
107
|
+
|
|
108
|
+
See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup, guidelines, and project structure.
|
|
109
|
+
|
|
110
|
+
## Code of Conduct
|
|
111
|
+
|
|
112
|
+
This project follows the [Contributor Covenant](CODE_OF_CONDUCT.md). By participating, you agree to uphold its terms.
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
[MIT](./LICENSE)
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
ApiError: () => ApiError,
|
|
34
|
+
BadRequest: () => BadRequest,
|
|
35
|
+
Conflict: () => Conflict,
|
|
36
|
+
Forbidden: () => Forbidden,
|
|
37
|
+
GatewayTimeout: () => GatewayTimeout,
|
|
38
|
+
InternalServerError: () => InternalServerError,
|
|
39
|
+
Logger: () => Logger,
|
|
40
|
+
NotFound: () => NotFound,
|
|
41
|
+
ServiceUnavailable: () => ServiceUnavailable,
|
|
42
|
+
TooManyRequests: () => TooManyRequests,
|
|
43
|
+
Unauthorized: () => Unauthorized,
|
|
44
|
+
ValidationError: () => ValidationError,
|
|
45
|
+
asyncHandler: () => asyncHandler,
|
|
46
|
+
createLogger: () => createLogger,
|
|
47
|
+
errorHandler: () => errorHandler,
|
|
48
|
+
getLogger: () => getLogger,
|
|
49
|
+
getRequestContext: () => getRequestContext,
|
|
50
|
+
getRequestId: () => getRequestId,
|
|
51
|
+
healthCheck: () => healthCheck,
|
|
52
|
+
httpLogger: () => httpLogger,
|
|
53
|
+
message: () => message,
|
|
54
|
+
requestContext: () => requestContext,
|
|
55
|
+
requestId: () => requestId,
|
|
56
|
+
runWithContext: () => runWithContext,
|
|
57
|
+
status: () => status,
|
|
58
|
+
timeout: () => timeout,
|
|
59
|
+
validate: () => validate
|
|
60
|
+
});
|
|
61
|
+
module.exports = __toCommonJS(index_exports);
|
|
62
|
+
|
|
63
|
+
// src/status/index.ts
|
|
64
|
+
var status = {
|
|
65
|
+
// 1xx Informational
|
|
66
|
+
continue: 100,
|
|
67
|
+
switchingProtocols: 101,
|
|
68
|
+
processing: 102,
|
|
69
|
+
earlyHints: 103,
|
|
70
|
+
// 2xx Success
|
|
71
|
+
ok: 200,
|
|
72
|
+
created: 201,
|
|
73
|
+
accepted: 202,
|
|
74
|
+
nonAuthoritativeInformation: 203,
|
|
75
|
+
noContent: 204,
|
|
76
|
+
resetContent: 205,
|
|
77
|
+
partialContent: 206,
|
|
78
|
+
// 3xx Redirection
|
|
79
|
+
multipleChoices: 300,
|
|
80
|
+
movedPermanently: 301,
|
|
81
|
+
found: 302,
|
|
82
|
+
seeOther: 303,
|
|
83
|
+
notModified: 304,
|
|
84
|
+
useProxy: 305,
|
|
85
|
+
temporaryRedirect: 307,
|
|
86
|
+
permanentRedirect: 308,
|
|
87
|
+
// 4xx Client Error
|
|
88
|
+
badRequest: 400,
|
|
89
|
+
unauthorized: 401,
|
|
90
|
+
paymentRequired: 402,
|
|
91
|
+
forbidden: 403,
|
|
92
|
+
notFound: 404,
|
|
93
|
+
methodNotAllowed: 405,
|
|
94
|
+
notAcceptable: 406,
|
|
95
|
+
proxyAuthenticationRequired: 407,
|
|
96
|
+
requestTimeout: 408,
|
|
97
|
+
conflict: 409,
|
|
98
|
+
gone: 410,
|
|
99
|
+
lengthRequired: 411,
|
|
100
|
+
preconditionFailed: 412,
|
|
101
|
+
payloadTooLarge: 413,
|
|
102
|
+
uriTooLong: 414,
|
|
103
|
+
unsupportedMediaType: 415,
|
|
104
|
+
rangeNotSatisfiable: 416,
|
|
105
|
+
expectationFailed: 417,
|
|
106
|
+
imATeapot: 418,
|
|
107
|
+
unprocessableEntity: 422,
|
|
108
|
+
tooEarly: 425,
|
|
109
|
+
upgradeRequired: 426,
|
|
110
|
+
preconditionRequired: 428,
|
|
111
|
+
tooManyRequests: 429,
|
|
112
|
+
requestHeaderFieldsTooLarge: 431,
|
|
113
|
+
unavailableForLegalReasons: 451,
|
|
114
|
+
// 5xx Server Error
|
|
115
|
+
internalServerError: 500,
|
|
116
|
+
notImplemented: 501,
|
|
117
|
+
badGateway: 502,
|
|
118
|
+
serviceUnavailable: 503,
|
|
119
|
+
gatewayTimeout: 504,
|
|
120
|
+
httpVersionNotSupported: 505,
|
|
121
|
+
insufficientStorage: 507,
|
|
122
|
+
loopDetected: 508,
|
|
123
|
+
notExtended: 510,
|
|
124
|
+
networkAuthenticationRequired: 511
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
// src/message/index.ts
|
|
128
|
+
var message = {
|
|
129
|
+
// 1xx Informational
|
|
130
|
+
continue: "Continue",
|
|
131
|
+
switchingProtocols: "Switching Protocols",
|
|
132
|
+
processing: "Processing request",
|
|
133
|
+
earlyHints: "Early hints available",
|
|
134
|
+
// 2xx Success
|
|
135
|
+
ok: "Success",
|
|
136
|
+
created: "Created successfully",
|
|
137
|
+
accepted: "Request accepted",
|
|
138
|
+
nonAuthoritativeInformation: "Non-authoritative information",
|
|
139
|
+
noContent: "No content",
|
|
140
|
+
resetContent: "Reset content",
|
|
141
|
+
partialContent: "Partial content",
|
|
142
|
+
// 3xx Redirection
|
|
143
|
+
multipleChoices: "Multiple redirect options available",
|
|
144
|
+
movedPermanently: "Resource moved permanently",
|
|
145
|
+
found: "Resource found elsewhere",
|
|
146
|
+
seeOther: "See other resource",
|
|
147
|
+
notModified: "Resource not modified",
|
|
148
|
+
useProxy: "Use proxy to access resource",
|
|
149
|
+
temporaryRedirect: "Resource temporarily moved",
|
|
150
|
+
permanentRedirect: "Resource permanently moved",
|
|
151
|
+
// 4xx Client Error
|
|
152
|
+
badRequest: "Invalid request",
|
|
153
|
+
unauthorized: "Authentication required",
|
|
154
|
+
paymentRequired: "Payment required",
|
|
155
|
+
forbidden: "You don't have permission to access this resource",
|
|
156
|
+
notFound: "Resource not found",
|
|
157
|
+
methodNotAllowed: "Method not allowed for this resource",
|
|
158
|
+
notAcceptable: "Requested format not available",
|
|
159
|
+
proxyAuthenticationRequired: "Proxy authentication required",
|
|
160
|
+
requestTimeout: "Request timed out",
|
|
161
|
+
conflict: "Resource conflict detected",
|
|
162
|
+
gone: "Resource no longer available",
|
|
163
|
+
lengthRequired: "Content length header is required",
|
|
164
|
+
preconditionFailed: "Request precondition failed",
|
|
165
|
+
payloadTooLarge: "Request payload exceeds size limit",
|
|
166
|
+
uriTooLong: "Request URI exceeds length limit",
|
|
167
|
+
unsupportedMediaType: "Unsupported media type",
|
|
168
|
+
rangeNotSatisfiable: "Requested range is not available",
|
|
169
|
+
expectationFailed: "Request expectation could not be met",
|
|
170
|
+
imATeapot: "I'm a teapot",
|
|
171
|
+
unprocessableEntity: "Unable to process request entity",
|
|
172
|
+
tooEarly: "Request sent too early, retry later",
|
|
173
|
+
upgradeRequired: "Protocol upgrade required",
|
|
174
|
+
preconditionRequired: "Precondition header is required",
|
|
175
|
+
tooManyRequests: "Too many requests, please slow down",
|
|
176
|
+
requestHeaderFieldsTooLarge: "Request headers exceed size limit",
|
|
177
|
+
unavailableForLegalReasons: "Resource unavailable for legal reasons",
|
|
178
|
+
// 5xx Server Error
|
|
179
|
+
internalServerError: "Something went wrong on our end",
|
|
180
|
+
notImplemented: "Feature not yet implemented",
|
|
181
|
+
badGateway: "Bad gateway response from upstream",
|
|
182
|
+
serviceUnavailable: "Service temporarily unavailable, try again later",
|
|
183
|
+
gatewayTimeout: "Upstream server timed out",
|
|
184
|
+
httpVersionNotSupported: "HTTP version not supported by server",
|
|
185
|
+
insufficientStorage: "Server has insufficient storage",
|
|
186
|
+
loopDetected: "Infinite request loop detected",
|
|
187
|
+
notExtended: "Server cannot fulfill extended request",
|
|
188
|
+
networkAuthenticationRequired: "Network authentication required"
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
// src/errors/api-error.ts
|
|
192
|
+
var ApiError = class _ApiError extends Error {
|
|
193
|
+
constructor(statusCode, message2, details) {
|
|
194
|
+
super(message2 ??= getDefaultMessage(statusCode));
|
|
195
|
+
this.statusCode = statusCode;
|
|
196
|
+
this.details = details;
|
|
197
|
+
this.name = "ApiError";
|
|
198
|
+
}
|
|
199
|
+
statusCode;
|
|
200
|
+
details;
|
|
201
|
+
static notFound(message2) {
|
|
202
|
+
return new _ApiError(status.notFound, message2);
|
|
203
|
+
}
|
|
204
|
+
static badRequest(message2) {
|
|
205
|
+
return new _ApiError(status.badRequest, message2);
|
|
206
|
+
}
|
|
207
|
+
static unauthorized(message2) {
|
|
208
|
+
return new _ApiError(status.unauthorized, message2);
|
|
209
|
+
}
|
|
210
|
+
static forbidden(message2) {
|
|
211
|
+
return new _ApiError(status.forbidden, message2);
|
|
212
|
+
}
|
|
213
|
+
static conflict(message2) {
|
|
214
|
+
return new _ApiError(status.conflict, message2);
|
|
215
|
+
}
|
|
216
|
+
static internalServerError(message2) {
|
|
217
|
+
return new _ApiError(status.internalServerError, message2);
|
|
218
|
+
}
|
|
219
|
+
static serviceUnavailable(message2) {
|
|
220
|
+
return new _ApiError(status.serviceUnavailable, message2);
|
|
221
|
+
}
|
|
222
|
+
static tooManyRequests(message2) {
|
|
223
|
+
return new _ApiError(status.tooManyRequests, message2);
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
function getDefaultMessage(code) {
|
|
227
|
+
const entry = Object.entries(status).find(([, v]) => v === code);
|
|
228
|
+
if (!entry) return "Error";
|
|
229
|
+
return message[entry[0]];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// src/errors/http-error.ts
|
|
233
|
+
var NotFound = class extends ApiError {
|
|
234
|
+
constructor(message2) {
|
|
235
|
+
super(404, message2);
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
var BadRequest = class extends ApiError {
|
|
239
|
+
constructor(message2) {
|
|
240
|
+
super(400, message2);
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
var Unauthorized = class extends ApiError {
|
|
244
|
+
constructor(message2) {
|
|
245
|
+
super(401, message2);
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
var Forbidden = class extends ApiError {
|
|
249
|
+
constructor(message2) {
|
|
250
|
+
super(403, message2);
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
var Conflict = class extends ApiError {
|
|
254
|
+
constructor(message2) {
|
|
255
|
+
super(409, message2);
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
var InternalServerError = class extends ApiError {
|
|
259
|
+
constructor(message2) {
|
|
260
|
+
super(500, message2);
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
var ServiceUnavailable = class extends ApiError {
|
|
264
|
+
constructor(message2) {
|
|
265
|
+
super(503, message2);
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
var TooManyRequests = class extends ApiError {
|
|
269
|
+
constructor(message2) {
|
|
270
|
+
super(429, message2);
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
var ValidationError = class extends ApiError {
|
|
274
|
+
constructor(message2, details) {
|
|
275
|
+
super(422, message2 ?? "Validation failed", details);
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
var GatewayTimeout = class extends ApiError {
|
|
279
|
+
constructor(message2) {
|
|
280
|
+
super(504, message2);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
// src/logger/index.ts
|
|
285
|
+
var levelPriority = {
|
|
286
|
+
debug: 0,
|
|
287
|
+
info: 1,
|
|
288
|
+
warn: 2,
|
|
289
|
+
error: 3
|
|
290
|
+
};
|
|
291
|
+
var defaultDestination = (entry) => {
|
|
292
|
+
console.log(JSON.stringify(entry));
|
|
293
|
+
};
|
|
294
|
+
var Logger = class _Logger {
|
|
295
|
+
level;
|
|
296
|
+
destination;
|
|
297
|
+
bindings;
|
|
298
|
+
constructor(options = {}, bindings = {}) {
|
|
299
|
+
this.level = options.level ?? "info";
|
|
300
|
+
this.destination = options.destination ?? defaultDestination;
|
|
301
|
+
this.bindings = bindings;
|
|
302
|
+
}
|
|
303
|
+
shouldLog(level) {
|
|
304
|
+
return levelPriority[level] >= levelPriority[this.level];
|
|
305
|
+
}
|
|
306
|
+
log(level, ...args) {
|
|
307
|
+
if (!this.shouldLog(level)) return;
|
|
308
|
+
let message2;
|
|
309
|
+
let meta = {};
|
|
310
|
+
if (args.length === 1) {
|
|
311
|
+
message2 = String(args[0]);
|
|
312
|
+
} else if (typeof args[0] === "object" && args[0] !== null) {
|
|
313
|
+
meta = { ...args[0] };
|
|
314
|
+
message2 = String(args[1]);
|
|
315
|
+
} else {
|
|
316
|
+
message2 = String(args[0]);
|
|
317
|
+
if (args[1] !== void 0) {
|
|
318
|
+
meta = args[1];
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
this.destination({
|
|
322
|
+
level,
|
|
323
|
+
...this.bindings,
|
|
324
|
+
...meta,
|
|
325
|
+
...message2 ? { message: message2 } : {}
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
debug(...args) {
|
|
329
|
+
this.log("debug", ...args);
|
|
330
|
+
}
|
|
331
|
+
info(...args) {
|
|
332
|
+
this.log("info", ...args);
|
|
333
|
+
}
|
|
334
|
+
warn(...args) {
|
|
335
|
+
this.log("warn", ...args);
|
|
336
|
+
}
|
|
337
|
+
error(...args) {
|
|
338
|
+
this.log("error", ...args);
|
|
339
|
+
}
|
|
340
|
+
child(bindings) {
|
|
341
|
+
return new _Logger(
|
|
342
|
+
{ level: this.level, destination: this.destination },
|
|
343
|
+
{ ...this.bindings, ...bindings }
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
function createLogger(options) {
|
|
348
|
+
return new Logger(options);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// src/context/index.ts
|
|
352
|
+
var import_node_async_hooks = require("async_hooks");
|
|
353
|
+
var storage = new import_node_async_hooks.AsyncLocalStorage();
|
|
354
|
+
function getRequestContext() {
|
|
355
|
+
return storage.getStore();
|
|
356
|
+
}
|
|
357
|
+
function getLogger() {
|
|
358
|
+
return storage.getStore()?.log;
|
|
359
|
+
}
|
|
360
|
+
function getRequestId() {
|
|
361
|
+
return storage.getStore()?.requestId;
|
|
362
|
+
}
|
|
363
|
+
function runWithContext(context, fn) {
|
|
364
|
+
storage.run(context, fn);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// src/middleware/error-handler.ts
|
|
368
|
+
function errorHandler(options = {}) {
|
|
369
|
+
const log = options.log ?? true;
|
|
370
|
+
return (err, _req, res, _next) => {
|
|
371
|
+
if (err instanceof ApiError) {
|
|
372
|
+
res.status(err.statusCode).json({
|
|
373
|
+
error: {
|
|
374
|
+
message: err.message,
|
|
375
|
+
statusCode: err.statusCode,
|
|
376
|
+
...err.details !== void 0 && { details: err.details }
|
|
377
|
+
}
|
|
378
|
+
});
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (log) {
|
|
382
|
+
console.error(err);
|
|
383
|
+
}
|
|
384
|
+
res.status(500).json({
|
|
385
|
+
error: {
|
|
386
|
+
message: message.internalServerError,
|
|
387
|
+
statusCode: 500
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// src/middleware/request-id.ts
|
|
394
|
+
var import_node_crypto = __toESM(require("crypto"), 1);
|
|
395
|
+
function requestId(options = {}) {
|
|
396
|
+
const {
|
|
397
|
+
header = "x-request-id",
|
|
398
|
+
generator = import_node_crypto.default.randomUUID,
|
|
399
|
+
respectExisting = true
|
|
400
|
+
} = options;
|
|
401
|
+
return (req, res, next) => {
|
|
402
|
+
const existing = req.get(header);
|
|
403
|
+
const id = existing && respectExisting ? existing : generator();
|
|
404
|
+
req.requestId = id;
|
|
405
|
+
res.setHeader(header, id);
|
|
406
|
+
next();
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// src/middleware/request-context.ts
|
|
411
|
+
function requestContext(options = {}) {
|
|
412
|
+
const logger = options.logger ?? new Logger();
|
|
413
|
+
return (req, _res, next) => {
|
|
414
|
+
const scoped = logger.child({ requestId: req.requestId });
|
|
415
|
+
req.log = scoped;
|
|
416
|
+
runWithContext({ requestId: req.requestId, log: scoped }, () => {
|
|
417
|
+
next();
|
|
418
|
+
});
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// src/middleware/http-logger.ts
|
|
423
|
+
function httpLogger(options = {}) {
|
|
424
|
+
const { skip } = options;
|
|
425
|
+
return (req, res, next) => {
|
|
426
|
+
if (skip?.(req, res)) {
|
|
427
|
+
next();
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
const start = Date.now();
|
|
431
|
+
res.on("finish", () => {
|
|
432
|
+
req.log.info({
|
|
433
|
+
method: req.method,
|
|
434
|
+
path: req.originalUrl ?? req.url,
|
|
435
|
+
status: res.statusCode,
|
|
436
|
+
durationMs: Date.now() - start
|
|
437
|
+
});
|
|
438
|
+
});
|
|
439
|
+
next();
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// src/middleware/validate.ts
|
|
444
|
+
function defaultFormatter(error) {
|
|
445
|
+
if (error && typeof error === "object" && "issues" in error && Array.isArray(error.issues)) {
|
|
446
|
+
return error.issues;
|
|
447
|
+
}
|
|
448
|
+
if (error instanceof Error) {
|
|
449
|
+
return [{ path: [], message: error.message }];
|
|
450
|
+
}
|
|
451
|
+
return [{ path: [], message: String(error) }];
|
|
452
|
+
}
|
|
453
|
+
function validate(schemas, options = {}) {
|
|
454
|
+
const formatError = options.formatError ?? defaultFormatter;
|
|
455
|
+
return (req, _res, next) => {
|
|
456
|
+
try {
|
|
457
|
+
if (schemas.body) req.body = schemas.body.parse(req.body);
|
|
458
|
+
if (schemas.params) req.params = schemas.params.parse(req.params);
|
|
459
|
+
if (schemas.query) req.query = schemas.query.parse(req.query);
|
|
460
|
+
next();
|
|
461
|
+
} catch (err) {
|
|
462
|
+
next(new ValidationError("Validation failed", formatError(err)));
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// src/middleware/async-handler.ts
|
|
468
|
+
function asyncHandler(fn) {
|
|
469
|
+
return (req, res, next) => {
|
|
470
|
+
Promise.resolve(fn(req, res, next)).catch(next);
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// src/middleware/timeout.ts
|
|
475
|
+
function timeout(ms, options = {}) {
|
|
476
|
+
return (req, _res, next) => {
|
|
477
|
+
const timer = setTimeout(() => {
|
|
478
|
+
next(new GatewayTimeout(options.message ?? "Request timed out"));
|
|
479
|
+
}, ms);
|
|
480
|
+
const done = () => clearTimeout(timer);
|
|
481
|
+
_res.on("finish", done);
|
|
482
|
+
_res.on("close", done);
|
|
483
|
+
next();
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// src/middleware/health-check.ts
|
|
488
|
+
function healthCheck(options = {}) {
|
|
489
|
+
const getUptime = options.uptime ?? (() => process.uptime());
|
|
490
|
+
const getTimestamp = options.timestamp ?? (() => (/* @__PURE__ */ new Date()).toISOString());
|
|
491
|
+
return (_req, res, _next) => {
|
|
492
|
+
res.json({
|
|
493
|
+
status: "ok",
|
|
494
|
+
uptime: getUptime(),
|
|
495
|
+
timestamp: getTimestamp(),
|
|
496
|
+
...options.checks?.() ?? {}
|
|
497
|
+
});
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
501
|
+
0 && (module.exports = {
|
|
502
|
+
ApiError,
|
|
503
|
+
BadRequest,
|
|
504
|
+
Conflict,
|
|
505
|
+
Forbidden,
|
|
506
|
+
GatewayTimeout,
|
|
507
|
+
InternalServerError,
|
|
508
|
+
Logger,
|
|
509
|
+
NotFound,
|
|
510
|
+
ServiceUnavailable,
|
|
511
|
+
TooManyRequests,
|
|
512
|
+
Unauthorized,
|
|
513
|
+
ValidationError,
|
|
514
|
+
asyncHandler,
|
|
515
|
+
createLogger,
|
|
516
|
+
errorHandler,
|
|
517
|
+
getLogger,
|
|
518
|
+
getRequestContext,
|
|
519
|
+
getRequestId,
|
|
520
|
+
healthCheck,
|
|
521
|
+
httpLogger,
|
|
522
|
+
message,
|
|
523
|
+
requestContext,
|
|
524
|
+
requestId,
|
|
525
|
+
runWithContext,
|
|
526
|
+
status,
|
|
527
|
+
timeout,
|
|
528
|
+
validate
|
|
529
|
+
});
|
|
530
|
+
//# sourceMappingURL=index.cjs.map
|