@cyberskill/shared 2.21.0 → 2.26.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 (41) hide show
  1. package/dist/config/eslint/index.cjs +1 -1
  2. package/dist/config/eslint/index.d.ts +2 -7
  3. package/dist/config/eslint/index.js +1 -1
  4. package/dist/config/vitest/vitest.e2e.cjs +1 -1
  5. package/dist/config/vitest/vitest.e2e.js +1 -1
  6. package/dist/config/vitest/vitest.unit.cjs +1 -1
  7. package/dist/config/vitest/vitest.unit.js +1 -1
  8. package/dist/config/vitest/vitest.unit.setup.d.ts +0 -1
  9. package/dist/node/cli/index.cjs +4 -4
  10. package/dist/node/cli/index.js +56 -51
  11. package/dist/node/command/command.util.cjs +2 -2
  12. package/dist/node/command/command.util.d.ts +4 -1
  13. package/dist/node/command/command.util.js +125 -112
  14. package/dist/node/express/express.type.d.ts +2 -0
  15. package/dist/node/express/express.util.cjs +1 -1
  16. package/dist/node/express/express.util.js +53 -47
  17. package/dist/node/mongo/index.cjs +1 -1
  18. package/dist/node/mongo/index.d.ts +1 -0
  19. package/dist/node/mongo/index.js +15 -12
  20. package/dist/node/mongo/mongo.controller.cjs +1 -0
  21. package/dist/node/mongo/mongo.controller.d.ts +317 -0
  22. package/dist/node/mongo/mongo.controller.js +956 -0
  23. package/dist/node/mongo/mongo.type.d.ts +9 -10
  24. package/dist/node/mongo/mongo.util.cjs +5 -5
  25. package/dist/node/mongo/mongo.util.d.ts +26 -315
  26. package/dist/node/mongo/mongo.util.js +314 -1241
  27. package/dist/node/path/path.constant.cjs +1 -1
  28. package/dist/node/path/path.constant.d.ts +2 -2
  29. package/dist/node/path/path.constant.js +43 -43
  30. package/dist/util/common/common.util.cjs +1 -1
  31. package/dist/util/common/common.util.d.ts +3 -0
  32. package/dist/util/common/common.util.js +36 -35
  33. package/dist/util/object/object.util.cjs +1 -1
  34. package/dist/util/object/object.util.js +49 -45
  35. package/dist/util/validate/validate.util.cjs +1 -1
  36. package/dist/util/validate/validate.util.js +1 -1
  37. package/package.json +25 -24
  38. /package/dist/node/mongo/{mongo-controller.test.unit.d.ts → mongo.controller.test.unit.d.ts} +0 -0
  39. /package/dist/node/mongo/{mongo.test.unit.d.ts → mongo.util.test.unit.d.ts} +0 -0
  40. /package/dist/node_modules/.pnpm/{vitest@4.0.16_@types_node@25.0.3_jiti@2.6.1_jsdom@27.3.0_sass@1.97.0_tsx@4.21.0_yaml@2.8.2 → vitest@4.0.16_@types_node@25.0.3_jiti@2.6.1_jsdom@27.4.0_sass@1.97.2_tsx@4.21.0_yaml@2.8.2}/node_modules/vitest/dist/config.cjs +0 -0
  41. /package/dist/node_modules/.pnpm/{vitest@4.0.16_@types_node@25.0.3_jiti@2.6.1_jsdom@27.3.0_sass@1.97.0_tsx@4.21.0_yaml@2.8.2 → vitest@4.0.16_@types_node@25.0.3_jiti@2.6.1_jsdom@27.4.0_sass@1.97.2_tsx@4.21.0_yaml@2.8.2}/node_modules/vitest/dist/config.js +0 -0
@@ -17,7 +17,7 @@ export declare class C_Collection<T extends Partial<C_Document>> extends Collect
17
17
  }
18
18
  export interface I_ExtendedModel<T extends Partial<C_Document>> extends Model<T>, PaginateModel<T>, AggregatePaginateModel<T> {
19
19
  }
20
- export type T_FilterQuery<T> = QueryFilter<T>;
20
+ export type T_QueryFilter<T> = QueryFilter<T>;
21
21
  export type T_ProjectionType<T> = ProjectionType<T>;
22
22
  export type T_QueryOptions<T> = QueryOptions<T>;
23
23
  export type T_PaginateOptions = PaginateOptions;
@@ -91,7 +91,6 @@ export interface I_CreateSchemaOptions<T, R extends string = string> extends I_M
91
91
  export type T_MongooseMiddlewareMethod = string | RegExp;
92
92
  export type T_MongooseMiddlewarePreFunction<T> = T_PreMiddlewareFunction<T> & T_PreSaveMiddlewareFunction<T>;
93
93
  export type T_MongooseMiddlewarePostFunction<T> = T_PostMiddlewareFunction<T> & T_ErrorHandlingMiddlewareFunction<T> & T_ErrorHandlingMiddlewareWithOption<T>;
94
- export type T_MongooseHookNextFunction = (error?: Error) => void;
95
94
  export interface I_MongooseModelMiddleware<T extends Partial<C_Document>> {
96
95
  method: T_MongooseMiddlewareMethod;
97
96
  pre?: T_MongooseMiddlewarePreFunction<T & T_QueryWithHelpers<T>>;
@@ -109,17 +108,17 @@ export interface I_PaginateOptionsWithPopulate extends T_PaginateOptions, Omit<T
109
108
  populate?: T_Input_Populate;
110
109
  }
111
110
  export interface I_Input_FindOne<T> extends T_PopulateOption {
112
- filter: T_FilterQuery<T>;
111
+ filter: T_QueryFilter<T>;
113
112
  projection?: T_ProjectionType<T>;
114
113
  options?: T_QueryOptions<T>;
115
114
  }
116
115
  export interface I_Input_FindAll<T> extends T_PopulateOption {
117
- filter: T_FilterQuery<T>;
116
+ filter: T_QueryFilter<T>;
118
117
  projection?: T_ProjectionType<T>;
119
118
  options?: T_QueryOptions<T>;
120
119
  }
121
120
  export interface I_Input_FindPaging<T = undefined> {
122
- filter?: T_FilterQuery<T>;
121
+ filter?: T_QueryFilter<T>;
123
122
  options?: I_PaginateOptionsWithPopulate;
124
123
  }
125
124
  export interface I_Input_FindPagingAggregate {
@@ -136,12 +135,12 @@ export interface I_UpdateOptionsExtended extends Omit<QueryOptions, 'session'> {
136
135
  session?: ClientSession;
137
136
  }
138
137
  export interface I_Input_UpdateOne<T> extends T_PopulateOption {
139
- filter: T_FilterQuery<T>;
138
+ filter: T_QueryFilter<T>;
140
139
  update: T_UpdateQuery<T>;
141
140
  options?: I_UpdateOptionsExtended;
142
141
  }
143
142
  export interface I_Input_UpdateMany<T> extends T_PopulateOption {
144
- filter: T_FilterQuery<T>;
143
+ filter: T_QueryFilter<T>;
145
144
  update: T_UpdateQuery<T>;
146
145
  options?: I_UpdateOptionsExtended;
147
146
  }
@@ -149,16 +148,16 @@ export interface I_DeleteOptionsExtended extends Omit<QueryOptions, 'session'> {
149
148
  session?: ClientSession;
150
149
  }
151
150
  export interface I_Input_DeleteOne<T> {
152
- filter: T_FilterQuery<T>;
151
+ filter: T_QueryFilter<T>;
153
152
  options?: I_DeleteOptionsExtended;
154
153
  }
155
154
  export interface I_Input_DeleteMany<T> {
156
- filter: T_FilterQuery<T>;
155
+ filter: T_QueryFilter<T>;
157
156
  options?: I_DeleteOptionsExtended;
158
157
  }
159
158
  export interface I_InputSlug<T> {
160
159
  field: string;
161
- filter?: T_FilterQuery<T>;
160
+ filter?: T_QueryFilter<T>;
162
161
  haveHistory?: boolean;
163
162
  }
164
163
  export interface I_Input_CreateSlug<T> extends I_InputSlug<T> {
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("node:crypto"),J=require("migrate-mongo"),X=require("mongoose-aggregate-paginate-v2"),Y=require("mongoose-paginate-v2"),Z=require("./mongo.constant.cjs"),V=require("../../util/object/object.util.cjs"),tt=require("../../util/common/common.util.cjs"),$=require("../fs/fs.util.cjs"),T=require("../path/path.constant.cjs"),et=require("../../util/validate/validate.util.cjs"),C=require("../../util/string/string.util.cjs"),F=require("../../constant/response-status.cjs"),N=require("../log/log.util.cjs");var rt=Object.defineProperty,st=Object.defineProperties,nt=Object.getOwnPropertyDescriptors,k=Object.getOwnPropertySymbols,it=Object.prototype.hasOwnProperty,ot=Object.prototype.propertyIsEnumerable,z=(n,e,t)=>e in n?rt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,A=(n,e)=>{for(var t in e||(e={}))it.call(e,t)&&z(n,t,e[t]);if(k)for(var t of k(e))ot.call(e,t)&&z(n,t,e[t]);return n},x=(n,e)=>st(n,nt(e)),lt=(n,e,t)=>z(n,typeof e!="symbol"?e+"":e,t),v=(n,e,t)=>new Promise((r,s)=>{var i=c=>{try{l(t.next(c))}catch(a){s(a)}},o=c=>{try{l(t.throw(c))}catch(a){s(a)}},l=c=>c.done?r(c.value):Promise.resolve(c.value).then(i,o);l((t=t.apply(n,e)).next())});function B(n){return n!=null&&typeof n=="object"}function M(n){return n===n.toUpperCase()?n.charAt(0).toUpperCase()+n.slice(1).toLowerCase():n}const P={createGenericFields(){return{id:W.randomUUID(),isDel:!1,createdAt:new Date,updatedAt:new Date}},applyPlugins(n,e){e.filter(t=>typeof t=="function").forEach(t=>n.plugin(t))},applyMiddlewares(n,e){e.forEach(({method:t,pre:r,post:s})=>{t&&r&&n.pre(t,r),t&&s&&n.post(t,s)})},createGenericSchema(n){return new n.Schema({id:{type:String,default:()=>W.randomUUID(),unique:!0},isDel:{type:Boolean,default:!1}},{timestamps:!0})},createSchema({mongoose:n,schema:e,virtuals:t=[],standalone:r=!1}){const s=new n.Schema(e,{toJSON:{virtuals:!0},toObject:{virtuals:!0}});return t.forEach(({name:i,options:o,get:l})=>{if(P.isDynamicVirtual(o)){const c=s.statics;c._dynamicVirtuals||(c._dynamicVirtuals=[]),c._dynamicVirtuals.push({name:i,options:o});const a=s.virtual(i);l?a.get(l):a.get(function(){var u;return((u=this._populated)==null?void 0:u[i])||(o!=null&&o.count?0:o!=null&&o.justOne?null:[])})}else{const c=s.virtual(i,o);l&&c.get(l)}}),r||s.add(P.createGenericSchema(n)),s},createModel({mongoose:n,name:e,schema:t,virtuals:r=[],pagination:s=!0,aggregate:i=!0,middlewares:o=[]}){if(!e)throw new Error("Model name is required.");if(n.models[e])return n.models[e];const l=P.createSchema({mongoose:n,schema:t,virtuals:r});(s||i)&&P.applyPlugins(l,[s&&Y,i&&X]),P.applyMiddlewares(l,o);const c=n.model(e,l);return r.length>0&&(c._virtualConfigs=r),c},validator:{isRequired(){return function(n){return v(this,null,function*(){return!et.validate.isEmpty(n)})}},isUnique(n){return function(e){return v(this,null,function*(){if(!Array.isArray(n)||n.length===0)throw new Error("Fields must be a non-empty array of strings.");const t={$or:n.map(s=>({[s]:e}))};return!(yield this.constructor.exists(t))})}},matchesRegex(n){return e=>v(null,null,function*(){if(!Array.isArray(n)||n.some(t=>!(t instanceof RegExp)))throw new Error("regexArray must be an array of valid RegExp objects.");return n.every(t=>t.test(e))})}},migrate:x(A({},J),{setConfig:n=>{const e=`// This file is automatically generated by the Cyberskill CLI.
2
- module.exports = ${JSON.stringify(n,null,4)}`;$.writeFileSync(T.PATH.MIGRATE_MONGO_CONFIG,e);const t=`
3
- ${T.MIGRATE_MONGO_CONFIG}
4
- `;$.pathExistsSync(T.PATH.GIT_IGNORE)?$.readFileSync(T.PATH.GIT_IGNORE,"utf-8").split(`
5
- `).includes(T.MIGRATE_MONGO_CONFIG)||$.appendFileSync(T.PATH.GIT_IGNORE,t):$.writeFileSync(T.PATH.GIT_IGNORE,t)}}),regexify(n,e){if(!n)return{};let t=V.deepClone(n);if(!e||e.length===0)return t;for(const r of e){const s=r.toString().split("."),i=V.getNestedValue(t,s);if(typeof i=="string"&&i.length>0){const o={$regex:`.*${tt.regexSearchMapper(i)}.*`,$options:"i"};t=V.setNestedValue(t,s,o)}}return t},isDynamicVirtual(n){return!!(n&&typeof n.ref=="function")},getNewRecords(n,e,t){return v(this,null,function*(){const r=yield n.findAll({});return r.success?e.filter(i=>!r.result.some(o=>t(o,i))):e})},getExistingRecords(n,e,t){return v(this,null,function*(){const r=yield n.findAll({});return r.success?r.result.filter(i=>e.some(o=>t(i,o))):[]})}};function U(n,e){if(!n||!e||e.length===0)return n;const t=new Set(e.map(r=>r.name));if(Array.isArray(n)){const r=n.filter(s=>{if(typeof s=="string")return!Array.from(t).some(i=>s===i||s.startsWith(`${i}.`));if(typeof s=="object"&&s!==null){const i=s,o=i.path||i.populate||"";return!Array.from(t).some(l=>o===l||o.startsWith(`${l}.`))}return!0});return r.length>0?r:void 0}if(typeof n=="string")return Array.from(t).some(r=>n===r||n.startsWith(`${r}.`))?void 0:n;if(typeof n=="object"&&n!==null){const r=n,s=r.path||r.populate||"";return Array.from(t).some(i=>s===i||s.startsWith(`${i}.`))?void 0:n}return n}function ct(n,e,t){if(!n.length||!e||!(t!=null&&t.ref))return[];const r=new Map;return n.forEach(s=>{try{const i=t.ref(s);if(i==null)return;const o=typeof i=="string"?i:String(i);if(o&&o.trim()!==""){const l=M(o);r.has(l)||r.set(l,[]),r.get(l).push(s)}}catch(i){N.catchError(new Error(`Dynamic ref function failed for virtual "${e}": ${i instanceof Error?i.message:String(i)}`))}}),Array.from(r.entries()).map(([s,i])=>({model:s,docs:i}))}function ut(n){return n!==null&&typeof n=="object"&&"toObject"in n&&typeof n.toObject=="function"}function L(n,e,t,r,s){return v(this,null,function*(){if(!e.length||!t)return e;const i=Array.isArray(t)?t:[t];for(const o of i)typeof o=="string"?yield Q(n,e,o,r,s):o&&typeof o=="object"&&(yield at(n,e,o,r,s));return e})}function Q(n,e,t,r,s){return v(this,null,function*(){var i,o,l,c;const a=t.split(".");if(a.length<2){for(const y of e)yield G(n,y,t,r,void 0,s);return}const u=a[0];if(!u||u.trim()==="")return;const p=a.slice(1).join(".");for(const y of e){const O=y,E=O[u];if(E&&typeof E=="object"){let g=s;const h=g;if(s&&s.schema&&s.schema.virtuals){const f=s.schema.virtuals[u];if(f&&f.options&&f.options.ref){let S;if(typeof f.options.ref=="function"?S=f.options.ref(O):typeof f.options.ref=="string"&&(S=f.options.ref),S){const d=M(S);n.models[d]&&(g=n.models[d])}}}if(!g){const f=(o=(i=s==null?void 0:s.schema)==null?void 0:i.statics)!=null?o:{},d=((s==null?void 0:s._virtualConfigs)||f._dynamicVirtuals||[]).find(m=>m.name===u);if(d&&d.options&&d.options.ref){let m;if(typeof d.options.ref=="function"?m=d.options.ref(O):typeof d.options.ref=="string"&&(m=d.options.ref),m){const j=M(m);n.models[j]&&(g=n.models[j])}}}if(g===h){const f=(c=(l=s==null?void 0:s.schema)==null?void 0:l.statics)!=null?c:{},d=((s==null?void 0:s._virtualConfigs)||f._dynamicVirtuals||[]).find(m=>m.name===u);if(d&&d.options&&d.options.ref){let m;if(typeof d.options.ref=="function"?m=d.options.ref(O):typeof d.options.ref=="string"&&(m=d.options.ref),m){const j=M(m);n.models[j]&&(g=n.models[j])}}}if(Array.isArray(E))for(const f of E)f&&typeof f=="object"&&(yield G(n,f,p,r,u,g));else E&&typeof E=="object"&&(yield G(n,E,p,r,u,g))}}})}function at(n,e,t,r,s){return v(this,null,function*(){const{path:i,populate:o}=t;if(!i)return;if(!o){yield Q(n,e,i,r,s);return}const l=i;for(const c of e){const a=c,u=a[l];let p=s;if(s&&s.schema&&s.schema.virtuals){const y=s.schema.virtuals[l];if(y&&y.options&&y.options.ref){let O;if(typeof y.options.ref=="function"?O=y.options.ref(a):typeof y.options.ref=="string"&&(O=y.options.ref),O){const E=M(O);n.models[E]&&(p=n.models[E])}}}if(!p&&typeof u=="object"&&u&&"entityType"in u){const y=M(String(u.entityType));n.models[y]&&(p=n.models[y])}if(u&&typeof u=="object")if(Array.isArray(u))for(const y of u)y&&typeof y=="object"&&(yield L(n,[y],o,r,p));else u&&typeof u=="object"&&(yield L(n,[u],o,r,p))}})}function q(n,e,t,r){if(!t||!e||!e.schema)return;const s=t.split(".");let i=e.schema;for(let o=0;o<s.length;o++){const l=s[o];if(i&&i.virtuals&&l){const c=i.virtuals[l];if(c&&c.options&&c.options.ref){let a;if(typeof c.options.ref=="function"?a=c.options.ref(r):typeof c.options.ref=="string"&&(a=c.options.ref),a&&typeof a=="string"){if(o===s.length-1)return a;const u=n.models[a];if(u&&u.schema){i=u.schema;continue}}}}if(i&&i.paths&&l){const c=i.paths[l];if(c&&c.schema){i=c.schema;continue}}return}}function ft(n,e){if(e)for(const t of Object.keys(n.models)){const r=n.models[t],s=r==null?void 0:r.schema;if(s&&(s.paths&&s.paths[e]||s.virtuals&&s.virtuals[e]))return r}}function dt(n,e){const t=(e||"").split(".")[0]||"";if(t)for(const r of Object.keys(n.models)){const s=n.models[r],i=s==null?void 0:s.schema;if(i&&(i.paths&&i.paths[t]||i.virtuals&&i.virtuals[t]))return s}}function G(n,e,t,r,s,i){return v(this,null,function*(){var o,l;let c=e.__t;if(!c){if(i){const g=s?`${s}.${t}`:t,h=(g||"").split(".")[0]||"";let f=i;if(!!!((o=f==null?void 0:f.schema)!=null&&o.paths&&f.schema.paths[h]||(l=f==null?void 0:f.schema)!=null&&l.virtuals&&f.schema.virtuals[h])){const m=dt(n,g);m&&(f=m)}const d=q(n,f,g,e);if(d)c=d;else{const m=(g.includes(".")?g.split(".").pop():g)||"";if(m){const j=ft(n,m);if(j){const R=q(n,j,g,e);R&&(c=R)}}}}if(r&&r.length>0){const g=t.split(".").pop()||"",h=r.find(f=>f.name===g);if(h&&h.options.ref){let f;typeof h.options.ref=="function"?f=h.options.ref(e):typeof h.options.ref=="string"&&(f=h.options.ref),f&&typeof f=="string"&&(c=f)}}if(!c){for(const[g,h]of Object.entries(e))if(g==="entityType"&&typeof h=="string"){c=h;break}if(c&&n.models[c]){const g=n.models[c];if(g&&g.schema){const h=g.schema,f=t.split(".").pop()||"",S=(m,j="root")=>{if(!m||!m.virtuals)return;const R=m.virtuals;for(const _ of Object.keys(R))if(_===f){const b=R[_];if(b&&b.options&&b.options.ref){let D;if(typeof b.options.ref=="function"?D=b.options.ref(e):typeof b.options.ref=="string"&&(D=b.options.ref),D&&typeof D=="string")return D}}if(m.paths)for(const _ of Object.keys(m.paths)){const b=m.paths[_];if(b&&b.schema){const D=S(b.schema,`${j}.${_}`);if(D)return D}}},d=S(h);d&&(c=d)}}}if(!c){const g=t.split(".").pop()||"";if(i&&i.schema){const h=i.schema,f=(d,m="root")=>{if(!d||!d.virtuals)return;const j=d.virtuals;for(const R of Object.keys(j))if(R===g){const _=j[R];if(_&&_.options&&_.options.ref){let b;if(typeof _.options.ref=="function"?b=_.options.ref(e):typeof _.options.ref=="string"&&(b=_.options.ref),b&&typeof b=="string")return b}}if(d.paths)for(const R of Object.keys(d.paths)){const _=d.paths[R];if(_&&_.schema){const b=f(_.schema,`${m}.${R}`);if(b)return b}}},S=f(h);S&&(c=S)}if(!c&&i){const h=q(n,i,t,e);h&&(c=h)}if(!c&&r&&r.length>0){const h=r.find(f=>f.name===g);if(h&&h.options.ref){let f;typeof h.options.ref=="function"?f=h.options.ref(e):typeof h.options.ref=="string"&&(f=h.options.ref),f&&typeof f=="string"&&(c=f)}}}if(!c){const g=t.split(".").pop()||"",h=g?g.charAt(0).toUpperCase()+g.slice(1):"";h&&n.models[h]&&(c=h)}}const a=n.models[c];if(!a)return;const u=`${t}Id`,p=`${t}Ids`,y=e[u]||e[p]||e[t];if(!y)return;const O=Array.isArray(y)?y:[y],E=yield a.find({id:{$in:O}}).lean();E.length>0&&(Array.isArray(y)?e[t]=E:e[t]=E[0])})}function K(n,e,t,r,s,i){return v(this,null,function*(){if(!e.length||!t.length||!r)return e;const o=t.filter(a=>{if(Array.isArray(r))return r.length>0&&r.some(u=>{if(typeof u=="string")return u===a.name||u.startsWith(`${a.name}.`);if(u&&typeof u=="object"){const p=u,y=p.path||p.populate||"";return y===a.name||y.startsWith(`${a.name}.`)}return!1});if(typeof r=="string")return r===a.name||r.startsWith(`${a.name}.`);if(typeof r=="object"&&r!==null){const u=r,p=u.path||u.populate||"";return p===a.name||p.startsWith(`${a.name}.`)}return!1});if(o.length===0)return e;const l=V.deepClone(e.map(a=>ut(a)?a.toObject():a));l.forEach(a=>{o.forEach(({name:u,options:p})=>{u in a||(a[u]=p.count?0:p.justOne?null:[])})});const c=new Map;for(const a of o){const{name:u,options:p}=a,y=ct(l,u,p);for(const O of y){c.has(O.model)||c.set(O.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const E=c.get(O.model);E.virtuals.find(h=>h.name===u)||(E.virtuals.push(a),E.localValueSets.set(u,new Set));const g=E.localValueSets.get(u);O.docs.forEach(h=>{const f=h[p.localField];if(f!=null){const S=String(f);g.add(S);let d=-1;const m=h;m.id!==void 0?d=l.findIndex(j=>j.id===m.id):m._id!==void 0&&(d=l.findIndex(j=>{var R,_,b,D;return((_=(R=j._id)==null?void 0:R.toString)==null?void 0:_.call(R))===((D=(b=m._id)==null?void 0:b.toString)==null?void 0:D.call(b))})),d!==-1&&(E.docsByLocalValue.has(S)||E.docsByLocalValue.set(S,[]),E.docsByLocalValue.get(S).push(d))}})}}if(yield Promise.all(Array.from(c.entries()).map(a=>v(null,[a],function*([u,p]){const y=n.models[u];if(!y)return;const O=new Set;if(p.localValueSets.forEach(S=>{S.forEach(d=>O.add(d))}),O.size===0)return;const E=[...new Set(p.virtuals.map(S=>S.options.foreignField))],g=Array.from(O);let h;E.length===1?h={[String(E[0])]:{$in:g}}:h={$or:E.map(S=>({[S]:{$in:g}}))};const f=yield y.find(h,s).lean();for(const S of p.virtuals){const{name:d,options:m}=S,j=f.filter(R=>{const _=R[m.foreignField];return _!=null&&O.has(String(_))});if(m.count){const R=new Map;j.forEach(_=>{var b;const D=(b=_[m.foreignField])==null?void 0:b.toString();D&&R.set(D,(R.get(D)||0)+1)}),p.localValueSets.get(d).forEach(_=>{const b=p.docsByLocalValue.get(_)||[],D=R.get(_)||0;b.forEach(w=>{const I=l[w];I[d]===void 0&&(I[d]=D)})})}else{const R=new Map;j.forEach(_=>{var b;const D=(b=_[m.foreignField])==null?void 0:b.toString();D&&(R.has(D)||R.set(D,[]),R.get(D).push(_))}),p.localValueSets.get(d).forEach(_=>{const b=p.docsByLocalValue.get(_)||[],D=R.get(_)||[],w=m.justOne?D[0]||null:D;b.forEach(I=>{const H=l[I];H[d]=w})})}}}))),r){const u=(p=>{const y=Array.isArray(p)?p:[p],O=new Map,E=[];for(const h of y)if(typeof h=="string")if(h.includes(".")){const f=h.split("."),S=f[0]||"",d=f.slice(1).join(".");S&&(O.has(S)||O.set(S,[]),d&&O.get(S).push(d))}else E.push(h);else if(h&&typeof h=="object"){const f=h;if(f.path&&f.path.includes(".")){const S=f.path.split("."),d=S[0]||"",m=S.slice(1).join(".");d&&(O.has(d)||O.set(d,[]),m&&O.get(d).push(m),f.populate&&O.get(d).push(f.populate))}else E.push(h)}const g=[...E];return O.forEach((h,f)=>{const S=[];for(const d of h)(typeof d=="string"||d&&typeof d=="object")&&S.push(d);S.length>0?g.push({path:f,populate:S}):g.push(f)}),g})(r);yield L(n,l,u,t,i)}return l})}class ht{constructor(e,t){lt(this,"collection"),this.collection=e.collection(t)}createOne(e){return v(this,null,function*(){try{const t=A(A({},P.createGenericFields()),e);return(yield this.collection.insertOne(t)).acknowledged?{success:!0,message:"Document created successfully",result:t}:{success:!1,message:"Document creation failed",code:F.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(t){return N.catchError(t)}})}createMany(e){return v(this,null,function*(){try{const t=e.map(s=>A(A({},P.createGenericFields()),s)),r=yield this.collection.insertMany(t);return r.insertedCount===0?{success:!1,message:"No documents were inserted",code:F.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:`${r.insertedCount} documents created successfully`,result:t}}catch(t){return N.catchError(t)}})}findOne(e){return v(this,null,function*(){try{const t=yield this.collection.findOne(e);return t?{success:!0,message:"Document found",result:t}:{success:!1,message:"Document not found",code:F.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(t){return N.catchError(t)}})}findAll(){return v(this,arguments,function*(e={}){try{return{success:!0,message:"Documents retrieved successfully",result:yield this.collection.find(e).toArray()}}catch(t){return N.catchError(t)}})}count(){return v(this,arguments,function*(e={}){try{const t=yield this.collection.countDocuments(e);return{success:!0,message:`${t} documents counted successfully`,result:t}}catch(t){return N.catchError(t)}})}updateOne(e,t){return v(this,null,function*(){try{const r=yield this.collection.updateOne(e,{$set:t});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:F.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document updated successfully",result:r}}catch(r){return N.catchError(r)}})}updateMany(e,t){return v(this,null,function*(){try{const r=yield this.collection.updateMany(e,{$set:t});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:F.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents updated successfully",result:r}}catch(r){return N.catchError(r)}})}deleteOne(e){return v(this,null,function*(){try{const t=yield this.collection.deleteOne(e);return t.deletedCount===0?{success:!1,message:"No documents matched the filter",code:F.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document deleted successfully",result:t}}catch(t){return N.catchError(t)}})}deleteMany(e){return v(this,null,function*(){try{const t=yield this.collection.deleteMany(e);return t.deletedCount===0?{success:!1,message:"No documents matched the filter",code:F.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents deleted successfully",result:t}}catch(t){return N.catchError(t)}})}}class pt{constructor(e){this.model=e}getModelName(){return this.model.modelName}getDynamicVirtuals(){if(this.model._virtualConfigs){const r=this.model._virtualConfigs.filter(s=>{var i;return typeof((i=s.options)==null?void 0:i.ref)=="function"});if(r.length>0)return r}return this.model.schema.statics._dynamicVirtuals}populateDynamicVirtualsForDocument(e,t){return v(this,null,function*(){const r=this.getDynamicVirtuals();if(r&&r.length>0){const s=yield K(this.model.base,[e],r,t,void 0,this.model);return s&&s[0]?s[0]:e}return e})}populateDynamicVirtualsForDocuments(e,t){return v(this,null,function*(){const r=this.getDynamicVirtuals();return r&&r.length>0&&e.length>0?yield K(this.model.base,e,r,t,void 0,this.model):e})}findOne(){return v(this,arguments,function*(e={},t={},r={},s){var i,o;try{const l=V.normalizeMongoFilter(e),c=this.model.findOne(l,t,r),a=this.getDynamicVirtuals(),u=U(s,a);u&&c.populate(u);const p=yield c.exec();if(!p)return{success:!1,message:`No ${this.getModelName()} found.`,code:F.RESPONSE_STATUS.NOT_FOUND.CODE};const y=yield this.populateDynamicVirtualsForDocument(p,s);return{success:!0,result:(o=(i=y==null?void 0:y.toObject)==null?void 0:i.call(y))!=null?o:y}}catch(l){return N.catchError(l)}})}findAll(){return v(this,arguments,function*(e={},t={},r={},s){try{const i=V.normalizeMongoFilter(e),o=this.model.find(i,t,r),l=this.getDynamicVirtuals(),c=U(s,l);c&&o.populate(c);const a=yield o.exec();return{success:!0,result:(yield this.populateDynamicVirtualsForDocuments(a,s)).map(p=>{var y,O;return(O=(y=p==null?void 0:p.toObject)==null?void 0:y.call(p))!=null?O:p})}}catch(i){return N.catchError(i)}})}findPaging(){return v(this,arguments,function*(e={},t={}){try{const r=V.normalizeMongoFilter(e),s=this.getDynamicVirtuals(),i=A({},t);t.populate&&(i.populate=U(t.populate,s));const o=yield this.model.paginate(r,i);if(s&&s.length>0){const l=yield this.populateDynamicVirtualsForDocuments(o.docs,t.populate);return{success:!0,result:x(A({},o),{docs:l.map(c=>{var a,u;return(u=(a=c==null?void 0:c.toObject)==null?void 0:a.call(c))!=null?u:c})})}}return{success:!0,result:x(A({},o),{docs:o.docs.map(l=>{var c,a;return(a=(c=l==null?void 0:l.toObject)==null?void 0:c.call(l))!=null?a:l})})}}catch(r){return N.catchError(r)}})}findPagingAggregate(e){return v(this,arguments,function*(t,r={}){try{const s=this.getDynamicVirtuals(),i=A({},r);r.populate&&(i.populate=U(r.populate,s));const o=yield this.model.aggregatePaginate(this.model.aggregate(t),i),l=yield this.populateDynamicVirtualsForDocuments(o.docs,r.populate);return{success:!0,result:x(A({},o),{docs:l.map(c=>{var a,u;return(u=(a=c==null?void 0:c.toObject)==null?void 0:a.call(c))!=null?u:c})})}}catch(s){return N.catchError(s)}})}count(){return v(this,arguments,function*(e={}){try{const t=V.normalizeMongoFilter(e);return{success:!0,result:yield this.model.countDocuments(t)}}catch(t){return N.catchError(t)}})}createOne(e){return v(this,null,function*(){var t,r;try{const s=yield this.model.create(e);return{success:!0,result:(r=(t=s==null?void 0:s.toObject)==null?void 0:t.call(s))!=null?r:s}}catch(s){return N.catchError(s)}})}createMany(e){return v(this,arguments,function*(t,r={}){try{return{success:!0,result:(yield this.model.insertMany(t,r)).map(i=>{var o,l;return(l=(o=i==null?void 0:i.toObject)==null?void 0:o.call(i))!=null?l:i})}}catch(s){return N.catchError(s)}})}updateOne(){return v(this,arguments,function*(e={},t={},r={}){var s,i;try{const o=V.normalizeMongoFilter(e),l=yield this.model.findOneAndUpdate(o,t,A({new:!0},r)).exec();return l?{success:!0,result:(i=(s=l==null?void 0:l.toObject)==null?void 0:s.call(l))!=null?i:l}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:F.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(o){return N.catchError(o)}})}updateMany(){return v(this,arguments,function*(e={},t={},r={}){try{const s=V.normalizeMongoFilter(e);return{success:!0,result:yield this.model.updateMany(s,t,r).exec()}}catch(s){return N.catchError(s)}})}deleteOne(){return v(this,arguments,function*(e={},t={}){var r,s;try{const i=V.normalizeMongoFilter(e),o=yield this.model.findOneAndDelete(i,t).exec();return o?{success:!0,result:(s=(r=o==null?void 0:o.toObject)==null?void 0:r.call(o))!=null?s:o}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:F.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(i){return N.catchError(i)}})}deleteMany(){return v(this,arguments,function*(e={},t={}){try{const r=V.normalizeMongoFilter(e),s=yield this.model.deleteMany(r,t).exec();return s.deletedCount===0?{success:!1,message:"No documents found to delete.",code:F.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:s}}catch(r){return N.catchError(r)}})}createShortId(e,t=4){return v(this,null,function*(){try{const s=Array.from({length:10},(l,c)=>C.generateShortId(e,c+t)),o=(yield Promise.all(s.map(l=>this.model.exists({shortId:l})))).findIndex(l=>!l);if(o!==-1){const l=s[o];if(l)return{success:!0,result:l}}return{success:!1,message:"Failed to create a unique shortId",code:F.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return N.catchError(r)}})}createSlugQuery({slug:e,field:t,isObject:r,haveHistory:s=!1,filter:i}){const o=A({},i!=null?i:{});return r?x(A({},o),{$or:[{[`slug.${t}`]:e},...s?[{slugHistory:{$elemMatch:{[`slug.${t}`]:e}}}]:[]]}):x(A({},o),{$or:[{slug:e},...s?[{slugHistory:e}]:[]]})}createUniqueSlug(e){return v(this,arguments,function*({slug:t,field:r,isObject:s,haveHistory:i,filter:o}){if(!t||typeof t!="string")throw new Error("Invalid slug provided: must be a non-empty string");const l=C.generateSlug(t);if(!(yield this.model.exists(this.createSlugQuery({slug:l,field:r,isObject:s,haveHistory:i,filter:o}))))return l;for(let p=1;p<=Z.MONGO_SLUG_MAX_ATTEMPTS;p++){const y=`${l}-${p}`;if(!(yield this.model.exists(this.createSlugQuery({slug:y,field:r,isObject:s,haveHistory:i,filter:o}))))return y}const a=Date.now(),u=Math.random().toString(36).substring(2,8);return`${l}-${a}-${u}`})}createSlug(e){return v(this,arguments,function*({field:t,from:r,filter:s,haveHistory:i}){try{const o=r[t];return B(o)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(o).map(u=>v(this,[u],function*([p,y]){const O=yield this.createUniqueSlug({slug:y,field:p,isObject:!0,haveHistory:i,filter:s});return[p,O]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:o,field:t,isObject:!1,haveHistory:i,filter:s})}}catch(o){return N.catchError(o)}})}checkSlug(e){return v(this,arguments,function*({slug:t,field:r,from:s,filter:i,haveHistory:o}){try{const l=s[r];if(B(l)){const y=Object.values(l).map(E=>C.generateSlug(E));return(yield Promise.all(y.map(E=>this.model.exists(this.createSlugQuery({slug:E,field:r,isObject:!0,haveHistory:o,filter:i}))))).some(E=>E)?{success:!0,result:!0}:{success:!0,result:!1}}const a=C.generateSlug(t);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:a,field:r,isObject:!1,filter:i})))!==null}}catch(l){return N.catchError(l)}})}aggregate(e){return v(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(e)}}catch(t){return N.catchError(t)}})}distinct(e){return v(this,arguments,function*(t,r={},s={}){try{return{success:!0,result:yield this.model.distinct(t,r,s)}}catch(i){return N.catchError(i)}})}}exports.MongoController=ht;exports.MongooseController=pt;exports.mongo=P;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("migrate-mongo"),U=require("mongoose-aggregate-paginate-v2"),k=require("mongoose-paginate-v2"),$=require("node:crypto"),F=require("../../util/object/object.util.cjs"),B=require("../../util/common/common.util.cjs"),E=require("../fs/fs.util.cjs"),w=require("../path/path.constant.cjs"),H=require("../../util/validate/validate.util.cjs");var J=Object.defineProperty,K=Object.defineProperties,L=Object.getOwnPropertyDescriptors,q=Object.getOwnPropertySymbols,M=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable,D=(t,i,e)=>i in t?J(t,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[i]=e,Q=(t,i)=>{for(var e in i||(i={}))M.call(i,e)&&D(t,e,i[e]);if(q)for(var e of q(i))z.call(i,e)&&D(t,e,i[e]);return t},W=(t,i)=>K(t,L(i)),R=(t,i,e)=>new Promise((o,r)=>{var n=s=>{try{y(e.next(s))}catch(h){r(h)}},l=s=>{try{y(e.throw(s))}catch(h){r(h)}},y=s=>s.done?o(s.value):Promise.resolve(s.value).then(n,l);y((e=e.apply(t,i)).next())});function P(t){return t===t.toUpperCase()?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():t}const I={createGenericFields(){return{id:$.randomUUID(),isDel:!1,createdAt:new Date,updatedAt:new Date}},applyPlugins(t,i){i.filter(e=>typeof e=="function").forEach(e=>t.plugin(e))},applyMiddlewares(t,i){i.forEach(({method:e,pre:o,post:r})=>{e&&o&&t.pre(e,o),e&&r&&t.post(e,r)})},createGenericSchema(t){return new t.Schema({id:{type:String,default:()=>$.randomUUID(),unique:!0},isDel:{type:Boolean,default:!1}},{timestamps:!0})},createSchema({mongoose:t,schema:i,virtuals:e=[],standalone:o=!1}){const r=new t.Schema(i,{toJSON:{virtuals:!0},toObject:{virtuals:!0}});return e.forEach(({name:n,options:l,get:y})=>{if(I.isDynamicVirtual(l)){const s=r.statics;s._dynamicVirtuals||(s._dynamicVirtuals=[]),s._dynamicVirtuals.push({name:n,options:l});const h=r.virtual(n);y?h.get(y):h.get(function(){var u;return((u=this._populated)==null?void 0:u[n])||(l!=null&&l.count?0:l!=null&&l.justOne?null:[])})}else{const s=r.virtual(n,l);y&&s.get(y)}}),o||r.add(I.createGenericSchema(t)),r},createModel({mongoose:t,name:i,schema:e,virtuals:o=[],pagination:r=!0,aggregate:n=!0,middlewares:l=[]}){if(!i)throw new Error("Model name is required.");if(t.models[i])return t.models[i];const y=I.createSchema({mongoose:t,schema:e,virtuals:o});(r||n)&&I.applyPlugins(y,[r&&k,n&&U]),I.applyMiddlewares(y,l);const s=t.model(i,y);return o.length>0&&(s._virtualConfigs=o),s},validator:{isRequired(){return function(t){return R(this,null,function*(){return!H.validate.isEmpty(t)})}},isUnique(t){return function(i){return R(this,null,function*(){if(!Array.isArray(t)||t.length===0)throw new Error("Fields must be a non-empty array of strings.");const e={$or:t.map(r=>({[r]:i}))};return!(yield this.constructor.exists(e))})}},matchesRegex(t){return i=>R(null,null,function*(){if(!Array.isArray(t)||t.some(e=>!(e instanceof RegExp)))throw new Error("regexArray must be an array of valid RegExp objects.");return t.every(e=>e.test(i))})}},migrate:W(Q({},T),{setConfig:t=>{const i=`// This file is automatically generated by the Cyberskill CLI.
2
+ module.exports = ${JSON.stringify(t,null,4)}`;E.writeFileSync(w.PATH.MIGRATE_MONGO_CONFIG,i);const e=`
3
+ ${w.MIGRATE_MONGO_CONFIG}
4
+ `;E.pathExistsSync(w.PATH.GIT_IGNORE)?E.readFileSync(w.PATH.GIT_IGNORE,"utf-8").split(`
5
+ `).includes(w.MIGRATE_MONGO_CONFIG)||E.appendFileSync(w.PATH.GIT_IGNORE,e):E.writeFileSync(w.PATH.GIT_IGNORE,e)}}),regexify(t,i){if(!t)return{};let e=F.deepClone(t);if(!i||i.length===0)return e;for(const o of i){const r=o.toString().split("."),n=F.getNestedValue(e,r);if(typeof n=="string"&&n.length>0){const l={$regex:`.*${B.regexSearchMapper(n)}.*`,$options:"i"};e=F.setNestedValue(e,r,l)}}return e},isDynamicVirtual(t){return!!(t&&typeof t.ref=="function")},getNewRecords(t,i,e){return R(this,null,function*(){const o=yield t.findAll({});return o.success?i.filter(n=>!o.result.some(l=>e(l,n))):i})},getExistingRecords(t,i,e){return R(this,null,function*(){const o=yield t.findAll({});return o.success?o.result.filter(n=>i.some(l=>e(n,l))):[]})}};function x(t,i,e,o,r){return R(this,null,function*(){if(!i.length||!e)return i;const n=Array.isArray(e)?e:[e];for(const l of n)typeof l=="string"?yield C(t,i,l,o,r):l&&typeof l=="object"&&(yield X(t,i,l,o,r));return i})}function C(t,i,e,o,r){return R(this,null,function*(){var n,l,y,s;const h=e.split(".");if(h.length<2){for(const m of i)yield V(t,m,e,o,void 0,r);return}const u=h[0];if(!u||u.trim()==="")return;const S=h.slice(1).join(".");for(const m of i){const N=m,O=N[u];if(O&&typeof O=="object"){let c=r;const a=c;if(r&&r.schema&&r.schema.virtuals){const f=r.schema.virtuals[u];if(f&&f.options&&f.options.ref){let g;if(typeof f.options.ref=="function"?g=f.options.ref(N):typeof f.options.ref=="string"&&(g=f.options.ref),g){const p=P(g);t.models[p]&&(c=t.models[p])}}}if(!c){const f=(l=(n=r==null?void 0:r.schema)==null?void 0:n.statics)!=null?l:{},p=((r==null?void 0:r._virtualConfigs)||f._dynamicVirtuals||[]).find(d=>d.name===u);if(p&&p.options&&p.options.ref){let d;if(typeof p.options.ref=="function"?d=p.options.ref(N):typeof p.options.ref=="string"&&(d=p.options.ref),d){const b=P(d);t.models[b]&&(c=t.models[b])}}}if(c===a){const f=(s=(y=r==null?void 0:r.schema)==null?void 0:y.statics)!=null?s:{},p=((r==null?void 0:r._virtualConfigs)||f._dynamicVirtuals||[]).find(d=>d.name===u);if(p&&p.options&&p.options.ref){let d;if(typeof p.options.ref=="function"?d=p.options.ref(N):typeof p.options.ref=="string"&&(d=p.options.ref),d){const b=P(d);t.models[b]&&(c=t.models[b])}}}if(Array.isArray(O))for(const f of O)f&&typeof f=="object"&&(yield V(t,f,S,o,u,c));else O&&typeof O=="object"&&(yield V(t,O,S,o,u,c))}}})}function X(t,i,e,o,r){return R(this,null,function*(){const{path:n,populate:l}=e;if(!n)return;if(!l){yield C(t,i,n,o,r);return}const y=n;for(const s of i){const h=s,u=h[y];let S=r;if(r&&r.schema&&r.schema.virtuals){const m=r.schema.virtuals[y];if(m&&m.options&&m.options.ref){let N;if(typeof m.options.ref=="function"?N=m.options.ref(h):typeof m.options.ref=="string"&&(N=m.options.ref),N){const O=P(N);t.models[O]&&(S=t.models[O])}}}if(!S&&typeof u=="object"&&u&&"entityType"in u){const m=P(String(u.entityType));t.models[m]&&(S=t.models[m])}if(u&&typeof u=="object")if(Array.isArray(u))for(const m of u)m&&typeof m=="object"&&(yield x(t,[m],l,o,S));else u&&typeof u=="object"&&(yield x(t,[u],l,o,S))}})}function G(t,i,e,o){if(!e||!i||!i.schema)return;const r=e.split(".");let n=i.schema;for(let l=0;l<r.length;l++){const y=r[l];if(n&&n.virtuals&&y){const s=n.virtuals[y];if(s&&s.options&&s.options.ref){let h;if(typeof s.options.ref=="function"?h=s.options.ref(o):typeof s.options.ref=="string"&&(h=s.options.ref),h&&typeof h=="string"){if(l===r.length-1)return h;const u=t.models[h];if(u&&u.schema){n=u.schema;continue}}}}if(n&&n.paths&&y){const s=n.paths[y];if(s&&s.schema){n=s.schema;continue}}return}}function Y(t,i){if(i)for(const e of Object.keys(t.models)){const o=t.models[e],r=o==null?void 0:o.schema;if(r&&(r.paths&&r.paths[i]||r.virtuals&&r.virtuals[i]))return o}}function Z(t,i){const e=(i||"").split(".")[0]||"";if(e)for(const o of Object.keys(t.models)){const r=t.models[o],n=r==null?void 0:r.schema;if(n&&(n.paths&&n.paths[e]||n.virtuals&&n.virtuals[e]))return r}}function V(t,i,e,o,r,n){return R(this,null,function*(){var l,y;let s=i.__t;if(!s){if(n){const c=r?`${r}.${e}`:e,a=(c||"").split(".")[0]||"";let f=n;if(!!!((l=f==null?void 0:f.schema)!=null&&l.paths&&f.schema.paths[a]||(y=f==null?void 0:f.schema)!=null&&y.virtuals&&f.schema.virtuals[a])){const d=Z(t,c);d&&(f=d)}const p=G(t,f,c,i);if(p)s=p;else{const d=(c.includes(".")?c.split(".").pop():c)||"";if(d){const b=Y(t,d);if(b){const j=G(t,b,c,i);j&&(s=j)}}}}if(o&&o.length>0){const c=e.split(".").pop()||"",a=o.find(f=>f.name===c);if(a&&a.options.ref){let f;typeof a.options.ref=="function"?f=a.options.ref(i):typeof a.options.ref=="string"&&(f=a.options.ref),f&&typeof f=="string"&&(s=f)}}if(!s){for(const[c,a]of Object.entries(i))if(c==="entityType"&&typeof a=="string"){s=a;break}if(s&&t.models[s]){const c=t.models[s];if(c&&c.schema){const a=c.schema,f=e.split(".").pop()||"",g=(d,b="root")=>{if(!d||!d.virtuals)return;const j=d.virtuals;for(const _ of Object.keys(j))if(_===f){const v=j[_];if(v&&v.options&&v.options.ref){let A;if(typeof v.options.ref=="function"?A=v.options.ref(i):typeof v.options.ref=="string"&&(A=v.options.ref),A&&typeof A=="string")return A}}if(d.paths)for(const _ of Object.keys(d.paths)){const v=d.paths[_];if(v&&v.schema){const A=g(v.schema,`${b}.${_}`);if(A)return A}}},p=g(a);p&&(s=p)}}}if(!s){const c=e.split(".").pop()||"";if(n&&n.schema){const a=n.schema,f=(p,d="root")=>{if(!p||!p.virtuals)return;const b=p.virtuals;for(const j of Object.keys(b))if(j===c){const _=b[j];if(_&&_.options&&_.options.ref){let v;if(typeof _.options.ref=="function"?v=_.options.ref(i):typeof _.options.ref=="string"&&(v=_.options.ref),v&&typeof v=="string")return v}}if(p.paths)for(const j of Object.keys(p.paths)){const _=p.paths[j];if(_&&_.schema){const v=f(_.schema,`${d}.${j}`);if(v)return v}}},g=f(a);g&&(s=g)}if(!s&&n){const a=G(t,n,e,i);a&&(s=a)}if(!s&&o&&o.length>0){const a=o.find(f=>f.name===c);if(a&&a.options.ref){let f;typeof a.options.ref=="function"?f=a.options.ref(i):typeof a.options.ref=="string"&&(f=a.options.ref),f&&typeof f=="string"&&(s=f)}}}if(!s){const c=e.split(".").pop()||"",a=c?c.charAt(0).toUpperCase()+c.slice(1):"";a&&t.models[a]&&(s=a)}}const h=t.models[s];if(!h)return;const u=`${e}Id`,S=`${e}Ids`,m=i[u]||i[S]||i[e];if(!m)return;const N=Array.isArray(m)?m:[m],O=yield h.find({id:{$in:N}}).lean();O.length>0&&(Array.isArray(m)?i[e]=O:i[e]=O[0])})}exports.applyNestedPopulate=x;exports.convertEnumToModelName=P;exports.mongo=I;
@@ -1,7 +1,15 @@
1
1
  import { default as mongooseRaw } from 'mongoose';
2
2
  import { default as migrate } from 'migrate-mongo';
3
- import { I_Return } from '../../typescript/index.js';
4
- import { C_Db, C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DeleteOptionsExtended, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_Input_CheckSlug, I_Input_CreateSlug, I_Input_GenerateSlug, I_MongooseModelMiddleware, I_PaginateOptionsWithPopulate, I_UpdateOptionsExtended, T_AggregatePaginateResult, T_DeleteResult, T_Filter, T_FilterQuery, T_Input_Populate, T_InsertManyOptions, T_MongoosePlugin, T_MongooseShema, T_PaginateResult, T_PipelineStage, T_ProjectionType, T_QueryOptions, T_UpdateQuery, T_UpdateResult, T_VirtualOptions, T_WithId } from './mongo.type.js';
3
+ import { MongoController } from './mongo.controller.js';
4
+ import { C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DynamicVirtualConfig, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_MongooseModelMiddleware, T_Input_Populate, T_MongoosePlugin, T_MongooseShema, T_QueryFilter, T_VirtualOptions, T_WithId } from './mongo.type.js';
5
+ /**
6
+ * Converts enum values to proper model names.
7
+ * Handles common naming conventions like converting 'USER' to 'User'.
8
+ *
9
+ * @param enumValue - The enum value to convert
10
+ * @returns The converted model name
11
+ */
12
+ export declare function convertEnumToModelName(enumValue: string): string;
5
13
  /**
6
14
  * MongoDB utility object providing comprehensive database operations and utilities.
7
15
  * This object contains methods for creating generic fields, applying plugins and middlewares,
@@ -150,6 +158,8 @@ export declare const mongo: {
150
158
  _id: mongooseRaw.Types.ObjectId;
151
159
  } & {
152
160
  __v: number;
161
+ } & {
162
+ id: string;
153
163
  }, any, unknown>>(name: string): ModelType;
154
164
  <ModelType = mongooseRaw.Model<any, {}, {}, {}, any, any, any>>(): ModelType;
155
165
  } | undefined, I_GenericDocument, mongooseRaw.Document<unknown, {}, I_GenericDocument, {}, mongooseRaw.ResolveSchemaOptions<mongooseRaw.DefaultSchemaOptions>> & I_GenericDocument & Required<{
@@ -319,6 +329,8 @@ export declare const mongo: {
319
329
  _id: mongooseRaw.Types.ObjectId;
320
330
  } & {
321
331
  __v: number;
332
+ } & {
333
+ id: string;
322
334
  }, any, unknown>>(name: string): ModelType;
323
335
  <ModelType = mongooseRaw.Model<any, {}, {}, {}, any, any, any>>(): ModelType;
324
336
  } | undefined, I_GenericDocument, mongooseRaw.Document<unknown, {}, I_GenericDocument, {}, mongooseRaw.ResolveSchemaOptions<mongooseRaw.DefaultSchemaOptions>> & I_GenericDocument & Required<{
@@ -988,7 +1000,7 @@ export declare const mongo: {
988
1000
  * @param fields - An array of field names to convert to regex patterns.
989
1001
  * @returns A new filter object with string values converted to regex patterns.
990
1002
  */
991
- regexify<T>(filter?: T_FilterQuery<T>, fields?: (keyof T | string)[]): T_FilterQuery<T>;
1003
+ regexify<T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]): T_QueryFilter<T>;
992
1004
  /**
993
1005
  * Checks if a virtual options object has a dynamic ref function.
994
1006
  *
@@ -1014,316 +1026,15 @@ export declare const mongo: {
1014
1026
  getExistingRecords<T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean): Promise<T_WithId<T>[]>;
1015
1027
  };
1016
1028
  /**
1017
- * MongoDB native driver controller for direct database operations.
1018
- * This class provides a simplified interface for MongoDB operations using the native driver,
1019
- * with automatic generic field generation and standardized response formatting.
1029
+ * Recursively applies nested populate options to populated documents.
1030
+ * This function handles cases where a populated field needs further population.
1031
+ *
1032
+ * @template T - The document type
1033
+ * @param mongoose - The Mongoose instance
1034
+ * @param documents - The documents to apply nested populations to
1035
+ * @param populateOptions - The populate options to apply
1036
+ * @param virtualConfigs - Optional virtual configurations for model inference
1037
+ * @param currentModel - The current model context (which model's schema to search for virtuals)
1038
+ * @returns Promise with documents that have nested populations applied
1020
1039
  */
1021
- export declare class MongoController<D extends Partial<C_Document>> {
1022
- private collection;
1023
- /**
1024
- * Creates a new MongoDB controller instance.
1025
- *
1026
- * @param db - The MongoDB database instance.
1027
- * @param collectionName - The name of the collection to operate on.
1028
- */
1029
- constructor(db: C_Db, collectionName: string);
1030
- /**
1031
- * Creates a single document in the collection.
1032
- * This method adds generic fields (id, isDel, timestamps) to the document before insertion.
1033
- *
1034
- * @param document - The document to create, with or without generic fields.
1035
- * @returns A promise that resolves to a standardized response with the created document.
1036
- */
1037
- createOne(document: D | Partial<D>): Promise<I_Return<D | Partial<D>>>;
1038
- /**
1039
- * Creates multiple documents in the collection.
1040
- * This method adds generic fields to each document before bulk insertion.
1041
- *
1042
- * @param documents - An array of documents to create.
1043
- * @returns A promise that resolves to a standardized response with the created documents.
1044
- */
1045
- createMany(documents: (D | Partial<D>)[]): Promise<I_Return<(D | Partial<D>)[]>>;
1046
- /**
1047
- * Finds a single document by filter criteria.
1048
- *
1049
- * @param filter - The filter criteria to find the document.
1050
- * @returns A promise that resolves to a standardized response with the found document.
1051
- */
1052
- findOne(filter: T_Filter<D>): Promise<I_Return<T_WithId<D>>>;
1053
- /**
1054
- * Finds all documents matching the filter criteria.
1055
- *
1056
- * @param filter - The filter criteria to find documents (defaults to empty object for all documents).
1057
- * @returns A promise that resolves to a standardized response with the found documents.
1058
- */
1059
- findAll(filter?: T_Filter<D>): Promise<I_Return<T_WithId<D>[]>>;
1060
- /**
1061
- * Counts documents matching the filter criteria.
1062
- *
1063
- * @param filter - The filter criteria to count documents (defaults to empty object for all documents).
1064
- * @returns A promise that resolves to a standardized response with the document count.
1065
- */
1066
- count(filter?: T_Filter<D>): Promise<I_Return<number>>;
1067
- /**
1068
- * Updates a single document matching the filter criteria.
1069
- *
1070
- * @param filter - The filter criteria to find the document to update.
1071
- * @param update - The update data to apply to the document.
1072
- * @returns A promise that resolves to a standardized response with the update result.
1073
- */
1074
- updateOne(filter: T_Filter<D>, update: Partial<D>): Promise<I_Return<T_UpdateResult>>;
1075
- /**
1076
- * Updates multiple documents matching the filter criteria.
1077
- *
1078
- * @param filter - The filter criteria to find documents to update.
1079
- * @param update - The update data to apply to the documents.
1080
- * @returns A promise that resolves to a standardized response with the update result.
1081
- */
1082
- updateMany(filter: T_Filter<D>, update: Partial<D>): Promise<I_Return<T_UpdateResult>>;
1083
- /**
1084
- * Deletes a single document matching the filter criteria.
1085
- *
1086
- * @param filter - The filter criteria to find the document to delete.
1087
- * @returns A promise that resolves to a standardized response with the delete result.
1088
- */
1089
- deleteOne(filter: T_Filter<D>): Promise<I_Return<T_DeleteResult>>;
1090
- /**
1091
- * Deletes multiple documents matching the filter criteria.
1092
- *
1093
- * @param filter - The filter criteria to find documents to delete.
1094
- * @returns A promise that resolves to a standardized response with the delete result.
1095
- */
1096
- deleteMany(filter: T_Filter<D>): Promise<I_Return<T_DeleteResult>>;
1097
- }
1098
- /**
1099
- * Mongoose controller for database operations with advanced features.
1100
- * This class provides a comprehensive interface for Mongoose operations including
1101
- * pagination, aggregation, slug generation, and short ID creation.
1102
- */
1103
- export declare class MongooseController<T extends Partial<C_Document>> {
1104
- private model;
1105
- /**
1106
- * Creates a new Mongoose controller instance.
1107
- *
1108
- * @param model - The Mongoose model to operate on.
1109
- */
1110
- constructor(model: I_ExtendedModel<T>);
1111
- /**
1112
- * Gets the model name for logging and error messages.
1113
- *
1114
- * @returns The name of the model.
1115
- */
1116
- private getModelName;
1117
- /**
1118
- * Gets the dynamic virtuals configuration from the model instance.
1119
- *
1120
- * @returns Array of dynamic virtual configurations or undefined if none exist.
1121
- */
1122
- private getDynamicVirtuals;
1123
- /**
1124
- * Populates dynamic virtuals for a single document.
1125
- *
1126
- * @param result - The document to populate dynamic virtuals for.
1127
- * @param populate - The populate options to determine which virtuals to populate.
1128
- * @returns The document with dynamic virtuals populated.
1129
- */
1130
- private populateDynamicVirtualsForDocument;
1131
- /**
1132
- * Populates dynamic virtuals for an array of documents.
1133
- *
1134
- * @param results - The documents to populate dynamic virtuals for.
1135
- * @param populate - The populate options to determine which virtuals to populate.
1136
- * @returns The documents with dynamic virtuals populated.
1137
- */
1138
- private populateDynamicVirtualsForDocuments;
1139
- /**
1140
- * Finds a single document with optional population and projection.
1141
- * Automatically handles dynamic virtual population if configured.
1142
- *
1143
- * @param filter - The filter criteria to find the document.
1144
- * @param projection - The fields to include/exclude in the result.
1145
- * @param options - Query options for the operation.
1146
- * @param populate - Population configuration for related documents.
1147
- * @returns A promise that resolves to a standardized response with the found document.
1148
- */
1149
- findOne(filter?: T_FilterQuery<T>, projection?: T_ProjectionType<T>, options?: T_QueryOptions<T>, populate?: T_Input_Populate): Promise<I_Return<T>>;
1150
- /**
1151
- * Finds all documents with optional population and projection.
1152
- * Automatically handles dynamic virtual population if configured.
1153
- *
1154
- * @param filter - The filter criteria to find documents.
1155
- * @param projection - The fields to include/exclude in the result.
1156
- * @param options - Query options for the operation.
1157
- * @param populate - Population configuration for related documents.
1158
- * @returns A promise that resolves to a standardized response with the found documents.
1159
- */
1160
- findAll(filter?: T_FilterQuery<T>, projection?: T_ProjectionType<T>, options?: T_QueryOptions<T>, populate?: T_Input_Populate): Promise<I_Return<T[]>>;
1161
- /**
1162
- * Finds documents with pagination support.
1163
- * Automatically handles dynamic virtual population if configured.
1164
- *
1165
- * @param filter - The filter criteria to find documents.
1166
- * @param options - Pagination options including page, limit, and population.
1167
- * @returns A promise that resolves to a standardized response with paginated results.
1168
- */
1169
- findPaging(filter?: T_FilterQuery<T>, options?: I_PaginateOptionsWithPopulate): Promise<I_Return<T_PaginateResult<T>>>;
1170
- /**
1171
- * Performs aggregation with pagination support.
1172
- *
1173
- * @param pipeline - The aggregation pipeline stages.
1174
- * @param options - Pagination options for the aggregation result.
1175
- * @returns A promise that resolves to a standardized response with paginated aggregation results.
1176
- */
1177
- findPagingAggregate(pipeline: T_PipelineStage[], options?: I_PaginateOptionsWithPopulate): Promise<I_Return<T_AggregatePaginateResult<T>>>;
1178
- /**
1179
- * Counts documents matching the filter criteria.
1180
- *
1181
- * @param filter - The filter criteria to count documents.
1182
- * @returns A promise that resolves to a standardized response with the document count.
1183
- */
1184
- count(filter?: T_FilterQuery<T>): Promise<I_Return<number>>;
1185
- /**
1186
- * Creates a single document.
1187
- *
1188
- * @param doc - The document to create.
1189
- * @returns A promise that resolves to a standardized response with the created document.
1190
- */
1191
- createOne(doc: T | Partial<T>): Promise<I_Return<T>>;
1192
- /**
1193
- * Creates multiple documents with bulk insertion.
1194
- *
1195
- * @param docs - An array of documents to create.
1196
- * @param options - Options for the bulk insertion operation.
1197
- * @returns A promise that resolves to a standardized response with the created documents.
1198
- */
1199
- createMany(docs: (T | Partial<T>)[], options?: T_InsertManyOptions): Promise<I_Return<T[]>>;
1200
- /**
1201
- * Updates a single document and returns the updated version.
1202
- *
1203
- * @param filter - The filter criteria to find the document to update.
1204
- * @param update - The update data to apply.
1205
- * @param options - Options for the update operation.
1206
- * @returns A promise that resolves to a standardized response with the updated document.
1207
- */
1208
- updateOne(filter?: T_FilterQuery<T>, update?: T_UpdateQuery<T>, options?: I_UpdateOptionsExtended): Promise<I_Return<T>>;
1209
- /**
1210
- * Updates multiple documents matching the filter criteria.
1211
- *
1212
- * @param filter - The filter criteria to find documents to update.
1213
- * @param update - The update data to apply.
1214
- * @param options - Options for the update operation.
1215
- * @returns A promise that resolves to a standardized response with the update result.
1216
- */
1217
- updateMany(filter?: T_FilterQuery<T>, update?: T_UpdateQuery<T>, options?: I_UpdateOptionsExtended): Promise<I_Return<T_UpdateResult>>;
1218
- /**
1219
- * Deletes a single document and returns the deleted version.
1220
- *
1221
- * @param filter - The filter criteria to find the document to delete.
1222
- * @param options - Options for the delete operation.
1223
- * @returns A promise that resolves to a standardized response with the deleted document.
1224
- */
1225
- deleteOne(filter?: T_FilterQuery<T>, options?: I_DeleteOptionsExtended): Promise<I_Return<T>>;
1226
- /**
1227
- * Deletes multiple documents matching the filter criteria.
1228
- *
1229
- * @param filter - The filter criteria to find documents to delete.
1230
- * @param options - Options for the delete operation.
1231
- * @returns A promise that resolves to a standardized response with the delete result.
1232
- */
1233
- deleteMany(filter?: T_FilterQuery<T>, options?: I_DeleteOptionsExtended): Promise<I_Return<T_DeleteResult>>;
1234
- /**
1235
- * Creates a unique short ID based on a given ID.
1236
- * This method generates multiple short IDs with increasing lengths and finds the first available one.
1237
- *
1238
- * @param id - The base ID to generate short IDs from.
1239
- * @param length - The initial length for short ID generation (default: 4).
1240
- * @returns A promise that resolves to a standardized response with the unique short ID.
1241
- */
1242
- createShortId(id: string, length?: number): Promise<I_Return<string>>;
1243
- /**
1244
- * Creates a query for slug existence checking.
1245
- * This method generates a query that checks for slug existence in both current and historical slug fields.
1246
- *
1247
- * @param options - Configuration for slug query generation including slug, field, and filter.
1248
- * @param options.slug - The slug string to check for existence.
1249
- * @param options.field - The field name for object-based slug checking.
1250
- * @param options.isObject - Whether the slug is stored as an object with nested fields.
1251
- * @param options.haveHistory - Whether to check historical slug fields for existence.
1252
- * @param options.filter - Additional filter conditions to apply to the query.
1253
- * @returns A MongoDB query object for checking slug existence.
1254
- */
1255
- createSlugQuery({ slug, field, isObject, haveHistory, filter }: I_Input_GenerateSlug<T>): (mongooseRaw.QueryFilter<T> & {
1256
- $or: ({
1257
- [x: string]: string;
1258
- slugHistory?: undefined;
1259
- } | {
1260
- slugHistory: {
1261
- $elemMatch: {
1262
- [x: string]: string;
1263
- };
1264
- };
1265
- })[];
1266
- }) | (mongooseRaw.QueryFilter<T> & {
1267
- $or: ({
1268
- slug: string;
1269
- slugHistory?: undefined;
1270
- } | {
1271
- slugHistory: string;
1272
- slug?: undefined;
1273
- })[];
1274
- });
1275
- /**
1276
- * Creates a unique slug based on a given string.
1277
- * This method generates multiple slug variations and finds the first available one.
1278
- *
1279
- * @param options - Configuration for slug generation including slug, field, and filter.
1280
- * @param options.slug - The base slug string to make unique.
1281
- * @param options.field - The field name for object-based slug checking.
1282
- * @param options.isObject - Whether the slug is stored as an object with nested fields.
1283
- * @param options.haveHistory - Whether to check historical slug fields for uniqueness.
1284
- * @param options.filter - Additional filter conditions to apply when checking slug existence.
1285
- * @returns A promise that resolves to a unique slug string.
1286
- */
1287
- createUniqueSlug({ slug, field, isObject, haveHistory, filter }: I_Input_GenerateSlug<T>): Promise<string>;
1288
- /**
1289
- * Creates a slug for a document field.
1290
- * This method handles both simple string fields and object fields with nested slug generation.
1291
- *
1292
- * @param options - Configuration for slug creation including field, source document, and filter.
1293
- * @param options.field - The field name to create a slug for.
1294
- * @param options.from - The source document containing the field value.
1295
- * @param options.haveHistory - Whether to check historical slug fields for uniqueness.
1296
- * @param options.filter - Additional filter conditions to apply when checking slug existence.
1297
- * @returns A promise that resolves to a standardized response with the created slug(s).
1298
- */
1299
- createSlug<R = string>({ field, from, filter, haveHistory }: I_Input_CreateSlug<T>): Promise<I_Return<R>>;
1300
- /**
1301
- * Checks if a slug already exists in the collection.
1302
- * This method verifies slug existence in both current and historical slug fields.
1303
- *
1304
- * @param options - Configuration for slug checking including slug, field, source document, and filter.
1305
- * @param options.slug - The slug string to check for existence.
1306
- * @param options.field - The field name for object-based slug checking.
1307
- * @param options.from - The source document containing the field value.
1308
- * @param options.haveHistory - Whether to check historical slug fields for existence.
1309
- * @param options.filter - Additional filter conditions to apply to the query.
1310
- * @returns A promise that resolves to a standardized response indicating whether the slug exists.
1311
- */
1312
- checkSlug({ slug, field, from, filter, haveHistory }: I_Input_CheckSlug<T>): Promise<I_Return<boolean>>;
1313
- /**
1314
- * Performs aggregation operations on the collection.
1315
- *
1316
- * @param pipeline - The aggregation pipeline stages to execute.
1317
- * @returns A promise that resolves to a standardized response with the aggregation results.
1318
- */
1319
- aggregate(pipeline: T_PipelineStage[]): Promise<I_Return<T[]>>;
1320
- /**
1321
- * Retrieves distinct values for the specified key from the collection.
1322
- *
1323
- * @param key - The field for which to return distinct values.
1324
- * @param filter - The filter query to apply (optional).
1325
- * @param options - Additional options for the distinct operation (optional).
1326
- * @returns A promise that resolves to a standardized response with the array of distinct values.
1327
- */
1328
- distinct(key: string, filter?: T_FilterQuery<T>, options?: T_QueryOptions<T>): Promise<I_Return<unknown[]>>;
1329
- }
1040
+ export declare function applyNestedPopulate<T extends object>(mongoose: typeof mongooseRaw, documents: T[], populateOptions: T_Input_Populate, virtualConfigs?: I_DynamicVirtualConfig<unknown, string>[], currentModel?: any): Promise<T[]>;