arkos 1.5.15-beta → 1.5.16-beta
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/exports/index.js +3 -1
- package/dist/cjs/exports/index.js.map +1 -1
- package/dist/cjs/modules/email/email.service.js +14 -8
- package/dist/cjs/modules/email/email.service.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +4 -3
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/file-upload/file-upload.router.js +9 -2
- package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js +4 -2
- package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/types/new-arkos-config.js.map +1 -1
- package/dist/cjs/types/{arkos-prisma-input.bak.js → upload.js} +1 -1
- package/dist/cjs/types/upload.js.map +1 -0
- package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js +3 -9
- package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js +14 -3
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js +5 -0
- package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +49 -13
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js +18 -18
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -1
- package/dist/cjs/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/esm/exports/index.js +2 -1
- package/dist/esm/exports/index.js.map +1 -1
- package/dist/esm/modules/email/email.service.js +14 -8
- package/dist/esm/modules/email/email.service.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +4 -3
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/file-upload/file-upload.router.js +9 -2
- package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js +4 -2
- package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
- package/dist/esm/types/index.js.map +1 -1
- package/dist/esm/types/new-arkos-config.js.map +1 -1
- package/dist/esm/types/upload.js +2 -0
- package/dist/esm/types/upload.js.map +1 -0
- package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js +3 -9
- package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js +14 -3
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js +5 -0
- package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +49 -13
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js +18 -18
- package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -1
- package/dist/esm/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/types/exports/index.d.ts +3 -26
- package/dist/types/types/index.d.ts +5 -4
- package/dist/types/types/new-arkos-config.d.ts +2 -2
- package/dist/types/types/upload.d.ts +10 -0
- package/dist/types/utils/arkos-router/types/index.d.ts +4 -4
- package/dist/types/utils/arkos-router/utils/helpers/upload-manager.d.ts +1 -0
- package/dist/types/utils/cli/utils/template-generator/templates/class-validator-dto-generator.d.ts +7 -0
- package/dist/types/utils/helpers/arkos-config.helpers.d.ts +5 -0
- package/package.json +1 -1
- package/dist/cjs/types/arkos-prisma-input.bak.js.map +0 -1
- package/dist/esm/types/arkos-prisma-input.bak.js +0 -2
- package/dist/esm/types/arkos-prisma-input.bak.js.map +0 -1
- package/dist/types/types/arkos-prisma-input.bak.d.ts +0 -237
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.ArkosRouter = exports.getArkosConfig = exports.loadEnvironmentVariables = exports.BaseController = void 0;
|
|
6
|
+
exports.isProduction = exports.ArkosRouter = exports.getArkosConfig = exports.loadEnvironmentVariables = exports.BaseController = void 0;
|
|
7
7
|
const base_controller_1 = require("./../modules/base/base.controller.js");
|
|
8
8
|
Object.defineProperty(exports, "BaseController", { enumerable: true, get: function () { return base_controller_1.BaseController; } });
|
|
9
9
|
const server_1 = require("../server.js");
|
|
@@ -12,6 +12,8 @@ const arkos_router_1 = __importDefault(require("../utils/arkos-router/index.js")
|
|
|
12
12
|
exports.ArkosRouter = arkos_router_1.default;
|
|
13
13
|
const dotenv_helpers_1 = require("../utils/dotenv.helpers.js");
|
|
14
14
|
Object.defineProperty(exports, "loadEnvironmentVariables", { enumerable: true, get: function () { return dotenv_helpers_1.loadEnvironmentVariables; } });
|
|
15
|
+
const arkos_config_helpers_1 = require("../utils/helpers/arkos-config.helpers.js");
|
|
16
|
+
Object.defineProperty(exports, "isProduction", { enumerable: true, get: function () { return arkos_config_helpers_1.isProduction; } });
|
|
15
17
|
const arkos = {
|
|
16
18
|
init: server_1.initApp,
|
|
17
19
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/exports/index.ts"],"names":[],"mappings":";;;;;;AACA,uEAAmE;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/exports/index.ts"],"names":[],"mappings":";;;;;;AACA,uEAAmE;AAiCjE,+FAjCO,gCAAc,OAiCP;AAhChB,sCAAoD;AAqClD,+FArCgB,uBAAc,OAqChB;AApChB,yEAAgD;AAqC9C,sBArCK,sBAAW,CAqCL;AA1Bb,4DAAmE;AAwBjE,yGAxBO,yCAAwB,OAwBP;AAtB1B,gFAAqE;AA2BnE,6FA3BO,mCAAY,OA2BP;AAnBd,MAAM,KAAK,GAAG;IACZ,IAAI,EAAE,gBAAO;CACd,CAAC;AAyBF,kBAAe,KAAK,CAAC","sourcesContent":["import { RouterConfig } from \"../types/router-config\";\nimport { BaseController } from \"./../modules/base/base.controller\";\nimport { initApp, getArkosConfig } from \"../server\";\nimport ArkosRouter from \"../utils/arkos-router\";\nimport { IArkosRouter } from \"../utils/arkos-router/types\";\nimport { ArkosRouteConfig } from \"../utils/arkos-router/types\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../types\";\nimport { ArkosConfig } from \"../types/new-arkos-config\";\nimport { ArkosInitConfig } from \"../types/arkos-config\";\nimport { loadEnvironmentVariables } from \"../utils/dotenv.helpers\";\nimport { ArkosFile } from \"../types/upload\";\nimport { isProduction } from \"../utils/helpers/arkos-config.helpers\";\n\n/**\n * Initializes the Arkos application.\n *\n * @module arkos\n * @property {Function} init - Function to initialize the app.\n */\nconst arkos = {\n init: initApp,\n};\n\nexport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n IArkosRouter,\n BaseController,\n ArkosConfig,\n ArkosInitConfig,\n RouterConfig,\n loadEnvironmentVariables,\n getArkosConfig,\n ArkosRouter,\n ArkosRouteConfig,\n ArkosFile,\n isProduction,\n};\n\n/**\n * Main entry point for the Arkos module.\n *\n * @module arkos\n */\nexport default arkos;\n"]}
|
|
@@ -32,10 +32,10 @@ class EmailService {
|
|
|
32
32
|
const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;
|
|
33
33
|
const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;
|
|
34
34
|
const name = emailConfigs?.name || process.env.EMAIL_NAME;
|
|
35
|
-
if (!host
|
|
35
|
+
if (!host) {
|
|
36
36
|
throw new app_error_1.default("You are trying to use emailService without setting email configurations. " +
|
|
37
|
-
"Please configure either arkosConfig.email or environment variables (EMAIL_HOST
|
|
38
|
-
docs: "Read more about emailService at https://www.arkosjs.com/docs/
|
|
37
|
+
"Please configure either arkosConfig.email or environment variables (EMAIL_HOST)", 500, {
|
|
38
|
+
docs: "Read more about emailService at https://www.arkosjs.com/docs/guides/email-service",
|
|
39
39
|
});
|
|
40
40
|
}
|
|
41
41
|
return {
|
|
@@ -43,10 +43,12 @@ class EmailService {
|
|
|
43
43
|
host,
|
|
44
44
|
port: port || 465,
|
|
45
45
|
secure: secure !== undefined ? secure : true,
|
|
46
|
-
auth:
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
46
|
+
auth: user && pass
|
|
47
|
+
? {
|
|
48
|
+
user,
|
|
49
|
+
pass,
|
|
50
|
+
}
|
|
51
|
+
: undefined,
|
|
50
52
|
name,
|
|
51
53
|
};
|
|
52
54
|
}
|
|
@@ -74,7 +76,11 @@ class EmailService {
|
|
|
74
76
|
}
|
|
75
77
|
const info = await transporter.sendMail({
|
|
76
78
|
...options,
|
|
77
|
-
from: fromAddress
|
|
79
|
+
from: fromAddress
|
|
80
|
+
? config.name
|
|
81
|
+
? `${config.name}<${fromAddress}>`
|
|
82
|
+
: fromAddress
|
|
83
|
+
: undefined,
|
|
78
84
|
text: options?.text ||
|
|
79
85
|
(typeof options.html === "string" && options.html
|
|
80
86
|
? (0, html_to_text_1.convert)(options.html)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":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MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AAjKD,oCAiKC;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,kBAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { SendMailOptions, Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n subject: string;\n} & SendMailOptions;\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/api-reference/the-email-service-class](https://www.arkosjs.com/docs/api-reference/the-email-service-class)\n */\nexport class EmailService {\n transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host || !user || !pass) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST, EMAIL_USER, EMAIL_PASSWORD)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/core-concepts/sending-emails\",\n }\n );\n }\n\n return {\n ...emailConfigs,\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth: {\n user,\n pass,\n },\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions & SendMailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress,\n text:\n options?.text ||\n (typeof options.html === \"string\" && options.html\n ? convert(options.html as string)\n : undefined),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
|
|
1
|
+
{"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAsE;AACtE,+CAAuC;AACvC,yCAA8C;AAC9C,iFAAwD;AAiCxD,MAAa,YAAY;IAUvB,YAAY,MAA8B;QAT1C,gBAAW,GAAuB,IAAI,CAAC;QAC/B,iBAAY,GAAiC,IAAI,CAAC;QASxD,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC7B,CAAC;IACH,CAAC;IAUO,cAAc;QACpB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,OAAO,IAAI,CAAC,YAAY,CAAC;QAC3B,CAAC;QAED,MAAM,EAAE,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AAW;gBACf,CAAC,CAAC,MAAM,CAAC,IAAI;oBACX,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,IAAI,WAAW,GAAG;oBAClC,CAAC,CAAC,WAAW;gBACf,CAAC,CAAC,SAAS;YACb,IAAI,EACF,OAAO,EAAE,IAAI;gBACb,CAAC,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI;oBAC/C,CAAC,CAAC,IAAA,sBAAO,EAAC,OAAO,CAAC,IAAc,CAAC;oBACjC,CAAC,CAAC,SAAS,CAAC;SACjB,CAAC,CAAC;QAEH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,CAAC;IACpC,CAAC;IAOM,KAAK,CAAC,gBAAgB,CAC3B,mBAAiC;QAEjC,IAAI,CAAC;YACH,MAAM,WAAW,GAAG,mBAAmB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACjE,MAAM,WAAW,CAAC,MAAM,EAAE,CAAC;YAC3B,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAMM,YAAY,CAAC,MAA6B;QAC/C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAOM,MAAM,CAAC,MAAM,CAAC,MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AAxKD,oCAwKC;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,kBAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { SendMailOptions, Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n subject: string;\n} & SendMailOptions;\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/api-reference/the-email-service-class](https://www.arkosjs.com/docs/api-reference/the-email-service-class)\n */\nexport class EmailService {\n transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/guides/email-service\",\n }\n );\n }\n\n return {\n ...emailConfigs,\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth:\n user && pass\n ? {\n user,\n pass,\n }\n : undefined,\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions & SendMailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress\n ? config.name\n ? `${config.name}<${fromAddress}>`\n : fromAddress\n : undefined,\n text:\n options?.text ||\n (typeof options.html === \"string\" && options.html\n ? convert(options.html as string)\n : undefined),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
|
|
@@ -42,8 +42,8 @@ const server_1 = require("../../server.js");
|
|
|
42
42
|
const multer_error_handler_1 = __importDefault(require("./utils/multer-error-handler.js"));
|
|
43
43
|
function errorHandler(err, req, res, _) {
|
|
44
44
|
console.error("[\x1b[31mError\x1b[0m]:", err);
|
|
45
|
-
err.statusCode = err.statusCode
|
|
46
|
-
err.status = err.status
|
|
45
|
+
err.statusCode = err.isOperational ? err.statusCode : 500;
|
|
46
|
+
err.status = err.isOperational ? err.status : "error";
|
|
47
47
|
let error = {
|
|
48
48
|
...err,
|
|
49
49
|
message: err.message,
|
|
@@ -146,7 +146,8 @@ function sendProductionError(err, _, res) {
|
|
|
146
146
|
});
|
|
147
147
|
}
|
|
148
148
|
process.on("SIGTERM", () => {
|
|
149
|
-
if (process.env.ARKOS_BUILD !== "true"
|
|
149
|
+
if (process.env.ARKOS_BUILD !== "true" ||
|
|
150
|
+
process.env.__SKIP_LISTEN === "true") {
|
|
150
151
|
process.exit();
|
|
151
152
|
}
|
|
152
153
|
else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler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GAAG,CAAC,CAAC,IAAI,CAAC;YACnB,MAAM,EAAE,OAAO;YACf,OAAO,EAAE,gDAAgD;YACzD,IAAI,EAAE,qBAAqB;YAC3B,IAAI,EAAE,EAAE;SACT,CAAC,CAAC;AACP,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\nimport multerErrorHandler from \"./utils/multer-error-handler\";\nimport { MulterError } from \"multer\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n switch (err.name) {\n case \"JsonWebTokenError\":\n error = errorControllerHelper.handleJWTError();\n break;\n case \"TokenExpiredError\":\n error = errorControllerHelper.handleJWTExpired();\n break;\n case \"PrismaClientValidationError\":\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n break;\n case \"PrismaClientInitializationError\":\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n break;\n case \"MulterError\":\n error = multerErrorHandler.handle(err as unknown as MulterError);\n break;\n }\n\n switch (err.code) {\n case \"P1000\":\n error = errorControllerHelper.handleAuthenticationError(err);\n break;\n case \"P1001\":\n error = errorControllerHelper.handleServerNotReachableError(err);\n break;\n case \"P1002\":\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n break;\n case \"P1003\":\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n break;\n case \"P2000\":\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n break;\n case \"P2001\":\n error = errorControllerHelper.handleRecordNotFoundError(err);\n break;\n case \"P2002\":\n error = errorControllerHelper.handleUniqueConstraintError(err);\n break;\n case \"P2003\":\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n break;\n case \"P2004\":\n error = errorControllerHelper.handleConstraintFailedError(err);\n break;\n case \"P2025\":\n error = errorControllerHelper.handleNonExistingRecord(err);\n break;\n case \"P3000\":\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n break;\n case \"P3001\":\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n break;\n case \"P3002\":\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n break;\n case \"P3003\":\n error = errorControllerHelper.handleVersionMismatchError(err);\n break;\n }\n\n const { message, ...rest } = error;\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n message: error.message,\n ...rest,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError({ message, ...rest }, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} _ - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, _: Request, res: Response): void {\n res.status(err.statusCode).json({\n ...err,\n message: err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} _ - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, _: Request, res: Response): void {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"InternalServerError\",\n meta: {},\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,+BAgGC;AApHD,qFAAuE;AACvE,yCAAsC;AACtC,wFAA8D;AAkB9D,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EAC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gD;YACzD,IAAI,EAAE,qBAAqB;YAC3B,IAAI,EAAE,EAAE;SACT,CAAC,CAAC;AACP,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;QAClC,OAAO,CAAC,GAAG,CAAC,aAAa,KAAK,MAAM,EACpC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\nimport multerErrorHandler from \"./utils/multer-error-handler\";\nimport { MulterError } from \"multer\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.isOperational ? err.statusCode : 500;\n err.status = err.isOperational ? err.status : \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n switch (err.name) {\n case \"JsonWebTokenError\":\n error = errorControllerHelper.handleJWTError();\n break;\n case \"TokenExpiredError\":\n error = errorControllerHelper.handleJWTExpired();\n break;\n case \"PrismaClientValidationError\":\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n break;\n case \"PrismaClientInitializationError\":\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n break;\n case \"MulterError\":\n error = multerErrorHandler.handle(err as unknown as MulterError);\n break;\n }\n\n switch (err.code) {\n case \"P1000\":\n error = errorControllerHelper.handleAuthenticationError(err);\n break;\n case \"P1001\":\n error = errorControllerHelper.handleServerNotReachableError(err);\n break;\n case \"P1002\":\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n break;\n case \"P1003\":\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n break;\n case \"P2000\":\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n break;\n case \"P2001\":\n error = errorControllerHelper.handleRecordNotFoundError(err);\n break;\n case \"P2002\":\n error = errorControllerHelper.handleUniqueConstraintError(err);\n break;\n case \"P2003\":\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n break;\n case \"P2004\":\n error = errorControllerHelper.handleConstraintFailedError(err);\n break;\n case \"P2025\":\n error = errorControllerHelper.handleNonExistingRecord(err);\n break;\n case \"P3000\":\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n break;\n case \"P3001\":\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n break;\n case \"P3002\":\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n break;\n case \"P3003\":\n error = errorControllerHelper.handleVersionMismatchError(err);\n break;\n }\n\n const { message, ...rest } = error;\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n message: error.message,\n ...rest,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError({ message, ...rest }, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} _ - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, _: Request, res: Response): void {\n res.status(err.statusCode).json({\n ...err,\n message: err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} _ - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, _: Request, res: Response): void {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"InternalServerError\",\n meta: {},\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.ARKOS_BUILD !== \"true\" ||\n process.env.__SKIP_LISTEN === \"true\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
@@ -18,6 +18,7 @@ const fs_helpers_1 = require("../../utils/helpers/fs.helpers.js");
|
|
|
18
18
|
const path_1 = __importDefault(require("path"));
|
|
19
19
|
const arkos_router_1 = __importDefault(require("../../utils/arkos-router/index.js"));
|
|
20
20
|
const file_upload_json_schema_generator_1 = __importDefault(require("./utils/file-upload-json-schema-generator.js"));
|
|
21
|
+
const app_error_1 = __importDefault(require("../error-handler/utils/app-error.js"));
|
|
21
22
|
function getFileUploadRouter(arkosConfig) {
|
|
22
23
|
const router = (0, arkos_router_1.default)();
|
|
23
24
|
const { fileUpload } = arkosConfig;
|
|
@@ -74,10 +75,16 @@ function getFileUploadRouter(arkosConfig) {
|
|
|
74
75
|
etag: true,
|
|
75
76
|
lastModified: true,
|
|
76
77
|
dotfiles: "ignore",
|
|
77
|
-
fallthrough:
|
|
78
|
+
fallthrough: false,
|
|
78
79
|
index: false,
|
|
79
80
|
cacheControl: true,
|
|
80
|
-
}, fileUpload?.expressStatic || {})),
|
|
81
|
+
}, fileUpload?.expressStatic || {})), (err, req, _res, next) => {
|
|
82
|
+
if (err.code === "ENOENT") {
|
|
83
|
+
const filepath = req.path.replace(`/api/${arkosConfig.fileUpload?.baseRoute}`.replace("//", "/"), "");
|
|
84
|
+
throw new app_error_1.default(`File ${filepath} was not found`, 404, "FileNotFound", { filepath });
|
|
85
|
+
}
|
|
86
|
+
next(err);
|
|
87
|
+
}, ...(0, routers_helpers_1.processMiddleware)(interceptors?.onFindFileError, { type: "error" }));
|
|
81
88
|
}
|
|
82
89
|
if (!(0, base_router_helpers_1.isEndpointDisabled)(routerConfig, "uploadFile")) {
|
|
83
90
|
router.post((0, routers_helpers_1.createRouteConfig)(arkosConfig, "uploadFile", baseRoutePrefix, `:fileType`, routerConfig, "file-upload", authConfigs), ...(0, routers_helpers_1.processMiddleware)(interceptors?.beforeUploadFile), file_upload_controller_1.default.uploadFile, ...(0, routers_helpers_1.processMiddleware)(interceptors?.afterUploadFile), base_middlewares_1.sendResponse, ...(0, routers_helpers_1.processMiddleware)(interceptors?.onUploadFileError, { type: "error" }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AAsBA,kDAgKC;AArLD,+DAAiE;AACjE,sFAA4D;AA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AAY,EAAE,iBAAiB,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACzE,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,IAAA,wCAAkB,EAAC,YAAY,EAAE,YAAY,CAAC,EAAE,CAAC;QACpD,MAAM,CAAC,MAAM,CACX,IAAA,mCAAiB,EACf,WAAW,EACX,YAAY,EACZ,eAAe,EACf,qBAAqB,EACrB,YAAY,EACZ,aAAa,EACb,WAAW,CACZ,EACD,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,gBAAgB,CAAC,EACpD,gCAAoB,CAAC,UAAU,EAC/B,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,eAAe,CAAC,EACnD,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,iBAAiB,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACzE,CAAC;IACJ,CAAC;IAED,0BAAe,CAAC,oBAAoB,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport fileUploadController from \"./file-upload.controller\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { sendResponse } from \"../base/base.middlewares\";\nimport {\n createRouteConfig,\n processMiddleware,\n} from \"../../utils/helpers/routers.helpers\";\nimport { adjustRequestUrl } from \"./utils/helpers/file-upload.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\nimport routerValidator from \"../base/utils/router-validator\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\nimport { ArkosConfig } from \"../../exports\";\nimport path from \"path\";\nimport ArkosRouter from \"../../utils/arkos-router\";\nimport { FileUploadRouterEndpoint } from \"../../types/router-config\";\nimport fileUploadJsonSchemaGenerator from \"./utils/file-upload-json-schema-generator\";\n\nexport function getFileUploadRouter(arkosConfig: ArkosConfig) {\n const router = ArkosRouter();\n const { fileUpload } = arkosConfig;\n\n if (!fileUpload?.enabled === false) return router;\n\n const moduleComponents = getModuleComponents(\"file-upload\");\n let {\n interceptors = {} as any,\n authConfigs = {} as AuthConfigs,\n router: customRouterModule,\n }: any = {};\n\n if (moduleComponents)\n ({\n interceptors = {},\n authConfigs = {},\n router: customRouterModule,\n } = moduleComponents);\n\n const routerConfig = customRouterModule?.config || {};\n if (routerConfig?.disable === true) return router;\n\n const customRouter = customRouterModule?.default as Router;\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n // Strip leading slash so createRouteConfig can prepend its own \"/\"\n // e.g. \"/api/uploads/\" → \"api/uploads/\" → createRouteConfig builds \"/api/uploads/*\"\n const baseRoutePrefix = basePathname.slice(1);\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(basePathname, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from file-upload.router.${getUserFileExtension()} is not a valid express or arkos Router.`\n );\n }\n\n const endpoints: FileUploadRouterEndpoint[] = [\n \"findFile\",\n \"uploadFile\",\n \"updateFile\",\n \"deleteFile\",\n ];\n\n for (const endpoint of endpoints) {\n const endpointConfig = routerConfig[endpoint];\n if (endpointConfig?.experimental?.openapi === false) continue;\n routerConfig[endpoint] = {\n ...(endpointConfig || {}),\n experimental: {\n ...(endpointConfig?.experimental || {}),\n openapi: fileUploadJsonSchemaGenerator.getOpenApiConfig(\n endpointConfig,\n endpoint\n ),\n },\n };\n }\n\n if (!isEndpointDisabled(routerConfig, \"findFile\")) {\n const baseUploadDirFullPath = path.resolve(\n path\n .join(process.cwd(), fileUpload?.baseUploadDir || \"uploads\")\n .replaceAll(\"//\", \"/\")\n );\n router.get(\n createRouteConfig(\n arkosConfig,\n \"findFile\",\n baseRoutePrefix,\n `*`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeFindFile),\n adjustRequestUrl,\n express.static(\n baseUploadDirFullPath,\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStatic || {}\n )\n ),\n ...processMiddleware(interceptors?.onFindFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"uploadFile\")) {\n router.post(\n createRouteConfig(\n arkosConfig,\n \"uploadFile\",\n baseRoutePrefix,\n `:fileType`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeUploadFile),\n fileUploadController.uploadFile,\n ...processMiddleware(interceptors?.afterUploadFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUploadFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updateFile\")) {\n router.patch(\n createRouteConfig(\n arkosConfig,\n \"updateFile\",\n baseRoutePrefix,\n `:fileType/:fileName`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeUpdateFile),\n fileUploadController.updateFile,\n ...processMiddleware(interceptors?.afterUpdateFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"deleteFile\")) {\n router.delete(\n createRouteConfig(\n arkosConfig,\n \"deleteFile\",\n baseRoutePrefix,\n `:fileType/:fileName`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeDeleteFile),\n fileUploadController.deleteFile,\n ...processMiddleware(interceptors?.afterDeleteFile),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteFileError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(\"file-upload\", router);\n return router;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AA4BA,kDAqLC;AAhND,+DAAiE;AACjE,sFAA4D;AAC5D,sDAA8B;AAC9B,4FAA6D;AAE7D,+DAAwD;AACxD,yEAG6C;AAC7C,6EAAuE;AACvE,mFAA+E;AAC/E,oFAA2D;AAC3D,sFAA6D;AAC7D,+DAAsE;AAOtE,gDAAwB;AACxB,4EAAmD;AAEnD,kHAAsF;AACtF,iFAAwD;AAExD,SAAgB,mBAAmB,CAAC,WAAwB;IAC1D,MAAM,MAAM,GAAG,IAAA,sBAAW,GAAE,CAAC;IAC7B,MAAM,EAAE,UAAU,EAAE,GAAG,WAAW,CAAC;IAEnC,IAAI,CAAC,UAAU,EAAE,OAAO,KAAK,KAAK;QAAE,OAAO,MAAM,CAAC;IAElD,MAAM,gBAAgB,GAAG,IAAA,oCAAmB,EAAC,aAAa,CAAC,CAAC;IAC5D,IAAI,EACF,YAAY,GAAG,EAAS,EACxB,WAAW,GAAG,EAAiB,EAC/B,MAAM,EAAE,kBAAkB,GAC3B,GAAQ,EAAE,CAAC;IAEZ,IAAI,gBAAgB;QAClB,CAAC;YACC,YAAY,GAAG,EAAE;YACjB,WAAW,GAAG,EAAE;YAChB,MAAM,EAAE,kBAAkB;SAC3B,GAAG,gBAAgB,CAAC,CAAC;IAExB,MAAM,YAAY,GAAG,kBAAkB,EAAE,MAAM,IAAI,EAAE,CAAC;IACtD,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAElD,MAAM,YAAY,GAAG,kBAAkB,EAAE,OAAiB,CAAC;IAC3D,IAAI,YAAY,GAAG,UAAU,EAAE,SAAS,IAAI,eAAe,CAAC;IAE5D,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,YAAY,GAAG,GAAG,GAAG,YAAY,CAAC;IACrE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B,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport fileUploadController from \"./file-upload.controller\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { sendResponse } from \"../base/base.middlewares\";\nimport {\n createRouteConfig,\n processMiddleware,\n} from \"../../utils/helpers/routers.helpers\";\nimport { adjustRequestUrl } from \"./utils/helpers/file-upload.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\nimport routerValidator from \"../base/utils/router-validator\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\nimport {\n ArkosConfig,\n ArkosNextFunction,\n ArkosRequest,\n ArkosResponse,\n} from \"../../exports\";\nimport path from \"path\";\nimport ArkosRouter from \"../../utils/arkos-router\";\nimport { FileUploadRouterEndpoint } from \"../../types/router-config\";\nimport fileUploadJsonSchemaGenerator from \"./utils/file-upload-json-schema-generator\";\nimport AppError from \"../error-handler/utils/app-error\";\n\nexport function getFileUploadRouter(arkosConfig: ArkosConfig) {\n const router = ArkosRouter();\n const { fileUpload } = arkosConfig;\n\n if (!fileUpload?.enabled === false) return router;\n\n const moduleComponents = getModuleComponents(\"file-upload\");\n let {\n interceptors = {} as any,\n authConfigs = {} as AuthConfigs,\n router: customRouterModule,\n }: any = {};\n\n if (moduleComponents)\n ({\n interceptors = {},\n authConfigs = {},\n router: customRouterModule,\n } = moduleComponents);\n\n const routerConfig = customRouterModule?.config || {};\n if (routerConfig?.disable === true) return router;\n\n const customRouter = customRouterModule?.default as Router;\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n // Strip leading slash so createRouteConfig can prepend its own \"/\"\n // e.g. \"/api/uploads/\" → \"api/uploads/\" → createRouteConfig builds \"/api/uploads/*\"\n const baseRoutePrefix = basePathname.slice(1);\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(basePathname, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from file-upload.router.${getUserFileExtension()} is not a valid express or arkos Router.`\n );\n }\n\n const endpoints: FileUploadRouterEndpoint[] = [\n \"findFile\",\n \"uploadFile\",\n \"updateFile\",\n \"deleteFile\",\n ];\n\n for (const endpoint of endpoints) {\n const endpointConfig = routerConfig[endpoint];\n if (endpointConfig?.experimental?.openapi === false) continue;\n routerConfig[endpoint] = {\n ...(endpointConfig || {}),\n experimental: {\n ...(endpointConfig?.experimental || {}),\n openapi: fileUploadJsonSchemaGenerator.getOpenApiConfig(\n endpointConfig,\n endpoint\n ),\n },\n };\n }\n\n if (!isEndpointDisabled(routerConfig, \"findFile\")) {\n const baseUploadDirFullPath = path.resolve(\n path\n .join(process.cwd(), fileUpload?.baseUploadDir || \"uploads\")\n .replaceAll(\"//\", \"/\")\n );\n router.get(\n createRouteConfig(\n arkosConfig,\n \"findFile\",\n baseRoutePrefix,\n `*`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeFindFile),\n adjustRequestUrl,\n express.static(\n baseUploadDirFullPath,\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: false,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStatic || {}\n )\n ),\n (\n err: any,\n req: ArkosRequest,\n _res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (err.code === \"ENOENT\") {\n const filepath = req.path.replace(\n `/api/${arkosConfig.fileUpload?.baseRoute}`.replace(\"//\", \"/\"),\n \"\"\n );\n throw new AppError(\n `File ${filepath} was not found`,\n 404,\n \"FileNotFound\",\n { filepath }\n );\n }\n\n next(err);\n },\n ...processMiddleware(interceptors?.onFindFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"uploadFile\")) {\n router.post(\n createRouteConfig(\n arkosConfig,\n \"uploadFile\",\n baseRoutePrefix,\n `:fileType`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeUploadFile),\n fileUploadController.uploadFile,\n ...processMiddleware(interceptors?.afterUploadFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUploadFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updateFile\")) {\n router.patch(\n createRouteConfig(\n arkosConfig,\n \"updateFile\",\n baseRoutePrefix,\n `:fileType/:fileName`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeUpdateFile),\n fileUploadController.updateFile,\n ...processMiddleware(interceptors?.afterUpdateFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"deleteFile\")) {\n router.delete(\n createRouteConfig(\n arkosConfig,\n \"deleteFile\",\n baseRoutePrefix,\n `:fileType/:fileName`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeDeleteFile),\n fileUploadController.deleteFile,\n ...processMiddleware(interceptors?.afterDeleteFile),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteFileError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(\"file-upload\", router);\n return router;\n}\n"]}
|
|
@@ -71,7 +71,7 @@ class OpenAPIchemaConverter {
|
|
|
71
71
|
return flattened;
|
|
72
72
|
}
|
|
73
73
|
if (schema.type === "array" && schema.items) {
|
|
74
|
-
const arrayPrefix = prefix ? `${prefix}[0]
|
|
74
|
+
const arrayPrefix = prefix && schema.items?.format === "binary" ? prefix : `${prefix}[0]`;
|
|
75
75
|
if (schema.items.type === "array") {
|
|
76
76
|
flattened.push(...this.flattenSchemaCore(schema.items, arrayPrefix, visitedRefs));
|
|
77
77
|
}
|
|
@@ -106,7 +106,9 @@ class OpenAPIchemaConverter {
|
|
|
106
106
|
visitedRefs.delete(refPath);
|
|
107
107
|
}
|
|
108
108
|
else if (value.type === "array" && value.items) {
|
|
109
|
-
const arrayPrefix =
|
|
109
|
+
const arrayPrefix = paramName && value.items?.format == "binary"
|
|
110
|
+
? paramName
|
|
111
|
+
: `${paramName}[0]`;
|
|
110
112
|
if (value.items.type === "array") {
|
|
111
113
|
flattened.push(...this.flattenSchemaCore(value.items, arrayPrefix, visitedRefs));
|
|
112
114
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi-schema-converter.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/openapi-schema-converter.ts"],"names":[],"mappings":";;;;;AACA,qEAAwE;AACxE,4EAAiD;AACjD,sGAA0E;AAC1E,+CAAoD;AAOpD,MAAM,qBAAqB;IAGzB;QACE,IAAI,CAAC,qBAAqB,GAAG,CAAC,MAAW,EAAE,EAAE;YAC3C,MAAM,kBAAkB,GAAG,IAAA,uBAAc,GAAE,EAAE,UAAU,EAAE,QAAQ,CAAC;YAClE,MAAM,EAAE,GACN,kBAAkB,KAAK,KAAK;gBAC1B,CAAC,CAAC,4BAAe;gBACjB,CAAC,CAAC,wCAA0B,CAAC;YAEjC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC;QACpB,CAAC,CAAC;IACJ,CAAC;IAQO,YAAY,CAAC,KAAU;QAC7B,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QAEzB,IAAI,IAAA,4BAAW,EAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAEpC,IAAI,IAAA,wBAAO,EAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAEhC,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI;YAAE,OAAO,I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EAAE,EAAE,CAAC,CAAC;YACpD,EAAE,EAAE,SAAS;YACb,IAAI;YACJ,QAAQ;YACR,MAAM;SACP,CAAC,CAAC,CAAC;IACN,CAAC;IAED,UAAU,CAAC,UAAe,EAAE,OAAe;QACzC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE,CAAC;YACzC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC7C,IAAI,OAAO,GAAG,UAAU,CAAC;QAEzB,KAAK,MAAM,IAAI,IAAI,IAAI,EAAE,CAAC;YACxB,IAAI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC;gBAC3C,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;YAC1B,CAAC;iBAAM,CAAC;gBACN,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF;AAED,MAAM,sBAAsB,GAAG,IAAI,qBAAqB,EAAE,CAAC;AAE3D,kBAAe,sBAAsB,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { isClass, isZodSchema } from \"../../../../utils/dynamic-loader\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"./class-validator-to-json-schema\";\nimport { getArkosConfig } from \"../../../../server\";\n\n/**\n * Singleton class responsible for converting various schema formats (Zod, Class DTOs, JSON Schema)\n * into OpenAPI-compliant schema objects. Handles shorthand syntax for responses, request bodies,\n * and parameters.\n */\nclass OpenAPIchemaConverter {\n private validatorToJsonSchema: (schema: any) => any;\n\n constructor() {\n this.validatorToJsonSchema = (schema: any) => {\n const validationResolver = getArkosConfig()?.validation?.resolver;\n const fn =\n validationResolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n return fn(schema);\n };\n }\n\n /**\n * Checks if a value is a schema-like object (Zod, Class, or JSON Schema).\n *\n * @param value - The value to check\n * @returns True if the value is a schema-like object\n */\n private isSchemaLike(value: any): boolean {\n if (!value) return false;\n\n if (isZodSchema(value)) return true;\n\n if (isClass(value)) return true;\n\n if (this.isPlainObject(value) && value.type) return true;\n\n return false;\n }\n\n /**\n * Checks if a value is a plain JavaScript object.\n *\n * @param value - The value to check\n * @returns True if the value is a plain object\n */\n private isPlainObject(value: any): boolean {\n return Object.prototype.toString.call(value) === \"[object Object]\";\n }\n\n /**\n * Converts a schema-like object (Zod, Class, or JSON Schema) into a JSON Schema object.\n *\n * @param schema - The schema to convert\n * @returns The JSON Schema representation, or undefined if schema is null/undefined\n */\n private convertToJsonSchema(schema: any): any {\n if (this.isPlainObject(schema) && schema?.type) return schema;\n\n if (isZodSchema(schema) || isClass(schema))\n return this.validatorToJsonSchema(schema);\n\n throw new Error(\n `Unsupported schema type. Expected Zod schema, class constructor, or JSON Schema object.`\n );\n }\n\n /**\n * Gets the default description for an HTTP status code.\n *\n * @param statusCode - The HTTP status code\n * @returns A human-readable default description\n */\n private getDefaultDescription(statusCode: string): string {\n const defaults: Record<string, string> = {\n \"200\": \"Success\",\n \"201\": \"Created\",\n \"202\": \"Accepted\",\n \"204\": \"No Content\",\n \"400\": \"Bad Request\",\n \"401\": \"Unauthorized\",\n \"403\": \"Forbidden\",\n \"404\": \"Not Found\",\n \"409\": \"Conflict\",\n \"422\": \"Unprocessable Entity\",\n \"500\": \"Internal Server Error\",\n \"502\": \"Bad Gateway\",\n \"503\": \"Service Unavailable\",\n };\n\n return defaults[statusCode] || \"Response\";\n }\n\n /**\n * Core flattening logic that converts a JSON schema into bracket notation.\n * Handles nested objects, arrays, and circular references.\n *\n * @param schema - The JSON schema to flatten\n * @param prefix - Optional prefix for nested properties\n * @param visitedRefs - Set to track circular references\n * @returns Array of flattened field descriptors\n */\n flattenSchemaCore(\n schema: any,\n prefix = \"\",\n visitedRefs = new Set<string>()\n ): Array<{ name: string; schema: any; required: boolean }> {\n const flattened: Array<{ name: string; schema: any; required: boolean }> =\n [];\n\n if (schema.$ref) {\n const refPath = schema.$ref;\n if (visitedRefs.has(refPath)) return flattened;\n\n visitedRefs.add(refPath);\n const resolvedSchema = this.resolveRef(schema, refPath);\n if (resolvedSchema) {\n flattened.push(\n ...this.flattenSchemaCore(resolvedSchema, prefix, visitedRefs)\n );\n }\n visitedRefs.delete(refPath);\n return flattened;\n }\n\n if (schema.type === \"array\" && schema.items) {\n const arrayPrefix = prefix ? `${prefix}[0]` : \"[0]\";\n\n // Check if items is an array FIRST, before checking for object\n if (schema.items.type === \"array\") {\n flattened.push(\n ...this.flattenSchemaCore(schema.items, arrayPrefix, visitedRefs)\n );\n } else if (schema.items.properties || schema.items.type === \"object\") {\n flattened.push(\n ...this.flattenSchemaCore(schema.items, arrayPrefix, visitedRefs)\n );\n } else if (schema.items.type || schema.items.$ref) {\n flattened.push({\n name: arrayPrefix,\n schema: {\n type: schema.items.type,\n ...(schema.items.enum && { enum: schema.items.enum }),\n ...(schema.items.format && { format: schema.items.format }),\n },\n required: false,\n });\n }\n\n return flattened;\n }\n\n if ((schema.type === \"object\" || !schema.type) && schema.properties) {\n for (const [key, value] of Object.entries(schema.properties) as any) {\n const paramName = prefix ? `${prefix}[${key}]` : key;\n\n if (value.$ref) {\n const refPath = value.$ref;\n if (visitedRefs.has(refPath)) continue;\n\n visitedRefs.add(refPath);\n const resolvedSchema = this.resolveRef(schema, refPath);\n\n if (resolvedSchema) {\n flattened.push(\n ...this.flattenSchemaCore(resolvedSchema, paramName, visitedRefs)\n );\n }\n visitedRefs.delete(refPath);\n } else if (value.type === \"array\" && value.items) {\n const arrayPrefix = `${paramName}[0]`;\n if (value.items.type === \"array\") {\n flattened.push(\n ...this.flattenSchemaCore(value.items, arrayPrefix, visitedRefs)\n );\n } else if (value.items.type === \"object\" || value.items.properties) {\n flattened.push(\n ...this.flattenSchemaCore(value.items, arrayPrefix, visitedRefs)\n );\n } else {\n flattened.push({\n name: arrayPrefix,\n schema: {\n type: value.items.type,\n ...(value.items.enum && { enum: value.items.enum }),\n ...(value.items.format && { format: value.items.format }),\n },\n required: false,\n });\n }\n } else if (value.type === \"object\" && value.properties) {\n flattened.push(\n ...this.flattenSchemaCore(value, paramName, visitedRefs)\n );\n } else {\n flattened.push({\n name: paramName,\n schema: {\n type: value.type,\n ...(value.enum && { enum: value.enum }),\n ...(value.format && { format: value.format }),\n },\n required: schema.required?.includes(key) || false,\n });\n }\n }\n return flattened;\n }\n\n // Handle primitive types with prefix\n if (schema.type && prefix) {\n flattened.push({\n name: prefix,\n schema: {\n type: schema.type,\n ...(schema.enum && { enum: schema.enum }),\n ...(schema.format && { format: schema.format }),\n },\n required: false,\n });\n }\n\n return flattened;\n }\n\n /**\n * Flattens a JSON schema while preserving the schema structure.\n * Converts nested objects and arrays into bracket notation properties.\n * Used for multipart/form-data schema representation.\n *\n * @param schema - The JSON schema to flatten\n * @returns A flattened schema object with bracket notation properties\n */\n flattenSchema(schema: any): any {\n const flattened = this.flattenSchemaCore(schema);\n\n // Convert the flattened array into a schema object\n const flattenedSchema: any = {\n ...schema,\n properties: {},\n required: [],\n };\n\n for (const item of flattened) {\n flattenedSchema.properties[item.name] = item.schema;\n if (item.required) {\n flattenedSchema.required.push(item.name);\n }\n }\n\n // Remove empty required array if no required fields\n if (flattenedSchema.required.length === 0) {\n delete flattenedSchema.required;\n }\n\n return flattenedSchema;\n }\n\n /**\n * Converts a response definition (shorthand, medium, or full format) into a standard\n * OpenAPI ResponseObject.\n *\n * Supports three formats:\n * 1. Shorthand: ProfileDto → assumes application/json + default description\n * 2. Medium: { content: ProfileDto, description: \"...\" } → custom description\n * 3. Full: { content: { \"application/json\": { schema: ProfileDto } } } → full control\n *\n * @param statusCode - The HTTP status code for this response\n * @param definition - The response definition to convert\n * @returns A standard OpenAPI ResponseObject\n */\n convertResponseDefinition(\n statusCode: string,\n definition: any\n ): OpenAPIV3.ResponseObject {\n if (!definition.content && this.isSchemaLike(definition)) {\n return {\n description: this.getDefaultDescription(statusCode),\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition),\n },\n },\n };\n }\n\n if (definition.content && this.isSchemaLike(definition.content)) {\n return {\n description:\n definition.description || this.getDefaultDescription(statusCode),\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition.content),\n },\n },\n ...(definition.headers && { headers: definition.headers }),\n ...(definition.links && { links: definition.links }),\n };\n }\n\n if (definition.content) {\n const converted: OpenAPIV3.ResponseObject = {\n description:\n definition.description || this.getDefaultDescription(statusCode),\n content: {},\n };\n\n for (const [mediaType, mediaObj] of Object.entries(\n definition.content\n ) as any[]) {\n converted.content![mediaType] = {\n ...mediaObj,\n schema: this.convertToJsonSchema(mediaObj.schema),\n };\n }\n\n if (definition.headers) converted.headers = definition.headers;\n if (definition.links) converted.links = definition.links;\n\n return converted;\n }\n\n return definition;\n }\n\n /**\n * Converts a request body definition (shorthand, medium, or full format) into a standard\n * OpenAPI RequestBodyObject.\n *\n * Supports three formats:\n * 1. Shorthand: CreateUserDto → assumes application/json + required: true\n * 2. Medium: { content: CreateUserDto, required?: boolean } → custom config\n * 3. Full: { content: { \"application/json\": { schema: CreateUserDto } } } → full control\n *\n * For multipart/form-data, automatically converts the schema into an array of parameters.\n *\n * @param definition - The request body definition to convert\n * @returns A standard OpenAPI RequestBodyObject, or undefined if no definition provided\n */\n convertRequestBodyDefinition(\n definition: any\n ): OpenAPIV3.RequestBodyObject | undefined {\n if (!definition) return undefined;\n\n if (!definition.content && this.isSchemaLike(definition)) {\n return {\n required: true,\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition),\n },\n },\n };\n }\n\n if (definition.content && this.isSchemaLike(definition.content)) {\n return {\n required: definition.required === false ? false : true,\n description: definition.description,\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition.content),\n },\n },\n };\n }\n\n if (definition.content) {\n const converted: OpenAPIV3.RequestBodyObject = {\n required: definition.required ?? true,\n content: {},\n };\n\n if (definition.description)\n converted.description = definition.description;\n\n for (const [mediaType, mediaObj] of Object.entries(\n definition.content\n ) as any[]) {\n const jsonSchema = this.convertToJsonSchema(mediaObj.schema);\n\n // For multipart/form-data, flatten the schema into bracket notation\n if (mediaType === \"multipart/form-data\") {\n converted.content[mediaType] = {\n ...mediaObj,\n schema: this.flattenSchema(jsonSchema),\n };\n } else {\n // For other media types (like application/json), keep the full schema\n converted.content[mediaType] = {\n ...mediaObj,\n schema: jsonSchema,\n };\n }\n }\n\n return converted;\n }\n\n return definition;\n }\n\n /**\n * Converts an array of parameter definitions, transforming any Zod/Class schemas\n * into JSON Schema objects.\n *\n * @param parameters - Array of parameter definitions to convert\n * @returns Array of standard OpenAPI ParameterObjects, or undefined if no parameters provided\n */\n convertParameters(\n parameters: any[] | undefined\n ): (OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject)[] | undefined {\n if (!parameters) return undefined;\n\n return parameters.map((param) => {\n if (param.$ref) return param;\n\n if (param.schema)\n return {\n ...param,\n schema: this.convertToJsonSchema(param.schema),\n };\n\n return param;\n });\n }\n\n /**\n * Converts all responses in a responses object, handling shorthand, medium, and full formats.\n *\n * @param responses - Object containing response definitions keyed by status code\n * @returns Object with converted OpenAPI ResponseObjects\n */\n convertResponses(\n responses: Record<string, any> | undefined\n ): Record<string, OpenAPIV3.ResponseObject> | undefined {\n if (!responses) return undefined;\n\n const converted: Record<string, OpenAPIV3.ResponseObject> = {};\n\n for (const [statusCode, definition] of Object.entries(responses)) {\n converted[statusCode] = this.convertResponseDefinition(\n statusCode,\n definition\n );\n }\n\n return converted;\n }\n\n /**\n * Converts a complete OpenAPI operation configuration, processing responses, requestBody,\n * and parameters to handle shorthand syntax and schema conversions.\n *\n * @param config - The OpenAPI operation configuration to convert\n * @returns The converted configuration with all schemas transformed to JSON Schema\n */\n convertOpenAPIConfig(config: any): any {\n if (!config || config === false) return config;\n\n const converted = { ...config };\n\n if (config.responses)\n converted.responses = this.convertResponses(config.responses);\n\n if (config.requestBody)\n converted.requestBody = this.convertRequestBodyDefinition(\n config.requestBody\n );\n\n if (config.parameters)\n converted.parameters = this.convertParameters(config.parameters);\n\n return converted;\n }\n\n /**\n * Converts a JSON schema to OpenAPI parameter objects with flattened paths.\n * This is used for query/path/header parameters.\n *\n * @param paramType - The parameter location (query, path, header, cookie)\n * @param schema - The JSON schema to convert\n * @param prefix - Optional prefix for nested properties\n * @param visitedRefs - Set to track circular references\n * @returns Array of OpenAPI parameter objects\n */\n jsonSchemaToOpenApiParameters(\n paramType: string,\n schema: any,\n prefix = \"\",\n visitedRefs = new Set<string>()\n ): any[] {\n const flattened = this.flattenSchemaCore(schema, prefix, visitedRefs);\n\n return flattened.map(({ name, schema, required }) => ({\n in: paramType,\n name,\n required,\n schema,\n }));\n }\n\n resolveRef(rootSchema: any, refPath: string): any {\n if (!refPath.startsWith(\"#/properties/\")) {\n return null;\n }\n\n const path = refPath.substring(2).split(\"/\");\n let current = rootSchema;\n\n for (const part of path) {\n if (current && current[part] !== undefined) {\n current = current[part];\n } else {\n return null;\n }\n }\n\n return current;\n }\n}\n\nconst openApiSchemaConverter = new OpenAPIchemaConverter();\n\nexport default openApiSchemaConverter;\n"]}
|
|
1
|
+
{"version":3,"file":"openapi-schema-converter.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/openapi-schema-converter.ts"],"names":[],"mappings":";;;;;AACA,qEAAwE;AACxE,4EAAiD;AACjD,sGAA0E;AAC1E,+CAAoD;AAOpD,MAAM,qBAAqB;IAGzB;QACE,IAAI,CAAC,qBAAqB,GAAG,CAAC,MAAW,EAAE,EAAE;YAC3C,MAAM,kBAAkB,GAAG,IAAA,uBAAc,GAAE,EAAE,UAAU,EAAE,QAAQ,CAAC;YAClE,MAAM,EAAE,GACN,kBAAkB,KAAK,KAAK;gBAC1B,CAAC,CAAC,4BAAe;gBACjB,CAAC,CAAC,wCAA0B,CAAC;YAEjC,OAAO,EAAE,CAAC,MAA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CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { isClass, isZodSchema } from \"../../../../utils/dynamic-loader\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"./class-validator-to-json-schema\";\nimport { getArkosConfig } from \"../../../../server\";\n\n/**\n * Singleton class responsible for converting various schema formats (Zod, Class DTOs, JSON Schema)\n * into OpenAPI-compliant schema objects. Handles shorthand syntax for responses, request bodies,\n * and parameters.\n */\nclass OpenAPIchemaConverter {\n private validatorToJsonSchema: (schema: any) => any;\n\n constructor() {\n this.validatorToJsonSchema = (schema: any) => {\n const validationResolver = getArkosConfig()?.validation?.resolver;\n const fn =\n validationResolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n return fn(schema);\n };\n }\n\n /**\n * Checks if a value is a schema-like object (Zod, Class, or JSON Schema).\n *\n * @param value - The value to check\n * @returns True if the value is a schema-like object\n */\n private isSchemaLike(value: any): boolean {\n if (!value) return false;\n\n if (isZodSchema(value)) return true;\n\n if (isClass(value)) return true;\n\n if (this.isPlainObject(value) && value.type) return true;\n\n return false;\n }\n\n /**\n * Checks if a value is a plain JavaScript object.\n *\n * @param value - The value to check\n * @returns True if the value is a plain object\n */\n private isPlainObject(value: any): boolean {\n return Object.prototype.toString.call(value) === \"[object Object]\";\n }\n\n /**\n * Converts a schema-like object (Zod, Class, or JSON Schema) into a JSON Schema object.\n *\n * @param schema - The schema to convert\n * @returns The JSON Schema representation, or undefined if schema is null/undefined\n */\n private convertToJsonSchema(schema: any): any {\n if (this.isPlainObject(schema) && schema?.type) return schema;\n\n if (isZodSchema(schema) || isClass(schema))\n return this.validatorToJsonSchema(schema);\n\n throw new Error(\n `Unsupported schema type. Expected Zod schema, class constructor, or JSON Schema object.`\n );\n }\n\n /**\n * Gets the default description for an HTTP status code.\n *\n * @param statusCode - The HTTP status code\n * @returns A human-readable default description\n */\n private getDefaultDescription(statusCode: string): string {\n const defaults: Record<string, string> = {\n \"200\": \"Success\",\n \"201\": \"Created\",\n \"202\": \"Accepted\",\n \"204\": \"No Content\",\n \"400\": \"Bad Request\",\n \"401\": \"Unauthorized\",\n \"403\": \"Forbidden\",\n \"404\": \"Not Found\",\n \"409\": \"Conflict\",\n \"422\": \"Unprocessable Entity\",\n \"500\": \"Internal Server Error\",\n \"502\": \"Bad Gateway\",\n \"503\": \"Service Unavailable\",\n };\n\n return defaults[statusCode] || \"Response\";\n }\n\n /**\n * Core flattening logic that converts a JSON schema into bracket notation.\n * Handles nested objects, arrays, and circular references.\n *\n * @param schema - The JSON schema to flatten\n * @param prefix - Optional prefix for nested properties\n * @param visitedRefs - Set to track circular references\n * @returns Array of flattened field descriptors\n */\n flattenSchemaCore(\n schema: any,\n prefix = \"\",\n visitedRefs = new Set<string>()\n ): Array<{ name: string; schema: any; required: boolean }> {\n const flattened: Array<{ name: string; schema: any; required: boolean }> =\n [];\n\n if (schema.$ref) {\n const refPath = schema.$ref;\n if (visitedRefs.has(refPath)) return flattened;\n\n visitedRefs.add(refPath);\n const resolvedSchema = this.resolveRef(schema, refPath);\n if (resolvedSchema) {\n flattened.push(\n ...this.flattenSchemaCore(resolvedSchema, prefix, visitedRefs)\n );\n }\n visitedRefs.delete(refPath);\n return flattened;\n }\n\n if (schema.type === \"array\" && schema.items) {\n const arrayPrefix =\n prefix && schema.items?.format === \"binary\" ? prefix : `${prefix}[0]`;\n\n // Check if items is an array FIRST, before checking for object\n if (schema.items.type === \"array\") {\n flattened.push(\n ...this.flattenSchemaCore(schema.items, arrayPrefix, visitedRefs)\n );\n } else if (schema.items.properties || schema.items.type === \"object\") {\n flattened.push(\n ...this.flattenSchemaCore(schema.items, arrayPrefix, visitedRefs)\n );\n } else if (schema.items.type || schema.items.$ref) {\n flattened.push({\n name: arrayPrefix,\n schema: {\n type: schema.items.type,\n ...(schema.items.enum && { enum: schema.items.enum }),\n ...(schema.items.format && { format: schema.items.format }),\n },\n required: false,\n });\n }\n\n return flattened;\n }\n\n if ((schema.type === \"object\" || !schema.type) && schema.properties) {\n for (const [key, value] of Object.entries(schema.properties) as any) {\n const paramName = prefix ? `${prefix}[${key}]` : key;\n\n if (value.$ref) {\n const refPath = value.$ref;\n if (visitedRefs.has(refPath)) continue;\n\n visitedRefs.add(refPath);\n const resolvedSchema = this.resolveRef(schema, refPath);\n\n if (resolvedSchema) {\n flattened.push(\n ...this.flattenSchemaCore(resolvedSchema, paramName, visitedRefs)\n );\n }\n visitedRefs.delete(refPath);\n } else if (value.type === \"array\" && value.items) {\n const arrayPrefix =\n paramName && value.items?.format == \"binary\"\n ? paramName\n : `${paramName}[0]`;\n\n if (value.items.type === \"array\") {\n flattened.push(\n ...this.flattenSchemaCore(value.items, arrayPrefix, visitedRefs)\n );\n } else if (value.items.type === \"object\" || value.items.properties) {\n flattened.push(\n ...this.flattenSchemaCore(value.items, arrayPrefix, visitedRefs)\n );\n } else {\n flattened.push({\n name: arrayPrefix,\n schema: {\n type: value.items.type,\n ...(value.items.enum && { enum: value.items.enum }),\n ...(value.items.format && { format: value.items.format }),\n },\n required: false,\n });\n }\n } else if (value.type === \"object\" && value.properties) {\n flattened.push(\n ...this.flattenSchemaCore(value, paramName, visitedRefs)\n );\n } else {\n flattened.push({\n name: paramName,\n schema: {\n type: value.type,\n ...(value.enum && { enum: value.enum }),\n ...(value.format && { format: value.format }),\n },\n required: schema.required?.includes(key) || false,\n });\n }\n }\n return flattened;\n }\n\n // Handle primitive types with prefix\n if (schema.type && prefix) {\n flattened.push({\n name: prefix,\n schema: {\n type: schema.type,\n ...(schema.enum && { enum: schema.enum }),\n ...(schema.format && { format: schema.format }),\n },\n required: false,\n });\n }\n\n return flattened;\n }\n\n /**\n * Flattens a JSON schema while preserving the schema structure.\n * Converts nested objects and arrays into bracket notation properties.\n * Used for multipart/form-data schema representation.\n *\n * @param schema - The JSON schema to flatten\n * @returns A flattened schema object with bracket notation properties\n */\n flattenSchema(schema: any): any {\n const flattened = this.flattenSchemaCore(schema);\n\n // Convert the flattened array into a schema object\n const flattenedSchema: any = {\n ...schema,\n properties: {},\n required: [],\n };\n\n for (const item of flattened) {\n flattenedSchema.properties[item.name] = item.schema;\n if (item.required) {\n flattenedSchema.required.push(item.name);\n }\n }\n\n // Remove empty required array if no required fields\n if (flattenedSchema.required.length === 0) {\n delete flattenedSchema.required;\n }\n\n return flattenedSchema;\n }\n\n /**\n * Converts a response definition (shorthand, medium, or full format) into a standard\n * OpenAPI ResponseObject.\n *\n * Supports three formats:\n * 1. Shorthand: ProfileDto → assumes application/json + default description\n * 2. Medium: { content: ProfileDto, description: \"...\" } → custom description\n * 3. Full: { content: { \"application/json\": { schema: ProfileDto } } } → full control\n *\n * @param statusCode - The HTTP status code for this response\n * @param definition - The response definition to convert\n * @returns A standard OpenAPI ResponseObject\n */\n convertResponseDefinition(\n statusCode: string,\n definition: any\n ): OpenAPIV3.ResponseObject {\n if (!definition.content && this.isSchemaLike(definition)) {\n return {\n description: this.getDefaultDescription(statusCode),\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition),\n },\n },\n };\n }\n\n if (definition.content && this.isSchemaLike(definition.content)) {\n return {\n description:\n definition.description || this.getDefaultDescription(statusCode),\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition.content),\n },\n },\n ...(definition.headers && { headers: definition.headers }),\n ...(definition.links && { links: definition.links }),\n };\n }\n\n if (definition.content) {\n const converted: OpenAPIV3.ResponseObject = {\n description:\n definition.description || this.getDefaultDescription(statusCode),\n content: {},\n };\n\n for (const [mediaType, mediaObj] of Object.entries(\n definition.content\n ) as any[]) {\n converted.content![mediaType] = {\n ...mediaObj,\n schema: this.convertToJsonSchema(mediaObj.schema),\n };\n }\n\n if (definition.headers) converted.headers = definition.headers;\n if (definition.links) converted.links = definition.links;\n\n return converted;\n }\n\n return definition;\n }\n\n /**\n * Converts a request body definition (shorthand, medium, or full format) into a standard\n * OpenAPI RequestBodyObject.\n *\n * Supports three formats:\n * 1. Shorthand: CreateUserDto → assumes application/json + required: true\n * 2. Medium: { content: CreateUserDto, required?: boolean } → custom config\n * 3. Full: { content: { \"application/json\": { schema: CreateUserDto } } } → full control\n *\n * For multipart/form-data, automatically converts the schema into an array of parameters.\n *\n * @param definition - The request body definition to convert\n * @returns A standard OpenAPI RequestBodyObject, or undefined if no definition provided\n */\n convertRequestBodyDefinition(\n definition: any\n ): OpenAPIV3.RequestBodyObject | undefined {\n if (!definition) return undefined;\n\n if (!definition.content && this.isSchemaLike(definition)) {\n return {\n required: true,\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition),\n },\n },\n };\n }\n\n if (definition.content && this.isSchemaLike(definition.content)) {\n return {\n required: definition.required === false ? false : true,\n description: definition.description,\n content: {\n \"application/json\": {\n schema: this.convertToJsonSchema(definition.content),\n },\n },\n };\n }\n\n if (definition.content) {\n const converted: OpenAPIV3.RequestBodyObject = {\n required: definition.required ?? true,\n content: {},\n };\n\n if (definition.description)\n converted.description = definition.description;\n\n for (const [mediaType, mediaObj] of Object.entries(\n definition.content\n ) as any[]) {\n const jsonSchema = this.convertToJsonSchema(mediaObj.schema);\n\n // For multipart/form-data, flatten the schema into bracket notation\n if (mediaType === \"multipart/form-data\") {\n converted.content[mediaType] = {\n ...mediaObj,\n schema: this.flattenSchema(jsonSchema),\n };\n } else {\n // For other media types (like application/json), keep the full schema\n converted.content[mediaType] = {\n ...mediaObj,\n schema: jsonSchema,\n };\n }\n }\n\n return converted;\n }\n\n return definition;\n }\n\n /**\n * Converts an array of parameter definitions, transforming any Zod/Class schemas\n * into JSON Schema objects.\n *\n * @param parameters - Array of parameter definitions to convert\n * @returns Array of standard OpenAPI ParameterObjects, or undefined if no parameters provided\n */\n convertParameters(\n parameters: any[] | undefined\n ): (OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject)[] | undefined {\n if (!parameters) return undefined;\n\n return parameters.map((param) => {\n if (param.$ref) return param;\n\n if (param.schema)\n return {\n ...param,\n schema: this.convertToJsonSchema(param.schema),\n };\n\n return param;\n });\n }\n\n /**\n * Converts all responses in a responses object, handling shorthand, medium, and full formats.\n *\n * @param responses - Object containing response definitions keyed by status code\n * @returns Object with converted OpenAPI ResponseObjects\n */\n convertResponses(\n responses: Record<string, any> | undefined\n ): Record<string, OpenAPIV3.ResponseObject> | undefined {\n if (!responses) return undefined;\n\n const converted: Record<string, OpenAPIV3.ResponseObject> = {};\n\n for (const [statusCode, definition] of Object.entries(responses)) {\n converted[statusCode] = this.convertResponseDefinition(\n statusCode,\n definition\n );\n }\n\n return converted;\n }\n\n /**\n * Converts a complete OpenAPI operation configuration, processing responses, requestBody,\n * and parameters to handle shorthand syntax and schema conversions.\n *\n * @param config - The OpenAPI operation configuration to convert\n * @returns The converted configuration with all schemas transformed to JSON Schema\n */\n convertOpenAPIConfig(config: any): any {\n if (!config || config === false) return config;\n\n const converted = { ...config };\n\n if (config.responses)\n converted.responses = this.convertResponses(config.responses);\n\n if (config.requestBody)\n converted.requestBody = this.convertRequestBodyDefinition(\n config.requestBody\n );\n\n if (config.parameters)\n converted.parameters = this.convertParameters(config.parameters);\n\n return converted;\n }\n\n /**\n * Converts a JSON schema to OpenAPI parameter objects with flattened paths.\n * This is used for query/path/header parameters.\n *\n * @param paramType - The parameter location (query, path, header, cookie)\n * @param schema - The JSON schema to convert\n * @param prefix - Optional prefix for nested properties\n * @param visitedRefs - Set to track circular references\n * @returns Array of OpenAPI parameter objects\n */\n jsonSchemaToOpenApiParameters(\n paramType: string,\n schema: any,\n prefix = \"\",\n visitedRefs = new Set<string>()\n ): any[] {\n const flattened = this.flattenSchemaCore(schema, prefix, visitedRefs);\n\n return flattened.map(({ name, schema, required }) => ({\n in: paramType,\n name,\n required,\n schema,\n }));\n }\n\n resolveRef(rootSchema: any, refPath: string): any {\n if (!refPath.startsWith(\"#/properties/\")) {\n return null;\n }\n\n const path = refPath.substring(2).split(\"/\");\n let current = rootSchema;\n\n for (const part of path) {\n if (current && current[part] !== undefined) {\n current = current[part];\n } else {\n return null;\n }\n }\n\n return current;\n }\n}\n\nconst openApiSchemaConverter = new OpenAPIchemaConverter();\n\nexport default openApiSchemaConverter;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AA+JA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Response, Request } from \"express\";\nimport { PrismaModels } from \"../generated\";\nimport { ArkosFile } from \"./upload\";\n\n/**\n * Type definition for authentication-related Prisma query operations\n * @template T - The Prisma model delegate type\n */\nexport type AuthPrismaQueryOptions<T extends Record<string, any>> = {\n // User profile endpoints\n /**\n * Options for retrieving the current authenticated user's profile\n */\n getMe?: Partial<Parameters<T[\"findUnique\"]>[0]>;\n /**\n * Options for updating the current authenticated user's profile\n */\n updateMe?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for soft deleting or deactivating the current authenticated user's account\n */\n deleteMe?: Partial<Parameters<T[\"update\"]>[0]>;\n // Authentication endpoints\n /**\n * Options for user login authentication queries\n */\n login?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for user registration and account creation\n */\n signup?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for updating the current authenticated user's password\n */\n updatePassword?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for finding multiple auth actions\n */\n findManyAuthAction?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for finding a single auth action\n */\n findOneAuthAction?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n};\n\n/**\n * Base Prisma query options for standard CRUD operations\n * @template T - The Prisma model delegate type\n */\ntype BasePrismaQueryOptions<T extends Record<string, any>> = {\n /**\n * @deprecated Use `global` instead for general query options\n */\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Global query options that can be used for all operations\n * Replaces the deprecated queryOptions\n */\n global?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General find options for findMany and findOne operations\n */\n find?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General create options for createOne and createMany operations\n */\n create?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * General update options for updateOne and updateMany operations\n */\n update?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * General delete options for deleteOne and deleteMany operations\n */\n delete?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * General save options for createOne, createMany, updateOne, updateMany operations\n */\n save?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for single record operations (createOne, updateOne)\n */\n saveOne?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for multiple record operations (createMany, updateMany)\n */\n saveMany?:\n | Partial<Parameters<T[\"createMany\"]>[0]>\n | Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for finding a single record (first match)\n */\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for finding multiple records\n */\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for creating a single record\n */\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for creating multiple records\n */\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n /**\n * Options for updating a single record\n */\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for updating multiple records\n */\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for deleting a single record\n */\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * Options for deleting multiple records\n */\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n};\n\n/**\n * Type definition for Prisma query operations with flexible options\n * Conditionally provides auth-specific options when ModelName is \"auth\"\n * @template T - The Prisma model delegate type\n * @template ModelName - The model name (defaults to string for standard models)\n */\nexport type PrismaQueryOptions<\n T extends Record<string, any>,\n ModelName extends string = string,\n> = ModelName extends \"auth\"\n ? AuthPrismaQueryOptions<T>\n : BasePrismaQueryOptions<T>;\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n Create = \"Create\",\n View = \"View\",\n Update = \"Update\",\n Delete = \"Delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface BaseUser extends Record<string, any> {\n id: string;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n}\n\ntype UserModelPayload =\n PrismaModels<{}> extends { user: infer U }\n ? U extends { GetPayload: infer P }\n ? P\n : never\n : never;\n\nexport type User = UserModelPayload extends never ? BaseUser : UserModelPayload;\n\nexport interface ArkosRequest<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n Query extends Record<string, any> = any,\n> extends Request<P, ResBody, ReqBody, Query> {\n /**\n * Authenticated user\n */\n user?: User;\n /**\n * Single uploaded file, populated when using `{ uploads: { type: \"single\" }}`\n */\n file?: ArkosFile;\n /**\n * Uploaded files, populated when using `{ uploads: { type: \"array\" }}` or `{ uploads: { type: \"fileds\" }}`.\n */\n files?: ArkosFile[] | Record<string, ArkosFile[]>;\n\n /**\n * Fields to include in relational queries\n */\n relationFields?: Record<string, boolean>;\n\n /**\n * Prisma include options for related data\n */\n include?: Record<string, any>;\n\n /**\n * Data to be sent in the response\n */\n responseData?: Record<string, any> | null;\n\n /**\n * Additional context data\n */\n additionalData?: Record<string, any> | null;\n\n /**\n * HTTP status code for the response\n */\n responseStatus?: number;\n\n /**\n * Typed request body\n */\n body: ReqBody;\n\n /**\n * Prisma query options (where, orderBy, select, etc.)\n */\n prismaQueryOptions?: Record<string, any>;\n\n /**\n * Typed query parameters\n */\n query: Query;\n\n /**\n * JWT token used in authentication process\n */\n accessToken?: string;\n\n /**\n * Query parameters after being handled and transformed by middleware\n */\n transformedQuery?: Record<string, any>;\n\n /**\n * Processed filters from APIFeatures.filters\n */\n filters?: Record<string, any>;\n\n /**\n * Name of the Prisma model being queried\n */\n modelName?: string;\n}\n\nexport interface ArkosResponse<\n ResBody = any,\n Locals extends Record<string, any> = Record<string, any>,\n> extends Response<ResBody, Locals> {}\n\nexport interface ArkosNextFunction extends NextFunction {}\n\nexport type ArkosRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosErrorRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n err: any,\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n"]}
|