@cyberskill/shared 3.2.0 → 3.3.0

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 (237) hide show
  1. package/dist/config/commitlint/index.js +8 -9
  2. package/dist/config/commitlint/index.js.map +1 -1
  3. package/dist/config/config.type.js +8 -5
  4. package/dist/config/config.type.js.map +1 -1
  5. package/dist/config/config.util.js +33 -42
  6. package/dist/config/config.util.js.map +1 -1
  7. package/dist/config/env/env.constant.js +6 -5
  8. package/dist/config/env/env.constant.js.map +1 -1
  9. package/dist/config/env/env.util.js +26 -27
  10. package/dist/config/env/env.util.js.map +1 -1
  11. package/dist/config/env/index.js +2 -7
  12. package/dist/config/eslint/index.js +23 -19
  13. package/dist/config/eslint/index.js.map +1 -1
  14. package/dist/config/graphql-codegen/graphql-codegen.util.js +30 -38
  15. package/dist/config/graphql-codegen/graphql-codegen.util.js.map +1 -1
  16. package/dist/config/graphql-codegen/index.js +2 -5
  17. package/dist/config/index.js +3 -7
  18. package/dist/config/lint-staged/index.js +8 -7
  19. package/dist/config/lint-staged/index.js.map +1 -1
  20. package/dist/config/storybook/index.js +2 -6
  21. package/dist/config/storybook/storybook.main.js +19 -18
  22. package/dist/config/storybook/storybook.main.js.map +1 -1
  23. package/dist/config/storybook/storybook.preview.js +31 -37
  24. package/dist/config/storybook/storybook.preview.js.map +1 -1
  25. package/dist/config/vitest/index.js +3 -7
  26. package/dist/config/vitest/vitest.e2e.js +14 -17
  27. package/dist/config/vitest/vitest.e2e.js.map +1 -1
  28. package/dist/config/vitest/vitest.unit.js +31 -32
  29. package/dist/config/vitest/vitest.unit.js.map +1 -1
  30. package/dist/constant/common.js +6 -5
  31. package/dist/constant/common.js.map +1 -1
  32. package/dist/constant/index.js +3 -7
  33. package/dist/constant/response-status.d.ts +186 -186
  34. package/dist/constant/response-status.js +254 -253
  35. package/dist/constant/response-status.js.map +1 -1
  36. package/dist/node/apollo-server/apollo-server.util.js +27 -29
  37. package/dist/node/apollo-server/apollo-server.util.js.map +1 -1
  38. package/dist/node/apollo-server/index.js +2 -7
  39. package/dist/node/cli/index.js +112 -113
  40. package/dist/node/cli/index.js.map +1 -1
  41. package/dist/node/command/command.type.js +8 -5
  42. package/dist/node/command/command.type.js.map +1 -1
  43. package/dist/node/command/command.util.js +136 -149
  44. package/dist/node/command/command.util.js.map +1 -1
  45. package/dist/node/command/index.js +3 -12
  46. package/dist/node/express/express.type.d.ts +11 -0
  47. package/dist/node/express/express.type.js +2 -0
  48. package/dist/node/express/express.util.js +74 -65
  49. package/dist/node/express/express.util.js.map +1 -1
  50. package/dist/node/express/index.js +3 -14
  51. package/dist/node/fs/fs.util.js +27 -51
  52. package/dist/node/fs/fs.util.js.map +1 -1
  53. package/dist/node/fs/index.js +2 -19
  54. package/dist/node/log/index.js +2 -8
  55. package/dist/node/log/log.type.js +8 -5
  56. package/dist/node/log/log.type.js.map +1 -1
  57. package/dist/node/log/log.util.js +51 -68
  58. package/dist/node/log/log.util.js.map +1 -1
  59. package/dist/node/mongo/index.js +8 -26
  60. package/dist/node/mongo/mongo.constant.js +6 -6
  61. package/dist/node/mongo/mongo.constant.js.map +1 -1
  62. package/dist/node/mongo/mongo.controller.mongoose.d.ts +6 -1
  63. package/dist/node/mongo/mongo.controller.mongoose.js +333 -467
  64. package/dist/node/mongo/mongo.controller.mongoose.js.map +1 -1
  65. package/dist/node/mongo/mongo.controller.native.js +153 -212
  66. package/dist/node/mongo/mongo.controller.native.js.map +1 -1
  67. package/dist/node/mongo/mongo.dynamic-populate.js +164 -192
  68. package/dist/node/mongo/mongo.dynamic-populate.js.map +1 -1
  69. package/dist/node/mongo/mongo.populate.js +229 -262
  70. package/dist/node/mongo/mongo.populate.js.map +1 -1
  71. package/dist/node/mongo/mongo.type.js +8 -17
  72. package/dist/node/mongo/mongo.type.js.map +1 -1
  73. package/dist/node/mongo/mongo.util.js +134 -293
  74. package/dist/node/mongo/mongo.util.js.map +1 -1
  75. package/dist/node/package/index.js +3 -11
  76. package/dist/node/package/package.type.js +8 -5
  77. package/dist/node/package/package.type.js.map +1 -1
  78. package/dist/node/package/package.util.js +216 -225
  79. package/dist/node/package/package.util.js.map +1 -1
  80. package/dist/node/path/index.js +3 -58
  81. package/dist/node/path/path.constant.js +211 -298
  82. package/dist/node/path/path.constant.js.map +1 -1
  83. package/dist/node/path/path.util.js +13 -16
  84. package/dist/node/path/path.util.js.map +1 -1
  85. package/dist/node/storage/index.js +3 -10
  86. package/dist/node/storage/storage.constant.js +6 -8
  87. package/dist/node/storage/storage.constant.js.map +1 -1
  88. package/dist/node/storage/storage.util.js +127 -178
  89. package/dist/node/storage/storage.util.js.map +1 -1
  90. package/dist/node/upload/index.js +4 -16
  91. package/dist/node/upload/upload.constant.js +58 -32
  92. package/dist/node/upload/upload.constant.js.map +1 -1
  93. package/dist/node/upload/upload.type.js +8 -5
  94. package/dist/node/upload/upload.type.js.map +1 -1
  95. package/dist/node/upload/upload.util.js +125 -137
  96. package/dist/node/upload/upload.util.js.map +1 -1
  97. package/dist/node/ws/index.js +2 -6
  98. package/dist/node/ws/ws.type.d.ts +7 -8
  99. package/dist/node/ws/ws.util.js +46 -44
  100. package/dist/node/ws/ws.util.js.map +1 -1
  101. package/dist/node_modules/.pnpm/vitest@4.1.0_@types_node@25.5.0_jsdom@29.0.0_@noble_hashes@1.8.0__vite@8.0.0_@types_nod_53aa4254f295b3c40bb8f17b6ab226b5/node_modules/vitest/dist/config.js +8 -0
  102. package/dist/node_modules/.pnpm/vitest@4.1.0_@types_node@25.5.0_jsdom@29.0.0_@noble_hashes@1.8.0__vite@8.0.0_@types_nod_53aa4254f295b3c40bb8f17b6ab226b5/node_modules/vitest/dist/config.js.map +1 -0
  103. package/dist/react/apollo-client/apollo-client.component.js +16 -18
  104. package/dist/react/apollo-client/apollo-client.component.js.map +1 -1
  105. package/dist/react/apollo-client/apollo-client.constant.js +6 -5
  106. package/dist/react/apollo-client/apollo-client.constant.js.map +1 -1
  107. package/dist/react/apollo-client/apollo-client.context.js +10 -13
  108. package/dist/react/apollo-client/apollo-client.context.js.map +1 -1
  109. package/dist/react/apollo-client/apollo-client.module.scss.js +8 -7
  110. package/dist/react/apollo-client/apollo-client.module.scss.js.map +1 -1
  111. package/dist/react/apollo-client/apollo-client.util.js +57 -75
  112. package/dist/react/apollo-client/apollo-client.util.js.map +1 -1
  113. package/dist/react/apollo-client/index.js +7 -30
  114. package/dist/react/apollo-client/links/index.js +2 -5
  115. package/dist/react/apollo-client/links/upload.js +63 -107
  116. package/dist/react/apollo-client/links/upload.js.map +1 -1
  117. package/dist/react/apollo-client-nextjs/apollo-client-nextjs.component.js +14 -16
  118. package/dist/react/apollo-client-nextjs/apollo-client-nextjs.component.js.map +1 -1
  119. package/dist/react/apollo-client-nextjs/apollo-client-nextjs.rsc.js +8 -7
  120. package/dist/react/apollo-client-nextjs/apollo-client-nextjs.rsc.js.map +1 -1
  121. package/dist/react/apollo-client-nextjs/apollo-client-nextjs.util.js +14 -14
  122. package/dist/react/apollo-client-nextjs/apollo-client-nextjs.util.js.map +1 -1
  123. package/dist/react/apollo-client-nextjs/index.js +3 -7
  124. package/dist/react/apollo-error/apollo-error.component.js +57 -69
  125. package/dist/react/apollo-error/apollo-error.component.js.map +1 -1
  126. package/dist/react/apollo-error/apollo-error.context.js +7 -6
  127. package/dist/react/apollo-error/apollo-error.context.js.map +1 -1
  128. package/dist/react/apollo-error/apollo-error.hook.js +10 -10
  129. package/dist/react/apollo-error/apollo-error.hook.js.map +1 -1
  130. package/dist/react/apollo-error/apollo-error.module.scss.js +15 -11
  131. package/dist/react/apollo-error/apollo-error.module.scss.js.map +1 -1
  132. package/dist/react/apollo-error/apollo-error.provider.js +31 -25
  133. package/dist/react/apollo-error/apollo-error.provider.js.map +1 -1
  134. package/dist/react/apollo-error/apollo-error.util.js +14 -16
  135. package/dist/react/apollo-error/apollo-error.util.js.map +1 -1
  136. package/dist/react/apollo-error/index.js +5 -15
  137. package/dist/react/i18next/i18next.hook.js +7 -6
  138. package/dist/react/i18next/i18next.hook.js.map +1 -1
  139. package/dist/react/i18next/i18next.util.js +9 -8
  140. package/dist/react/i18next/i18next.util.js.map +1 -1
  141. package/dist/react/i18next/index.js +3 -7
  142. package/dist/react/loading/index.js +3 -9
  143. package/dist/react/loading/loading.component.js +47 -48
  144. package/dist/react/loading/loading.component.js.map +1 -1
  145. package/dist/react/loading/loading.context.js +7 -6
  146. package/dist/react/loading/loading.context.js.map +1 -1
  147. package/dist/react/loading/loading.hook.js +11 -11
  148. package/dist/react/loading/loading.hook.js.map +1 -1
  149. package/dist/react/loading/loading.module.scss.js +18 -15
  150. package/dist/react/loading/loading.module.scss.js.map +1 -1
  151. package/dist/react/loading/loading.provider.js +26 -18
  152. package/dist/react/loading/loading.provider.js.map +1 -1
  153. package/dist/react/log/index.js +2 -6
  154. package/dist/react/log/log.util.d.ts +8 -0
  155. package/dist/react/log/log.util.js +33 -29
  156. package/dist/react/log/log.util.js.map +1 -1
  157. package/dist/react/next-intl/index.js +6 -14
  158. package/dist/react/next-intl/next-intl.constant.js +16 -15
  159. package/dist/react/next-intl/next-intl.constant.js.map +1 -1
  160. package/dist/react/next-intl/next-intl.context.js +7 -6
  161. package/dist/react/next-intl/next-intl.context.js.map +1 -1
  162. package/dist/react/next-intl/next-intl.hoc.js +20 -23
  163. package/dist/react/next-intl/next-intl.hoc.js.map +1 -1
  164. package/dist/react/next-intl/next-intl.hook.js +13 -14
  165. package/dist/react/next-intl/next-intl.hook.js.map +1 -1
  166. package/dist/react/next-intl/next-intl.provider.js +28 -23
  167. package/dist/react/next-intl/next-intl.provider.js.map +1 -1
  168. package/dist/react/storage/index.js +3 -7
  169. package/dist/react/storage/storage.hook.js +61 -58
  170. package/dist/react/storage/storage.hook.js.map +1 -1
  171. package/dist/react/storage/storage.util.js +36 -68
  172. package/dist/react/storage/storage.util.js.map +1 -1
  173. package/dist/react/toast/index.js +2 -6
  174. package/dist/react/userback/index.js +2 -5
  175. package/dist/react/userback/userback.component.js +27 -27
  176. package/dist/react/userback/userback.component.js.map +1 -1
  177. package/dist/style.css +2 -1
  178. package/dist/typescript/common.type.js +8 -5
  179. package/dist/typescript/common.type.js.map +1 -1
  180. package/dist/typescript/index.js +2 -5
  181. package/dist/util/common/common.util.js +119 -48
  182. package/dist/util/common/common.util.js.map +1 -1
  183. package/dist/util/common/index.js +2 -9
  184. package/dist/util/index.js +6 -27
  185. package/dist/util/object/index.d.ts +3 -0
  186. package/dist/util/object/index.js +2 -10
  187. package/dist/util/object/object.util.js +94 -128
  188. package/dist/util/object/object.util.js.map +1 -1
  189. package/dist/util/serializer/index.js +2 -5
  190. package/dist/util/serializer/serializer.util.js +73 -78
  191. package/dist/util/serializer/serializer.util.js.map +1 -1
  192. package/dist/util/string/index.d.ts +3 -0
  193. package/dist/util/string/index.js +2 -10
  194. package/dist/util/string/string.util.js +59 -71
  195. package/dist/util/string/string.util.js.map +1 -1
  196. package/dist/util/validate/index.d.ts +3 -0
  197. package/dist/util/validate/index.js +2 -5
  198. package/dist/util/validate/validate.util.js +13 -39
  199. package/dist/util/validate/validate.util.js.map +1 -1
  200. package/package.json +29 -27
  201. package/dist/config/env/index.js.map +0 -1
  202. package/dist/config/graphql-codegen/index.js.map +0 -1
  203. package/dist/config/index.js.map +0 -1
  204. package/dist/config/storybook/index.js.map +0 -1
  205. package/dist/config/vitest/index.js.map +0 -1
  206. package/dist/constant/index.js.map +0 -1
  207. package/dist/node/apollo-server/index.js.map +0 -1
  208. package/dist/node/command/index.js.map +0 -1
  209. package/dist/node/express/index.js.map +0 -1
  210. package/dist/node/fs/index.js.map +0 -1
  211. package/dist/node/log/index.js.map +0 -1
  212. package/dist/node/mongo/index.js.map +0 -1
  213. package/dist/node/package/index.js.map +0 -1
  214. package/dist/node/path/index.js.map +0 -1
  215. package/dist/node/storage/index.js.map +0 -1
  216. package/dist/node/upload/index.js.map +0 -1
  217. package/dist/node/ws/index.js.map +0 -1
  218. package/dist/node_modules/.pnpm/vitest@4.0.18_@types_node@25.3.5_jiti@2.6.1_jsdom@28.1.0_@noble_hashes@1.8.0__sass@1.97.3_tsx@4.21.0_yaml@2.8.2/node_modules/vitest/dist/config.js +0 -7
  219. package/dist/node_modules/.pnpm/vitest@4.0.18_@types_node@25.3.5_jiti@2.6.1_jsdom@28.1.0_@noble_hashes@1.8.0__sass@1.97.3_tsx@4.21.0_yaml@2.8.2/node_modules/vitest/dist/config.js.map +0 -1
  220. package/dist/react/apollo-client/index.js.map +0 -1
  221. package/dist/react/apollo-client/links/index.js.map +0 -1
  222. package/dist/react/apollo-client-nextjs/index.js.map +0 -1
  223. package/dist/react/apollo-error/index.js.map +0 -1
  224. package/dist/react/i18next/index.js.map +0 -1
  225. package/dist/react/loading/index.js.map +0 -1
  226. package/dist/react/log/index.js.map +0 -1
  227. package/dist/react/next-intl/index.js.map +0 -1
  228. package/dist/react/storage/index.js.map +0 -1
  229. package/dist/react/toast/index.js.map +0 -1
  230. package/dist/react/userback/index.js.map +0 -1
  231. package/dist/typescript/index.js.map +0 -1
  232. package/dist/util/common/index.js.map +0 -1
  233. package/dist/util/index.js.map +0 -1
  234. package/dist/util/object/index.js.map +0 -1
  235. package/dist/util/serializer/index.js.map +0 -1
  236. package/dist/util/string/index.js.map +0 -1
  237. package/dist/util/validate/index.js.map +0 -1
@@ -1,295 +1,136 @@
1
- import m from "mongoose-aggregate-paginate-v2";
2
- import p from "mongoose-paginate-v2";
3
- import { randomUUID as f } from "node:crypto";
4
- import { deepClone as y, getNestedValue as g, setNestedValue as h } from "../../util/object/object.util.js";
5
- import { regexSearchMapper as w } from "../../util/common/common.util.js";
6
- import { writeFileSync as S, addGitIgnoreEntry as E } from "../fs/fs.util.js";
7
- import { PATH as d, MIGRATE_MONGO_CONFIG as R } from "../path/path.constant.js";
8
- import { validate as x } from "../../util/validate/validate.util.js";
9
- function I(e) {
10
- return e === e.toUpperCase() ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : e;
1
+ import { regexSearchMapper as e } from "../../util/common/common.util.js";
2
+ import { deepClone as t, getNestedValue as n, setNestedValue as r } from "../../util/object/object.util.js";
3
+ import { validate as i } from "../../util/validate/validate.util.js";
4
+ import { addGitIgnoreEntry as a, writeFileSync as o } from "../fs/fs.util.js";
5
+ import { MIGRATE_MONGO_CONFIG as s, PATH as c } from "../path/path.constant.js";
6
+ import "./mongo.populate.js";
7
+ import l from "mongoose-aggregate-paginate-v2";
8
+ import u from "mongoose-paginate-v2";
9
+ import { randomUUID as d } from "node:crypto";
10
+ //#region src/node/mongo/mongo.util.ts
11
+ function f(e) {
12
+ return e === e.toUpperCase() ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : e;
11
13
  }
12
- const l = {
13
- /**
14
- * Creates generic fields that are commonly used across MongoDB documents.
15
- * This function generates standard fields including a UUID, deletion flag, and timestamps
16
- * that can be applied to any document schema.
17
- *
18
- * @returns An object containing generic document fields (id, isDel, createdAt, updatedAt).
19
- */
20
- createGenericFields() {
21
- return {
22
- id: f(),
23
- isDel: !1,
24
- createdAt: /* @__PURE__ */ new Date(),
25
- updatedAt: /* @__PURE__ */ new Date()
26
- };
27
- },
28
- /**
29
- * Applies plugins to a Mongoose schema.
30
- * This function filters out falsy plugins and applies the remaining valid plugins
31
- * to the provided schema.
32
- *
33
- * @param schema - The Mongoose schema to apply plugins to.
34
- * @param plugins - An array of plugin functions or false values to filter and apply.
35
- */
36
- applyPlugins(e, r) {
37
- r.filter((t) => typeof t == "function").forEach((t) => e.plugin(t));
38
- },
39
- /**
40
- * Applies middleware functions to a Mongoose schema.
41
- * This function configures pre and post middleware for specified methods on the schema.
42
- *
43
- * @param schema - The Mongoose schema to apply middleware to.
44
- * @param middlewares - An array of middleware configurations with method, pre, and post functions.
45
- */
46
- applyMiddlewares(e, r) {
47
- r.forEach(({ method: t, pre: n, post: i }) => {
48
- t && n && e.pre(t, n), t && i && e.post(t, i);
49
- });
50
- },
51
- /**
52
- * Creates a generic Mongoose schema with common fields.
53
- * This function creates a base schema with UUID field and deletion flag,
54
- * configured with automatic timestamps.
55
- *
56
- * @param mongoose - The Mongoose instance to create the schema with.
57
- * @returns A Mongoose schema with generic document fields.
58
- */
59
- createGenericSchema(e) {
60
- return new e.Schema(
61
- {
62
- id: { type: String, default: () => f(), unique: !0 },
63
- isDel: { type: Boolean, default: !1 }
64
- },
65
- { timestamps: !0 }
66
- );
67
- },
68
- /**
69
- * Creates a Mongoose schema with optional virtual fields and generic fields.
70
- * This function creates a new Mongoose schema from the provided schema definition,
71
- * optionally adds virtual fields, and includes generic fields (unless standalone is true).
72
- *
73
- * @param options - Configuration options including mongoose instance, schema definition, virtuals, and standalone flag.
74
- * @param options.mongoose - The Mongoose instance to use for schema creation.
75
- * @param options.schema - The schema definition object.
76
- * @param options.virtuals - Optional array of virtual field configurations.
77
- * @param options.standalone - Whether to exclude generic fields (default: false).
78
- * @returns A configured Mongoose schema.
79
- */
80
- createSchema({
81
- mongoose: e,
82
- schema: r,
83
- virtuals: t = [],
84
- standalone: n = !1
85
- }) {
86
- const i = new e.Schema(r, {
87
- toJSON: { virtuals: !0 },
88
- // So `res.json()` and other `JSON.stringify()` functions include virtuals
89
- toObject: { virtuals: !0 }
90
- // So `console.log()` and other functions that use `toObject()` include virtuals
91
- });
92
- return t.forEach(({ name: s, options: a, get: o }) => {
93
- if (l.isDynamicVirtual(a)) {
94
- const c = i.statics;
95
- c._dynamicVirtuals || (c._dynamicVirtuals = []), c._dynamicVirtuals.push({
96
- name: s,
97
- options: a
98
- });
99
- const u = i.virtual(s);
100
- o ? u.get(o) : u.get(function() {
101
- return this._populated?.[s] || (a?.count ? 0 : a?.justOne ? null : []);
102
- });
103
- } else {
104
- const c = i.virtual(s, a);
105
- o && c.get(o);
106
- }
107
- }), n || i.add(l.createGenericSchema(e)), i;
108
- },
109
- /**
110
- * Creates a Mongoose model with plugins, middleware, and pagination support.
111
- * This function creates a model from a schema with optional pagination and aggregation plugins,
112
- * and applies any specified middleware. If a model with the same name already exists, it returns the existing model.
113
- *
114
- * @param options - Configuration options including mongoose instance, model name, schema, and feature flags.
115
- * @param options.mongoose - The Mongoose instance to use for model creation.
116
- * @param options.name - The name of the model to create.
117
- * @param options.schema - The schema definition for the model.
118
- * @param options.pagination - Whether to enable pagination plugin (default: false).
119
- * @param options.aggregate - Whether to enable aggregation pagination plugin (default: false).
120
- * @param options.virtuals - Optional array of virtual field configurations.
121
- * @param options.middlewares - Optional array of middleware configurations.
122
- * @returns A configured Mongoose model with extended functionality.
123
- * @throws {Error} When the model name is not provided.
124
- */
125
- createModel({
126
- mongoose: e,
127
- name: r,
128
- schema: t,
129
- virtuals: n = [],
130
- pagination: i = !0,
131
- aggregate: s = !0,
132
- middlewares: a = []
133
- }) {
134
- if (!r)
135
- throw new Error("Model name is required.");
136
- if (e.models[r])
137
- return e.models[r];
138
- const o = l.createSchema({ mongoose: e, schema: t, virtuals: n });
139
- (i || s) && l.applyPlugins(o, [
140
- i && p,
141
- s && m
142
- ]), l.applyMiddlewares(o, a);
143
- const c = e.model(r, o);
144
- return n.length > 0 && (c._virtualConfigs = n), c;
145
- },
146
- /**
147
- * Validation utilities for Mongoose schemas.
148
- * This object provides common validation functions that can be used in Mongoose schema definitions.
149
- */
150
- validator: {
151
- /**
152
- * Creates a required field validator.
153
- * This function returns a validator that checks if a field value is not empty
154
- * using the validate.isEmpty utility.
155
- *
156
- * @returns A validation function that returns true if the field is not empty.
157
- */
158
- isRequired() {
159
- return async function(e) {
160
- return !x.isEmpty(e);
161
- };
162
- },
163
- /**
164
- * Creates a unique field validator.
165
- * This function returns a validator that checks if a field value is unique
166
- * across the specified fields in the collection.
167
- *
168
- * @param fields - An array of field names to check for uniqueness.
169
- * @returns A validation function that returns true if the value is unique across the specified fields.
170
- * @throws {Error} When fields is not a non-empty array of strings.
171
- */
172
- isUnique(e) {
173
- return async function(r) {
174
- if (!Array.isArray(e) || e.length === 0)
175
- throw new Error("Fields must be a non-empty array of strings.");
176
- const t = { $or: e.map((i) => ({ [i]: r })) };
177
- return !await this.constructor.exists(t);
178
- };
179
- },
180
- /**
181
- * Creates a regex pattern validator.
182
- * This function returns a validator that checks if a string value matches
183
- * all provided regular expressions.
184
- *
185
- * @param regexArray - An array of regular expressions to test against the value.
186
- * @returns A validation function that returns true if the value matches all regex patterns.
187
- * @throws {Error} When regexArray is not an array of valid RegExp objects.
188
- */
189
- matchesRegex(e) {
190
- return async (r) => {
191
- if (!Array.isArray(e) || e.some((t) => !(t instanceof RegExp)))
192
- throw new Error("regexArray must be an array of valid RegExp objects.");
193
- return e.every((t) => t.test(r));
194
- };
195
- }
196
- },
197
- /**
198
- * Migration utilities for MongoDB.
199
- * This object extends the migrate-mongo library with additional configuration utilities.
200
- */
201
- migrate: {
202
- /**
203
- * Lazily loads the migrate-mongo module to avoid eager import overhead.
204
- * Use this to access migrate-mongo methods (up, down, status, create) programmatically.
205
- *
206
- * @returns A promise resolving to the migrate-mongo module.
207
- */
208
- async getModule() {
209
- return (await import("migrate-mongo")).default;
210
- },
211
- /**
212
- * Sets the migration configuration and updates .gitignore.
213
- * This function creates a migration configuration file and ensures it's properly
214
- * excluded from version control.
215
- *
216
- * @param options - Migration configuration options to write to the config file.
217
- */
218
- setConfig: (e) => {
219
- const r = `// This file is automatically generated by the Cyberskill CLI.
220
- module.exports = ${JSON.stringify(e, null, 4)}`;
221
- S(d.MIGRATE_MONGO_CONFIG, r), E(d.GIT_IGNORE, R);
222
- }
223
- },
224
- /**
225
- * Converts string values in a filter to regex patterns for case-insensitive search.
226
- * This function recursively processes a filter object and converts string values in specified fields
227
- * to MongoDB regex patterns that support accented character matching.
228
- *
229
- * @param filter - The filter object to process.
230
- * @param fields - An array of field names to convert to regex patterns.
231
- * @returns A new filter object with string values converted to regex patterns.
232
- */
233
- regexify(e, r) {
234
- if (!e)
235
- return {};
236
- let t = y(e);
237
- if (!r || r.length === 0)
238
- return t;
239
- for (const n of r) {
240
- const i = n.toString().split("."), s = g(t, i);
241
- if (typeof s == "string" && s.length > 0) {
242
- const a = {
243
- $regex: `.*${w(s)}.*`,
244
- $options: "i"
245
- };
246
- t = h(t, i, a);
247
- }
248
- }
249
- return t;
250
- },
251
- /**
252
- * Checks if a virtual options object has a dynamic ref function.
253
- *
254
- * @param options - The virtual options to check.
255
- * @returns True if the options contain a dynamic ref function.
256
- */
257
- isDynamicVirtual(e) {
258
- return !!(e && typeof e.ref == "function");
259
- },
260
- /**
261
- * Generic utility function to get new records from the database
262
- * @param controller - MongoController instance
263
- * @param recordsToCheck - Array of records to check
264
- * @param filterFn - Function to determine if a record already exists
265
- * @returns Array of records that don't exist in the database
266
- */
267
- async getNewRecords(e, r, t) {
268
- const n = await e.findAll({});
269
- return n.success ? r.filter(
270
- (s) => !n.result.some(
271
- (a) => t(a, s)
272
- )
273
- ) : r;
274
- },
275
- /**
276
- * Generic utility function to get existing records that match the filter criteria
277
- * @param controller - MongoController instance
278
- * @param recordsToCheck - Array of records to check
279
- * @param filterFn - Function to determine if a record exists
280
- * @returns Array of existing records that match the filter criteria
281
- */
282
- async getExistingRecords(e, r, t) {
283
- const n = await e.findAll({});
284
- return n.success ? n.result.filter(
285
- (s) => r.some(
286
- (a) => t(s, a)
287
- )
288
- ) : [];
289
- }
14
+ var p = {
15
+ createGenericFields() {
16
+ return {
17
+ id: d(),
18
+ isDel: !1,
19
+ createdAt: /* @__PURE__ */ new Date(),
20
+ updatedAt: /* @__PURE__ */ new Date()
21
+ };
22
+ },
23
+ applyPlugins(e, t) {
24
+ t.filter((e) => typeof e == "function").forEach((t) => e.plugin(t));
25
+ },
26
+ applyMiddlewares(e, t) {
27
+ t.forEach(({ method: t, pre: n, post: r }) => {
28
+ t && n && e.pre(t, n), t && r && e.post(t, r);
29
+ });
30
+ },
31
+ createGenericSchema(e) {
32
+ return new e.Schema({
33
+ id: {
34
+ type: String,
35
+ default: () => d(),
36
+ unique: !0
37
+ },
38
+ isDel: {
39
+ type: Boolean,
40
+ default: !1
41
+ }
42
+ }, { timestamps: !0 });
43
+ },
44
+ createSchema({ mongoose: e, schema: t, virtuals: n = [], standalone: r = !1 }) {
45
+ let i = new e.Schema(t, {
46
+ toJSON: { virtuals: !0 },
47
+ toObject: { virtuals: !0 }
48
+ });
49
+ return n.forEach(({ name: e, options: t, get: n }) => {
50
+ if (p.isDynamicVirtual(t)) {
51
+ let r = i.statics;
52
+ r._dynamicVirtuals ||= [], r._dynamicVirtuals.push({
53
+ name: e,
54
+ options: t
55
+ }), i.virtual(e).get(n || function() {
56
+ return this._populated?.[e] || (t?.count ? 0 : t?.justOne ? null : []);
57
+ });
58
+ } else {
59
+ let r = i.virtual(e, t);
60
+ n && r.get(n);
61
+ }
62
+ }), r || i.add(p.createGenericSchema(e)), i;
63
+ },
64
+ createModel({ mongoose: e, name: t, schema: n, virtuals: r = [], pagination: i = !0, aggregate: a = !0, middlewares: o = [] }) {
65
+ if (!t) throw Error("Model name is required.");
66
+ if (e.models[t]) return e.models[t];
67
+ let s = p.createSchema({
68
+ mongoose: e,
69
+ schema: n,
70
+ virtuals: r
71
+ });
72
+ (i || a) && p.applyPlugins(s, [i && u, a && l]), p.applyMiddlewares(s, o);
73
+ let c = e.model(t, s);
74
+ return r.length > 0 && (c._virtualConfigs = r), c;
75
+ },
76
+ validator: {
77
+ isRequired() {
78
+ return async function(e) {
79
+ return !i.isEmpty(e);
80
+ };
81
+ },
82
+ isUnique(e) {
83
+ return async function(t) {
84
+ if (!Array.isArray(e) || e.length === 0) throw Error("Fields must be a non-empty array of strings.");
85
+ let n = { $or: e.map((e) => ({ [e]: t })) };
86
+ return !await this.constructor.exists(n);
87
+ };
88
+ },
89
+ matchesRegex(e) {
90
+ return async (t) => {
91
+ if (!Array.isArray(e) || e.some((e) => !(e instanceof RegExp))) throw Error("regexArray must be an array of valid RegExp objects.");
92
+ return e.every((e) => e.test(t));
93
+ };
94
+ }
95
+ },
96
+ migrate: {
97
+ async getModule() {
98
+ return (await import("migrate-mongo")).default;
99
+ },
100
+ setConfig: (e) => {
101
+ let t = `// This file is automatically generated by the Cyberskill CLI.\nmodule.exports = ${JSON.stringify(e, null, 4)}`;
102
+ o(c.MIGRATE_MONGO_CONFIG, t), a(c.GIT_IGNORE, s);
103
+ }
104
+ },
105
+ regexify(i, a) {
106
+ if (!i) return {};
107
+ let o = t(i);
108
+ if (!a || a.length === 0) return o;
109
+ for (let t of a) {
110
+ let i = t.toString().split("."), a = n(o, i);
111
+ if (typeof a == "string" && a.length > 0) {
112
+ let t = {
113
+ $regex: `.*${e(a)}.*`,
114
+ $options: "i"
115
+ };
116
+ o = r(o, i, t);
117
+ }
118
+ }
119
+ return o;
120
+ },
121
+ isDynamicVirtual(e) {
122
+ return !!(e && typeof e.ref == "function");
123
+ },
124
+ async getNewRecords(e, t, n, r = {}) {
125
+ let i = await e.findAll(r);
126
+ return i.success ? t.filter((e) => !i.result.some((t) => n(t, e))) : t;
127
+ },
128
+ async getExistingRecords(e, t, n, r = {}) {
129
+ let i = await e.findAll(r);
130
+ return i.success ? i.result.filter((e) => t.some((t) => n(e, t))) : [];
131
+ }
290
132
  };
291
- export {
292
- I as convertEnumToModelName,
293
- l as mongo
294
- };
295
- //# sourceMappingURL=mongo.util.js.map
133
+ //#endregion
134
+ export { f as convertEnumToModelName, p as mongo };
135
+
136
+ //# sourceMappingURL=mongo.util.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mongo.util.js","sources":["../../../src/node/mongo/mongo.util.ts"],"sourcesContent":["import type migrate from 'migrate-mongo';\nimport type mongooseRaw from 'mongoose';\n\nimport aggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\nimport { randomUUID } from 'node:crypto';\n\nimport { deepClone, getNestedValue, regexSearchMapper, setNestedValue } from '#util/index.js';\nimport { validate } from '#util/validate/index.js';\n\nimport type { MongoController } from './mongo.controller.js';\nimport type { C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DynamicVirtualConfig, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_MongooseModelMiddleware, T_MongoosePlugin, T_MongooseShema, T_QueryFilter, T_VirtualOptions, T_WithId } from './mongo.type.js';\n\nimport { addGitIgnoreEntry, writeFileSync } from '../fs/index.js';\nimport { MIGRATE_MONGO_CONFIG, PATH } from '../path/index.js';\n\n/**\n * Converts enum values to proper model names.\n * Handles common naming conventions like converting 'USER' to 'User'.\n *\n * @param enumValue - The enum value to convert\n * @returns The converted model name\n */\nexport function convertEnumToModelName(enumValue: string): string {\n if (enumValue === enumValue.toUpperCase()) {\n return enumValue.charAt(0).toUpperCase() + enumValue.slice(1).toLowerCase();\n }\n\n return enumValue;\n}\n\n/**\n * Interface for the MongoDB utility object to enable explicit type annotation.\n * Required to avoid TS7056 (inferred type exceeds maximum serialization length).\n */\ninterface I_MongoUtils {\n createGenericFields: () => I_GenericDocument;\n applyPlugins: <T>(schema: T_MongooseShema<T>, plugins: Array<T_MongoosePlugin | false>) => void;\n applyMiddlewares: <T extends Partial<C_Document>>(schema: T_MongooseShema<T>, middlewares: I_MongooseModelMiddleware<T>[]) => void;\n createGenericSchema: (mongoose: typeof mongooseRaw) => T_MongooseShema<I_GenericDocument>;\n createSchema: <T, R extends string>(options: I_CreateSchemaOptions<T, R>) => T_MongooseShema<T>;\n createModel: <T extends Partial<C_Document>, R extends string>(options: I_CreateModelOptions<T, R>) => I_ExtendedModel<T>;\n validator: {\n isRequired: <T>() => (this: T, value: unknown) => Promise<boolean>;\n isUnique: <T extends { constructor: { exists: (query: { [key: string]: unknown }) => Promise<unknown> } }>(fields: string[]) => (this: T, value: unknown) => Promise<boolean>;\n matchesRegex: (regexArray: RegExp[]) => (value: string) => Promise<boolean>;\n };\n migrate: {\n getModule: () => Promise<typeof migrate>;\n setConfig: (options: Partial<migrate.config.Config> & { moduleSystem?: 'commonjs' | 'esm' }) => void;\n };\n regexify: <T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]) => T_QueryFilter<T>;\n isDynamicVirtual: <T, R extends string>(options?: T_VirtualOptions<T, R>) => options is I_DynamicVirtualOptions<T, R>;\n getNewRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean) => Promise<T[]>;\n getExistingRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean) => Promise<T_WithId<T>[]>;\n}\n\n/**\n * MongoDB utility object providing comprehensive database operations and utilities.\n * This object contains methods for creating generic fields, applying plugins and middlewares,\n * creating schemas and models, validation functions, migration utilities, and regex filtering.\n */\nexport const mongo: I_MongoUtils = {\n /**\n * Creates generic fields that are commonly used across MongoDB documents.\n * This function generates standard fields including a UUID, deletion flag, and timestamps\n * that can be applied to any document schema.\n *\n * @returns An object containing generic document fields (id, isDel, createdAt, updatedAt).\n */\n createGenericFields(): I_GenericDocument {\n return {\n id: randomUUID(),\n isDel: false,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n },\n /**\n * Applies plugins to a Mongoose schema.\n * This function filters out falsy plugins and applies the remaining valid plugins\n * to the provided schema.\n *\n * @param schema - The Mongoose schema to apply plugins to.\n * @param plugins - An array of plugin functions or false values to filter and apply.\n */\n applyPlugins<T>(schema: T_MongooseShema<T>, plugins: Array<T_MongoosePlugin | false>) {\n plugins\n .filter((plugin): plugin is T_MongoosePlugin => typeof plugin === 'function')\n .forEach(plugin => schema.plugin(plugin));\n },\n /**\n * Applies middleware functions to a Mongoose schema.\n * This function configures pre and post middleware for specified methods on the schema.\n *\n * @param schema - The Mongoose schema to apply middleware to.\n * @param middlewares - An array of middleware configurations with method, pre, and post functions.\n */\n applyMiddlewares<T extends Partial<C_Document>>(\n schema: T_MongooseShema<T>,\n middlewares: I_MongooseModelMiddleware<T>[],\n ) {\n middlewares.forEach(({ method, pre, post }) => {\n if (method && pre) {\n schema.pre(method as RegExp, pre);\n }\n\n if (method && post) {\n schema.post(method as RegExp, post);\n }\n });\n },\n /**\n * Creates a generic Mongoose schema with common fields.\n * This function creates a base schema with UUID field and deletion flag,\n * configured with automatic timestamps.\n *\n * @param mongoose - The Mongoose instance to create the schema with.\n * @returns A Mongoose schema with generic document fields.\n */\n createGenericSchema(mongoose: typeof mongooseRaw) {\n return new mongoose.Schema<I_GenericDocument>(\n {\n id: { type: String, default: () => randomUUID(), unique: true },\n isDel: { type: Boolean, default: false },\n },\n { timestamps: true },\n );\n },\n /**\n * Creates a Mongoose schema with optional virtual fields and generic fields.\n * This function creates a new Mongoose schema from the provided schema definition,\n * optionally adds virtual fields, and includes generic fields (unless standalone is true).\n *\n * @param options - Configuration options including mongoose instance, schema definition, virtuals, and standalone flag.\n * @param options.mongoose - The Mongoose instance to use for schema creation.\n * @param options.schema - The schema definition object.\n * @param options.virtuals - Optional array of virtual field configurations.\n * @param options.standalone - Whether to exclude generic fields (default: false).\n * @returns A configured Mongoose schema.\n */\n createSchema<T, R extends string = string>({\n mongoose,\n schema,\n virtuals = [],\n standalone = false,\n }: I_CreateSchemaOptions<T, R>): T_MongooseShema<T> {\n const createdSchema = new mongoose.Schema<T>(schema, {\n toJSON: { virtuals: true }, // So `res.json()` and other `JSON.stringify()` functions include virtuals\n toObject: { virtuals: true }, // So `console.log()` and other functions that use `toObject()` include virtuals\n });\n\n virtuals.forEach(({ name, options, get }) => {\n if (mongo.isDynamicVirtual<T, R>(options)) {\n const schemaStatics = createdSchema.statics as Record<string, unknown>;\n\n if (!schemaStatics['_dynamicVirtuals']) {\n schemaStatics['_dynamicVirtuals'] = [];\n }\n\n (schemaStatics['_dynamicVirtuals'] as I_DynamicVirtualConfig<T>[]).push({\n name: name as string,\n options,\n });\n\n const virtualInstance = createdSchema.virtual(name as string);\n\n if (get) {\n virtualInstance.get(get);\n }\n else {\n virtualInstance.get(function (this: T & { _populated?: { [key: string]: unknown } }) {\n return this._populated?.[name as string] || (options?.count ? 0 : (options?.justOne ? null : []));\n });\n }\n }\n else {\n const virtualInstance = createdSchema.virtual(name as string, options);\n\n if (get) {\n virtualInstance.get(get);\n }\n }\n });\n\n if (!standalone) {\n createdSchema.add(mongo.createGenericSchema(mongoose));\n }\n\n return createdSchema;\n },\n /**\n * Creates a Mongoose model with plugins, middleware, and pagination support.\n * This function creates a model from a schema with optional pagination and aggregation plugins,\n * and applies any specified middleware. If a model with the same name already exists, it returns the existing model.\n *\n * @param options - Configuration options including mongoose instance, model name, schema, and feature flags.\n * @param options.mongoose - The Mongoose instance to use for model creation.\n * @param options.name - The name of the model to create.\n * @param options.schema - The schema definition for the model.\n * @param options.pagination - Whether to enable pagination plugin (default: false).\n * @param options.aggregate - Whether to enable aggregation pagination plugin (default: false).\n * @param options.virtuals - Optional array of virtual field configurations.\n * @param options.middlewares - Optional array of middleware configurations.\n * @returns A configured Mongoose model with extended functionality.\n * @throws {Error} When the model name is not provided.\n */\n createModel<T extends Partial<C_Document>, R extends string = string>({\n mongoose: currentMongooseInstance,\n name,\n schema,\n virtuals = [],\n pagination = true,\n aggregate = true,\n middlewares = [],\n }: I_CreateModelOptions<T, R>): I_ExtendedModel<T> {\n if (!name) {\n throw new Error('Model name is required.');\n }\n\n if (currentMongooseInstance.models[name]) {\n return currentMongooseInstance.models[name] as I_ExtendedModel<T>;\n }\n\n const createdSchema = mongo.createSchema({ mongoose: currentMongooseInstance, schema, virtuals });\n\n if (pagination || aggregate) {\n mongo.applyPlugins<T>(createdSchema, [\n pagination && mongoosePaginate,\n aggregate && aggregatePaginate,\n ]);\n }\n\n mongo.applyMiddlewares<T>(createdSchema, middlewares);\n\n const model = currentMongooseInstance.model<T>(name, createdSchema) as I_ExtendedModel<T>;\n\n if (virtuals.length > 0) {\n (model as any)._virtualConfigs = virtuals;\n }\n\n return model;\n },\n /**\n * Validation utilities for Mongoose schemas.\n * This object provides common validation functions that can be used in Mongoose schema definitions.\n */\n validator: {\n /**\n * Creates a required field validator.\n * This function returns a validator that checks if a field value is not empty\n * using the validate.isEmpty utility.\n *\n * @returns A validation function that returns true if the field is not empty.\n */\n isRequired<T>(): (this: T, value: unknown) => Promise<boolean> {\n return async function (this: T, value: unknown): Promise<boolean> {\n return !validate.isEmpty(value);\n };\n },\n /**\n * Creates a unique field validator.\n * This function returns a validator that checks if a field value is unique\n * across the specified fields in the collection.\n *\n * @param fields - An array of field names to check for uniqueness.\n * @returns A validation function that returns true if the value is unique across the specified fields.\n * @throws {Error} When fields is not a non-empty array of strings.\n */\n isUnique<T extends { constructor: { exists: (query: { [key: string]: unknown }) => Promise<unknown> } }>(fields: string[]) {\n return async function (this: T, value: unknown): Promise<boolean> {\n if (!Array.isArray(fields) || fields.length === 0) {\n throw new Error('Fields must be a non-empty array of strings.');\n }\n\n const query = { $or: fields.map(field => ({ [field]: value })) };\n const existingDocument = await this.constructor.exists(query);\n\n return !existingDocument;\n };\n },\n /**\n * Creates a regex pattern validator.\n * This function returns a validator that checks if a string value matches\n * all provided regular expressions.\n *\n * @param regexArray - An array of regular expressions to test against the value.\n * @returns A validation function that returns true if the value matches all regex patterns.\n * @throws {Error} When regexArray is not an array of valid RegExp objects.\n */\n matchesRegex(regexArray: RegExp[]): (value: string) => Promise<boolean> {\n return async (value: string): Promise<boolean> => {\n if (!Array.isArray(regexArray) || regexArray.some(r => !(r instanceof RegExp))) {\n throw new Error('regexArray must be an array of valid RegExp objects.');\n }\n\n return regexArray.every(regex => regex.test(value));\n };\n },\n },\n /**\n * Migration utilities for MongoDB.\n * This object extends the migrate-mongo library with additional configuration utilities.\n */\n migrate: {\n /**\n * Lazily loads the migrate-mongo module to avoid eager import overhead.\n * Use this to access migrate-mongo methods (up, down, status, create) programmatically.\n *\n * @returns A promise resolving to the migrate-mongo module.\n */\n async getModule(): Promise<typeof migrate> {\n return (await import('migrate-mongo')).default;\n },\n /**\n * Sets the migration configuration and updates .gitignore.\n * This function creates a migration configuration file and ensures it's properly\n * excluded from version control.\n *\n * @param options - Migration configuration options to write to the config file.\n */\n setConfig: (options: Partial<migrate.config.Config> & { moduleSystem?: 'commonjs' | 'esm' }) => {\n const optionsJS = `// This file is automatically generated by the Cyberskill CLI.\\nmodule.exports = ${JSON.stringify(options, null, 4)}`;\n\n writeFileSync(PATH.MIGRATE_MONGO_CONFIG, optionsJS);\n\n addGitIgnoreEntry(PATH.GIT_IGNORE, MIGRATE_MONGO_CONFIG);\n },\n },\n /**\n * Converts string values in a filter to regex patterns for case-insensitive search.\n * This function recursively processes a filter object and converts string values in specified fields\n * to MongoDB regex patterns that support accented character matching.\n *\n * @param filter - The filter object to process.\n * @param fields - An array of field names to convert to regex patterns.\n * @returns A new filter object with string values converted to regex patterns.\n */\n regexify<T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]): T_QueryFilter<T> {\n if (!filter) {\n return {} as T_QueryFilter<T>;\n }\n\n let newFilter = deepClone(filter);\n\n if (!fields || fields.length === 0) {\n return newFilter;\n }\n\n for (const field of fields) {\n const path = field.toString().split('.');\n const value = getNestedValue(newFilter, path);\n\n if (typeof value === 'string' && value.length > 0) {\n const regexValue = {\n $regex: `.*${regexSearchMapper(value)}.*`,\n $options: 'i',\n };\n\n newFilter = setNestedValue(newFilter, path, regexValue);\n }\n }\n\n return newFilter;\n },\n /**\n * Checks if a virtual options object has a dynamic ref function.\n *\n * @param options - The virtual options to check.\n * @returns True if the options contain a dynamic ref function.\n */\n isDynamicVirtual<T, R extends string = string>(options?: T_VirtualOptions<T, R>): options is I_DynamicVirtualOptions<T, R> {\n return Boolean(options && typeof options.ref === 'function');\n },\n\n /**\n * Generic utility function to get new records from the database\n * @param controller - MongoController instance\n * @param recordsToCheck - Array of records to check\n * @param filterFn - Function to determine if a record already exists\n * @returns Array of records that don't exist in the database\n */\n async getNewRecords<T extends I_GenericDocument>(\n controller: MongoController<T>,\n recordsToCheck: T[],\n filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean,\n ): Promise<T[]> {\n const existingRecords = await controller.findAll({});\n\n if (!existingRecords.success) {\n return recordsToCheck;\n }\n\n const filteredRecords = recordsToCheck.filter(newRecord =>\n !existingRecords.result.some((existingRecord: T_WithId<T>) =>\n filterFn(existingRecord, newRecord),\n ),\n );\n\n return filteredRecords;\n },\n\n /**\n * Generic utility function to get existing records that match the filter criteria\n * @param controller - MongoController instance\n * @param recordsToCheck - Array of records to check\n * @param filterFn - Function to determine if a record exists\n * @returns Array of existing records that match the filter criteria\n */\n async getExistingRecords<T extends I_GenericDocument>(\n controller: MongoController<T>,\n recordsToCheck: T[],\n filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean,\n ): Promise<T_WithId<T>[]> {\n const existingRecords = await controller.findAll({});\n\n if (!existingRecords.success) {\n return [];\n }\n\n const foundRecords = existingRecords.result.filter((existingRecord: T_WithId<T>) =>\n recordsToCheck.some((newRecord: T) =>\n filterFn(existingRecord, newRecord),\n ),\n );\n\n return foundRecords;\n },\n};\n\nexport { applyNestedPopulate } from './mongo.populate.js';\n"],"names":["convertEnumToModelName","enumValue","mongo","randomUUID","schema","plugins","plugin","middlewares","method","pre","post","mongoose","virtuals","standalone","createdSchema","name","options","get","schemaStatics","virtualInstance","currentMongooseInstance","pagination","aggregate","mongoosePaginate","aggregatePaginate","model","value","validate","fields","query","field","regexArray","r","regex","optionsJS","writeFileSync","PATH","addGitIgnoreEntry","MIGRATE_MONGO_CONFIG","filter","newFilter","deepClone","path","getNestedValue","regexValue","regexSearchMapper","setNestedValue","controller","recordsToCheck","filterFn","existingRecords","newRecord","existingRecord"],"mappings":";;;;;;;;AAuBO,SAASA,EAAuBC,GAA2B;AAC9D,SAAIA,MAAcA,EAAU,gBACjBA,EAAU,OAAO,CAAC,EAAE,gBAAgBA,EAAU,MAAM,CAAC,EAAE,YAAA,IAG3DA;AACX;AAiCO,MAAMC,IAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ/B,sBAAyC;AACrC,WAAO;AAAA,MACH,IAAIC,EAAA;AAAA,MACJ,OAAO;AAAA,MACP,+BAAe,KAAA;AAAA,MACf,+BAAe,KAAA;AAAA,IAAK;AAAA,EAE5B;AAAA;AA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ANOH;AAAA,EAUf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,mBACFD,GACAC,GACAC,GACsB;AACtB,UAAMC,IAAkB,MAAMH,EAAW,QAAQ,CAAA,CAAE;AAEnD,WAAKG,EAAgB,UAIAA,EAAgB,OAAO;AAAA,MAAO,CAACE,MAChDJ,EAAe;AAAA,QAAK,CAACG,MACjBF,EAASG,GAAgBD,CAAS;AAAA,MAAA;AAAA,IACtC,IANO,CAAA;AAAA,EAUf;AACJ;"}
1
+ {"version":3,"file":"mongo.util.js","names":[],"sources":["../../../src/node/mongo/mongo.util.ts"],"sourcesContent":["import type migrate from 'migrate-mongo';\nimport type mongooseRaw from 'mongoose';\n\nimport aggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\nimport { randomUUID } from 'node:crypto';\n\nimport { deepClone, getNestedValue, regexSearchMapper, setNestedValue } from '#util/index.js';\nimport { validate } from '#util/validate/index.js';\n\nimport type { MongoController } from './mongo.controller.js';\nimport type { C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DynamicVirtualConfig, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_MongooseModelMiddleware, T_MongoosePlugin, T_MongooseShema, T_QueryFilter, T_VirtualOptions, T_WithId } from './mongo.type.js';\n\nimport { addGitIgnoreEntry, writeFileSync } from '../fs/index.js';\nimport { MIGRATE_MONGO_CONFIG, PATH } from '../path/index.js';\n\n/**\n * Converts enum values to proper model names.\n * Handles common naming conventions like converting 'USER' to 'User'.\n *\n * @param enumValue - The enum value to convert\n * @returns The converted model name\n */\nexport function convertEnumToModelName(enumValue: string): string {\n if (enumValue === enumValue.toUpperCase()) {\n return enumValue.charAt(0).toUpperCase() + enumValue.slice(1).toLowerCase();\n }\n\n return enumValue;\n}\n\n/**\n * Interface for the MongoDB utility object to enable explicit type annotation.\n * Required to avoid TS7056 (inferred type exceeds maximum serialization length).\n */\ninterface I_MongoUtils {\n createGenericFields: () => I_GenericDocument;\n applyPlugins: <T>(schema: T_MongooseShema<T>, plugins: Array<T_MongoosePlugin | false>) => void;\n applyMiddlewares: <T extends Partial<C_Document>>(schema: T_MongooseShema<T>, middlewares: I_MongooseModelMiddleware<T>[]) => void;\n createGenericSchema: (mongoose: typeof mongooseRaw) => T_MongooseShema<I_GenericDocument>;\n createSchema: <T, R extends string>(options: I_CreateSchemaOptions<T, R>) => T_MongooseShema<T>;\n createModel: <T extends Partial<C_Document>, R extends string>(options: I_CreateModelOptions<T, R>) => I_ExtendedModel<T>;\n validator: {\n isRequired: <T>() => (this: T, value: unknown) => Promise<boolean>;\n isUnique: <T extends { constructor: { exists: (query: { [key: string]: unknown }) => Promise<unknown> } }>(fields: string[]) => (this: T, value: unknown) => Promise<boolean>;\n matchesRegex: (regexArray: RegExp[]) => (value: string) => Promise<boolean>;\n };\n migrate: {\n getModule: () => Promise<typeof migrate>;\n setConfig: (options: Partial<migrate.config.Config> & { moduleSystem?: 'commonjs' | 'esm' }) => void;\n };\n regexify: <T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]) => T_QueryFilter<T>;\n isDynamicVirtual: <T, R extends string>(options?: T_VirtualOptions<T, R>) => options is I_DynamicVirtualOptions<T, R>;\n getNewRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean) => Promise<T[]>;\n getExistingRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean) => Promise<T_WithId<T>[]>;\n}\n\n/**\n * MongoDB utility object providing comprehensive database operations and utilities.\n * This object contains methods for creating generic fields, applying plugins and middlewares,\n * creating schemas and models, validation functions, migration utilities, and regex filtering.\n */\nexport const mongo: I_MongoUtils = {\n /**\n * Creates generic fields that are commonly used across MongoDB documents.\n * This function generates standard fields including a UUID, deletion flag, and timestamps\n * that can be applied to any document schema.\n *\n * @returns An object containing generic document fields (id, isDel, createdAt, updatedAt).\n */\n createGenericFields(): I_GenericDocument {\n return {\n id: randomUUID(),\n isDel: false,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n },\n /**\n * Applies plugins to a Mongoose schema.\n * This function filters out falsy plugins and applies the remaining valid plugins\n * to the provided schema.\n *\n * @param schema - The Mongoose schema to apply plugins to.\n * @param plugins - An array of plugin functions or false values to filter and apply.\n */\n applyPlugins<T>(schema: T_MongooseShema<T>, plugins: Array<T_MongoosePlugin | false>) {\n plugins\n .filter((plugin): plugin is T_MongoosePlugin => typeof plugin === 'function')\n .forEach(plugin => schema.plugin(plugin));\n },\n /**\n * Applies middleware functions to a Mongoose schema.\n * This function configures pre and post middleware for specified methods on the schema.\n *\n * @param schema - The Mongoose schema to apply middleware to.\n * @param middlewares - An array of middleware configurations with method, pre, and post functions.\n */\n applyMiddlewares<T extends Partial<C_Document>>(\n schema: T_MongooseShema<T>,\n middlewares: I_MongooseModelMiddleware<T>[],\n ) {\n middlewares.forEach(({ method, pre, post }) => {\n if (method && pre) {\n schema.pre(method as RegExp, pre);\n }\n\n if (method && post) {\n schema.post(method as RegExp, post);\n }\n });\n },\n /**\n * Creates a generic Mongoose schema with common fields.\n * This function creates a base schema with UUID field and deletion flag,\n * configured with automatic timestamps.\n *\n * @param mongoose - The Mongoose instance to create the schema with.\n * @returns A Mongoose schema with generic document fields.\n */\n createGenericSchema(mongoose: typeof mongooseRaw) {\n return new mongoose.Schema<I_GenericDocument>(\n {\n id: { type: String, default: () => randomUUID(), unique: true },\n isDel: { type: Boolean, default: false },\n },\n { timestamps: true },\n );\n },\n /**\n * Creates a Mongoose schema with optional virtual fields and generic fields.\n * This function creates a new Mongoose schema from the provided schema definition,\n * optionally adds virtual fields, and includes generic fields (unless standalone is true).\n *\n * @param options - Configuration options including mongoose instance, schema definition, virtuals, and standalone flag.\n * @param options.mongoose - The Mongoose instance to use for schema creation.\n * @param options.schema - The schema definition object.\n * @param options.virtuals - Optional array of virtual field configurations.\n * @param options.standalone - Whether to exclude generic fields (default: false).\n * @returns A configured Mongoose schema.\n */\n createSchema<T, R extends string = string>({\n mongoose,\n schema,\n virtuals = [],\n standalone = false,\n }: I_CreateSchemaOptions<T, R>): T_MongooseShema<T> {\n const createdSchema = new mongoose.Schema<T>(schema, {\n toJSON: { virtuals: true }, // So `res.json()` and other `JSON.stringify()` functions include virtuals\n toObject: { virtuals: true }, // So `console.log()` and other functions that use `toObject()` include virtuals\n });\n\n virtuals.forEach(({ name, options, get }) => {\n if (mongo.isDynamicVirtual<T, R>(options)) {\n const schemaStatics = createdSchema.statics as Record<string, unknown>;\n\n if (!schemaStatics['_dynamicVirtuals']) {\n schemaStatics['_dynamicVirtuals'] = [];\n }\n\n (schemaStatics['_dynamicVirtuals'] as I_DynamicVirtualConfig<T>[]).push({\n name: name as string,\n options,\n });\n\n const virtualInstance = createdSchema.virtual(name as string);\n\n if (get) {\n virtualInstance.get(get);\n }\n else {\n virtualInstance.get(function (this: T & { _populated?: { [key: string]: unknown } }) {\n return this._populated?.[name as string] || (options?.count ? 0 : (options?.justOne ? null : []));\n });\n }\n }\n else {\n const virtualInstance = createdSchema.virtual(name as string, options);\n\n if (get) {\n virtualInstance.get(get);\n }\n }\n });\n\n if (!standalone) {\n createdSchema.add(mongo.createGenericSchema(mongoose));\n }\n\n return createdSchema;\n },\n /**\n * Creates a Mongoose model with plugins, middleware, and pagination support.\n * This function creates a model from a schema with optional pagination and aggregation plugins,\n * and applies any specified middleware. If a model with the same name already exists, it returns the existing model.\n *\n * @param options - Configuration options including mongoose instance, model name, schema, and feature flags.\n * @param options.mongoose - The Mongoose instance to use for model creation.\n * @param options.name - The name of the model to create.\n * @param options.schema - The schema definition for the model.\n * @param options.pagination - Whether to enable pagination plugin (default: false).\n * @param options.aggregate - Whether to enable aggregation pagination plugin (default: false).\n * @param options.virtuals - Optional array of virtual field configurations.\n * @param options.middlewares - Optional array of middleware configurations.\n * @returns A configured Mongoose model with extended functionality.\n * @throws {Error} When the model name is not provided.\n */\n createModel<T extends Partial<C_Document>, R extends string = string>({\n mongoose: currentMongooseInstance,\n name,\n schema,\n virtuals = [],\n pagination = true,\n aggregate = true,\n middlewares = [],\n }: I_CreateModelOptions<T, R>): I_ExtendedModel<T> {\n if (!name) {\n throw new Error('Model name is required.');\n }\n\n if (currentMongooseInstance.models[name]) {\n return currentMongooseInstance.models[name] as I_ExtendedModel<T>;\n }\n\n const createdSchema = mongo.createSchema({ mongoose: currentMongooseInstance, schema, virtuals });\n\n if (pagination || aggregate) {\n mongo.applyPlugins<T>(createdSchema, [\n pagination && mongoosePaginate,\n aggregate && aggregatePaginate,\n ]);\n }\n\n mongo.applyMiddlewares<T>(createdSchema, middlewares);\n\n const model = currentMongooseInstance.model<T>(name, createdSchema) as I_ExtendedModel<T>;\n\n if (virtuals.length > 0) {\n (model as any)._virtualConfigs = virtuals;\n }\n\n return model;\n },\n /**\n * Validation utilities for Mongoose schemas.\n * This object provides common validation functions that can be used in Mongoose schema definitions.\n */\n validator: {\n /**\n * Creates a required field validator.\n * This function returns a validator that checks if a field value is not empty\n * using the validate.isEmpty utility.\n *\n * @returns A validation function that returns true if the field is not empty.\n */\n isRequired<T>(): (this: T, value: unknown) => Promise<boolean> {\n return async function (this: T, value: unknown): Promise<boolean> {\n return !validate.isEmpty(value);\n };\n },\n /**\n * Creates a unique field validator.\n * This function returns a validator that checks if a field value is unique\n * across the specified fields in the collection.\n *\n * @param fields - An array of field names to check for uniqueness.\n * @returns A validation function that returns true if the value is unique across the specified fields.\n * @throws {Error} When fields is not a non-empty array of strings.\n */\n isUnique<T extends { constructor: { exists: (query: { [key: string]: unknown }) => Promise<unknown> } }>(fields: string[]) {\n return async function (this: T, value: unknown): Promise<boolean> {\n if (!Array.isArray(fields) || fields.length === 0) {\n throw new Error('Fields must be a non-empty array of strings.');\n }\n\n const query = { $or: fields.map(field => ({ [field]: value })) };\n const existingDocument = await this.constructor.exists(query);\n\n return !existingDocument;\n };\n },\n /**\n * Creates a regex pattern validator.\n * This function returns a validator that checks if a string value matches\n * all provided regular expressions.\n *\n * @param regexArray - An array of regular expressions to test against the value.\n * @returns A validation function that returns true if the value matches all regex patterns.\n * @throws {Error} When regexArray is not an array of valid RegExp objects.\n */\n matchesRegex(regexArray: RegExp[]): (value: string) => Promise<boolean> {\n return async (value: string): Promise<boolean> => {\n if (!Array.isArray(regexArray) || regexArray.some(r => !(r instanceof RegExp))) {\n throw new Error('regexArray must be an array of valid RegExp objects.');\n }\n\n return regexArray.every(regex => regex.test(value));\n };\n },\n },\n /**\n * Migration utilities for MongoDB.\n * This object extends the migrate-mongo library with additional configuration utilities.\n */\n migrate: {\n /**\n * Lazily loads the migrate-mongo module to avoid eager import overhead.\n * Use this to access migrate-mongo methods (up, down, status, create) programmatically.\n *\n * @returns A promise resolving to the migrate-mongo module.\n */\n async getModule(): Promise<typeof migrate> {\n return (await import('migrate-mongo')).default;\n },\n /**\n * Sets the migration configuration and updates .gitignore.\n * This function creates a migration configuration file and ensures it's properly\n * excluded from version control.\n *\n * @param options - Migration configuration options to write to the config file.\n */\n setConfig: (options: Partial<migrate.config.Config> & { moduleSystem?: 'commonjs' | 'esm' }) => {\n const optionsJS = `// This file is automatically generated by the Cyberskill CLI.\\nmodule.exports = ${JSON.stringify(options, null, 4)}`;\n\n writeFileSync(PATH.MIGRATE_MONGO_CONFIG, optionsJS);\n\n addGitIgnoreEntry(PATH.GIT_IGNORE, MIGRATE_MONGO_CONFIG);\n },\n },\n /**\n * Converts string values in a filter to regex patterns for case-insensitive search.\n * This function recursively processes a filter object and converts string values in specified fields\n * to MongoDB regex patterns that support accented character matching.\n *\n * @param filter - The filter object to process.\n * @param fields - An array of field names to convert to regex patterns.\n * @returns A new filter object with string values converted to regex patterns.\n */\n regexify<T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]): T_QueryFilter<T> {\n if (!filter) {\n return {} as T_QueryFilter<T>;\n }\n\n let newFilter = deepClone(filter);\n\n if (!fields || fields.length === 0) {\n return newFilter;\n }\n\n for (const field of fields) {\n const path = field.toString().split('.');\n const value = getNestedValue(newFilter, path);\n\n if (typeof value === 'string' && value.length > 0) {\n const regexValue = {\n $regex: `.*${regexSearchMapper(value)}.*`,\n $options: 'i',\n };\n\n newFilter = setNestedValue(newFilter, path, regexValue);\n }\n }\n\n return newFilter;\n },\n /**\n * Checks if a virtual options object has a dynamic ref function.\n *\n * @param options - The virtual options to check.\n * @returns True if the options contain a dynamic ref function.\n */\n isDynamicVirtual<T, R extends string = string>(options?: T_VirtualOptions<T, R>): options is I_DynamicVirtualOptions<T, R> {\n return Boolean(options && typeof options.ref === 'function');\n },\n\n /**\n * Generic utility function to get new records from the database\n * @param controller - MongoController instance\n * @param recordsToCheck - Array of records to check\n * @param filterFn - Function to determine if a record already exists\n * @returns Array of records that don't exist in the database\n */\n async getNewRecords<T extends I_GenericDocument>(\n controller: MongoController<T>,\n recordsToCheck: T[],\n filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean,\n filter: Record<string, unknown> = {},\n ): Promise<T[]> {\n const existingRecords = await controller.findAll(filter as any);\n\n if (!existingRecords.success) {\n return recordsToCheck;\n }\n\n const filteredRecords = recordsToCheck.filter(newRecord =>\n !existingRecords.result.some((existingRecord: T_WithId<T>) =>\n filterFn(existingRecord, newRecord),\n ),\n );\n\n return filteredRecords;\n },\n\n /**\n * Generic utility function to get existing records that match the filter criteria\n * @param controller - MongoController instance\n * @param recordsToCheck - Array of records to check\n * @param filterFn - Function to determine if a record exists\n * @returns Array of existing records that match the filter criteria\n */\n async getExistingRecords<T extends I_GenericDocument>(\n controller: MongoController<T>,\n recordsToCheck: T[],\n filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean,\n filter: Record<string, unknown> = {},\n ): Promise<T_WithId<T>[]> {\n const existingRecords = await controller.findAll(filter as any);\n\n if (!existingRecords.success) {\n return [];\n }\n\n const foundRecords = existingRecords.result.filter((existingRecord: T_WithId<T>) =>\n recordsToCheck.some((newRecord: T) =>\n filterFn(existingRecord, newRecord),\n ),\n );\n\n return foundRecords;\n },\n};\n\nexport { applyNestedPopulate } from './mongo.populate.js';\n"],"mappings":";;;;;;;;;;AAuBA,SAAgB,EAAuB,GAA2B;AAK9D,QAJI,MAAc,EAAU,aAAa,GAC9B,EAAU,OAAO,EAAE,CAAC,aAAa,GAAG,EAAU,MAAM,EAAE,CAAC,aAAa,GAGxE;;AAkCX,IAAa,IAAsB;CAQ/B,sBAAyC;AACrC,SAAO;GACH,IAAI,GAAY;GAChB,OAAO;GACP,2BAAW,IAAI,MAAM;GACrB,2BAAW,IAAI,MAAM;GACxB;;CAUL,aAAgB,GAA4B,GAA0C;AAClF,IACK,QAAQ,MAAuC,OAAO,KAAW,WAAW,CAC5E,SAAQ,MAAU,EAAO,OAAO,EAAO,CAAC;;CASjD,iBACI,GACA,GACF;AACE,IAAY,SAAS,EAAE,WAAQ,QAAK,cAAW;AAK3C,GAJI,KAAU,KACV,EAAO,IAAI,GAAkB,EAAI,EAGjC,KAAU,KACV,EAAO,KAAK,GAAkB,EAAK;IAEzC;;CAUN,oBAAoB,GAA8B;AAC9C,SAAO,IAAI,EAAS,OAChB;GACI,IAAI;IAAE,MAAM;IAAQ,eAAe,GAAY;IAAE,QAAQ;IAAM;GAC/D,OAAO;IAAE,MAAM;IAAS,SAAS;IAAO;GAC3C,EACD,EAAE,YAAY,IAAM,CACvB;;CAcL,aAA2C,EACvC,aACA,WACA,cAAW,EAAE,EACb,gBAAa,MACmC;EAChD,IAAM,IAAgB,IAAI,EAAS,OAAU,GAAQ;GACjD,QAAQ,EAAE,UAAU,IAAM;GAC1B,UAAU,EAAE,UAAU,IAAM;GAC/B,CAAC;AAuCF,SArCA,EAAS,SAAS,EAAE,SAAM,YAAS,aAAU;AACzC,OAAI,EAAM,iBAAuB,EAAQ,EAAE;IACvC,IAAM,IAAgB,EAAc;AAapC,IAXA,AACI,EAAc,qBAAsB,EAAE,EAGzC,EAAc,iBAAoD,KAAK;KA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,MACjB,EAAS,GAAgB,EAAU,CACtC,CACJ,GAPU,EAAE;;CAWpB"}
@@ -1,11 +1,3 @@
1
- import { E_PackageType as t } from "./package.type.js";
2
- import { getLatestPackageVersion as c, getPackage as p, installDependencies as s, setupPackages as k, updatePackage as o } from "./package.util.js";
3
- export {
4
- t as E_PackageType,
5
- c as getLatestPackageVersion,
6
- p as getPackage,
7
- s as installDependencies,
8
- k as setupPackages,
9
- o as updatePackage
10
- };
11
- //# sourceMappingURL=index.js.map
1
+ import { E_PackageType as e } from "./package.type.js";
2
+ import { getLatestPackageVersion as t, getPackage as n, installDependencies as r, setupPackages as i, updatePackage as a } from "./package.util.js";
3
+ export { e as E_PackageType, t as getLatestPackageVersion, n as getPackage, r as installDependencies, i as setupPackages, a as updatePackage };
@@ -1,5 +1,8 @@
1
- var D = /* @__PURE__ */ ((e) => (e.DEPENDENCY = "dependencies", e.DEV_DEPENDENCY = "devDependencies", e.PEER_DEPENDENCY = "peerDependencies", e.BUNDLE_DEPENDENCY = "bundleDependencies", e.OPTIONAL_DEPENDENCY = "optionalDependencies", e))(D || {});
2
- export {
3
- D as E_PackageType
4
- };
5
- //# sourceMappingURL=package.type.js.map
1
+ //#region src/node/package/package.type.ts
2
+ var e = /* @__PURE__ */ function(e) {
3
+ return e.DEPENDENCY = "dependencies", e.DEV_DEPENDENCY = "devDependencies", e.PEER_DEPENDENCY = "peerDependencies", e.BUNDLE_DEPENDENCY = "bundleDependencies", e.OPTIONAL_DEPENDENCY = "optionalDependencies", e;
4
+ }({});
5
+ //#endregion
6
+ export { e as E_PackageType };
7
+
8
+ //# sourceMappingURL=package.type.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"package.type.js","sources":["../../../src/node/package/package.type.ts"],"sourcesContent":["export interface I_PackageJson {\n name?: string;\n version?: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n [key: string]: unknown;\n}\n\nexport interface I_PackageInfo {\n name: string;\n currentVersion: string;\n latestVersion: string;\n isCurrentProject: boolean;\n isInstalled: boolean;\n isUpToDate: boolean;\n isDependency: boolean;\n isDevDependency: boolean;\n installedPath: string;\n file: I_PackageJson;\n}\n\nexport enum E_PackageType {\n DEPENDENCY = 'dependencies',\n DEV_DEPENDENCY = 'devDependencies',\n PEER_DEPENDENCY = 'peerDependencies',\n BUNDLE_DEPENDENCY = 'bundleDependencies',\n OPTIONAL_DEPENDENCY = 'optionalDependencies',\n}\n\nexport interface I_PackageInput {\n name: string;\n type?: E_PackageType;\n}\n"],"names":["E_PackageType"],"mappings":"AAqBO,IAAKA,sBAAAA,OACRA,EAAA,aAAa,gBACbA,EAAA,iBAAiB,mBACjBA,EAAA,kBAAkB,oBAClBA,EAAA,oBAAoB,sBACpBA,EAAA,sBAAsB,wBALdA,IAAAA,KAAA,CAAA,CAAA;"}
1
+ {"version":3,"file":"package.type.js","names":[],"sources":["../../../src/node/package/package.type.ts"],"sourcesContent":["export interface I_PackageJson {\n name?: string;\n version?: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n [key: string]: unknown;\n}\n\nexport interface I_PackageInfo {\n name: string;\n currentVersion: string;\n latestVersion: string;\n isCurrentProject: boolean;\n isInstalled: boolean;\n isUpToDate: boolean;\n isDependency: boolean;\n isDevDependency: boolean;\n installedPath: string;\n file: I_PackageJson;\n}\n\nexport enum E_PackageType {\n DEPENDENCY = 'dependencies',\n DEV_DEPENDENCY = 'devDependencies',\n PEER_DEPENDENCY = 'peerDependencies',\n BUNDLE_DEPENDENCY = 'bundleDependencies',\n OPTIONAL_DEPENDENCY = 'optionalDependencies',\n}\n\nexport interface I_PackageInput {\n name: string;\n type?: E_PackageType;\n}\n"],"mappings":";AAqBA,IAAY,IAAL,yBAAA,GAAA;QACH,EAAA,aAAA,gBACA,EAAA,iBAAA,mBACA,EAAA,kBAAA,oBACA,EAAA,oBAAA,sBACA,EAAA,sBAAA;KACH"}