arkos 1.5.11-beta → 1.5.12-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/app.js +39 -28
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +2 -0
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/base/base.controller.js +15 -3
- package/dist/cjs/modules/base/base.controller.js.map +1 -1
- package/dist/cjs/modules/base/base.service.js +5 -0
- package/dist/cjs/modules/base/base.service.js.map +1 -1
- package/dist/cjs/modules/file-upload/file-upload.router.js +2 -0
- package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/cjs/types/new-arkos-config.js.map +1 -1
- package/dist/cjs/utils/bundler.js.map +1 -1
- package/dist/cjs/utils/cli/build.js +1 -2
- package/dist/cjs/utils/cli/build.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/features/api.features.js +20 -9
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/esm/app.js +40 -29
- package/dist/esm/app.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +2 -0
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/base/base.controller.js +15 -3
- package/dist/esm/modules/base/base.controller.js.map +1 -1
- package/dist/esm/modules/base/base.service.js +5 -0
- package/dist/esm/modules/base/base.service.js.map +1 -1
- package/dist/esm/modules/file-upload/file-upload.router.js +2 -0
- package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/esm/types/new-arkos-config.js.map +1 -1
- package/dist/esm/utils/bundler.js.map +1 -1
- package/dist/esm/utils/cli/build.js +1 -2
- package/dist/esm/utils/cli/build.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/features/api.features.js +20 -9
- package/dist/esm/utils/features/api.features.js.map +1 -1
- package/dist/types/modules/auth/auth.service.d.ts +2 -6
- package/dist/types/modules/base/base.service.d.ts +3 -1
- package/dist/types/types/new-arkos-config.d.ts +79 -39
- package/dist/types/utils/bundler.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":";;;;;;AAAA,iFAIiD;AACjD,+DAAiE;AACjE,4FAA6D;AAC7D,+EAG8C;AAC9C,uEAAuE;AACvE,wEAA+C;AAS/C,0FAAgE;AAChE,mGAAyE;AA6GzE,MAAa,WAAW;IAKtB,YAAY,SAAqB;QAezB,qBAAgB,GAAG,CAAC,MAA8B,EAAE,EAAE;YAC5D,OAAO,KAAK,EAAE,GAAG,IAAW,EAAgB,EAAE;gBAC5C,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAuB,CAAC;gBAE5D,IAAI,CAAC;oBACH,IAAI,6BAA6B,GAC/B,MAAM,IAAI,CAAC,2BAA2B,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;oBACvD,IAAI,eAAe,GAAG,MAAM,IAAI,CAAC,qBAAqB,CACpD,6BAA6B,EAC7B,MAAM,CACP,CAAC;oBAEF,MAAM,IAAI,CAAC,YAAY,CACrB,QAAQ,EACR,MAAM,CAAC,aAAa,EACpB,IAAI,CAAC,eAAe,CAAC,6BAA6B,EAAE,MAAM,CAAC,EAC3D,OAAO,CACR,CAAC;oBAEF,IAAI,MAAM,CAAC,KAAK,EAAE,eAAe;wBAC/B,MAAM,MAAM,CAAC,KAAK,CAAC,eAAe,CAChC,IAAI,CAAC,eAAe,CAAC,6BAA6B,EAAE,MAAM,CAAC,CAC5D,CAAC;oBAEJ,IAAI,MAAM,CAAC,KAAK,EAAE,YAAY,EAAE,CAAC;wBAC/B,6BAA6B,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,YAAY,CAC7D,6BAA6B,EAC7B,IAAI,CAAC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AAE,aAAa;YAC5B,YAAY,EAAE,QAAQ;YACtB,uBAAuB,EAAE,IAAI;YAC7B,sBAAsB,EAAE,EAAE;YAC1B,eAAe,EAAE,SAAS;SAC3B,CAAC,CAAC,SAAS,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IACvC,CAAC;IAgBD,KAAK,CAAC,WAAW,CACf,YAAiD,EACjD,OAA4B;QAE5B,OAAO,IAAI,CAAC,2BAA2B,CAAC;YACtC,aAAa,EAAE,aAAa;YAC5B,YAAY,EAAE,QAAQ;YACtB,sBAAsB,EAAE,EAAE;YAC1B,eAAe,EAAE,SAAS;SAC3B,CAAC,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IAC5B,CAAC;CACF;AA1zBD,kCA0zBC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport {\n handleRelationFieldsInBody,\n ModelGroupRelationFields,\n} from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\nimport {\n PrismaModels,\n PrismaClient,\n ExtractPrismaFilters,\n ExtractPrismaData,\n ExtractPrismaQueryOptions,\n} from \"../../generated\";\nimport { ServiceBaseContext } from \"./types/base.service.types\";\nimport serviceHooksManager from \"./utils/service-hooks-manager\";\nimport prismaSchemaParser from \"../../utils/prisma/prisma-schema-parser\";\n\ntype Models = PrismaModels<any>;\n\ntype Delegate<TModelName extends keyof Models> = Models[TModelName][\"Delegate\"];\n\ntype CreateData<TModelName extends keyof Models> = ExtractPrismaData<\n Models[TModelName][\"CreateArgs\"]\n>;\ntype CreateManyData<TModelName extends keyof Models> = ExtractPrismaData<\n Models[TModelName][\"CreateManyArgs\"]\n>;\ntype CreateOptions<TModelName extends keyof Models> = ExtractPrismaQueryOptions<\n Models[TModelName][\"CreateArgs\"],\n \"data\"\n>;\ntype CreateManyOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<Models[TModelName][\"CreateManyArgs\"], \"data\">;\n\ntype CountFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"CountArgs\"]\n>;\n\ntype FindManyFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"FindManyArgs\"]\n>;\ntype FindManyOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<Models[TModelName][\"FindManyArgs\"], \"where\">;\n\ntype FindOneFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"FindFirstArgs\"]\n>;\ntype FindOneOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<Models[TModelName][\"FindFirstArgs\"], \"where\">;\n\ntype UpdateOneFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"UpdateArgs\"]\n>;\ntype UpdateOneData<TModelName extends keyof Models> = ExtractPrismaData<\n Models[TModelName][\"UpdateArgs\"]\n>;\ntype UpdateOneOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<Models[TModelName][\"UpdateArgs\"], \"where\" | \"data\">;\n\ntype UpdateManyFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"UpdateManyArgs\"]\n>;\ntype UpdateManyData<TModelName extends keyof Models> = ExtractPrismaData<\n Models[TModelName][\"UpdateManyArgs\"]\n>;\ntype UpdateManyOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<\n Models[TModelName][\"UpdateManyArgs\"],\n \"where\" | \"data\"\n >;\n\ntype DeleteOneFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"DeleteArgs\"]\n>;\ntype DeleteManyFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"DeleteManyArgs\"]\n>;\n\ntype GetPayload<\n TModelName extends keyof Models,\n TOptions extends Record<string, any>,\n> = PrismaModels<TOptions>[TModelName][\"GetPayload\"];\n\nexport interface ServiceOperationHooks {\n beforeOperation?: (params: any) => void | Promise<void>;\n afterOperation?: (result: any, params: any) => void | Promise<void>;\n beforePrisma?: (prismaArgs: any, params: any) => any | Promise<any>;\n afterPrisma?: (result: any, params: any) => any | Promise<any>;\n}\n\ninterface ServiceOperationConfig {\n operationType: string;\n prismaMethod: string;\n requiresPasswordHashing?: boolean;\n relationFieldsHandling?: string[];\n returnsFallback?: any;\n customPrismaLogic?: (\n args: any[],\n prisma: PrismaClient,\n config: ServiceOperationConfig,\n context: BaseService<any>\n ) => Promise<any>;\n hooks?: ServiceOperationHooks;\n}\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n * by model-specific service classes.\n *\n * @class BaseService\n *\n * @example\n * ```ts\n * import { BaseService } from \"arkos/services\";\n *\n * export class UserService extends BaseService<\"user\"> {}\n *\n * const userService = new UserService(\"user\");\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-service-class}\n * @see {@link https://www.arkosjs.com/docs/guide/accessing-request-context-in-services}\n */\nexport class BaseService<TModelName extends keyof Models = keyof Models> {\n modelName: TModelName;\n relationFields: ModelGroupRelationFields;\n // prisma: PrismaClient;\n\n constructor(modelName: TModelName) {\n this.modelName = camelCase(modelName as string) as TModelName;\n const modelFields = prismaSchemaParser.getModelRelations(\n modelName as string\n );\n\n this.relationFields = {\n singular:\n modelFields?.filter((field) => field.isRelation && !field.isArray) ||\n [],\n list:\n modelFields?.filter((field) => field.isRelation && field.isArray) || [],\n };\n }\n\n private executeOperation = (config: ServiceOperationConfig) => {\n return async (...args: any[]): Promise<any> => {\n const context = args[args.length - 1] as ServiceBaseContext;\n\n try {\n let argsWithRelationFieldsHandled =\n await this.processRelationFieldsInBody(args, config);\n let prismaFinalArgs = await this.handlePasswordHashing(\n argsWithRelationFieldsHandled,\n config\n );\n\n await this.executeHooks(\n \"before\",\n config.operationType,\n this.buildHookParams(argsWithRelationFieldsHandled, config),\n context\n );\n\n if (config.hooks?.beforeOperation)\n await config.hooks.beforeOperation(\n this.buildHookParams(argsWithRelationFieldsHandled, config)\n );\n\n if (config.hooks?.beforePrisma) {\n argsWithRelationFieldsHandled = await config.hooks.beforePrisma(\n argsWithRelationFieldsHandled,\n this.buildHookParams(argsWithRelationFieldsHandled, config)\n );\n }\n\n const prisma = getPrismaInstance();\n let result: any;\n\n if (config.customPrismaLogic) {\n result = await config.customPrismaLogic(\n argsWithRelationFieldsHandled,\n prisma,\n config,\n this\n );\n } else {\n const prismaArgs = this.buildPrismaArgs(prismaFinalArgs, config);\n result = await (\n prisma[this.modelName as string] as Delegate<TModelName>\n )[config.prismaMethod](prismaArgs);\n }\n\n if (config.hooks?.afterPrisma) {\n result = await config.hooks.afterPrisma(\n result,\n this.buildHookParams(argsWithRelationFieldsHandled, config)\n );\n }\n\n await this.executeHooks(\n \"after\",\n config.operationType,\n {\n ...this.buildHookParams(argsWithRelationFieldsHandled, config),\n result,\n },\n context\n );\n\n if (config.hooks?.afterOperation) {\n await config.hooks.afterOperation(\n result,\n this.buildHookParams(argsWithRelationFieldsHandled, config)\n );\n }\n\n return result;\n } catch (err: any) {\n await this.executeHooks(\n \"error\",\n config.operationType,\n { ...this.buildHookParams(args, config), error: err },\n context\n );\n if (context?.throwOnError !== false) throw err;\n return config.returnsFallback;\n }\n };\n };\n\n private executeTransactionOperation = (config: ServiceOperationConfig) => {\n return async (...args: any[]): Promise<any> => {\n const context = args[args.length - 1] as ServiceBaseContext;\n\n try {\n let argsWithRelationFieldsHandled =\n await this.processRelationFieldsInBody(args, config);\n let prismaFinalArgs = await this.handlePasswordHashing(\n argsWithRelationFieldsHandled,\n config\n );\n\n await this.executeHooks(\n \"before\",\n config.operationType,\n this.buildTransactionHookParams(\n argsWithRelationFieldsHandled,\n config\n ),\n context\n );\n\n const prisma = getPrismaInstance();\n const results = await this.executeTransactionLogic(\n prismaFinalArgs,\n config,\n prisma\n );\n\n await this.executeHooks(\n \"after\",\n config.operationType,\n {\n ...this.buildTransactionHookParams(\n argsWithRelationFieldsHandled,\n config\n ),\n results,\n },\n context\n );\n return results;\n } catch (err: any) {\n await this.executeHooks(\n \"error\",\n config.operationType,\n { ...this.buildTransactionHookParams(args, config), error: err },\n context\n );\n if (context?.throwOnError !== false) throw err;\n return config.returnsFallback;\n }\n };\n };\n\n private async executeHooks(\n hookType: \"before\" | \"after\" | \"error\",\n operationType: string,\n params: any,\n context?: ServiceBaseContext\n ): Promise<void> {\n const serviceHooks = getModuleComponents(this.modelName as string)?.hooks;\n if (!serviceHooks) return;\n\n const skipCondition =\n context?.skip === hookType ||\n context?.skip === \"all\" ||\n (Array.isArray(context?.skip) && context.skip.includes(hookType));\n\n if (skipCondition) return;\n\n const hookName = `${hookType === \"error\" ? \"on\" : hookType}${operationType.charAt(0).toUpperCase()}${operationType.slice(1)}${hookType === \"error\" ? \"Error\" : \"\"}`;\n const hook = serviceHooks[hookName as keyof typeof serviceHooks];\n\n if (hook) await serviceHooksManager.handleHook(hook, params);\n }\n\n private buildHookParams(args: any[], config: ServiceOperationConfig): any {\n const context = args[args.length - 1];\n\n switch (config.operationType) {\n case \"createOne\":\n case \"createMany\":\n return { data: args[0], queryOptions: args[1], context };\n case \"findMany\":\n return { filters: args[0], queryOptions: args[1], context };\n case \"findById\":\n return { id: args[0], queryOptions: args[1], context };\n case \"findOne\":\n return { filters: args[0], queryOptions: args[1], context };\n case \"updateOne\":\n return {\n filters: args[0],\n data: args[1],\n queryOptions: args[2],\n context,\n };\n case \"updateMany\":\n return {\n filters: args[0],\n data: args[1],\n queryOptions: args[2],\n context,\n };\n case \"deleteOne\":\n return { filters: args[0], context };\n case \"deleteMany\":\n return { filters: args[0], context };\n case \"count\":\n return { filters: args[0], context };\n default:\n return { context };\n }\n }\n\n private buildTransactionHookParams(\n args: any[],\n config: ServiceOperationConfig\n ): any {\n const context = args[args.length - 1];\n\n switch (config.operationType) {\n case \"batchUpdate\":\n return { data: args[0], queryOptions: args[1], context };\n case \"batchDelete\":\n return { batchFilters: args[0], context };\n default:\n return { context };\n }\n }\n\n private async handlePasswordHashing(\n args: any[],\n config: ServiceOperationConfig\n ): Promise<any[]> {\n let processedArgs = [...args];\n\n if (config.requiresPasswordHashing) {\n const dataIndex = config.operationType.includes(\"update\") ? 1 : 0;\n const data = processedArgs[dataIndex];\n\n if (Array.isArray(data)) {\n for (const i in data) {\n if (this.shouldHashPassword(data[i]))\n processedArgs[dataIndex][i] = await this.processPasswordHashing(\n data[i]\n );\n }\n } else if (this.shouldHashPassword(data)) {\n processedArgs[dataIndex] = await this.processPasswordHashing(data);\n }\n }\n\n return processedArgs;\n }\n\n private async processRelationFieldsInBody(\n args: any[],\n config: ServiceOperationConfig\n ): Promise<any[]> {\n let processedArgs = [...args];\n\n if (config.relationFieldsHandling) {\n const dataIndex = config.operationType.includes(\"update\") ? 1 : 0;\n\n if (config.operationType === \"batchUpdate\") {\n const dataArray = processedArgs[0];\n if (Array.isArray(dataArray)) {\n processedArgs[0] = dataArray.map((data) =>\n handleRelationFieldsInBody(\n data as Record<string, any>,\n this.relationFields,\n config.relationFieldsHandling\n )\n );\n }\n } else if (config.operationType === \"batchDelete\") {\n const batchFilters = processedArgs[0];\n if (Array.isArray(batchFilters)) {\n processedArgs[0] = batchFilters.map((filters) =>\n handleRelationFieldsInBody(\n filters as Record<string, any>,\n this.relationFields\n )\n );\n }\n } else if (config.operationType === \"createMany\") {\n const data = processedArgs[dataIndex];\n if (Array.isArray(data)) {\n processedArgs[dataIndex] = data.map((item) =>\n handleRelationFieldsInBody(\n item as Record<string, any>,\n this.relationFields,\n config.relationFieldsHandling\n )\n );\n }\n } else {\n const data = processedArgs[dataIndex];\n if (data) {\n processedArgs[dataIndex] = handleRelationFieldsInBody(\n data as Record<string, any>,\n this.relationFields,\n config.relationFieldsHandling\n );\n }\n }\n }\n\n return processedArgs;\n }\n\n private buildPrismaArgs(args: any[], config: ServiceOperationConfig): any {\n switch (config.operationType) {\n case \"createOne\":\n case \"createMany\":\n return deepmerge({ data: args[0] }, args[1] || {});\n case \"findMany\":\n return deepmerge({ where: args[0] }, args[1] || {});\n case \"findById\":\n return deepmerge({ where: { id: args[0] } }, args[1] || {});\n case \"findOne\":\n return deepmerge({ where: args[0] }, args[1] || {});\n case \"updateOne\":\n return deepmerge({ where: args[0], data: args[1] }, args[2] || {});\n case \"updateMany\":\n const firstMerge = deepmerge({ data: args[1] }, args[2] || {});\n return deepmerge({ where: args[0] }, firstMerge);\n case \"deleteOne\":\n case \"deleteMany\":\n return { where: args[0] };\n case \"count\":\n return { where: args[0] };\n default:\n return {};\n }\n }\n\n private async executeTransactionLogic(\n args: any[],\n config: ServiceOperationConfig,\n prisma: PrismaClient\n ): Promise<any> {\n if (config.operationType === \"batchUpdate\") {\n const dataArray = args[0];\n const queryOptions = args[1];\n\n return await (prisma as any).$transaction(async (tx: any) => {\n const updatePromises = dataArray.map(async (data: any) => {\n let processedData = data;\n if (this.shouldHashPassword(data)) {\n processedData = await this.processPasswordHashing(data);\n }\n\n const finalPrismaQueryParams = handleRelationFieldsInBody(\n {\n batchedData: {\n ...processedData,\n apiAction: \"update\",\n },\n } as Record<string, any>,\n {\n singular: [\n {\n ...prismaSchemaParser.getField({\n type: pascalCase(this.modelName as string),\n })!,\n name: \"batchedData\",\n },\n ],\n list: [],\n }\n );\n\n return await tx[this.modelName as string].update(\n deepmerge(\n finalPrismaQueryParams.batchedData?.update,\n queryOptions || {}\n ) as { where: any; data: any }\n );\n });\n\n return await Promise.all(updatePromises);\n });\n }\n\n if (config.operationType === \"batchDelete\") {\n const batchFilters = args[0];\n\n return await (prisma as any).$transaction(async (tx: any) => {\n const deletePromises = batchFilters.map(async (filters: any) => {\n return await tx[this.modelName as string].delete({ where: filters });\n });\n\n return await Promise.all(deletePromises);\n });\n }\n\n throw new Error(`Unknown transaction operation: ${config.operationType}`);\n }\n\n private shouldHashPassword(data: any): boolean {\n return kebabCase(this.modelName as string) === \"user\" && data?.password;\n }\n\n private async processPasswordHashing(data: any): Promise<any> {\n if (Array.isArray(data)) {\n const processedArray: any[] = [];\n for (let i = 0; i < data.length; i++) {\n const curr = data[i];\n if (\n \"password\" in curr &&\n !authService.isPasswordHashed(curr.password!)\n ) {\n processedArray[i] = {\n ...curr,\n password: await authService.hashPassword(curr.password!),\n };\n } else {\n processedArray[i] = curr;\n }\n }\n return processedArray;\n } else {\n if (data.password && !authService.isPasswordHashed(data.password)) {\n return {\n ...data,\n password: await authService.hashPassword(data.password),\n };\n }\n }\n return data;\n }\n\n // ─── Public API ─────────────────────────────────────────────────────────────\n\n /**\n * Creates a single record in the database.\n *\n * @param data - The data for creating the record\n * @param queryOptions - Optional Prisma query options (select, include, etc.)\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const user = await userService.createOne({\n * name: \"John Doe\",\n * email: \"john@example.com\"\n * });\n * ```\n */\n async createOne<TOptions extends CreateOptions<TModelName>>(\n data: CreateData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>> {\n return this.executeOperation({\n operationType: \"createOne\",\n prismaMethod: \"create\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [\"delete\", \"disconnect\", \"update\"],\n returnsFallback: undefined,\n })(data, queryOptions, context);\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param data - Array of data objects or object with data array\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const result = await userService.createMany([\n * { name: \"John Doe\", email: \"john@example.com\" },\n * { name: \"Jane Smith\", email: \"jane@example.com\" }\n * ]);\n * ```\n */\n async createMany<TOptions extends CreateManyOptions<TModelName>>(\n data: CreateManyData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>[]> {\n return this.executeOperation({\n operationType: \"createMany\",\n prismaMethod: \"createMany\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [\"delete\", \"disconnect\", \"update\"],\n returnsFallback: undefined,\n })(data, queryOptions, context);\n }\n\n /**\n * Counts records matching the specified filters.\n *\n * @param filters - Optional where conditions\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const total = await userService.count({ status: \"active\" });\n * ```\n */\n async count(\n filters?: CountFilters<TModelName>,\n context?: ServiceBaseContext\n ): Promise<number> {\n return this.executeOperation({\n operationType: \"count\",\n prismaMethod: \"count\",\n returnsFallback: 0,\n })(filters, context);\n }\n\n /**\n * Finds multiple records matching the specified filters.\n *\n * @param filters - Optional where conditions\n * @param queryOptions - Optional Prisma query options (select, include, orderBy, skip, take, etc.)\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const users = await userService.findMany(\n * { status: \"active\" },\n * { orderBy: { createdAt: \"desc\" }, take: 10 }\n * );\n * ```\n */\n async findMany<TOptions extends FindManyOptions<TModelName>>(\n filters?: FindManyFilters<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>[]> {\n return this.executeOperation({\n operationType: \"findMany\",\n prismaMethod: \"findMany\",\n returnsFallback: [],\n })(filters, queryOptions, context);\n }\n\n /**\n * Finds a single record by its ID.\n *\n * @param id - The unique identifier of the record\n * @param queryOptions - Optional Prisma query options (select, include, etc.)\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const user = await userService.findById(\"user-123\");\n * ```\n */\n async findById<TOptions extends FindOneOptions<TModelName>>(\n id: string | number,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions> | null> {\n return this.executeOperation({\n operationType: \"findById\",\n prismaMethod: \"findUnique\",\n returnsFallback: undefined,\n })(id, queryOptions, context);\n }\n\n /**\n * Finds the first record matching the specified filters.\n *\n * @param filters - Where conditions to filter records\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const user = await userService.findOne({ email: \"john@example.com\" });\n * ```\n */\n async findOne<TOptions extends FindOneOptions<TModelName>>(\n filters: FindOneFilters<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions> | null> {\n return this.executeOperation({\n operationType: \"findOne\",\n prismaMethod: \"findFirst\",\n returnsFallback: undefined,\n customPrismaLogic: async (args, prisma, _, serviceContext) => {\n const filters = args[0];\n const queryOptions = args[1];\n\n if (\n Object.keys(filters as Record<string, any>).length === 1 &&\n \"id\" in (filters as Record<string, any>) &&\n (filters as any).id !== \"me\"\n ) {\n return await (prisma as any)[serviceContext.modelName].findUnique(\n deepmerge({ where: filters }, queryOptions || {})\n );\n } else {\n return await (prisma as any)[serviceContext.modelName].findFirst(\n deepmerge({ where: filters }, queryOptions || {})\n );\n }\n },\n })(filters, queryOptions, context);\n }\n\n /**\n * Updates a single record matching the specified filters.\n *\n * @param filters - Where conditions to identify the record\n * @param data - The data to update\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const updated = await userService.updateOne(\n * { id: \"user-123\" },\n * { name: \"John Updated\" }\n * );\n * ```\n */\n async updateOne<TOptions extends UpdateOneOptions<TModelName>>(\n filters: UpdateOneFilters<TModelName>,\n data: UpdateOneData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>> {\n return this.executeOperation({\n operationType: \"updateOne\",\n prismaMethod: \"update\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })(filters, data, queryOptions, context);\n }\n\n /**\n * Updates a single record matching the specified id.\n *\n * @param id - The unique identifier of the record\n * @param data - The data to update\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const updated = await userService.updateById(\"user-123\", { name: \"John Updated\" });\n * ```\n */\n async updateById<TOptions extends UpdateOneOptions<TModelName>>(\n id: string | number,\n data: UpdateOneData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>> {\n return this.executeOperation({\n operationType: \"updateOne\",\n prismaMethod: \"update\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })({ id }, data, queryOptions, context);\n }\n\n /**\n * Updates multiple records matching the specified filters.\n *\n * @param filters - Where conditions to identify records\n * @param data - The data to update\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const result = await userService.updateMany(\n * { status: \"pending\" },\n * { status: \"active\" }\n * );\n * ```\n */\n async updateMany<TOptions extends UpdateManyOptions<TModelName>>(\n filters: UpdateManyFilters<TModelName>,\n data: UpdateManyData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<{ count: number }> {\n return this.executeOperation({\n operationType: \"updateMany\",\n prismaMethod: \"updateMany\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })(filters, data, queryOptions, context);\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param id - The unique identifier of the record\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const deleted = await userService.deleteById(\"user-123\");\n * ```\n */\n async deleteById(\n id: string | number,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, any>> {\n return this.executeOperation({\n operationType: \"deleteOne\",\n prismaMethod: \"delete\",\n returnsFallback: undefined,\n })({ id }, context);\n }\n\n /**\n * Deletes a single record matching the specified filters.\n *\n * @param filters - Where conditions to identify the record\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const deleted = await userService.deleteOne({ id: \"user-123\" });\n * ```\n */\n async deleteOne(\n filters: DeleteOneFilters<TModelName>,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, any>> {\n return this.executeOperation({\n operationType: \"deleteOne\",\n prismaMethod: \"delete\",\n returnsFallback: undefined,\n })(filters, context);\n }\n\n /**\n * Deletes multiple records matching the specified filters.\n *\n * @param filters - Where conditions to identify records\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const result = await userService.deleteMany({ status: \"inactive\" });\n * ```\n */\n async deleteMany(\n filters: DeleteManyFilters<TModelName>,\n context?: ServiceBaseContext\n ): Promise<{ count: number }> {\n return this.executeOperation({\n operationType: \"deleteMany\",\n prismaMethod: \"deleteMany\",\n returnsFallback: undefined,\n })(filters, context);\n }\n\n /**\n * Performs multiple update operations in a single transaction.\n *\n * @param dataArray - Array of update objects each containing filter criteria and data\n * @param queryOptions - Optional Prisma query options applied to all updates\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const results = await userService.batchUpdate([\n * { id: \"user-1\", status: \"active\" },\n * { id: \"user-2\", status: \"inactive\" }\n * ]);\n * ```\n */\n async batchUpdate<TOptions extends UpdateOneOptions<TModelName>>(\n dataArray: UpdateOneData<TModelName>[],\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>[]> {\n return this.executeTransactionOperation({\n operationType: \"batchUpdate\",\n prismaMethod: \"update\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })(dataArray, queryOptions, context);\n }\n\n /**\n * Performs multiple delete operations in a single transaction.\n *\n * @param batchFilters - Array of where conditions each identifying a record to delete\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const deleted = await userService.batchDelete([\n * { id: \"user-1\" },\n * { id: \"user-2\" }\n * ]);\n * ```\n */\n async batchDelete(\n batchFilters: Array<DeleteOneFilters<TModelName>>,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, any>[]> {\n return this.executeTransactionOperation({\n operationType: \"batchDelete\",\n prismaMethod: \"delete\",\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })(batchFilters, context);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":";;;;;;AAAA,iFAIiD;AACjD,+DAAiE;AACjE,4FAA6D;AAC7D,+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CAAC,SAAS,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IACvC,CAAC;IAgBD,KAAK,CAAC,WAAW,CACf,YAAiD,EACjD,OAA4B;QAE5B,OAAO,IAAI,CAAC,2BAA2B,CAAC;YACtC,aAAa,EAAE,aAAa;YAC5B,YAAY,EAAE,QAAQ;YACtB,sBAAsB,EAAE,EAAE;YAC1B,eAAe,EAAE,SAAS;SAC3B,CAAC,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IAC5B,CAAC;CACF;AA/zBD,kCA+zBC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport {\n handleRelationFieldsInBody,\n ModelGroupRelationFields,\n} from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\nimport {\n PrismaModels,\n PrismaClient,\n ExtractPrismaFilters,\n ExtractPrismaData,\n ExtractPrismaQueryOptions,\n} from \"../../generated\";\nimport { ServiceBaseContext } from \"./types/base.service.types\";\nimport serviceHooksManager from \"./utils/service-hooks-manager\";\nimport prismaSchemaParser from \"../../utils/prisma/prisma-schema-parser\";\n\ntype Models = PrismaModels<any>;\n\ntype Delegate<TModelName extends keyof Models> = Models[TModelName][\"Delegate\"];\n\ntype CreateData<TModelName extends keyof Models> = ExtractPrismaData<\n Models[TModelName][\"CreateArgs\"]\n>;\ntype CreateManyData<TModelName extends keyof Models> = ExtractPrismaData<\n Models[TModelName][\"CreateManyArgs\"]\n>;\ntype CreateOptions<TModelName extends keyof Models> = ExtractPrismaQueryOptions<\n Models[TModelName][\"CreateArgs\"],\n \"data\"\n>;\ntype CreateManyOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<Models[TModelName][\"CreateManyArgs\"], \"data\">;\n\ntype CountFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"CountArgs\"]\n>;\n\ntype FindManyFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"FindManyArgs\"]\n>;\ntype FindManyOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<Models[TModelName][\"FindManyArgs\"], \"where\">;\n\ntype FindOneFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"FindFirstArgs\"]\n>;\ntype FindOneOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<Models[TModelName][\"FindFirstArgs\"], \"where\">;\n\ntype UpdateOneFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"UpdateArgs\"]\n>;\ntype UpdateOneData<TModelName extends keyof Models> = ExtractPrismaData<\n Models[TModelName][\"UpdateArgs\"]\n>;\ntype UpdateOneOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<Models[TModelName][\"UpdateArgs\"], \"where\" | \"data\">;\n\ntype UpdateManyFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"UpdateManyArgs\"]\n>;\ntype UpdateManyData<TModelName extends keyof Models> = ExtractPrismaData<\n Models[TModelName][\"UpdateManyArgs\"]\n>;\ntype UpdateManyOptions<TModelName extends keyof Models> =\n ExtractPrismaQueryOptions<\n Models[TModelName][\"UpdateManyArgs\"],\n \"where\" | \"data\"\n >;\n\ntype DeleteOneFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"DeleteArgs\"]\n>;\ntype DeleteManyFilters<TModelName extends keyof Models> = ExtractPrismaFilters<\n Models[TModelName][\"DeleteManyArgs\"]\n>;\n\ntype GetPayload<\n TModelName extends keyof Models,\n TOptions extends Record<string, any>,\n> = PrismaModels<TOptions>[TModelName][\"GetPayload\"];\n\nexport interface ServiceOperationHooks {\n beforeOperation?: (params: any) => void | Promise<void>;\n afterOperation?: (result: any, params: any) => void | Promise<void>;\n beforePrisma?: (prismaArgs: any, params: any) => any | Promise<any>;\n afterPrisma?: (result: any, params: any) => any | Promise<any>;\n}\n\ninterface ServiceOperationConfig {\n operationType: string;\n prismaMethod: string;\n requiresPasswordHashing?: boolean;\n relationFieldsHandling?: string[];\n returnsFallback?: any;\n customPrismaLogic?: (\n args: any[],\n prisma: PrismaClient,\n config: ServiceOperationConfig,\n context: BaseService<any>\n ) => Promise<any>;\n hooks?: ServiceOperationHooks;\n}\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n * by model-specific service classes.\n *\n * @class BaseService\n *\n * @example\n * ```ts\n * import { BaseService } from \"arkos/services\";\n *\n * export class UserService extends BaseService<\"user\"> {}\n *\n * const userService = new UserService(\"user\");\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-service-class}\n * @see {@link https://www.arkosjs.com/docs/guide/accessing-request-context-in-services}\n */\nexport class BaseService<TModelName extends keyof Models = keyof Models> {\n modelName: TModelName;\n relationFields: ModelGroupRelationFields;\n private prismaInstace?: PrismaClient;\n\n constructor(modelName: TModelName) {\n this.modelName = camelCase(modelName as string) as TModelName;\n const modelFields = prismaSchemaParser.getModelRelations(\n modelName as string\n );\n\n this.relationFields = {\n singular:\n modelFields?.filter((field) => field.isRelation && !field.isArray) ||\n [],\n list:\n modelFields?.filter((field) => field.isRelation && field.isArray) || [],\n };\n }\n\n get prisma() {\n if (!this.prismaInstace) this.prismaInstace = getPrismaInstance();\n return this.prismaInstace!;\n }\n\n private executeOperation = (config: ServiceOperationConfig) => {\n return async (...args: any[]): Promise<any> => {\n const context = args[args.length - 1] as ServiceBaseContext;\n\n try {\n let argsWithRelationFieldsHandled =\n await this.processRelationFieldsInBody(args, config);\n let prismaFinalArgs = await this.handlePasswordHashing(\n argsWithRelationFieldsHandled,\n config\n );\n\n await this.executeHooks(\n \"before\",\n config.operationType,\n this.buildHookParams(argsWithRelationFieldsHandled, config),\n context\n );\n\n if (config.hooks?.beforeOperation)\n await config.hooks.beforeOperation(\n this.buildHookParams(argsWithRelationFieldsHandled, config)\n );\n\n if (config.hooks?.beforePrisma) {\n argsWithRelationFieldsHandled = await config.hooks.beforePrisma(\n argsWithRelationFieldsHandled,\n this.buildHookParams(argsWithRelationFieldsHandled, config)\n );\n }\n\n const prisma = getPrismaInstance();\n let result: any;\n\n if (config.customPrismaLogic) {\n result = await config.customPrismaLogic(\n argsWithRelationFieldsHandled,\n prisma,\n config,\n this\n );\n } else {\n const prismaArgs = this.buildPrismaArgs(prismaFinalArgs, config);\n result = await (\n prisma[this.modelName as string] as Delegate<TModelName>\n )[config.prismaMethod](prismaArgs);\n }\n\n if (config.hooks?.afterPrisma) {\n result = await config.hooks.afterPrisma(\n result,\n this.buildHookParams(argsWithRelationFieldsHandled, config)\n );\n }\n\n await this.executeHooks(\n \"after\",\n config.operationType,\n {\n ...this.buildHookParams(argsWithRelationFieldsHandled, config),\n result,\n },\n context\n );\n\n if (config.hooks?.afterOperation) {\n await config.hooks.afterOperation(\n result,\n this.buildHookParams(argsWithRelationFieldsHandled, config)\n );\n }\n\n return result;\n } catch (err: any) {\n await this.executeHooks(\n \"error\",\n config.operationType,\n { ...this.buildHookParams(args, config), error: err },\n context\n );\n if (context?.throwOnError !== false) throw err;\n return config.returnsFallback;\n }\n };\n };\n\n private executeTransactionOperation = (config: ServiceOperationConfig) => {\n return async (...args: any[]): Promise<any> => {\n const context = args[args.length - 1] as ServiceBaseContext;\n\n try {\n let argsWithRelationFieldsHandled =\n await this.processRelationFieldsInBody(args, config);\n let prismaFinalArgs = await this.handlePasswordHashing(\n argsWithRelationFieldsHandled,\n config\n );\n\n await this.executeHooks(\n \"before\",\n config.operationType,\n this.buildTransactionHookParams(\n argsWithRelationFieldsHandled,\n config\n ),\n context\n );\n\n const prisma = getPrismaInstance();\n const results = await this.executeTransactionLogic(\n prismaFinalArgs,\n config,\n prisma\n );\n\n await this.executeHooks(\n \"after\",\n config.operationType,\n {\n ...this.buildTransactionHookParams(\n argsWithRelationFieldsHandled,\n config\n ),\n results,\n },\n context\n );\n return results;\n } catch (err: any) {\n await this.executeHooks(\n \"error\",\n config.operationType,\n { ...this.buildTransactionHookParams(args, config), error: err },\n context\n );\n if (context?.throwOnError !== false) throw err;\n return config.returnsFallback;\n }\n };\n };\n\n private async executeHooks(\n hookType: \"before\" | \"after\" | \"error\",\n operationType: string,\n params: any,\n context?: ServiceBaseContext\n ): Promise<void> {\n const serviceHooks = getModuleComponents(this.modelName as string)?.hooks;\n if (!serviceHooks) return;\n\n const skipCondition =\n context?.skip === hookType ||\n context?.skip === \"all\" ||\n (Array.isArray(context?.skip) && context.skip.includes(hookType));\n\n if (skipCondition) return;\n\n const hookName = `${hookType === \"error\" ? \"on\" : hookType}${operationType.charAt(0).toUpperCase()}${operationType.slice(1)}${hookType === \"error\" ? \"Error\" : \"\"}`;\n const hook = serviceHooks[hookName as keyof typeof serviceHooks];\n\n if (hook) await serviceHooksManager.handleHook(hook, params);\n }\n\n private buildHookParams(args: any[], config: ServiceOperationConfig): any {\n const context = args[args.length - 1];\n\n switch (config.operationType) {\n case \"createOne\":\n case \"createMany\":\n return { data: args[0], queryOptions: args[1], context };\n case \"findMany\":\n return { filters: args[0], queryOptions: args[1], context };\n case \"findById\":\n return { id: args[0], queryOptions: args[1], context };\n case \"findOne\":\n return { filters: args[0], queryOptions: args[1], context };\n case \"updateOne\":\n return {\n filters: args[0],\n data: args[1],\n queryOptions: args[2],\n context,\n };\n case \"updateMany\":\n return {\n filters: args[0],\n data: args[1],\n queryOptions: args[2],\n context,\n };\n case \"deleteOne\":\n return { filters: args[0], context };\n case \"deleteMany\":\n return { filters: args[0], context };\n case \"count\":\n return { filters: args[0], context };\n default:\n return { context };\n }\n }\n\n private buildTransactionHookParams(\n args: any[],\n config: ServiceOperationConfig\n ): any {\n const context = args[args.length - 1];\n\n switch (config.operationType) {\n case \"batchUpdate\":\n return { data: args[0], queryOptions: args[1], context };\n case \"batchDelete\":\n return { batchFilters: args[0], context };\n default:\n return { context };\n }\n }\n\n private async handlePasswordHashing(\n args: any[],\n config: ServiceOperationConfig\n ): Promise<any[]> {\n let processedArgs = [...args];\n\n if (config.requiresPasswordHashing) {\n const dataIndex = config.operationType.includes(\"update\") ? 1 : 0;\n const data = processedArgs[dataIndex];\n\n if (Array.isArray(data)) {\n for (const i in data) {\n if (this.shouldHashPassword(data[i]))\n processedArgs[dataIndex][i] = await this.processPasswordHashing(\n data[i]\n );\n }\n } else if (this.shouldHashPassword(data)) {\n processedArgs[dataIndex] = await this.processPasswordHashing(data);\n }\n }\n\n return processedArgs;\n }\n\n private async processRelationFieldsInBody(\n args: any[],\n config: ServiceOperationConfig\n ): Promise<any[]> {\n let processedArgs = [...args];\n\n if (config.relationFieldsHandling) {\n const dataIndex = config.operationType.includes(\"update\") ? 1 : 0;\n\n if (config.operationType === \"batchUpdate\") {\n const dataArray = processedArgs[0];\n if (Array.isArray(dataArray)) {\n processedArgs[0] = dataArray.map((data) =>\n handleRelationFieldsInBody(\n data as Record<string, any>,\n this.relationFields,\n config.relationFieldsHandling\n )\n );\n }\n } else if (config.operationType === \"batchDelete\") {\n const batchFilters = processedArgs[0];\n if (Array.isArray(batchFilters)) {\n processedArgs[0] = batchFilters.map((filters) =>\n handleRelationFieldsInBody(\n filters as Record<string, any>,\n this.relationFields\n )\n );\n }\n } else if (config.operationType === \"createMany\") {\n const data = processedArgs[dataIndex];\n if (Array.isArray(data)) {\n processedArgs[dataIndex] = data.map((item) =>\n handleRelationFieldsInBody(\n item as Record<string, any>,\n this.relationFields,\n config.relationFieldsHandling\n )\n );\n }\n } else {\n const data = processedArgs[dataIndex];\n if (data) {\n processedArgs[dataIndex] = handleRelationFieldsInBody(\n data as Record<string, any>,\n this.relationFields,\n config.relationFieldsHandling\n );\n }\n }\n }\n\n return processedArgs;\n }\n\n private buildPrismaArgs(args: any[], config: ServiceOperationConfig): any {\n switch (config.operationType) {\n case \"createOne\":\n case \"createMany\":\n return deepmerge({ data: args[0] }, args[1] || {});\n case \"findMany\":\n return deepmerge({ where: args[0] }, args[1] || {});\n case \"findById\":\n return deepmerge({ where: { id: args[0] } }, args[1] || {});\n case \"findOne\":\n return deepmerge({ where: args[0] }, args[1] || {});\n case \"updateOne\":\n return deepmerge({ where: args[0], data: args[1] }, args[2] || {});\n case \"updateMany\":\n const firstMerge = deepmerge({ data: args[1] }, args[2] || {});\n return deepmerge({ where: args[0] }, firstMerge);\n case \"deleteOne\":\n case \"deleteMany\":\n return { where: args[0] };\n case \"count\":\n return { where: args[0] };\n default:\n return {};\n }\n }\n\n private async executeTransactionLogic(\n args: any[],\n config: ServiceOperationConfig,\n prisma: PrismaClient\n ): Promise<any> {\n if (config.operationType === \"batchUpdate\") {\n const dataArray = args[0];\n const queryOptions = args[1];\n\n return await (prisma as any).$transaction(async (tx: any) => {\n const updatePromises = dataArray.map(async (data: any) => {\n let processedData = data;\n if (this.shouldHashPassword(data)) {\n processedData = await this.processPasswordHashing(data);\n }\n\n const finalPrismaQueryParams = handleRelationFieldsInBody(\n {\n batchedData: {\n ...processedData,\n apiAction: \"update\",\n },\n } as Record<string, any>,\n {\n singular: [\n {\n ...prismaSchemaParser.getField({\n type: pascalCase(this.modelName as string),\n })!,\n name: \"batchedData\",\n },\n ],\n list: [],\n }\n );\n\n return await tx[this.modelName as string].update(\n deepmerge(\n finalPrismaQueryParams.batchedData?.update,\n queryOptions || {}\n ) as { where: any; data: any }\n );\n });\n\n return await Promise.all(updatePromises);\n });\n }\n\n if (config.operationType === \"batchDelete\") {\n const batchFilters = args[0];\n\n return await (prisma as any).$transaction(async (tx: any) => {\n const deletePromises = batchFilters.map(async (filters: any) => {\n return await tx[this.modelName as string].delete({ where: filters });\n });\n\n return await Promise.all(deletePromises);\n });\n }\n\n throw new Error(`Unknown transaction operation: ${config.operationType}`);\n }\n\n private shouldHashPassword(data: any): boolean {\n return kebabCase(this.modelName as string) === \"user\" && data?.password;\n }\n\n private async processPasswordHashing(data: any): Promise<any> {\n if (Array.isArray(data)) {\n const processedArray: any[] = [];\n for (let i = 0; i < data.length; i++) {\n const curr = data[i];\n if (\n \"password\" in curr &&\n !authService.isPasswordHashed(curr.password!)\n ) {\n processedArray[i] = {\n ...curr,\n password: await authService.hashPassword(curr.password!),\n };\n } else {\n processedArray[i] = curr;\n }\n }\n return processedArray;\n } else {\n if (data.password && !authService.isPasswordHashed(data.password)) {\n return {\n ...data,\n password: await authService.hashPassword(data.password),\n };\n }\n }\n return data;\n }\n\n // ─── Public API ─────────────────────────────────────────────────────────────\n\n /**\n * Creates a single record in the database.\n *\n * @param data - The data for creating the record\n * @param queryOptions - Optional Prisma query options (select, include, etc.)\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const user = await userService.createOne({\n * name: \"John Doe\",\n * email: \"john@example.com\"\n * });\n * ```\n */\n async createOne<TOptions extends CreateOptions<TModelName>>(\n data: CreateData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>> {\n return this.executeOperation({\n operationType: \"createOne\",\n prismaMethod: \"create\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [\"delete\", \"disconnect\", \"update\"],\n returnsFallback: undefined,\n })(data, queryOptions, context);\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param data - Array of data objects or object with data array\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const result = await userService.createMany([\n * { name: \"John Doe\", email: \"john@example.com\" },\n * { name: \"Jane Smith\", email: \"jane@example.com\" }\n * ]);\n * ```\n */\n async createMany<TOptions extends CreateManyOptions<TModelName>>(\n data: CreateManyData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>[]> {\n return this.executeOperation({\n operationType: \"createMany\",\n prismaMethod: \"createMany\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [\"delete\", \"disconnect\", \"update\"],\n returnsFallback: undefined,\n })(data, queryOptions, context);\n }\n\n /**\n * Counts records matching the specified filters.\n *\n * @param filters - Optional where conditions\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const total = await userService.count({ status: \"active\" });\n * ```\n */\n async count(\n filters?: CountFilters<TModelName>,\n context?: ServiceBaseContext\n ): Promise<number> {\n return this.executeOperation({\n operationType: \"count\",\n prismaMethod: \"count\",\n returnsFallback: 0,\n })(filters, context);\n }\n\n /**\n * Finds multiple records matching the specified filters.\n *\n * @param filters - Optional where conditions\n * @param queryOptions - Optional Prisma query options (select, include, orderBy, skip, take, etc.)\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const users = await userService.findMany(\n * { status: \"active\" },\n * { orderBy: { createdAt: \"desc\" }, take: 10 }\n * );\n * ```\n */\n async findMany<TOptions extends FindManyOptions<TModelName>>(\n filters?: FindManyFilters<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>[]> {\n return this.executeOperation({\n operationType: \"findMany\",\n prismaMethod: \"findMany\",\n returnsFallback: [],\n })(filters, queryOptions, context);\n }\n\n /**\n * Finds a single record by its ID.\n *\n * @param id - The unique identifier of the record\n * @param queryOptions - Optional Prisma query options (select, include, etc.)\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const user = await userService.findById(\"user-123\");\n * ```\n */\n async findById<TOptions extends FindOneOptions<TModelName>>(\n id: string | number,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions> | null> {\n return this.executeOperation({\n operationType: \"findById\",\n prismaMethod: \"findUnique\",\n returnsFallback: undefined,\n })(id, queryOptions, context);\n }\n\n /**\n * Finds the first record matching the specified filters.\n *\n * @param filters - Where conditions to filter records\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const user = await userService.findOne({ email: \"john@example.com\" });\n * ```\n */\n async findOne<TOptions extends FindOneOptions<TModelName>>(\n filters: FindOneFilters<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions> | null> {\n return this.executeOperation({\n operationType: \"findOne\",\n prismaMethod: \"findFirst\",\n returnsFallback: undefined,\n customPrismaLogic: async (args, prisma, _, serviceContext) => {\n const filters = args[0];\n const queryOptions = args[1];\n\n if (\n Object.keys(filters as Record<string, any>).length === 1 &&\n \"id\" in (filters as Record<string, any>) &&\n (filters as any).id !== \"me\"\n ) {\n return await (prisma as any)[serviceContext.modelName].findUnique(\n deepmerge({ where: filters }, queryOptions || {})\n );\n } else {\n return await (prisma as any)[serviceContext.modelName].findFirst(\n deepmerge({ where: filters }, queryOptions || {})\n );\n }\n },\n })(filters, queryOptions, context);\n }\n\n /**\n * Updates a single record matching the specified filters.\n *\n * @param filters - Where conditions to identify the record\n * @param data - The data to update\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const updated = await userService.updateOne(\n * { id: \"user-123\" },\n * { name: \"John Updated\" }\n * );\n * ```\n */\n async updateOne<TOptions extends UpdateOneOptions<TModelName>>(\n filters: UpdateOneFilters<TModelName>,\n data: UpdateOneData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>> {\n return this.executeOperation({\n operationType: \"updateOne\",\n prismaMethod: \"update\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })(filters, data, queryOptions, context);\n }\n\n /**\n * Updates a single record matching the specified id.\n *\n * @param id - The unique identifier of the record\n * @param data - The data to update\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const updated = await userService.updateById(\"user-123\", { name: \"John Updated\" });\n * ```\n */\n async updateById<TOptions extends UpdateOneOptions<TModelName>>(\n id: string | number,\n data: UpdateOneData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>> {\n return this.executeOperation({\n operationType: \"updateOne\",\n prismaMethod: \"update\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })({ id }, data, queryOptions, context);\n }\n\n /**\n * Updates multiple records matching the specified filters.\n *\n * @param filters - Where conditions to identify records\n * @param data - The data to update\n * @param queryOptions - Optional Prisma query options\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const result = await userService.updateMany(\n * { status: \"pending\" },\n * { status: \"active\" }\n * );\n * ```\n */\n async updateMany<TOptions extends UpdateManyOptions<TModelName>>(\n filters: UpdateManyFilters<TModelName>,\n data: UpdateManyData<TModelName>,\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<{ count: number }> {\n return this.executeOperation({\n operationType: \"updateMany\",\n prismaMethod: \"updateMany\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })(filters, data, queryOptions, context);\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param id - The unique identifier of the record\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const deleted = await userService.deleteById(\"user-123\");\n * ```\n */\n async deleteById(\n id: string | number,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, any>> {\n return this.executeOperation({\n operationType: \"deleteOne\",\n prismaMethod: \"delete\",\n returnsFallback: undefined,\n })({ id }, context);\n }\n\n /**\n * Deletes a single record matching the specified filters.\n *\n * @param filters - Where conditions to identify the record\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const deleted = await userService.deleteOne({ id: \"user-123\" });\n * ```\n */\n async deleteOne(\n filters: DeleteOneFilters<TModelName>,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, any>> {\n return this.executeOperation({\n operationType: \"deleteOne\",\n prismaMethod: \"delete\",\n returnsFallback: undefined,\n })(filters, context);\n }\n\n /**\n * Deletes multiple records matching the specified filters.\n *\n * @param filters - Where conditions to identify records\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const result = await userService.deleteMany({ status: \"inactive\" });\n * ```\n */\n async deleteMany(\n filters: DeleteManyFilters<TModelName>,\n context?: ServiceBaseContext\n ): Promise<{ count: number }> {\n return this.executeOperation({\n operationType: \"deleteMany\",\n prismaMethod: \"deleteMany\",\n returnsFallback: undefined,\n })(filters, context);\n }\n\n /**\n * Performs multiple update operations in a single transaction.\n *\n * @param dataArray - Array of update objects each containing filter criteria and data\n * @param queryOptions - Optional Prisma query options applied to all updates\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const results = await userService.batchUpdate([\n * { id: \"user-1\", status: \"active\" },\n * { id: \"user-2\", status: \"inactive\" }\n * ]);\n * ```\n */\n async batchUpdate<TOptions extends UpdateOneOptions<TModelName>>(\n dataArray: UpdateOneData<TModelName>[],\n queryOptions?: TOptions,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, TOptions>[]> {\n return this.executeTransactionOperation({\n operationType: \"batchUpdate\",\n prismaMethod: \"update\",\n requiresPasswordHashing: true,\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })(dataArray, queryOptions, context);\n }\n\n /**\n * Performs multiple delete operations in a single transaction.\n *\n * @param batchFilters - Array of where conditions each identifying a record to delete\n * @param context - Optional service execution context\n *\n * @example\n * ```ts\n * const deleted = await userService.batchDelete([\n * { id: \"user-1\" },\n * { id: \"user-2\" }\n * ]);\n * ```\n */\n async batchDelete(\n batchFilters: Array<DeleteOneFilters<TModelName>>,\n context?: ServiceBaseContext\n ): Promise<GetPayload<TModelName, any>[]> {\n return this.executeTransactionOperation({\n operationType: \"batchDelete\",\n prismaMethod: \"delete\",\n relationFieldsHandling: [],\n returnsFallback: undefined,\n })(batchFilters, context);\n }\n}\n"]}
|
|
@@ -21,6 +21,8 @@ const file_upload_json_schema_generator_1 = __importDefault(require("./utils/fil
|
|
|
21
21
|
function getFileUploadRouter(arkosConfig) {
|
|
22
22
|
const router = (0, arkos_router_1.default)();
|
|
23
23
|
const { fileUpload } = arkosConfig;
|
|
24
|
+
if (!fileUpload?.enabled === false)
|
|
25
|
+
return router;
|
|
24
26
|
const moduleComponents = (0, dynamic_loader_1.getModuleComponents)("file-upload");
|
|
25
27
|
let { interceptors = {}, authConfigs = {}, router: customRouterModule, } = {};
|
|
26
28
|
if (moduleComponents)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AAsBA,
|
|
1
|
+
{"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AAsBA,kDAgKC;AArLD,+DAAiE;AACjE,sFAA4D;AAC5D,sDAA8B;AAC9B,4FAA6D;AAE7D,+DAAwD;AACxD,yEAG6C;AAC7C,6EAAuE;AACvE,mFAA+E;AAC/E,oFAA2D;AAC3D,sFAA6D;AAC7D,+DAAsE;AAEtE,gDAAwB;AACxB,4EAAmD;AAEnD,kHAAsF;AAEtF,SAAgB,mBAAmB,CAAC,WAAwB;IAC1D,MAAM,MAAM,GAAG,IAAA,sBAAW,GAAE,CAAC;IAC7B,MAAM,EAAE,UAAU,EAAE,GAAG,WAAW,CAAC;IAEnC,IAAI,CAAC,UAAU,EAAE,OAAO,KAAK,KAAK;QAAE,OAAO,MAAM,CAAC;IAElD,MAAM,gBAAgB,GAAG,IAAA,oCAAmB,EAAC,aAAa,CAAC,CAAC;IAC5D,IAAI,EACF,YAAY,GAAG,EAAS,EACxB,WAAW,GAAG,EAAiB,EAC/B,MAAM,EAAE,kBAAkB,GAC3B,GAAQ,EAAE,CAAC;IAEZ,IAAI,gBAAgB;QAClB,CAAC;YACC,YAAY,GAAG,EAAE;YACjB,WAAW,GAAG,EAAE;YAChB,MAAM,EAAE,kBAAkB;SAC3B,GAAG,gBAAgB,CAAC,CAAC;IAExB,MAAM,YAAY,GAAG,kBAAkB,EAAE,MAAM,IAAI,EAAE,CAAC;IACtD,IAAI,YAAY,EAAE,OAAO,K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E,CAAC,CACzE,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,IAAA,wCAAkB,EAAC,YAAY,EAAE,YAAY,CAAC,EAAE,CAAC;QACpD,MAAM,CAAC,KAAK,CACV,IAAA,mCAAiB,EACf,WAAW,EACX,YAAY,EACZ,eAAe,EACf,qBAAqB,EACrB,YAAY,EACZ,aAAa,EACb,WAAW,CACZ,EACD,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,gBAAgB,CAAC,EACpD,gCAAoB,CAAC,UAAU,EAC/B,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,eAAe,CAAC,EACnD,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,iBAAiB,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACzE,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,IAAA,wCAAkB,EAAC,YAAY,EAAE,YAAY,CAAC,EAAE,CAAC;QACpD,MAAM,CAAC,MAAM,CACX,IAAA,mCAAiB,EACf,WAAW,EACX,YAAY,EACZ,eAAe,EACf,qBAAqB,EACrB,YAAY,EACZ,aAAa,EACb,WAAW,CACZ,EACD,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,gBAAgB,CAAC,EACpD,gCAAoB,CAAC,UAAU,EAC/B,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,eAAe,CAAC,EACnD,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,iBAAiB,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACzE,CAAC;IACJ,CAAC;IAED,0BAAe,CAAC,oBAAoB,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport fileUploadController from \"./file-upload.controller\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { sendResponse } from \"../base/base.middlewares\";\nimport {\n createRouteConfig,\n processMiddleware,\n} from \"../../utils/helpers/routers.helpers\";\nimport { adjustRequestUrl } from \"./utils/helpers/file-upload.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\nimport routerValidator from \"../base/utils/router-validator\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\nimport { ArkosConfig } from \"../../exports\";\nimport path from \"path\";\nimport ArkosRouter from \"../../utils/arkos-router\";\nimport { FileUploadRouterEndpoint } from \"../../types/router-config\";\nimport fileUploadJsonSchemaGenerator from \"./utils/file-upload-json-schema-generator\";\n\nexport function getFileUploadRouter(arkosConfig: ArkosConfig) {\n const router = ArkosRouter();\n const { fileUpload } = arkosConfig;\n\n if (!fileUpload?.enabled === false) return router;\n\n const moduleComponents = getModuleComponents(\"file-upload\");\n let {\n interceptors = {} as any,\n authConfigs = {} as AuthConfigs,\n router: customRouterModule,\n }: any = {};\n\n if (moduleComponents)\n ({\n interceptors = {},\n authConfigs = {},\n router: customRouterModule,\n } = moduleComponents);\n\n const routerConfig = customRouterModule?.config || {};\n if (routerConfig?.disable === true) return router;\n\n const customRouter = customRouterModule?.default as Router;\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n // Strip leading slash so createRouteConfig can prepend its own \"/\"\n // e.g. \"/api/uploads/\" → \"api/uploads/\" → createRouteConfig builds \"/api/uploads/*\"\n const baseRoutePrefix = basePathname.slice(1);\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(basePathname, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from file-upload.router.${getUserFileExtension()} is not a valid express or arkos Router.`\n );\n }\n\n const endpoints: FileUploadRouterEndpoint[] = [\n \"findFile\",\n \"uploadFile\",\n \"updateFile\",\n \"deleteFile\",\n ];\n\n for (const endpoint of endpoints) {\n const endpointConfig = routerConfig[endpoint];\n if (endpointConfig?.experimental?.openapi === false) continue;\n routerConfig[endpoint] = {\n ...(endpointConfig || {}),\n experimental: {\n ...(endpointConfig?.experimental || {}),\n openapi: fileUploadJsonSchemaGenerator.getOpenApiConfig(\n endpointConfig,\n endpoint\n ),\n },\n };\n }\n\n if (!isEndpointDisabled(routerConfig, \"findFile\")) {\n const baseUploadDirFullPath = path.resolve(\n path\n .join(process.cwd(), fileUpload?.baseUploadDir || \"uploads\")\n .replaceAll(\"//\", \"/\")\n );\n router.get(\n createRouteConfig(\n arkosConfig,\n \"findFile\",\n baseRoutePrefix,\n `*`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeFindFile),\n adjustRequestUrl,\n express.static(\n baseUploadDirFullPath,\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStatic || {}\n )\n ),\n ...processMiddleware(interceptors?.onFindFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"uploadFile\")) {\n router.post(\n createRouteConfig(\n arkosConfig,\n \"uploadFile\",\n baseRoutePrefix,\n `:fileType`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeUploadFile),\n fileUploadController.uploadFile,\n ...processMiddleware(interceptors?.afterUploadFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUploadFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updateFile\")) {\n router.patch(\n createRouteConfig(\n arkosConfig,\n \"updateFile\",\n baseRoutePrefix,\n `:fileType/:fileName`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeUpdateFile),\n fileUploadController.updateFile,\n ...processMiddleware(interceptors?.afterUpdateFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"deleteFile\")) {\n router.delete(\n createRouteConfig(\n arkosConfig,\n \"deleteFile\",\n baseRoutePrefix,\n `:fileType/:fileName`,\n routerConfig,\n \"file-upload\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeDeleteFile),\n fileUploadController.deleteFile,\n ...processMiddleware(interceptors?.afterDeleteFile),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteFileError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(\"file-upload\", router);\n return router;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\n enabled?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: Partial<RateLimitOptions>;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n *@see Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?: {\n /**\n * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n */\n strict?: boolean;\n } & (\n | {\n resolver: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * forbidNonWhitelisted: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver: \"zod\";\n validationOptions?: {\n /**\n * Throws an error for know whitelisted fields\n *\n * @default true\n */\n forbidNonWhitelisted?: boolean;\n };\n }\n );\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStatic?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Defines express middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compression?: false | compression.CompressionOptions | ArkosRequestHandler;\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customHandler] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customHandler` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?:\n | false\n | {\n /**\n * Defines allowed origins to acess the API.\n */\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n }\n | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParser?:\n | false\n | Parameters<typeof cookieParser>\n | ArkosRequestHandler;\n /**\n * Options to define how query must be parsed.\n *\n * #### for 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 parseNumber: true,\n }\n * \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?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeRoute?: false | ArkosRequestHandler;\n };\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/core-concepts/open-api-documentation}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"PrismaFinalQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n /**\n * Allows to suppress specific warnings emitted by Arkos at startup or runtime.\n */\n warnings?: {\n /**\n * Suppresses specific warning messages.\n */\n suppress?: {\n /**\n * Suppresses Prisma-related warnings.\n */\n prisma?: {\n /**\n * Suppresses the warning emitted when no Prisma instance is found.\n */\n noInstanceFound?: boolean;\n /**\n * Suppresses the warning emitted when no Prisma schema is found.\n */\n noSchemaFound?: boolean;\n };\n };\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express, { CookieOptions } from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\n enabled?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: Partial<RateLimitOptions>;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n *@see Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n *\n * @env `JWT_COOKIE_SECURE`\n */\n secure?: boolean;\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n *\n * @env `JWT_COOKIE_HTTP_ONLY`\n */\n httpOnly?: boolean;\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n *\n * @env `JWT_COOKIE_SAME_SITE`\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n /**\n * Expiry date of the cookie in GMT. If not specified (undefined), creates a session cookie.\n *\n * @default `now() + authentication.jwt.expireIn | JWT_EXPIRES_IN`\n *\n * @since 1.5.11-beta\n */\n expires?: Date | undefined;\n /**\n * Domain for the cookie. Use a leading dot (e.g. `.example.com`) to include all subdomains.\n *\n * @env `JWT_COOKIE_DOMAIN`\n *\n * @since 1.5.11-beta\n */\n domain?: string | undefined;\n } & Omit<\n CookieOptions,\n \"secure\" | \"httpOnly\" | \"sameSite\" | \"expires\" | \"domain\"\n >;\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?: {\n /**\n * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n */\n strict?: boolean;\n } & (\n | {\n resolver: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * forbidNonWhitelisted: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver: \"zod\";\n validationOptions?: {\n /**\n * Throws an error for know whitelisted fields\n *\n * @default true\n */\n forbidNonWhitelisted?: boolean;\n };\n }\n );\n /**\n * Defines file upload configurations\n *\n * See {@link https://www.arkosjs.com/docs/guides/file-uploads/setup}\n */\n fileUpload?: {\n /**\n * Disables built-in file upload\n *\n * @since 1.5.11-beta\n */\n enabled?: boolean;\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStatic?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Defines express middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compression?: false | compression.CompressionOptions | ArkosRequestHandler;\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * Accepts:\n * - `false` — disables CORS middleware entirely.\n * - `cors.CorsOptions` — passed directly to the `cors` middleware.\n * - `cors.CorsOptionsDelegate` — a delegate function passed directly to the `cors` middleware.\n * - `ArkosRequestHandler` — a full Express middleware that replaces the cors middleware entirely.\n * - An object with deprecated `allowedOrigins`, `options`, and `customHandler` properties.\n *\n * In development, defaults to `origin: true, credentials: true`.\n * In production, defaults to `origin: \"*\"` (equivalent to plain `cors()`).\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?:\n | false\n | cors.CorsOptions\n | cors.CorsOptionsDelegate\n | {\n /**\n * Defines allowed origins to access the API.\n *\n * @deprecated Use `cors: { origin: string | string[] }` (cors.CorsOptions) directly instead.\n */\n allowedOrigins?: string | string[] | \"*\" | true;\n /**\n * Additional cors options.\n *\n * @deprecated Pass cors.CorsOptions directly instead: `cors: { origin: \"...\", credentials: true }`.\n */\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware.\n *\n * @deprecated Pass the handler directly instead: `cors: myCorsHandler`.\n */\n customHandler?: cors.CorsOptionsDelegate;\n }\n | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParser?:\n | false\n | {\n secret?: string | string[];\n options?: Parameters<typeof cookieParser>[1];\n }\n | ArkosRequestHandler /**\n * Options to define how query must be parsed.\n *\n * #### for 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 parseNumber: true,\n }\n * \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?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeRoute?: false | ArkosRequestHandler;\n };\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/core-concepts/open-api-documentation}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"PrismaFinalQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n /**\n * Allows to suppress specific warnings emitted by Arkos at startup or runtime.\n */\n warnings?: {\n /**\n * Suppresses specific warning messages.\n */\n suppress?: {\n /**\n * Suppresses Prisma-related warnings.\n */\n prisma?: {\n /**\n * Suppresses the warning emitted when no Prisma instance is found.\n */\n noInstanceFound?: boolean;\n /**\n * Suppresses the warning emitted when no Prisma schema is found.\n */\n noSchemaFound?: boolean;\n };\n };\n };\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundler.js","sourceRoot":"","sources":["../../../src/utils/bundler.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAoB;AACpB,gDAAwB;AA8DxB,MAAa,OAAO;IAiBV,cAAc,CAAC,aAA4B;QACjD,OAAO,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAA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AAa,EACb,eAAe,CAChB,CAAC;gBACF,IAAI,OAAO,KAAK,OAAO;oBAAE,YAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC;IACH,CAAC;;AAxWH,0BAyWC;AApWyB,sBAAc,GAAG;IACvC,0BAA0B;IAC1B,4BAA4B;IAC5B,sCAAsC;IACtC,uCAAuC;CACxC,CAAC;AAiWS,QAAA,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\n\n/**\n * Options for configuring a bundle run.\n */\ninterface BundlerOptions {\n /** Output file extension: \".js\" | \".cjs\" | \".mjs\" */\n ext: string;\n /** Directory containing the compiled output files to process */\n outDir: string;\n /** Source root directory used to resolve tsconfig paths. Defaults to process.cwd() */\n rootDir?: string;\n /** Explicit path to tsconfig.json or jsconfig.json. Auto-detected from rootDir if omitted */\n configPath?: string;\n}\n\n/**\n * Resolved path aliases and base URL extracted from tsconfig/jsconfig.\n */\ninterface ResolvedPaths {\n /** Absolute path used as the base for resolving alias targets */\n baseUrl: string;\n /** Map of alias patterns to their target path arrays, e.g. { \"@/*\": [\"src/*\"] } */\n paths: Record<string, string[]>;\n}\n\n/**\n * A pre-compiled alias entry for efficient matching at runtime.\n */\ninterface CompiledAlias {\n /** The alias prefix, e.g. \"@\" for \"@/*\" or \"@utils\" for \"@utils/*\" */\n prefix: string;\n /** Whether the alias uses a wildcard, e.g. \"@/*\" vs \"@root\" */\n isWildcard: boolean;\n /** Ordered list of target paths to try when the alias matches */\n targets: string[];\n}\n\n/**\n * Post-compilation import rewriter and alias resolver.\n *\n * Recursively processes all `.js`, `.cjs`, and `.mjs` files in the output\n * directory, rewriting:\n * - Relative imports to include the correct file extension\n * - Directory imports to use `/index.ext`\n * - Path aliases defined in tsconfig/jsconfig `paths` to relative paths\n *\n * Bare node_modules specifiers (e.g. `\"express\"`, `\"@prisma/client\"`) are\n * left untouched.\n *\n * @example\n * ```ts\n * const bundler = new Bundler();\n *\n * bundler.bundle({\n * ext: \".js\",\n * outDir: \"./dist\",\n * rootDir: \"./\",\n * configPath: \"./tsconfig.json\",\n * });\n * ```\n */\nexport class Bundler {\n /**\n * Regexes for matching all import/export/require statement forms.\n * Defined as static to avoid recreation per file processed.\n */\n private static readonly IMPORT_REGEXES = [\n /from\\s+['\"]([^'\"]+)['\"]/g,\n /import\\s+['\"]([^'\"]+)['\"]/g,\n /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n /require\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n ];\n\n /**\n * Pre-compiles path alias patterns into a lookup-friendly structure\n * so alias matching during processing is O(n) over aliases rather than\n * re-parsing patterns per import.\n */\n private compileAliases(resolvedPaths: ResolvedPaths): CompiledAlias[] {\n return Object.entries(resolvedPaths.paths).map(([pattern, targets]) => {\n const isWildcard = pattern.endsWith(\"/*\");\n return {\n prefix: isWildcard ? pattern.slice(0, -2) : pattern,\n isWildcard,\n targets,\n };\n });\n }\n\n /**\n * Loads and parses the tsconfig/jsconfig file, resolving any `extends` chain.\n * Falls back to `{ baseUrl: rootDir, paths: {} }` if no config is found.\n *\n * @param rootDir - Absolute root directory\n * @param configPath - Explicit config path, or undefined to auto-detect\n */\n private loadConfig(rootDir: string, configPath?: string): ResolvedPaths {\n const resolved = configPath\n ? path.resolve(configPath)\n : this.findConfig(rootDir);\n\n if (!resolved || !fs.existsSync(resolved)) {\n return { baseUrl: rootDir, paths: {} };\n }\n\n return this.parseConfig(resolved, rootDir);\n }\n\n /**\n * Searches for a tsconfig.json or jsconfig.json in the given directory.\n * Prefers tsconfig.json over jsconfig.json.\n *\n * @param dir - Directory to search in\n * @returns Absolute path to the config file, or null if not found\n */\n private findConfig(dir: string): string | null {\n for (const name of [\"tsconfig.json\", \"jsconfig.json\"]) {\n const candidate = path.join(dir, name);\n if (fs.existsSync(candidate)) return candidate;\n }\n return null;\n }\n\n /**\n * Recursively parses a tsconfig/jsconfig file, following `extends` chains\n * and merging `paths` with child config taking precedence over parent.\n *\n * @param configPath - Absolute path to the config file to parse\n * @param rootDir - Absolute root directory used as fallback baseUrl\n */\n private parseConfig(configPath: string, rootDir: string): ResolvedPaths {\n const configDir = path.dirname(configPath);\n const raw = this.readJsonWithComments(configPath);\n\n let base: ResolvedPaths = { baseUrl: rootDir, paths: {} };\n\n if (raw.extends) {\n const isPackage = !raw.extends.startsWith(\".\");\n const parentPath = isPackage\n ? this.resolveNodeModulesConfig(raw.extends, rootDir)\n : path.resolve(configDir, raw.extends);\n\n if (parentPath && fs.existsSync(parentPath)) {\n base = this.parseConfig(parentPath, rootDir);\n }\n }\n\n const co = raw.compilerOptions || {};\n const baseUrl = co.baseUrl\n ? path.resolve(configDir, co.baseUrl)\n : base.baseUrl;\n\n return {\n baseUrl,\n paths: { ...base.paths, ...(co.paths || {}) },\n };\n }\n\n /**\n * Resolves a tsconfig `extends` value that points to a node_modules package,\n * e.g. `\"@tsconfig/node18/tsconfig.json\"`.\n *\n * @param extendsValue - The raw extends string from tsconfig\n * @param rootDir - Root directory to resolve from\n * @returns Absolute path to the resolved config file, or null if not found\n */\n private resolveNodeModulesConfig(\n extendsValue: string,\n rootDir: string\n ): string | null {\n try {\n return require.resolve(extendsValue, { paths: [rootDir] });\n } catch {\n return null;\n }\n }\n\n /**\n * Reads a JSON file that may contain comments and trailing commas\n * (as tsconfig/jsconfig files allow) and returns the parsed object.\n *\n * @param filePath - Absolute path to the JSON file\n * @returns Parsed object, or empty object if parsing fails\n */\n private readJsonWithComments(filePath: string): any {\n const raw = fs.readFileSync(filePath, \"utf8\");\n return JSON.parse(\n raw\n .replace(\n /(\"(?:[^\"\\\\]|\\\\.)*\")|\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\//g,\n (_, str) => str ?? \"\"\n )\n .replace(/,(\\s*[}\\]])/g, \"$1\")\n );\n }\n\n /**\n * Resolves a single import path to its final rewritten form.\n *\n * Resolution order:\n * 1. Relative imports (`./`, `../`) — extension is added via `addExtension`\n * 2. Aliased imports — matched against compiled aliases and converted to relative paths\n * 3. Bare specifiers (`express`, `@prisma/client`) — returned untouched\n *\n * @param importPath - The raw import string from source code\n * @param fileDir - Absolute directory of the file containing the import\n * @param ext - The output file extension\n * @param resolvedPaths - Resolved baseUrl and paths from tsconfig\n * @param compiledAliases - Pre-compiled alias entries\n */\n\n private resolveImport(\n importPath: string,\n fileDir: string,\n rootOutDir: string,\n rootDir: string,\n ext: string,\n resolvedPaths: ResolvedPaths,\n compiledAliases: CompiledAlias[]\n ): string {\n if (importPath.startsWith(\".\") || importPath.startsWith(\"/\")) {\n return this.addExtension(importPath, fileDir, ext);\n }\n\n for (const alias of compiledAliases) {\n if (alias.isWildcard) {\n if (!importPath.startsWith(alias.prefix + \"/\")) continue;\n const remainder = importPath.slice(alias.prefix.length + 1);\n\n for (const target of alias.targets) {\n const absoluteSource = path.resolve(\n resolvedPaths.baseUrl,\n target.replace(\"*\", remainder)\n );\n const fileDirInSource = this.getFileDirInSource(\n fileDir,\n rootOutDir,\n rootDir,\n resolvedPaths.baseUrl\n );\n return this.addExtension(\n this.toRelative(fileDirInSource, absoluteSource),\n fileDir,\n ext\n );\n }\n } else {\n if (importPath !== alias.prefix) continue;\n for (const target of alias.targets) {\n const absoluteSource = path.resolve(resolvedPaths.baseUrl, target);\n const fileDirInSource = this.getFileDirInSource(\n fileDir,\n rootOutDir,\n rootDir,\n resolvedPaths.baseUrl\n );\n return this.addExtension(\n this.toRelative(fileDirInSource, absoluteSource),\n fileDir,\n ext\n );\n }\n }\n }\n\n return importPath;\n }\n\n private getFileDirInSource(\n fileDir: string,\n rootOutDir: string,\n rootDir: string,\n baseUrl: string\n ): string {\n const relToRootDir = path.relative(rootDir, rootOutDir);\n if (!relToRootDir) return baseUrl;\n\n // First component of relToRootDir is the dist folder name (e.g. \"dist\")\n const distFolderName = relToRootDir.split(path.sep)[0];\n const distRoot = path.join(rootDir, distFolderName);\n const relFromDistRoot = path.relative(distRoot, fileDir);\n return path.resolve(baseUrl, relFromDistRoot);\n }\n\n /**\n * Appends the configured extension to an import path if not already present.\n * If the path resolves to a directory containing an `index` file, appends\n * `/index.ext` instead.\n *\n * @param importPath - The relative import path to fix\n * @param fileDir - Absolute directory of the file containing the import\n * @param ext - The output file extension\n */\n private addExtension(\n importPath: string,\n fileDir: string,\n ext: string\n ): string {\n if (importPath.endsWith(ext)) return importPath;\n\n const absolute = path.resolve(fileDir, importPath);\n if (fs.existsSync(absolute + \"/index\" + ext)) {\n return importPath + \"/index\" + ext;\n }\n\n return importPath + ext;\n }\n\n /**\n * Converts an absolute path to a relative path from a given directory,\n * ensuring the result always starts with `./` or `../`.\n *\n * @param fromDir - The directory to compute the relative path from\n * @param toPath - The absolute target path\n * @returns A POSIX-style relative path\n */\n private toRelative(fromDir: string, toPath: string): string {\n const rel = path.relative(fromDir, toPath).replace(/\\\\/g, \"/\");\n return rel.startsWith(\".\") ? rel : \"./\" + rel;\n }\n\n /**\n * Rewrites all import/export/require statements in a string of JS source code.\n * Each regex is reset before use since they are stateful with the `/g` flag.\n *\n * @param content - Raw file content to process\n * @param fileDir - Absolute directory of the file being processed\n * @param ext - The output file extension\n * @param resolvedPaths - Resolved baseUrl and paths from tsconfig\n * @param compiledAliases - Pre-compiled alias entries\n */\n private rewriteImports(\n content: string,\n fileDir: string,\n rootOutDir: string,\n rootDir: string,\n ext: string,\n resolvedPaths: ResolvedPaths,\n compiledAliases: CompiledAlias[]\n ): string {\n for (const regex of Bundler.IMPORT_REGEXES) {\n regex.lastIndex = 0;\n content = content.replace(regex, (match, p) => {\n const fixed = this.resolveImport(\n p,\n fileDir,\n rootOutDir,\n rootDir,\n ext,\n resolvedPaths,\n compiledAliases\n );\n return fixed === p ? match : match.replace(p, fixed);\n });\n }\n return content;\n }\n\n /**\n * Recursively processes all `.js`, `.cjs`, and `.mjs` files in the output\n * directory, rewriting imports in-place. Files whose content is unchanged\n * are not written back to disk.\n *\n * @param options - Configuration options for this bundle run\n */\n bundle(options: BundlerOptions): void {\n const rootDir = path.resolve(options.rootDir || process.cwd());\n const outDir = path.resolve(options.outDir);\n const resolvedPaths = this.loadConfig(rootDir, options.configPath);\n const compiledAliases = this.compileAliases(resolvedPaths);\n\n this._bundleDir(\n options.ext,\n outDir,\n rootDir,\n resolvedPaths,\n compiledAliases,\n outDir\n );\n }\n\n /**\n * Internal recursive directory walker, separated so that `bundle()` only\n * resolves config once at the top level rather than on every recursion.\n */\n private _bundleDir(\n ext: string,\n rootOutDir: string,\n rootDir: string,\n resolvedPaths: ResolvedPaths,\n compiledAliases: CompiledAlias[],\n dir: string\n ): void {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n this._bundleDir(\n ext,\n rootOutDir,\n rootDir,\n resolvedPaths,\n compiledAliases,\n fullPath\n );\n } else if (/\\.(js|cjs|mjs)$/.test(entry.name)) {\n const content = fs.readFileSync(fullPath, \"utf8\");\n const updated = this.rewriteImports(\n content,\n path.dirname(fullPath),\n rootOutDir,\n rootDir,\n ext,\n resolvedPaths,\n compiledAliases\n );\n if (updated !== content) fs.writeFileSync(fullPath, updated);\n }\n }\n }\n}\n\nexport const bundler = new Bundler();\n"]}
|
|
1
|
+
{"version":3,"file":"bundler.js","sourceRoot":"","sources":["../../../src/utils/bundler.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAoB;AACpB,gDAAwB;AA8DxB,MAAa,OAAO;IAiBV,cAAc,CAAC,aAA4B;QACjD,OAAO,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,EAAE;YACpE,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;YAC1C,OAAO;gBACL,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC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yWC;AApWyB,sBAAc,GAAG;IACvC,0BAA0B;IAC1B,4BAA4B;IAC5B,sCAAsC;IACtC,uCAAuC;CACxC,CAAC;AAiWS,QAAA,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\n\n/**\n * Options for configuring a bundle run.\n */\ninterface BundlerOptions {\n /** Output file extension: \".js\" | \".cjs\" | \".mjs\" */\n ext: string;\n /** Directory containing the compiled output files to process */\n outDir: string;\n /** Source root directory used to resolve tsconfig paths. Defaults to process.cwd() */\n rootDir?: string;\n /** Explicit path to tsconfig.json or jsconfig.json. Auto-detected from rootDir if omitted */\n configPath?: string;\n}\n\n/**\n * Resolved path aliases and base URL extracted from tsconfig/jsconfig.\n */\ninterface ResolvedPaths {\n /** Absolute path used as the base for resolving alias targets */\n baseUrl: string;\n /** Map of alias patterns to their target path arrays, e.g. { \"@/*\": [\"src/*\"] } */\n paths: Record<string, string[]>;\n}\n\n/**\n * A pre-compiled alias entry for efficient matching at runtime.\n */\ninterface CompiledAlias {\n /** The alias prefix, e.g. \"@\" for \"@/*\" or \"@utils\" for \"@utils/*\" */\n prefix: string;\n /** Whether the alias uses a wildcard, e.g. \"@/*\" vs \"@root\" */\n isWildcard: boolean;\n /** Ordered list of target paths to try when the alias matches */\n targets: string[];\n}\n\n/**\n * Post-compilation import rewriter and alias resolver.\n *\n * Recursively processes all `.js`, `.cjs`, and `.mjs` files in the output\n * directory, rewriting:\n * - Relative imports to include the correct file extension\n * - Directory imports to use `/index.ext`\n * - Path aliases defined in tsconfig/jsconfig `paths` to relative paths\n *\n * Bare node_modules specifiers (e.g. `\"express\"`, `\"@prisma/client\"`) are\n * left untouched.\n *\n * @example\n * ```ts\n * const bundler = new Bundler();\n *\n * bundler.bundle({\n * ext: \".js\",\n * outDir: \"./dist\",\n * rootDir: \"./\",\n * configPath: \"./tsconfig.json\",\n * });\n * ```\n */\nexport class Bundler {\n /**\n * Regexes for matching all import/export/require statement forms.\n * Defined as static to avoid recreation per file processed.\n */\n private static readonly IMPORT_REGEXES = [\n /from\\s+['\"]([^'\"]+)['\"]/g,\n /import\\s+['\"]([^'\"]+)['\"]/g,\n /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n /require\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n ];\n\n /**\n * Pre-compiles path alias patterns into a lookup-friendly structure\n * so alias matching during processing is O(n) over aliases rather than\n * re-parsing patterns per import.\n */\n private compileAliases(resolvedPaths: ResolvedPaths): CompiledAlias[] {\n return Object.entries(resolvedPaths.paths).map(([pattern, targets]) => {\n const isWildcard = pattern.endsWith(\"/*\");\n return {\n prefix: isWildcard ? pattern.slice(0, -2) : pattern,\n isWildcard,\n targets,\n };\n });\n }\n\n /**\n * Loads and parses the tsconfig/jsconfig file, resolving any `extends` chain.\n * Falls back to `{ baseUrl: rootDir, paths: {} }` if no config is found.\n *\n * @param rootDir - Absolute root directory\n * @param configPath - Explicit config path, or undefined to auto-detect\n */\n private loadConfig(rootDir: string, configPath?: string): ResolvedPaths {\n const resolved = configPath\n ? path.resolve(configPath)\n : this.findConfig(rootDir);\n\n if (!resolved || !fs.existsSync(resolved)) {\n return { baseUrl: rootDir, paths: {} };\n }\n\n return this.parseConfig(resolved, rootDir);\n }\n\n /**\n * Searches for a tsconfig.json or jsconfig.json in the given directory.\n * Prefers tsconfig.json over jsconfig.json.\n *\n * @param dir - Directory to search in\n * @returns Absolute path to the config file, or null if not found\n */\n private findConfig(dir: string): string | null {\n for (const name of [\"tsconfig.json\", \"jsconfig.json\"]) {\n const candidate = path.join(dir, name);\n if (fs.existsSync(candidate)) return candidate;\n }\n return null;\n }\n\n /**\n * Recursively parses a tsconfig/jsconfig file, following `extends` chains\n * and merging `paths` with child config taking precedence over parent.\n *\n * @param configPath - Absolute path to the config file to parse\n * @param rootDir - Absolute root directory used as fallback baseUrl\n */\n private parseConfig(configPath: string, rootDir: string): ResolvedPaths {\n const configDir = path.dirname(configPath);\n const raw = this.readJsonWithComments(configPath);\n\n let base: ResolvedPaths = { baseUrl: rootDir, paths: {} };\n\n if (raw.extends) {\n const isPackage = !raw.extends.startsWith(\".\");\n const parentPath = isPackage\n ? this.resolveNodeModulesConfig(raw.extends, rootDir)\n : path.resolve(configDir, raw.extends);\n\n if (parentPath && fs.existsSync(parentPath)) {\n base = this.parseConfig(parentPath, rootDir);\n }\n }\n\n const co = raw.compilerOptions || {};\n const baseUrl = co.baseUrl\n ? path.resolve(configDir, co.baseUrl)\n : base.baseUrl;\n\n return {\n baseUrl,\n paths: { ...base.paths, ...(co.paths || {}) },\n };\n }\n\n /**\n * Resolves a tsconfig `extends` value that points to a node_modules package,\n * e.g. `\"@tsconfig/node18/tsconfig.json\"`.\n *\n * @param extendsValue - The raw extends string from tsconfig\n * @param rootDir - Root directory to resolve from\n * @returns Absolute path to the resolved config file, or null if not found\n */\n private resolveNodeModulesConfig(\n extendsValue: string,\n rootDir: string\n ): string | null {\n try {\n return require.resolve(extendsValue, { paths: [rootDir] });\n } catch {\n return null;\n }\n }\n\n /**\n * Reads a JSON file that may contain comments and trailing commas\n * (as tsconfig/jsconfig files allow) and returns the parsed object.\n *\n * @param filePath - Absolute path to the JSON file\n * @returns Parsed object, or empty object if parsing fails\n */\n readJsonWithComments(filePath: string): any {\n const raw = fs.readFileSync(filePath, \"utf8\");\n return JSON.parse(\n raw\n .replace(\n /(\"(?:[^\"\\\\]|\\\\.)*\")|\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\//g,\n (_, str) => str ?? \"\"\n )\n .replace(/,(\\s*[}\\]])/g, \"$1\")\n );\n }\n\n /**\n * Resolves a single import path to its final rewritten form.\n *\n * Resolution order:\n * 1. Relative imports (`./`, `../`) — extension is added via `addExtension`\n * 2. Aliased imports — matched against compiled aliases and converted to relative paths\n * 3. Bare specifiers (`express`, `@prisma/client`) — returned untouched\n *\n * @param importPath - The raw import string from source code\n * @param fileDir - Absolute directory of the file containing the import\n * @param ext - The output file extension\n * @param resolvedPaths - Resolved baseUrl and paths from tsconfig\n * @param compiledAliases - Pre-compiled alias entries\n */\n\n private resolveImport(\n importPath: string,\n fileDir: string,\n rootOutDir: string,\n rootDir: string,\n ext: string,\n resolvedPaths: ResolvedPaths,\n compiledAliases: CompiledAlias[]\n ): string {\n if (importPath.startsWith(\".\") || importPath.startsWith(\"/\")) {\n return this.addExtension(importPath, fileDir, ext);\n }\n\n for (const alias of compiledAliases) {\n if (alias.isWildcard) {\n if (!importPath.startsWith(alias.prefix + \"/\")) continue;\n const remainder = importPath.slice(alias.prefix.length + 1);\n\n for (const target of alias.targets) {\n const absoluteSource = path.resolve(\n resolvedPaths.baseUrl,\n target.replace(\"*\", remainder)\n );\n const fileDirInSource = this.getFileDirInSource(\n fileDir,\n rootOutDir,\n rootDir,\n resolvedPaths.baseUrl\n );\n return this.addExtension(\n this.toRelative(fileDirInSource, absoluteSource),\n fileDir,\n ext\n );\n }\n } else {\n if (importPath !== alias.prefix) continue;\n for (const target of alias.targets) {\n const absoluteSource = path.resolve(resolvedPaths.baseUrl, target);\n const fileDirInSource = this.getFileDirInSource(\n fileDir,\n rootOutDir,\n rootDir,\n resolvedPaths.baseUrl\n );\n return this.addExtension(\n this.toRelative(fileDirInSource, absoluteSource),\n fileDir,\n ext\n );\n }\n }\n }\n\n return importPath;\n }\n\n private getFileDirInSource(\n fileDir: string,\n rootOutDir: string,\n rootDir: string,\n baseUrl: string\n ): string {\n const relToRootDir = path.relative(rootDir, rootOutDir);\n if (!relToRootDir) return baseUrl;\n\n // First component of relToRootDir is the dist folder name (e.g. \"dist\")\n const distFolderName = relToRootDir.split(path.sep)[0];\n const distRoot = path.join(rootDir, distFolderName);\n const relFromDistRoot = path.relative(distRoot, fileDir);\n return path.resolve(baseUrl, relFromDistRoot);\n }\n\n /**\n * Appends the configured extension to an import path if not already present.\n * If the path resolves to a directory containing an `index` file, appends\n * `/index.ext` instead.\n *\n * @param importPath - The relative import path to fix\n * @param fileDir - Absolute directory of the file containing the import\n * @param ext - The output file extension\n */\n private addExtension(\n importPath: string,\n fileDir: string,\n ext: string\n ): string {\n if (importPath.endsWith(ext)) return importPath;\n\n const absolute = path.resolve(fileDir, importPath);\n if (fs.existsSync(absolute + \"/index\" + ext)) {\n return importPath + \"/index\" + ext;\n }\n\n return importPath + ext;\n }\n\n /**\n * Converts an absolute path to a relative path from a given directory,\n * ensuring the result always starts with `./` or `../`.\n *\n * @param fromDir - The directory to compute the relative path from\n * @param toPath - The absolute target path\n * @returns A POSIX-style relative path\n */\n private toRelative(fromDir: string, toPath: string): string {\n const rel = path.relative(fromDir, toPath).replace(/\\\\/g, \"/\");\n return rel.startsWith(\".\") ? rel : \"./\" + rel;\n }\n\n /**\n * Rewrites all import/export/require statements in a string of JS source code.\n * Each regex is reset before use since they are stateful with the `/g` flag.\n *\n * @param content - Raw file content to process\n * @param fileDir - Absolute directory of the file being processed\n * @param ext - The output file extension\n * @param resolvedPaths - Resolved baseUrl and paths from tsconfig\n * @param compiledAliases - Pre-compiled alias entries\n */\n private rewriteImports(\n content: string,\n fileDir: string,\n rootOutDir: string,\n rootDir: string,\n ext: string,\n resolvedPaths: ResolvedPaths,\n compiledAliases: CompiledAlias[]\n ): string {\n for (const regex of Bundler.IMPORT_REGEXES) {\n regex.lastIndex = 0;\n content = content.replace(regex, (match, p) => {\n const fixed = this.resolveImport(\n p,\n fileDir,\n rootOutDir,\n rootDir,\n ext,\n resolvedPaths,\n compiledAliases\n );\n return fixed === p ? match : match.replace(p, fixed);\n });\n }\n return content;\n }\n\n /**\n * Recursively processes all `.js`, `.cjs`, and `.mjs` files in the output\n * directory, rewriting imports in-place. Files whose content is unchanged\n * are not written back to disk.\n *\n * @param options - Configuration options for this bundle run\n */\n bundle(options: BundlerOptions): void {\n const rootDir = path.resolve(options.rootDir || process.cwd());\n const outDir = path.resolve(options.outDir);\n const resolvedPaths = this.loadConfig(rootDir, options.configPath);\n const compiledAliases = this.compileAliases(resolvedPaths);\n\n this._bundleDir(\n options.ext,\n outDir,\n rootDir,\n resolvedPaths,\n compiledAliases,\n outDir\n );\n }\n\n /**\n * Internal recursive directory walker, separated so that `bundle()` only\n * resolves config once at the top level rather than on every recursion.\n */\n private _bundleDir(\n ext: string,\n rootOutDir: string,\n rootDir: string,\n resolvedPaths: ResolvedPaths,\n compiledAliases: CompiledAlias[],\n dir: string\n ): void {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n this._bundleDir(\n ext,\n rootOutDir,\n rootDir,\n resolvedPaths,\n compiledAliases,\n fullPath\n );\n } else if (/\\.(js|cjs|mjs)$/.test(entry.name)) {\n const content = fs.readFileSync(fullPath, \"utf8\");\n const updated = this.rewriteImports(\n content,\n path.dirname(fullPath),\n rootOutDir,\n rootDir,\n ext,\n resolvedPaths,\n compiledAliases\n );\n if (updated !== content) fs.writeFileSync(fullPath, updated);\n }\n }\n }\n}\n\nexport const bundler = new Bundler();\n"]}
|
|
@@ -71,8 +71,7 @@ function buildTypeScriptProject(options, moduleType) {
|
|
|
71
71
|
let tsconfig = {};
|
|
72
72
|
try {
|
|
73
73
|
if (fs_1.default.existsSync(tsconfigPath)) {
|
|
74
|
-
|
|
75
|
-
tsconfig = JSON.parse(tsconfigContent);
|
|
74
|
+
tsconfig = bundler_1.bundler.readJsonWithComments(tsconfigPath);
|
|
76
75
|
}
|
|
77
76
|
}
|
|
78
77
|
catch (error) {
|