arkos 1.5.12-beta → 1.5.13-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/app.js +3 -3
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/modules/email/email.service.js +1 -0
- package/dist/cjs/modules/email/email.service.js.map +1 -1
- package/dist/cjs/modules/file-upload/file-upload.controller.js +7 -4
- package/dist/cjs/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/cjs/types/validation/validator.js +3 -0
- package/dist/cjs/types/validation/validator.js.map +1 -0
- package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
- package/dist/cjs/utils/cli/build.js +1 -1
- package/dist/cjs/utils/cli/build.js.map +1 -1
- package/dist/cjs/utils/cli/start.js +7 -9
- package/dist/cjs/utils/cli/start.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/app.js +3 -3
- package/dist/esm/app.js.map +1 -1
- package/dist/esm/modules/email/email.service.js +1 -0
- package/dist/esm/modules/email/email.service.js.map +1 -1
- package/dist/esm/modules/file-upload/file-upload.controller.js +7 -4
- package/dist/esm/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/esm/types/validation/validator.js +2 -0
- package/dist/esm/types/validation/validator.js.map +1 -0
- package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
- package/dist/esm/utils/cli/build.js +2 -2
- package/dist/esm/utils/cli/build.js.map +1 -1
- package/dist/esm/utils/cli/start.js +7 -9
- package/dist/esm/utils/cli/start.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/types/types/validation/validator.d.ts +2 -0
- package/dist/types/utils/arkos-router/types/index.d.ts +5 -4
- package/dist/types/utils/cli/start.d.ts +1 -0
- package/package.json +33 -15
package/dist/esm/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names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AC,MAAM,CAAC,WAAW,EAAE,IAAI,GAAG,gBAAgB,EACxD,GAAG,EACH,EAAE,KAAK,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,WAAW,EAAE,IAAI,GAAG,EAAE,EAAE,EAC/C,eAAe,CAChB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,IAAI,iBAAiB,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;QAC9C,IAAI,OAAO,iBAAiB,EAAE,YAAY,KAAK,UAAU,EAAE,CAAC;YAC1D,GAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC1C,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { IRouter, Router } from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\nimport { ArkosRequestHandler, getArkosConfig } from \"./exports\";\nimport { ArkosInitConfig } from \"./types/arkos-config\";\nimport {\n isAuthenticationEnabled,\n isProduction,\n validateArkosConfig,\n} from \"./utils/helpers/arkos-config.helpers\";\nimport { lenientDecode } from \"./utils/helpers/url-helpers\";\nimport sheu from \"./utils/sheu\";\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n initConfig: ArkosInitConfig\n): Promise<express.Express> {\n const arkosConfig = getArkosConfig();\n\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n initConfig?.configureApp && (await initConfig?.configureApp(app)),\n ]);\n\n validateArkosConfig();\n const middlewaresConfig = arkosConfig?.middlewares;\n\n if (middlewaresConfig?.requestLogger !== false) {\n if (typeof middlewaresConfig?.requestLogger === \"function\") {\n app.use(middlewaresConfig.requestLogger);\n } else {\n app.use(handleRequestLogs);\n }\n }\n\n if (middlewaresConfig?.compression !== false) {\n if (typeof middlewaresConfig?.compression === \"function\") {\n app.use(middlewaresConfig.compression);\n } else {\n app.use(compression(middlewaresConfig?.compression || {}));\n }\n }\n\n if (middlewaresConfig?.rateLimit !== false) {\n if (typeof middlewaresConfig?.rateLimit === \"function\") {\n app.use(middlewaresConfig.rateLimit);\n } else {\n app.use(\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 300,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n middlewaresConfig?.rateLimit || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.cors !== false) {\n const corsConfig = middlewaresConfig?.cors || {};\n\n if (\"customHandler\" in corsConfig)\n sheu.warn(\n \"cors.customHandler is deprecated. Pass the handler directly: `cors: myHandler`. See https://www.arkosjs.com/blog/rethinking-cors-defaults-in-arkosjs\"\n );\n\n if (\"allowedOrigins\" in corsConfig)\n sheu.warn(\n \"cors.allowedOrigins is deprecated. Use `cors: { origin: '...' }` directly instead. See https://www.arkosjs.com/blog/rethinking-cors-defaults-in-arkosjs\"\n );\n\n if (\"options\" in corsConfig)\n sheu.warn(\n \"cors.options is deprecated. Pass cors.CorsOptions directly instead. See https://www.arkosjs.com/blog/rethinking-cors-defaults-in-arkosjs\"\n );\n\n const defaultOptions = {\n origin: isProduction() ? \"*\" : true,\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"Content-Type\", \"Authorization\", \"Connection\"],\n credentials: isProduction() ? false : true,\n };\n\n if (typeof corsConfig === \"function\") {\n if (corsConfig.length >= 3) {\n app.use(corsConfig as ArkosRequestHandler);\n } else {\n // cors.CorsOptionsDelegate — (req, cb)\n app.use(cors(corsConfig as cors.CorsOptionsDelegate));\n }\n } else if (\n middlewaresConfig?.cors &&\n typeof corsConfig === \"object\" &&\n \"customHandler\" in corsConfig\n ) {\n // { customHandler } shape — delegate entirely to user's handler\n app.use(cors(corsConfig.customHandler));\n } else if (\n middlewaresConfig?.cors &&\n typeof corsConfig === \"object\" &&\n !(\"allowedOrigins\" in corsConfig)\n ) {\n // Plain cors.CorsOptions passed directly at top level\n app.use(cors(deepmerge(defaultOptions, corsConfig as cors.CorsOptions)));\n } else {\n const { allowedOrigins, options } = corsConfig as {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n };\n\n app.use(\n cors(\n deepmerge(defaultOptions, {\n origin: allowedOrigins ?? defaultOptions.origin,\n ...(options || {}),\n })\n )\n );\n }\n }\n\n if (middlewaresConfig?.expressJson !== false) {\n if (typeof middlewaresConfig?.expressJson === \"function\") {\n app.use(middlewaresConfig.expressJson);\n } else {\n app.use(express.json(middlewaresConfig?.expressJson || {}));\n }\n }\n\n if (middlewaresConfig?.cookieParser !== false) {\n if (typeof middlewaresConfig?.cookieParser === \"function\") {\n app.use(middlewaresConfig.cookieParser);\n } else {\n const params =\n typeof middlewaresConfig?.cookieParser == \"object\"\n ? middlewaresConfig.cookieParser\n : { secret: undefined, options: undefined };\n app.use(cookieParser(params.secret, params.options));\n }\n }\n\n if (middlewaresConfig?.queryParser !== false) {\n if (typeof middlewaresConfig?.queryParser === \"function\") {\n app.use(middlewaresConfig.queryParser);\n } else {\n app.use(\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n },\n middlewaresConfig?.queryParser || {}\n )\n )\n );\n }\n }\n\n app.use(debuggerService.logRequestInfo);\n\n const routersConfig = arkosConfig?.routers;\n\n if (routersConfig?.welcomeRoute !== false) {\n if (typeof routersConfig?.welcomeRoute === \"function\") {\n app.get(\"/api\", routersConfig.welcomeRoute);\n } else {\n app.get(\"/api\", (_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n });\n }\n }\n\n if (initConfig?.use)\n for (const mwOrRouter of initConfig.use) {\n app.use(mwOrRouter as IRouter);\n }\n\n const fileUploadRouter = getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n\n if (isAuthenticationEnabled()) {\n const authRouter = getAuthRouter(arkosConfig) as any;\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n const modelsRouter = getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter as any);\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig, app));\n\n app.use(\"*\", (req) => {\n const url = lenientDecode(req.originalUrl);\n throw new AppError(\n `Route ${req.method.toUpperCase()} ${url} was not found`,\n 404,\n { route: `${req.method.toUpperCase()} ${url}` },\n \"RouteNotFound\"\n );\n });\n\n if (middlewaresConfig?.errorHandler !== false) {\n if (typeof middlewaresConfig?.errorHandler === \"function\") {\n app.use(middlewaresConfig.errorHandler);\n } else {\n app.use(errorHandler);\n }\n }\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,OAA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AAC,GAAG,CAAC,WAAW,CAAC,CAAC;QAC3C,MAAM,IAAI,QAAQ,CAChB,SAAS,GAAG,CAAC,MAAM,CAAC,WAAW,EAAE,IAAI,GAAG,gBAAgB,EACxD,GAAG,EACH,EAAE,KAAK,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,WAAW,EAAE,IAAI,GAAG,EAAE,EAAE,EAC/C,eAAe,CAChB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,IAAI,iBAAiB,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;QAC9C,IAAI,OAAO,iBAAiB,EAAE,YAAY,KAAK,UAAU,EAAE,CAAC;YAC1D,GAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC1C,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { IRouter, Router } from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\nimport { ArkosRequestHandler, getArkosConfig } from \"./exports\";\nimport { ArkosInitConfig } from \"./types/arkos-config\";\nimport {\n isAuthenticationEnabled,\n isProduction,\n validateArkosConfig,\n} from \"./utils/helpers/arkos-config.helpers\";\nimport { lenientDecode } from \"./utils/helpers/url-helpers\";\nimport sheu from \"./utils/sheu\";\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n initConfig: ArkosInitConfig\n): Promise<express.Express> {\n const arkosConfig = getArkosConfig();\n\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n initConfig?.configureApp && (await initConfig?.configureApp(app)),\n ]);\n\n validateArkosConfig();\n const middlewaresConfig = arkosConfig?.middlewares;\n\n if (middlewaresConfig?.requestLogger !== false) {\n if (typeof middlewaresConfig?.requestLogger === \"function\") {\n app.use(middlewaresConfig.requestLogger);\n } else {\n app.use(handleRequestLogs);\n }\n }\n\n if (middlewaresConfig?.compression !== false) {\n if (typeof middlewaresConfig?.compression === \"function\") {\n app.use(middlewaresConfig.compression);\n } else {\n app.use(compression(middlewaresConfig?.compression || {}));\n }\n }\n\n if (middlewaresConfig?.rateLimit !== false) {\n if (typeof middlewaresConfig?.rateLimit === \"function\") {\n app.use(middlewaresConfig.rateLimit);\n } else {\n app.use(\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 300,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n middlewaresConfig?.rateLimit || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.cors !== false) {\n const corsConfig = middlewaresConfig?.cors || {};\n\n if (\"customHandler\" in corsConfig)\n sheu.warn(\n \"cors.customHandler is deprecated. Pass the handler directly: `cors: myHandler`. See https://www.arkosjs.com/blog/rethinking-cors-defaults-in-arkosjs\",\n { timestamp: true }\n );\n\n if (\"allowedOrigins\" in corsConfig)\n sheu.warn(\n \"cors.allowedOrigins is deprecated. Use `cors: { origin: '...' }` directly instead. See https://www.arkosjs.com/blog/rethinking-cors-defaults-in-arkosjs\",\n { timestamp: true }\n );\n\n if (\"options\" in corsConfig)\n sheu.warn(\n \"cors.options is deprecated. Pass cors.CorsOptions directly instead. See https://www.arkosjs.com/blog/rethinking-cors-defaults-in-arkosjs\",\n { timestamp: true }\n );\n\n const defaultOptions = {\n origin: isProduction() ? \"*\" : true,\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"Content-Type\", \"Authorization\", \"Connection\"],\n credentials: isProduction() ? false : true,\n };\n\n if (typeof corsConfig === \"function\") {\n if (corsConfig.length >= 3) {\n app.use(corsConfig as ArkosRequestHandler);\n } else {\n // cors.CorsOptionsDelegate — (req, cb)\n app.use(cors(corsConfig as cors.CorsOptionsDelegate));\n }\n } else if (\n middlewaresConfig?.cors &&\n typeof corsConfig === \"object\" &&\n \"customHandler\" in corsConfig\n ) {\n // { customHandler } shape — delegate entirely to user's handler\n app.use(cors(corsConfig.customHandler));\n } else if (\n middlewaresConfig?.cors &&\n typeof corsConfig === \"object\" &&\n !(\"allowedOrigins\" in corsConfig)\n ) {\n // Plain cors.CorsOptions passed directly at top level\n app.use(cors(deepmerge(defaultOptions, corsConfig as cors.CorsOptions)));\n } else {\n const { allowedOrigins, options } = corsConfig as {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n };\n\n app.use(\n cors(\n deepmerge(defaultOptions, {\n origin: allowedOrigins ?? defaultOptions.origin,\n ...(options || {}),\n })\n )\n );\n }\n }\n\n if (middlewaresConfig?.expressJson !== false) {\n if (typeof middlewaresConfig?.expressJson === \"function\") {\n app.use(middlewaresConfig.expressJson);\n } else {\n app.use(express.json(middlewaresConfig?.expressJson || {}));\n }\n }\n\n if (middlewaresConfig?.cookieParser !== false) {\n if (typeof middlewaresConfig?.cookieParser === \"function\") {\n app.use(middlewaresConfig.cookieParser);\n } else {\n const params =\n typeof middlewaresConfig?.cookieParser == \"object\"\n ? middlewaresConfig.cookieParser\n : { secret: undefined, options: undefined };\n app.use(cookieParser(params.secret, params.options));\n }\n }\n\n if (middlewaresConfig?.queryParser !== false) {\n if (typeof middlewaresConfig?.queryParser === \"function\") {\n app.use(middlewaresConfig.queryParser);\n } else {\n app.use(\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n },\n middlewaresConfig?.queryParser || {}\n )\n )\n );\n }\n }\n\n app.use(debuggerService.logRequestInfo);\n\n const routersConfig = arkosConfig?.routers;\n\n if (routersConfig?.welcomeRoute !== false) {\n if (typeof routersConfig?.welcomeRoute === \"function\") {\n app.get(\"/api\", routersConfig.welcomeRoute);\n } else {\n app.get(\"/api\", (_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n });\n }\n }\n\n if (initConfig?.use)\n for (const mwOrRouter of initConfig.use) {\n app.use(mwOrRouter as IRouter);\n }\n\n const fileUploadRouter = getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n\n if (isAuthenticationEnabled()) {\n const authRouter = getAuthRouter(arkosConfig) as any;\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n const modelsRouter = getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter as any);\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig, app));\n\n app.use(\"*\", (req) => {\n const url = lenientDecode(req.originalUrl);\n throw new AppError(\n `Route ${req.method.toUpperCase()} ${url} was not found`,\n 404,\n { route: `${req.method.toUpperCase()} ${url}` },\n \"RouteNotFound\"\n );\n });\n\n if (middlewaresConfig?.errorHandler !== false) {\n if (typeof middlewaresConfig?.errorHandler === \"function\") {\n app.use(middlewaresConfig.errorHandler);\n } else {\n app.use(errorHandler);\n }\n }\n\n return app;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":"AAAA,OAAO,UAA4C,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AAiCxD,MAAM,OAAO,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,KAAK,EAAE,YAAY,EAAE,GAAG,cAAc,EAAE,CAAC;QACjD,MAAM,IAAI,GAAG,YAAY,EAAE,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;QAC1D,MAAM,IAAI,GACR,YAAY,EAAE,IAAI;YAClB,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAC1E,MAAM,MAAM,GACV,YAAY,EAAE,MAAM,KAAK,SAAS;YAChC,CAAC,CAAC,YAAY,CAAC,MAAM;YACrB,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY;gBACxB,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,KAAK,MAAM;gBACrC,CAAC,CAAC,SAAS,CAAC;QAClB,MAAM,IAAI,GAAG,YAAY,EAAE,IAA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C;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;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,eAAe,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 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,OAAO,UAA4C,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AAiCxD,MAAM,OAAO,YAAY;IAUvB,YAAY,MAA8B;QAT1C,gBAAW,GAAuB,IAAI,CAAC;QAC/B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gBAAgB,CAAC,WAAW,CAAC,CAAC;YAC7D,IAAI,CAAC,WAAW;gBAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;QACzE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,WAAW,CAAC,QAAQ,CAAC;YACtC,GAAG,OAAO;YACV,IAAI,EAAE,WAAW;YACjB,IAAI,EACF,OAAO,EAAE,IAAI;gBACb,CAAC,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI;oBAC/C,CAAC,CAAC,OAAO,CAAC,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;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,eAAe,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"]}
|
|
@@ -6,6 +6,10 @@ import catchAsync from "../error-handler/utils/catch-async.js";
|
|
|
6
6
|
import { getArkosConfig } from "../../server.js";
|
|
7
7
|
import { processFile, processImage } from "./utils/helpers/file-upload.helpers.js";
|
|
8
8
|
import { getModuleComponents } from "../../utils/dynamic-loader.js";
|
|
9
|
+
function matchesUploadUrl(originalUrl, baseUploadRoute, fileType, fileName) {
|
|
10
|
+
const expectedPath = `${baseUploadRoute}/${fileType}/${fileName}`;
|
|
11
|
+
return originalUrl === expectedPath || originalUrl.startsWith(expectedPath);
|
|
12
|
+
}
|
|
9
13
|
export class FileUploadController {
|
|
10
14
|
constructor() {
|
|
11
15
|
this.uploadFile = catchAsync(async (req, res, next) => {
|
|
@@ -106,10 +110,11 @@ export class FileUploadController {
|
|
|
106
110
|
default:
|
|
107
111
|
return next(new AppError("Invalid file type", 400, "InvalidFileType"));
|
|
108
112
|
}
|
|
113
|
+
const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
109
114
|
try {
|
|
110
115
|
const { fileUpload } = getArkosConfig();
|
|
111
116
|
const baseUploadRoute = fileUpload?.baseRoute || "/api/uploads";
|
|
112
|
-
const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
|
|
117
|
+
const urlPattern = new RegExp(`${escapeRegExp(baseUploadRoute)}/${escapeRegExp(fileType)}/${escapeRegExp(fileName)}`);
|
|
113
118
|
const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
|
|
114
119
|
if (isExpectedUrlPattern) {
|
|
115
120
|
const fullUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
|
|
@@ -171,9 +176,7 @@ export class FileUploadController {
|
|
|
171
176
|
return next(new AppError("No new file uploaded", 400, "MissingNewFile"));
|
|
172
177
|
if (fileName && fileName.trim() !== "") {
|
|
173
178
|
try {
|
|
174
|
-
const
|
|
175
|
-
const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
|
|
176
|
-
const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
|
|
179
|
+
const isExpectedUrlPattern = matchesUploadUrl(req.originalUrl, fileUpload?.baseRoute || "/api/uploads", fileType, fileName);
|
|
177
180
|
if (isExpectedUrlPattern) {
|
|
178
181
|
const oldFileUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
|
|
179
182
|
await uploader.deleteFileByUrl(oldFileUrl);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAEL,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAEhF,OAAO,EAAE,mBAA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,YAAY,GAAG,WAAW,CAAC;oBACxC,GAAG,CAAC,YAAY,GAAG,WAAW,CAAC;oBAC/B,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,WAAW,CAAC;oBAC7B,GAAW,CAAC,cAAc,GAAG,GAAG,CAAC;oBAClC,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;oBACzB,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC;oBACxB,OAAO,IAAI,EAAE,CAAC;gBAChB,CAAC;gBAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IAqDJ,CAAC;CAAA;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,eAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n // streamFile = catchAsync(\n // async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(filePath);\n // const fileSize = fileStat.size;\n // const range = req.headers.range;\n\n // if (range) {\n // const [partialStart, partialEnd] = range\n // .replace(/bytes=/, \"\")\n // .split(\"-\");\n // const start = parseInt(partialStart, 10) || 0;\n // const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n // if (start >= fileSize || end >= fileSize) {\n // res.status(416).json({ error: \"Range Not Satisfiable\" });\n // return;\n // }\n\n // res.writeHead(206, {\n // \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n // \"Accept-Ranges\": \"bytes\",\n // \"Content-Length\": end - start + 1,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n\n // fs.createReadStream(filePath, { start, end }).pipe(res);\n // } else {\n // res.writeHead(200, {\n // \"Content-Length\": fileSize,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n // fs.createReadStream(filePath).pipe(res);\n // }\n // }\n // );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
|
|
1
|
+
{"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAEL,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAEhF,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,SAAS,gBAAgB,CACvB,WAAmB,EACnB,eAAuB,EACvB,QAAgB,EAChB,QAAgB;IAEhB,MAAM,YAAY,GAAG,GAAG,eAAe,IAAI,QAAQ,IAAI,QAAQ,EAAE,CAAC;IAClE,OAAO,WAAW,KAAK,YAAY,IAAI,WAAW,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;AAC9E,CAAC;AAKD,MAAM,OAAO,oBAAoB;IAAjC;QAeE,eAAU,GAAG,UAAU,CACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,IAAI,CAAC,YAAY;gBACf,mBAAmB,CAAC,aAAa,CAAC,EAAE,YAAY,IAAI,EAAE,CAAC;YAEzD,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CA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AAC,MAAM,GAAG,GAAG,CAAC;oBACxB,OAAO,IAAI,EAAE,CAAC;gBAChB,CAAC;gBAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IAqDJ,CAAC;CAAA;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,eAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\nfunction matchesUploadUrl(\n originalUrl: string,\n baseUploadRoute: string,\n fileType: string,\n fileName: string\n): boolean {\n const expectedPath = `${baseUploadRoute}/${fileType}/${fileName}`;\n return originalUrl === expectedPath || originalUrl.startsWith(expectedPath);\n}\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n // top of file or a shared utils import\n const escapeRegExp = (value: string) =>\n value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n try {\n const { fileUpload } = getArkosConfig();\n\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n const urlPattern = new RegExp(\n `${escapeRegExp(baseUploadRoute)}/${escapeRegExp(fileType)}/${escapeRegExp(fileName)}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const isExpectedUrlPattern = matchesUploadUrl(\n req.originalUrl,\n fileUpload?.baseRoute || \"/api/uploads\",\n fileType,\n fileName\n );\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n // streamFile = catchAsync(\n // async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(filePath);\n // const fileSize = fileStat.size;\n // const range = req.headers.range;\n\n // if (range) {\n // const [partialStart, partialEnd] = range\n // .replace(/bytes=/, \"\")\n // .split(\"-\");\n // const start = parseInt(partialStart, 10) || 0;\n // const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n // if (start >= fileSize || end >= fileSize) {\n // res.status(416).json({ error: \"Range Not Satisfiable\" });\n // return;\n // }\n\n // res.writeHead(206, {\n // \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n // \"Accept-Ranges\": \"bytes\",\n // \"Content-Length\": end - start + 1,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n\n // fs.createReadStream(filePath, { start, end }).pipe(res);\n // } else {\n // res.writeHead(200, {\n // \"Content-Length\": fileSize,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n // fs.createReadStream(filePath).pipe(res);\n // }\n // }\n // );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validator.js","sourceRoot":"","sources":["../../../../src/types/validation/validator.ts"],"names":[],"mappings":"","sourcesContent":["import { ZodSchema } from \"zod\";\n\nexport type Validator =\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import { IRoute, IRouter, Locals } from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\n\ntype InferValidationType<T, Fallback> = T extends ZodSchema\n ? z.infer<T>\n : T extends new (...args: any[]) => infer I\n ? I\n : Fallback;\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\nexport type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>;\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype RouterMethodHandler<T> = {\n (config: PathParams, ...handlers: Array<ArkosAnyRequestHandler>): T;\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams> | PathParams,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams> | PathParams,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n};\n\nexport type ArkosRouteMethodHandler<T> = {\n (\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n ): T;\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n\n <\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | null\n | false\n | undefined = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n};\n\nexport interface IArkosRoute extends IRoute {\n /** GET method handler with route configuration support */\n get: ArkosRouteMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: ArkosRouteMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: ArkosRouteMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: ArkosRouteMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: ArkosRouteMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: ArkosRouteMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: ArkosRouteMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: ArkosRouteMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: ArkosRouteMethodHandler<this>;\n}\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport interface IArkosRouter extends IRouter {\n /** GET method handler with route configuration support */\n get: RouterMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: RouterMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: RouterMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: RouterMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: RouterMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: RouterMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: RouterMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: RouterMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: RouterMethodHandler<this>;\n\n route<T extends string>(prefix: T): IArkosRoute;\n route(prefix: PathParams): IArkosRoute;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig<\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | null\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | null\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | null\n | undefined = any,\n> = {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: PathParams;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Set to `null` to forbidden all request inputs.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | null\n | {\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n };\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n *\n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import { IRoute, IRouter, Locals } from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\nimport { Validator } from \"../../../types/validation/validator\";\n\ntype InferValidationType<T, Fallback> = T extends ZodSchema\n ? z.infer<T>\n : T extends new (...args: any[]) => infer I\n ? I\n : Fallback;\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\nexport type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>;\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype RouterMethodHandler<T> = {\n (config: PathParams, ...handlers: Array<ArkosAnyRequestHandler>): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams> | PathParams,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams> | PathParams,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n};\n\nexport type ArkosRouteMethodHandler<T> = {\n (\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n};\n\nexport interface IArkosRoute extends IRoute {\n /** GET method handler with route configuration support */\n get: ArkosRouteMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: ArkosRouteMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: ArkosRouteMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: ArkosRouteMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: ArkosRouteMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: ArkosRouteMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: ArkosRouteMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: ArkosRouteMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: ArkosRouteMethodHandler<this>;\n}\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport interface IArkosRouter extends IRouter {\n /** GET method handler with route configuration support */\n get: RouterMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: RouterMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: RouterMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: RouterMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: RouterMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: RouterMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: RouterMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: RouterMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: RouterMethodHandler<this>;\n\n route<T extends string>(prefix: T): IArkosRoute;\n route(prefix: PathParams): IArkosRoute;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig<\n TQuery extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | null\n | undefined = any,\n TBody extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | null\n | undefined = any,\n TParams extends\n | ZodSchema\n | (new (...args: any[]) => object)\n | false\n | null\n | undefined = any,\n> = {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: PathParams;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Set to `null` to forbidden all request inputs.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | null\n | {\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n };\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n *\n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n};\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import path from "path";
|
|
2
2
|
import fs from "fs";
|
|
3
|
-
import { execSync } from "child_process";
|
|
3
|
+
import { execFileSync, execSync } from "child_process";
|
|
4
4
|
import { getUserFileExtension } from "../helpers/fs.helpers.js";
|
|
5
5
|
import { loadEnvironmentVariables } from "../dotenv.helpers.js";
|
|
6
6
|
import { detectPackageManagerFromUserAgent } from "../helpers/global.helpers.js";
|
|
@@ -83,7 +83,7 @@ function buildTypeScriptProject(options, moduleType) {
|
|
|
83
83
|
fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));
|
|
84
84
|
try {
|
|
85
85
|
removeDir(BUILD_DIR);
|
|
86
|
-
|
|
86
|
+
execFileSync("tsc", ["-p", tempTsconfigPath], {
|
|
87
87
|
stdio: "inherit",
|
|
88
88
|
cwd: process.cwd(),
|
|
89
89
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,2BAA2B,CAAC;AAC9E,OAAO,IAAI,MAAM,SAAS,CAAC;AAC3B,OAAO,gBAAgB,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AA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AAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;wBAC/C,CAAC;wBAED,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;oBAC1C,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAGD,gBAAgB,CAAC,SAAS,CAAC,CAAC;QAG5B,MAAM,eAAe,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAE5C,KAAK,MAAM,IAAI,IAAI,eAAe,EAAE,CAAC;YACnC,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC;gBAClD,EAAE,CAAC,YAAY,CACb,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,EAC9B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAC3B,CAAC;YACJ,CAAC;QACH,CAAC;IAGH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,CAAC,CAAC;QAC7D,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;AACH,CAAC;AAKD,SAAS,iBAAiB,CAAC,UAAkB;IAC3C,IAAI,CAAC;QACH,IAAI,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC;YAAE,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport { removeDir } from \"../remove-dir\";\nimport { bundler } from \"../bundler\";\n\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n const fileExt = getUserFileExtension();\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n watermarkStamper.stamp({\n envFiles,\n });\n // console.info(\"\");\n // console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n // console.info(\n // ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n // .replaceAll(`${process.cwd()}/`, \"\")\n // .replaceAll(\"/\", \"\")}`\n // );\n\n console.info(`\\n Creating an optimized production build...`);\n\n ensureBuildDir();\n\n if (fileExt === \"ts\") buildTypeScriptProject(options, moduleType);\n else buildJavaScriptProject(options, moduleType);\n\n const packageManger = detectPackageManagerFromUserAgent();\n\n console.info(`\\n\\x1b[1m\\x1b[32m Build complete!\\x1b[0m\\n`);\n console.info(` \\x1b[1mNext step:\\x1b[0m`);\n console.info(\n ` Run it using \\x1b[1m\\x1b[36m${packageManger} run start\\x1b[0m\\n`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(`Build failed: ${err?.message}`);\n console.error(err);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") return \"cjs\";\n else if ([\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType))\n return \"esm\";\n\n sheu.warn(`Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`);\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) fs.mkdirSync(BUILD_DIR, { recursive: true });\n\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n try {\n if (fs.existsSync(tsconfigPath)) {\n tsconfig = bundler.readJsonWithComments(tsconfigPath);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n }\n\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n removeDir(BUILD_DIR);\n execSync(`tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n configPath: tempTsconfigPath,\n });\n\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(_: BuildOptions, moduleType: ModuleType) {\n const targetDir = path.join(BUILD_DIR);\n\n try {\n if (moduleType === \"esm\") {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n });\n // createModulePackageJson(moduleType);\n } catch (error: any) {\n console.info(error.stack);\n console.error(\"❌ Error building JavaScript project:\", error.stack);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(_: ModuleType, skipExtensions: string[]) {\n const targetDir = path.join(BUILD_DIR);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"arkos.config.js\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n // console.info(`Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,2BAA2B,CAAC;AAC9E,OAAO,IAAI,MAAM,SAAS,CAAC;AAC3B,OAAO,gBAAgB,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,MAAM,SAAS,GAAG,QAAQ,CAAC;AAC3B,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,KAAK,CAAU,CAAC;AAW7C,MAAM,UAAU,YAAY,CAAC,UAAwB,EAAE;I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AAC;oBAC1C,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAGD,gBAAgB,CAAC,SAAS,CAAC,CAAC;QAG5B,MAAM,eAAe,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAE5C,KAAK,MAAM,IAAI,IAAI,eAAe,EAAE,CAAC;YACnC,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC;gBAClD,EAAE,CAAC,YAAY,CACb,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,EAC9B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAC3B,CAAC;YACJ,CAAC;QACH,CAAC;IAGH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,CAAC,CAAC;QAC7D,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;AACH,CAAC;AAKD,SAAS,iBAAiB,CAAC,UAAkB;IAC3C,IAAI,CAAC;QACH,IAAI,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC;YAAE,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { execFileSync, execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport { removeDir } from \"../remove-dir\";\nimport { bundler } from \"../bundler\";\n\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n const fileExt = getUserFileExtension();\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n watermarkStamper.stamp({\n envFiles,\n });\n\n console.info(`\\n Creating an optimized production build...`);\n\n ensureBuildDir();\n\n if (fileExt === \"ts\") buildTypeScriptProject(options, moduleType);\n else buildJavaScriptProject(options, moduleType);\n\n const packageManger = detectPackageManagerFromUserAgent();\n\n console.info(`\\n\\x1b[1m\\x1b[32m Build complete!\\x1b[0m\\n`);\n console.info(` \\x1b[1mNext step:\\x1b[0m`);\n console.info(\n ` Run it using \\x1b[1m\\x1b[36m${packageManger} run start\\x1b[0m\\n`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(`Build failed: ${err?.message}`);\n console.error(err);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") return \"cjs\";\n else if ([\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType))\n return \"esm\";\n\n sheu.warn(`Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`);\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) fs.mkdirSync(BUILD_DIR, { recursive: true });\n\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n try {\n if (fs.existsSync(tsconfigPath)) {\n tsconfig = bundler.readJsonWithComments(tsconfigPath);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n }\n\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n removeDir(BUILD_DIR);\n execFileSync(\"tsc\", [\"-p\", tempTsconfigPath], {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n configPath: tempTsconfigPath,\n });\n\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(_: BuildOptions, moduleType: ModuleType) {\n const targetDir = path.join(BUILD_DIR);\n\n try {\n if (moduleType === \"esm\") {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n });\n // createModulePackageJson(moduleType);\n } catch (error: any) {\n console.info(error.stack);\n console.error(\"❌ Error building JavaScript project:\", error.stack);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(_: ModuleType, skipExtensions: string[]) {\n const targetDir = path.join(BUILD_DIR);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"arkos.config.js\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n // console.info(`Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}
|
|
@@ -32,15 +32,13 @@ export function startCommand(options = {}) {
|
|
|
32
32
|
env?.CLI_HOST ||
|
|
33
33
|
env?.HOST ||
|
|
34
34
|
(env.ARKOS_BUILD !== "true" ? "0.0.0.0" : "127.0.0.1");
|
|
35
|
-
env.__PORT =
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
host: env.__HOST,
|
|
43
|
-
});
|
|
35
|
+
env.__PORT = env?.CLI_PORT || env?.PORT || "8000";
|
|
36
|
+
if (options.stamp !== false)
|
|
37
|
+
watermarkStamper.stamp({
|
|
38
|
+
envFiles,
|
|
39
|
+
port: env.__PORT,
|
|
40
|
+
host: env.__HOST,
|
|
41
|
+
});
|
|
44
42
|
child = spawn("node", [entryPoint], {
|
|
45
43
|
stdio: "inherit",
|
|
46
44
|
env,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.js","sourceRoot":"","sources":["../../../../src/utils/cli/start.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAgB,KAAK,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,gBAAgB,MAAM,2BAA2B,CAAC;AACzD,OAAO,IAAI,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"start.js","sourceRoot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AAU,gCAAgC;IAC7C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { ChildProcess, spawn } from \"child_process\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { fullCleanCwd } from \"../helpers/fs.helpers\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport sheu from \"../sheu\";\n\ninterface StartOptions {\n port?: string;\n host?: string;\n stamp?: false;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Production start command for the arkos CLI\n */\nexport function startCommand(options: StartOptions = {}) {\n process.env.NO_CLI = \"true\";\n\n if (!process.env.NODE_ENV) process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n envFiles = loadEnvironmentVariables();\n\n try {\n const { port, host } = options;\n\n const entryPoint = path.join(process.cwd(), \".build\", \"src\", \"app.js\");\n\n if (!fs.existsSync(path.join(entryPoint))) {\n sheu.error(\n `Could not find built application entry point at ${fullCleanCwd(entryPoint).replaceAll(/^\\/+/g, \"\")}`\n );\n process.exit(1);\n }\n\n const env: { [x: string]: string } = {\n NODE_ENV: \"production\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n ARKOS_BUILD: \"true\",\n CLI: \"false\",\n };\n\n env.__HOST =\n env?.CLI_HOST ||\n env?.HOST ||\n (env.ARKOS_BUILD !== \"true\" ? \"0.0.0.0\" : \"127.0.0.1\");\n\n env.__PORT = env?.CLI_PORT || env?.PORT || \"8000\";\n\n if (options.stamp !== false)\n watermarkStamper.stamp({\n envFiles,\n port: env.__PORT,\n host: env.__HOST,\n });\n\n child = spawn(\"node\", [entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n\n process.on(\"SIGINT\", () => {\n if (child) child.kill();\n\n process.exit(0);\n });\n } catch (error) {\n sheu.error(\"Production server failed to start:\");\n console.error(error);\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the production server child process\n */\nexport function killProductionServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
|
|
@@ -8,6 +8,7 @@ import compression from "compression";
|
|
|
8
8
|
import { OpenApiConfig } from "./openapi-config";
|
|
9
9
|
import { UploadConfig } from "./upload-config";
|
|
10
10
|
import { BodyParserConfig } from "./body-parser-config";
|
|
11
|
+
import { Validator } from "../../../types/validation/validator";
|
|
11
12
|
type InferValidationType<T, Fallback> = T extends ZodSchema ? z.infer<T> : T extends new (...args: any[]) => infer I ? I : Fallback;
|
|
12
13
|
export type PathParams = string | RegExp | Array<string | RegExp>;
|
|
13
14
|
export type ArkosAnyRequestHandler = ArkosRequestHandler | ArkosErrorRequestHandler | Array<ArkosRequestHandler | ArkosErrorRequestHandler>;
|
|
@@ -20,13 +21,13 @@ export type ArkosAnyRequestHandler = ArkosRequestHandler | ArkosErrorRequestHand
|
|
|
20
21
|
*/
|
|
21
22
|
type RouterMethodHandler<T> = {
|
|
22
23
|
(config: PathParams, ...handlers: Array<ArkosAnyRequestHandler>): T;
|
|
23
|
-
<TQuery extends
|
|
24
|
-
<TQuery extends
|
|
24
|
+
<TQuery extends Validator = any, TBody extends Validator = any, TParams extends Validator = any>(config: ArkosRouteConfig<TQuery, TBody, TParams> | PathParams, ...handlers: Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any> | Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any>>>): T;
|
|
25
|
+
<TQuery extends Validator = any, TBody extends Validator = any, TParams extends Validator = any>(config: ArkosRouteConfig<TQuery, TBody, TParams> | PathParams, ...handlers: Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any> | Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, any>>>): T;
|
|
25
26
|
};
|
|
26
27
|
export type ArkosRouteMethodHandler<T> = {
|
|
27
28
|
(config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, "path">, ...handlers: Array<ArkosRequestHandler | ArkosErrorRequestHandler | Array<ArkosRequestHandler | ArkosErrorRequestHandler>>): T;
|
|
28
|
-
<TQuery extends
|
|
29
|
-
<TQuery extends
|
|
29
|
+
<TQuery extends Validator = any, TBody extends Validator = any, TParams extends Validator = any>(config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, "path">, ...handlers: Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals> | Array<ArkosRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals>>>): T;
|
|
30
|
+
<TQuery extends Validator = any, TBody extends Validator = any, TParams extends Validator = any>(config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, "path">, ...handlers: Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals> | Array<ArkosErrorRequestHandler<InferValidationType<TParams, Record<string, string>>, any, InferValidationType<TBody, any>, InferValidationType<TQuery, qs.ParsedQs>, Locals>>>): T;
|
|
30
31
|
};
|
|
31
32
|
export interface IArkosRoute extends IRoute {
|
|
32
33
|
/** GET method handler with route configuration support */
|