arkos 1.2.13-beta → 1.2.13-test.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/dist/cjs/app.js +138 -1
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/index.js +22 -0
- package/dist/cjs/modules/base/base.middlewares.js +4 -4
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +62 -43
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +82 -62
- package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js +23 -16
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js +40 -11
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js +419 -9
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +253 -0
- package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -0
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js +31 -20
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
- package/dist/cjs/paths.js +9 -1
- package/dist/cjs/server.js +85 -5
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/types/arkos-config.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +7 -7
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/start.js +4 -3
- package/dist/cjs/utils/cli/start.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-service-template.js +1 -1
- package/dist/cjs/utils/features/api.features.js +1 -1
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/cjs/utils/helpers/global.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +43 -21
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/cjs/utils/prisma/enhaced-prisma-json-schema-generator.js +451 -0
- package/dist/cjs/utils/prisma/enhaced-prisma-json-schema-generator.js.map +1 -0
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +88 -0
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -0
- package/dist/cjs/utils/prisma/prisma-schema-parser.js +158 -0
- package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -0
- package/dist/cjs/utils/prisma/types.js +3 -0
- package/dist/cjs/utils/prisma/types.js.map +1 -0
- package/dist/esm/index.d.mts +280 -0
- package/dist/esm/index.mjs +22 -0
- package/dist/exports/index.js +1 -0
- package/dist/types/arkos-config.js +1 -0
- package/dist/types/auth.js +1 -0
- package/dist/types/index.js +1 -0
- package/dist/types/modules/base/base.middlewares.d.ts +4 -4
- package/dist/types/modules/swagger/utils/helpers/get-authentication-json-schema-paths.d.ts +2 -1
- package/dist/types/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.d.ts +2 -1
- package/dist/types/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.d.ts +2 -1
- package/dist/types/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.d.ts +2 -1
- package/dist/types/modules/swagger/utils/helpers/missing-json-schemas-generator.d.ts +34 -0
- package/dist/types/modules/swagger/utils/helpers/swagger.router.helpers.d.ts +2 -2
- package/dist/types/router-config.js +1 -0
- package/dist/types/types/arkos-config.d.ts +3 -1
- package/dist/types/utils/helpers/models.helpers.d.ts +18 -4
- package/dist/types/utils/prisma/enhaced-prisma-json-schema-generator.d.ts +34 -0
- package/dist/types/utils/prisma/prisma-json-schema-generator.d.ts +10 -0
- package/dist/types/utils/prisma/prisma-schema-parser.d.ts +18 -0
- package/dist/types/utils/prisma/types.d.ts +48 -0
- package/dist/utils/arkos-env.js +1 -0
- package/dist/utils/dotenv.helpers.js +1 -0
- package/dist/utils/sheu.js +1 -0
- package/dist/utils/validate-dto.js +1 -0
- package/dist/utils/validate-schema.js +1 -0
- package/package.json +11 -6
- package/dist/esm/app.js +0 -1
- package/dist/esm/app.js.map +0 -1
- package/dist/esm/exports/auth/index.js +0 -2
- package/dist/esm/exports/auth/index.js.map +0 -1
- package/dist/esm/exports/controllers/index.js +0 -4
- package/dist/esm/exports/controllers/index.js.map +0 -1
- package/dist/esm/exports/error-handler/index.js +0 -4
- package/dist/esm/exports/error-handler/index.js.map +0 -1
- package/dist/esm/exports/index.js +0 -8
- package/dist/esm/exports/index.js.map +0 -1
- package/dist/esm/exports/middlewares/index.js +0 -2
- package/dist/esm/exports/middlewares/index.js.map +0 -1
- package/dist/esm/exports/prisma/index.js +0 -3
- package/dist/esm/exports/prisma/index.js.map +0 -1
- package/dist/esm/exports/services/index.js +0 -9
- package/dist/esm/exports/services/index.js.map +0 -1
- package/dist/esm/exports/utils/index.js +0 -4
- package/dist/esm/exports/utils/index.js.map +0 -1
- package/dist/esm/exports/validation/index.js +0 -4
- package/dist/esm/exports/validation/index.js.map +0 -1
- package/dist/esm/modules/auth/auth.controller.js +0 -187
- package/dist/esm/modules/auth/auth.controller.js.map +0 -1
- package/dist/esm/modules/auth/auth.router.js +0 -44
- package/dist/esm/modules/auth/auth.router.js.map +0 -1
- package/dist/esm/modules/auth/auth.service.js +0 -178
- package/dist/esm/modules/auth/auth.service.js.map +0 -1
- package/dist/esm/modules/auth/utils/helpers/auth.controller.helpers.js +0 -73
- package/dist/esm/modules/auth/utils/helpers/auth.controller.helpers.js.map +0 -1
- package/dist/esm/modules/base/base.controller.js +0 -150
- package/dist/esm/modules/base/base.controller.js.map +0 -1
- package/dist/esm/modules/base/base.middlewares.js +0 -81
- package/dist/esm/modules/base/base.middlewares.js.map +0 -1
- package/dist/esm/modules/base/base.router.js +0 -17
- package/dist/esm/modules/base/base.router.js.map +0 -1
- package/dist/esm/modules/base/base.service.js +0 -120
- package/dist/esm/modules/base/base.service.js.map +0 -1
- package/dist/esm/modules/base/utils/helpers/base.controller.helpers.js +0 -77
- package/dist/esm/modules/base/utils/helpers/base.controller.helpers.js.map +0 -1
- package/dist/esm/modules/base/utils/helpers/base.middlewares.helpers.js +0 -44
- package/dist/esm/modules/base/utils/helpers/base.middlewares.helpers.js.map +0 -1
- package/dist/esm/modules/base/utils/helpers/base.router.helpers.js +0 -89
- package/dist/esm/modules/base/utils/helpers/base.router.helpers.js.map +0 -1
- package/dist/esm/modules/base/utils/helpers/base.service.helpers.js +0 -165
- package/dist/esm/modules/base/utils/helpers/base.service.helpers.js.map +0 -1
- package/dist/esm/modules/email/email.service.js +0 -97
- package/dist/esm/modules/email/email.service.js.map +0 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +0 -107
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +0 -1
- package/dist/esm/modules/error-handler/utils/app-error.js +0 -15
- package/dist/esm/modules/error-handler/utils/app-error.js.map +0 -1
- package/dist/esm/modules/error-handler/utils/catch-async.js +0 -10
- package/dist/esm/modules/error-handler/utils/catch-async.js.map +0 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +0 -160
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +0 -1
- package/dist/esm/modules/file-upload/file-upload.controller.js +0 -266
- package/dist/esm/modules/file-upload/file-upload.controller.js.map +0 -1
- package/dist/esm/modules/file-upload/file-upload.router.js +0 -38
- package/dist/esm/modules/file-upload/file-upload.router.js.map +0 -1
- package/dist/esm/modules/file-upload/file-upload.service.js +0 -314
- package/dist/esm/modules/file-upload/file-upload.service.js.map +0 -1
- package/dist/esm/modules/file-upload/utils/helpers/file-upload.helpers.js +0 -87
- package/dist/esm/modules/file-upload/utils/helpers/file-upload.helpers.js.map +0 -1
- package/dist/esm/modules/swagger/swagger.router.js +0 -94
- package/dist/esm/modules/swagger/swagger.router.js.map +0 -1
- package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +0 -247
- package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +0 -1
- package/dist/esm/modules/swagger/utils/helpers/get-system-json-schema-paths.js +0 -63
- package/dist/esm/modules/swagger/utils/helpers/get-system-json-schema-paths.js.map +0 -1
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js +0 -38
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js.map +0 -1
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js +0 -19
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js.map +0 -1
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js +0 -24
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js.map +0 -1
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js +0 -436
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js.map +0 -1
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js +0 -159
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js.map +0 -1
- package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js +0 -84
- package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js.map +0 -1
- package/dist/esm/paths.js +0 -1
- package/dist/esm/paths.js.map +0 -1
- package/dist/esm/server.js +0 -5
- package/dist/esm/server.js.map +0 -1
- package/dist/esm/types/arkos-config.js +0 -2
- package/dist/esm/types/arkos-config.js.map +0 -1
- package/dist/esm/types/auth.js +0 -2
- package/dist/esm/types/auth.js.map +0 -1
- package/dist/esm/types/index.js +0 -8
- package/dist/esm/types/index.js.map +0 -1
- package/dist/esm/types/router-config.js +0 -2
- package/dist/esm/types/router-config.js.map +0 -1
- package/dist/esm/utils/arkos-env.js +0 -7
- package/dist/esm/utils/arkos-env.js.map +0 -1
- package/dist/esm/utils/cli/build.js +0 -206
- package/dist/esm/utils/cli/build.js.map +0 -1
- package/dist/esm/utils/cli/dev.js +0 -249
- package/dist/esm/utils/cli/dev.js.map +0 -1
- package/dist/esm/utils/cli/generate.js +0 -183
- package/dist/esm/utils/cli/generate.js.map +0 -1
- package/dist/esm/utils/cli/index.js +0 -74
- package/dist/esm/utils/cli/index.js.map +0 -1
- package/dist/esm/utils/cli/start.js +0 -86
- package/dist/esm/utils/cli/start.js.map +0 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +0 -16
- package/dist/esm/utils/cli/utils/cli.helpers.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-auth-configs-template.js +0 -33
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-auth-configs-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js +0 -18
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-middlewares.js +0 -232
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-middlewares.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js +0 -61
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-router-template.js +0 -37
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-router-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-service-template.js +0 -32
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-service-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generators.js +0 -25
- package/dist/esm/utils/cli/utils/template-generators.js.map +0 -1
- package/dist/esm/utils/dotenv.helpers.js +0 -37
- package/dist/esm/utils/dotenv.helpers.js.map +0 -1
- package/dist/esm/utils/features/api.features.js +0 -160
- package/dist/esm/utils/features/api.features.js.map +0 -1
- package/dist/esm/utils/features/change-case.features.js +0 -31
- package/dist/esm/utils/features/change-case.features.js.map +0 -1
- package/dist/esm/utils/helpers/api.features.helpers.js +0 -103
- package/dist/esm/utils/helpers/api.features.helpers.js.map +0 -1
- package/dist/esm/utils/helpers/change-case.helpers.js +0 -161
- package/dist/esm/utils/helpers/change-case.helpers.js.map +0 -1
- package/dist/esm/utils/helpers/deepmerge.helper.js +0 -113
- package/dist/esm/utils/helpers/deepmerge.helper.js.map +0 -1
- package/dist/esm/utils/helpers/fs.helpers.js +0 -52
- package/dist/esm/utils/helpers/fs.helpers.js.map +0 -1
- package/dist/esm/utils/helpers/global.helpers.js +0 -47
- package/dist/esm/utils/helpers/global.helpers.js.map +0 -1
- package/dist/esm/utils/helpers/models.helpers.js +0 -300
- package/dist/esm/utils/helpers/models.helpers.js.map +0 -1
- package/dist/esm/utils/helpers/prisma.helpers.js +0 -44
- package/dist/esm/utils/helpers/prisma.helpers.js.map +0 -1
- package/dist/esm/utils/helpers/query-parser.helpers.js +0 -40
- package/dist/esm/utils/helpers/query-parser.helpers.js.map +0 -1
- package/dist/esm/utils/helpers/routers.helpers.js +0 -16
- package/dist/esm/utils/helpers/routers.helpers.js.map +0 -1
- package/dist/esm/utils/helpers/text.helpers.js +0 -22
- package/dist/esm/utils/helpers/text.helpers.js.map +0 -1
- package/dist/esm/utils/sheu.js +0 -117
- package/dist/esm/utils/sheu.js.map +0 -1
- package/dist/esm/utils/validate-dto.js +0 -11
- package/dist/esm/utils/validate-dto.js.map +0 -1
- package/dist/esm/utils/validate-schema.js +0 -9
- package/dist/esm/utils/validate-schema.js.map +0 -1
package/dist/cjs/app.js
CHANGED
|
@@ -1 +1,138 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.app = void 0;
|
|
7
|
+
exports.bootstrap = bootstrap;
|
|
8
|
+
const express_1 = __importDefault(require("express"));
|
|
9
|
+
const cors_1 = __importDefault(require("cors"));
|
|
10
|
+
const cookie_parser_1 = __importDefault(require("cookie-parser"));
|
|
11
|
+
const auth_router_1 = require("./modules/auth/auth.router");
|
|
12
|
+
const base_router_1 = require("./modules/base/base.router");
|
|
13
|
+
const error_handler_controller_1 = __importDefault(require("./modules/error-handler/error-handler.controller"));
|
|
14
|
+
const express_rate_limit_1 = require("express-rate-limit");
|
|
15
|
+
const compression_1 = __importDefault(require("compression"));
|
|
16
|
+
const base_middlewares_1 = require("./modules/base/base.middlewares");
|
|
17
|
+
const prisma_helpers_1 = require("./utils/helpers/prisma.helpers");
|
|
18
|
+
const file_upload_router_1 = require("./modules/file-upload/file-upload.router");
|
|
19
|
+
const query_parser_helpers_1 = require("./utils/helpers/query-parser.helpers");
|
|
20
|
+
const deepmerge_helper_1 = __importDefault(require("./utils/helpers/deepmerge.helper"));
|
|
21
|
+
const swagger_router_1 = require("./modules/swagger/swagger.router");
|
|
22
|
+
exports.app = (0, express_1.default)();
|
|
23
|
+
async function bootstrap(arkosConfig) {
|
|
24
|
+
await (0, prisma_helpers_1.loadPrismaModule)();
|
|
25
|
+
if (arkosConfig?.configureApp)
|
|
26
|
+
await arkosConfig.configureApp(exports.app);
|
|
27
|
+
const middlewaresConfig = arkosConfig?.middlewares;
|
|
28
|
+
const disabledMiddlewares = middlewaresConfig?.disable || [];
|
|
29
|
+
const replacedMiddlewares = middlewaresConfig?.replace || {};
|
|
30
|
+
if (!disabledMiddlewares?.includes?.("compression"))
|
|
31
|
+
exports.app.use(replacedMiddlewares.compression ||
|
|
32
|
+
(0, compression_1.default)(arkosConfig?.compressionOptions));
|
|
33
|
+
if (!disabledMiddlewares?.includes?.("global-rate-limit"))
|
|
34
|
+
exports.app.use(replacedMiddlewares.globalRateLimit ||
|
|
35
|
+
(0, express_rate_limit_1.rateLimit)((0, deepmerge_helper_1.default)({
|
|
36
|
+
windowMs: 60 * 1000,
|
|
37
|
+
limit: 500,
|
|
38
|
+
standardHeaders: "draft-7",
|
|
39
|
+
legacyHeaders: false,
|
|
40
|
+
handler: (_, res) => {
|
|
41
|
+
res.status(429).json({
|
|
42
|
+
message: "Too many requests, please try again later",
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
}, arkosConfig?.globalRequestRateLimitOptions || {})));
|
|
46
|
+
if (!disabledMiddlewares?.includes?.("cors"))
|
|
47
|
+
exports.app.use(replacedMiddlewares.cors ||
|
|
48
|
+
(0, cors_1.default)(arkosConfig?.cors?.customHandler
|
|
49
|
+
? arkosConfig.cors.customHandler
|
|
50
|
+
: (0, deepmerge_helper_1.default)({
|
|
51
|
+
origin: (origin, cb) => {
|
|
52
|
+
const allowed = arkosConfig?.cors?.allowedOrigins;
|
|
53
|
+
if (allowed === "*") {
|
|
54
|
+
cb(null, true);
|
|
55
|
+
}
|
|
56
|
+
else if (Array.isArray(allowed)) {
|
|
57
|
+
cb(null, !origin || allowed?.includes?.(origin));
|
|
58
|
+
}
|
|
59
|
+
else if (typeof allowed === "string") {
|
|
60
|
+
cb(null, !origin || allowed === origin);
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
cb(null, false);
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
|
|
67
|
+
allowedHeaders: [
|
|
68
|
+
"Content-Type",
|
|
69
|
+
"Authorization",
|
|
70
|
+
"Connection",
|
|
71
|
+
],
|
|
72
|
+
credentials: true,
|
|
73
|
+
}, arkosConfig?.cors?.options || {})));
|
|
74
|
+
if (!disabledMiddlewares?.includes?.("express-json"))
|
|
75
|
+
exports.app.use(replacedMiddlewares.expressJson ||
|
|
76
|
+
express_1.default.json(arkosConfig?.jsonBodyParserOptions));
|
|
77
|
+
if (!disabledMiddlewares?.includes?.("cookie-parser"))
|
|
78
|
+
exports.app.use(replacedMiddlewares.cookieParser ||
|
|
79
|
+
(0, cookie_parser_1.default)(...[...(arkosConfig?.cookieParserParameters || [])]));
|
|
80
|
+
if (!disabledMiddlewares?.includes?.("query-parser"))
|
|
81
|
+
exports.app.use(replacedMiddlewares.queryParser ||
|
|
82
|
+
(0, query_parser_helpers_1.queryParser)((0, deepmerge_helper_1.default)({
|
|
83
|
+
parseNull: true,
|
|
84
|
+
parseUndefined: true,
|
|
85
|
+
parseBoolean: true,
|
|
86
|
+
}, arkosConfig?.queryParserOptions || {})));
|
|
87
|
+
if (!disabledMiddlewares?.includes?.("database-connection"))
|
|
88
|
+
exports.app.use(replacedMiddlewares.databaseConnection || prisma_helpers_1.checkDatabaseConnection);
|
|
89
|
+
if (!disabledMiddlewares?.includes?.("request-logger"))
|
|
90
|
+
exports.app.use(replacedMiddlewares.requestLogger || base_middlewares_1.handleRequestLogs);
|
|
91
|
+
if (arkosConfig?.middlewares?.additional)
|
|
92
|
+
arkosConfig.middlewares.additional.forEach((middleware) => {
|
|
93
|
+
exports.app.use(middleware);
|
|
94
|
+
});
|
|
95
|
+
const routersConfig = arkosConfig?.routers;
|
|
96
|
+
const disabledRouters = routersConfig?.disable || [];
|
|
97
|
+
const replacedRouters = routersConfig?.replace || {};
|
|
98
|
+
if (!disabledRouters?.includes?.("welcome-endpoint"))
|
|
99
|
+
exports.app.get("/api", replacedRouters.welcomeEndpoint ||
|
|
100
|
+
((_, res) => {
|
|
101
|
+
res.status(200).json({ message: arkosConfig.welcomeMessage });
|
|
102
|
+
}));
|
|
103
|
+
if (!disabledRouters?.includes?.("file-upload")) {
|
|
104
|
+
const fileUploadRouter = replacedRouters.fileUpload
|
|
105
|
+
? await replacedRouters.fileUpload(arkosConfig)
|
|
106
|
+
: await (0, file_upload_router_1.getFileUploadRouter)(arkosConfig);
|
|
107
|
+
exports.app.use(fileUploadRouter);
|
|
108
|
+
}
|
|
109
|
+
if (!disabledRouters?.includes?.("auth-router") &&
|
|
110
|
+
arkosConfig.authentication) {
|
|
111
|
+
const authRouter = replacedRouters.authRouter
|
|
112
|
+
? await replacedRouters.authRouter(arkosConfig)
|
|
113
|
+
: await (0, auth_router_1.getAuthRouter)(arkosConfig);
|
|
114
|
+
exports.app.use("/api", authRouter);
|
|
115
|
+
}
|
|
116
|
+
if (!disabledRouters?.includes?.("prisma-models-router")) {
|
|
117
|
+
const modelsRouter = replacedRouters.prismaModelsRouter
|
|
118
|
+
? await replacedRouters.prismaModelsRouter(arkosConfig)
|
|
119
|
+
: await (0, base_router_1.getPrismaModelsRouter)(arkosConfig);
|
|
120
|
+
exports.app.use("/api", modelsRouter);
|
|
121
|
+
}
|
|
122
|
+
exports.app.use("/api", (0, base_router_1.getAvailableResourcesAndRoutesRouter)());
|
|
123
|
+
if (arkosConfig.swagger &&
|
|
124
|
+
(process.env.ARKOS_BUILD !== "true" ||
|
|
125
|
+
arkosConfig.swagger.enableAfterBuild === true))
|
|
126
|
+
exports.app.use("/api", await (0, swagger_router_1.getSwaggerRouter)(arkosConfig));
|
|
127
|
+
if (routersConfig?.additional)
|
|
128
|
+
routersConfig.additional.forEach((router) => {
|
|
129
|
+
exports.app.use(router);
|
|
130
|
+
});
|
|
131
|
+
if (!disabledMiddlewares?.includes?.("global-error-handler"))
|
|
132
|
+
exports.app.use(replacedMiddlewares.globalErrorHandler || error_handler_controller_1.default);
|
|
133
|
+
exports.app.use("*", (_, res) => {
|
|
134
|
+
res.status(404).json({ message: "Route not found!" });
|
|
135
|
+
});
|
|
136
|
+
return exports.app;
|
|
137
|
+
}
|
|
138
|
+
//# sourceMappingURL=app.js.map
|
package/dist/cjs/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"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","sourcesContent":["import express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (req, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File upload router\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n app.use(fileUploadRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n // Additional custom routers\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n app.use(\"*\", (req, res) => {\n res.status(404).json({ message: \"Route not found!\" });\n });\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"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","sourcesContent":["// require(\"ts-node\").register({\n// esm: true,\n// experimentalSpecifierResolution: \"node\",\n// });\nimport express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File upload router\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n app.use(fileUploadRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n // Additional custom routers\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n app.use(\"*\", (_, res) => {\n res.status(404).json({ message: \"Route not found!\" });\n });\n\n return app;\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } function _optionalChainDelete(ops) { const result = _optionalChain(ops); return result == null ? true : result; }var jr=r=>async(e,t,s)=>{try{return await r(e,t,s)}catch(n){s(n)}},x=jr;function qr(r){return Lr(r)&&!_r(r)}function Lr(r){return!!r&&typeof r=="object"}function _r(r){let e=Object.prototype.toString.call(r);return e==="[object RegExp]"||e==="[object Date]"}function Wr(r){return Array.isArray(r)?[]:{}}function at(r){let e=Object.keys(r),t=Vr(r);return[...e,...t]}function Vr(r){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(r).filter(function(e){return Object.propertyIsEnumerable.call(r,e)}):[]}function Br(r,e){return e.clone!==!1&&_optionalChain([e, 'access', _2 => _2.isMergeableObject, 'optionalCall', _3 => _3(r)])?ne(Wr(r),r,e):r}function Jr(r,e,t){return r.concat(e).map(function(s){return t.cloneUnlessOtherwiseSpecified(s,t)})}function Qr(r,e){if(!e.customMerge)return ne;let t=e.customMerge(r);return typeof t=="function"?t:ne}function ct(r,e){try{return e in r}catch (e2){return!1}}function Hr(r,e){return ct(r,e)&&!(Object.hasOwnProperty.call(r,e)&&Object.propertyIsEnumerable.call(r,e))}function zr(r,e,t){let s={};return _optionalChain([t, 'access', _4 => _4.isMergeableObject, 'optionalCall', _5 => _5(r)])&&at(r).forEach(function(n){s[n]=t.cloneUnlessOtherwiseSpecified?t.cloneUnlessOtherwiseSpecified(r[n],t):r[n]}),at(e).forEach(function(n){Hr(r,n)||(ct(r,n)&&_optionalChain([t, 'access', _6 => _6.isMergeableObject, 'optionalCall', _7 => _7(e[n])])?s[n]=Qr(n,t)(r[n],e[n],t):s[n]=t.cloneUnlessOtherwiseSpecified?t.cloneUnlessOtherwiseSpecified(e[n],t):e[n])}),s}function ne(r,e,t){t=t||{};let s={arrayMerge:t.arrayMerge||Jr,isMergeableObject:t.isMergeableObject||qr,cloneUnlessOtherwiseSpecified:t.cloneUnlessOtherwiseSpecified||Br,clone:t.clone,customMerge:t.customMerge},n=Array.isArray(e),i=Array.isArray(r);return n===i?n?_optionalChain([s, 'access', _8 => _8.arrayMerge, 'optionalCall', _9 => _9(r,e,s)]):zr(r,e,s):s.cloneUnlessOtherwiseSpecified(e,s)}function Gr(r,e){if(!Array.isArray(r))throw new Error("first argument should be an array");return r.reduce((t,s)=>ne(t,s,e),{})}ne.all=Gr;var w=ne;var Kr={dateFields:["createdAt","updatedAt","deletedAt","date"],booleanFields:["isActive","isDeleted","isPublished","isArchived"],numericFields:["age","price","quantity","amount","rating"]};function Te(r,e=Kr){return Object.entries(JSON.parse(JSON.stringify(r))).reduce((t,[s,n])=>{let i=s.split("__");if(!n&&n!==!1&&n!=="false"&&i.length<2)return t;let o=Array.isArray(n)?_optionalChain([n, 'access', _10 => _10[0], 'optionalAccess', _11 => _11.toString, 'call', _12 => _12()]):n;if(i.length<2)return t[s]=typeof n=="string"&&!Number.isNaN(n)?fe(o,i[0],e):n,t;let a=i[0];if(a==="orderBy"&&i.length===2)return t.orderBy||(t.orderBy={}),t.orderBy[i[1]]=o,t;if(i.length===1)return t[a]={equals:fe(o,a,e)},t;let c=t,l=a;for(let p=1;p<i.length-1;p++)c[l]||(c[l]={}),c=c[l],l=i[p];let d=i[i.length-1];switch(d){case"icontains":c[l]={contains:o,mode:"insensitive"};break;case"contains":c[l]={contains:o,mode:"sensitive"};break;case"in":case"notIn":c[l]={[d]:o.split(",").map(u=>fe(u.trim(),a,e))};break;case"or":let p=o.split(",");t.OR||(t.OR=[]),t.OR.push(...p.map(u=>({[a]:{equals:fe(u.trim(),a,e)}})));break;case"isNull":c[l]={equals:o.toLowerCase()==="true"?null:void 0};break;case"isEmpty":c[l]={equals:o.toLowerCase()==="true"?"":void 0};break;default:c[l]={[d]:fe(o,a,e)}}return t},{})}function fe(r,e,t){return _optionalChain([t, 'access', _13 => _13.dateFields, 'optionalAccess', _14 => _14.includes, 'optionalCall', _15 => _15(e)])&&r?new Date(r):_optionalChain([t, 'access', _16 => _16.booleanFields, 'optionalAccess', _17 => _17.includes, 'optionalCall', _18 => _18(e)])&&r?r.toLowerCase()==="true":_optionalChain([t, 'access', _19 => _19.numericFields, 'optionalAccess', _20 => _20.includes, 'optionalCall', _21 => _21(e)])&&r?Number(r):r}var Ue=class extends Error{constructor(e,t,s,n){super(e),this.message=e,this.statusCode=t,this.status=`${t}`.startsWith("4")?"fail":"error",this.isOperational=!0,this.code=n,this.meta=s,this.missing=!1,Error.captureStackTrace(this,this.constructor)}},m=Ue;var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var _util = require('util');var _path = require('path'); var _path2 = _interopRequireDefault(_path);var lt=_util.promisify.call(void 0, _fs2.default.stat),xe=_util.promisify.call(void 0, _fs2.default.access),Ie=_util.promisify.call(void 0, _fs2.default.mkdir),oe=()=>process.env.ARKOS_BUILD==="true"?process.cwd()+"/.build/":process.cwd();function Me(r){if(typeof r!="string")throw new Error("Path must be a string");let t=process.cwd().replace(/\/+$/,"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return r.replace(new RegExp(`${t}/?`,"g"),"")}var W,K=()=>{if(W)return W;try{let r=process.cwd(),e=_fs2.default.existsSync(_path2.default.join(r,"tsconfig.json")),t=_fs2.default.existsSync(_path2.default.join(r,"src","app.ts")),s=_fs2.default.existsSync(_path2.default.join(r,"src","app.js"));return process.env.ARKOS_BUILD==="true"?W="js":e||t&&!s?W="ts":W="js",W}catch (e3){return W="js",W}};var _module = require('module');var _url = require('url');function Zr(){try{let r=_path2.default.join(process.cwd(),"package.json");if(_fs2.default.existsSync(r))return JSON.parse(_fs2.default.readFileSync(r,"utf8"))}catch(r){console.error("Error checking package.json:",r)}}function es(){return _optionalChain([Zr, 'call', _22 => _22(), 'optionalAccess', _23 => _23.type])==="module"}async function Q(r,e={fixExtension:!0}){if(!e.fixExtension||r.endsWith(".ts")||!es())return await Promise.resolve().then(() => _interopRequireWildcard(require(r)));let s=_module.createRequire.call(void 0, _url.pathToFileURL.call(void 0, process.cwd()+"/package.json")).resolve(r);return await Promise.resolve().then(() => _interopRequireWildcard(require(_url.pathToFileURL.call(void 0, s))))}var he=null;async function je(){if(!he)try{let r=`${oe()}/src/utils/prisma.${K()}`;if(_fs2.default.existsSync(r)||(r=`${oe()}/src/utils/prisma/index.${K()}`),!_fs2.default.existsSync(r))throw new Error("Could not found exported prisma insteance");let e=await Q(r,{fixExtension:!1});if(he=e.default||e.prisma,!he)throw new Error("Prisma not found")}catch(r){throw r.message==="Prisma not found"?new m(`Could not initialize Prisma module. Make sure your prisma instance is exported under src/utils/prisma.${K()} or src/utils/prisma/index.${K()}, read more about Arkos' Project Structure under https://www.arkosjs.com/docs/project-structure#root-structure`,500,{},"PrismaInstanceNotFound"):r}return he}function U(){return he}var mt=x(async(r,e,t)=>{let s=await je();try{await s.$connect(),t()}catch(n){console.error("Database connection error",n.message),t(new m(n.message,503))}});var H=class{constructor(e,t){this.filters={};this.reqFiltersSearchParam={};this.excludedFields=["page","filters","sort","limit","fields","addFields","removeFields","search","include","filterMode","where","prismaQueryOptions","ignoredFields"];if(e){let{filters:s="{}",...n}=e.query;this.req=e,this.searchParams=w(Te(n),JSON.parse(s))}t&&(this.modelName=t),this.filters={...this.filters}}setup(e,t){if(e){let{filters:s="{}",...n}=e.query;this.req=e,this.searchParams=w(Te(n),JSON.parse(s))}return t&&(this.modelName=t),this.filters={...this.filters},this}filter(){if(!this.req)throw new Error("Trying to use APIFeatures.filter() without passing request on class constructor or APIFeatures.setup() method. read more about at www.arkosjs.com/docs/advanced-guide/api-features-class");let e=[],t={...this.searchParams};this.excludedFields.forEach(a=>delete t[a]);let s={...this.req.params,...t},n=Object.keys(s).map(a=>({[a]:s[a]})),i=n.length>0?{[_nullishCoalesce(_optionalChain([this, 'access', _24 => _24.req, 'access', _25 => _25.query, 'optionalAccess', _26 => _26.filterMode]), () => ("OR"))]:n}:{};if(this.searchParams.search){let a=U();this.modelName&&Object.keys(a[this.modelName].fields).forEach(c=>{let l=a[this.modelName].fields[c];_optionalChain([l, 'optionalAccess', _27 => _27.typeName])==="String"&&c!=="id"&&c!=="password"&&!l.isList&&!_optionalChain([c, 'optionalAccess', _28 => _28.includes, 'optionalCall', _29 => _29("Id")])&&!_optionalChain([c, 'optionalAccess', _30 => _30.includes, 'optionalCall', _31 => _31("ID")])&&e.push({[`${c}`]:{contains:this.searchParams.search,mode:"insensitive"}})}),i=w({OR:e},i)}let o=w({where:i},this.req.prismaQueryOptions||{});return this.filters=w(o,this.filters),this}search(){_optionalChain([this, 'access', _32 => _32.searchParams, 'optionalAccess', _33 => _33.search])&&(this.filters=w(this.filters,{where:{OR:[]}}))}sort(){if(this.searchParams.sort){let e=_optionalChain([this, 'access', _34 => _34.searchParams, 'optionalAccess', _35 => _35.sort, 'optionalAccess', _36 => _36.split, 'call', _37 => _37(","), 'optionalAccess', _38 => _38.map, 'call', _39 => _39(t=>({[t.startsWith("-")?t.substring(1):t]:t.startsWith("-")?"desc":"asc"}))]);this.filters=w(this.filters,{orderBy:e})}return this}limitFields(){if(_optionalChain([this, 'access', _40 => _40.searchParams, 'optionalAccess', _41 => _41.fields])){let e=this.searchParams.fields.split(","),t=e.filter(o=>!o.startsWith("+")&&!o.startsWith("-")),s=e.filter(o=>o.startsWith("+")).map(o=>o.substring(1)),n=e.filter(o=>o.startsWith("-")).map(o=>o.substring(1)),i={};t.length>0?i=t.reduce((o,a)=>(o[a]=!0,o),{}):(i=this.filters.include||{},s.forEach(o=>{i[o]=!0}),n.forEach(o=>{i[o]=!1})),this.filters={...this.filters,select:i},this.filters.include&&delete this.filters.include}if(_optionalChain([this, 'access', _42 => _42.searchParams, 'optionalAccess', _43 => _43.addFields])||_optionalChain([this, 'access', _44 => _44.searchParams, 'optionalAccess', _45 => _45.removeFields]))throw new m("The addFields and removeFields parameters are deprecated. Please use fields with + and - prefixes instead.",400);return this}paginate(){let e=parseInt(this.searchParams.page,10)||1,t=parseInt(this.searchParams.limit,10)||30,s=(e-1)*t;return this.filters={...this.filters,skip:s,take:t},this}},ts=new H;var rs=/([\p{Ll}\d])(\p{Lu})/gu,ss=/(\p{Lu})([\p{Lu}][\p{Ll}])/gu,ns=/(\d)\p{Ll}|(\p{L})\d/u,is=/[^\p{L}\d]+/giu,ft="$1\0$2";function ht(r){let e=r.trim();e=e.replace(rs,ft).replace(ss,ft),e=e.replace(is,"\0");let t=0,s=e.length;for(;e.charAt(t)==="\0";)t++;if(t===s)return[];for(;e.charAt(s-1)==="\0";)s--;return e.slice(t,s).split(/\0/g)}function os(r){let e=ht(r);for(let t=0;t<e.length;t++){let s=e[t],n=ns.exec(s);if(n){let i=n.index+(_nullishCoalesce(n[1], () => (n[2]))).length;e.splice(t,1,s.slice(0,i),s.slice(i))}}return e}function as(r,e){let[t,s,n]=Le(r,e);return t+s.map(qe(_optionalChain([e, 'optionalAccess', _46 => _46.locale]))).join(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _47 => _47.delimiter]), () => (" ")))+n}function re(r,e){let[t,s,n]=Le(r,e),i=qe(_optionalChain([e, 'optionalAccess', _48 => _48.locale])),o=gt(_optionalChain([e, 'optionalAccess', _49 => _49.locale])),a=_optionalChain([e, 'optionalAccess', _50 => _50.mergeAmbiguousCharacters])?yt(i,o):wt(i,o);return t+s.map((c,l)=>l===0?i(c):a(c,l)).join(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _51 => _51.delimiter]), () => ("")))+n}function P(r,e){let[t,s,n]=Le(r,e),i=qe(_optionalChain([e, 'optionalAccess', _52 => _52.locale])),o=gt(_optionalChain([e, 'optionalAccess', _53 => _53.locale])),a=_optionalChain([e, 'optionalAccess', _54 => _54.mergeAmbiguousCharacters])?yt(i,o):wt(i,o);return t+s.map(a).join(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _55 => _55.delimiter]), () => ("")))+n}function $(r,e){return as(r,{delimiter:"-",...e})}function qe(r){return r===!1?e=>e.toLowerCase():e=>e.toLocaleLowerCase(r)}function gt(r){return r===!1?e=>e.toUpperCase():e=>e.toLocaleUpperCase(r)}function yt(r,e){return t=>`${e(t[0])}${r(t.slice(1))}`}function wt(r,e){return(t,s)=>{let n=t[0];return(s>0&&n>="0"&&n<="9"?"_"+n:e(n))+r(t.slice(1))}}function Le(r,e={}){let t=_nullishCoalesce(e.split, () => ((e.separateNumbers?os:ht))),s=_nullishCoalesce(e.prefixCharacters, () => ("")),n=_nullishCoalesce(e.suffixCharacters, () => ("")),i=0,o=r.length;for(;i<r.length;){let a=r.charAt(i);if(!_optionalChain([s, 'optionalAccess', _56 => _56.includes, 'optionalCall', _57 => _57(a)]))break;i++}for(;o>i;){let a=o-1,c=r.charAt(a);if(!_optionalChain([n, 'optionalAccess', _58 => _58.includes, 'optionalCall', _59 => _59(c)]))break;o=a}return[r.slice(0,i),t(r.slice(i,o)),r.slice(o)]}var _chokidar = require('chokidar');var _dotenv = require('dotenv'); var _dotenv2 = _interopRequireDefault(_dotenv);var _e=class{getTimestamp(){return new Date().toTimeString().split(" ")[0]}formatText(e="",t={}){let s=_optionalChain([t, 'optionalAccess', _60 => _60.label])?e?_optionalChain([t, 'optionalAccess', _61 => _61.label])+" ":_optionalChain([t, 'optionalAccess', _62 => _62.label]):"",n=`${s}${e}`;if(t.timestamp){let i=this.getTimestamp();if(t.timestamp===!0)n=`${s}\x1B[90m${i}\x1B[0m ${e}`;else if(typeof t.timestamp=="string"){let o=this.getColorCode(t.timestamp);n=`${s}${o}${i}\x1B[0m ${e}`}}return t.bold&&(n=`\x1B[1m${n}\x1B[0m`),n}getColorCode(e){return{red:"\x1B[31m",blue:"\x1B[34m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",magenta:"\x1B[35m",white:"\x1B[37m",black:"\x1B[30m",gray:"\x1B[90m",orange:"\x1B[91m"}[e]||"\x1B[90m"}red(e,t){let s=`\x1B[31m${e}\x1B[0m`;return this.formatText(s,t||{})}blue(e,t){let s=`\x1B[34m${e}\x1B[0m`;return this.formatText(s,t||{})}green(e,t){let s=`\x1B[32m${e}\x1B[0m`;return this.formatText(s,t||{})}yellow(e,t){let s=`\x1B[33m${e}\x1B[0m`;return this.formatText(s,t||{})}cyan(e,t){let s=`\x1B[36m${e}\x1B[0m`;return this.formatText(s,t||{})}magenta(e,t){let s=`\x1B[35m${e}\x1B[0m`;return this.formatText(s,t||{})}white(e,t){let s=`\x1B[37m${e}\x1B[0m`;return this.formatText(s,t||{})}black(e,t){let s=`\x1B[30m${e}\x1B[0m`;return this.formatText(s,t||{})}gray(e,t){let s=`\x1B[90m${e}\x1B[0m`;return this.formatText(s,t||{})}orange(e,t){let s=`\x1B[91m${e}\x1B[0m`;return this.formatText(s,t||{})}bold(e,t){let s=`\x1B[1m${e}\x1B[0m`;return this.formatText(s,{...t,bold:!1})}info(e,t){let n=this.formatText(e,{...t,label:"[\x1B[36mINFO\x1B[0m]"});return console.info(n),n}error(e,t){let n=this.formatText(e,{...t,label:"[\x1B[31mERROR\x1B[0m]"});return console.error(n),n}ready(e,t){let n=this.formatText(e,{...t,label:"[\x1B[32mREADY\x1B[0m]"});return console.info(n),n}done(e,t){let n=this.formatText(e,{...t,label:"[\x1B[32mDONE\x1B[0m]"});return console.info(n),n}warn(e,t){let n=this.formatText(e,{...t,label:"[\x1B[33mWARN\x1B[0m]"});return console.warn(n),n}},cs=new _e,I=cs;var bt=null;function At(){_optionalChain([bt, 'optionalAccess', _63 => _63.kill, 'optionalCall', _64 => _64()]),bt=null}var xt=null;function Mt(){_optionalChain([xt, 'optionalAccess', _65 => _65.kill, 'optionalCall', _66 => _66()]),xt=null}function X(){At(),Mt()}var Rt={};function L(r){return Rt[$(r)]}function $t(r){let e=$(r).toLowerCase(),t=r.toLowerCase()==="auth",s=K();return{core:{service:`${e}.service.${s}`,controller:`${e}.controller.${s}`,middlewares:`${e}.middlewares.${s}`,authConfigs:`${e}.auth-configs.${s}`,authConfigsNew:`${e}.auth.${s}`,prismaQueryOptions:`${e}.prisma-query-options.${s}`,prismaQueryOptionsNew:`${e}.query.${s}`,router:`${e}.router.${s}`},dtos:t?{login:`login.dto.${s}`,signup:`signup.dto.${s}`,getMe:`get-me.dto.${s}`,updateMe:`update-me.dto.${s}`,updatePassword:`update-password.dto.${s}`}:{model:`${e}.dto.${s}`,create:`create-${e}.dto.${s}`,createOne:`create-${e}.dto.${s}`,createMany:`create-many-${e}.dto.${s}`,update:`update-${e}.dto.${s}`,updateOne:`update-${e}.dto.${s}`,updateMany:`update-many-${e}.dto.${s}`,query:`query-${e}.dto.${s}`,findOne:`find-one-${e}.dto.${s}`,findMany:`find-many-${e}.dto.${s}`},schemas:t?{login:`login.schema.${s}`,signup:`signup.schema.${s}`,getMe:`get-me.schema.${s}`,updateMe:`update-me.schema.${s}`,updatePassword:`update-password.schema.${s}`}:{model:`${e}.schema.${s}`,create:`create-${e}.schema.${s}`,createOne:`create-${e}.schema.${s}`,createMany:`create-many-${e}.schema.${s}`,update:`update-${e}.schema.${s}`,updateOne:`update-${e}.schema.${s}`,updateMany:`update-many-${e}.schema.${s}`,query:`query-${e}.schema.${s}`,findOne:`find-one-${e}.schema.${s}`,findMany:`find-many-${e}.schema.${s}`}}}async function ps(r,e){let t=_path2.default.resolve(oe(),"src","modules",$(r)),s=_path2.default.join(t,e),n=$t(r),i={};try{await _fs2.default.promises.access(s).catch(()=>{}),await Promise.all(Object.entries(n[e]).map(async([o,a])=>{let c=_path2.default.join(s,a);try{let l=await Q(c).catch(d=>{d.message.includes("Cannot find module")||(I.error(`Failed to import ${a}:`),console.error(d),X(),process.exit(1))});l&&(i[o]=l.default)}catch(l){console.error(l)}}))}catch(o){console.error(o)}return i}function us(r,e,t){if(r==="prismaQueryOptions"){if(t.prismaQueryOptions)throw X(),new Error(`
|
|
2
|
+
Cannot use both ${e} and ${e.replace("prisma-query-options","query")} at once, please choose only one name convention.
|
|
3
|
+
`)}else if(r==="prismaQueryOptionsNew"){if(t.prismaQueryOptions)throw X(),new Error(`
|
|
4
|
+
Cannot use both ${e} and ${e.replace("query","prisma-query-options")} at once, please choose only one name convention.
|
|
5
|
+
`)}else if(r==="authConfigs"){if(t.authConfigs)throw X(),new Error(`
|
|
6
|
+
Cannot use both ${e} and ${e.replace("auth-configs","auth")} at once, please choose only one name convention.
|
|
7
|
+
`)}else if(r==="authConfigsNew"&&t.authConfigs)throw X(),new Error(`
|
|
8
|
+
Cannot use both ${e} and ${e.replace("auth","auth-configs")} at once, please choose only one name convention.
|
|
9
|
+
`)}function ms(r,e,t){r==="prismaQueryOptions"||r==="prismaQueryOptionsNew"?t.prismaQueryOptions=e.default||e:r==="authConfigs"||r==="authConfigsNew"?t.authConfigs=e.default||e:r==="middlewares"||r==="router"?t[r]=e:t[r]=e.default||e}async function j(r,e){let t=_path2.default.resolve(oe(),"src","modules",$(r)),s={dtos:{},schemas:{}};if(L(r))return L(r);let n=$t(r);await Promise.all(Object.entries(n.core).map(async([a,c])=>{let l=_path2.default.join(t,c);try{let d=await Q(l).catch(p=>{p.message.includes("Cannot find module")||(I.error(`Failed to import ${c}:`),console.error(p),X(),process.exit(1))});d&&(us(a,c,s),ms(a,d,s))}catch(d){if(d.message.includes("Cannot use both"))throw d;console.error(d),X()}}));let i=_optionalChain([e, 'access', _67 => _67.validation, 'optionalAccess', _68 => _68.resolver])?e.validation.resolver==="zod"?"schemas":"dtos":null,o={};return i&&(o=await ps(r,i)),Rt[r]={...s,...i&&{[i]:o}},{...s,...i&&{[i]:o}}}var We={};function vt(r,e=[]){return _optionalChain([_fs2.default, 'access', _69 => _69.readdirSync, 'call', _70 => _70(r), 'optionalAccess', _71 => _71.forEach, 'call', _72 => _72(s=>{let n=_path2.default.join(r,s),i=_fs2.default.statSync(n);i.isDirectory()&&s!=="migrations"?e=vt(n,e):i.isFile()&&s.endsWith(".prisma")&&e.push(n)})]),e}var fs=/model\s+(\w+)\s*{/g,ge=[],Pt,Ve=[];function Ot(){let r=Re();for(let e of ge){let t=P(e),s=r.indexOf(`model ${t} {`),n=r.indexOf("}",s),i=r.slice(s,n),o={singular:[],list:[]},a=i.split(`
|
|
10
|
+
`);for(let c of a){let l=c.trim();if(!l||l.startsWith("model")||l.startsWith("//")||l.startsWith("/*"))continue;let[d,p]=l.split(/\s+/),u=_optionalChain([l, 'optionalAccess', _73 => _73.includes, 'optionalCall', _74 => _74("@unique")]);if(u){let y=Ve[e]||[];y.some(b=>b.name===d&&b.type===p&&b.isUnique===u)||(Ve[e]=[...y,{name:d,type:p,isUnique:u}])}let f=_optionalChain([p, 'optionalAccess', _75 => _75.replace, 'call', _76 => _76("[]",""), 'access', _77 => _77.replace, 'call', _78 => _78("?","")]);if(_optionalChain([l, 'optionalAccess', _79 => _79.includes, 'optionalCall', _80 => _80("@relation")])||l.match(/\s+\w+(\[\])?(\s+@|$)/)||_optionalChain([ge, 'optionalAccess', _81 => _81.includes, 'optionalCall', _82 => _82(re(f||""))])){let y=r.indexOf(`enum ${f} {`),h=r.indexOf(`type ${f} {`);if(!f||y>=0||h>=0||f==="String"||f==="Int"||f==="Float"||f==="Boolean"||f==="DateTime"||f==="Bytes"||f==="Decimal"||f==="BigInt"||f==="Json")continue;_optionalChain([p, 'optionalAccess', _83 => _83.includes, 'optionalCall', _84 => _84("[]")])?o.list.push({name:d,type:f}):o.singular.push({name:d,type:f})}We[t]=o}}}function ce(r){if(r=P(r),r in We)return We[r]}function D(){return ge}function Re(){if(Pt)return Pt;let r=[],e=vt("./prisma");for(let s of e){let n=_fs2.default.readFileSync(s,"utf-8");_optionalChain([r, 'optionalAccess', _85 => _85.includes, 'optionalCall', _86 => _86(n)])||r.push(n)}return r.join(`
|
|
11
|
+
`).replace(fs,(s,n)=>(_optionalChain([ge, 'optionalAccess', _87 => _87.includes, 'optionalCall', _88 => _88(n)])||ge.push(re(n.trim())),`model ${n} {`))}function St(r){return Ve[r]}async function k(r,e,t){return _optionalChain([t, 'optionalAccess', _89 => _89.swagger, 'optionalAccess', _90 => _90.mode])==="prisma"?!1:!!await _asyncOptionalChain([(await j(e,t)), 'optionalAccess', async _91 => _91[_optionalChain([t, 'access', _92 => _92.validation, 'optionalAccess', _93 => _93.resolver])==="zod"?"schemas":"dtos"], 'optionalAccess', async _94 => _94[re(r)]])}function Be(r){if(!r||typeof r!="object")return r;let e={};for(let[t,s]of Object.entries(r))t!=="apiAction"&&(Array.isArray(s)?e[t]=s.map(n=>typeof n=="object"&&n!==null?Be(n):n):typeof s=="object"&&s!==null?e[t]=Be(s):e[t]=s);return e}function Ct(r){return!r||typeof r!="object"?!1:["create","connect","update","delete","disconnect","deleteMany","connectOrCreate","upsert","set"].some(t=>t in r)}function Y(r,e,t=[]){let s={...r};if(_optionalChain([e, 'optionalAccess', _95 => _95.list, 'optionalAccess', _96 => _96.forEach, 'call', _97 => _97(n=>{if(!r[n.name]||Ct(r[n.name])||!Array.isArray(r[n.name]))return;let i=[],o=[],a=[],c=[],l=[];_optionalChain([r, 'access', _98 => _98[n.name], 'optionalAccess', _99 => _99.forEach, 'call', _100 => _100(d=>{if(_optionalChain([t, 'optionalAccess', _101 => _101.includes, 'optionalCall', _102 => _102(_optionalChain([d, 'optionalAccess', _103 => _103.apiAction]))]))return;let p=_optionalChain([d, 'optionalAccess', _104 => _104.apiAction]);if(p==="delete")l.push(d.id);else if(p==="disconnect")c.push({id:d.id});else if(Et(n.type,d)){let{apiAction:u,...f}=d;o.push(f)}else if(_optionalChain([d, 'optionalAccess', _105 => _105.id])){let{id:u,apiAction:f,...y}=d,h=ce(n.type),b=y;h&&(b=Y(y,h,t)),a.push({where:{id:u},data:b})}else{let u=ce(n.type),f={...d};if(u&&(f=Y(f,u,t)),"apiAction"in f){let{apiAction:y,...h}=f;f=h}i.push(f)}})]),s[n.name]={...i.length?{create:i}:{},...o.length?{connect:o}:{},...a.length?{update:a}:{},...c.length?{disconnect:c}:{},...l.length?{deleteMany:{id:{in:l}}}:{}}})]),_optionalChain([e, 'optionalAccess', _106 => _106.singular, 'optionalAccess', _107 => _107.forEach, 'call', _108 => _108(n=>{if(!r[n.name]||_optionalChain([t, 'optionalAccess', _109 => _109.includes, 'optionalCall', _110 => _110(_optionalChain([r, 'access', _111 => _111[n.name], 'optionalAccess', _112 => _112.apiAction]))])||Ct(r[n.name]))return;let i=r[n.name],o=ce(n.type);if(Et(n.type,i)){let{apiAction:a,...c}=i;s[n.name]={connect:c}}else if(_optionalChain([i, 'optionalAccess', _113 => _113.id])){let{id:a,apiAction:c,...l}=i,d=l;o&&(d=Y(l,o,t)),s[n.name]={update:{data:d}}}else{let a={...i};if("apiAction"in a){let{apiAction:c,...l}=a;a=l}o&&(a=Y(a,o,t)),s[n.name]={create:a}}})]),"apiAction"in s){let{apiAction:n,...i}=s;s=i}return Be(s)}function Et(r,e){if(!e||e.apiAction&&!_optionalChain([["connect"], 'access', _114 => _114.includes, 'optionalCall', _115 => _115(e.apiAction)]))return!1;if(e.apiAction==="connect"||_optionalChain([Object, 'access', _116 => _116.keys, 'call', _117 => _117(e), 'optionalAccess', _118 => _118.length])===1&&_optionalChain([e, 'optionalAccess', _119 => _119.id]))return!0;let t=St(r);if(Object.keys(e).length===1){let s=Object.keys(e)[0];return _optionalChain([t, 'optionalAccess', _120 => _120.some, 'call', _121 => _121(n=>n.name===s)])}return!1}var _jsonwebtoken = require('jsonwebtoken'); var _jsonwebtoken2 = _interopRequireDefault(_jsonwebtoken);var _bcryptjs = require('bcryptjs'); var _bcryptjs2 = _interopRequireDefault(_bcryptjs);var _express = require('express'); var _express2 = _interopRequireDefault(_express);var _cors = require('cors'); var _cors2 = _interopRequireDefault(_cors);var _cookieparser = require('cookie-parser'); var _cookieparser2 = _interopRequireDefault(_cookieparser);var hs={JWT_SECRET:"13a9279eedb286f756212511267152e9585055809ec0606ea9f7eb98a87660c1616fbd39c44d4238a82f29df90b529e24bfdf72a480d1149d79c991c863a22b5ae0fb3ae6f5323bfd6664faef99792637477c38da488e7aa0d39b83ba99aba8e8a20efde7fd5c7ba21a6c938e17a9f99f73226dc61e89cd63f159257841194323f100d1a49b88ce4fdcdf2b066a5f32f88ee12f6487b55b4b5687d7c0caffdd8524e2adc4b941cf52e948f5b330f527eb1354341c876eed12dfa92cef3c341d030d05e6beb1e0a7f6d3e08e7b1aac045130457fd3a53ee469fecdd20fdd2c7a6a72b07cbcb1157c5b1cc581e6767bea32be8e125016a48951e85c7bdb961d9c9fab28444499ce063664fe0bd1a05d60294323bdd69af6d6ff1a2533dac8d4a869f76dbc746ee12f144e0af41029f620471817843140c23d036e731f3ebee21a70ff1549e97486fdf9cbef132ff2ced59fde9be35dd04b358c9a25ec4fd9cc0e36dae651e626d8c13b0c6d2a21f237517a05059680173e71817597062c792ea9c66030ca0d8ed82987e29189947692a0be5fffac4c988ca33f14ce96349661ef850dbff6909c7797676c90a5e47655346f59759482ef8a3a948e97e30f889bd4571610fd19e8ea4818651d37f6529cf32f0fc805bc053e911f0fe96f52b4420d54bd1f40739a95f5853b036c86ab9a51bed57fa9bd48607b5302e88db00900adf",JWT_EXPIRES_IN:"30d",PRISMA_SCHEMA_PATH:"./prisma/schema"},le=hs;var Ft=r=>{let e=_optionalChain([M, 'call', _122 => _122(), 'optionalAccess', _123 => _123.authentication]);if(_optionalChain([r, 'access', _124 => _124.query, 'optionalAccess', _125 => _125.usernameField])&&typeof _optionalChain([r, 'access', _126 => _126.query, 'optionalAccess', _127 => _127.usernameField])=="string"&&_optionalChain([e, 'optionalAccess', _128 => _128.login, 'optionalAccess', _129 => _129.allowedUsernames, 'optionalAccess', _130 => _130.includes, 'optionalCall', _131 => _131(r.query.usernameField)]))return r.query.usernameField;if(_optionalChain([r, 'access', _132 => _132.query, 'optionalAccess', _133 => _133.usernameField]))throw new m("Invalid usernameField parameter, it is not allowed!",400);return _optionalChain([e, 'optionalAccess', _134 => _134.login, 'optionalAccess', _135 => _135.allowedUsernames, 'optionalAccess', _136 => _136[0]])||"username"},kt=(r,e)=>{if(!r)return{};let t=r.split("."),s={};if(t.length===1)return s[t[0]]=e,s;let n=s;for(let i=0;i<t.length-1;i++){let o=t[i];n[o]={},n=n[o]}return n[t[t.length-1]]=e,s},Tt=(r,e)=>{if(!r||!e)return;let t=e.split("."),s=t[t.length-1];if(s in r)return r[s]};function gs(r){return r.toLowerCase().replace(/years?|yr|year/g,"y").replace(/minutes?|min/g,"m").replace(/seconds?|sec|secs/g,"s").replace(/hours?|hr/g,"h").replace(/days?/g,"d").replace(/weeks?/g,"w").replace(/milliseconds?/g,"ms")}function Ut(r){if(typeof r=="number")return r*1e3;let e=gs(r.trim()),t=/^(\d+(?:\.\d+)?)(ms|s|m|h|d|w|y)$/i,s=e.match(t);if(!s)throw new Error(`Invalid time format: ${r}`);let n=parseFloat(s[1]),i=s[2].toLowerCase();return n*{ms:1,s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,y:315576e5}[i]}var $e={password:!1},Nt=async(r={})=>{let e=Dt().user;return{getMe:x(async(t,s,n)=>{let i=await e.findOne({id:t.user.id},t.prismaQueryOptions||{});if(Object.keys($e).forEach(o=>{i&&delete i[o]}),_optionalChain([r, 'optionalAccess', _137 => _137.afterGetMe]))return t.responseData={data:i},t.responseStatus=200,n();s.status(200).json({data:i})}),updateMe:x(async(t,s,n)=>{if("password"in t.body)throw new m("In order to update password use the update-password endpoint.",400,{},"InvalidFieldPassword");let i=await e.updateOne({id:t.user.id},t.body,t.prismaQueryOptions||{});if(Object.keys($e).forEach(o=>{i&&delete i[o]}),_optionalChain([r, 'optionalAccess', _138 => _138.afterUpdateMe]))return t.responseData={data:i},t.responseStatus=200,n();s.status(200).json({data:i})}),logout:x(async(t,s,n)=>{if(s.cookie("arkos_access_token","no-token",{expires:new Date(Date.now()+10*1e3),httpOnly:!0}),_optionalChain([r, 'optionalAccess', _139 => _139.afterLogout]))return t.responseData=null,t.responseStatus=204,n();s.status(204).json()}),login:x(async(t,s,n)=>{let i=_optionalChain([M, 'call', _140 => _140(), 'optionalAccess', _141 => _141.authentication]),o=Ft(t),a=o.split(".")[o.split(".").length-1],c=t.body[a],{password:l}=t.body;if(!c||!l)return n(new m(`Please provide both ${a} and password`,400));let d;if(_optionalChain([o, 'optionalAccess', _142 => _142.includes, 'optionalCall', _143 => _143(".")])){let y=Tt(t.body,o);if(y===void 0)return n(new m(`Invalid ${o} provided`,400));d=kt(o,y)}else d={[o]:c};let p=await e.findOne(d,t.prismaQueryOptions||{});if(!p||!await g.isCorrectPassword(l,p.password))return n(new m(`Incorrect ${a} or password`,401));let u=g.signJwtToken(p.id),f={expires:new Date(Date.now()+Number(Ut(_optionalChain([i, 'optionalAccess', _144 => _144.jwt, 'optionalAccess', _145 => _145.expiresIn])||process.env.JWT_EXPIRES_IN||le.JWT_EXPIRES_IN))),httpOnly:_optionalChain([i, 'optionalAccess', _146 => _146.jwt, 'optionalAccess', _147 => _147.cookie, 'optionalAccess', _148 => _148.httpOnly])||process.env.JWT_COOKIE_HTTP_ONLY==="true"||!0,secure:_optionalChain([i, 'optionalAccess', _149 => _149.jwt, 'optionalAccess', _150 => _150.cookie, 'optionalAccess', _151 => _151.secure])||process.env.JWT_COOKIE_SECURE==="true"||t.secure||t.headers["x-forwarded-proto"]==="https",sameSite:_optionalChain([i, 'optionalAccess', _152 => _152.jwt, 'optionalAccess', _153 => _153.cookie, 'optionalAccess', _154 => _154.sameSite])||process.env.JWT_COOKIE_SAME_SITE||(process.env.NODE_ENV==="production"?"none":"lax")};if((_optionalChain([i, 'optionalAccess', _155 => _155.login, 'optionalAccess', _156 => _156.sendAccessTokenThrough])==="response-only"||_optionalChain([i, 'optionalAccess', _157 => _157.login, 'optionalAccess', _158 => _158.sendAccessTokenThrough])==="both"||!_optionalChain([i, 'optionalAccess', _159 => _159.login, 'optionalAccess', _160 => _160.sendAccessTokenThrough]))&&(t.responseData={accessToken:u}),(_optionalChain([i, 'optionalAccess', _161 => _161.login, 'optionalAccess', _162 => _162.sendAccessTokenThrough])==="cookie-only"||_optionalChain([i, 'optionalAccess', _163 => _163.login, 'optionalAccess', _164 => _164.sendAccessTokenThrough])==="both"||!_optionalChain([i, 'optionalAccess', _165 => _165.login, 'optionalAccess', _166 => _166.sendAccessTokenThrough]))&&s.cookie("arkos_access_token",u,f),_optionalChain([r, 'optionalAccess', _167 => _167.afterLogin]))return t.additionalData={user:p},t.responseStatus=200,n();_optionalChain([i, 'optionalAccess', _168 => _168.login, 'optionalAccess', _169 => _169.sendAccessTokenThrough])==="response-only"||_optionalChain([i, 'optionalAccess', _170 => _170.login, 'optionalAccess', _171 => _171.sendAccessTokenThrough])==="both"||!_optionalChain([i, 'optionalAccess', _172 => _172.login, 'optionalAccess', _173 => _173.sendAccessTokenThrough])?s.status(200).json(t.responseData):(_optionalChain([i, 'optionalAccess', _174 => _174.login, 'optionalAccess', _175 => _175.sendAccessTokenThrough])==="cookie-only"||_optionalChain([i, 'optionalAccess', _176 => _176.login, 'optionalAccess', _177 => _177.sendAccessTokenThrough])==="both"||!_optionalChain([i, 'optionalAccess', _178 => _178.login, 'optionalAccess', _179 => _179.sendAccessTokenThrough]))&&s.status(200).send()}),signup:x(async(t,s,n)=>{let i=await e.createOne(t.body,t.prismaQueryOptions||{});if(_optionalChain([r, 'optionalAccess', _180 => _180.afterSignup]))return t.responseData={data:i},t.responseStatus=201,n();Object.keys($e).forEach(o=>{delete i[o]}),s.status(201).json({data:i})}),deleteMe:x(async(t,s,n)=>{let i=t.user.id,o=await e.updateOne({id:i},{deletedSelfAccountAt:new Date().toISOString()},t.prismaQueryOptions||{});if(_optionalChain([r, 'optionalAccess', _181 => _181.afterDeleteMe]))return t.responseData={data:o},t.responseStatus=200,n();Object.keys($e).forEach(a=>{delete o[a]}),s.status(200).json({message:"Account deleted successfully"})}),updatePassword:x(async(t,s,n)=>{let{currentPassword:i,newPassword:o}=t.body;if(!i||!o)return n(new m("currentPassword and newPassword are required",400));let a=t.user;if(!a||_optionalChain([a, 'optionalAccess', _182 => _182.isActive])===!1||_optionalChain([a, 'optionalAccess', _183 => _183.deletedSelfAccountAt]))return n(new m("User not found!",404));let c=await g.isCorrectPassword(String(i),String(a.password)),l=M(),d=_optionalChain([l, 'optionalAccess', _184 => _184.authentication]);if(!c)return n(new m("Current password is incorrect.",400));if(!g.isPasswordStrong(String(o))&&!_optionalChain([l, 'optionalAccess', _185 => _185.validation]))return n(new m(_optionalChain([d, 'optionalAccess', _186 => _186.passwordValidation, 'optionalAccess', _187 => _187.message])||"The new password must contain at least one uppercase letter, one lowercase letter, and one number",400));if(await e.updateOne({id:a.id},{password:await g.hashPassword(o),passwordChangedAt:new Date(Date.now())}),_optionalChain([r, 'optionalAccess', _188 => _188.afterUpdatePassword]))return t.additionalData={user:a},t.responseData={status:"success",message:"Password updated successfully!"},t.responseStatus=200,n();s.status(200).json({status:"success",message:"Password updated successfully!"})})}};var _expressratelimit = require('express-rate-limit'); var _expressratelimit2 = _interopRequireDefault(_expressratelimit);var It=r=>r?x(r):void 0,A=r=>r?Array.isArray(r)?r.filter(e=>!!e).map(e=>It(e)):[It(r)]:[];var se=_express.Router.call(void 0, );async function jt(r){let{middlewares:e,dtos:t,schemas:s,prismaQueryOptions:n}=await j("auth",r),i=await Nt(e),o=a=>{let c=_optionalChain([r, 'optionalAccess', _189 => _189.validation]);if(_optionalChain([c, 'optionalAccess', _190 => _190.resolver])==="class-validator")return _optionalChain([t, 'optionalAccess', _191 => _191[a]]);if(_optionalChain([c, 'optionalAccess', _192 => _192.resolver])==="zod")return _optionalChain([s, 'optionalAccess', _193 => _193[a]])};return se.get("/users/me",g.authenticate,N(n,"getMe"),...A(_optionalChain([e, 'optionalAccess', _194 => _194.beforeGetMe])),i.getMe,...A(_optionalChain([e, 'optionalAccess', _195 => _195.afterGetMe])),O).patch("/users/me",g.authenticate,q(o("updateMe")),N(n,"updateMe"),...A(_optionalChain([e, 'optionalAccess', _196 => _196.beforeUpdateMe])),i.updateMe,...A(_optionalChain([e, 'optionalAccess', _197 => _197.afterUpdateMe])),O).delete("/users/me",g.authenticate,N(n,"deleteMe"),...A(_optionalChain([e, 'optionalAccess', _198 => _198.beforeDeleteMe])),i.deleteMe,...A(_optionalChain([e, 'optionalAccess', _199 => _199.afterDeleteMe])),O),se.use("/auth",_expressratelimit2.default.call(void 0, w({windowMs:5e3,limit:10,standardHeaders:"draft-7",legacyHeaders:!1,handler:(a,c)=>{c.status(429).json({message:"Too many requests, please try again later"})}},_optionalChain([r, 'optionalAccess', _200 => _200.authentication, 'optionalAccess', _201 => _201.requestRateLimitOptions])||{}))),se.post("/auth/login",q(o("login")),N(n,"login"),...A(_optionalChain([e, 'optionalAccess', _202 => _202.beforeLogin])),i.login,...A(_optionalChain([e, 'optionalAccess', _203 => _203.afterLogin])),O),se.delete("/auth/logout",g.authenticate,...A(_optionalChain([e, 'optionalAccess', _204 => _204.beforeLogout])),i.logout,...A(_optionalChain([e, 'optionalAccess', _205 => _205.afterLogout])),O),se.post("/auth/signup",q(o("signup")),N(n,"signup"),...A(_optionalChain([e, 'optionalAccess', _206 => _206.beforeSignup])),i.signup,...A(_optionalChain([e, 'optionalAccess', _207 => _207.afterSignup])),O),se.post("/auth/update-password",g.authenticate,q(o("updatePassword")),N(n,"updatePassword"),...A(_optionalChain([e, 'optionalAccess', _208 => _208.beforeUpdatePassword])),i.updatePassword,...A(_optionalChain([e, 'optionalAccess', _209 => _209.afterUpdatePassword])),O),se}var _pluralize = require('pluralize'); var _pluralize2 = _interopRequireDefault(_pluralize);function qt(r,e,t){return r.map(async s=>{let n=$(s),i=await j(n,t),{middlewares:o,authConfigs:a,prismaQueryOptions:c,router:l,dtos:d,schemas:p}=i,u=_pluralize2.default.plural(n),f=new ye(s),y=_optionalChain([l, 'optionalAccess', _210 => _210.config])||{},h=l||{},b=(S,E)=>_optionalChain([h, 'access', _211 => _211.stack, 'optionalAccess', _212 => _212.some, 'call', _213 => _213(F=>(F.path===`/api/${S}`||F.path===`api/${S}`||F.path===`api/${S}/`||F.path===`/api/${S}/`)&&F.method.toLowerCase()===E.toLowerCase())]),R=S=>{let E=_optionalChain([t, 'optionalAccess', _214 => _214.validation]);if(_optionalChain([E, 'optionalAccess', _215 => _215.resolver])==="class-validator")return _optionalChain([d, 'optionalAccess', _216 => _216[S]]);if(_optionalChain([E, 'optionalAccess', _217 => _217.resolver])==="zod")return _optionalChain([p, 'optionalAccess', _218 => _218[S]])};_optionalChain([l, 'optionalAccess', _219 => _219.default])&&!_optionalChain([y, 'optionalAccess', _220 => _220.disable])&&e.use(`/${u}`,l.default),!T(y,"createOne")&&!b(`/${u}`,"post")&&e.post(`/${u}`,g.handleAuthenticationControl("Create",_optionalChain([a, 'optionalAccess', _221 => _221.authenticationControl])),g.handleAccessControl("Create",$(_pluralize2.default.singular(n)),_optionalChain([a, 'optionalAccess', _222 => _222.accessControl])||{}),q(R("create")),N(c,"createOne"),...A(_optionalChain([o, 'optionalAccess', _223 => _223.beforeCreateOne])),f.createOne,...A(_optionalChain([o, 'optionalAccess', _224 => _224.afterCreateOne])),O),!T(y,"findMany")&&!b(`/${u}`,"get")&&e.get(`/${u}`,g.handleAuthenticationControl("View",_optionalChain([a, 'optionalAccess', _225 => _225.authenticationControl])),g.handleAccessControl("View",$(_pluralize2.default.singular(n)),_optionalChain([a, 'optionalAccess', _226 => _226.accessControl])||{}),N(c,"findMany"),...A(_optionalChain([o, 'optionalAccess', _227 => _227.beforeFindMany])),f.findMany,...A(_optionalChain([o, 'optionalAccess', _228 => _228.afterFindMany])),O),!T(y,"createMany")&&!b(`/${u}/many`,"post")&&e.post(`/${u}/many`,g.handleAuthenticationControl("Create",_optionalChain([a, 'optionalAccess', _229 => _229.authenticationControl])),g.handleAccessControl("Create",$(_pluralize2.default.singular(n)),_optionalChain([a, 'optionalAccess', _230 => _230.accessControl])||{}),q(R("createMany")),N(c,"createMany"),...A(_optionalChain([o, 'optionalAccess', _231 => _231.beforeCreateMany])),f.createMany,...A(_optionalChain([o, 'optionalAccess', _232 => _232.afterCreateMany])),O),!T(y,"updateMany")&&!b(`/${u}/many`,"patch")&&e.patch(`/${u}/many`,g.handleAuthenticationControl("Update",_optionalChain([a, 'optionalAccess', _233 => _233.authenticationControl])),g.handleAccessControl("Update",$(_pluralize2.default.singular(n)),_optionalChain([a, 'optionalAccess', _234 => _234.accessControl])||{}),q(R("updateMany")),N(c,"updateMany"),...A(_optionalChain([o, 'optionalAccess', _235 => _235.beforeUpdateMany])),f.updateMany,...A(_optionalChain([o, 'optionalAccess', _236 => _236.afterUpdateMany])),O),!T(y,"deleteMany")&&!b(`/${u}/many`,"delete")&&e.delete(`/${u}/many`,g.handleAuthenticationControl("Delete",_optionalChain([a, 'optionalAccess', _237 => _237.authenticationControl])),g.handleAccessControl("Delete",$(_pluralize2.default.singular(n)),_optionalChain([a, 'optionalAccess', _238 => _238.accessControl])||{}),q(R("deleteMany")),N(c,"deleteMany"),...A(_optionalChain([o, 'optionalAccess', _239 => _239.beforeDeleteMany])),f.deleteMany,...A(_optionalChain([o, 'optionalAccess', _240 => _240.afterDeleteMany])),O),!T(y,"findOne")&&!b(`/${u}/:id`,"get")&&e.get(`/${u}/:id`,g.handleAuthenticationControl("View",_optionalChain([a, 'optionalAccess', _241 => _241.authenticationControl])),g.handleAccessControl("View",$(_pluralize2.default.singular(n)),_optionalChain([a, 'optionalAccess', _242 => _242.accessControl])||{}),q(R("findOne")),N(c,"findOne"),...A(_optionalChain([o, 'optionalAccess', _243 => _243.beforeFindOne])),f.findOne,...A(_optionalChain([o, 'optionalAccess', _244 => _244.afterFindOne])),O),!T(y,"updateOne")&&!b(`/${u}/:id`,"patch")&&e.patch(`/${u}/:id`,g.handleAuthenticationControl("Update",_optionalChain([a, 'optionalAccess', _245 => _245.authenticationControl])),g.handleAccessControl("Update",$(_pluralize2.default.singular(n)),_optionalChain([a, 'optionalAccess', _246 => _246.accessControl])||{}),q(R("update")),N(c,"updateOne"),...A(_optionalChain([o, 'optionalAccess', _247 => _247.beforeUpdateOne])),f.updateOne,...A(_optionalChain([o, 'optionalAccess', _248 => _248.afterUpdateOne])),O),!T(y,"deleteOne")&&!b(`/${u}/:id`,"delete")&&e.delete(`/${u}/:id`,g.handleAuthenticationControl("Delete",_optionalChain([a, 'optionalAccess', _249 => _249.authenticationControl])),g.handleAccessControl("Delete",$(_pluralize2.default.singular(n)),_optionalChain([a, 'optionalAccess', _250 => _250.accessControl])||{}),q(R("delete")),N(c,"deleteOne"),...A(_optionalChain([o, 'optionalAccess', _251 => _251.beforeDeleteOne])),f.deleteOne,...A(_optionalChain([o, 'optionalAccess', _252 => _252.afterDeleteOne])),O)})}function T(r,e){return _optionalChain([r, 'optionalAccess', _253 => _253.disable])?r.disable===!0?!0:typeof r.disable=="object"?r.disable[e]===!0:!1:!1}async function _t(r){let e=_express.Router.call(void 0, );return await Promise.all(qt(D(),e,r)),e}function Wt(){let r=_express.Router.call(void 0, );return r.get("/available-routes",_optionalChain([g, 'optionalAccess', _254 => _254.authenticate]),Vt),r.get("/available-resources",_optionalChain([g, 'optionalAccess', _255 => _255.authenticate]),Bt),r}function Jt(){return new m("Invalid token. Please log in again!",401)}function Qt(){return new m("Your token has expired, Please log again!",401)}function Ht(r){let e=_optionalChain([r, 'optionalAccess', _256 => _256.message, 'access', _257 => _257.split, 'call', _258 => _258(`
|
|
12
|
+
`), 'access', _259 => _259[_optionalChain([r, 'optionalAccess', _260 => _260.message, 'access', _261 => _261.split, 'call', _262 => _262(`
|
|
13
|
+
`), 'access', _263 => _263.length])-1]]);return new m(e,400)}function zt(r){let e="Authentication failed against the database server. Please check your credentials.";return new m(e,401)}function Gt(r){let e="The database server is not reachable. Verify your connection string or ensure the server is online.";return new m(e,503)}function Kt(r){let e="Connection to the database timed out. Please check server performance or network connectivity.";return new m(e,504)}function Xt(r){let e="The specified database does not exist on the server.";return new m(e,404)}function Yt(r){let e=`The value for the field "${_optionalChain([r, 'optionalAccess', _264 => _264.meta, 'optionalAccess', _265 => _265.field_name])}" is too large. Please provide a smaller value.`;return new m(e,400)}function Zt(r){let e="No record found for the given query. Ensure the query parameters are correct.";return new m(e,404)}function er(r){let t=`Duplicate value detected for the unique field(s): ${_optionalChain([r, 'optionalAccess', _266 => _266.meta, 'optionalAccess', _267 => _267.target])||"unknown field"}. Please use a different value.`;return new m(t,409)}function tr(r){let e="Foreign key constraint violation. Ensure that the referenced record exists.";return new m(e,400)}function rr(r){let t=`A database constraint "${_optionalChain([r, 'optionalAccess', _268 => _268.meta, 'optionalAccess', _269 => _269.constraint])||"unknown constraint"}" failed. Please review your input data.`;return new m(t,400)}function sr(r){let e="Failed to create the database schema. Verify the schema definition and try again.";return new m(e,500)}function nr(r){let t=`The migration "${_optionalChain([r, 'optionalAccess', _270 => _270.meta, 'optionalAccess', _271 => _271.migration])||"unknown migration"}" has already been applied to the database.`;return new m(t,409)}function ir(r){let t=`The migration script "${_optionalChain([r, 'optionalAccess', _272 => _272.meta, 'optionalAccess', _273 => _273.migration])||"unknown migration"}" failed. Review the script and resolve any issues.`;return new m(t,500)}function or(r){let e="Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.";return new m(e,400)}function ar(r){let e="Network error: Unable to connect to the database or internet. Please check your network connection.";return new m(e,500)}function cr(r){let e=_optionalChain([r, 'optionalAccess', _274 => _274.meta, 'optionalAccess', _275 => _275.cause])||"Operation could not be completed as the required record was not found";return new m(e,404,r.meta||{},"PrismaRecordNotFound")}function Je(r,e,t,s){if(console.error("[\x1B[31mERROR\x1B[0m]:",r),r.statusCode=r.statusCode||500,r.status=r.status||"error",process.env.NODE_ENV!=="production"){As(r,e,t);return}let n={...r,message:r.message};r.name==="JsonWebTokenError"&&(n=Jt()),r.name==="TokenExpiredError"&&(n=Qt()),r.name==="PrismaClientValidationError"&&(n=Ht(r)),r.code==="P1000"&&(n=zt(r)),r.code==="P1001"&&(n=Gt(r)),r.code==="P1002"&&(n=Kt(r)),r.code==="P1003"&&(n=Xt(r)),r.code==="P2000"&&(n=Yt(r)),r.code==="P2001"&&(n=Zt(r)),r.code==="P2002"&&(n=er(r)),r.code==="P2003"&&(n=tr(r)),r.code==="P2004"&&(n=rr(r)),r.code==="P2025"&&(n=cr(r)),r.code==="P3000"&&(n=sr(r)),r.code==="P3001"&&(n=nr(r)),r.code==="P3002"&&(n=ir(r)),r.code==="P3003"&&(n=or(r)),r.name==="NetworkError"&&(n=ar(r)),n.isOperational||(n=new m("Something went wrong!",500)),xs(n,e,t)}function As(r,e,t){e.originalUrl.startsWith("/api")?t.status(r.statusCode).json({...r,message:r.message.split(`
|
|
14
|
+
`)[r.message.split(`
|
|
15
|
+
`).length-1],stack:_optionalChain([r, 'access', _276 => _276.stack, 'optionalAccess', _277 => _277.split, 'call', _278 => _278(`
|
|
16
|
+
`)])}):t.status(r.statusCode).json({title:"Something went wrong!",message:r.message})}function xs(r,e,t){if(e.originalUrl.startsWith("/api")){r.isOperational?t.status(r.statusCode).json({status:r.status,message:r.message,meta:r.meta||{},code:r.code||"unknown"}):t.status(500).json({status:"error",message:"Something went wrong!"});return}if(r.isOperational){t.status(r.statusCode).json({title:"Something went wrong!",message:r.message});return}t.status(r.statusCode).json({title:"Something went wrong!",message:"Please try again later."})}process.on("SIGTERM",()=>{process.env.NODE_ENV!=="production"&&process.env.NODE_ENV!=="staging"?process.exit():(console.error("SIGTERM RECEIVED in Production. Shutting down gracefully!"),de.close(()=>{console.error("Process terminated!!!"),process.exit()}))});var _compression = require('compression'); var _compression2 = _interopRequireDefault(_compression);var _multer = require('multer'); var _multer2 = _interopRequireDefault(_multer);var _sharp = require('sharp'); var _sharp2 = _interopRequireDefault(_sharp);var _mimetype = require('mimetype'); var _mimetype2 = _interopRequireDefault(_mimetype);function lr(r,e,t){let{fileUpload:s}=M();r.url=r.url.replace(_optionalChain([s, 'optionalAccess', _279 => _279.baseRoute])+"/"||"/api/uploads/","/"),r.url=r.url.replace(_optionalChain([s, 'optionalAccess', _280 => _280.baseRoute])||"/api/uploads/","/"),t()}function dr(r){let{fileUpload:e}=M(),s=`${r.headers["x-forwarded-proto"]==="https"?"https":"http"}://${_optionalChain([r, 'access', _281 => _281.get, 'optionalCall', _282 => _282("host")])}`,n=_optionalChain([e, 'optionalAccess', _283 => _283.baseRoute])||"/api/uploads";return{baseURL:s,baseRoute:n}}var ze=(r,e)=>{let{fileUpload:t}=M(),s=_optionalChain([t, 'optionalAccess', _284 => _284.baseUploadDir])||"/uploads";return s.startsWith("..")?_path2.default.join(e,_path2.default.basename(r)):Me(r.replace(`${s}/`,"").replace(`/${s}/`,"").replace(`/${s}`,"").replace(`${s}`,""))},Z=async(r,e)=>{let{baseURL:t,baseRoute:s}=dr(r),n=ze(e,r.params.fileType);return`${t}${s==="/"?"":s}/${n}`},ee=async(r,e,t)=>{let{baseURL:s,baseRoute:n}=dr(r),i=_path2.default.extname(e).toLowerCase(),o=i.replace(".",""),a=t.format||o;if(!_optionalChain([_mimetype2.default, 'access', _285 => _285.lookup, 'call', _286 => _286(i), 'optionalAccess', _287 => _287.includes, 'optionalCall', _288 => _288("image")])){let d=ze(e,r.params.fileType);return`${s}${n}/${d}`}let c=`${_path2.default.basename(e,i)}_${Date.now()}${i}`,l=_path2.default.join(_path2.default.dirname(e),c);try{let d=_sharp2.default.call(void 0, e),p=await d.metadata();if(t.resizeTo&&p.width&&p.height){let y=t.resizeTo/Math.min(p.width,p.height),h=Math.round(p.width*y),b=Math.round(p.height*y);d=d.resize(h,b)}else(t.width||t.height)&&(d=d.resize(t.width||null,t.height||null,{fit:"inside"}));a==="webp"?d=d.toFormat("webp"):(a==="jpeg"||a==="jpg")&&(d=d.toFormat("jpeg")),await d.toFile(l),await _util.promisify.call(void 0, _fs2.default.rename)(l,e);let u=ze(e,_optionalChain([r, 'optionalAccess', _289 => _289.params, 'access', _290 => _290.fileType]));return`${s}${n}/${u}`}catch(d){try{await _util.promisify.call(void 0, _fs2.default.stat)(l),await _util.promisify.call(void 0, _fs2.default.unlink)(l)}catch (e4){}throw d}};function ve(r){return r?r.split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "):""}function Rs(r){return r.startsWith("/")?r.substring(1):r}function $s(r){return r.endsWith("/")?r.substring(0,r.length-1):r}function Ge(r){return $s(Rs(r))}var ue=class{constructor(e,t=1024*1024*5,s=/.*/,n=30){this.fileFilter=(e,t,s)=>{let n=this.allowedFileTypes.test(_path2.default.extname(t.originalname).toLowerCase());this.allowedFileTypes.test(t.mimetype)&&n?s(null,!0):s(new m("Invalid file type",400))};e=e.startsWith("/")?e.substring(1):e,e=e.endsWith("/")?e.slice(0,-1):e,this.uploadDir=_path2.default.resolve(process.cwd(),`${e}/`),this.fileSizeLimit=t,this.allowedFileTypes=s,this.maxCount=n,_fs2.default.existsSync(this.uploadDir)||_fs2.default.mkdirSync(this.uploadDir,{recursive:!0}),this.storage=_multer2.default.diskStorage({destination:(i,o,a)=>{a(null,this.uploadDir)},filename:(i,o,a)=>{let c=Date.now()+"-"+Math.round(Math.random()*1e9);a(null,`${c}${_path2.default.extname(o.originalname)}`)}})}getUpload(){return _multer2.default.call(void 0, {storage:this.storage,fileFilter:this.fileFilter,limits:{fileSize:this.fileSizeLimit}})}handleSingleUpload(e){return(t,s,n)=>{this.getUpload().single(this.getFieldName())(t,s,async o=>{if(o instanceof _multer2.default.MulterError)return n(o);if(o)return n(o);if(e){let{fileUpload:a}=M(),c=_path2.default.resolve(process.cwd(),Ge(_optionalChain([a, 'optionalAccess', _291 => _291.baseUploadDir])),Ge(e));try{await _util.promisify.call(void 0, _fs2.default.stat)(c)&&await _util.promisify.call(void 0, _fs2.default.unlink)(c)}catch(l){console.error(l)}}n()})}}handleMultipleUpload(){return(e,t,s)=>{this.getUpload().array(this.getFieldName(),this.maxCount)(e,t,i=>{if(i instanceof _multer2.default.MulterError)return s(i);if(i)return s(i);s()})}}handleDeleteSingleFile(e){return async(t,s,n)=>{let i=_path2.default.join(e);try{await _util.promisify.call(void 0, _fs2.default.stat)(i)&&await _util.promisify.call(void 0, _fs2.default.unlink)(i)}catch(o){console.error(o)}n()}}async deleteFileByUrl(e){try{let{fileUpload:t}=M(),s=_optionalChain([t, 'optionalAccess', _292 => _292.baseRoute])||"/api/uploads",n;e.startsWith("http")?n=new URL(e).pathname:n=e;let i=n.indexOf(s);if(i===-1)throw new m("Invalid file URL: base route not found",400);let o=n.substring(i+s.length),a=o.startsWith("/")?o.substring(1):o,c=["images","videos","documents","files"],l=null,d=null;for(let b of c){let R=a.indexOf(b+"/");if(R!==-1){l=b,d=a.substring(R+b.length+1);break}}if(!l||!d)throw new m("Unable to determine file type or file name from URL",400);let{documentUploadService:p,fileUploadService:u,imageUploadService:f,videoUploadService:y}=me(),h;switch(l){case"images":h=_path2.default.join(f.uploadDir,d);break;case"videos":h=_path2.default.join(y.uploadDir,d);break;case"documents":h=_path2.default.join(p.uploadDir,d);break;case"files":h=_path2.default.join(u.uploadDir,d);break;default:throw new m(`Unsupported file type: ${l}`,400)}return await _util.promisify.call(void 0, _fs2.default.stat)(h),await _util.promisify.call(void 0, _fs2.default.unlink)(h),!0}catch(t){throw t instanceof m?t:t.code==="ENOENT"?new m("File not found",404):new m(`Failed to delete file: ${t.message}`,500)}}getFieldName(){let e="files";return(this.uploadDir.endsWith("images")||this.uploadDir.endsWith("images/"))&&(e="images"),(this.uploadDir.endsWith("videos")||this.uploadDir.endsWith("videos/"))&&(e="videos"),(this.uploadDir.endsWith("documents")||this.uploadDir.endsWith("documents/"))&&(e="documents"),(this.uploadDir.endsWith("files")||this.uploadDir.endsWith("files/"))&&(e="files"),e}async upload(e,t,s={}){let{fileUpload:n}=M(),i=_optionalChain([n, 'optionalAccess', _293 => _293.baseRoute])||"/api/uploads";return new Promise((o,a)=>{((Array.isArray(e.query.multiple)?e.query.multiple[0]=="true":e.query.multiple=="true")?this.getUpload().array(this.getFieldName(),this.maxCount):this.getUpload().single(this.getFieldName()))(e,t,async d=>{if(d)return a(d);try{let u=`${_optionalChain([e, 'access', _294 => _294.get, 'call', _295 => _295("host"), 'optionalAccess', _296 => _296.includes, 'optionalCall', _297 => _297("localhost")])?"http":"https"}://${e.get("host")}`,f=this.uploadDir.split("/"),y=(this.uploadDir.endsWith("/")?f[f.length-2]:f[f.length-1])||"files",h;if(e.files&&Array.isArray(e.files)&&e.files.length>0)_optionalChain([this, 'access', _298 => _298.uploadDir, 'optionalAccess', _299 => _299.includes, 'optionalCall', _300 => _300("/images")])?h=await Promise.all(e.files.map(R=>ee(e,R.path,s))):h=await Promise.all(e.files.map(R=>Z(e,R.path))),h=h.filter(R=>R!==null);else if(e.file)_optionalChain([this, 'access', _301 => _301.uploadDir, 'optionalAccess', _302 => _302.includes, 'optionalCall', _303 => _303("/images")])?h=await ee(e,e.file.path,s):h=await Z(e,e.file.path);else return a(new m("No file uploaded",400));o(h)}catch(p){a(p)}})})}async deleteFileByName(e,t){try{if(!t)throw new m("File type parameter is required",400);let s=["images","videos","documents","files"];if(!s.includes(t))throw new m(`Invalid file type: ${t}. Must be one of: ${s.join(", ")}`,400);let{documentUploadService:n,fileUploadService:i,imageUploadService:o,videoUploadService:a}=me(),c;switch(t){case"images":c=o;break;case"videos":c=a;break;case"documents":c=n;break;case"files":c=i;break;default:throw new m(`Unsupported file type: ${t}`,400)}let l=_path2.default.join(c.uploadDir,e);return await _util.promisify.call(void 0, _fs2.default.stat)(l),await _util.promisify.call(void 0, _fs2.default.unlink)(l),!0}catch(s){throw s instanceof m?s:s.code==="ENOENT"?new m("File not found",404):new m(`Failed to delete file: ${s.message}`,500)}}},me=()=>{let{fileUpload:r}=M(),e=_optionalChain([r, 'optionalAccess', _304 => _304.baseUploadDir])||"/uploads",t={images:{maxCount:30,maxSize:1024*1024*15,supportedFilesRegex:/jpeg|jpg|png|gif|webp|svg|bmp|tiff|heif|heic|ico|jfif|raw|cr2|nef|orf|sr2|arw|dng|pef|raf|rw2|psd|ai|eps|xcf|jxr|wdp|hdp|jp2|j2k|jpf|jpx|jpm|mj2|avif/},videos:{maxCount:10,maxSize:1024*1024*5096,supportedFilesRegex:/mp4|avi|mov|mkv|flv|wmv|webm|mpg|mpeg|3gp|m4v|ts|rm|rmvb|vob|ogv|dv|qt|asf|m2ts|mts|divx|f4v|swf|mxf|roq|nsv|mvb|svi|mpe|m2v|mp2|mpv|h264|h265|hevc/},documents:{maxCount:30,maxSize:1024*1024*50,supportedFilesRegex:/pdf|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odg|odp|txt|rtf|csv|epub|md|tex|pages|numbers|key|xml|json|yaml|yml|ini|cfg|conf|log|html|htm|xhtml|djvu|mobi|azw|azw3|fb2|lit|ps|wpd|wps|dot|dotx|xlt|xltx|pot|potx|oft|one|onetoc2|opf|oxps|hwp/},files:{maxCount:10,maxSize:1024*1024*5096,supportedFilesRegex:/.*/}},s=_optionalChain([r, 'optionalAccess', _305 => _305.restrictions])?w(t,r.restrictions):t,n=new ue(`${e}/images`,s.images.maxSize,s.images.supportedFilesRegex,s.images.maxCount),i=new ue(`${e}/videos`,s.videos.maxSize,s.videos.supportedFilesRegex,s.videos.maxCount),o=new ue(`${e}/documents`,s.documents.maxSize,s.documents.supportedFilesRegex,s.documents.maxCount),a=new ue(`${e}/files`,s.files.maxSize,s.files.supportedFilesRegex,s.files.maxCount);return{imageUploadService:n,videoUploadService:i,documentUploadService:o,fileUploadService:a}};var Xe=class{constructor(){this.uploadFile=x(async(e,t,s)=>{this.middlewares=_optionalChain([L, 'call', _306 => _306("file-upload"), 'optionalAccess', _307 => _307.middlewares])||{};let{fileType:n}=e.params,{format:i,width:o,height:a,resizeTo:c}=e.query,l={format:i,width:o,height:a,resizeTo:c},{documentUploadService:d,fileUploadService:p,imageUploadService:u,videoUploadService:f}=me(),{fileUpload:y}=M(),h=_optionalChain([y, 'optionalAccess', _308 => _308.baseUploadDir])||"/uploads",b=_path2.default.resolve(process.cwd(),h,n);try{await xe(b)}catch (e5){await Ie(b,{recursive:!0})}let R;switch(n){case"images":R=u;break;case"videos":R=f;break;case"documents":R=d;break;case"files":R=p;break;default:return s(new m("Invalid file type",400))}R.handleMultipleUpload()(e,t,async S=>{if(S)return s(S);let E;if(e.files&&Array.isArray(e.files)&&e.files.length>0)n==="images"?E=await Promise.all(e.files.map(G=>ee(e,G.path,l))):E=await Promise.all(e.files.map(G=>Z(e,G.path))),E=E.filter(G=>G!==null);else if(e.file)n==="images"?E=await ee(e,e.file.path,l):E=await Z(e,e.file.path);else return s(new m("No file uploaded",400));let F={success:!0,data:E,message:Array.isArray(E)?`${E.length} files uploaded successfully`:"File uploaded successfully"};if(_optionalChain([this, 'access', _309 => _309.middlewares, 'optionalAccess', _310 => _310.afterUploadFile]))return e.responseData=F,e.responseStatus=200,s();t.status(200).json(F)})});this.deleteFile=x(async(e,t,s)=>{this.middlewares=_optionalChain([L, 'call', _311 => _311("file-upload"), 'optionalAccess', _312 => _312.middlewares])||{};let{fileType:n,fileName:i}=e.params,{documentUploadService:o,fileUploadService:a,imageUploadService:c,videoUploadService:l}=me(),d;switch(n){case"images":d=c;break;case"videos":d=l;break;case"documents":d=o;break;case"files":d=a;break;default:return s(new m("Invalid file type",400))}try{let{fileUpload:p}=M(),u=_optionalChain([p, 'optionalAccess', _313 => _313.baseRoute])||"/api/uploads";if(new RegExp(`${u}/${n}/${i}`).test(e.originalUrl)){let h=`${e.protocol}://${e.get("host")}${e.originalUrl}`;await d.deleteFileByUrl(h)}else await d.deleteFileByName(i,n);if(this.middlewares.afterDeleteFile)return e.responseStatus=204,s();t.status(204).json()}catch(p){return p instanceof m?s(p):s(new m("File not found",404))}});this.updateFile=x(async(e,t,s)=>{this.middlewares=_optionalChain([L, 'call', _314 => _314("file-upload"), 'optionalAccess', _315 => _315.middlewares])||{};let{fileType:n,fileName:i}=e.params,{format:o,width:a,height:c,resizeTo:l}=e.query,d={format:o,width:a,height:c,resizeTo:l},{documentUploadService:p,fileUploadService:u,imageUploadService:f,videoUploadService:y}=me(),{fileUpload:h}=M(),b=_optionalChain([h, 'optionalAccess', _316 => _316.baseUploadDir])||"/uploads",R=_path2.default.resolve(process.cwd(),b,n);try{await xe(R)}catch (e6){await Ie(R,{recursive:!0})}let S;switch(n){case"images":S=f;break;case"videos":S=y;break;case"documents":S=p;break;case"files":S=u;break;default:return s(new m("Invalid file type",400))}S.handleMultipleUpload()(e,t,async E=>{if(E)return s(E);if(!e.file&&(!e.files||!Array.isArray(e.files)||e.files.length===0))return s(new m("No new file uploaded",400));if(i&&i.trim()!=="")try{let J=_optionalChain([h, 'optionalAccess', _317 => _317.baseRoute])||"/api/uploads";if(new RegExp(`${J}/${n}/${i}`).test(e.originalUrl)){let Ir=`${e.protocol}://${e.get("host")}${e.originalUrl}`;await S.deleteFileByUrl(Ir)}else await S.deleteFileByName(i,n)}catch(J){console.warn(`Could not delete old file: ${i}`,J)}let F;e.files&&Array.isArray(e.files)&&e.files.length>0?(n==="images"?F=await Promise.all(e.files.map(J=>ee(e,J.path,d))):F=await Promise.all(e.files.map(J=>Z(e,J.path))),F=F.filter(J=>J!==null)):e.file&&(n==="images"?F=await ee(e,e.file.path,d):F=await Z(e,e.file.path));let G={success:!0,data:F,message:Array.isArray(F)?i&&i.trim()!==""?`File updated successfully. ${F.length} new files uploaded`:`${F.length} files uploaded successfully`:i&&i.trim()!==""?"File updated successfully":"File uploaded successfully"};if(this.middlewares.afterUpdateFile)return e.responseData=G,e.responseStatus=200,s();t.status(200).json(G)})});this.streamFile=x(async(e,t,s)=>{let{fileName:n,fileType:i}=e.params,o=_path2.default.join(".","uploads",i,n);try{await xe(o)}catch (e7){throw new m("File not found",404)}let c=(await lt(o)).size,l=e.headers.range;if(l){let[d,p]=l.replace(/bytes=/,"").split("-"),u=parseInt(d,10)||0,f=p?parseInt(p,10):c-1;if(u>=c||f>=c){t.status(416).json({error:"Range Not Satisfiable"});return}t.writeHead(206,{"Content-Range":`bytes ${u}-${f}/${c}`,"Accept-Ranges":"bytes","Content-Length":f-u+1,"Content-Type":"application/octet-stream","Content-Disposition":`inline; filename="${n}"`}),_fs2.default.createReadStream(o,{start:u,end:f}).pipe(t)}else t.writeHead(200,{"Content-Length":c,"Content-Type":"application/octet-stream","Content-Disposition":`inline; filename="${n}"`}),_fs2.default.createReadStream(o).pipe(t)})}},vs=new Xe,Se=vs;var we=_express.Router.call(void 0, );async function ur(r){let{fileUpload:e}=r,t=await j("file-upload",r),{middlewares:s={},authConfigs:n={}}={};t&&({middlewares:s={},authConfigs:n={}}=t);let i=_optionalChain([e, 'optionalAccess', _318 => _318.baseRoute])||"/api/uploads/";return i.startsWith("/")||(i="/"+i),i.endsWith("/")||(i=i+"/"),we.get(`${i}*`,g.handleAuthenticationControl("View",n.authenticationControl),g.handleAccessControl("View","file-upload",n.accessControl),...A(_optionalChain([s, 'optionalAccess', _319 => _319.beforeFindFile])),lr,_express2.default.static(_path2.default.resolve(process.cwd(),_optionalChain([e, 'optionalAccess', _320 => _320.baseUploadDir])||"uploads"),w({maxAge:"1y",etag:!0,lastModified:!0,dotfiles:"ignore",fallthrough:!0,index:!1,cacheControl:!0},_optionalChain([e, 'optionalAccess', _321 => _321.expressStaticOptions])||{}))),we.post(`${i}:fileType`,g.handleAuthenticationControl("Create",n.authenticationControl),g.handleAccessControl("Create","file-upload",n.accessControl),...A(_optionalChain([s, 'optionalAccess', _322 => _322.beforeUploadFile])),Se.uploadFile,...A(_optionalChain([s, 'optionalAccess', _323 => _323.afterUploadFile])),O),we.patch(`${i}:fileType/:fileName`,g.handleAuthenticationControl("Update",n.authenticationControl),g.handleAccessControl("Update","file-upload",n.accessControl),...A(_optionalChain([s, 'optionalAccess', _324 => _324.beforeUpdateFile])),Se.updateFile,...A(_optionalChain([s, 'optionalAccess', _325 => _325.afterUpdateFile])),O),we.delete(`${i}:fileType/:fileName`,g.handleAuthenticationControl("Delete",n.authenticationControl),g.handleAccessControl("Delete","file-upload",n.accessControl),...A(_optionalChain([s, 'optionalAccess', _326 => _326.beforeDeleteFile])),Se.deleteFile,...A(_optionalChain([s, 'optionalAccess', _327 => _327.afterDeleteFile])),O),we}var Ye=(r,e)=>{switch(typeof r){case"string":return r===""?"":e.parseNull&&r==="null"?null:e.parseUndefined&&r==="undefined"?void 0:e.parseBoolean&&(r==="true"||r==="false")?r==="true":e.parseNumber&&!isNaN(Number(r))?Number(r):r;case"object":if(Array.isArray(r))return r.map(t=>Ye(t,e));{let t=r;return Object.keys(t).map(s=>t[s]=Ye(r[s],e)),t}default:return r}},mr=r=>(e,t,s)=>{e.query=Ye(e.query,r),s()};var _expressapireference = require('@scalar/express-api-reference'); var vr = _interopRequireWildcard(_expressapireference);var _swaggerjsdoc = require('swagger-jsdoc'); var _swaggerjsdoc2 = _interopRequireDefault(_swaggerjsdoc);function fr(){let r={};return r["/api/available-resources"]={get:{tags:["System"],summary:"Get available resources",description:"Returns a comprehensive list of all available API resource endpoints",operationId:"getAvailableResources",responses:{200:{description:"List of available resources retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{data:{type:"array",items:{type:"string"},description:"Array of available resource endpoints"}}}}}}}}},r["/api/available-routes"]={get:{tags:["System"],summary:"Get available routes",description:"Returns a comprehensive list of all registered API routes and their methods",operationId:"getAvailableRoutes",responses:{200:{description:"List of available routes retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{routes:{type:"array",items:{type:"string"},description:"Array of available API routes"}}}}}}}}},r}async function hr(r){let e={},t=async l=>{let d=_optionalChain([r, 'access', _328 => _328.swagger, 'optionalAccess', _329 => _329.mode]),p=_optionalChain([r, 'access', _330 => _330.swagger, 'optionalAccess', _331 => _331.strict]);return d&&(p||await k(l,"user",r))?d:"prisma"};if(!_optionalChain([r, 'access', _332 => _332.swagger, 'optionalAccess', _333 => _333.mode]))return e;let s=await t("login");e["/api/auth/login"]={post:{tags:["Authentication"],summary:"Login to the system",description:"Authenticates a user and returns an access token",operationId:"login",requestBody:{description:"User credentials",required:!0,content:{"application/json":{schema:{$ref:v("Login",s)}}}},responses:{200:{description:"Login successful",content:{"application/json":{schema:{type:"object",properties:{accessToken:{type:"string",description:"JWT access token"}}}}}},400:{description:"Invalid input data"},401:{description:"Invalid credentials"}}}},e["/api/auth/logout"]={delete:{tags:["Authentication"],summary:"Logout from the system",description:"Invalidates the current user's JWT token",operationId:"logout",security:[{BearerAuth:[]}],responses:{204:{description:"Logout successful"},401:{description:"Authentication required"}}}};let n=await t("signup"),i=await t("user");e["/api/auth/signup"]={post:{tags:["Authentication"],summary:"Register a new user",description:"Creates a new user account",operationId:"signup",requestBody:{description:"User registration data",required:!0,content:{"application/json":{schema:{$ref:v("Signup",n)}}}},responses:{201:{description:"User created successfully",content:{"application/json":{schema:{$ref:v("User",i)}}}},400:{description:"Invalid input data"},409:{description:"User already exists"}}}};let o=await t("updatePassword");e["/api/auth/update-password"]={post:{tags:["Authentication"],summary:"Update user password",description:"Changes the password for the authenticated user",operationId:"updatePassword",security:[{BearerAuth:[]}],requestBody:{description:"Current and new password",required:!0,content:{"application/json":{schema:{$ref:v("UpdatePassword",o)}}}},responses:{200:{description:"Password updated successfully",content:{"application/json":{schema:{type:"object",properties:{status:{type:"string",example:"success"},message:{type:"string",example:"Password updated successfully!"}}}}}},400:{description:"Invalid input data or current password incorrect"},401:{description:"Authentication required"}}}};let a=await t("getMe");e["/api/users/me"]={get:{tags:["Authentication"],summary:"Get current user information",description:"Retrieves information about the currently authenticated user",operationId:"getMe",security:[{BearerAuth:[]}],responses:{200:{description:"User information retrieved successfully",content:{"application/json":{schema:{$ref:v("GetMe",a)}}}},401:{description:"Authentication required"}}}};let c=await t("updateMe");return e["/api/users/me"]||(e["/api/users/me"]={}),e["/api/users/me"].patch={tags:["Authentication"],summary:"Update current user information",description:"Updates information for the currently authenticated user",operationId:"updateMe",security:[{BearerAuth:[]}],requestBody:{description:"User data to update",required:!0,content:{"application/json":{schema:{$ref:v("UpdateMe",c)}}}},responses:{200:{description:"User updated successfully",content:{"application/json":{schema:{$ref:v("User",i)}}}},400:{description:"Invalid input data"},401:{description:"Authentication required"}}},e["/api/users/me"]||(e["/api/users/me"]={}),e["/api/users/me"].delete={tags:["Authentication"],summary:"Delete current user account",description:"Marks the current user's account as deleted",operationId:"deleteMe",security:[{BearerAuth:[]}],responses:{200:{description:"Account deleted successfully",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",example:"Account deleted successfully"}}}}}},401:{description:"Authentication required"}}},e}var _zodtojsonschema = require('zod-to-json-schema'); var _zodtojsonschema2 = _interopRequireDefault(_zodtojsonschema);async function gr(){let r=[...D(),"auth"],e={};return r.forEach(t=>{let s=L(t);_optionalChain([s, 'optionalAccess', _334 => _334.schemas])&&Object.entries(s.schemas).forEach(([n,i])=>{if(i)try{let o=_zodtojsonschema2.default.call(void 0, i),a=Ce(n,t,"Schema");e[a]=o}catch(o){console.warn(`Failed to generate schema for ${n} ${t}:`,o)}})}),e}var _classvalidatorjsonschema = require('class-validator-jsonschema');var _classvalidator = require('class-validator');async function yr(){let r=D(),e={},{defaultMetadataStorage:t}=await Q("class-transformer/cjs/storage.js"),s=_classvalidatorjsonschema.validationMetadatasToSchemas.call(void 0, {classValidatorMetadataStorage:_classvalidator.getMetadataStorage.call(void 0, ),classTransformerMetadataStorage:t,refPointerPrefix:"#/components/schemas/"});return Object.entries(s).forEach(([n,i])=>{e[n]=i}),r.forEach(n=>{let i=L(n);_optionalChain([i, 'optionalAccess', _335 => _335.dtos])&&Object.entries(i.dtos).forEach(([o,a])=>{if(a)try{let c=Ce(o,n,"Dto");e[c]=s[a.name]||{},e[a.name]&&delete e[a.name]}catch(c){console.warn(`Failed to generate schema for ${o} ${n}:`,c)}})}),e}var Ze=class{constructor(){this.enums=[];this.models=[]}parse(){return this.enums=this.extractEnums(),this.models=this.extractModels(),{models:this.models,enums:this.enums}}extractEnums(){let e=[],s=Re().match(/enum\s+\w+\s*\{[^}]*\}/g)||[];for(let n of s){let i=this.parseEnumBlock(n);i&&e.push(i)}return e}parseEnumBlock(e){let t=e.match(/enum\s+(\w+)/);if(!t)return null;let s=t[1],n=e.split(`
|
|
17
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("enum")&&!i.startsWith("{")&&!i.startsWith("}")).map(i=>i.replace(/,$/,""));return{name:s,values:n}}extractModels(){let e=[],t=this.extractModelBlocks();for(let s of t){let n=this.parseModelBlock(s);n&&e.push(n)}return e}extractModelBlocks(){let e=/model\s+\w+\s*\{[^}]*\}/g;return Re().match(e)||[]}parseModelBlock(e){let t=e.match(/model\s+(\w+)/);if(!t)return null;let s=t[1],n=this.parseFields(e),i=e.match(/@@map\s*\(\s*"([^"]+)"\s*\)/),o=i?i[1]:void 0;return{name:s,fields:n,mapName:o}}parseFields(e){let t=[],s=e.split(`
|
|
18
|
+
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("model")&&!n.startsWith("{")&&!n.startsWith("}"));for(let n of s){if(n.startsWith("//")||n.startsWith("@@"))continue;let i=this.parseFieldLine(n);i&&t.push(i)}return t}parseFieldLine(e){let t=e.match(/^(\w+)\s+(\w+(?:\[\])?)\??\s*(.*)/);if(!t)return null;let[,s,n,i]=t,o=n.endsWith("[]"),a=o?n.slice(0,-2):n,c=e.includes("?"),l=i.split(/\s+/).filter(b=>b.startsWith("@")),d,p=i.match(/@default\(([^)]+)\)/);p&&(d=this.parseDefaultValue(p[1]));let u="",f=i.match(/@relation\([^)]*fields:\s*\[([^\]]+)\]/);f&&(u=f[1].trim().replace(/['"]/g,""));let y=l.some(b=>b.startsWith("@id")),h=l.some(b=>b.startsWith("@unique"));return{name:s,type:a,isOptional:c,isArray:o,connectionField:u,defaultValue:d,isId:y,isUnique:h,attributes:l}}parseDefaultValue(e){if(e=e.trim(),e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);if(e==="true")return!0;if(e==="false")return!1;if(/^\d+$/.test(e))return parseInt(e,10);if(/^\d+\.\d+$/.test(e))return parseFloat(e);if(!e.includes("("))return e;if(!e.includes("("))return e}isEnum(e){return this.enums.some(t=>t.name===e)}isModel(e){return this.models.some(t=>t.name===e)}},Ts=new Ze,wr=Ts;var et=class{constructor(){this.schema=wr.parse()}async generateModelSchemas(e){let{modelName:t,arkosConfig:s,schemasToGenerate:n=["model","login","signup","getMe","updateMe","updatePassword","create","createOne","createMany","update","updateOne","updateMany","query","findOne","findMany"]}=e,i=await j(t,s),o=_optionalChain([i, 'optionalAccess', _336 => _336.router, 'optionalAccess', _337 => _337.config])||{},a=_optionalChain([i, 'optionalAccess', _338 => _338.prismaQueryOptions])||{},l=["auth","me","password","signup","login"].includes(t.toLowerCase());if(_optionalChain([s, 'optionalAccess', _339 => _339.swagger, 'optionalAccess', _340 => _340.strict])&&s.swagger.mode!=="prisma")return{};if(_optionalChain([o, 'optionalAccess', _341 => _341.disable])===!0)return{};let d=this.schema.models.find(u=>u.name.toLowerCase()===t.toLowerCase());if(!d&&!l)throw new Error(`Model ${t} not found in schema`);let p={};return l?await this.generateAuthSchemas(this.schema.models.find(u=>u.name.toLowerCase()==="user"),p,s,n,a):d&&await this.generateCrudSchemas(d,p,s,n,a,o),{...p}}async generateAuthSchemas(e,t,s,n,i,o){let a="Auth";if(!_optionalChain([s, 'optionalAccess', _342 => _342.authentication]))return t;n.includes("login")&&!this.isEndpointDisabled("login",o)&&!await k("login",a,s)&&(t.LoginSchema=this.generateLoginSchema(s)),n.includes("signup")&&!this.isEndpointDisabled("signup",o)&&!await k("signup",a,s)&&(t.SignupSchema=this.generateSignupSchema(e,_optionalChain([i, 'optionalAccess', _343 => _343.signup]))),n.includes("updateMe")&&!this.isEndpointDisabled("updateMe",o)&&!await k("updateMe",a,s)&&(t.UpdateMeSchema=this.generateUpdateMeSchema(e,_optionalChain([i, 'optionalAccess', _344 => _344.updateMe]))),n.includes("updatePassword")&&!this.isEndpointDisabled("updatePassword",o)&&!await k("updatePassword",a,s)&&(t.UpdatePasswordSchema=this.generateUpdatePasswordSchema(e,_optionalChain([i, 'optionalAccess', _345 => _345.updatePassword]))),n.includes("getMe")&&!this.isEndpointDisabled("getMe",o)&&!await k("getMe",a,s)&&(t.GetMeSchema=this.generateResponseSchema(e,_optionalChain([i, 'optionalAccess', _346 => _346.getMe])||{},"findOne"))}async generateCrudSchemas(e,t,s,n,i,o){let a=e.name,c=async(l,d)=>{let p=_optionalChain([s, 'access', _347 => _347.validation, 'optionalAccess', _348 => _348.resolver])==="zod"?"Schema":"Dto";if(await k(l==="Create"?"createOne":"updateOne",d,s))return`${l}${d}${p}`;{let y=`${l}${d}ModelSchema`;return t[y]||(l==="Create"?t[y]=this.generateCreateSchema(e,this.resolvePrismaQueryOptions(i,"createOne")):l==="Update"&&(t[y]=this.generateUpdateSchema(e,this.resolvePrismaQueryOptions(i,"updateOne")))),y}};if(n.includes("createOne")&&!this.isEndpointDisabled("createOne",o)&&!await k("createOne",a,s)&&(t[`Create${a}ModelSchema`]=this.generateCreateSchema(e,this.resolvePrismaQueryOptions(i,"createOne"))),n.includes("createMany")&&!this.isEndpointDisabled("createMany",o)&&!await k("createMany",a,s)){let l=await c("Create",a);t[`CreateMany${a}ModelSchema`]={type:"array",items:{$ref:`#/components/schemas/${l}`}}}if(n.includes("updateOne")&&!this.isEndpointDisabled("updateOne",o)&&!await k("updateOne",a,s)&&(t[`Update${a}ModelSchema`]=this.generateUpdateSchema(e,this.resolvePrismaQueryOptions(i,"updateOne"))),n.includes("updateMany")&&!this.isEndpointDisabled("updateMany",o)&&!await k("updateMany",a,s)){let l=await c("Update",a);t[`UpdateMany${a}ModelSchema`]={type:"object",properties:{data:{type:"object",$ref:`#/components/schemas/${l}`},where:{type:"object"}},required:["data"]}}n.includes("findOne")&&!this.isEndpointDisabled("findOne",o)&&!await k("findOne",a,s)&&(t[`FindOne${a}ModelSchema`]=this.generateResponseSchema(e,this.resolvePrismaQueryOptions(i,"findOne"),"findOne")),n.includes("findMany")&&!this.isEndpointDisabled("findMany",o)&&!await k("findMany",a,s)&&(t[`FindMany${a}ModelSchema`]={type:"array",items:this.generateResponseSchema(e,this.resolvePrismaQueryOptions(i,"findMany"),"findMany")})}generateCreateSchema(e,t){let s={},n=[],i=["createdAt","updatedAt","deletedAt","id"];e.name.toLowerCase()==="auth"&&i.push("roles","role","isActive","isStaff","isSuperUser","passwordChangedAt","deletedSelfAccountAt","lastLoginAt");for(let o of e.fields){if(o.isId||i.includes(o.name))continue;if(this.isModelRelation(o.type)){o.isArray||(s[o.connectionField]={type:this.mapPrismaTypeToJsonSchema(_optionalChain([e, 'access', _349 => _349.fields, 'access', _350 => _350.find, 'call', _351 => _351(c=>c.name===o.connectionField), 'optionalAccess', _352 => _352.type])||"String")},!o.isOptional&&o.defaultValue===void 0&&n.push(o.name));continue}let a=this.convertFieldToJsonSchema(o);s[o.name]=a,!o.isOptional&&o.defaultValue===void 0&&!o.isArray&&n.push(o.name)}return{type:"object",properties:s,required:n}}generateUpdateSchema(e,t){let s={},n=["createdAt","updatedAt","deletedAt","id"];for(let i of e.fields){if(i.isId||n.includes(i.name))continue;if(this.isModelRelation(i.type)){i.isArray||(s[i.connectionField]={type:this.mapPrismaTypeToJsonSchema(_optionalChain([e, 'access', _353 => _353.fields, 'access', _354 => _354.find, 'call', _355 => _355(a=>a.name===i.connectionField), 'optionalAccess', _356 => _356.type])||"String")});continue}let o=this.convertFieldToJsonSchema(i);s[i.name]=o}return{type:"object",properties:s,required:[]}}generateResponseSchema(e,t,s){let n={},i=[],o=_optionalChain([t, 'optionalAccess', _357 => _357.select]),a=_optionalChain([t, 'optionalAccess', _358 => _358.include]);for(let c of e.fields){if(c.name.toLowerCase().includes("password")||o&&!o[c.name])continue;if(this.isModelRelation(c.type)){if(_optionalChain([a, 'optionalAccess', _359 => _359[c.name]])){let d=this.schema.models.find(p=>p.name===c.type);if(d){let p=this.generateNestedRelationSchema(d,a[c.name]);n[c.name]=c.isArray?{type:"array",items:p}:p}}continue}let l=this.convertFieldToJsonSchema(c);n[c.name]=l,c.isOptional||i.push(c.name)}return{type:"object",properties:n,required:i}}generateNestedRelationSchema(e,t){let s={},n=[],i=_optionalChain([t, 'optionalAccess', _360 => _360.select]),o=_optionalChain([t, 'optionalAccess', _361 => _361.include]);for(let a of e.fields){if(a.name.toLowerCase().includes("password")||i&&!i[a.name])continue;if(this.isModelRelation(a.type)){if(_optionalChain([o, 'optionalAccess', _362 => _362[a.name]])){let l=this.schema.models.find(d=>d.name===a.type);if(l){let d=this.generateNestedRelationSchema(l,o[a.name]);s[a.name]=a.isArray?{type:"array",items:d}:d}}continue}let c=this.convertFieldToJsonSchema(a);s[a.name]=c,a.isOptional||n.push(a.name)}return{type:"object",properties:s,required:n}}generateLoginSchema(e){let t=_optionalChain([e, 'optionalAccess', _363 => _363.authentication, 'optionalAccess', _364 => _364.login, 'optionalAccess', _365 => _365.allowedUsernames])||[],s=i=>i.includes(".")&&i.split(".").pop()||i,n={type:"object",properties:{password:{type:"string",minLength:8}},required:["password"]};if(t.forEach(i=>{let o=s(i);n.properties[o]={type:"string",format:"string",description:`Username field: ${i}`}}),t.length>0){let i=t.map(s);return{...n,anyOf:i.map(()=>({required:[...n.required]}))}}return n}generateSignupSchema(e,t){let s=this.generateCreateSchema(e,t||{});return["roles","role","isActive","isStaff","isSuperUser","passwordChangedAt","deletedSelfAccountAt","lastLoginAt"].forEach(i=>{ _optionalChainDelete([s, 'optionalAccess', _366 => _366.properties, 'optionalAccess', _367 => delete _367[i]])}),s}generateUpdateMeSchema(e,t){let s=this.generateUpdateSchema(e,t||{});return["roles","role","isActive","isStaff","isSuperUser","passwordChangedAt","deletedSelfAccountAt","password","lastLoginAt"].forEach(i=>{ _optionalChainDelete([s, 'optionalAccess', _368 => _368.properties, 'optionalAccess', _369 => delete _369[i]])}),s}generateUpdatePasswordSchema(e,t){return{type:"object",properties:{currentPassword:{type:"string"},newPassword:{type:"string",minLength:8}},required:["currentPassword","newPassword"]}}resolvePrismaQueryOptions(e,t){if(!e||!t)return{};let s=e,n=s[t]||{},i=s.queryOptions||{};s.global&&(i=w(i,s.global));let o=this.getGeneralOptionsForAction(s,t);return o&&(i=w(i,o)),n&&(i=w(i,n)),i}getGeneralOptionsForAction(e,t){let s={find:["findOne","findMany"],create:["createOne","createMany"],update:["updateOne","updateMany"],delete:["deleteOne","deleteMany"],save:["createOne","createMany","updateOne","updateMany"],saveOne:["createOne","updateOne"],saveMany:["createMany","updateMany"]};for(let[n,i]of Object.entries(s))if(i.includes(t)&&e[n])return e[n];return null}isEndpointDisabled(e,t){return _optionalChain([t, 'optionalAccess', _370 => _370.disable])?typeof t.disable=="boolean"?t.disable:t.disable[e]||!1:!1}isModelRelation(e){return this.schema.models.some(t=>t.name===e)}convertFieldToJsonSchema(e){let s={type:this.mapPrismaTypeToJsonSchema(e.type)};if(e.isArray&&(s.type="array",s.items={type:this.mapPrismaTypeToJsonSchema(e.type)}),e.defaultValue!==void 0&&(s.default=e.defaultValue),e.type==="DateTime"&&(s.format="date-time"),this.isEnum(e.type)){let n=this.schema.enums.find(i=>i.name===e.type);n&&(s.enum=n.values)}return s}mapPrismaTypeToJsonSchema(e){let t={String:"string",Int:"number",Float:"number",Boolean:"boolean",DateTime:"string",Json:"object",Bytes:"string"};return t[e]?t[e]:this.isEnum(e)?"string":this.isModelRelation(e)?"object":"string"}isEnum(e){return this.schema.enums.some(t=>t.name===e)}},Us=new et,Ee=Us;async function br(r){let e=[...D(),"auth"];try{return(await Promise.all(e.map(async n=>await Ee.generateModelSchemas({modelName:n,arkosConfig:r})))).reduce((n,i)=>({...n,...i}),{})}catch(t){throw console.error(t),t}}async function Ar(r,e,t){let s=$(r),n=_pluralize2.default.plural(s),i=P(r),o=be(s),a=_pluralize2.default.plural(o),l=await _asyncOptionalChain([(await j(r,t)), 'optionalAccess', async _371 => _371.router, 'optionalAccess', async _372 => _372.config]);if(_optionalChain([l, 'optionalAccess', _373 => _373.disable])===!0)return;let d=async p=>{let u=_optionalChain([t, 'access', _374 => _374.swagger, 'optionalAccess', _375 => _375.mode]);return _optionalChain([t, 'access', _376 => _376.swagger, 'optionalAccess', _377 => _377.strict])?u||"prisma":await k(p,r,t)&&u||"prisma"};if(!T(l,"createOne")){e[`/api/${n}`]||(e[`/api/${n}`]={});let p=await d("create");e[`/api/${n}`].post={tags:[a],summary:`Create a new ${o}`,description:`Creates a new ${o} record in the system`,operationId:`create${i}`,requestBody:{description:`${o} data to create`,required:!0,content:{"application/json":{schema:{$ref:v(`Create${i}`,p)}}}},responses:{201:{description:`${o} created successfully`,content:{"application/json":{schema:{$ref:v(`${i}`,p)}}}},400:{description:"Invalid input data provided"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"}},security:[{BearerAuth:[]}]}}if(!T(l,"findMany")){e[`/api/${n}`]||(e[`/api/${n}`]={});let p=await d("findMany");e[`/api/${n}`].get={tags:[a],summary:`Get ${a}`,description:`Retrieves a paginated list of ${a} with optional filtering and sorting`,operationId:`find${_pluralize2.default.plural(i)}`,parameters:[{name:"filter",in:"query",description:"Filter criteria in JSON format",schema:{type:"string"}},{name:"sort",in:"query",description:"Sort field (prefix with '-' for descending order)",schema:{type:"string"}},{name:"page",in:"query",description:"Page number (starts from 1)",schema:{type:"integer",minimum:1}},{name:"limit",in:"query",description:"Number of items per page",schema:{type:"integer",minimum:1,maximum:100}},{name:"fields",in:"query",description:"Comma-separated list of fields to include in response",schema:{type:"string"}}],responses:{200:{description:`List of ${a} retrieved successfully`,content:{"application/json":{schema:{type:"object",properties:{total:{type:"integer",description:"Total number of records matching the criteria"},results:{type:"integer",description:"Number of records returned in current page"},data:{type:"array",items:{$ref:v(`FindMany${i}`,p)}}}}}}},401:{description:"Authentication required"},403:{description:"Insufficient permissions"}},security:[{BearerAuth:[]}]}}if(!T(l,"createMany")){let p=await d("createMany");e[`/api/${n}/many`]={post:{tags:[a],summary:`Create multiple ${a}`,description:`Creates multiple ${a} records in a single batch operation`,operationId:`createMany${i}`,requestBody:{description:`Array of ${o} data to create`,required:!0,content:{"application/json":{schema:{type:"array",items:{$ref:v(`CreateMany${i}`,p)}}}}},responses:{201:{description:`${a} created successfully`,content:{"application/json":{schema:{type:"object",properties:{count:{type:"integer",description:"Number of records created"}}}}}},400:{description:"Invalid input data provided"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"}},security:[{BearerAuth:[]}]}}}if(!T(l,"updateMany")){e[`/api/${n}/many`]||(e[`/api/${n}/many`]={});let p=await d("updateMany");e[`/api/${n}/many`].patch={tags:[a],summary:`Update multiple ${a}`,description:`Updates multiple ${a} records that match the specified filter criteria`,operationId:`updateMany${i}`,parameters:[{name:"filter",in:"query",description:"Filter criteria in JSON format (required)",required:!0,schema:{type:"string"}}],requestBody:{description:`Partial ${o} data to update`,required:!0,content:{"application/json":{schema:{$ref:v(`UpdateMany${i}`,p)}}}},responses:{200:{description:`${a} updated successfully`,content:{"application/json":{schema:{type:"object",properties:{count:{type:"integer",description:"Number of records updated"}}}}}},400:{description:"Invalid input data or missing filter criteria"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"}},security:[{BearerAuth:[]}]}}if(T(l,"deleteMany")||(e[`/api/${n}/many`]||(e[`/api/${n}/many`]={}),e[`/api/${n}/many`].delete={tags:[a],summary:`Delete multiple ${a}`,description:`Deletes multiple ${a} records that match the specified filter criteria`,operationId:`deleteMany${i}`,parameters:[{name:"filter",in:"query",description:"Filter criteria in JSON format (required)",required:!0,schema:{type:"string"}}],responses:{200:{description:`${a} deleted successfully`,content:{"application/json":{schema:{type:"object",properties:{count:{type:"integer",description:"Number of records deleted"}}}}}},400:{description:"Missing filter criteria"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"}},security:[{BearerAuth:[]}]}),!T(l,"findOne")){let p=await d("findOne");e[`/api/${n}/{id}`]={get:{tags:[a],summary:`Get ${o} by ID`,description:`Retrieves a single ${o} record by its unique identifier`,operationId:`find${i}ById`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${o}`,required:!0,schema:{type:"string"}}],responses:{200:{description:`${o} retrieved successfully`,content:{"application/json":{schema:{$ref:v(`FindOne${i}`,p)}}}},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${o} not found`}},security:[{BearerAuth:[]}]}}}if(!T(l,"updateOne")){e[`/api/${n}/{id}`]||(e[`/api/${n}/{id}`]={});let p=await d("update");e[`/api/${n}/{id}`].patch={tags:[a],summary:`Update ${o} by ID`,description:`Updates a single ${o} record by its unique identifier`,operationId:`update${i}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${o}`,required:!0,schema:{type:"string"}}],requestBody:{description:`Partial ${o} data to update`,required:!0,content:{"application/json":{schema:{$ref:v(`Update${i}`,p)}}}},responses:{200:{description:`${o} updated successfully`,content:{"application/json":{schema:{$ref:v(`${i}`,p)}}}},400:{description:"Invalid input data provided"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${o} not found`}},security:[{BearerAuth:[]}]}}T(l,"deleteOne")||(e[`/api/${n}/{id}`]||(e[`/api/${n}/{id}`]={}),e[`/api/${n}/{id}`].delete={tags:[a],summary:`Delete ${o} by ID`,description:`Permanently deletes a single ${o} record by its unique identifier`,operationId:`delete${i}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${o}`,required:!0,schema:{type:"string"}}],responses:{204:{description:`${o} deleted successfully`},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${o} not found`}},security:[{BearerAuth:[]}]})}async function xr(r,e,t){let s=$(r),n=_pluralize2.default.plural(s),i=P(r),o=be(s),a=_pluralize2.default.plural(o),l=await _asyncOptionalChain([(await j(r,t)), 'optionalAccess', async _378 => _378.router, 'optionalAccess', async _379 => _379.config]);if(_optionalChain([l, 'optionalAccess', _380 => _380.disable])===!0||!_optionalChain([l, 'optionalAccess', _381 => _381.parent]))return;let d=l.parent.model,p=_pluralize2.default.plural($(d)),u=be($(d)),f=h=>{let b=_optionalChain([l, 'optionalAccess', _382 => _382.parent, 'optionalAccess', _383 => _383.endpoints]);return!b||b==="*"?!0:Array.isArray(b)?b.includes(h):!1},y=async h=>{let b=_optionalChain([t, 'access', _384 => _384.swagger, 'optionalAccess', _385 => _385.mode]);return _optionalChain([t, 'access', _386 => _386.swagger, 'optionalAccess', _387 => _387.strict])?b||"prisma":await k(h,r,t)&&b||"prisma"};if(f("createOne")){let h=await y("create");e[`/api/${p}/{id}/${n}`]={post:{tags:[a],summary:`Create ${o} for ${u}`,description:`Creates a new ${o} record associated with the specified ${u}`,operationId:`create${i}For${P(d)}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${u}`,required:!0,schema:{type:"string"}}],requestBody:{description:`${o} data to create`,required:!0,content:{"application/json":{schema:{$ref:v(`Create${i}`,h)}}}},responses:{201:{description:`${o} created successfully`,content:{"application/json":{schema:{$ref:v(`${i}`,h)}}}},400:{description:"Invalid input data provided"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${u} not found`}},security:[{BearerAuth:[]}]}}}if(f("findMany")){e[`/api/${p}/{id}/${n}`]||(e[`/api/${p}/{id}/${n}`]={});let h=await y("findMany");e[`/api/${p}/{id}/${n}`].get={tags:[a],summary:`Get ${a} for ${u}`,description:`Retrieves all ${a} associated with the specified ${u}`,operationId:`get${_pluralize2.default.plural(i)}For${P(d)}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${u}`,required:!0,schema:{type:"string"}},{name:"filter",in:"query",description:"Additional filter criteria in JSON format",schema:{type:"string"}},{name:"sort",in:"query",description:"Sort field (prefix with '-' for descending order)",schema:{type:"string"}},{name:"page",in:"query",description:"Page number (starts from 1)",schema:{type:"integer",minimum:1}},{name:"limit",in:"query",description:"Number of items per page",schema:{type:"integer",minimum:1,maximum:100}},{name:"fields",in:"query",description:"Comma-separated list of fields to include in response",schema:{type:"string"}}],responses:{200:{description:`List of ${a} retrieved successfully`,content:{"application/json":{schema:{type:"object",properties:{total:{type:"integer",description:"Total number of records matching the criteria"},results:{type:"integer",description:"Number of records returned in current page"},data:{type:"array",items:{$ref:v(`FindMany${i}`,h)}}}}}}},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${u} not found`}},security:[{BearerAuth:[]}]}}if(f("createMany")){let h=await y("createMany");e[`/api/${p}/{id}/${n}/many`]={post:{tags:[a],summary:`Create multiple ${a} for ${u}`,description:`Creates multiple ${a} records associated with the specified ${u}`,operationId:`createMany${i}For${P(d)}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${u}`,required:!0,schema:{type:"string"}}],requestBody:{description:`Array of ${o} data to create`,required:!0,content:{"application/json":{schema:{type:"array",items:{$ref:v(`CreateMany${i}`,h)}}}}},responses:{201:{description:`${a} created successfully`,content:{"application/json":{schema:{type:"object",properties:{count:{type:"integer",description:"Number of records created"}}}}}},400:{description:"Invalid input data provided"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${u} not found`}},security:[{BearerAuth:[]}]}}}if(f("updateMany")){e[`/api/${p}/{id}/${n}/many`]||(e[`/api/${p}/{id}/${n}/many`]={});let h=await y("updateMany");e[`/api/${p}/{id}/${n}/many`].patch={tags:[a],summary:`Update multiple ${a} for ${u}`,description:`Updates multiple ${a} records associated with the specified ${u}`,operationId:`updateMany${i}For${P(d)}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${u}`,required:!0,schema:{type:"string"}},{name:"filter",in:"query",description:"Additional filter criteria in JSON format",schema:{type:"string"}}],requestBody:{description:`Partial ${o} data to update`,required:!0,content:{"application/json":{schema:{$ref:v(`UpdateMany${i}`,h)}}}},responses:{200:{description:`${a} updated successfully`,content:{"application/json":{schema:{type:"object",properties:{count:{type:"integer",description:"Number of records updated"}}}}}},400:{description:"Invalid input data provided"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${u} not found`}},security:[{BearerAuth:[]}]}}if(f("deleteMany")&&(e[`/api/${p}/{id}/${n}/many`]||(e[`/api/${p}/{id}/${n}/many`]={}),e[`/api/${p}/{id}/${n}/many`].delete={tags:[a],summary:`Delete multiple ${a} for ${u}`,description:`Deletes multiple ${a} records associated with the specified ${u}`,operationId:`deleteMany${i}For${P(d)}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${u}`,required:!0,schema:{type:"string"}},{name:"filter",in:"query",description:"Additional filter criteria in JSON format",schema:{type:"string"}}],responses:{200:{description:`${a} deleted successfully`,content:{"application/json":{schema:{type:"object",properties:{count:{type:"integer",description:"Number of records deleted"}}}}}},400:{description:"Missing filter criteria"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${u} not found`}},security:[{BearerAuth:[]}]}),f("findOne")){let h=await y("findOne");e[`/api/${p}/{id}/${n}/{childId}`]={get:{tags:[a],summary:`Get ${o} by ID for ${u}`,description:`Retrieves a single ${o} record by its unique identifier associated with the specified ${u}`,operationId:`get${i}ByIdFor${P(d)}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${u}`,required:!0,schema:{type:"string"}},{name:"childId",in:"path",description:`Unique identifier of the ${o}`,required:!0,schema:{type:"string"}}],responses:{200:{description:`${o} retrieved successfully`,content:{"application/json":{schema:{$ref:v(`FindOne${i}`,h)}}}},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${o} or ${u} not found`}},security:[{BearerAuth:[]}]}}}if(f("updateOne")){e[`/api/${p}/{id}/${n}/{childId}`]||(e[`/api/${p}/{id}/${n}/{childId}`]={});let h=await y("update");e[`/api/${p}/{id}/${n}/{childId}`].patch={tags:[a],summary:`Update ${o} by ID for ${u}`,description:`Updates a single ${o} record by its unique identifier associated with the specified ${u}`,operationId:`update${i}ByIdFor${P(d)}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${u}`,required:!0,schema:{type:"string"}},{name:"childId",in:"path",description:`Unique identifier of the ${o}`,required:!0,schema:{type:"string"}}],requestBody:{description:`Partial ${o} data to update`,required:!0,content:{"application/json":{schema:{$ref:v(`Update${i}`,h)}}}},responses:{200:{description:`${o} updated successfully`,content:{"application/json":{schema:{$ref:v(`${i}`,h)}}}},400:{description:"Invalid input data provided"},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${o} or ${u} not found`}},security:[{BearerAuth:[]}]}}f("deleteOne")&&(e[`/api/${p}/{id}/${n}/{childId}`]||(e[`/api/${p}/{id}/${n}/{childId}`]={}),e[`/api/${p}/{id}/${n}/{childId}`].delete={tags:[a],summary:`Delete ${o} by ID for ${u}`,description:`Permanently deletes a single ${o} record by its unique identifier associated with the specified ${u}`,operationId:`delete${i}ByIdFor${P(d)}`,parameters:[{name:"id",in:"path",description:`Unique identifier of the ${u}`,required:!0,schema:{type:"string"}},{name:"childId",in:"path",description:`Unique identifier of the ${o}`,required:!0,schema:{type:"string"}}],responses:{204:{description:`${o} deleted successfully`},401:{description:"Authentication required"},403:{description:"Insufficient permissions"},404:{description:`${o} or ${u} not found`}},security:[{BearerAuth:[]}]})}async function Mr(r){switch(_optionalChain([r, 'optionalAccess', _388 => _388.swagger, 'access', _389 => _389.mode])){case"prisma":return await br(r);case"class-validator":return await yr();case"zod":return await gr();default:throw Error("Unknown mode for auto documentation, supported values are prisma, class-validator, zod or json-schemas")}}function Ce(r,e,t){let s=P(e);return`${_nullishCoalesce({model:s,create:`Create${s}`,createMany:`CreateMany${s}`,findOne:`FindOne${s}`,findMany:`FindMany${s}`,update:`Update${s}`,updateMany:`UpdateMany${s}`,query:`Query${s}`,login:"Login",signup:"Signup",updateMe:"UpdateMe",updatePassword:"UpdatePassword"}[r], () => (P(r)))}${t}`}function be(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function v(r,e){let t=r.toLowerCase();if(["getme","updateme","login","signup","updatepassword","password","me"].some(i=>i===t)&&e==="prisma")return`#/components/schemas/${r}Schema`;switch(e){case"prisma":return`#/components/schemas/${r}ModelSchema`;case"zod":return`#/components/schemas/${r}Schema`;case"class-validator":return`#/components/schemas/${r}Dto`;default:return I.error(`Unknown Arkos.js swagger documentation provided, available options are prisma, zod or class-validator but received ${e}`),""}}async function Pr(r){if(!_optionalChain([r, 'optionalAccess', _390 => _390.swagger]))return{};let t={},s=D();for(let n of s)await Ar(n,t,r),await xr(n,t,r);return t={...t,...fr()},t={...t,...await hr(r)||{}},t}var rt=class{extractModelNameFromSchemaRef(e){let t=e.match(/#\/components\/schemas\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/);if(t){let s=t[1];return s==="Auth"||s==="Login"||s==="Signup"||s==="GetMe"||s==="UpdateMe"||s==="UpdatePassword"?"Auth":s}return null}extractActionFromOperationId(e){return e.includes("createMany")?"createMany":e.includes("updateMany")?"updateMany":e.includes("deleteMany")?"deleteMany":e.startsWith("create")?"createOne":e.startsWith("update")?"updateOne":e.startsWith("delete")?"deleteOne":e.startsWith("find")&&(e.includes("ById")||e.includes("One"))?"findOne":e.startsWith("find")?"findMany":e.includes("login")||e==="login"?"login":e.includes("signup")||e==="signup"?"signup":e.includes("getMe")||e==="getMe"?"getMe":e.includes("updateMe")||e==="updateMe"?"updateMe":e.includes("updatePassword")||e==="updatePassword"?"updatePassword":null}extractModelNameFromOperationId(e){let t=e.replace(/^(create|update|delete|find)Many/i,"").replace(/^(create|update|delete|find)/i,"").replace(/ById$/i,"").replace(/s$/,"");return e.includes("login")||e.includes("signup")||e.includes("getMe")||e.includes("updateMe")||e.includes("updatePassword")?"Auth":t||null}extractSchemaRefsWithContext(e,t=new Map,s={}){return typeof e!="object"||e===null?t:Array.isArray(e)?(e.forEach(n=>this.extractSchemaRefsWithContext(n,t,s)),t):(e.operationId&&typeof e.operationId=="string"&&(s={...s,operationId:e.operationId}),e.$ref&&typeof e.$ref=="string"&&t.set(e.$ref,{...s}),Object.values(e).forEach(n=>{this.extractSchemaRefsWithContext(n,t,s)}),t)}extractPathSchemaRefs(e){let t=new Map;return Object.entries(e).forEach(([s,n])=>{n&&Object.entries(n).forEach(([i,o])=>{if(!o||typeof o!="object")return;let a={method:i,path:s,operationId:o.operationId};this.extractSchemaRefsWithContext(o,t,a)})}),t}getSchemaNameFromRef(e){let t=e.match(/#\/components\/schemas\/(.+)$/);return t?t[1]:null}async generateMissingJsonSchemas(e,t,s){let n={},i=this.extractPathSchemaRefs(e),o=new Map;for(let[a,c]of i){let l=this.getSchemaNameFromRef(a);if(!l||t[l]||!l.includes("ModelSchema")&&!l.includes("Schema"))continue;let d=null,p=null;c.operationId&&(d=this.extractModelNameFromOperationId(c.operationId),p=this.extractActionFromOperationId(c.operationId)),(!d||!p)&&(d=d||this.extractModelNameFromSchemaRef(a),p=p||this.extractActionFromSchemaRef(a)),d&&p&&(o.has(d)||o.set(d,new Set),o.get(d).add(p))}for(let[a,c]of o)try{let l=Array.from(c),d=await Ee.generateModelSchemas({modelName:a,arkosConfig:s,schemasToGenerate:l});Object.entries(d).forEach(([p,u])=>{let f=p;["auth","login","me","password","me"].includes(a.toLowerCase())?p==="LoginSchema"?f="LoginSchema":p==="SignupSchema"?f="SignupSchema":p==="GetMeSchema"?f="GetMeSchema":p==="UpdateMeSchema"?f="UpdateMeSchema":p==="UpdatePasswordSchema"&&(f="UpdatePasswordSchema"):p.includes("ModelSchema")?f=p:f=`${p}ModelSchema`,n[f]=u})}catch(l){console.warn(`Failed to generate schemas for model ${a}:`,l)}return n}extractActionFromSchemaRef(e){return e.includes("CreateMany")?"createMany":e.includes("Create")?"createOne":e.includes("UpdateMany")?"updateMany":e.includes("Update")&&!e.includes("UpdateMe")&&!e.includes("UpdatePassword")?"updateOne":e.includes("FindMany")?"findMany":e.includes("FindOne")?"findOne":e.includes("Login")?"login":e.includes("Signup")?"signup":e.includes("GetMe")?"getMe":e.includes("UpdateMe")?"updateMe":e.includes("UpdatePassword")?"updatePassword":null}analyzeMissingSchemas(e,t){let s=this.extractPathSchemaRefs(e),n=[],i=[],o=[],a=[];for(let[c,l]of s){let d={ref:c,context:l};n.push(d);let p=this.getSchemaNameFromRef(c);if(p)if(t[p])o.push(d);else{i.push(d);let u=null,f=null;l.operationId&&(u=this.extractModelNameFromOperationId(l.operationId),f=this.extractActionFromOperationId(l.operationId)),(!u||!f)&&(u=u||this.extractModelNameFromSchemaRef(c),f=f||this.extractActionFromSchemaRef(c)),u&&f&&a.push({model:u,action:f,ref:c,operationId:l.operationId})}}return{allRefs:n,missingRefs:i,existingRefs:o,modelActions:a}}},Ns=new rt,Rr=Ns;var $r=_express.Router.call(void 0, );async function Or(r){let e=await Mr(r),t=await Pr(r);e={...e,...await Rr.generateMissingJsonSchemas(t,e,r)};let s={endpoint:"/docs",mode:"prisma",strict:!1,options:{definition:{openapi:"3.0.0",info:{title:"Powered By Arkos.js",version:"1.0.0",description:"This API was automatically generated by Arkos.js, read more about at www.arkosjs.com"},servers:[{url:`http://${r.host}:${r.port}`,description:`Local ${ve(process.env.NODE_ENV||"development")} Server`}],paths:t,components:{schemas:e||{},securitySchemes:{BearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}},security:[]},apis:["./src/routers/*.router.{ts,js}","./src/modules/**/*.router.{ts,js}"],deepLinking:!0,tryItOutEnabled:!0,persistAuthorization:!1},scalarApiReferenceConfiguration:{theme:"deepSpace",darkMode:!0,layout:"modern",showSidebar:!0,hideDownloadButton:!1,metaData:{title:"Arkos.js API Documentation",description:"API documentation generated by Arkos.js"},pageTitle:"Arkos.js API Documentation"}},n=w(s||{},r.swagger||{}),{definition:i,...o}=_optionalChain([n, 'optionalAccess', _391 => _391.options]),a=_swaggerjsdoc2.default.call(void 0, {definition:i,...o});return $r.use(n.endpoint,vr.apiReference({content:a,..._optionalChain([n, 'optionalAccess', _392 => _392.scalarApiReferenceConfiguration])})),$r}var C=_express2.default.call(void 0, );async function Cr(r){await je(),_optionalChain([r, 'optionalAccess', _393 => _393.configureApp])&&await r.configureApp(C);let e=_optionalChain([r, 'optionalAccess', _394 => _394.middlewares]),t=_optionalChain([e, 'optionalAccess', _395 => _395.disable])||[],s=_optionalChain([e, 'optionalAccess', _396 => _396.replace])||{};_optionalChain([t, 'optionalAccess', _397 => _397.includes, 'optionalCall', _398 => _398("compression")])||C.use(s.compression||_compression2.default.call(void 0, _optionalChain([r, 'optionalAccess', _399 => _399.compressionOptions]))),_optionalChain([t, 'optionalAccess', _400 => _400.includes, 'optionalCall', _401 => _401("global-rate-limit")])||C.use(s.globalRateLimit||_expressratelimit.rateLimit.call(void 0, w({windowMs:60*1e3,limit:500,standardHeaders:"draft-7",legacyHeaders:!1,handler:(a,c)=>{c.status(429).json({message:"Too many requests, please try again later"})}},_optionalChain([r, 'optionalAccess', _402 => _402.globalRequestRateLimitOptions])||{}))),_optionalChain([t, 'optionalAccess', _403 => _403.includes, 'optionalCall', _404 => _404("cors")])||C.use(s.cors||_cors2.default.call(void 0, _optionalChain([r, 'optionalAccess', _405 => _405.cors, 'optionalAccess', _406 => _406.customHandler])?r.cors.customHandler:w({origin:(a,c)=>{let l=_optionalChain([r, 'optionalAccess', _407 => _407.cors, 'optionalAccess', _408 => _408.allowedOrigins]);l==="*"?c(null,!0):Array.isArray(l)?c(null,!a||_optionalChain([l, 'optionalAccess', _409 => _409.includes, 'optionalCall', _410 => _410(a)])):typeof l=="string"?c(null,!a||l===a):c(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},_optionalChain([r, 'optionalAccess', _411 => _411.cors, 'optionalAccess', _412 => _412.options])||{}))),_optionalChain([t, 'optionalAccess', _413 => _413.includes, 'optionalCall', _414 => _414("express-json")])||C.use(s.expressJson||_express2.default.json(_optionalChain([r, 'optionalAccess', _415 => _415.jsonBodyParserOptions]))),_optionalChain([t, 'optionalAccess', _416 => _416.includes, 'optionalCall', _417 => _417("cookie-parser")])||C.use(s.cookieParser||_cookieparser2.default.call(void 0, ..._optionalChain([r, 'optionalAccess', _418 => _418.cookieParserParameters])||[])),_optionalChain([t, 'optionalAccess', _419 => _419.includes, 'optionalCall', _420 => _420("query-parser")])||C.use(s.queryParser||mr(w({parseNull:!0,parseUndefined:!0,parseBoolean:!0},_optionalChain([r, 'optionalAccess', _421 => _421.queryParserOptions])||{}))),_optionalChain([t, 'optionalAccess', _422 => _422.includes, 'optionalCall', _423 => _423("database-connection")])||C.use(s.databaseConnection||mt),_optionalChain([t, 'optionalAccess', _424 => _424.includes, 'optionalCall', _425 => _425("request-logger")])||C.use(s.requestLogger||Er),_optionalChain([r, 'optionalAccess', _426 => _426.middlewares, 'optionalAccess', _427 => _427.additional])&&r.middlewares.additional.forEach(a=>{C.use(a)});let n=_optionalChain([r, 'optionalAccess', _428 => _428.routers]),i=_optionalChain([n, 'optionalAccess', _429 => _429.disable])||[],o=_optionalChain([n, 'optionalAccess', _430 => _430.replace])||{};if(_optionalChain([i, 'optionalAccess', _431 => _431.includes, 'optionalCall', _432 => _432("welcome-endpoint")])||C.get("/api",o.welcomeEndpoint||((a,c)=>{c.status(200).json({message:r.welcomeMessage})})),!_optionalChain([i, 'optionalAccess', _433 => _433.includes, 'optionalCall', _434 => _434("file-upload")])){let a=o.fileUpload?await o.fileUpload(r):await ur(r);C.use(a)}if(!_optionalChain([i, 'optionalAccess', _435 => _435.includes, 'optionalCall', _436 => _436("auth-router")])&&r.authentication){let a=o.authRouter?await o.authRouter(r):await jt(r);C.use("/api",a)}if(!_optionalChain([i, 'optionalAccess', _437 => _437.includes, 'optionalCall', _438 => _438("prisma-models-router")])){let a=o.prismaModelsRouter?await o.prismaModelsRouter(r):await _t(r);C.use("/api",a)}return C.use("/api",Wt()),r.swagger&&(process.env.ARKOS_BUILD!=="true"||r.swagger.enableAfterBuild===!0)&&C.use("/api",await Or(r)),_optionalChain([n, 'optionalAccess', _439 => _439.additional])&&n.additional.forEach(a=>{C.use(a)}),_optionalChain([t, 'optionalAccess', _440 => _440.includes, 'optionalCall', _441 => _441("global-error-handler")])||C.use(s.globalErrorHandler||Je),C.use("*",(a,c)=>{c.status(404).json({message:"Route not found!"})}),C}var _http = require('http'); var _http2 = _interopRequireDefault(_http);process.on("uncaughtException",r=>{I.error(`
|
|
19
|
+
UNCAUGHT EXCEPTION! SHUTTING DOWN...
|
|
20
|
+
`,{timestamp:!0,bold:!0}),console.error(r.name,r.message),console.error(r),process.exit(1)});var de,ke,_={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:Number(process.env.CLI_PORT)||Number(process.env.PORT)||8e3,host:process.env.CLI_HOST||process.env.HOST||"localhost",fileUpload:{baseUploadDir:"uploads",baseRoute:"/api/uploads"},available:!1};async function Fr(r={}){Ot(),_.available=!0,_=w(_,r);let e=process.env.CLI_PORT||_.port||process.env.PORT||"port"in _?_.port:8e3;ke=await Cr(_);let t=new Date().toTimeString().split(" ")[0];return e?(de=_http2.default.createServer(ke),_optionalChain([_, 'optionalAccess', _442 => _442.configureServer])&&await _.configureServer(de),de.listen(Number(e),_.host,()=>{I.ready(`${I.gray(t)} ${ve(process.env.NODE_ENV||"development")} server waiting on http://${_.host||"localhost"}:${e}`)})):I.warn(`${I.gray(t)} port set to undefined, hence no internal http server was setup.`),ke}process.on("unhandledRejection",r=>{I.error(`
|
|
21
|
+
UNHANDLED REJECTION! SHUTTING DOWN...
|
|
22
|
+
`,{timestamp:!0,bold:!0}),console.error(r.name,r.message),console.error(r),_optionalChain([de, 'optionalAccess', _443 => _443.close, 'call', _444 => _444(()=>{process.exit(1)})])});function M(){return _}function kr(){return ke}var _classtransformer = require('class-transformer');async function st(r,e,t){let s=_classtransformer.plainToInstance.call(void 0, r,e),n=await _classvalidator.validate.call(void 0, s,t);if(n.length>0)throw new m("Invalid request body",400,n,"invalid_request_body");return s}async function nt(r,e){let t=r.safeParse(e);if(!t.success)throw new m("Invalid request body",400,t.error.format(),"invalid_request_body");return t.data}function Tr(r,e){if(!r)return{};let t=r,s=t[e]||{},n=t.queryOptions||{};t.global&&(n=w(n,t.global));let i=Js(t,e);return i&&(n=w(n,i)),s&&(n=w(n,s)),n}function Js(r,e){let s={findMany:["find"],findOne:["find"],create:["create","save"],createOne:["create","save","saveOne"],createMany:["create","save","saveMany"],update:["update","save"],updateOne:["update","save","saveOne"],updateMany:["update","save","saveMany"],delete:["delete"],deleteOne:["delete"],deleteMany:["delete"]}[e]||[],n={};for(let i of s)r[i]&&(n=w(n,r[i]));return Object.keys(n).length>0?n:null}function Ur(r,e,t){t()}function O(r,e){Number(_optionalChain([r, 'optionalAccess', _445 => _445.responseStatus]))===204?e.status(Number(_optionalChain([r, 'optionalAccess', _446 => _446.responseStatus]))).send():r.responseData&&_optionalChain([r, 'optionalAccess', _447 => _447.responseStatus])?e.status(Number(_optionalChain([r, 'optionalAccess', _448 => _448.responseStatus]))).json(r.responseData):Number(_optionalChain([r, 'optionalAccess', _449 => _449.responseStatus]))&&!r.responseData?e.status(Number(_optionalChain([r, 'optionalAccess', _450 => _450.responseStatus]))).send():e.status(500).json({message:"No status or data attached to the response"})}function N(r,e){return(t,s,n)=>{let i=M(),o=Tr(r,e),a=_optionalChain([i, 'optionalAccess', _451 => _451.request, 'optionalAccess', _452 => _452.parameters, 'optionalAccess', _453 => _453.allowDangerousPrismaQueryOptions])?JSON.parse(_optionalChain([t, 'access', _454 => _454.query, 'optionalAccess', _455 => _455.prismaQueryOptions])||"{}"):{};t.prismaQueryOptions=w(o,a),n()}}function Er(r,e,t){let s=Date.now(),n={GET:"\x1B[36m",POST:"\x1B[32m",PUT:"\x1B[33m",PATCH:"\x1B[33m",DELETE:"\x1B[31m",HEAD:"\x1B[34m",OPTIONS:"\x1B[34m"},i=o=>o>=200&&o<300?"\x1B[32m":o>=300&&o<400||o>=400&&o<500?"\x1B[33m":o>=500?"\x1B[31m":"\x1B[0m";e.on("finish",()=>{let o=Date.now()-s,c=new Date().toTimeString().split(" ")[0],l=n[r.method]||"\x1B[0m",d=i(e.statusCode);console.info(`[\x1B[36mINFO\x1B[0m] \x1B[90m${c}\x1B[0m ${l}${r.method}\x1B[0m ${decodeURIComponent(r.originalUrl)} ${d}${e.statusCode}\x1B[0m \x1B[35m${o}ms\x1B[0m`)}),t()}function q(r,e){return x(async(t,s,n)=>{let i=_optionalChain([M, 'call', _456 => _456(), 'optionalAccess', _457 => _457.validation]),o=t.body;_optionalChain([i, 'optionalAccess', _458 => _458.resolver])==="class-validator"&&r?t.body=await st(r,o,w({whitelist:!0,...e},_optionalChain([i, 'optionalAccess', _459 => _459.validationOptions])||{})):_optionalChain([i, 'optionalAccess', _460 => _460.resolver])==="zod"&&r&&(t.body=await nt(r,o)),n()})}var ot=class{constructor(){this.authenticate=x(async(e,t,s)=>{if(!_optionalChain([M, 'call', _461 => _461(), 'optionalAccess', _462 => _462.authentication])){s();return}e.user=await this.getAuthenticatedUser(e),s()})}signJwtToken(e,t,s){let{authentication:n}=M();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!_optionalChain([n, 'optionalAccess', _463 => _463.jwt, 'optionalAccess', _464 => _464.secret]))throw new m("Missing JWT secret on production!",500,{},"MissingJWTOnProduction");return s=s||_optionalChain([n, 'optionalAccess', _465 => _465.jwt, 'optionalAccess', _466 => _466.secret])||process.env.JWT_SECRET||le.JWT_SECRET,t=t||_optionalChain([n, 'optionalAccess', _467 => _467.jwt, 'optionalAccess', _468 => _468.expiresIn])||process.env.JWT_EXPIRES_IN||le.JWT_EXPIRES_IN,_jsonwebtoken2.default.sign({id:e},s,{expiresIn:t})}isPasswordHashed(e){return!Number.isNaN(_bcryptjs2.default.getRounds(e)*1)}async isCorrectPassword(e,t){return await _bcryptjs2.default.compare(e,t)}async hashPassword(e){return await _bcryptjs2.default.hash(e,12)}isPasswordStrong(e){return(_optionalChain([M, 'call', _469 => _469(), 'optionalAccess', _470 => _470.authentication, 'optionalAccess', _471 => _471.passwordValidation, 'optionalAccess', _472 => _472.regex])||/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).+$/).test(e)}userChangedPasswordAfter(e,t){if(e.passwordChangedAt){let s=parseInt(String(e.passwordChangedAt.getTime()/1e3),10);return t<s}return!1}async verifyJwtToken(e,t){let{authentication:s}=M();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!_optionalChain([s, 'optionalAccess', _473 => _473.jwt, 'optionalAccess', _474 => _474.secret]))throw new m("Missing JWT secret!",500);return t=t||_optionalChain([s, 'optionalAccess', _475 => _475.jwt, 'optionalAccess', _476 => _476.secret])||process.env.JWT_SECRET||le.JWT_SECRET,new Promise((n,i)=>{_jsonwebtoken2.default.verify(e,t,(o,a)=>{o?i(o):n(a)})})}handleAccessControl(e,t,s){return x(async(n,i,o)=>{if(n.user){let a=n.user,c=U(),l=M();if(a.isSuperUser){o();return}if(_optionalChain([l, 'optionalAccess', _477 => _477.authentication, 'optionalAccess', _478 => _478.mode])==="dynamic"){if(!await c.userRole.findFirst({where:{userId:n.user.id,role:{permissions:{some:{resource:t,action:e}}}},select:{id:!0}}))return o(new m("You do not have permission to perfom this action",403))}else if(_optionalChain([l, 'optionalAccess', _479 => _479.authentication, 'optionalAccess', _480 => _480.mode])==="static"){let d=[];if(!s)return o(new m("You do not have permission to perform this action",403));if(Array.isArray(s)?d=s:s[e]&&(d=s[e]||[]),!(Array.isArray(_optionalChain([a, 'optionalAccess', _481 => _481.roles]))?a.roles:[a.role]).some(f=>d.includes(f)))return o(new m("You do not have permission to perform this action",403))}}o()})}async getAuthenticatedUser(e){if(!_optionalChain([M, 'call', _482 => _482(), 'optionalAccess', _483 => _483.authentication]))return null;let s=U(),n;if(_optionalChain([e, 'optionalAccess', _484 => _484.headers, 'optionalAccess', _485 => _485.authorization])&&_optionalChain([e, 'optionalAccess', _486 => _486.headers, 'optionalAccess', _487 => _487.authorization, 'access', _488 => _488.startsWith, 'call', _489 => _489("Bearer")])?n=_optionalChain([e, 'optionalAccess', _490 => _490.headers, 'optionalAccess', _491 => _491.authorization, 'access', _492 => _492.split, 'call', _493 => _493(" "), 'access', _494 => _494[1]]):_optionalChain([e, 'optionalAccess', _495 => _495.cookies, 'optionalAccess', _496 => _496.arkos_access_token])!=="no-token"&&e.cookies&&(n=_optionalChain([e, 'optionalAccess', _497 => _497.cookies, 'optionalAccess', _498 => _498.arkos_access_token])),!n)throw new m("You are not logged in! please log in to get access",401,{},"LoginRequired");let i;try{i=await this.verifyJwtToken(n)}catch (e8){throw new m("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken")}if(!_optionalChain([i, 'optionalAccess', _499 => _499.id]))throw new m("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken");let o=await s.user.findUnique({where:{id:String(i.id)}});if(!o)throw new m("The user belonging to this token does no longer exists",401);if(this.userChangedPasswordAfter(o,i.iat)&&!_optionalChain([e, 'access', _500 => _500.path, 'optionalAccess', _501 => _501.includes, 'optionalCall', _502 => _502("logout")]))throw new m("User recently changed password! Please log in again.",401,{},"PasswordChanged");return o}handleAuthenticationControl(e,t){if(t&&typeof t=="object"){if(t[e]===!1)return Ur;if(t[e]===!0)return this.authenticate}else return this.authenticate;return this.authenticate}},Qs=new ot,g=Qs;var Ae=class{constructor(e){this.modelName=re(e),this.relationFields=ce(P(e))}async createOne(e,t){$(this.modelName)==="user"&&e.password&&(g.isPasswordHashed(e.password)||(e.password=await g.hashPassword(e.password)));let s=U(),n=Y(e,{...this.relationFields},["delete","disconnect","update"]);return await s[this.modelName].create(w({data:n},t||{}))}async createMany(e,t){let s=U(),n=[];return Array.isArray(e)&&await new Promise(i=>{e.forEach(async(o,a)=>{"password"in o&&this.modelName==="user"&&(g.isPasswordHashed(o.password)||(e[a].password=await g.hashPassword(_optionalChain([o, 'optionalAccess', _503 => _503.password])))),n[a]=Y(e[a],{...this.relationFields},["delete","disconnect","update"]),a===e.length-1&&i(null)})}),await s[this.modelName].createMany(w({data:n},t||{}))}async count(e){return await U()[this.modelName].count({where:e})}async findMany(e,t){return await U()[this.modelName].findMany(w({where:e},t||{}))}async findById(e,t){return await U()[this.modelName].findUnique(w({where:{id:e}},t||{}))}async findOne(e,t){let s=U();return Object.keys(e).length===1&&"id"in e&&e.id!=="me"?s[this.modelName].findUnique(w({where:e},t||{})):await s[this.modelName].findFirst(w({where:e},t||{}))}async updateOne(e,t,s){let n=U();$(this.modelName)==="user"&&_optionalChain([t, 'optionalAccess', _504 => _504.password])&&(g.isPasswordHashed(t.password)||(t.password=await g.hashPassword(_optionalChain([t, 'optionalAccess', _505 => _505.password]))));let i=Y(t,{...this.relationFields});return await n[this.modelName].update(w({where:e,data:i},s||{}))}async updateMany(e,t,s){let n=U();Array.isArray(t)&&this.modelName==="user"&&await new Promise(o=>{t.forEach(async(a,c)=>{"password"in t[c]&&(g.isPasswordHashed(a.password)||(t[c].password=await g.hashPassword(a.password))),c===t.length-1&&o(void 0)})});let i=w({data:t},s||{});return await n[this.modelName].updateMany(w({where:e},i))}async deleteOne(e){return await U()[this.modelName].delete({where:e})}async deleteMany(e){return await U()[this.modelName].deleteMany({where:e})}};function Dt(){let r=D(),e={};return r.forEach(t=>{e[`${re(t)}`]=new Ae(t)}),e}var Dr=()=>{let r=kr(),e=[];return r._router.stack.forEach(t=>{if(t.route)Object.keys(t.route.methods).forEach(s=>{e.push({method:s.toUpperCase(),path:t.route.path})});else if(t.handle&&t.handle.stack){let s="";if(t.regexp){let n=t.regexp.toString();if(_optionalChain([n, 'access', _506 => _506.includes, 'optionalCall', _507 => _507("/?(?=")])){let i=n.match(/\/\^(\\\/[^?]+)/);i&&(s=i[1].replace(/\\\//g,"/"))}else{let i=n.match(/\/\^(\\\/[^\\]+)/);i&&(s=i[1].replace(/\\\//g,"/"))}}t.handle.stack.forEach(n=>{n.route&&Object.keys(n.route.methods).forEach(i=>{let o=n.route.path,a;if(_optionalChain([o, 'access', _508 => _508.includes, 'optionalCall', _509 => _509("/?(?=")])){let c=o.match(/\/\^?(\\\/[^?]+|\/[^?]+)/);if(c){let l=c[1].replace(/\\\//g,"/");a=s?s+l:l}else{let l=o.match(/\?\(\?=([^)]+)/);l?a=l[1]:a=o}}else a=s?s.replace(/\/$/,"")+(o.startsWith("/")?o:"/"+o):o;a=a.replace(/\\\//g,"/").replace(/\^/g,"").replace(/\$/g,""),_optionalChain([a, 'access', _510 => _510.includes, 'optionalCall', _511 => _511("/?(?=")])&&(a=a.replace(/\/\?\(\?=[^)]*\)/g,"")),e.push({method:i.toUpperCase(),path:a})})})}}),e};var ye=class{constructor(e){this.createOne=x(async(e,t,s)=>{let n=await this.service.createOne(e.body,e.prismaQueryOptions);if(this.middlewares.afterCreateOne)return e.responseData={data:n},e.responseStatus=201,s();t.status(201).json({data:n})});this.createMany=x(async(e,t,s)=>{let n=await this.service.createMany(e.body,e.prismaQueryOptions);if(!n)return s(new m("Failed to create the resources. Please check your input.",400,{},"MissingRequestBody"));if(this.middlewares.afterCreateMany)return e.responseData={data:n},e.responseStatus=201,s();t.status(201).json({data:n})});this.findMany=x(async(e,t,s)=>{let{filters:{where:n,...i}}=new H(e,this.modelName).filter().sort().limitFields().paginate(),[o,a]=await Promise.all([this.service.findMany(n,i),this.service.count(n)]);if(this.middlewares.afterFindMany)return e.responseData={total:a,results:o.length,data:o},e.responseStatus=200,s();t.status(200).json({total:a,results:o.length,data:o})});this.findOne=x(async(e,t,s)=>{let n=await this.service.findOne(e.params,e.prismaQueryOptions);if(!n)return Object.keys(e.params).length===1&&"id"in e.params&&e.params.id!=="me"?s(new m(`${P(String(this.modelName))} with ID ${_optionalChain([e, 'access', _512 => _512.params, 'optionalAccess', _513 => _513.id])} not found`,404,{},"NotFound")):s(new m(`${P(String(this.modelName))} not found`,404,{},"NotFound"));if(this.middlewares.afterFindOne)return e.responseData={data:n},e.responseStatus=200,s();t.status(200).json({data:n})});this.updateOne=x(async(e,t,s)=>{let n=await this.service.updateOne(e.params,e.body,e.prismaQueryOptions);if(!n)return Object.keys(e.params).length===1&&"id"in e.params?s(new m(`${P(String(this.modelName))} with ID ${_optionalChain([e, 'access', _514 => _514.params, 'optionalAccess', _515 => _515.id])} not found`,404,{},"NotFound")):s(new m(`${P(String(this.modelName))} not found`,404,{},"NotFound"));if(this.middlewares.afterUpdateOne)return e.responseData={data:n},e.responseStatus=200,s();t.status(200).json({data:n})});this.updateMany=x(async(e,t,s)=>{if(!Object.keys(e.query).some(a=>a!=="prismaQueryOptions"))return s(new m("Filter criteria not provided for bulk update.",400,{},"MissingRequestQueryParameters"));e.query.filterMode=_optionalChain([e, 'access', _516 => _516.query, 'optionalAccess', _517 => _517.filterMode])||"AND";let{filters:{where:n,...i}}=new H(e,this.modelName).filter().sort();delete i.include;let o=await this.service.updateMany(n,e.body,i);if(!o||o.count===0)return s(new m(`${_pluralize2.default.call(void 0, P(String(this.modelName)))} not found`,404));if(this.middlewares.afterUpdateMany)return e.responseData={results:o.count,data:o},e.responseStatus=200,s();t.status(200).json({results:o.count,data:o})});this.deleteOne=x(async(e,t,s)=>{let n=await this.service.deleteOne(e.params);if(!n)return Object.keys(e.params).length===1&&"id"in e.params?s(new m(`${P(String(this.modelName))} with ID ${_optionalChain([e, 'access', _518 => _518.params, 'optionalAccess', _519 => _519.id])} not found`,404,{},"NotFound")):s(new m(`${P(String(this.modelName))} not found`,404,{},"NotFound"));if(this.middlewares.afterDeleteOne)return e.additionalData={data:n},e.responseStatus=204,s();t.status(204).send()});this.deleteMany=x(async(e,t,s)=>{if(!Object.keys(e.query).some(o=>o!=="prismaQueryOptions"))return s(new m("Filter criteria not provided for bulk deletion.",400,{},"MissingRequestQueryParameters"));e.query.filterMode=_optionalChain([e, 'access', _520 => _520.query, 'optionalAccess', _521 => _521.filterMode])||"AND";let{filters:{where:n}}=new H(e,this.modelName).filter().sort(),i=await this.service.deleteMany(n);if(!i||i.count===0)return s(new m("No records found to delete",404,{},"NotFound"));if(this.middlewares.afterDeleteMany)return e.responseData={results:i.count,data:i},e.responseStatus=200,s();t.status(200).json({results:i.count,data:i})});this.modelName=e,this.service=new Ae(e),this.middlewares=_optionalChain([L, 'call', _522 => _522(e), 'optionalAccess', _523 => _523.middlewares])||{}}};function Vt(r,e,t){let s=Dr();e.json(s)}var Bt=x(async(r,e,t)=>{let s=D();e.status(200).json({data:[...s.map(n=>$(n)),"file-upload"]})});var zs={init:Fr};var dl=zs;exports.BaseController = ye; exports.default = dl; exports.getArkosConfig = M;
|