express-resforge 1.0.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +309 -0
  4. package/dist/constants/defaultMessages.d.ts +5 -0
  5. package/dist/constants/defaultMessages.js +29 -0
  6. package/dist/constants/httpStatus.d.ts +28 -0
  7. package/dist/constants/httpStatus.js +33 -0
  8. package/dist/constants/responseCodes.d.ts +22 -0
  9. package/dist/constants/responseCodes.js +25 -0
  10. package/dist/core/context.d.ts +36 -0
  11. package/dist/core/context.js +45 -0
  12. package/dist/core/formatter.d.ts +7 -0
  13. package/dist/core/formatter.js +17 -0
  14. package/dist/core/pluginManager.d.ts +27 -0
  15. package/dist/core/pluginManager.js +37 -0
  16. package/dist/core/responseBuilder.d.ts +32 -0
  17. package/dist/core/responseBuilder.js +107 -0
  18. package/dist/core/responseFactory.d.ts +12 -0
  19. package/dist/core/responseFactory.js +52 -0
  20. package/dist/formatter/axiosFormatter.d.ts +8 -0
  21. package/dist/formatter/axiosFormatter.js +12 -0
  22. package/dist/formatter/firebaseFormatter.d.ts +6 -0
  23. package/dist/formatter/firebaseFormatter.js +19 -0
  24. package/dist/formatter/joiFormatter.d.ts +8 -0
  25. package/dist/formatter/joiFormatter.js +26 -0
  26. package/dist/formatter/mongooseFormatter.d.ts +2 -0
  27. package/dist/formatter/mongooseFormatter.js +20 -0
  28. package/dist/formatter/prismaFormatter.d.ts +15 -0
  29. package/dist/formatter/prismaFormatter.js +49 -0
  30. package/dist/formatter/zodFormatter.d.ts +9 -0
  31. package/dist/formatter/zodFormatter.js +27 -0
  32. package/dist/helpers/cache.d.ts +2 -0
  33. package/dist/helpers/cache.js +6 -0
  34. package/dist/helpers/cookies.d.ts +2 -0
  35. package/dist/helpers/cookies.js +6 -0
  36. package/dist/helpers/download.d.ts +2 -0
  37. package/dist/helpers/download.js +6 -0
  38. package/dist/helpers/errors.d.ts +10 -0
  39. package/dist/helpers/errors.js +21 -0
  40. package/dist/helpers/headers.d.ts +2 -0
  41. package/dist/helpers/headers.js +7 -0
  42. package/dist/helpers/health.d.ts +2 -0
  43. package/dist/helpers/health.js +10 -0
  44. package/dist/helpers/meta.d.ts +2 -0
  45. package/dist/helpers/meta.js +11 -0
  46. package/dist/helpers/pagination.d.ts +9 -0
  47. package/dist/helpers/pagination.js +14 -0
  48. package/dist/helpers/redirect.d.ts +2 -0
  49. package/dist/helpers/redirect.js +6 -0
  50. package/dist/helpers/success.d.ts +3 -0
  51. package/dist/helpers/success.js +7 -0
  52. package/dist/helpers/validation.d.ts +2 -0
  53. package/dist/helpers/validation.js +6 -0
  54. package/dist/index.d.ts +90 -0
  55. package/dist/index.js +74 -0
  56. package/dist/middleware/errorHandler.d.ts +9 -0
  57. package/dist/middleware/errorHandler.js +90 -0
  58. package/dist/middleware/requestId.d.ts +16 -0
  59. package/dist/middleware/requestId.js +18 -0
  60. package/dist/middleware/requestTimer.d.ts +6 -0
  61. package/dist/middleware/requestTimer.js +26 -0
  62. package/dist/middleware/responseMiddleware.d.ts +7 -0
  63. package/dist/middleware/responseMiddleware.js +93 -0
  64. package/dist/plugins/pluginAPI.d.ts +7 -0
  65. package/dist/plugins/pluginAPI.js +12 -0
  66. package/dist/types/config.d.ts +52 -0
  67. package/dist/types/config.js +22 -0
  68. package/dist/types/index.d.ts +3 -0
  69. package/dist/types/index.js +19 -0
  70. package/dist/types/plugin.d.ts +11 -0
  71. package/dist/types/plugin.js +2 -0
  72. package/dist/types/responses.d.ts +72 -0
  73. package/dist/types/responses.js +6 -0
  74. package/dist/utils/cleanObject.d.ts +11 -0
  75. package/dist/utils/cleanObject.js +26 -0
  76. package/dist/utils/deepMerge.d.ts +12 -0
  77. package/dist/utils/deepMerge.js +43 -0
  78. package/dist/utils/helpers.d.ts +4 -0
  79. package/dist/utils/helpers.js +15 -0
  80. package/dist/utils/time.d.ts +4 -0
  81. package/dist/utils/time.js +11 -0
  82. package/dist/utils/uuid.d.ts +9 -0
  83. package/dist/utils/uuid.js +24 -0
  84. package/dist/version.d.ts +4 -0
  85. package/dist/version.js +7 -0
  86. package/package.json +68 -0
@@ -0,0 +1,90 @@
1
+ import { responseMiddleware } from './middleware/responseMiddleware';
2
+ import { errorHandler } from './middleware/errorHandler';
3
+ import { requestIdMiddleware } from './middleware/requestId';
4
+ import { requestTimerMiddleware } from './middleware/requestTimer';
5
+ import { asyncWrapper } from './helpers/errors';
6
+ import { formatZodError } from './formatter/zodFormatter';
7
+ import { formatJoiError } from './formatter/joiFormatter';
8
+ import { formatMongooseError } from './formatter/mongooseFormatter';
9
+ import { formatPrismaError } from './formatter/prismaFormatter';
10
+ import { formatAxiosError } from './formatter/axiosFormatter';
11
+ import { formatFirebaseError } from './formatter/firebaseFormatter';
12
+ import { StandardApiResponse, ApiResponsePagination, ApiResponseMeta, ValidationErrorItem, ResponseOptions, PaginationOptions } from './types/responses';
13
+ import { ApiKitConfig } from './types/config';
14
+ import { ResponseBuilder } from './core/responseBuilder';
15
+ /**
16
+ * Enterprise core orchestration object for express-api-kit.
17
+ */
18
+ export declare const apiKit: {
19
+ /**
20
+ * The current semantic version of the toolkit.
21
+ */
22
+ version: string;
23
+ /**
24
+ * Main Express middleware that initializes request contexts and injects standard semantic response methods.
25
+ * @example app.use(apiKit.middleware({ apiVersion: 'v1' }));
26
+ */
27
+ middleware: typeof responseMiddleware;
28
+ /**
29
+ * Global Express error handling middleware that captures and formats uncaught exceptions.
30
+ * @example app.use(apiKit.errorHandler());
31
+ */
32
+ errorHandler: typeof errorHandler;
33
+ /**
34
+ * Standalone middleware to assign or forward unique transaction tracking correlation tokens.
35
+ */
36
+ requestId: typeof requestIdMiddleware;
37
+ /**
38
+ * Standalone middleware providing low-overhead performance profiling response headers.
39
+ */
40
+ requestTimer: typeof requestTimerMiddleware;
41
+ /**
42
+ * Higher-order async wrapper that handles errors in route pipelines without requiring try/catch blocks.
43
+ * @example app.get('/users', apiKit.async(async (req, res) => { ... }));
44
+ */
45
+ async: typeof asyncWrapper;
46
+ /**
47
+ * Registers custom global response payload modification plugins or analytics interceptors.
48
+ * @example
49
+ * apiKit.use((payload, req, res) => {
50
+ * payload.meta.server = "Dream Mythic";
51
+ * return payload;
52
+ * });
53
+ */
54
+ use: (plugin: import("./core/pluginManager").ApiKitPlugin) => void;
55
+ /**
56
+ * Centralized parsing utilities to normalize diverse ecosystem exceptions into consistent envelopes.
57
+ */
58
+ formatters: {
59
+ zod: typeof formatZodError;
60
+ joi: typeof formatJoiError;
61
+ mongoose: typeof formatMongooseError;
62
+ prisma: typeof formatPrismaError;
63
+ axios: typeof formatAxiosError;
64
+ firebase: typeof formatFirebaseError;
65
+ };
66
+ };
67
+ declare global {
68
+ namespace Express {
69
+ interface Response {
70
+ success<T = any>(data?: T, options?: ResponseOptions): ResponseBuilder<T>;
71
+ created<T = any>(data?: T, options?: ResponseOptions): ResponseBuilder<T>;
72
+ accepted<T = any>(data?: T, options?: ResponseOptions): ResponseBuilder<T>;
73
+ deleted(options?: ResponseOptions): ResponseBuilder<null>;
74
+ noContent(): void;
75
+ badRequest(options?: ResponseOptions): ResponseBuilder<null>;
76
+ unauthorized(options?: ResponseOptions): ResponseBuilder<null>;
77
+ forbidden(options?: ResponseOptions): ResponseBuilder<null>;
78
+ notFound(options?: ResponseOptions): ResponseBuilder<null>;
79
+ conflict(options?: ResponseOptions): ResponseBuilder<null>;
80
+ unprocessable(options?: ResponseOptions): ResponseBuilder<null>;
81
+ tooManyRequests(options?: ResponseOptions): ResponseBuilder<null>;
82
+ serverError(options?: ResponseOptions): ResponseBuilder<null>;
83
+ notImplemented(options?: ResponseOptions): ResponseBuilder<null>;
84
+ serviceUnavailable(options?: ResponseOptions): ResponseBuilder<null>;
85
+ paginate<T = any>(data: T[], options: PaginationOptions): ResponseBuilder<T[]>;
86
+ }
87
+ }
88
+ }
89
+ export { StandardApiResponse, ApiResponsePagination, ApiResponseMeta, ValidationErrorItem, ResponseOptions, PaginationOptions, ApiKitConfig, ResponseBuilder };
90
+ export default apiKit;
package/dist/index.js ADDED
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ResponseBuilder = exports.apiKit = void 0;
4
+ // Core Architectural Components
5
+ const responseMiddleware_1 = require("./middleware/responseMiddleware");
6
+ const errorHandler_1 = require("./middleware/errorHandler");
7
+ const requestId_1 = require("./middleware/requestId");
8
+ const requestTimer_1 = require("./middleware/requestTimer");
9
+ const errors_1 = require("./helpers/errors");
10
+ const pluginManager_1 = require("./core/pluginManager");
11
+ const version_1 = require("./version");
12
+ // Ecosystem Error Formatters
13
+ const zodFormatter_1 = require("./formatter/zodFormatter");
14
+ const joiFormatter_1 = require("./formatter/joiFormatter");
15
+ const mongooseFormatter_1 = require("./formatter/mongooseFormatter");
16
+ const prismaFormatter_1 = require("./formatter/prismaFormatter");
17
+ const axiosFormatter_1 = require("./formatter/axiosFormatter");
18
+ const firebaseFormatter_1 = require("./formatter/firebaseFormatter");
19
+ const responseBuilder_1 = require("./core/responseBuilder");
20
+ Object.defineProperty(exports, "ResponseBuilder", { enumerable: true, get: function () { return responseBuilder_1.ResponseBuilder; } });
21
+ /**
22
+ * Enterprise core orchestration object for express-api-kit.
23
+ */
24
+ exports.apiKit = {
25
+ /**
26
+ * The current semantic version of the toolkit.
27
+ */
28
+ version: version_1.VERSION,
29
+ /**
30
+ * Main Express middleware that initializes request contexts and injects standard semantic response methods.
31
+ * @example app.use(apiKit.middleware({ apiVersion: 'v1' }));
32
+ */
33
+ middleware: responseMiddleware_1.responseMiddleware,
34
+ /**
35
+ * Global Express error handling middleware that captures and formats uncaught exceptions.
36
+ * @example app.use(apiKit.errorHandler());
37
+ */
38
+ errorHandler: errorHandler_1.errorHandler,
39
+ /**
40
+ * Standalone middleware to assign or forward unique transaction tracking correlation tokens.
41
+ */
42
+ requestId: requestId_1.requestIdMiddleware,
43
+ /**
44
+ * Standalone middleware providing low-overhead performance profiling response headers.
45
+ */
46
+ requestTimer: requestTimer_1.requestTimerMiddleware,
47
+ /**
48
+ * Higher-order async wrapper that handles errors in route pipelines without requiring try/catch blocks.
49
+ * @example app.get('/users', apiKit.async(async (req, res) => { ... }));
50
+ */
51
+ async: errors_1.asyncWrapper,
52
+ /**
53
+ * Registers custom global response payload modification plugins or analytics interceptors.
54
+ * @example
55
+ * apiKit.use((payload, req, res) => {
56
+ * payload.meta.server = "Dream Mythic";
57
+ * return payload;
58
+ * });
59
+ */
60
+ use: pluginManager_1.globalPluginManager.use.bind(pluginManager_1.globalPluginManager),
61
+ /**
62
+ * Centralized parsing utilities to normalize diverse ecosystem exceptions into consistent envelopes.
63
+ */
64
+ formatters: {
65
+ zod: zodFormatter_1.formatZodError,
66
+ joi: joiFormatter_1.formatJoiError,
67
+ mongoose: mongooseFormatter_1.formatMongooseError,
68
+ prisma: prismaFormatter_1.formatPrismaError,
69
+ axios: axiosFormatter_1.formatAxiosError,
70
+ firebase: firebaseFormatter_1.formatFirebaseError,
71
+ }
72
+ };
73
+ // Default export compatibility support mapping for CommonJS / ESM workflows
74
+ exports.default = exports.apiKit;
@@ -0,0 +1,9 @@
1
+ import { ErrorRequestHandler } from 'express';
2
+ import { ApiKitConfig } from '../types/config';
3
+ /**
4
+ * Enterprise-grade global Express error handling middleware factory.
5
+ * Intercepts thrown application exceptions and normalizes them into standard envelopes.
6
+ *
7
+ * @param config Optional configuration overrides block.
8
+ */
9
+ export declare function errorHandler(config?: ApiKitConfig): ErrorRequestHandler;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errorHandler = errorHandler;
4
+ const config_1 = require("../types/config");
5
+ const httpStatus_1 = require("../constants/httpStatus");
6
+ const responseCodes_1 = require("../constants/responseCodes");
7
+ /**
8
+ * Enterprise-grade global Express error handling middleware factory.
9
+ * Intercepts thrown application exceptions and normalizes them into standard envelopes.
10
+ *
11
+ * @param config Optional configuration overrides block.
12
+ */
13
+ function errorHandler(config) {
14
+ return (err, req, res, next) => {
15
+ // Dynamically look up active framework configurations attached to the response context
16
+ const activeConfig = res.__apiKitConfig || {
17
+ ...config_1.DefaultApiKitConfig,
18
+ ...config,
19
+ errors: { ...config_1.DefaultApiKitConfig.errors, ...config?.errors },
20
+ };
21
+ let statusCode = err.status || err.statusCode || httpStatus_1.HttpStatus.INTERNAL_SERVER_ERROR;
22
+ let responseCode = err.code || responseCodes_1.ResponseCodes.SERVER_ERROR;
23
+ let message = err.message || 'An unexpected error occurred.';
24
+ let errors = err.errors || undefined;
25
+ // Detect if this is a standard operational or semantic exception
26
+ const isClientError = statusCode >= 400 && statusCode < 500;
27
+ // Sanitize unhandled 5xx internal crashes in production environments to safeguard system security
28
+ if (!isClientError && activeConfig.errors.sanitizeServerErrors) {
29
+ message = activeConfig.customMessages?.[httpStatus_1.HttpStatus.INTERNAL_SERVER_ERROR] || 'An unexpected internal server error occurred.';
30
+ responseCode = responseCodes_1.ResponseCodes.SERVER_ERROR;
31
+ }
32
+ // Capture standard validation error footprints exposed across third-party engines
33
+ if (err.name === 'ValidationError' || err.isJoi || err.name === 'ZodError') {
34
+ statusCode = httpStatus_1.HttpStatus.UNPROCESSABLE_ENTITY;
35
+ responseCode = responseCodes_1.ResponseCodes.UNPROCESSABLE;
36
+ }
37
+ // Build the finalized JSON payload while checking stack trace configurations
38
+ const errorPayload = {
39
+ message,
40
+ };
41
+ if (errors) {
42
+ errorPayload.errors = errors;
43
+ }
44
+ if (activeConfig.errors.exposeStack && err.stack) {
45
+ errorPayload.meta = {
46
+ ...errorPayload.meta,
47
+ stack: err.stack,
48
+ };
49
+ }
50
+ // Dispatch the payload through the appropriate contextual res channel safely
51
+ if (typeof res.unprocessable === 'function' && statusCode === httpStatus_1.HttpStatus.UNPROCESSABLE_ENTITY) {
52
+ res.unprocessable(errorPayload).send();
53
+ return;
54
+ }
55
+ if (typeof res.badRequest === 'function' && statusCode === httpStatus_1.HttpStatus.BAD_REQUEST) {
56
+ res.badRequest(errorPayload).send();
57
+ return;
58
+ }
59
+ if (typeof res.unauthorized === 'function' && statusCode === httpStatus_1.HttpStatus.UNAUTHORIZED) {
60
+ res.unauthorized(errorPayload).send();
61
+ return;
62
+ }
63
+ if (typeof res.forbidden === 'function' && statusCode === httpStatus_1.HttpStatus.FORBIDDEN) {
64
+ res.forbidden(errorPayload).send();
65
+ return;
66
+ }
67
+ if (typeof res.notFound === 'function' && statusCode === httpStatus_1.HttpStatus.NOT_FOUND) {
68
+ res.notFound(errorPayload).send();
69
+ return;
70
+ }
71
+ // Default fallback structural dispatch for standard unhandled server executions
72
+ if (typeof res.serverError === 'function') {
73
+ res.serverError(errorPayload).send();
74
+ return;
75
+ }
76
+ // Extreme fallback if invoked prior to response middleware decoration
77
+ res.status(statusCode).json({
78
+ success: false,
79
+ statusCode,
80
+ responseCode,
81
+ message,
82
+ data: null,
83
+ meta: {
84
+ timestamp: new Date().toISOString(),
85
+ },
86
+ ...(errors ? { errors } : {}),
87
+ ...(activeConfig.errors.exposeStack && err.stack ? { stack: err.stack } : {}),
88
+ });
89
+ };
90
+ }
@@ -0,0 +1,16 @@
1
+ import { RequestHandler } from 'express';
2
+ declare global {
3
+ namespace Express {
4
+ interface Request {
5
+ /**
6
+ * Unique enterprise transaction correlation identifier.
7
+ */
8
+ id?: string;
9
+ }
10
+ }
11
+ }
12
+ /**
13
+ * Middleware that assigns or forwards a unique transaction identifier to every incoming request.
14
+ * Automatically injects the tracking token into the outbound 'X-Request-ID' header.
15
+ */
16
+ export declare function requestIdMiddleware(): RequestHandler;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requestIdMiddleware = requestIdMiddleware;
4
+ const uuid_1 = require("../utils/uuid");
5
+ /**
6
+ * Middleware that assigns or forwards a unique transaction identifier to every incoming request.
7
+ * Automatically injects the tracking token into the outbound 'X-Request-ID' header.
8
+ */
9
+ function requestIdMiddleware() {
10
+ return (req, res, next) => {
11
+ const headerName = 'X-Request-ID';
12
+ const activeId = req.headers['x-request-id'] || req.headers['x-correlation-id'] || (0, uuid_1.generateUuid)();
13
+ // Safely assign the tracking token using our extended interface type definition
14
+ req.id = Array.isArray(activeId) ? activeId[0] : activeId;
15
+ res.setHeader(headerName, req.id);
16
+ next();
17
+ };
18
+ }
@@ -0,0 +1,6 @@
1
+ import { RequestHandler } from 'express';
2
+ /**
3
+ * High-precision performance profiling middleware.
4
+ * Intercepts the response stream write step to safely inject execution time markers.
5
+ */
6
+ export declare function requestTimerMiddleware(): RequestHandler;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requestTimerMiddleware = requestTimerMiddleware;
4
+ /**
5
+ * High-precision performance profiling middleware.
6
+ * Intercepts the response stream write step to safely inject execution time markers.
7
+ */
8
+ function requestTimerMiddleware() {
9
+ return (req, res, next) => {
10
+ const start = process.hrtime();
11
+ // Capture the original baseline terminal method reference
12
+ const originalEnd = res.end;
13
+ // Intercept the final payload flushing step
14
+ res.end = function (chunk, encoding, cb) {
15
+ // Calculate delta milliseconds precisely before headers freeze
16
+ const diff = process.hrtime(start);
17
+ const ms = (diff[0] * 1000) + (diff[1] / 1000000);
18
+ if (!res.headersSent) {
19
+ res.setHeader('X-Response-Time', `${ms.toFixed(2)}ms`);
20
+ }
21
+ // Restore application execution context back to the original engine channel
22
+ return originalEnd.call(this, chunk, encoding, cb);
23
+ };
24
+ next();
25
+ };
26
+ }
@@ -0,0 +1,7 @@
1
+ import { RequestHandler } from 'express';
2
+ import { ApiKitConfig } from '../types/config';
3
+ /**
4
+ * Express Middleware factory providing standardized API orchestration across endpoints.
5
+ * @param config Optional user customization options object.
6
+ */
7
+ export declare function responseMiddleware(config?: ApiKitConfig): RequestHandler;
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.responseMiddleware = responseMiddleware;
4
+ const config_1 = require("../types/config");
5
+ const httpStatus_1 = require("../constants/httpStatus");
6
+ const responseCodes_1 = require("../constants/responseCodes");
7
+ const responseFactory_1 = require("../core/responseFactory");
8
+ const uuid_1 = require("../utils/uuid");
9
+ const context_1 = require("../core/context");
10
+ /**
11
+ * Express Middleware factory providing standardized API orchestration across endpoints.
12
+ * @param config Optional user customization options object.
13
+ */
14
+ function responseMiddleware(config) {
15
+ const activeConfig = {
16
+ ...config_1.DefaultApiKitConfig,
17
+ ...config,
18
+ errors: { ...config_1.DefaultApiKitConfig.errors, ...config?.errors },
19
+ };
20
+ return (req, res, next) => {
21
+ // Attach current configurations to response object internally for access down the line
22
+ res.__apiKitConfig = activeConfig;
23
+ // Resolve or generate incoming transaction tracking identifier tokens
24
+ let requestId = '';
25
+ if (activeConfig.enableRequestId) {
26
+ const incomingId = req.headers['x-request-id'] || req.headers['x-correlation-id'];
27
+ requestId = Array.isArray(incomingId) ? incomingId[0] : incomingId || (0, uuid_1.generateUuid)();
28
+ res.setHeader('X-Request-ID', requestId);
29
+ }
30
+ // 1. Inject semantic shortcut helpers directly into the response instance
31
+ res.success = function (data, options) {
32
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.OK, true, responseCodes_1.ResponseCodes.SUCCESS, data, options);
33
+ };
34
+ res.created = function (data, options) {
35
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.CREATED, true, responseCodes_1.ResponseCodes.CREATED, data, options);
36
+ };
37
+ res.accepted = function (data, options) {
38
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.ACCEPTED, true, responseCodes_1.ResponseCodes.ACCEPTED, data, options);
39
+ };
40
+ res.deleted = function (options) {
41
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.OK, false, responseCodes_1.ResponseCodes.DELETED, null, options);
42
+ };
43
+ res.noContent = function () {
44
+ return res.status(httpStatus_1.HttpStatus.NO_CONTENT).send();
45
+ };
46
+ res.badRequest = function (options) {
47
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.BAD_REQUEST, false, responseCodes_1.ResponseCodes.BAD_REQUEST, null, options);
48
+ };
49
+ res.unauthorized = function (options) {
50
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.UNAUTHORIZED, false, responseCodes_1.ResponseCodes.UNAUTHORIZED, null, options);
51
+ };
52
+ res.forbidden = function (options) {
53
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.FORBIDDEN, false, responseCodes_1.ResponseCodes.FORBIDDEN, null, options);
54
+ };
55
+ res.notFound = function (options) {
56
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.NOT_FOUND, false, responseCodes_1.ResponseCodes.NOT_FOUND, null, options);
57
+ };
58
+ res.conflict = function (options) {
59
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.CONFLICT, false, responseCodes_1.ResponseCodes.CONFLICT, null, options);
60
+ };
61
+ res.unprocessable = function (options) {
62
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.UNPROCESSABLE_ENTITY, false, responseCodes_1.ResponseCodes.UNPROCESSABLE, null, options);
63
+ };
64
+ res.tooManyRequests = function (options) {
65
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.TOO_MANY_REQUESTS, false, responseCodes_1.ResponseCodes.TOO_MANY_REQUESTS, null, options);
66
+ };
67
+ res.serverError = function (options) {
68
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.INTERNAL_SERVER_ERROR, false, responseCodes_1.ResponseCodes.SERVER_ERROR, null, options);
69
+ };
70
+ res.notImplemented = function (options) {
71
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.NOT_IMPLEMENTED, false, responseCodes_1.ResponseCodes.NOT_IMPLEMENTED, null, options);
72
+ };
73
+ res.serviceUnavailable = function (options) {
74
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.SERVICE_UNAVAILABLE, false, responseCodes_1.ResponseCodes.SERVICE_UNAVAILABLE, null, options);
75
+ };
76
+ // 2. Automate pagination schema formatting logic
77
+ res.paginate = function (data, options) {
78
+ const { page, limit, total, message, responseCode, meta } = options;
79
+ return responseFactory_1.ResponseFactory.create(res, httpStatus_1.HttpStatus.OK, true, responseCodes_1.ResponseCodes.SUCCESS, data, {
80
+ message,
81
+ responseCode,
82
+ meta,
83
+ pagination: { page, limit, total },
84
+ });
85
+ };
86
+ // 3. Wrap request inside isolation store container to track performance metrics flawlessly
87
+ context_1.requestContext.run({
88
+ requestId,
89
+ startTime: process.hrtime(),
90
+ timestamp: new Date().toISOString(),
91
+ }, () => next());
92
+ };
93
+ }
@@ -0,0 +1,7 @@
1
+ import { ApiKitPlugin } from '../core/pluginManager';
2
+ export declare const pluginAPI: {
3
+ /**
4
+ * Registers a global payload modification plugin hook.
5
+ */
6
+ register(plugin: ApiKitPlugin): void;
7
+ };
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pluginAPI = void 0;
4
+ const pluginManager_1 = require("../core/pluginManager");
5
+ exports.pluginAPI = {
6
+ /**
7
+ * Registers a global payload modification plugin hook.
8
+ */
9
+ register(plugin) {
10
+ pluginManager_1.globalPluginManager.use(plugin);
11
+ }
12
+ };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * @fileoverview Toolkit configuration signatures and defaults validation typing.
3
+ */
4
+ export interface ApiKitConfig {
5
+ /**
6
+ * The global active version of your API (e.g., 'v1', '1.0.0').
7
+ * If provided, automatically injected into every output meta object.
8
+ */
9
+ apiVersion?: string;
10
+ /**
11
+ * Toggle to enable or disable automatic X-Request-ID middleware parsing/generation.
12
+ * @default true
13
+ */
14
+ enableRequestId?: boolean;
15
+ /**
16
+ * Toggle to enable or disable high-precision performance monitoring (execution time).
17
+ * @default true
18
+ */
19
+ enablePerformanceTiming?: boolean;
20
+ /**
21
+ * Custom plugin/interceptors applied globally to all responses.
22
+ */
23
+ plugins?: Array<(payload: any, req: any, res: any) => any>;
24
+ /**
25
+ * Enterprise deep-override fallback message dictionary for mapping raw status numbers to custom text.
26
+ */
27
+ customMessages?: Record<number, string>;
28
+ /**
29
+ * Standard error options covering environmental handling constraints.
30
+ */
31
+ errors?: {
32
+ /**
33
+ * Expose full debug stacks directly in the json errors array.
34
+ * Generally set to false or conditionally tied to `process.env.NODE_ENV === 'development'`.
35
+ * @default false
36
+ */
37
+ exposeStack?: boolean;
38
+ /**
39
+ * Obfuscate default unhandled runtime exceptions with a sanitized fallback message.
40
+ * @default true
41
+ */
42
+ sanitizeServerErrors?: boolean;
43
+ };
44
+ }
45
+ /**
46
+ * Frozen defaults structure used internally when configuration properties are omitted.
47
+ */
48
+ export declare const DefaultApiKitConfig: Required<Omit<ApiKitConfig, 'apiVersion' | 'plugins' | 'customMessages'>> & {
49
+ apiVersion: string | undefined;
50
+ plugins: NonNullable<ApiKitConfig['plugins']>;
51
+ customMessages: Record<number, string>;
52
+ };
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ /**
3
+ * @fileoverview Toolkit configuration signatures and defaults validation typing.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DefaultApiKitConfig = void 0;
7
+ /**
8
+ * Frozen defaults structure used internally when configuration properties are omitted.
9
+ */
10
+ exports.DefaultApiKitConfig = {
11
+ apiVersion: undefined,
12
+ enableRequestId: true,
13
+ enablePerformanceTiming: true,
14
+ plugins: [],
15
+ customMessages: {},
16
+ errors: {
17
+ exposeStack: false,
18
+ sanitizeServerErrors: true,
19
+ },
20
+ };
21
+ Object.freeze(exports.DefaultApiKitConfig);
22
+ Object.freeze(exports.DefaultApiKitConfig.errors);
@@ -0,0 +1,3 @@
1
+ export * from './responses';
2
+ export * from './config';
3
+ export * from './plugin';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./responses"), exports);
18
+ __exportStar(require("./config"), exports);
19
+ __exportStar(require("./plugin"), exports);
@@ -0,0 +1,11 @@
1
+ import { StandardApiResponse } from './responses';
2
+ import { Request, Response } from 'express';
3
+ /**
4
+ * Signature function blueprint for all custom response interceptor plugins.
5
+ */
6
+ export type ApiKitPlugin = (payload: StandardApiResponse<any>, req: Request, res: Response) => StandardApiResponse<any> | Promise<StandardApiResponse<any>>;
7
+ export interface PluginMetadata {
8
+ name: string;
9
+ version: string;
10
+ description?: string;
11
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @fileoveriew Core response type definitions for express-api-kit.
3
+ * Establishes strict contract types for standardized API structural states.
4
+ */
5
+ /**
6
+ * Standard pagination metadata structure generated automatically by the toolkit.
7
+ */
8
+ export interface ApiResponsePagination {
9
+ page: number;
10
+ limit: number;
11
+ totalElements: number;
12
+ totalPages: number;
13
+ hasNextPage: boolean;
14
+ hasPrevPage: boolean;
15
+ }
16
+ /**
17
+ * Structural metadata automatically appended to API payloads by internal middleware.
18
+ */
19
+ export interface ApiResponseMeta {
20
+ requestId: string;
21
+ timestamp: string;
22
+ executionTimeMs: number;
23
+ apiVersion?: string;
24
+ [key: string]: unknown;
25
+ }
26
+ /**
27
+ * Structural shape of standard validation error items.
28
+ */
29
+ export interface ValidationErrorItem {
30
+ field: string;
31
+ message: string;
32
+ rule?: string;
33
+ }
34
+ /**
35
+ * Base standardized envelope for all API responses across the enterprise kit.
36
+ * @template T The type of the main data payload.
37
+ */
38
+ export interface StandardApiResponse<T = unknown> {
39
+ success: boolean;
40
+ statusCode: number;
41
+ responseCode: string;
42
+ message: string;
43
+ data: T | null;
44
+ meta: ApiResponseMeta;
45
+ pagination?: ApiResponsePagination;
46
+ errors?: ValidationErrorItem[] | unknown;
47
+ }
48
+ /**
49
+ * Flexible input signature for modifying standard response options dynamically.
50
+ */
51
+ export interface ResponseOptions {
52
+ message?: string;
53
+ responseCode?: string;
54
+ meta?: Record<string, unknown>;
55
+ errors?: ValidationErrorItem[] | unknown;
56
+ pagination?: {
57
+ page: number;
58
+ limit: number;
59
+ total: number;
60
+ };
61
+ }
62
+ /**
63
+ * Custom extended options specifically mapped for paginated execution.
64
+ */
65
+ export interface PaginationOptions {
66
+ page: number;
67
+ limit: number;
68
+ total: number;
69
+ message?: string;
70
+ responseCode?: string;
71
+ meta?: Record<string, unknown>;
72
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * @fileoveriew Core response type definitions for express-api-kit.
4
+ * Establishes strict contract types for standardized API structural states.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });