arkos 1.4.0-canary.46 → 1.4.0-canary.48
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/modules/auth/auth.service.js +4 -4
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +3 -4
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js +2 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/cjs/utils/cli/build.js +9 -13
- package/dist/cjs/utils/cli/build.js.map +1 -1
- package/dist/cjs/utils/cli/start.js +1 -0
- package/dist/cjs/utils/cli/start.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/dotenv.helpers.js +2 -1
- package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +4 -4
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +3 -4
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/index.js +2 -1
- package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/esm/utils/cli/build.js +9 -13
- package/dist/esm/utils/cli/build.js.map +1 -1
- package/dist/esm/utils/cli/start.js +1 -0
- package/dist/esm/utils/cli/start.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/dotenv.helpers.js +2 -1
- package/dist/esm/utils/dotenv.helpers.js.map +1 -1
- package/dist/types/utils/arkos-router/types/index.d.ts +2 -2
- package/package.json +1 -1
|
@@ -32,10 +32,10 @@ class AuthService {
|
|
|
32
32
|
}
|
|
33
33
|
signJwtToken(id, expiresIn, secret) {
|
|
34
34
|
const { authentication: configs } = (0, server_1.getArkosConfig)();
|
|
35
|
-
if (process.env.
|
|
35
|
+
if (process.env.ARKOS_BUILD === "true" &&
|
|
36
36
|
!process.env.JWT_SECRET &&
|
|
37
37
|
!configs?.jwt?.secret)
|
|
38
|
-
throw new app_error_1.default("Missing JWT secret on production!", 500,
|
|
38
|
+
throw new app_error_1.default("Missing JWT secret on production!", 500, "MissingJWTOnProduction");
|
|
39
39
|
secret =
|
|
40
40
|
secret ||
|
|
41
41
|
configs?.jwt?.secret ||
|
|
@@ -99,10 +99,10 @@ class AuthService {
|
|
|
99
99
|
}
|
|
100
100
|
async verifyJwtToken(token, secret) {
|
|
101
101
|
const { authentication: configs } = (0, server_1.getArkosConfig)();
|
|
102
|
-
if (process.env.
|
|
102
|
+
if (process.env.ARKOS_BUILD === "true" &&
|
|
103
103
|
!process.env.JWT_SECRET &&
|
|
104
104
|
!configs?.jwt?.secret)
|
|
105
|
-
throw new app_error_1.default("Missing JWT secret
|
|
105
|
+
throw new app_error_1.default("Missing JWT secret in production", 500, "MissingJWTSecretInProduction");
|
|
106
106
|
secret =
|
|
107
107
|
secret ||
|
|
108
108
|
configs?.jwt?.secret ||
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AAMrE,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QAyarD,iBAAY,GAAG,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ync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport { CookieOptions } from \"express\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n {},\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\"Missing JWT secret!\", 500);\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles;\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any>): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n if (!configs?.authentication)\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!user) throw loginRequiredError;\n if (user.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl && appModules.includes(kebabCase(resource)))\n accessControl = getModuleComponents(kebabCase(resource))?.authConfigs\n ?.accessControl;\n\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
|
|
1
|
+
{"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AAKrE,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA4arD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,WAAW,GAAG,IAAA,uBAAc,GAAE,CAAC;YACrC,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,CAAC;gBACjC,IAAI,EAAE,CAAC;gBACP,OAAO;YACT,CAAC;YAED,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC1D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAqFJ,CAAC;IAlgBC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;QAErD,IACE,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;YAClC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU;YACvB,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM;YAErB,MAAM,IAAI,mBAAQ,CAChB,mCAAmC,EACnC,GAAG,EACH,wBAAwB,CACzB,CAAC;QAEJ,MAAM;YACJ,MAAM;gBACN,OAAO,EAAE,GAAG,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,IAAA,oCAAmB,EAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC,EAAE,WAAW;wBACnE,EAAE,aAAa,CAAC;gBAEpB,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAhhBD,kCAghBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles;\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any>): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n if (!configs?.authentication)\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!user) throw loginRequiredError;\n if (user.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl && appModules.includes(kebabCase(resource)))\n accessControl = getModuleComponents(kebabCase(resource))?.authConfigs\n ?.accessControl;\n\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
|
|
@@ -45,7 +45,7 @@ function errorHandler(err, req, res, _) {
|
|
|
45
45
|
message: err.message,
|
|
46
46
|
stack: err?.stack || undefined,
|
|
47
47
|
};
|
|
48
|
-
if (process.env.
|
|
48
|
+
if (process.env.ARKOS_BUILD === "true")
|
|
49
49
|
delete error?.stack;
|
|
50
50
|
if (err.name === "JsonWebTokenError")
|
|
51
51
|
error = errorControllerHelper.handleJWTError();
|
|
@@ -85,7 +85,7 @@ function errorHandler(err, req, res, _) {
|
|
|
85
85
|
error = errorControllerHelper.handleVersionMismatchError(err);
|
|
86
86
|
if (err.name === "NetworkError")
|
|
87
87
|
error = errorControllerHelper.handleNetworkError(err);
|
|
88
|
-
if (process.env.
|
|
88
|
+
if (process.env.ARKOS_BUILD !== "true")
|
|
89
89
|
return sendDevelopmentError({
|
|
90
90
|
...error,
|
|
91
91
|
message: error.message,
|
|
@@ -139,8 +139,7 @@ function sendProductionError(err, req, res) {
|
|
|
139
139
|
});
|
|
140
140
|
}
|
|
141
141
|
process.on("SIGTERM", () => {
|
|
142
|
-
if (process.env.
|
|
143
|
-
process.env.NODE_ENV !== "staging") {
|
|
142
|
+
if (process.env.ARKOS_BUILD !== "true") {
|
|
144
143
|
process.exit();
|
|
145
144
|
}
|
|
146
145
|
else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAyEC;AA3FD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,YAAY;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE9D,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;IAEnD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B;QAC5C,KAAK,GAAG,qBAAqB,CAAC,iCAAiC,CAAC,GAAG,CAAC,CAAC;IACvE,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAiC;QAChD,KAAK,GAAG,qBAAqB,CAAC,qCAAqC,CAAC,GA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ACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.NODE_ENV == \"production\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAyEC;AA3FD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAA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IAAI,IAAI,EAAE;gBACpB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,SAAS;aAC5B,CAAC,CAAC;;YAEH,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACnB,MAAM,EAAE,OAAO;gBACf,OAAO,EAAE,gDAAgD;gBACzD,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,EAAE;aACT,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,SAAS;SAChB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":";;;;;AAmCA,8BA+FC;AAED,wDAqDC;AAzLD,qCAAiC;AAGjC,sFAA4D;AAC5D,oFAA0D;AAC1D,6CAAyE;AACzE,2CAA+C;AAC/C,+DAAyD;AAEzD,4EAAiD;AA0BjD,SAAwB,WAAW;IACjC,MAAM,MAAM,GAAiB,IAAA,gBAAM,GAAE,CAAC;IAEtC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;YACxB,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;YAE3D,MAAM,WAAW,GAAG;gBAClB,KAAK;gBACL,MAAM;gBACN,KAAK;gBACL,OAAO;gBACP,QAAQ;gBACR,KAAK;gBACL,MAAM;gBACN,OAAO;gBACP,SAAS;aACV,CAAC;YAMF,IAAI,WAAW,CAAC,QAAQ,CAAC,IAAc,CAAC,EAAE,CAAC;gBACzC,OAAO,UACL,MAAwB,EACxB,GAAG,QAAkC;oBAErC,MAAM,KAAK,GAAG,MAAM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AE,UAAU,EAAE,QAAQ,KAAK,KAAK;YACzC,CAAC,CAAC,4BAAe;YACjB,CAAC,CAAC,4BAAe,CAAC;QAErB,KAAa,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG;YAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YAChD,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YACxD,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC;YACnC,WAAW,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE;YAa9C,GAAG,OAAO;SACX,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport { extractArkosRoutes, getMiddlewareStack } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\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 * route: \"/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 default function ArkosRouter(): IArkosRouter {\n const router: IArkosRouter = Router();\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n const route = config.route;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig but recevied ${config}`\n );\n\n const method = prop as string;\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) =>\n typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : handler.map((nesteHandler: any) =>\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n )\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n // TEMPORARY: Wait for async initArkos() to complete\n // TODO(v1.5): Remove when migrating to arkos.config.ts (synchronous load)\n const start = Date.now();\n while (Date.now() - start < 100) {}\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })\"\n );\n\n if (!authenticationConfig?.mode && config.authentication)\n throw Error(\n \"Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })\"\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n return originalMethod.call(target, route, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport async function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n const arkosConfig = getArkosConfig();\n\n routes.forEach(async ({ path, method, config }) => {\n if (config?.openapi === false) return;\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.openapi === \"boolean\") {\n config = {\n ...config,\n openapi: {},\n };\n }\n\n const openapi =\n typeof config?.openapi === \"object\" && config.openapi !== null\n ? config.openapi\n : {};\n\n const validatorToJsonSchemaTransformer =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : zodToJsonSchema;\n\n (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${method} ${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n // ...(!openapi.requestBody &&\n // config?.validation?.body && {\n // requestBody: {\n // content: {\n // \"application/json\": {\n // schema: validatorToJsonSchemaTransformer(\n // config?.validation?.body as any\n // ),\n // },\n // },\n // },\n // }),\n ...openapi,\n };\n });\n\n return paths;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import { IRouter } from \"express\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport {
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import { IRouter } from \"express\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport {\n AccessControlRules,\n DetailedAccessControlRule,\n} from \"../../../types/auth\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../../types\";\nimport express from \"express\";\nimport compression from \"compression\";\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 MethodHandler = (\n config: ArkosRouteConfig,\n ...handlers: (ArkosRequestHandler | ArkosErrorRequestHandler)[]\n) => IRouter;\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 * route: \"/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\n extends Omit<\n IRouter,\n | \"get\"\n | \"post\"\n | \"put\"\n | \"patch\"\n | \"delete\"\n | \"options\"\n | \"head\"\n | \"trace\"\n | \"all\"\n > {\n /** GET method handler with route configuration support */\n get: MethodHandler;\n /** POST method handler with route configuration support */\n post: MethodHandler;\n /** PUT method handler with route configuration support */\n put: MethodHandler;\n /** PATCH method handler with route configuration support */\n patch: MethodHandler;\n /** DELETE method handler with route configuration support */\n delete: MethodHandler;\n /** OPTIONS method handler with route configuration support */\n options: MethodHandler;\n /** HEAD method handler with route configuration support */\n head: MethodHandler;\n /** TRACE method handler with route configuration support */\n trace: MethodHandler;\n /** ALL methods handler with route configuration support */\n all: MethodHandler;\n}\n\n/**\n * Configuration object for defining routes in the Arkos framework.\n */\nexport interface ArkosRouteConfig {\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n route: string;\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 * - 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 | {\n query?: ZodSchema | (new (...args: any[]) => object) | false;\n body?: ZodSchema | (new (...args: any[]) => object) | false;\n params?: ZodSchema | (new (...args: any[]) => object) | false;\n };\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 | Partial<OpenAPIV3.OperationObject>;\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?:\n | { parser: \"json\"; options?: Parameters<typeof express.json>[0] }\n | {\n parser: \"urlencoded\";\n options?: Parameters<typeof express.urlencoded>[0];\n }\n | { parser: \"raw\"; options?: Parameters<typeof express.raw>[0] }\n | { parser: \"text\"; options?: Parameters<typeof express.text>[0] }\n | false;\n /**\n * Defines\n *\n */\n}\n"]}
|
|
@@ -65,7 +65,7 @@ function getMiddlewareStack(config) {
|
|
|
65
65
|
if (typeof config.authentication === "object" &&
|
|
66
66
|
config.authentication.action &&
|
|
67
67
|
config.authentication.resource)
|
|
68
|
-
middlewares.push(services_1.authService.handleAccessControl(config.authentication.action, config.authentication.resource, config.authentication?.rule));
|
|
68
|
+
middlewares.push(services_1.authService.handleAccessControl(config.authentication.action, config.authentication.resource, { [config.authentication.action]: config.authentication?.rule }));
|
|
69
69
|
if (config.rateLimit)
|
|
70
70
|
middlewares.push((0, express_rate_limit_1.default)(config.rateLimit));
|
|
71
71
|
if (config.compression)
|
|
@@ -75,6 +75,7 @@ function getMiddlewareStack(config) {
|
|
|
75
75
|
if (typeof config?.bodyParser === "object" &&
|
|
76
76
|
["json", "urlencoded", "raw", "text"].includes(config?.bodyParser?.parser))
|
|
77
77
|
middlewares.push(express_1.default[config.bodyParser.parser](config.bodyParser.options));
|
|
78
|
+
middlewares.push();
|
|
78
79
|
middlewares.push((0, base_middlewares_1.validateRequestInputs)(config));
|
|
79
80
|
return middlewares;
|
|
80
81
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/index.ts"],"names":[],"mappings":";;;;;AASA,gDA+DC;AAED,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/index.ts"],"names":[],"mappings":";;;;;AASA,gDA+DC;AAED,gDAmCC;AA7GD,4EAA2C;AAC3C,2DAA2D;AAC3D,gFAAkF;AAClF,wFAA8D;AAE9D,sDAA8B;AAC9B,8DAAsC;AACtC,gFAAoE;AAEpE,SAAgB,kBAAkB,CAChC,GAAQ,EACR,QAAQ,GAAG,EAAE;IAMb,MAAM,MAAM,GAIP,EAAE,CAAC;IAER,SAAS,gBAAgB,CAAC,KAAY,EAAE,MAAM,GAAG,EAAE;QACjD,KAAK,CAAC,OAAO,CAAC,CAAC,KAAU,EAAE,EAAE;YAC3B,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;gBAChB,MAAM,QAAQ,GAAG,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC;gBAC3C,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;gBAEjD,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;oBACzB,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;oBACzC,IAAI,MAAoC,CAAC;oBAEzC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;wBAC/B,MAAM,WAAW,GAAG,+BAAmB,CAA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AAC,CAAC,CAAC;IAEhD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import rateLimit from \"express-rate-limit\";\nimport { authService } from \"../../../../exports/services\";\nimport { validateRequestInputs } from \"../../../../modules/base/base.middlewares\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { ArkosRouteConfig } from \"../../types\";\nimport express from \"express\";\nimport compression from \"compression\";\nimport { queryParser } from \"../../../helpers/query-parser.helpers\";\n\nexport function extractArkosRoutes(\n app: any,\n basePath = \"\"\n): Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n}> {\n const routes: Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n }> = [];\n\n function extractFromStack(stack: any[], prefix = \"\") {\n stack.forEach((layer: any) => {\n if (layer.route) {\n const fullPath = prefix + layer.route.path;\n const methods = Object.keys(layer.route.methods);\n\n methods.forEach((method) => {\n const handlers = layer.route.stack || [];\n let config: ArkosRouteConfig | undefined;\n\n for (const handler of handlers) {\n const foundConfig = RouteConfigRegistry.get(handler.handle);\n\n if (foundConfig) {\n config = foundConfig;\n routes.push({\n path: fullPath,\n method: method.toUpperCase(),\n config,\n });\n\n break;\n }\n }\n });\n } else if (layer.name === \"router\" && layer.handle?.stack) {\n let nestedPrefix = prefix;\n\n if (layer.regexp) {\n const match = layer.regexp\n .toString()\n .match(/\\/\\^?(\\\\\\/[^?]+|\\/[^?]+)/);\n if (match) {\n nestedPrefix = prefix + \"/\" + match[1].replace(/\\\\\\//g, \"/\");\n nestedPrefix = nestedPrefix\n .replace(/\\/\\//g, \"/\")\n .replace(/\\/$/, \"\");\n }\n }\n\n extractFromStack(layer.handle.stack, nestedPrefix);\n }\n });\n }\n\n const stack = app._router?.stack || app.stack;\n if (stack) extractFromStack(stack, basePath);\n\n return routes;\n}\n\nexport function getMiddlewareStack(config: ArkosRouteConfig) {\n const middlewares = [];\n\n if (config.authentication) middlewares.push(authService.authenticate);\n\n if (\n typeof config.authentication === \"object\" &&\n config.authentication.action &&\n config.authentication.resource\n )\n middlewares.push(\n authService.handleAccessControl(\n config.authentication.action,\n config.authentication.resource,\n { [config.authentication.action]: config.authentication?.rule }\n )\n );\n\n if (config.rateLimit) middlewares.push(rateLimit(config.rateLimit));\n if (config.compression) middlewares.push(compression(config.compression));\n if (config.queryParser) middlewares.push(queryParser(config.queryParser));\n\n if (\n typeof config?.bodyParser === \"object\" &&\n [\"json\", \"urlencoded\", \"raw\", \"text\"].includes(config?.bodyParser?.parser)\n )\n middlewares.push(\n express[config.bodyParser.parser](config.bodyParser.options)\n );\n\n middlewares.push();\n\n middlewares.push(validateRequestInputs(config));\n\n return middlewares;\n}\n"]}
|
|
@@ -16,8 +16,9 @@ const BUILD_DIR = ".build";
|
|
|
16
16
|
const MODULE_TYPES = ["cjs", "esm"];
|
|
17
17
|
function buildCommand(options = {}) {
|
|
18
18
|
const fileExt = (0, fs_helpers_1.getUserFileExtension)();
|
|
19
|
-
process.env.NODE_ENV
|
|
20
|
-
|
|
19
|
+
if (process.env.NODE_ENV === "test" || !process.env.NODE_ENV)
|
|
20
|
+
process.env.NODE_ENV = "production";
|
|
21
|
+
process.env.ARKOS_BUILD = "true";
|
|
21
22
|
const envFiles = (0, dotenv_helpers_1.loadEnvironmentVariables)();
|
|
22
23
|
const moduleType = validateModuleType(options.module);
|
|
23
24
|
try {
|
|
@@ -27,12 +28,10 @@ function buildCommand(options = {}) {
|
|
|
27
28
|
.replaceAll("/", "")}`);
|
|
28
29
|
console.info(`\n Creating an optimized production build...`);
|
|
29
30
|
ensureBuildDir();
|
|
30
|
-
if (fileExt === "ts")
|
|
31
|
+
if (fileExt === "ts")
|
|
31
32
|
buildTypeScriptProject(options, moduleType);
|
|
32
|
-
|
|
33
|
-
else {
|
|
33
|
+
else
|
|
34
34
|
buildJavaScriptProject(options, moduleType);
|
|
35
|
-
}
|
|
36
35
|
const packageManger = (0, global_helpers_1.detectPackageManagerFromUserAgent)();
|
|
37
36
|
console.info(`\n\x1b[1m\x1b[32m Build complete!\x1b[0m\n`);
|
|
38
37
|
console.info(` \x1b[1mNext step:\x1b[0m`);
|
|
@@ -49,19 +48,16 @@ function validateModuleType(moduleType) {
|
|
|
49
48
|
if (!moduleType)
|
|
50
49
|
return "cjs";
|
|
51
50
|
const normalizedType = moduleType.toLowerCase();
|
|
52
|
-
if (normalizedType === "cjs" || normalizedType === "commonjs")
|
|
51
|
+
if (normalizedType === "cjs" || normalizedType === "commonjs")
|
|
53
52
|
return "cjs";
|
|
54
|
-
|
|
55
|
-
else if (["esm", "es", "es2020", "esnext", "module"].includes(normalizedType)) {
|
|
53
|
+
else if (["esm", "es", "es2020", "esnext", "module"].includes(normalizedType))
|
|
56
54
|
return "esm";
|
|
57
|
-
}
|
|
58
|
-
console.warn(`⚠️ Unrecognized module type "${moduleType}", defaulting to "cjs"`);
|
|
55
|
+
sheu_1.default.warn(`Unrecognized module type "${moduleType}", defaulting to "cjs"`);
|
|
59
56
|
return "cjs";
|
|
60
57
|
}
|
|
61
58
|
function ensureBuildDir() {
|
|
62
|
-
if (!fs_1.default.existsSync(BUILD_DIR))
|
|
59
|
+
if (!fs_1.default.existsSync(BUILD_DIR))
|
|
63
60
|
fs_1.default.mkdirSync(BUILD_DIR, { recursive: true });
|
|
64
|
-
}
|
|
65
61
|
for (const moduleType of MODULE_TYPES) {
|
|
66
62
|
const moduleDir = path_1.default.join(BUILD_DIR, moduleType);
|
|
67
63
|
if (!fs_1.default.existsSync(moduleDir)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":";;;;;AAsBA,oCAyCC;AA/DD,gDAAwB;AACxB,4CAAoB;AACpB,iDAAyC;AACzC,sDAA2E;AAC3E,sDAA6D;AAC7D,qDAAiD;AACjD,8DAA8E;AAC9E,mDAA2B;AAG3B,MAAM,SAAS,GAAG,QAAQ,CAAC;AAC3B,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,KAA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,gBAAgB,CAAC,IAAI,GAAG,QAAQ,CAAC;QACnC,CAAC;QAED,MAAM,SAAS,GAAG,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;QACnD,YAAE,CAAC,aAAa,CACd,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EACpC,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC,CAC1C,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CACV,wDAAwD,EACxD,KAAK,CACN,CAAC;IACJ,CAAC;AACH,CAAC;AAKD,SAAS,iBAAiB,CAAC,UAAkB;IAC3C,IAAI,CAAC;QACH,IAAI,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC;YAAE,YAAE,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 { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { getVersion } from \"./utils/cli.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\n\n// Constants\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 process.env.NODE_ENV = \"production\";\n process.env.NODE_ENV = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\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 // Detect project type\n\n if (fileExt === \"ts\") {\n buildTypeScriptProject(options, moduleType);\n } else {\n buildJavaScriptProject(options, moduleType);\n }\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 // Map common terms to our module types\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") {\n return \"cjs\";\n } else if (\n [\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType)\n ) {\n return \"esm\";\n }\n\n // Default to CJS if unrecognized\n console.warn(\n `⚠️ Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`\n );\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) {\n fs.mkdirSync(BUILD_DIR, { recursive: true });\n }\n\n // Create module-specific subdirectories\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 // Read the user's tsconfig.json\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n // Continue with default config\n }\n\n // Create a custom tsconfig that outputs to our build directory with the correct module type\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n // module: moduleType === \"esm\" ? \"ESNext\" : \"CommonJS\",\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 execSync(`npx trash ${BUILD_DIR} && npx tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n\n // Clean up temp config\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 // Create appropriate package.json in the build directory\n createModulePackageJson(moduleType);\n } catch (error) {\n console.error(\"❌ Error building JavaScript project:\", error);\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 = [\"README.md\", \"LICENSE\"];\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 * Create appropriate package.json in the build directory\n */\nfunction createModulePackageJson(moduleType: ModuleType) {\n const packageJsonPath = path.join(process.cwd(), \"package.json\");\n\n if (!fs.existsSync(packageJsonPath)) {\n return;\n }\n\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n const buildPackageJson: any = {\n name: packageJson.name,\n version: packageJson.version,\n description: packageJson.description,\n main: \"index.js\",\n dependencies: packageJson.dependencies,\n };\n\n // Set appropriate type field for ESM\n if (moduleType === \"esm\") {\n buildPackageJson.type = \"module\";\n }\n\n const targetDir = path.join(BUILD_DIR, moduleType);\n fs.writeFileSync(\n path.join(targetDir, \"package.json\"),\n JSON.stringify(buildPackageJson, null, 2)\n );\n } catch (error) {\n console.warn(\n \"Warning: Failed to create module-specific package.json\",\n error\n );\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":";;;;;AAqBA,oCAqCC;AA1DD,gDAAwB;AACxB,4CAAoB;AACpB,iDAAyC;AACzC,sDAA2E;AAC3E,sDAA6D;AAC7D,qDAAiD;AACjD,8DAA8E;AAC9E,mDAA2B;AAE3B,MAAM,SAAS,GAAG,QAAQ,CAAC;AAC3B,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,KAAK,CAAU,CAAC;AAW7C,SAAgB,YAAY,CAAC,UAAwB,EAAE;IACrD,MAAM,OAAO,GAAG,IAAA,iCAAoB,GAAE,CAAC;IACvC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ;QAC1D,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,YAAY,CAAC;IACtC,OAAO,CAAC,GAAG,CA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IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CACV,wDAAwD,EACxD,KAAK,CACN,CAAC;IACJ,CAAC;AACH,CAAC;AAKD,SAAS,iBAAiB,CAAC,UAAkB;IAC3C,IAAI,CAAC;QACH,IAAI,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC;YAAE,YAAE,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 { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { getVersion } from \"./utils/cli.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\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 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\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\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 execSync(`npx trash ${BUILD_DIR} && npx tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n\n // Clean up temp config\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 // Create appropriate package.json in the build directory\n createModulePackageJson(moduleType);\n } catch (error) {\n console.error(\"❌ Error building JavaScript project:\", error);\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 = [\"README.md\", \"LICENSE\"];\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 * Create appropriate package.json in the build directory\n */\nfunction createModulePackageJson(moduleType: ModuleType) {\n const packageJsonPath = path.join(process.cwd(), \"package.json\");\n\n if (!fs.existsSync(packageJsonPath)) {\n return;\n }\n\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n const buildPackageJson: any = {\n name: packageJson.name,\n version: packageJson.version,\n description: packageJson.description,\n main: \"index.js\",\n dependencies: packageJson.dependencies,\n };\n\n // Set appropriate type field for ESM\n if (moduleType === \"esm\") {\n buildPackageJson.type = \"module\";\n }\n\n const targetDir = path.join(BUILD_DIR, moduleType);\n fs.writeFileSync(\n path.join(targetDir, \"package.json\"),\n JSON.stringify(buildPackageJson, null, 2)\n );\n } catch (error) {\n console.warn(\n \"Warning: Failed to create module-specific package.json\",\n error\n );\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"]}
|
|
@@ -17,6 +17,7 @@ let envFiles;
|
|
|
17
17
|
async function startCommand(options = {}) {
|
|
18
18
|
if (process.env.NODE_ENV === "test" || !process.env.NODE_ENV)
|
|
19
19
|
process.env.NODE_ENV = "production";
|
|
20
|
+
process.env.ARKOS_BUILD = "true";
|
|
20
21
|
envFiles = (0, dotenv_helpers_1.loadEnvironmentVariables)();
|
|
21
22
|
try {
|
|
22
23
|
const { port, host } = options;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.js","sourceRoot":"","sources":["../../../../src/utils/cli/start.ts"],"names":[],"mappings":";;;;;AAmBA,
|
|
1
|
+
{"version":3,"file":"start.js","sourceRoot":"","sources":["../../../../src/utils/cli/start.ts"],"names":[],"mappings":";;;;;AAmBA,oCAsDC;AAKD,4EAGC;AAjFD,gDAAwB;AACxB,4CAAoB;AACpB,iDAAoD;AACpD,sDAA6D;AAC7D,sDAAqD;AACrD,kGAAuE;AACvE,kFAAyD;AAOzD,IAAI,KAAK,GAAwB,IAAI,CAAC;AACtC,IAAI,QAA8B,CAAC;AAK5B,KAAK,UAAU,YAAY,CAAC,UAAwB,EAAE;IAC3D,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ;QAC1D,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,YAAY,CAAC;IACtC,OAAO,CAAC,GAAG,CAAC,WAAW,GAAG,MAAM,CAAC;IAEjC,QAAQ,GAAG,IAAA,yCAAwB,GAAE,CAAC;IAEtC,IAAI,CAAC;QACH,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAE/B,MAAM,UAAU,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OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,SAAgB,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 portAndHostAllocator from \"../features/port-and-host-allocator\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\n\ninterface StartOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Production start command for the arkos CLI\n */\nexport async function startCommand(options: StartOptions = {}) {\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 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 console.error(\n `❌ Could not find built application entry point at ${fullCleanCwd(entryPoint)}`\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 };\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\n const hostAndPort = await portAndHostAllocator.getHostAndAvailablePort(\n env,\n {\n logWarning: true,\n }\n );\n\n watermarkStamper.stamp({\n envFiles,\n ...hostAndPort,\n });\n } catch (error) {\n console.error(\"❌ Production server failed to start:\", 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"]}
|
|
@@ -20,7 +20,7 @@ function loadEnvironmentVariables() {
|
|
|
20
20
|
];
|
|
21
21
|
envFiles.forEach((filePath) => {
|
|
22
22
|
if (fs_1.default.existsSync(filePath)) {
|
|
23
|
-
if (
|
|
23
|
+
if (process.env.ARKOS_BUILD === "true" && filePath.endsWith(".local"))
|
|
24
24
|
console.info(`Skipping the local ${filePath.replace(cwd, "")} files in production`);
|
|
25
25
|
else {
|
|
26
26
|
const result = dotenv_1.default.config({ path: filePath, override: true });
|
|
@@ -36,6 +36,7 @@ function loadEnvironmentVariables() {
|
|
|
36
36
|
const missingVars = requiredVars.filter((varName) => !process.env[varName]);
|
|
37
37
|
if (missingVars.length > 0) {
|
|
38
38
|
console.error("Missing required environment variables:", missingVars.join(", "));
|
|
39
|
+
throw new Error(`Missing required environment variables: ${missingVars.join(", ")}`);
|
|
39
40
|
}
|
|
40
41
|
if (loadedEnvs)
|
|
41
42
|
return loadedEnvs;
|