arkos 2.0.0-next.2 → 2.0.0-next.4

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.
Files changed (29) hide show
  1. package/dist/cjs/components/arkos-policy/index.js +3 -1
  2. package/dist/cjs/components/arkos-policy/index.js.map +1 -1
  3. package/dist/cjs/modules/file-upload/file-upload.controller.js +2 -2
  4. package/dist/cjs/modules/file-upload/file-upload.controller.js.map +1 -1
  5. package/dist/cjs/utils/bundler.js.map +1 -1
  6. package/dist/cjs/utils/cli/build.js +2 -1
  7. package/dist/cjs/utils/cli/build.js.map +1 -1
  8. package/dist/cjs/utils/cli/start.js +1 -1
  9. package/dist/cjs/utils/cli/start.js.map +1 -1
  10. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  11. package/dist/cjs/utils/cli/utils/runtime-cli-commander.js +0 -1
  12. package/dist/cjs/utils/cli/utils/runtime-cli-commander.js.map +1 -1
  13. package/dist/cjs/utils/helpers/fs.helpers.js +1 -1
  14. package/dist/cjs/utils/helpers/fs.helpers.js.map +1 -1
  15. package/dist/esm/components/arkos-policy/index.js +3 -1
  16. package/dist/esm/components/arkos-policy/index.js.map +1 -1
  17. package/dist/esm/modules/file-upload/file-upload.controller.js +2 -2
  18. package/dist/esm/modules/file-upload/file-upload.controller.js.map +1 -1
  19. package/dist/esm/utils/bundler.js.map +1 -1
  20. package/dist/esm/utils/cli/build.js +2 -1
  21. package/dist/esm/utils/cli/build.js.map +1 -1
  22. package/dist/esm/utils/cli/start.js +1 -1
  23. package/dist/esm/utils/cli/start.js.map +1 -1
  24. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  25. package/dist/esm/utils/cli/utils/runtime-cli-commander.js +0 -1
  26. package/dist/esm/utils/cli/utils/runtime-cli-commander.js.map +1 -1
  27. package/dist/esm/utils/helpers/fs.helpers.js +1 -1
  28. package/dist/esm/utils/helpers/fs.helpers.js.map +1 -1
  29. package/package.json +1 -1
@@ -19,7 +19,9 @@ function buildPolicy(resource, store) {
19
19
  action,
20
20
  rule: config,
21
21
  };
22
- const checker = (user) => auth_service_1.default.permission(action, resource, { [action]: config || {} })(user);
22
+ const checker = auth_service_1.default.permission(action, resource, {
23
+ [action]: config || {},
24
+ });
23
25
  const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;
24
26
  return [
25
27
  [action, authEntry],
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/components/arkos-policy/index.ts"],"names":[],"mappings":";;;;;AAuCA,kCAIC;AAnCD,mFAA0D;AA+B1D,SAAgB,WAAW,CACzB,QAAmB;IAEnB,OAAO,WAAW,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,WAAW,CAClB,QAAmB,EACnB,KAAsC;IAEtC,MAAM,IAAI,GAAG,CACX,MAAe,EACf,MAAuB,EAC2B,EAAE;QACpD,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAChD,OAAO,WAAW,CAAgC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACxE,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CACtC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,EAAE;QACjD,MAAM,SAAS,GAA8C;YAC3D,QAAQ;YACR,MAAM;YACN,IAAI,EAAE,MAAM;SACb,CAAC;QAEF,MAAM,OAAO,GAAkB,CAAC,IAAW,EAAoB,EAAE,CAC/D,sBAAW,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,IAAI,EAAE,EAAE,CAAC,CAClE,IAAI,CACL,CAAC;QAEJ,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QAExE,OAAO;YACL,CAAC,MAAM,EAAE,SAAS,CAAC;YACnB,CAAC,MAAM,EAAE,OAAO,CAAC;SAClB,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;IAEF,OAAO;QACL,MAAM,EAAE,aAAsB;QAC9B,QAAQ;QACR,IAAI;QACJ,GAAG,aAAa;KACoC,CAAC;AACzD,CAAC","sourcesContent":["import { User } from \"../../types\";\nimport {\n ArkosPolicyRule,\n IArkosPolicy,\n PolicyAuthEntry,\n PolicyChecker,\n PolicyWithActions,\n} from \"./types\";\nimport authService from \"../../modules/auth/auth.service\";\n\n/**\n * Creates a typed policy for a Prisma model resource.\n *\n * Each `.rule()` call registers an action and returns the policy\n * with a typed `can{Action}` permission checker and a typed `{Action}`\n * entry — both passable to the `authentication` field on `ArkosRouteHook`\n * and `ArkosRouter`, and callable for fine-grained permission checks.\n *\n * @param resource - The resource name in kebab-case (e.g. `\"user\"`, `\"blog-post\"`)\n *\n * @example\n * ```ts\n * const userPolicy = ArkosPolicy(\"user\")\n * .rule(\"Create\", [\"Admin\", \"Editor\"])\n * .rule(\"View\", \"*\")\n * .rule(\"Delete\", [\"Admin\"]);\n *\n * // Pass to authentication field\n * userRouter.post({ path: \"/users\", authentication: userPolicy.Create });\n * userRouteHook.deleteOne({ authentication: userPolicy.Delete });\n *\n * // Fine-grained check\n * if (userPolicy.canCreate(req.user)) { ... }\n *\n * export default userPolicy;\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-referency/arkos-policy}\n */\nexport function ArkosPolicy<TResource extends string>(\n resource: TResource\n): IArkosPolicy<TResource, never> {\n return buildPolicy(resource, {});\n}\n\nfunction buildPolicy<TResource extends string, TActions extends string>(\n resource: TResource,\n store: Record<string, ArkosPolicyRule>\n): PolicyWithActions<TResource, TActions> {\n const rule = <TAction extends string>(\n action: TAction,\n config: ArkosPolicyRule\n ): PolicyWithActions<TResource, TActions | TAction> => {\n const newStore = { ...store, [action]: config };\n return buildPolicy<TResource, TActions | TAction>(resource, newStore);\n };\n\n const actionEntries = Object.fromEntries(\n Object.entries(store).flatMap(([action, config]) => {\n const authEntry: PolicyAuthEntry<TResource, typeof action> = {\n resource,\n action,\n rule: config,\n };\n\n const checker: PolicyChecker = (user?: User): Promise<boolean> =>\n authService.permission(action, resource, { [action]: config || {} })(\n user\n );\n\n const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;\n\n return [\n [action, authEntry],\n [canKey, checker],\n ];\n })\n );\n\n return {\n __type: \"ArkosPolicy\" as const,\n resource,\n rule,\n ...actionEntries,\n } as unknown as PolicyWithActions<TResource, TActions>;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/components/arkos-policy/index.ts"],"names":[],"mappings":";;;;;AAuCA,kCAIC;AAnCD,mFAA0D;AA+B1D,SAAgB,WAAW,CACzB,QAAmB;IAEnB,OAAO,WAAW,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,WAAW,CAClB,QAAmB,EACnB,KAAsC;IAEtC,MAAM,IAAI,GAAG,CACX,MAAe,EACf,MAAuB,EAC2B,EAAE;QACpD,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAChD,OAAO,WAAW,CAAgC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACxE,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CACtC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,EAAE;QACjD,MAAM,SAAS,GAA8C;YAC3D,QAAQ;YACR,MAAM;YACN,IAAI,EAAE,MAAM;SACb,CAAC;QAEF,MAAM,OAAO,GAAkB,sBAAW,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,EAAE;YACtE,CAAC,MAAM,CAAC,EAAE,MAAM,IAAI,EAAE;SACvB,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QAExE,OAAO;YACL,CAAC,MAAM,EAAE,SAAS,CAAC;YACnB,CAAC,MAAM,EAAE,OAAO,CAAC;SAClB,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;IAEF,OAAO;QACL,MAAM,EAAE,aAAsB;QAC9B,QAAQ;QACR,IAAI;QACJ,GAAG,aAAa;KACoC,CAAC;AACzD,CAAC","sourcesContent":["import { User } from \"../../types\";\nimport {\n ArkosPolicyRule,\n IArkosPolicy,\n PolicyAuthEntry,\n PolicyChecker,\n PolicyWithActions,\n} from \"./types\";\nimport authService from \"../../modules/auth/auth.service\";\n\n/**\n * Creates a typed policy for a Prisma model resource.\n *\n * Each `.rule()` call registers an action and returns the policy\n * with a typed `can{Action}` permission checker and a typed `{Action}`\n * entry — both passable to the `authentication` field on `ArkosRouteHook`\n * and `ArkosRouter`, and callable for fine-grained permission checks.\n *\n * @param resource - The resource name in kebab-case (e.g. `\"user\"`, `\"blog-post\"`)\n *\n * @example\n * ```ts\n * const userPolicy = ArkosPolicy(\"user\")\n * .rule(\"Create\", [\"Admin\", \"Editor\"])\n * .rule(\"View\", \"*\")\n * .rule(\"Delete\", [\"Admin\"]);\n *\n * // Pass to authentication field\n * userRouter.post({ path: \"/users\", authentication: userPolicy.Create });\n * userRouteHook.deleteOne({ authentication: userPolicy.Delete });\n *\n * // Fine-grained check\n * if (userPolicy.canCreate(req.user)) { ... }\n *\n * export default userPolicy;\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-referency/arkos-policy}\n */\nexport function ArkosPolicy<TResource extends string>(\n resource: TResource\n): IArkosPolicy<TResource, never> {\n return buildPolicy(resource, {});\n}\n\nfunction buildPolicy<TResource extends string, TActions extends string>(\n resource: TResource,\n store: Record<string, ArkosPolicyRule>\n): PolicyWithActions<TResource, TActions> {\n const rule = <TAction extends string>(\n action: TAction,\n config: ArkosPolicyRule\n ): PolicyWithActions<TResource, TActions | TAction> => {\n const newStore = { ...store, [action]: config };\n return buildPolicy<TResource, TActions | TAction>(resource, newStore);\n };\n\n const actionEntries = Object.fromEntries(\n Object.entries(store).flatMap(([action, config]) => {\n const authEntry: PolicyAuthEntry<TResource, typeof action> = {\n resource,\n action,\n rule: config,\n };\n\n const checker: PolicyChecker = authService.permission(action, resource, {\n [action]: config || {},\n });\n\n const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;\n\n return [\n [action, authEntry],\n [canKey, checker],\n ];\n })\n );\n\n return {\n __type: \"ArkosPolicy\" as const,\n resource,\n rule,\n ...actionEntries,\n } as unknown as PolicyWithActions<TResource, TActions>;\n}\n"]}
@@ -24,7 +24,7 @@ class FileUploadController {
24
24
  const { documentUploadService, fileUploadService, imageUploadService, videoUploadService, } = (0, file_upload_service_1.getFileUploadServices)();
25
25
  const { fileUpload } = (0, server_1.getArkosConfig)();
26
26
  const baseUploadDir = fileUpload?.baseUploadDir || "/uploads";
27
- const uploadPath = path_1.default.resolve(process.cwd(), baseUploadDir, fileType);
27
+ const uploadPath = path_1.default.resolve(path_1.default.join(process.cwd(), baseUploadDir, fileType));
28
28
  try {
29
29
  await fs_1.default.promises.access(uploadPath);
30
30
  }
@@ -144,7 +144,7 @@ class FileUploadController {
144
144
  const { documentUploadService, fileUploadService, imageUploadService, videoUploadService, } = (0, file_upload_service_1.getFileUploadServices)();
145
145
  const { fileUpload } = (0, server_1.getArkosConfig)();
146
146
  const baseUploadDir = fileUpload?.baseUploadDir || "/uploads";
147
- const uploadPath = path_1.default.resolve(process.cwd(), baseUploadDir, fileType);
147
+ const uploadPath = path_1.default.resolve(path_1.default.join(process.cwd(), baseUploadDir, fileType));
148
148
  try {
149
149
  await fs_1.default.promises.access(uploadPath);
150
150
  }
@@ -1 +1 @@
1
- {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,mCAAqC;AACrC,+CAAiD;AACjD,uGAAwE;AACxE,qEAA2E;AAK3E,MAAa,oBAAoB;IAAjC;QAgCE,eAAU,GAAG,IAAA,qBAAU,EACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;YAChC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;YACtD,MAAM,OAAO,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;YAEpD,MAAM,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,GAAG,IAAA,2CAAqB,GAAE,CAAC;YAE5B,MAAM,EAAE,UAAU,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;YACxC,MAAM,aAAa,GAAG,UAAU,EAAE,aAAa,IAAI,UAAU,CAAC;YAE9D,MAAM,UAAU,GAAG,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,QAAQ,CAAC,CAAC;YACxE,IAAI,CAAC;gBACH,MAAM,YAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;YACvC,CAAC;YAAC,MAAM,CAAC;gBACP,MAAM,YAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAA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ACJ,CAAC;CA+SF;AAtUD,oDAsUC;AAOD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { MulterError } from \"multer\";\nimport { pascalCase } from \"../../exports/utils\";\nimport loadableRegistry from \"../../components/arkos-loadable-registry\";\nimport { routeHookReader } from \"../../components/arkos-route-hook/reader\";\n\n/**\n * Handles file uploads and allows to be extended via route hooks.\n */\nexport class FileUploadController {\n private handleUploadError(err: any, next: ArkosNextFunction) {\n if (err instanceof MulterError)\n return next(\n new AppError(\n err.message,\n 400,\n pascalCase(err.code || \"FileUploadError\")\n )\n );\n else return next(err);\n }\n\n private getRouteHook() {\n return loadableRegistry.getItem(\"ArkosRouteHook\", \"file-upload\");\n }\n\n private getAfterHook(operation: string) {\n const hook = this.getRouteHook();\n if (!hook) return null;\n return (\n routeHookReader.getHooks(\"file-upload\", operation as any)?.after ?? null\n );\n }\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = req.files.map((file) => processFile(req, file.path));\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n const afterHook = this.getAfterHook(\"uploadFile\");\n if (afterHook) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n const afterHook = this.getAfterHook(\"deleteFile\");\n if (afterHook) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = req.files.map((file) => processFile(req, file.path));\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n const afterHook = this.getAfterHook(\"updateFile\");\n if (afterHook) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
1
+ {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,mCAAqC;AACrC,+CAAiD;AACjD,uGAAwE;AACxE,qEAA2E;AAK3E,MAAa,oBAAoB;IAAjC;QAgCE,eAAU,GAAG,IAAA,qBAAU,EACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;YAChC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;YACtD,MAAM,OAAO,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;YAEpD,MAAM,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,GAAG,IAAA,2CAAqB,GAAE,CAAC;YAE5B,MAAM,EAAE,UAAU,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;YACxC,MAAM,aAAa,GAAG,UAAU,EAAE,aAAa,IAAI,UAAU,CAAC;YAE9D,MAAM,UAAU,GAAG,cAAI,CAAC,OAAO,CAC7B,cAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,Q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,EAAE,aAAa,CAAC,CAAC;IACnE,CAAC;IAEO,YAAY,CAAC,SAAiB;QACpC,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QACjC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,OAAO,CACL,wBAAe,CAAC,QAAQ,CAAC,aAAa,EAAE,SAAgB,CAAC,EAAE,KAAK,IAAI,IAAI,CACzE,CAAC;IACJ,CAAC;CAmTF;AA1UD,oDA0UC;AAOD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { MulterError } from \"multer\";\nimport { pascalCase } from \"../../exports/utils\";\nimport loadableRegistry from \"../../components/arkos-loadable-registry\";\nimport { routeHookReader } from \"../../components/arkos-route-hook/reader\";\n\n/**\n * Handles file uploads and allows to be extended via route hooks.\n */\nexport class FileUploadController {\n private handleUploadError(err: any, next: ArkosNextFunction) {\n if (err instanceof MulterError)\n return next(\n new AppError(\n err.message,\n 400,\n pascalCase(err.code || \"FileUploadError\")\n )\n );\n else return next(err);\n }\n\n private getRouteHook() {\n return loadableRegistry.getItem(\"ArkosRouteHook\", \"file-upload\");\n }\n\n private getAfterHook(operation: string) {\n const hook = this.getRouteHook();\n if (!hook) return null;\n return (\n routeHookReader.getHooks(\"file-upload\", operation as any)?.after ?? null\n );\n }\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = req.files.map((file) => processFile(req, file.path));\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n const afterHook = this.getAfterHook(\"uploadFile\");\n if (afterHook) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n const afterHook = this.getAfterHook(\"deleteFile\");\n if (afterHook) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = req.files.map((file) => processFile(req, file.path));\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n const afterHook = this.getAfterHook(\"updateFile\");\n if (afterHook) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
@@ -1 +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,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,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO;gBACnD,UAAU;gBACV,OAAO;aACR,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IASO,UAAU,CAAC,OAAe,EAAE,UAAmB;QACrD,MAAM,QAAQ,GAAG,UAAU;YACzB,CAAC,CAAC,cAAI,CAAC,OAAO,CAAC,UAAU,CAAC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CAAC;IACJ,CAAC;IAMO,UAAU,CAChB,GAAW,EACX,UAAkB,EAClB,OAAe,EACf,aAA4B,EAC5B,eAAgC,EAChC,GAAW;QAEX,MAAM,OAAO,GAAG,YAAE,CAAC,WAAW,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;QAE7D,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;YAC5B,MAAM,QAAQ,GAAG,cAAI,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;YAE5C,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;gBACxB,IAAI,CAAC,UAAU,CACb,GAAG,EACH,UAAU,EACV,OAAO,EACP,aAAa,EACb,eAAe,EACf,QAAQ,CACT,CAAC;YACJ,CAAC;iBAAM,IAAI,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC9C,MAAM,OAAO,GAAG,YAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;gBAClD,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CACjC,OAAO,EACP,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EACtB,UAAU,EACV,OAAO,EACP,GAAG,EACH,aAAa,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;;AAzWH,0BA0WC;AArWyB,sBAAc,GAAG;IACvC,0BAA0B;IAC1B,4BAA4B;IAC5B,sCAAsC;IACtC,uCAAuC;CACxC,CAAC;AAkWS,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\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,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO;gBACnD,UAAU;gBACV,OAAO;aACR,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IASO,UAAU,CAAC,OAAe,EAAE,UAAmB;QACrD,MAAM,QAAQ,GAAG,UAAU;YACzB,CAAC,CAAC,cAAI,CAAC,OAAO,CAAC,UAAU,CAAC;YAC1B,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAE7B,IAAI,CAAC,QAAQ,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC1C,OAAO,EAAE,O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aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;QAE7D,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;YAC5B,MAAM,QAAQ,GAAG,cAAI,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;YAE5C,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;gBACxB,IAAI,CAAC,UAAU,CACb,GAAG,EACH,UAAU,EACV,OAAO,EACP,aAAa,EACb,eAAe,EACf,QAAQ,CACT,CAAC;YACJ,CAAC;iBAAM,IAAI,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC9C,MAAM,OAAO,GAAG,YAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;gBAClD,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CACjC,OAAO,EACP,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EACtB,UAAU,EACV,OAAO,EACP,GAAG,EACH,aAAa,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"]}
@@ -140,7 +140,8 @@ function buildJavaScriptProject(_, moduleType) {
140
140
  });
141
141
  }
142
142
  catch (error) {
143
- console.error("❌ Error building JavaScript project:", error);
143
+ console.info(error.stack);
144
+ console.error("❌ Error building JavaScript project:", error.stack);
144
145
  throw error;
145
146
  }
146
147
  }
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":";;;;;AAuBA,oCAmCC;AA1DD,gDAAwB;AACxB,4CAAoB;AACpB,iDAAyC;AACzC,sDAA6D;AAC7D,sDAA6D;AAC7D,8DAA8E;AAC9E,mDAA2B;AAC3B,kFAAyD;AACzD,8CAA0C;AAC1C,wCAAqC;AAErC,MAAM,SAAS,GAAG,QAAQ,CAAC;AAC3B,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,KAAK,CAAU,CAAC;AAW7C,SAAgB,YAAY,CAAC,UAAwB,EAAE;IACrD,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC;IAC5B,MAAM,OAAO,GAAG,IAAA,iCAAoB,GAAE,CAAC;IACvC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ;QAC1D,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,YAAY,CAAC;IACtC,OAAO,CAAC,GAAG,CAAC,WAAW,GAAG,MAAM,CAAC;IAEjC,MAAM,QAAQ,GAAG,IAAA,yCAAwB,GAAE,CAAC;IAC5C,MAAM,UAAU,GAAG,kBAAkB,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC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AAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,EAC9B,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAC3B,CAAC;YACJ,CAAC;QACH,CAAC;IAGH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,CAAC,CAAC;QAC7D,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;AACH,CAAC;AAKD,SAAS,iBAAiB,CAAC,UAAkB;IAC3C,IAAI,CAAC;QACH,IAAI,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC;YAAE,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport { removeDir } from \"../remove-dir\";\nimport { bundler } from \"../bundler\";\n\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n process.env.NO_CLI = \"true\";\n const fileExt = getUserFileExtension();\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n watermarkStamper.stamp({\n envFiles,\n });\n\n console.info(`\\n Creating an optimized production build...`);\n\n ensureBuildDir();\n\n if (fileExt === \"ts\") buildTypeScriptProject(options, moduleType);\n else buildJavaScriptProject(options, moduleType);\n\n const packageManger = detectPackageManagerFromUserAgent();\n\n console.info(`\\n\\x1b[1m\\x1b[32m Build complete!\\x1b[0m\\n`);\n console.info(` \\x1b[1mNext step:\\x1b[0m`);\n console.info(\n ` Run it using \\x1b[1m\\x1b[36m${packageManger} run start\\x1b[0m\\n`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(`Build failed: ${err?.message}`);\n console.error(err);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") return \"cjs\";\n else if ([\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType))\n return \"esm\";\n\n sheu.warn(`Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`);\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) fs.mkdirSync(BUILD_DIR, { recursive: true });\n\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n }\n\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n removeDir(BUILD_DIR);\n execSync(`npx tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n configPath: tempTsconfigPath,\n });\n\n // Clean up temp config\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(_: BuildOptions, moduleType: ModuleType) {\n const targetDir = path.join(BUILD_DIR);\n\n try {\n if (moduleType === \"esm\") {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n });\n // createModulePackageJson(moduleType);\n } catch (error) {\n console.error(\"❌ Error building JavaScript project:\", error);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(_: ModuleType, skipExtensions: string[]) {\n const targetDir = path.join(BUILD_DIR);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"arkos.config.js\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n // console.info(`Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}
1
+ {"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":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UAAU,CAAC,UAAU,CAAC;YAAE,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport { removeDir } from \"../remove-dir\";\nimport { bundler } from \"../bundler\";\n\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n process.env.NO_CLI = \"true\";\n const fileExt = getUserFileExtension();\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n watermarkStamper.stamp({\n envFiles,\n });\n\n console.info(`\\n Creating an optimized production build...`);\n\n ensureBuildDir();\n\n if (fileExt === \"ts\") buildTypeScriptProject(options, moduleType);\n else buildJavaScriptProject(options, moduleType);\n\n const packageManger = detectPackageManagerFromUserAgent();\n\n console.info(`\\n\\x1b[1m\\x1b[32m Build complete!\\x1b[0m\\n`);\n console.info(` \\x1b[1mNext step:\\x1b[0m`);\n console.info(\n ` Run it using \\x1b[1m\\x1b[36m${packageManger} run start\\x1b[0m\\n`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(`Build failed: ${err?.message}`);\n console.error(err);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") return \"cjs\";\n else if ([\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType))\n return \"esm\";\n\n sheu.warn(`Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`);\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) fs.mkdirSync(BUILD_DIR, { recursive: true });\n\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n }\n\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n removeDir(BUILD_DIR);\n execSync(`npx tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n configPath: tempTsconfigPath,\n });\n\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(_: BuildOptions, moduleType: ModuleType) {\n const targetDir = path.join(BUILD_DIR);\n\n try {\n if (moduleType === \"esm\") {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n });\n // createModulePackageJson(moduleType);\n } catch (error: any) {\n console.info(error.stack);\n console.error(\"❌ Error building JavaScript project:\", error.stack);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(_: ModuleType, skipExtensions: string[]) {\n const targetDir = path.join(BUILD_DIR);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"arkos.config.js\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n // console.info(`Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}
@@ -24,7 +24,7 @@ function startCommand(options = {}) {
24
24
  const { port, host } = options;
25
25
  const entryPoint = path_1.default.join(process.cwd(), ".build", "src", "app.js");
26
26
  if (!fs_1.default.existsSync(path_1.default.join(entryPoint))) {
27
- sheu_1.default.error(`Could not find built application entry point at ${(0, fs_helpers_1.fullCleanCwd)(entryPoint)}`);
27
+ sheu_1.default.error(`Could not find built application entry point at ${(0, fs_helpers_1.fullCleanCwd)(entryPoint).replaceAll(/^\/+/g, "")}`);
28
28
  process.exit(1);
29
29
  }
30
30
  const env = {
@@ -1 +1 @@
1
- {"version":3,"file":"start.js","sourceRoot":"","sources":["../../../../src/utils/cli/start.ts"],"names":[],"mappings":";;;;;AAmBA,oCA+DC;AAKD,4EA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AE,QAAQ;gBAEb,GAAG,EAAE,IAAI;gBACT,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;QAEzD,GAAG,CAAC,MAAM;YACR,GAAG,EAAE,QAAQ;gBAEb,GAAG,EAAE,IAAI;gBACT,MAAM,CAAC;QAET,2BAAgB,CAAC,KAAK,CAAC;YACrB,QAAQ;YACR,IAAI,EAAE,GAAG,CAAC,MAAM;YAChB,IAAI,EAAE,GAAG,CAAC,MAAM;SACjB,CAAC,CAAC;QAEH,KAAK,GAAG,IAAA,qBAAK,EAAC,MAAM,EAAE,CAAC,UAAU,CAAC,EAAE;YAClC,KAAK,EAAE,SAAS;YAChB,GAAG;YACH,KAAK,EAAE,IAAI;SACZ,CAAC,CAAC;QAEH,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;YACxB,IAAI,KAAK;gBAAE,KAAK,CAAC,IAAI,EAAE,CAAC;YAExB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,cAAI,CAAC,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACjD,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,SAAgB,gCAAgC;IAC7C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { ChildProcess, spawn } from \"child_process\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { fullCleanCwd } from \"../helpers/fs.helpers\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport sheu from \"../sheu\";\n\ninterface StartOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Production start command for the arkos CLI\n */\nexport function startCommand(options: StartOptions = {}) {\n process.env.NO_CLI = \"true\";\n\n if (!process.env.NODE_ENV) process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n envFiles = loadEnvironmentVariables();\n\n try {\n const { port, host } = options;\n\n const entryPoint = path.join(process.cwd(), \".build\", \"src\", \"app.js\");\n\n if (!fs.existsSync(path.join(entryPoint))) {\n sheu.error(\n `Could not find built application entry point at ${fullCleanCwd(entryPoint)}`\n );\n process.exit(1);\n }\n\n const env: { [x: string]: string } = {\n NODE_ENV: \"production\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n ARKOS_BUILD: \"true\",\n CLI: \"false\",\n };\n\n env.__HOST =\n env?.CLI_HOST ||\n // config?.host ||\n env?.HOST ||\n (env.ARKOS_BUILD !== \"true\" ? \"0.0.0.0\" : \"127.0.0.1\");\n\n env.__PORT =\n env?.CLI_PORT ||\n // || config?.port\n env?.PORT ||\n \"8000\";\n\n watermarkStamper.stamp({\n envFiles,\n port: env.__PORT,\n host: env.__HOST,\n });\n\n child = spawn(\"node\", [entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n\n process.on(\"SIGINT\", () => {\n if (child) child.kill();\n\n process.exit(0);\n });\n } catch (error) {\n sheu.error(\"Production server failed to start:\");\n console.error(error);\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the production server child process\n */\nexport function killProductionServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
1
+ {"version":3,"file":"start.js","sourceRoot":"","sources":["../../../../src/utils/cli/start.ts"],"names":[],"mappings":";;;;;AAmBA,oCA+DC;AAKD,4EAGC;AA1FD,gDAAwB;AACxB,4CAAoB;AACpB,iDAAoD;AACpD,sDAA6D;AAC7D,sDAAqD;AACrD,kFAAyD;AACzD,mDAA2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W,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;QAEzD,GAAG,CAAC,MAAM;YACR,GAAG,EAAE,QAAQ;gBAEb,GAAG,EAAE,IAAI;gBACT,MAAM,CAAC;QAET,2BAAgB,CAAC,KAAK,CAAC;YACrB,QAAQ;YACR,IAAI,EAAE,GAAG,CAAC,MAAM;YAChB,IAAI,EAAE,GAAG,CAAC,MAAM;SACjB,CAAC,CAAC;QAEH,KAAK,GAAG,IAAA,qBAAK,EAAC,MAAM,EAAE,CAAC,UAAU,CAAC,EAAE;YAClC,KAAK,EAAE,SAAS;YAChB,GAAG;YACH,KAAK,EAAE,IAAI;SACZ,CAAC,CAAC;QAEH,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;YACxB,IAAI,KAAK;gBAAE,KAAK,CAAC,IAAI,EAAE,CAAC;YAExB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,cAAI,CAAC,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACjD,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,SAAgB,gCAAgC;IAC7C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { ChildProcess, spawn } from \"child_process\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { fullCleanCwd } from \"../helpers/fs.helpers\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport sheu from \"../sheu\";\n\ninterface StartOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Production start command for the arkos CLI\n */\nexport function startCommand(options: StartOptions = {}) {\n process.env.NO_CLI = \"true\";\n\n if (!process.env.NODE_ENV) process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n envFiles = loadEnvironmentVariables();\n\n try {\n const { port, host } = options;\n\n const entryPoint = path.join(process.cwd(), \".build\", \"src\", \"app.js\");\n\n if (!fs.existsSync(path.join(entryPoint))) {\n sheu.error(\n `Could not find built application entry point at ${fullCleanCwd(entryPoint).replaceAll(/^\\/+/g, \"\")}`\n );\n process.exit(1);\n }\n\n const env: { [x: string]: string } = {\n NODE_ENV: \"production\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n ARKOS_BUILD: \"true\",\n CLI: \"false\",\n };\n\n env.__HOST =\n env?.CLI_HOST ||\n // config?.host ||\n env?.HOST ||\n (env.ARKOS_BUILD !== \"true\" ? \"0.0.0.0\" : \"127.0.0.1\");\n\n env.__PORT =\n env?.CLI_PORT ||\n // || config?.port\n env?.PORT ||\n \"8000\";\n\n watermarkStamper.stamp({\n envFiles,\n port: env.__PORT,\n host: env.__HOST,\n });\n\n child = spawn(\"node\", [entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n\n process.on(\"SIGINT\", () => {\n if (child) child.kill();\n\n process.exit(0);\n });\n } catch (error) {\n sheu.error(\"Production server failed to start:\");\n console.error(error);\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the production server child process\n */\nexport function killProductionServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
@@ -19,6 +19,6 @@ function killServerChildProcess() {
19
19
  (0, start_1.killProductionServerChildProcess)();
20
20
  }
21
21
  function getVersion() {
22
- return "2.0.0-next.2";
22
+ return "2.0.0-next.4";
23
23
  }
24
24
  //# sourceMappingURL=cli.helpers.js.map
@@ -97,7 +97,6 @@ export type AuthAction<R extends AuthResource = AuthResource> = Extract<
97
97
  >["action"];
98
98
  `
99
99
  : ""}
100
-
101
100
  export default authActions;
102
101
  `;
103
102
  await promises_1.default.mkdir(path_1.default.dirname(targetPath), { recursive: true });
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-cli-commander.js","sourceRoot":"","sources":["../../../../../src/utils/cli/utils/runtime-cli-commander.ts"],"names":[],"mappings":";;;;;AAAA,wDAA8D;AAC9D,2DAA6B;AAC7B,gDAAwB;AACxB,sDAA8B;AAC9B,yDAA8E;AAC9E,iEAA4D;AAC5D,gCAA2D;AAS3D,MAAM,mBAAmB;IAUvB,UAAU;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,IAAI,CAAC,CAAC;IAC7D,CAAC;IAOD,GAAG;QACD,IAAA,uCAAiC,GAAE,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAYD,KAAK,CAAC,MAAM;QACV,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;QACxC,IAAI,OAAO,KAAK,oBAAoB;YAAE,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;IACtE,CAAC;IAmBD,KAAK,CAAC,gBAAgB;QACpB,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,EAA4C,CAAC;QAC5E,MAAM,WAAW,GAAG,4BAAiB,CAAC,MAAM,EAAE,CAAC;QAC/C,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;QAEnC,MAAM,UAAU,GAAG,cAAI,CAAC,IAAI,CAC1B,OAAO,CAAC,GAAG,EAAE,EACb,OAAO,CAAC,IAAI,IAAI,EAAE,EAClB,gBAAgB,GAAG,EAAE,CACtB,CAAC;QAEF,IAAI,gBAAgB,GAAG,WAAW,CAAC;QACnC,IAAI,QAAQ,GAAG,KAAK,CAAC;QAErB,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC;YACvB,IAAI,CAAC;gBACH,MAAM,cAAc,GAAG,M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AC;oBAED,OAAO,SAAS,CAAC;gBACnB,CAAC,CACF,CAAC;gBAEF,QAAQ,GAAG,IAAI,CAAC;YAClB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC,CAAA,CAAC;QACpB,CAAC;QAED,MAAM,WAAW,GAAG,uBAAuB,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;EAExH,GAAG,KAAK,IAAI;YACV,CAAC,CAAC;;;;;;;;;CASL;YACG,CAAC,CAAC,EACN;;;CAGC,CAAC;QAEE,MAAM,kBAAE,CAAC,KAAK,CAAC,cAAI,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC9D,MAAM,kBAAE,CAAC,SAAS,CAAC,UAAU,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;QAErD,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACjB,IAAI,QAAQ;YACV,cAAI,CAAC,IAAI,CACP,qDAAqD,IAAA,yBAAY,EAAC,UAAU,CAAC,EAAE,CAChF,CAAC;;YAEF,cAAI,CAAC,IAAI,CACP,yCAAyC,IAAA,yBAAY,EAAC,UAAU,CAAC,EAAE,CACpE,CAAC;QAEJ,IAAI,CAAC,GAAG,EAAE,CAAC;IACb,CAAC;CACF;AAOD,MAAM,mBAAmB,GAAwB,IAAI,mBAAmB,EAAE,CAAC;AAE3E,kBAAe,mBAAmB,CAAC","sourcesContent":["import { authActionService } from \"../../../exports/services\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport sheu from \"../../sheu\";\nimport { fullCleanCwd, getUserFileExtension } from \"../../helpers/fs.helpers\";\nimport { importModule } from \"../../helpers/global.helpers\";\nimport { killDevelopmentServerChildProcess } from \"../dev\";\n\n/**\n * Runtime CLI Commander class for handling command-line interface commands\n * during runtime execution. Provides methods for executing various CLI commands\n * and managing their lifecycle.\n *\n * @class RuntimeCliCommander\n */\nclass RuntimeCliCommander {\n /**\n * Parses and returns CLI command options from environment variables\n *\n * @returns {Object} Parsed CLI command options object\n *\n * @example\n * // Returns { overwrite: true, path: './exports' }\n * getOptions();\n */\n getOptions(): { overwrite?: boolean; path: string } {\n return JSON.parse(process.env.CLI_COMMAND_OPTIONS || \"{}\");\n }\n\n /**\n * Terminates the development server child process and exits the current process\n *\n * @returns {void}\n */\n end(): void {\n killDevelopmentServerChildProcess();\n process.exit(1);\n }\n\n /**\n * Main command handler that routes to specific command implementations\n * based on the CLI_COMMAND environment variable\n *\n * @returns {Promise<void>}\n *\n * @example\n * // Handles EXPORT_AUTH_ACTION command\n * await handle();\n */\n async handle(): Promise<void> {\n const command = process.env.CLI_COMMAND;\n if (command === \"EXPORT_AUTH_ACTION\") await this.exportAuthAction();\n }\n\n /**\n * Exports authentication actions to a file, with options for merging with existing\n * actions and specifying output path\n *\n * @param {Object} [options] - Export configuration options\n * @param {boolean} [options.overwrite] - Whether to overwrite existing file (default: false)\n * @param {string} [options.path] - Custom output directory path\n * @returns {Promise<void>}\n *\n * @example\n * // Export with default options (merge if exists)\n * await exportAuthAction();\n *\n * @example\n * // Export with overwrite and custom path\n * await exportAuthAction({ overwrite: true, path: './custom-exports' });\n */\n async exportAuthAction(): Promise<void> {\n const options = this.getOptions() as { overwrite?: boolean; path?: string };\n const authActions = authActionService.getAll();\n const ext = getUserFileExtension();\n\n const targetPath = path.join(\n process.cwd(),\n options.path || \"\",\n `auth-actions.${ext}`\n );\n\n let finalAuthActions = authActions;\n let isUpdate = false;\n\n if (!options.overwrite) {\n try {\n const existingModule = await importModule(targetPath);\n const existingActions = existingModule.default || existingModule;\n\n const rolesChanges: string[] = [];\n\n for (const newAction of authActions) {\n const existingAction = existingActions.find(\n (existing: any) =>\n existing.action === newAction.action &&\n existing.resource === newAction.resource\n );\n\n if (existingAction) {\n const existingRoles = existingAction.roles\n ? [...existingAction.roles].sort()\n : [];\n const newRoles = newAction.roles ? [...newAction.roles].sort() : [];\n\n const rolesMatch =\n existingRoles.length === newRoles.length &&\n existingRoles.every((role, index) => role === newRoles[index]);\n\n if (!rolesMatch) {\n rolesChanges.push(\n ` - ${newAction.action}:${newAction.resource}: [${existingRoles.join(\", \")}] → [${newRoles.join(\", \")}]`\n );\n }\n }\n }\n\n if (rolesChanges.length > 0) {\n const warningMessage = `Roles for the following permissions will be updated:\\n${rolesChanges.join(\"\\n\")}`;\n\n sheu.warn(warningMessage);\n\n const answer = await new Promise<boolean>((resolve) => {\n process.stdout.write(\n `\\n${sheu.green(\"?\", { bold: true })} Do you want to proceed with updating these roles? (Y/n): `\n );\n process.stdin.once(\"data\", (data) => {\n const result = data.toString().trim().toLowerCase();\n process.stdin.pause();\n resolve(result === \"y\" || result.length === 0);\n });\n });\n\n if (!answer) {\n throw new Error(\n `Auth action export cancelled. Roles were not updated to preserve existing permissions., if you would like to overwrite existing auth actions run:\n\nnpx arkos export auth-action --overwrite\n`\n );\n }\n }\n\n finalAuthActions = [...authActions, ...existingActions].map(\n (newAction) => {\n const existingAction = existingActions.find(\n (existing: any) =>\n existing.action === newAction.action &&\n existing.resource === newAction.resource\n );\n\n if (existingAction) {\n return {\n ...newAction,\n ...existingAction,\n roles: newAction.roles,\n };\n }\n\n return newAction;\n }\n );\n\n isUpdate = true;\n } catch (error) {}\n }\n\n const fileContent = `const authActions = ${JSON.stringify(finalAuthActions, null, 2)}${ext === \"ts\" ? \" as const\" : \"\"};\n${\n ext === \"ts\"\n ? `\ntype AuthActionsArray = typeof authActions;\n\nexport type AuthResource = AuthActionsArray[number][\"resource\"];\n\nexport type AuthAction<R extends AuthResource = AuthResource> = Extract<\n AuthActionsArray[number],\n { resource: R }\n>[\"action\"];\n`\n : \"\"\n}\n\nexport default authActions;\n`;\n\n await fs.mkdir(path.dirname(targetPath), { recursive: true });\n await fs.writeFile(targetPath, fileContent, \"utf-8\");\n\n console.info(\"\");\n if (isUpdate)\n sheu.done(\n `Auth actions updated and exported successfully at ${fullCleanCwd(targetPath)}`\n );\n else\n sheu.done(\n `Auth actions exported successfully at ${fullCleanCwd(targetPath)}`\n );\n\n this.end();\n }\n}\n\n/**\n * Singleton instance of RuntimeCliCommander\n *\n * @type {RuntimeCliCommander}\n */\nconst runtimeCliCommander: RuntimeCliCommander = new RuntimeCliCommander();\n\nexport default runtimeCliCommander;\n"]}
1
+ {"version":3,"file":"runtime-cli-commander.js","sourceRoot":"","sources":["../../../../../src/utils/cli/utils/runtime-cli-commander.ts"],"names":[],"mappings":";;;;;AAAA,wDAA8D;AAC9D,2DAA6B;AAC7B,gDAAwB;AACxB,sDAA8B;AAC9B,yDAA8E;AAC9E,iEAA4D;AAC5D,gCAA2D;AAS3D,MAAM,mBAAmB;IAUvB,UAAU;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,IAAI,CAAC,CAAC;IAC7D,CAAC;IAOD,GAAG;QACD,IAAA,uCAAiC,GAAE,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAYD,KAAK,CAAC,MAAM;QACV,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;QACxC,IAAI,OAAO,KAAK,oBAAoB;YAAE,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;IACtE,CAAC;IAmBD,KAAK,CAAC,gBAAgB;QACpB,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,EAA4C,CAAC;QAC5E,MAAM,WAAW,GAAG,4BAAiB,CAAC,MAAM,EAAE,CAAC;QAC/C,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;QAEnC,MAAM,UAAU,GAAG,cAAI,CAAC,IAAI,CAC1B,OAAO,CAAC,GAAG,EAAE,EACb,OAAO,CAAC,IAAI,IAAI,EAAE,EAClB,gBAAgB,GAAG,EAAE,CACtB,CAAC;Q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AC,QAAQ,CAC3C,CAAC;oBAEF,IAAI,cAAc,EAAE,CAAC;wBACnB,OAAO;4BACL,GAAG,SAAS;4BACZ,GAAG,cAAc;4BACjB,KAAK,EAAE,SAAS,CAAC,KAAK;yBACvB,CAAC;oBACJ,CAAC;oBAED,OAAO,SAAS,CAAC;gBACnB,CAAC,CACF,CAAC;gBAEF,QAAQ,GAAG,IAAI,CAAC;YAClB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC,CAAA,CAAC;QACpB,CAAC;QAED,MAAM,WAAW,GAAG,uBAAuB,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;EAExH,GAAG,KAAK,IAAI;YACV,CAAC,CAAC;;;;;;;;;CASL;YACG,CAAC,CAAC,EACN;;CAEC,CAAC;QAEE,MAAM,kBAAE,CAAC,KAAK,CAAC,cAAI,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC9D,MAAM,kBAAE,CAAC,SAAS,CAAC,UAAU,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;QAErD,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACjB,IAAI,QAAQ;YACV,cAAI,CAAC,IAAI,CACP,qDAAqD,IAAA,yBAAY,EAAC,UAAU,CAAC,EAAE,CAChF,CAAC;;YAEF,cAAI,CAAC,IAAI,CACP,yCAAyC,IAAA,yBAAY,EAAC,UAAU,CAAC,EAAE,CACpE,CAAC;QAEJ,IAAI,CAAC,GAAG,EAAE,CAAC;IACb,CAAC;CACF;AAOD,MAAM,mBAAmB,GAAwB,IAAI,mBAAmB,EAAE,CAAC;AAE3E,kBAAe,mBAAmB,CAAC","sourcesContent":["import { authActionService } from \"../../../exports/services\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport sheu from \"../../sheu\";\nimport { fullCleanCwd, getUserFileExtension } from \"../../helpers/fs.helpers\";\nimport { importModule } from \"../../helpers/global.helpers\";\nimport { killDevelopmentServerChildProcess } from \"../dev\";\n\n/**\n * Runtime CLI Commander class for handling command-line interface commands\n * during runtime execution. Provides methods for executing various CLI commands\n * and managing their lifecycle.\n *\n * @class RuntimeCliCommander\n */\nclass RuntimeCliCommander {\n /**\n * Parses and returns CLI command options from environment variables\n *\n * @returns {Object} Parsed CLI command options object\n *\n * @example\n * // Returns { overwrite: true, path: './exports' }\n * getOptions();\n */\n getOptions(): { overwrite?: boolean; path: string } {\n return JSON.parse(process.env.CLI_COMMAND_OPTIONS || \"{}\");\n }\n\n /**\n * Terminates the development server child process and exits the current process\n *\n * @returns {void}\n */\n end(): void {\n killDevelopmentServerChildProcess();\n process.exit(1);\n }\n\n /**\n * Main command handler that routes to specific command implementations\n * based on the CLI_COMMAND environment variable\n *\n * @returns {Promise<void>}\n *\n * @example\n * // Handles EXPORT_AUTH_ACTION command\n * await handle();\n */\n async handle(): Promise<void> {\n const command = process.env.CLI_COMMAND;\n if (command === \"EXPORT_AUTH_ACTION\") await this.exportAuthAction();\n }\n\n /**\n * Exports authentication actions to a file, with options for merging with existing\n * actions and specifying output path\n *\n * @param {Object} [options] - Export configuration options\n * @param {boolean} [options.overwrite] - Whether to overwrite existing file (default: false)\n * @param {string} [options.path] - Custom output directory path\n * @returns {Promise<void>}\n *\n * @example\n * // Export with default options (merge if exists)\n * await exportAuthAction();\n *\n * @example\n * // Export with overwrite and custom path\n * await exportAuthAction({ overwrite: true, path: './custom-exports' });\n */\n async exportAuthAction(): Promise<void> {\n const options = this.getOptions() as { overwrite?: boolean; path?: string };\n const authActions = authActionService.getAll();\n const ext = getUserFileExtension();\n\n const targetPath = path.join(\n process.cwd(),\n options.path || \"\",\n `auth-actions.${ext}`\n );\n\n let finalAuthActions = authActions;\n let isUpdate = false;\n\n if (!options.overwrite) {\n try {\n const existingModule = await importModule(targetPath);\n const existingActions = existingModule.default || existingModule;\n\n const rolesChanges: string[] = [];\n\n for (const newAction of authActions) {\n const existingAction = existingActions.find(\n (existing: any) =>\n existing.action === newAction.action &&\n existing.resource === newAction.resource\n );\n\n if (existingAction) {\n const existingRoles = existingAction.roles\n ? [...existingAction.roles].sort()\n : [];\n const newRoles = newAction.roles ? [...newAction.roles].sort() : [];\n\n const rolesMatch =\n existingRoles.length === newRoles.length &&\n existingRoles.every((role, index) => role === newRoles[index]);\n\n if (!rolesMatch) {\n rolesChanges.push(\n ` - ${newAction.action}:${newAction.resource}: [${existingRoles.join(\", \")}] → [${newRoles.join(\", \")}]`\n );\n }\n }\n }\n\n if (rolesChanges.length > 0) {\n const warningMessage = `Roles for the following permissions will be updated:\\n${rolesChanges.join(\"\\n\")}`;\n\n sheu.warn(warningMessage);\n\n const answer = await new Promise<boolean>((resolve) => {\n process.stdout.write(\n `\\n${sheu.green(\"?\", { bold: true })} Do you want to proceed with updating these roles? (Y/n): `\n );\n process.stdin.once(\"data\", (data) => {\n const result = data.toString().trim().toLowerCase();\n process.stdin.pause();\n resolve(result === \"y\" || result.length === 0);\n });\n });\n\n if (!answer) {\n throw new Error(\n `Auth action export cancelled. Roles were not updated to preserve existing permissions., if you would like to overwrite existing auth actions run:\n\nnpx arkos export auth-action --overwrite\n`\n );\n }\n }\n\n finalAuthActions = [...authActions, ...existingActions].map(\n (newAction) => {\n const existingAction = existingActions.find(\n (existing: any) =>\n existing.action === newAction.action &&\n existing.resource === newAction.resource\n );\n\n if (existingAction) {\n return {\n ...newAction,\n ...existingAction,\n roles: newAction.roles,\n };\n }\n\n return newAction;\n }\n );\n\n isUpdate = true;\n } catch (error) {}\n }\n\n const fileContent = `const authActions = ${JSON.stringify(finalAuthActions, null, 2)}${ext === \"ts\" ? \" as const\" : \"\"};\n${\n ext === \"ts\"\n ? `\ntype AuthActionsArray = typeof authActions;\n\nexport type AuthResource = AuthActionsArray[number][\"resource\"];\n\nexport type AuthAction<R extends AuthResource = AuthResource> = Extract<\n AuthActionsArray[number],\n { resource: R }\n>[\"action\"];\n`\n : \"\"\n}\nexport default authActions;\n`;\n\n await fs.mkdir(path.dirname(targetPath), { recursive: true });\n await fs.writeFile(targetPath, fileContent, \"utf-8\");\n\n console.info(\"\");\n if (isUpdate)\n sheu.done(\n `Auth actions updated and exported successfully at ${fullCleanCwd(targetPath)}`\n );\n else\n sheu.done(\n `Auth actions exported successfully at ${fullCleanCwd(targetPath)}`\n );\n\n this.end();\n }\n}\n\n/**\n * Singleton instance of RuntimeCliCommander\n *\n * @type {RuntimeCliCommander}\n */\nconst runtimeCliCommander: RuntimeCliCommander = new RuntimeCliCommander();\n\nexport default runtimeCliCommander;\n"]}
@@ -18,7 +18,7 @@ function fullCleanCwd(path) {
18
18
  if (path.startsWith(`/${process.cwd()}`) ||
19
19
  path.startsWith(`${process.cwd()}`) ||
20
20
  path.startsWith(`${process.cwd()}/`))
21
- return path.replaceAll(process.cwd(), "").replaceAll(/^\/+/g, "");
21
+ return path.replaceAll(process.cwd(), "");
22
22
  else
23
23
  return path;
24
24
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fs.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/fs.helpers.ts"],"names":[],"mappings":";;;;;;AAcA,oCAUC;AAiDD,0CAMC;AA/ED,4CAAoB;AACpB,gDAAwB;AAEjB,MAAM,GAAG,GAAG,GAAG,EAAE,CACtB,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;IAChC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,UAAU;IAC5B,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;AAHP,QAAA,GAAG,OAGI;AAQpB,SAAgB,YAAY,CAAC,IAAY;IACvC,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAEvE,IACE,IAAI,CAAC,UAAU,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,EAAE,C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,EAAE,CAAC;QACX,yBAAiB,GAAG,IAAI,CAAC;QACzB,OAAO,yBAAiB,CAAC;IAC3B,CAAC;AACH,CAAC,CAAC;AAxBW,QAAA,oBAAoB,wBAwB/B;AAgBF,SAAgB,eAAe,CAAC,QAAgB;IAC9C,IAAI,CAAC;QACH,OAAO,YAAE,CAAC,UAAU,CAAC,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC/C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\n\nexport const crd = () =>\n process.env.ARKOS_BUILD === \"true\"\n ? process.cwd() + \"/.build/\"\n : process.cwd();\n\n/**\n * Removes the current working directory prefix from the given path.\n * Handles cases with or without a trailing slash in cwd.\n * @param path - The path to clean\n * @returns The path without the cwd prefix\n */\nexport function fullCleanCwd(path: string): string {\n if (typeof path !== \"string\") throw new Error(\"Path must be a string\");\n\n if (\n path.startsWith(`/${process.cwd()}`) ||\n path.startsWith(`${process.cwd()}`) ||\n path.startsWith(`${process.cwd()}/`)\n )\n return path.replaceAll(process.cwd(), \"\").replaceAll(/^\\/+/g, \"\");\n else return path;\n}\n\nexport let userFileExtension: \"ts\" | \"js\" | undefined;\n\n/**\n * Detects the file extension that should be used in the current execution context\n * Returns 'ts' when TypeScript config exists and not in build mode, otherwise 'js'\n * @returns 'ts' | 'js'\n */\nexport const getUserFileExtension = (): \"ts\" | \"js\" => {\n if (userFileExtension) return userFileExtension;\n\n try {\n const currentDir = process.cwd();\n\n const hasTsConfig = fs.existsSync(path.join(currentDir, \"tsconfig.json\"));\n\n const hasAppTs = fs.existsSync(path.join(currentDir, \"src\", \"app.ts\"));\n const hasAppJs = fs.existsSync(path.join(currentDir, \"src\", \"app.js\"));\n\n const isBuildMode = process.env.ARKOS_BUILD === \"true\";\n\n if (isBuildMode) userFileExtension = \"js\";\n else if (hasTsConfig && hasAppTs) userFileExtension = \"ts\";\n else if (hasAppTs && !hasAppJs) userFileExtension = \"ts\";\n else if (hasAppJs) userFileExtension = \"js\";\n else userFileExtension = \"js\";\n\n return userFileExtension;\n } catch (e) {\n userFileExtension = \"js\";\n return userFileExtension;\n }\n};\n\n/**\n * Checks if a file exists at the specified file path.\n *\n * @param filePath - The path to the file to check\n * @returns {boolean} True if the file exists, false otherwise or if there's an error\n *\n * @example\n * ```ts\n * const exists = checkFileExists('./path/to/file.txt');\n * if (exists) {\n * console.info('File exists!');\n * }\n * ```\n */\nexport function checkFileExists(filePath: string): boolean {\n try {\n return fs.existsSync(path.resolve(filePath));\n } catch (error) {\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"fs.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/fs.helpers.ts"],"names":[],"mappings":";;;;;;AAcA,oCAUC;AAiDD,0CAMC;AA/ED,4CAAoB;AACpB,gDAAwB;AAEjB,MAAM,GAAG,GAAG,GAAG,EAAE,CACtB,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;IAChC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,UAAU;IAC5B,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;AAHP,QAAA,GAAG,OAGI;AAQpB,SAAgB,YAAY,CAAC,IAAY;IACvC,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAEvE,IACE,IAAI,CAAC,UAAU,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC;QACpC,IAAI,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC;QAEpC,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC;;QACvC,OAAO,IA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,KAAK,EAAE,CAAC;QACf,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\n\nexport const crd = () =>\n process.env.ARKOS_BUILD === \"true\"\n ? process.cwd() + \"/.build/\"\n : process.cwd();\n\n/**\n * Removes the current working directory prefix from the given path.\n * Handles cases with or without a trailing slash in cwd.\n * @param path - The path to clean\n * @returns The path without the cwd prefix\n */\nexport function fullCleanCwd(path: string): string {\n if (typeof path !== \"string\") throw new Error(\"Path must be a string\");\n\n if (\n path.startsWith(`/${process.cwd()}`) ||\n path.startsWith(`${process.cwd()}`) ||\n path.startsWith(`${process.cwd()}/`)\n )\n return path.replaceAll(process.cwd(), \"\");\n else return path;\n}\n\nexport let userFileExtension: \"ts\" | \"js\" | undefined;\n\n/**\n * Detects the file extension that should be used in the current execution context\n * Returns 'ts' when TypeScript config exists and not in build mode, otherwise 'js'\n * @returns 'ts' | 'js'\n */\nexport const getUserFileExtension = (): \"ts\" | \"js\" => {\n if (userFileExtension) return userFileExtension;\n\n try {\n const currentDir = process.cwd();\n\n const hasTsConfig = fs.existsSync(path.join(currentDir, \"tsconfig.json\"));\n\n const hasAppTs = fs.existsSync(path.join(currentDir, \"src\", \"app.ts\"));\n const hasAppJs = fs.existsSync(path.join(currentDir, \"src\", \"app.js\"));\n\n const isBuildMode = process.env.ARKOS_BUILD === \"true\";\n\n if (isBuildMode) userFileExtension = \"js\";\n else if (hasTsConfig && hasAppTs) userFileExtension = \"ts\";\n else if (hasAppTs && !hasAppJs) userFileExtension = \"ts\";\n else if (hasAppJs) userFileExtension = \"js\";\n else userFileExtension = \"js\";\n\n return userFileExtension;\n } catch (e) {\n userFileExtension = \"js\";\n return userFileExtension;\n }\n};\n\n/**\n * Checks if a file exists at the specified file path.\n *\n * @param filePath - The path to the file to check\n * @returns {boolean} True if the file exists, false otherwise or if there's an error\n *\n * @example\n * ```ts\n * const exists = checkFileExists('./path/to/file.txt');\n * if (exists) {\n * console.info('File exists!');\n * }\n * ```\n */\nexport function checkFileExists(filePath: string): boolean {\n try {\n return fs.existsSync(path.resolve(filePath));\n } catch (error) {\n return false;\n }\n}\n"]}
@@ -13,7 +13,9 @@ function buildPolicy(resource, store) {
13
13
  action,
14
14
  rule: config,
15
15
  };
16
- const checker = (user) => authService.permission(action, resource, { [action]: config || {} })(user);
16
+ const checker = authService.permission(action, resource, {
17
+ [action]: config || {},
18
+ });
17
19
  const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;
18
20
  return [
19
21
  [action, authEntry],
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/components/arkos-policy/index.ts"],"names":[],"mappings":"AAQA,OAAO,WAAW,MAAM,iCAAiC,CAAC;AA+B1D,MAAM,UAAU,WAAW,CACzB,QAAmB;IAEnB,OAAO,WAAW,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,WAAW,CAClB,QAAmB,EACnB,KAAsC;IAEtC,MAAM,IAAI,GAAG,CACX,MAAe,EACf,MAAuB,EAC2B,EAAE;QACpD,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAChD,OAAO,WAAW,CAAgC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACxE,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CACtC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,EAAE;QACjD,MAAM,SAAS,GAA8C;YAC3D,QAAQ;YACR,MAAM;YACN,IAAI,EAAE,MAAM;SACb,CAAC;QAEF,MAAM,OAAO,GAAkB,CAAC,IAAW,EAAoB,EAAE,CAC/D,WAAW,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,IAAI,EAAE,EAAE,CAAC,CAClE,IAAI,CACL,CAAC;QAEJ,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QAExE,OAAO;YACL,CAAC,MAAM,EAAE,SAAS,CAAC;YACnB,CAAC,MAAM,EAAE,OAAO,CAAC;SAClB,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;IAEF,OAAO;QACL,MAAM,EAAE,aAAsB;QAC9B,QAAQ;QACR,IAAI;QACJ,GAAG,aAAa;KACoC,CAAC;AACzD,CAAC","sourcesContent":["import { User } from \"../../types\";\nimport {\n ArkosPolicyRule,\n IArkosPolicy,\n PolicyAuthEntry,\n PolicyChecker,\n PolicyWithActions,\n} from \"./types\";\nimport authService from \"../../modules/auth/auth.service\";\n\n/**\n * Creates a typed policy for a Prisma model resource.\n *\n * Each `.rule()` call registers an action and returns the policy\n * with a typed `can{Action}` permission checker and a typed `{Action}`\n * entry — both passable to the `authentication` field on `ArkosRouteHook`\n * and `ArkosRouter`, and callable for fine-grained permission checks.\n *\n * @param resource - The resource name in kebab-case (e.g. `\"user\"`, `\"blog-post\"`)\n *\n * @example\n * ```ts\n * const userPolicy = ArkosPolicy(\"user\")\n * .rule(\"Create\", [\"Admin\", \"Editor\"])\n * .rule(\"View\", \"*\")\n * .rule(\"Delete\", [\"Admin\"]);\n *\n * // Pass to authentication field\n * userRouter.post({ path: \"/users\", authentication: userPolicy.Create });\n * userRouteHook.deleteOne({ authentication: userPolicy.Delete });\n *\n * // Fine-grained check\n * if (userPolicy.canCreate(req.user)) { ... }\n *\n * export default userPolicy;\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-referency/arkos-policy}\n */\nexport function ArkosPolicy<TResource extends string>(\n resource: TResource\n): IArkosPolicy<TResource, never> {\n return buildPolicy(resource, {});\n}\n\nfunction buildPolicy<TResource extends string, TActions extends string>(\n resource: TResource,\n store: Record<string, ArkosPolicyRule>\n): PolicyWithActions<TResource, TActions> {\n const rule = <TAction extends string>(\n action: TAction,\n config: ArkosPolicyRule\n ): PolicyWithActions<TResource, TActions | TAction> => {\n const newStore = { ...store, [action]: config };\n return buildPolicy<TResource, TActions | TAction>(resource, newStore);\n };\n\n const actionEntries = Object.fromEntries(\n Object.entries(store).flatMap(([action, config]) => {\n const authEntry: PolicyAuthEntry<TResource, typeof action> = {\n resource,\n action,\n rule: config,\n };\n\n const checker: PolicyChecker = (user?: User): Promise<boolean> =>\n authService.permission(action, resource, { [action]: config || {} })(\n user\n );\n\n const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;\n\n return [\n [action, authEntry],\n [canKey, checker],\n ];\n })\n );\n\n return {\n __type: \"ArkosPolicy\" as const,\n resource,\n rule,\n ...actionEntries,\n } as unknown as PolicyWithActions<TResource, TActions>;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/components/arkos-policy/index.ts"],"names":[],"mappings":"AAQA,OAAO,WAAW,MAAM,iCAAiC,CAAC;AA+B1D,MAAM,UAAU,WAAW,CACzB,QAAmB;IAEnB,OAAO,WAAW,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,WAAW,CAClB,QAAmB,EACnB,KAAsC;IAEtC,MAAM,IAAI,GAAG,CACX,MAAe,EACf,MAAuB,EAC2B,EAAE;QACpD,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAChD,OAAO,WAAW,CAAgC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACxE,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CACtC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,EAAE;QACjD,MAAM,SAAS,GAA8C;YAC3D,QAAQ;YACR,MAAM;YACN,IAAI,EAAE,MAAM;SACb,CAAC;QAEF,MAAM,OAAO,GAAkB,WAAW,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,EAAE;YACtE,CAAC,MAAM,CAAC,EAAE,MAAM,IAAI,EAAE;SACvB,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QAExE,OAAO;YACL,CAAC,MAAM,EAAE,SAAS,CAAC;YACnB,CAAC,MAAM,EAAE,OAAO,CAAC;SAClB,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;IAEF,OAAO;QACL,MAAM,EAAE,aAAsB;QAC9B,QAAQ;QACR,IAAI;QACJ,GAAG,aAAa;KACoC,CAAC;AACzD,CAAC","sourcesContent":["import { User } from \"../../types\";\nimport {\n ArkosPolicyRule,\n IArkosPolicy,\n PolicyAuthEntry,\n PolicyChecker,\n PolicyWithActions,\n} from \"./types\";\nimport authService from \"../../modules/auth/auth.service\";\n\n/**\n * Creates a typed policy for a Prisma model resource.\n *\n * Each `.rule()` call registers an action and returns the policy\n * with a typed `can{Action}` permission checker and a typed `{Action}`\n * entry — both passable to the `authentication` field on `ArkosRouteHook`\n * and `ArkosRouter`, and callable for fine-grained permission checks.\n *\n * @param resource - The resource name in kebab-case (e.g. `\"user\"`, `\"blog-post\"`)\n *\n * @example\n * ```ts\n * const userPolicy = ArkosPolicy(\"user\")\n * .rule(\"Create\", [\"Admin\", \"Editor\"])\n * .rule(\"View\", \"*\")\n * .rule(\"Delete\", [\"Admin\"]);\n *\n * // Pass to authentication field\n * userRouter.post({ path: \"/users\", authentication: userPolicy.Create });\n * userRouteHook.deleteOne({ authentication: userPolicy.Delete });\n *\n * // Fine-grained check\n * if (userPolicy.canCreate(req.user)) { ... }\n *\n * export default userPolicy;\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-referency/arkos-policy}\n */\nexport function ArkosPolicy<TResource extends string>(\n resource: TResource\n): IArkosPolicy<TResource, never> {\n return buildPolicy(resource, {});\n}\n\nfunction buildPolicy<TResource extends string, TActions extends string>(\n resource: TResource,\n store: Record<string, ArkosPolicyRule>\n): PolicyWithActions<TResource, TActions> {\n const rule = <TAction extends string>(\n action: TAction,\n config: ArkosPolicyRule\n ): PolicyWithActions<TResource, TActions | TAction> => {\n const newStore = { ...store, [action]: config };\n return buildPolicy<TResource, TActions | TAction>(resource, newStore);\n };\n\n const actionEntries = Object.fromEntries(\n Object.entries(store).flatMap(([action, config]) => {\n const authEntry: PolicyAuthEntry<TResource, typeof action> = {\n resource,\n action,\n rule: config,\n };\n\n const checker: PolicyChecker = authService.permission(action, resource, {\n [action]: config || {},\n });\n\n const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;\n\n return [\n [action, authEntry],\n [canKey, checker],\n ];\n })\n );\n\n return {\n __type: \"ArkosPolicy\" as const,\n resource,\n rule,\n ...actionEntries,\n } as unknown as PolicyWithActions<TResource, TActions>;\n}\n"]}
@@ -18,7 +18,7 @@ export class FileUploadController {
18
18
  const { documentUploadService, fileUploadService, imageUploadService, videoUploadService, } = getFileUploadServices();
19
19
  const { fileUpload } = getArkosConfig();
20
20
  const baseUploadDir = fileUpload?.baseUploadDir || "/uploads";
21
- const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);
21
+ const uploadPath = path.resolve(path.join(process.cwd(), baseUploadDir, fileType));
22
22
  try {
23
23
  await fs.promises.access(uploadPath);
24
24
  }
@@ -138,7 +138,7 @@ export class FileUploadController {
138
138
  const { documentUploadService, fileUploadService, imageUploadService, videoUploadService, } = getFileUploadServices();
139
139
  const { fileUpload } = getArkosConfig();
140
140
  const baseUploadDir = fileUpload?.baseUploadDir || "/uploads";
141
- const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);
141
+ const uploadPath = path.resolve(path.join(process.cwd(), baseUploadDir, fileType));
142
142
  try {
143
143
  await fs.promises.access(uploadPath);
144
144
  }
@@ -1 +1 @@
1
- {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAEL,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAEhF,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,gBAAgB,MAAM,0CAA0C,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAK3E,MAAM,OAAO,oBAAoB;IAAjC;QAgCE,eAAU,GAAG,UAAU,CACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;YAChC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;YACtD,MAAM,OAAO,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;YAEpD,MAAM,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,GAAG,qBAAqB,EAAE,CAAC;YAE5B,MAAM,EAAE,UAAU,EAAE,GAAG,cAAc,EAAE,CAAC;YACxC,MAAM,aAAa,GAAG,UAAU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E,CAAC;IAEO,YAAY,CAAC,SAAiB;QACpC,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QACjC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,OAAO,CACL,eAAe,CAAC,QAAQ,CAAC,aAAa,EAAE,SAAgB,CAAC,EAAE,KAAK,IAAI,IAAI,CACzE,CAAC;IACJ,CAAC;CA+SF;AAOD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,eAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { MulterError } from \"multer\";\nimport { pascalCase } from \"../../exports/utils\";\nimport loadableRegistry from \"../../components/arkos-loadable-registry\";\nimport { routeHookReader } from \"../../components/arkos-route-hook/reader\";\n\n/**\n * Handles file uploads and allows to be extended via route hooks.\n */\nexport class FileUploadController {\n private handleUploadError(err: any, next: ArkosNextFunction) {\n if (err instanceof MulterError)\n return next(\n new AppError(\n err.message,\n 400,\n pascalCase(err.code || \"FileUploadError\")\n )\n );\n else return next(err);\n }\n\n private getRouteHook() {\n return loadableRegistry.getItem(\"ArkosRouteHook\", \"file-upload\");\n }\n\n private getAfterHook(operation: string) {\n const hook = this.getRouteHook();\n if (!hook) return null;\n return (\n routeHookReader.getHooks(\"file-upload\", operation as any)?.after ?? null\n );\n }\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = req.files.map((file) => processFile(req, file.path));\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n const afterHook = this.getAfterHook(\"uploadFile\");\n if (afterHook) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n const afterHook = this.getAfterHook(\"deleteFile\");\n if (afterHook) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = req.files.map((file) => processFile(req, file.path));\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n const afterHook = this.getAfterHook(\"updateFile\");\n if (afterHook) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
1
+ {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAEL,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAEhF,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,gBAAgB,MAAM,0CAA0C,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAK3E,MAAM,OAAO,oBAAoB;IAAjC;QAgCE,eAAU,GAAG,UAAU,CACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,EAAE,QAAQ,EAAE,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AAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IACJ,CAAC;IAzUS,iBAAiB,CAAC,GAAQ,EAAE,IAAuB;QACzD,IAAI,GAAG,YAAY,WAAW;YAC5B,OAAO,IAAI,CACT,IAAI,QAAQ,CACV,GAAG,CAAC,OAAO,EACX,GAAG,EACH,UAAU,CAAC,GAAG,CAAC,IAAI,IAAI,iBAAiB,CAAC,CAC1C,CACF,CAAC;;YACC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;IAEO,YAAY;QAClB,OAAO,gBAAgB,CAAC,OAAO,CAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC;IACnE,CAAC;IAEO,YAAY,CAAC,SAAiB;QACpC,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QACjC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,OAAO,CACL,eAAe,CAAC,QAAQ,CAAC,aAAa,EAAE,SAAgB,CAAC,EAAE,KAAK,IAAI,IAAI,CACzE,CAAC;IACJ,CAAC;CAmTF;AAOD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,eAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { MulterError } from \"multer\";\nimport { pascalCase } from \"../../exports/utils\";\nimport loadableRegistry from \"../../components/arkos-loadable-registry\";\nimport { routeHookReader } from \"../../components/arkos-route-hook/reader\";\n\n/**\n * Handles file uploads and allows to be extended via route hooks.\n */\nexport class FileUploadController {\n private handleUploadError(err: any, next: ArkosNextFunction) {\n if (err instanceof MulterError)\n return next(\n new AppError(\n err.message,\n 400,\n pascalCase(err.code || \"FileUploadError\")\n )\n );\n else return next(err);\n }\n\n private getRouteHook() {\n return loadableRegistry.getItem(\"ArkosRouteHook\", \"file-upload\");\n }\n\n private getAfterHook(operation: string) {\n const hook = this.getRouteHook();\n if (!hook) return null;\n return (\n routeHookReader.getHooks(\"file-upload\", operation as any)?.after ?? null\n );\n }\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = req.files.map((file) => processFile(req, file.path));\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n const afterHook = this.getAfterHook(\"uploadFile\");\n if (afterHook) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n const afterHook = this.getAfterHook(\"deleteFile\");\n if (afterHook) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one.\n *\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = req.files.map((file) => processFile(req, file.path));\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n const afterHook = this.getAfterHook(\"updateFile\");\n if (afterHook) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bundler.js","sourceRoot":"","sources":["../../../src/utils/bundler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AA8DxB,MAAM,OAAO,OAAO;IAiBV,cAAc,CAAC,aAA4B;QACjD,OAAO,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,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UAAU,EACV,OAAO,EACP,GAAG,EACH,aAAa,EACb,eAAe,CAChB,CAAC;gBACF,IAAI,OAAO,KAAK,OAAO;oBAAE,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC;IACH,CAAC;;AApWuB,sBAAc,GAAG;IACvC,0BAA0B;IAC1B,4BAA4B;IAC5B,sCAAsC;IACtC,uCAAuC;CACxC,CAAC;AAkWJ,MAAM,CAAC,MAAM,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\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,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AA8DxB,MAAM,OAAO,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,CA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EAAE,OAAO,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC;IACH,CAAC;;AAnWuB,sBAAc,GAAG;IACvC,0BAA0B;IAC1B,4BAA4B;IAC5B,sCAAsC;IACtC,uCAAuC;CACxC,CAAC;AAiWJ,MAAM,CAAC,MAAM,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"]}
@@ -134,7 +134,8 @@ function buildJavaScriptProject(_, moduleType) {
134
134
  });
135
135
  }
136
136
  catch (error) {
137
- console.error("❌ Error building JavaScript project:", error);
137
+ console.info(error.stack);
138
+ console.error("❌ Error building JavaScript project:", error.stack);
138
139
  throw error;
139
140
  }
140
141
  }
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,i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C,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport { removeDir } from \"../remove-dir\";\nimport { bundler } from \"../bundler\";\n\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n process.env.NO_CLI = \"true\";\n const fileExt = getUserFileExtension();\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n watermarkStamper.stamp({\n envFiles,\n });\n\n console.info(`\\n Creating an optimized production build...`);\n\n ensureBuildDir();\n\n if (fileExt === \"ts\") buildTypeScriptProject(options, moduleType);\n else buildJavaScriptProject(options, moduleType);\n\n const packageManger = detectPackageManagerFromUserAgent();\n\n console.info(`\\n\\x1b[1m\\x1b[32m Build complete!\\x1b[0m\\n`);\n console.info(` \\x1b[1mNext step:\\x1b[0m`);\n console.info(\n ` Run it using \\x1b[1m\\x1b[36m${packageManger} run start\\x1b[0m\\n`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(`Build failed: ${err?.message}`);\n console.error(err);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") return \"cjs\";\n else if ([\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType))\n return \"esm\";\n\n sheu.warn(`Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`);\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) fs.mkdirSync(BUILD_DIR, { recursive: true });\n\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n }\n\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n removeDir(BUILD_DIR);\n execSync(`npx tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n configPath: tempTsconfigPath,\n });\n\n // Clean up temp config\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(_: BuildOptions, moduleType: ModuleType) {\n const targetDir = path.join(BUILD_DIR);\n\n try {\n if (moduleType === \"esm\") {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n });\n // createModulePackageJson(moduleType);\n } catch (error) {\n console.error(\"❌ Error building JavaScript project:\", error);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(_: ModuleType, skipExtensions: string[]) {\n const targetDir = path.join(BUILD_DIR);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"arkos.config.js\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n // console.info(`Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}
1
+ {"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,2BAA2B,CAAC;AAC9E,OAAO,IAAI,MAAM,SAAS,CAAC;AAC3B,OAAO,gBAAgB,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,MAAM,SAAS,GAA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"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { detectPackageManagerFromUserAgent } from \"../helpers/global.helpers\";\nimport sheu from \"../sheu\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport { removeDir } from \"../remove-dir\";\nimport { bundler } from \"../bundler\";\n\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n process.env.NO_CLI = \"true\";\n const fileExt = getUserFileExtension();\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n watermarkStamper.stamp({\n envFiles,\n });\n\n console.info(`\\n Creating an optimized production build...`);\n\n ensureBuildDir();\n\n if (fileExt === \"ts\") buildTypeScriptProject(options, moduleType);\n else buildJavaScriptProject(options, moduleType);\n\n const packageManger = detectPackageManagerFromUserAgent();\n\n console.info(`\\n\\x1b[1m\\x1b[32m Build complete!\\x1b[0m\\n`);\n console.info(` \\x1b[1mNext step:\\x1b[0m`);\n console.info(\n ` Run it using \\x1b[1m\\x1b[36m${packageManger} run start\\x1b[0m\\n`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(`Build failed: ${err?.message}`);\n console.error(err);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") return \"cjs\";\n else if ([\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType))\n return \"esm\";\n\n sheu.warn(`Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`);\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) fs.mkdirSync(BUILD_DIR, { recursive: true });\n\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n }\n\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n removeDir(BUILD_DIR);\n execSync(`npx tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n configPath: tempTsconfigPath,\n });\n\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(_: BuildOptions, moduleType: ModuleType) {\n const targetDir = path.join(BUILD_DIR);\n\n try {\n if (moduleType === \"esm\") {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n bundler.bundle({\n ext: \".js\",\n outDir: path.join(process.cwd(), BUILD_DIR),\n rootDir: process.cwd(),\n });\n // createModulePackageJson(moduleType);\n } catch (error: any) {\n console.info(error.stack);\n console.error(\"❌ Error building JavaScript project:\", error.stack);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(_: ModuleType, skipExtensions: string[]) {\n const targetDir = path.join(BUILD_DIR);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"arkos.config.js\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n // console.info(`Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}
@@ -17,7 +17,7 @@ export function startCommand(options = {}) {
17
17
  const { port, host } = options;
18
18
  const entryPoint = path.join(process.cwd(), ".build", "src", "app.js");
19
19
  if (!fs.existsSync(path.join(entryPoint))) {
20
- sheu.error(`Could not find built application entry point at ${fullCleanCwd(entryPoint)}`);
20
+ sheu.error(`Could not find built application entry point at ${fullCleanCwd(entryPoint).replaceAll(/^\/+/g, "")}`);
21
21
  process.exit(1);
22
22
  }
23
23
  const env = {
@@ -1 +1 @@
1
- {"version":3,"file":"start.js","sourceRoot":"","sources":["../../../../src/utils/cli/start.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAgB,KAAK,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,gBAAgB,MAAM,2BAA2B,CAAC;AACzD,OAAO,IAAI,MAAM,SAAS,CAAC;AAO3B,IAAI,KAAK,GAAwB,IA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,GAAG,CAAC,MAAM;YACR,GAAG,EAAE,QAAQ;gBAEb,GAAG,EAAE,IAAI;gBACT,MAAM,CAAC;QAET,gBAAgB,CAAC,KAAK,CAAC;YACrB,QAAQ;YACR,IAAI,EAAE,GAAG,CAAC,MAAM;YAChB,IAAI,EAAE,GAAG,CAAC,MAAM;SACjB,CAAC,CAAC;QAEH,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,UAAU,CAAC,EAAE;YAClC,KAAK,EAAE,SAAS;YAChB,GAAG;YACH,KAAK,EAAE,IAAI;SACZ,CAAC,CAAC;QAEH,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;YACxB,IAAI,KAAK;gBAAE,KAAK,CAAC,IAAI,EAAE,CAAC;YAExB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACjD,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,MAAM,UAAU,gCAAgC;IAC7C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { ChildProcess, spawn } from \"child_process\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { fullCleanCwd } from \"../helpers/fs.helpers\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport sheu from \"../sheu\";\n\ninterface StartOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Production start command for the arkos CLI\n */\nexport function startCommand(options: StartOptions = {}) {\n process.env.NO_CLI = \"true\";\n\n if (!process.env.NODE_ENV) process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n envFiles = loadEnvironmentVariables();\n\n try {\n const { port, host } = options;\n\n const entryPoint = path.join(process.cwd(), \".build\", \"src\", \"app.js\");\n\n if (!fs.existsSync(path.join(entryPoint))) {\n sheu.error(\n `Could not find built application entry point at ${fullCleanCwd(entryPoint)}`\n );\n process.exit(1);\n }\n\n const env: { [x: string]: string } = {\n NODE_ENV: \"production\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n ARKOS_BUILD: \"true\",\n CLI: \"false\",\n };\n\n env.__HOST =\n env?.CLI_HOST ||\n // config?.host ||\n env?.HOST ||\n (env.ARKOS_BUILD !== \"true\" ? \"0.0.0.0\" : \"127.0.0.1\");\n\n env.__PORT =\n env?.CLI_PORT ||\n // || config?.port\n env?.PORT ||\n \"8000\";\n\n watermarkStamper.stamp({\n envFiles,\n port: env.__PORT,\n host: env.__HOST,\n });\n\n child = spawn(\"node\", [entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n\n process.on(\"SIGINT\", () => {\n if (child) child.kill();\n\n process.exit(0);\n });\n } catch (error) {\n sheu.error(\"Production server failed to start:\");\n console.error(error);\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the production server child process\n */\nexport function killProductionServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
1
+ {"version":3,"file":"start.js","sourceRoot":"","sources":["../../../../src/utils/cli/start.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAgB,KAAK,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,gBAAgB,MAAM,2BAA2B,CAAC;AACzD,OAAO,IA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,CAAC,WAAW,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;QAEzD,GAAG,CAAC,MAAM;YACR,GAAG,EAAE,QAAQ;gBAEb,GAAG,EAAE,IAAI;gBACT,MAAM,CAAC;QAET,gBAAgB,CAAC,KAAK,CAAC;YACrB,QAAQ;YACR,IAAI,EAAE,GAAG,CAAC,MAAM;YAChB,IAAI,EAAE,GAAG,CAAC,MAAM;SACjB,CAAC,CAAC;QAEH,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,UAAU,CAAC,EAAE;YAClC,KAAK,EAAE,SAAS;YAChB,GAAG;YACH,KAAK,EAAE,IAAI;SACZ,CAAC,CAAC;QAEH,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;YACxB,IAAI,KAAK;gBAAE,KAAK,CAAC,IAAI,EAAE,CAAC;YAExB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACjD,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,MAAM,UAAU,gCAAgC;IAC7C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { ChildProcess, spawn } from \"child_process\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { fullCleanCwd } from \"../helpers/fs.helpers\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\nimport sheu from \"../sheu\";\n\ninterface StartOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Production start command for the arkos CLI\n */\nexport function startCommand(options: StartOptions = {}) {\n process.env.NO_CLI = \"true\";\n\n if (!process.env.NODE_ENV) process.env.NODE_ENV = \"production\";\n process.env.ARKOS_BUILD = \"true\";\n\n envFiles = loadEnvironmentVariables();\n\n try {\n const { port, host } = options;\n\n const entryPoint = path.join(process.cwd(), \".build\", \"src\", \"app.js\");\n\n if (!fs.existsSync(path.join(entryPoint))) {\n sheu.error(\n `Could not find built application entry point at ${fullCleanCwd(entryPoint).replaceAll(/^\\/+/g, \"\")}`\n );\n process.exit(1);\n }\n\n const env: { [x: string]: string } = {\n NODE_ENV: \"production\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n ARKOS_BUILD: \"true\",\n CLI: \"false\",\n };\n\n env.__HOST =\n env?.CLI_HOST ||\n // config?.host ||\n env?.HOST ||\n (env.ARKOS_BUILD !== \"true\" ? \"0.0.0.0\" : \"127.0.0.1\");\n\n env.__PORT =\n env?.CLI_PORT ||\n // || config?.port\n env?.PORT ||\n \"8000\";\n\n watermarkStamper.stamp({\n envFiles,\n port: env.__PORT,\n host: env.__HOST,\n });\n\n child = spawn(\"node\", [entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n\n process.on(\"SIGINT\", () => {\n if (child) child.kill();\n\n process.exit(0);\n });\n } catch (error) {\n sheu.error(\"Production server failed to start:\");\n console.error(error);\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the production server child process\n */\nexport function killProductionServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
@@ -11,6 +11,6 @@ export function killServerChildProcess() {
11
11
  killProductionServerChildProcess();
12
12
  }
13
13
  export function getVersion() {
14
- return "2.0.0-next.2";
14
+ return "2.0.0-next.4";
15
15
  }
16
16
  //# sourceMappingURL=cli.helpers.js.map
@@ -92,7 +92,6 @@ export type AuthAction<R extends AuthResource = AuthResource> = Extract<
92
92
  >["action"];
93
93
  `
94
94
  : ""}
95
-
96
95
  export default authActions;
97
96
  `;
98
97
  await fs.mkdir(path.dirname(targetPath), { recursive: true });
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-cli-commander.js","sourceRoot":"","sources":["../../../../../src/utils/cli/utils/runtime-cli-commander.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,MAAM,aAAa,CAAC;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,YAAY,CAAC;AAC9B,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,iCAAiC,EAAE,MAAM,QAAQ,CAAC;AAS3D,MAAM,mBAAmB;IAUvB,UAAU;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,IAAI,CAAC,CAAC;IAC7D,CAAC;IAOD,GAAG;QACD,iCAAiC,EAAE,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAYD,KAAK,CAAC,MAAM;QACV,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;QACxC,IAAI,OAAO,KAAK,oBAAoB;YAAE,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;IACtE,CAAC;IAmBD,KAAK,CAAC,gBAAgB;QACpB,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,EAA4C,CAAC;QAC5E,MAAM,WAAW,GAAG,iBAAiB,CAAC,MAAM,EAAE,CAAC;QAC/C,MAAM,GAAG,GAAG,oBAAoB,EAAE,CAAC;QAEnC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAC1B,OAAO,CAAC,GAAG,EAAE,EACb,OAAO,CAAC,IAAI,IAAI,EAAE,EACl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,CAAC,QAAQ,KAAK,SAAS,CAAC,QAAQ,CAC3C,CAAC;oBAEF,IAAI,cAAc,EAAE,CAAC;wBACnB,OAAO;4BACL,GAAG,SAAS;4BACZ,GAAG,cAAc;4BACjB,KAAK,EAAE,SAAS,CAAC,KAAK;yBACvB,CAAC;oBACJ,CAAC;oBAED,OAAO,SAAS,CAAC;gBACnB,CAAC,CACF,CAAC;gBAEF,QAAQ,GAAG,IAAI,CAAC;YAClB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC,CAAA,CAAC;QACpB,CAAC;QAED,MAAM,WAAW,GAAG,uBAAuB,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;EAExH,GAAG,KAAK,IAAI;YACV,CAAC,CAAC;;;;;;;;;CASL;YACG,CAAC,CAAC,EACN;;;CAGC,CAAC;QAEE,MAAM,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC9D,MAAM,EAAE,CAAC,SAAS,CAAC,UAAU,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;QAErD,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACjB,IAAI,QAAQ;YACV,IAAI,CAAC,IAAI,CACP,qDAAqD,YAAY,CAAC,UAAU,CAAC,EAAE,CAChF,CAAC;;YAEF,IAAI,CAAC,IAAI,CACP,yCAAyC,YAAY,CAAC,UAAU,CAAC,EAAE,CACpE,CAAC;QAEJ,IAAI,CAAC,GAAG,EAAE,CAAC;IACb,CAAC;CACF;AAOD,MAAM,mBAAmB,GAAwB,IAAI,mBAAmB,EAAE,CAAC;AAE3E,eAAe,mBAAmB,CAAC","sourcesContent":["import { authActionService } from \"../../../exports/services\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport sheu from \"../../sheu\";\nimport { fullCleanCwd, getUserFileExtension } from \"../../helpers/fs.helpers\";\nimport { importModule } from \"../../helpers/global.helpers\";\nimport { killDevelopmentServerChildProcess } from \"../dev\";\n\n/**\n * Runtime CLI Commander class for handling command-line interface commands\n * during runtime execution. Provides methods for executing various CLI commands\n * and managing their lifecycle.\n *\n * @class RuntimeCliCommander\n */\nclass RuntimeCliCommander {\n /**\n * Parses and returns CLI command options from environment variables\n *\n * @returns {Object} Parsed CLI command options object\n *\n * @example\n * // Returns { overwrite: true, path: './exports' }\n * getOptions();\n */\n getOptions(): { overwrite?: boolean; path: string } {\n return JSON.parse(process.env.CLI_COMMAND_OPTIONS || \"{}\");\n }\n\n /**\n * Terminates the development server child process and exits the current process\n *\n * @returns {void}\n */\n end(): void {\n killDevelopmentServerChildProcess();\n process.exit(1);\n }\n\n /**\n * Main command handler that routes to specific command implementations\n * based on the CLI_COMMAND environment variable\n *\n * @returns {Promise<void>}\n *\n * @example\n * // Handles EXPORT_AUTH_ACTION command\n * await handle();\n */\n async handle(): Promise<void> {\n const command = process.env.CLI_COMMAND;\n if (command === \"EXPORT_AUTH_ACTION\") await this.exportAuthAction();\n }\n\n /**\n * Exports authentication actions to a file, with options for merging with existing\n * actions and specifying output path\n *\n * @param {Object} [options] - Export configuration options\n * @param {boolean} [options.overwrite] - Whether to overwrite existing file (default: false)\n * @param {string} [options.path] - Custom output directory path\n * @returns {Promise<void>}\n *\n * @example\n * // Export with default options (merge if exists)\n * await exportAuthAction();\n *\n * @example\n * // Export with overwrite and custom path\n * await exportAuthAction({ overwrite: true, path: './custom-exports' });\n */\n async exportAuthAction(): Promise<void> {\n const options = this.getOptions() as { overwrite?: boolean; path?: string };\n const authActions = authActionService.getAll();\n const ext = getUserFileExtension();\n\n const targetPath = path.join(\n process.cwd(),\n options.path || \"\",\n `auth-actions.${ext}`\n );\n\n let finalAuthActions = authActions;\n let isUpdate = false;\n\n if (!options.overwrite) {\n try {\n const existingModule = await importModule(targetPath);\n const existingActions = existingModule.default || existingModule;\n\n const rolesChanges: string[] = [];\n\n for (const newAction of authActions) {\n const existingAction = existingActions.find(\n (existing: any) =>\n existing.action === newAction.action &&\n existing.resource === newAction.resource\n );\n\n if (existingAction) {\n const existingRoles = existingAction.roles\n ? [...existingAction.roles].sort()\n : [];\n const newRoles = newAction.roles ? [...newAction.roles].sort() : [];\n\n const rolesMatch =\n existingRoles.length === newRoles.length &&\n existingRoles.every((role, index) => role === newRoles[index]);\n\n if (!rolesMatch) {\n rolesChanges.push(\n ` - ${newAction.action}:${newAction.resource}: [${existingRoles.join(\", \")}] → [${newRoles.join(\", \")}]`\n );\n }\n }\n }\n\n if (rolesChanges.length > 0) {\n const warningMessage = `Roles for the following permissions will be updated:\\n${rolesChanges.join(\"\\n\")}`;\n\n sheu.warn(warningMessage);\n\n const answer = await new Promise<boolean>((resolve) => {\n process.stdout.write(\n `\\n${sheu.green(\"?\", { bold: true })} Do you want to proceed with updating these roles? (Y/n): `\n );\n process.stdin.once(\"data\", (data) => {\n const result = data.toString().trim().toLowerCase();\n process.stdin.pause();\n resolve(result === \"y\" || result.length === 0);\n });\n });\n\n if (!answer) {\n throw new Error(\n `Auth action export cancelled. Roles were not updated to preserve existing permissions., if you would like to overwrite existing auth actions run:\n\nnpx arkos export auth-action --overwrite\n`\n );\n }\n }\n\n finalAuthActions = [...authActions, ...existingActions].map(\n (newAction) => {\n const existingAction = existingActions.find(\n (existing: any) =>\n existing.action === newAction.action &&\n existing.resource === newAction.resource\n );\n\n if (existingAction) {\n return {\n ...newAction,\n ...existingAction,\n roles: newAction.roles,\n };\n }\n\n return newAction;\n }\n );\n\n isUpdate = true;\n } catch (error) {}\n }\n\n const fileContent = `const authActions = ${JSON.stringify(finalAuthActions, null, 2)}${ext === \"ts\" ? \" as const\" : \"\"};\n${\n ext === \"ts\"\n ? `\ntype AuthActionsArray = typeof authActions;\n\nexport type AuthResource = AuthActionsArray[number][\"resource\"];\n\nexport type AuthAction<R extends AuthResource = AuthResource> = Extract<\n AuthActionsArray[number],\n { resource: R }\n>[\"action\"];\n`\n : \"\"\n}\n\nexport default authActions;\n`;\n\n await fs.mkdir(path.dirname(targetPath), { recursive: true });\n await fs.writeFile(targetPath, fileContent, \"utf-8\");\n\n console.info(\"\");\n if (isUpdate)\n sheu.done(\n `Auth actions updated and exported successfully at ${fullCleanCwd(targetPath)}`\n );\n else\n sheu.done(\n `Auth actions exported successfully at ${fullCleanCwd(targetPath)}`\n );\n\n this.end();\n }\n}\n\n/**\n * Singleton instance of RuntimeCliCommander\n *\n * @type {RuntimeCliCommander}\n */\nconst runtimeCliCommander: RuntimeCliCommander = new RuntimeCliCommander();\n\nexport default runtimeCliCommander;\n"]}
1
+ {"version":3,"file":"runtime-cli-commander.js","sourceRoot":"","sources":["../../../../../src/utils/cli/utils/runtime-cli-commander.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,MAAM,aAAa,CAAC;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,YAAY,CAAC;AAC9B,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,iCAAiC,EAAE,MAAM,QAAQ,CAAC;AAS3D,MAAM,mBAAmB;IAUvB,UAAU;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,IAAI,CAAC,CAAC;IAC7D,CAAC;IAOD,GAAG;QACD,iCAAiC,EAAE,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAYD,KAAK,CAAC,MAAM;QACV,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;QACxC,IAAI,OAAO,KAAK,oBAAoB;YAAE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AAC,IAAI,CACP,qDAAqD,YAAY,CAAC,UAAU,CAAC,EAAE,CAChF,CAAC;;YAEF,IAAI,CAAC,IAAI,CACP,yCAAyC,YAAY,CAAC,UAAU,CAAC,EAAE,CACpE,CAAC;QAEJ,IAAI,CAAC,GAAG,EAAE,CAAC;IACb,CAAC;CACF;AAOD,MAAM,mBAAmB,GAAwB,IAAI,mBAAmB,EAAE,CAAC;AAE3E,eAAe,mBAAmB,CAAC","sourcesContent":["import { authActionService } from \"../../../exports/services\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport sheu from \"../../sheu\";\nimport { fullCleanCwd, getUserFileExtension } from \"../../helpers/fs.helpers\";\nimport { importModule } from \"../../helpers/global.helpers\";\nimport { killDevelopmentServerChildProcess } from \"../dev\";\n\n/**\n * Runtime CLI Commander class for handling command-line interface commands\n * during runtime execution. Provides methods for executing various CLI commands\n * and managing their lifecycle.\n *\n * @class RuntimeCliCommander\n */\nclass RuntimeCliCommander {\n /**\n * Parses and returns CLI command options from environment variables\n *\n * @returns {Object} Parsed CLI command options object\n *\n * @example\n * // Returns { overwrite: true, path: './exports' }\n * getOptions();\n */\n getOptions(): { overwrite?: boolean; path: string } {\n return JSON.parse(process.env.CLI_COMMAND_OPTIONS || \"{}\");\n }\n\n /**\n * Terminates the development server child process and exits the current process\n *\n * @returns {void}\n */\n end(): void {\n killDevelopmentServerChildProcess();\n process.exit(1);\n }\n\n /**\n * Main command handler that routes to specific command implementations\n * based on the CLI_COMMAND environment variable\n *\n * @returns {Promise<void>}\n *\n * @example\n * // Handles EXPORT_AUTH_ACTION command\n * await handle();\n */\n async handle(): Promise<void> {\n const command = process.env.CLI_COMMAND;\n if (command === \"EXPORT_AUTH_ACTION\") await this.exportAuthAction();\n }\n\n /**\n * Exports authentication actions to a file, with options for merging with existing\n * actions and specifying output path\n *\n * @param {Object} [options] - Export configuration options\n * @param {boolean} [options.overwrite] - Whether to overwrite existing file (default: false)\n * @param {string} [options.path] - Custom output directory path\n * @returns {Promise<void>}\n *\n * @example\n * // Export with default options (merge if exists)\n * await exportAuthAction();\n *\n * @example\n * // Export with overwrite and custom path\n * await exportAuthAction({ overwrite: true, path: './custom-exports' });\n */\n async exportAuthAction(): Promise<void> {\n const options = this.getOptions() as { overwrite?: boolean; path?: string };\n const authActions = authActionService.getAll();\n const ext = getUserFileExtension();\n\n const targetPath = path.join(\n process.cwd(),\n options.path || \"\",\n `auth-actions.${ext}`\n );\n\n let finalAuthActions = authActions;\n let isUpdate = false;\n\n if (!options.overwrite) {\n try {\n const existingModule = await importModule(targetPath);\n const existingActions = existingModule.default || existingModule;\n\n const rolesChanges: string[] = [];\n\n for (const newAction of authActions) {\n const existingAction = existingActions.find(\n (existing: any) =>\n existing.action === newAction.action &&\n existing.resource === newAction.resource\n );\n\n if (existingAction) {\n const existingRoles = existingAction.roles\n ? [...existingAction.roles].sort()\n : [];\n const newRoles = newAction.roles ? [...newAction.roles].sort() : [];\n\n const rolesMatch =\n existingRoles.length === newRoles.length &&\n existingRoles.every((role, index) => role === newRoles[index]);\n\n if (!rolesMatch) {\n rolesChanges.push(\n ` - ${newAction.action}:${newAction.resource}: [${existingRoles.join(\", \")}] → [${newRoles.join(\", \")}]`\n );\n }\n }\n }\n\n if (rolesChanges.length > 0) {\n const warningMessage = `Roles for the following permissions will be updated:\\n${rolesChanges.join(\"\\n\")}`;\n\n sheu.warn(warningMessage);\n\n const answer = await new Promise<boolean>((resolve) => {\n process.stdout.write(\n `\\n${sheu.green(\"?\", { bold: true })} Do you want to proceed with updating these roles? (Y/n): `\n );\n process.stdin.once(\"data\", (data) => {\n const result = data.toString().trim().toLowerCase();\n process.stdin.pause();\n resolve(result === \"y\" || result.length === 0);\n });\n });\n\n if (!answer) {\n throw new Error(\n `Auth action export cancelled. Roles were not updated to preserve existing permissions., if you would like to overwrite existing auth actions run:\n\nnpx arkos export auth-action --overwrite\n`\n );\n }\n }\n\n finalAuthActions = [...authActions, ...existingActions].map(\n (newAction) => {\n const existingAction = existingActions.find(\n (existing: any) =>\n existing.action === newAction.action &&\n existing.resource === newAction.resource\n );\n\n if (existingAction) {\n return {\n ...newAction,\n ...existingAction,\n roles: newAction.roles,\n };\n }\n\n return newAction;\n }\n );\n\n isUpdate = true;\n } catch (error) {}\n }\n\n const fileContent = `const authActions = ${JSON.stringify(finalAuthActions, null, 2)}${ext === \"ts\" ? \" as const\" : \"\"};\n${\n ext === \"ts\"\n ? `\ntype AuthActionsArray = typeof authActions;\n\nexport type AuthResource = AuthActionsArray[number][\"resource\"];\n\nexport type AuthAction<R extends AuthResource = AuthResource> = Extract<\n AuthActionsArray[number],\n { resource: R }\n>[\"action\"];\n`\n : \"\"\n}\nexport default authActions;\n`;\n\n await fs.mkdir(path.dirname(targetPath), { recursive: true });\n await fs.writeFile(targetPath, fileContent, \"utf-8\");\n\n console.info(\"\");\n if (isUpdate)\n sheu.done(\n `Auth actions updated and exported successfully at ${fullCleanCwd(targetPath)}`\n );\n else\n sheu.done(\n `Auth actions exported successfully at ${fullCleanCwd(targetPath)}`\n );\n\n this.end();\n }\n}\n\n/**\n * Singleton instance of RuntimeCliCommander\n *\n * @type {RuntimeCliCommander}\n */\nconst runtimeCliCommander: RuntimeCliCommander = new RuntimeCliCommander();\n\nexport default runtimeCliCommander;\n"]}
@@ -9,7 +9,7 @@ export function fullCleanCwd(path) {
9
9
  if (path.startsWith(`/${process.cwd()}`) ||
10
10
  path.startsWith(`${process.cwd()}`) ||
11
11
  path.startsWith(`${process.cwd()}/`))
12
- return path.replaceAll(process.cwd(), "").replaceAll(/^\/+/g, "");
12
+ return path.replaceAll(process.cwd(), "");
13
13
  else
14
14
  return path;
15
15
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fs.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/fs.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,MAAM,CAAC,MAAM,GAAG,GAAG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CAAC,CAAC;QAEvE,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,CAAC;QAEvD,IAAI,WAAW;YAAE,iBAAiB,GAAG,IAAI,CAAC;aACrC,IAAI,WAAW,IAAI,QAAQ;YAAE,iBAAiB,GAAG,IAAI,CAAC;aACtD,IAAI,QAAQ,IAAI,CAAC,QAAQ;YAAE,iBAAiB,GAAG,IAAI,CAAC;aACpD,IAAI,QAAQ;YAAE,iBAAiB,GAAG,IAAI,CAAC;;YACvC,iBAAiB,GAAG,IAAI,CAAC;QAE9B,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,iBAAiB,GAAG,IAAI,CAAC;QACzB,OAAO,iBAAiB,CAAC;IAC3B,CAAC;AACH,CAAC,CAAC;AAgBF,MAAM,UAAU,eAAe,CAAC,QAAgB;IAC9C,IAAI,CAAC;QACH,OAAO,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC/C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\n\nexport const crd = () =>\n process.env.ARKOS_BUILD === \"true\"\n ? process.cwd() + \"/.build/\"\n : process.cwd();\n\n/**\n * Removes the current working directory prefix from the given path.\n * Handles cases with or without a trailing slash in cwd.\n * @param path - The path to clean\n * @returns The path without the cwd prefix\n */\nexport function fullCleanCwd(path: string): string {\n if (typeof path !== \"string\") throw new Error(\"Path must be a string\");\n\n if (\n path.startsWith(`/${process.cwd()}`) ||\n path.startsWith(`${process.cwd()}`) ||\n path.startsWith(`${process.cwd()}/`)\n )\n return path.replaceAll(process.cwd(), \"\").replaceAll(/^\\/+/g, \"\");\n else return path;\n}\n\nexport let userFileExtension: \"ts\" | \"js\" | undefined;\n\n/**\n * Detects the file extension that should be used in the current execution context\n * Returns 'ts' when TypeScript config exists and not in build mode, otherwise 'js'\n * @returns 'ts' | 'js'\n */\nexport const getUserFileExtension = (): \"ts\" | \"js\" => {\n if (userFileExtension) return userFileExtension;\n\n try {\n const currentDir = process.cwd();\n\n const hasTsConfig = fs.existsSync(path.join(currentDir, \"tsconfig.json\"));\n\n const hasAppTs = fs.existsSync(path.join(currentDir, \"src\", \"app.ts\"));\n const hasAppJs = fs.existsSync(path.join(currentDir, \"src\", \"app.js\"));\n\n const isBuildMode = process.env.ARKOS_BUILD === \"true\";\n\n if (isBuildMode) userFileExtension = \"js\";\n else if (hasTsConfig && hasAppTs) userFileExtension = \"ts\";\n else if (hasAppTs && !hasAppJs) userFileExtension = \"ts\";\n else if (hasAppJs) userFileExtension = \"js\";\n else userFileExtension = \"js\";\n\n return userFileExtension;\n } catch (e) {\n userFileExtension = \"js\";\n return userFileExtension;\n }\n};\n\n/**\n * Checks if a file exists at the specified file path.\n *\n * @param filePath - The path to the file to check\n * @returns {boolean} True if the file exists, false otherwise or if there's an error\n *\n * @example\n * ```ts\n * const exists = checkFileExists('./path/to/file.txt');\n * if (exists) {\n * console.info('File exists!');\n * }\n * ```\n */\nexport function checkFileExists(filePath: string): boolean {\n try {\n return fs.existsSync(path.resolve(filePath));\n } catch (error) {\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"fs.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/fs.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,MAAM,CAAC,MAAM,GAAG,GAAG,GAAG,EAAE,CACtB,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;IAChC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,UAAU;IAC5B,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;AAQpB,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,IAAI,OAAO,IAAI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AC;aACpD,IAAI,QAAQ;YAAE,iBAAiB,GAAG,IAAI,CAAC;;YACvC,iBAAiB,GAAG,IAAI,CAAC;QAE9B,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,iBAAiB,GAAG,IAAI,CAAC;QACzB,OAAO,iBAAiB,CAAC;IAC3B,CAAC;AACH,CAAC,CAAC;AAgBF,MAAM,UAAU,eAAe,CAAC,QAAgB;IAC9C,IAAI,CAAC;QACH,OAAO,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC/C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\n\nexport const crd = () =>\n process.env.ARKOS_BUILD === \"true\"\n ? process.cwd() + \"/.build/\"\n : process.cwd();\n\n/**\n * Removes the current working directory prefix from the given path.\n * Handles cases with or without a trailing slash in cwd.\n * @param path - The path to clean\n * @returns The path without the cwd prefix\n */\nexport function fullCleanCwd(path: string): string {\n if (typeof path !== \"string\") throw new Error(\"Path must be a string\");\n\n if (\n path.startsWith(`/${process.cwd()}`) ||\n path.startsWith(`${process.cwd()}`) ||\n path.startsWith(`${process.cwd()}/`)\n )\n return path.replaceAll(process.cwd(), \"\");\n else return path;\n}\n\nexport let userFileExtension: \"ts\" | \"js\" | undefined;\n\n/**\n * Detects the file extension that should be used in the current execution context\n * Returns 'ts' when TypeScript config exists and not in build mode, otherwise 'js'\n * @returns 'ts' | 'js'\n */\nexport const getUserFileExtension = (): \"ts\" | \"js\" => {\n if (userFileExtension) return userFileExtension;\n\n try {\n const currentDir = process.cwd();\n\n const hasTsConfig = fs.existsSync(path.join(currentDir, \"tsconfig.json\"));\n\n const hasAppTs = fs.existsSync(path.join(currentDir, \"src\", \"app.ts\"));\n const hasAppJs = fs.existsSync(path.join(currentDir, \"src\", \"app.js\"));\n\n const isBuildMode = process.env.ARKOS_BUILD === \"true\";\n\n if (isBuildMode) userFileExtension = \"js\";\n else if (hasTsConfig && hasAppTs) userFileExtension = \"ts\";\n else if (hasAppTs && !hasAppJs) userFileExtension = \"ts\";\n else if (hasAppJs) userFileExtension = \"js\";\n else userFileExtension = \"js\";\n\n return userFileExtension;\n } catch (e) {\n userFileExtension = \"js\";\n return userFileExtension;\n }\n};\n\n/**\n * Checks if a file exists at the specified file path.\n *\n * @param filePath - The path to the file to check\n * @returns {boolean} True if the file exists, false otherwise or if there's an error\n *\n * @example\n * ```ts\n * const exists = checkFileExists('./path/to/file.txt');\n * if (exists) {\n * console.info('File exists!');\n * }\n * ```\n */\nexport function checkFileExists(filePath: string): boolean {\n try {\n return fs.existsSync(path.resolve(filePath));\n } catch (error) {\n return false;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkos",
3
- "version": "2.0.0-next.2",
3
+ "version": "2.0.0-next.4",
4
4
  "description": "The Express & Prisma RESTful Framework",
5
5
  "main": "dist/cjs/exports/index.js",
6
6
  "module": "dist/esm/exports/index.js",