@cyberskill/shared 2.2.0 → 2.3.1

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.
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("lodash-es"),B=require("migrate-mongo"),k=require("mongoose"),H=require("mongoose-aggregate-paginate-v2"),K=require("mongoose-paginate-v2"),U=require("uuid"),$=require("../../util/object/object.util.cjs"),W=require("../../util/common/common.util.cjs"),P=require("../fs/fs.util.cjs"),A=require("../path/path.constant.cjs"),Q=require("../../util/validate/validate.util.cjs"),I=require("../../util/string/string.util.cjs"),v=require("../../constant/response-status.cjs"),f=require("../log/log.util.cjs");var J=Object.defineProperty,z=Object.defineProperties,X=Object.getOwnPropertyDescriptors,G=Object.getOwnPropertySymbols,Y=Object.prototype.hasOwnProperty,Z=Object.prototype.propertyIsEnumerable,F=(n,t,e)=>t in n?J(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,O=(n,t)=>{for(var e in t||(t={}))Y.call(t,e)&&F(n,e,t[e]);if(G)for(var e of G(t))Z.call(t,e)&&F(n,e,t[e]);return n},V=(n,t)=>z(n,X(t)),ee=(n,t,e)=>F(n,typeof t!="symbol"?t+"":t,e),a=(n,t,e)=>new Promise((r,s)=>{var c=i=>{try{o(e.next(i))}catch(l){s(l)}},u=i=>{try{o(e.throw(i))}catch(l){s(l)}},o=i=>i.done?r(i.value):Promise.resolve(i.value).then(c,u);o((e=e.apply(n,t)).next())});function te(n){return n===n.toUpperCase()?n.charAt(0).toUpperCase()+n.slice(1).toLowerCase():n}const T={createGenericFields(){return{id:U.v4(),isDel:!1,createdAt:new Date,updatedAt:new Date}},applyPlugins(n,t){t.filter(e=>typeof e=="function").forEach(e=>n.plugin(e))},applyMiddlewares(n,t){t.forEach(({method:e,pre:r,post:s})=>{e&&r&&n.pre(e,r),e&&s&&n.post(e,s)})},createGenericSchema(n){return new n.Schema({id:{type:String,default:U.v4,unique:!0},isDel:{type:Boolean,default:!1}},{timestamps:!0})},createSchema({mongoose:n,schema:t,virtuals:e=[],standalone:r=!1}){const s=new n.Schema(t);return e.forEach(({name:c,options:u,get:o})=>{if(T.isDynamicVirtual(u)){const i=s.statics;i._dynamicVirtuals||(i._dynamicVirtuals=[]),i._dynamicVirtuals.push({name:c,options:u});const l=s.virtual(c);o?l.get(o):l.get(function(){var d;return((d=this._populated)==null?void 0:d[c])||(u!=null&&u.count?0:u!=null&&u.justOne?null:[])})}else{const i=s.virtual(c,u);o&&i.get(o)}}),r||s.add(T.createGenericSchema(n)),s},createModel({mongoose:n,name:t,schema:e,virtuals:r=[],pagination:s=!0,aggregate:c=!0,middlewares:u=[]}){if(!t)throw new Error("Model name is required.");if(n.models[t])return n.models[t];const o=T.createSchema({mongoose:n,schema:e,virtuals:r});return(s||c)&&T.applyPlugins(o,[s&&K,c&&H]),T.applyMiddlewares(o,u),n.model(t,o)},validator:{isRequired(){return function(n){return a(this,null,function*(){return!Q.validate.isEmpty(n)})}},isUnique(n){return function(t){return a(this,null,function*(){if(!Array.isArray(n)||n.length===0)throw new Error("Fields must be a non-empty array of strings.");const e={$or:n.map(s=>({[s]:t}))};return!(yield this.constructor.exists(e))})}},matchesRegex(n){return function(t){return a(this,null,function*(){if(!Array.isArray(n)||n.some(e=>!(e instanceof RegExp)))throw new Error("regexArray must be an array of valid RegExp objects.");return n.every(e=>e.test(t))})}}},migrate:V(O({},B),{setConfig:n=>{const t=`// This file is automatically generated by the Cyberskill CLI.
2
- module.exports = ${JSON.stringify(n,null,4)}`;P.writeFileSync(A.PATH.MIGRATE_MONGO_CONFIG,t);const e=`
3
- ${A.MIGRATE_MONGO_CONFIG}
4
- `;P.pathExistsSync(A.PATH.GIT_IGNORE)?P.readFileSync(A.PATH.GIT_IGNORE,"utf-8").split(`
5
- `).includes(A.MIGRATE_MONGO_CONFIG)||P.appendFileSync(A.PATH.GIT_IGNORE,e):P.writeFileSync(A.PATH.GIT_IGNORE,e)}}),regexify(n,t){if(!n)return{};let e=j.cloneDeep(n);if(!t||t.length===0)return e;for(const r of t){const s=r.toString().split("."),c=$.getNestedValue(e,s);if(typeof c=="string"&&c.length>0){const u={$regex:`.*${W.regexSearchMapper(c)}.*`,$options:"i"};e=$.setNestedValue(e,s,u)}}return e},isDynamicVirtual(n){return!!(n&&typeof n.ref=="function")}};function re(n){return n!==null&&typeof n=="object"&&"toObject"in n&&typeof n.toObject=="function"}function se(n,t,e){if(!n.length||!t||!(e!=null&&e.ref))return[];const r=new Map;return n.forEach(s=>{try{const c=e.ref(s);if(c==null)return;const u=typeof c=="string"?c:String(c);if(u&&u.trim()!==""){const o=te(u);r.has(o)||r.set(o,[]),r.get(o).push(s)}}catch(c){f.catchError(new Error(`Dynamic ref function failed for virtual "${t}": ${c instanceof Error?c.message:String(c)}`))}}),Array.from(r.entries()).map(([s,c])=>({model:s,docs:c}))}function q(n,t,e,r,s){return a(this,null,function*(){if(!t.length||!e.length||!r)return t;const c=e.filter(i=>{if(Array.isArray(r))return r.length>0&&r.some(l=>typeof l=="string"?l===i.name:l.path===i.name);if(typeof r=="string")return r===i.name;if(typeof r=="object"&&r!==null){const l=r;return l.path&&l.path===i.name||l.populate&&l.populate===i.name}return!1});if(c.length===0)return t;const u=j.cloneDeep(t.map(i=>re(i)?i.toObject():i));u.forEach(i=>{c.forEach(({name:l,options:d})=>{if(!(l in i)){const h=i;h[l]=d.count?0:d.justOne?null:[]}})});const o=new Map;for(const i of c){const{name:l,options:d}=i,h=se(u,l,d);for(const S of h){o.has(S.model)||o.set(S.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const m=o.get(S.model);m.virtuals.find(D=>D.name===l)||(m.virtuals.push(i),m.localValueSets.set(l,new Set));const M=m.localValueSets.get(l);S.docs.forEach(D=>{const C=D[d.localField];if(C!=null){const _=String(C);M.add(_);let R=-1;const N=D;N.id!==void 0?R=u.findIndex(b=>b.id===N.id):N._id!==void 0&&(R=u.findIndex(b=>{var E,g,p,y;return((g=(E=b._id)==null?void 0:E.toString)==null?void 0:g.call(E))===((y=(p=N._id)==null?void 0:p.toString)==null?void 0:y.call(p))})),R!==-1&&(m.docsByLocalValue.has(_)||m.docsByLocalValue.set(_,[]),m.docsByLocalValue.get(_).push(R))}})}}return yield Promise.all(Array.from(o.entries()).map(i=>a(null,[i],function*([l,d]){const h=n.models[l];if(!h)return;const S=new Set;if(d.localValueSets.forEach(_=>{_.forEach(R=>S.add(R))}),S.size===0)return;const m=[...new Set(d.virtuals.map(_=>_.options.foreignField))],M=Array.from(S);let D;m.length===1?D={[String(m[0])]:{$in:M}}:D={$or:m.map(_=>({[_]:{$in:M}}))};const C=yield h.find(D,s).lean();for(const _ of d.virtuals){const{name:R,options:N}=_,b=C.filter(E=>{const g=E[N.foreignField];return g!=null&&S.has(String(g))});if(N.count){const E=new Map;b.forEach(g=>{var p;const y=(p=g[N.foreignField])==null?void 0:p.toString();y&&E.set(y,(E.get(y)||0)+1)}),d.localValueSets.get(R).forEach(g=>{const p=d.docsByLocalValue.get(g)||[],y=E.get(g)||0;p.forEach(w=>{const x=u[w];x[R]===void 0&&(x[R]=y)})})}else{const E=new Map;b.forEach(g=>{var p;const y=(p=g[N.foreignField])==null?void 0:p.toString();y&&(E.has(y)||E.set(y,[]),E.get(y).push(g))}),d.localValueSets.get(R).forEach(g=>{const p=d.docsByLocalValue.get(g)||[],y=E.get(g)||[],w=N.justOne?y[0]||null:y;p.forEach(x=>{const L=u[x];L[R]=w})})}}}))),u})}class ne{constructor(t,e){ee(this,"collection"),this.collection=t.collection(e)}createOne(t){return a(this,null,function*(){try{const e=O(O({},T.createGenericFields()),t);return(yield this.collection.insertOne(e)).acknowledged?{success:!0,message:"Document created successfully",result:e}:{success:!1,message:"Document creation failed",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(e){return f.catchError(e)}})}createMany(t){return a(this,null,function*(){try{const e=t.map(s=>O(O({},T.createGenericFields()),s)),r=yield this.collection.insertMany(e);return r.insertedCount===0?{success:!1,message:"No documents were inserted",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:`${r.insertedCount} documents created successfully`,result:e}}catch(e){return f.catchError(e)}})}findOne(t){return a(this,null,function*(){try{const e=yield this.collection.findOne(t);return e?{success:!0,message:"Document found",result:e}:{success:!1,message:"Document not found",code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(e){return f.catchError(e)}})}findAll(){return a(this,arguments,function*(t={}){try{return{success:!0,message:"Documents retrieved successfully",result:yield this.collection.find(t).toArray()}}catch(e){return f.catchError(e)}})}count(){return a(this,arguments,function*(t={}){try{const e=yield this.collection.countDocuments(t);return{success:!0,message:`${e} documents counted successfully`,result:e}}catch(e){return f.catchError(e)}})}updateOne(t,e){return a(this,null,function*(){try{const r=yield this.collection.updateOne(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document updated successfully",result:r}}catch(r){return f.catchError(r)}})}updateMany(t,e){return a(this,null,function*(){try{const r=yield this.collection.updateMany(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents updated successfully",result:r}}catch(r){return f.catchError(r)}})}deleteOne(t){return a(this,null,function*(){try{const e=yield this.collection.deleteOne(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document deleted successfully",result:e}}catch(e){return f.catchError(e)}})}deleteMany(t){return a(this,null,function*(){try{const e=yield this.collection.deleteMany(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents deleted successfully",result:e}}catch(e){return f.catchError(e)}})}}class ce{constructor(t){this.model=t}getModelName(){return this.model.modelName}findOne(){return a(this,arguments,function*(t={},e={},r={},s){try{const c=this.model.findOne(t,e,r),o=this.model.schema.statics._dynamicVirtuals;s&&(!o||o.length===0)&&c.populate(s);const i=yield c.exec();if(!i)return{success:!1,message:`No ${this.getModelName()} found.`,code:v.RESPONSE_STATUS.NOT_FOUND.CODE};let l=i;if(o&&o.length>0){const d=yield q(this.model.base,[i],o,s);l=d&&d[0]?d[0]:i}return{success:!0,result:l}}catch(c){return f.catchError(c)}})}findAll(){return a(this,arguments,function*(t={},e={},r={},s){try{const c=this.model.find(t,e,r),o=this.model.schema.statics._dynamicVirtuals;s&&(!o||o.length===0)&&c.populate(s);const i=yield c.exec();let l=i;return o&&o.length>0&&i.length>0&&(l=yield q(this.model.base,i,o,s)),{success:!0,result:l}}catch(c){return f.catchError(c)}})}findPaging(){return a(this,arguments,function*(t={},e={}){try{const s=this.model.schema.statics._dynamicVirtuals,c=O({},e);s&&s.length>0&&(c.populate=void 0);const u=yield this.model.paginate(t,c);let o=u.docs;return s&&s.length>0&&u.docs.length>0&&(o=yield q(this.model.base,u.docs,s,e.populate)),{success:!0,result:V(O({},u),{docs:o})}}catch(r){return f.catchError(r)}})}findPagingAggregate(t){return a(this,arguments,function*(e,r={}){try{const c=this.model.schema.statics._dynamicVirtuals,u=O({},r);c&&c.length>0&&(u.populate=void 0);const o=yield this.model.aggregatePaginate(this.model.aggregate(e),u);let i=o.docs;return c&&c.length>0&&o.docs.length>0&&(i=yield q(this.model.base,o.docs,c,r.populate)),{success:!0,result:V(O({},o),{docs:i})}}catch(s){return f.catchError(s)}})}count(){return a(this,arguments,function*(t={}){try{return{success:!0,result:yield this.model.countDocuments(t)}}catch(e){return f.catchError(e)}})}createOne(t){return a(this,null,function*(){try{return{success:!0,result:yield this.model.create(t)}}catch(e){return f.catchError(e)}})}createMany(t){return a(this,arguments,function*(e,r={}){try{return{success:!0,result:(yield this.model.insertMany(e,r)).map(u=>u instanceof k.Document?u.toObject():null).filter(u=>u!==null)}}catch(s){return f.catchError(s)}})}updateOne(){return a(this,arguments,function*(t={},e={},r={}){try{const s=yield this.model.findOneAndUpdate(t,e,O({new:!0},r)).exec();return s?{success:!0,result:s}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(s){return f.catchError(s)}})}updateMany(){return a(this,arguments,function*(t={},e={},r={}){try{return{success:!0,result:yield this.model.updateMany(t,e,r).exec()}}catch(s){return f.catchError(s)}})}deleteOne(){return a(this,arguments,function*(t={},e={}){try{const r=yield this.model.findOneAndDelete(t,e).exec();return r?{success:!0,result:r}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return f.catchError(r)}})}deleteMany(){return a(this,arguments,function*(t={},e={}){try{const r=yield this.model.deleteMany(t,e).exec();return r.deletedCount===0?{success:!1,message:"No documents found to delete.",code:v.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:r}}catch(r){return f.catchError(r)}})}createShortId(t,e=4){return a(this,null,function*(){try{const s=Array.from({length:10},(o,i)=>I.generateShortId(t,i+e)),u=(yield Promise.all(s.map(o=>this.model.exists({shortId:o})))).findIndex(o=>!o);if(u!==-1){const o=s[u];if(o)return{success:!0,result:o}}return{success:!1,message:"Failed to create a unique shortId",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return f.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,filter:s}){const c=O({},s!=null?s:{});return r?V(O({},c),{$or:[{[`slug.${e}`]:t},{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]}):V(O({},c),{$or:[{slug:t},{slugHistory:t}]})}createUniqueSlug(t){return a(this,arguments,function*({slug:e,field:r,isObject:s,filter:c}){const u=I.generateSlug(e),i=Array.from({length:100},(h,S)=>S===0?u:`${u}-${S}`),d=(yield Promise.all(i.map(h=>this.model.exists(this.createSlugQuery({slug:h,field:r,isObject:s,filter:c}))))).findIndex(h=>!h);if(d!==-1){const h=i[d];if(h)return h}return`${u}-${Date.now()}`})}createSlug(t){return a(this,arguments,function*({field:e,from:r,filter:s}){try{const c=r[e];return j.isObject(c)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(c).map(l=>a(this,[l],function*([d,h]){const S=yield this.createUniqueSlug({slug:h,field:d,isObject:!0,filter:s});return[d,S]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:c,field:e,isObject:!1,filter:s})}}catch(c){return f.catchError(c)}})}checkSlug(t){return a(this,arguments,function*({slug:e,field:r,from:s,filter:c}){try{const u=s[r];if(j.isObject(u)){const h=Object.values(u).map(m=>I.generateSlug(m));return(yield Promise.all(h.map(m=>this.model.exists(this.createSlugQuery({slug:m,field:r,isObject:!0,filter:c}))))).some(m=>m)?{success:!0,result:!0}:{success:!0,result:!1}}const i=I.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:i,field:r,isObject:!1,filter:c})))!==null}}catch(u){return f.catchError(u)}})}aggregate(t){return a(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return f.catchError(e)}})}}exports.MongoController=ne;exports.MongooseController=ce;exports.mongo=T;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("lodash-es"),k=require("migrate-mongo"),H=require("mongoose"),K=require("mongoose-aggregate-paginate-v2"),W=require("mongoose-paginate-v2"),U=require("uuid"),$=require("../../util/object/object.util.cjs"),Q=require("../../util/common/common.util.cjs"),P=require("../fs/fs.util.cjs"),T=require("../path/path.constant.cjs"),J=require("../../util/validate/validate.util.cjs"),j=require("../../util/string/string.util.cjs"),v=require("../../constant/response-status.cjs"),d=require("../log/log.util.cjs");var z=Object.defineProperty,X=Object.defineProperties,Y=Object.getOwnPropertyDescriptors,G=Object.getOwnPropertySymbols,Z=Object.prototype.hasOwnProperty,ee=Object.prototype.propertyIsEnumerable,q=(s,t,e)=>t in s?z(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,O=(s,t)=>{for(var e in t||(t={}))Z.call(t,e)&&q(s,e,t[e]);if(G)for(var e of G(t))ee.call(t,e)&&q(s,e,t[e]);return s},b=(s,t)=>X(s,Y(t)),te=(s,t,e)=>q(s,typeof t!="symbol"?t+"":t,e),l=(s,t,e)=>new Promise((r,n)=>{var c=o=>{try{i(e.next(o))}catch(a){n(a)}},u=o=>{try{i(e.throw(o))}catch(a){n(a)}},i=o=>o.done?r(o.value):Promise.resolve(o.value).then(c,u);i((e=e.apply(s,t)).next())});function re(s){return s===s.toUpperCase()?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():s}const V={createGenericFields(){return{id:U.v4(),isDel:!1,createdAt:new Date,updatedAt:new Date}},applyPlugins(s,t){t.filter(e=>typeof e=="function").forEach(e=>s.plugin(e))},applyMiddlewares(s,t){t.forEach(({method:e,pre:r,post:n})=>{e&&r&&s.pre(e,r),e&&n&&s.post(e,n)})},createGenericSchema(s){return new s.Schema({id:{type:String,default:U.v4,unique:!0},isDel:{type:Boolean,default:!1}},{timestamps:!0})},createSchema({mongoose:s,schema:t,virtuals:e=[],standalone:r=!1}){const n=new s.Schema(t,{toJSON:{virtuals:!0},toObject:{virtuals:!0}});return e.forEach(({name:c,options:u,get:i})=>{if(V.isDynamicVirtual(u)){const o=n.statics;o._dynamicVirtuals||(o._dynamicVirtuals=[]),o._dynamicVirtuals.push({name:c,options:u});const a=n.virtual(c);i?a.get(i):a.get(function(){var f;return((f=this._populated)==null?void 0:f[c])||(u!=null&&u.count?0:u!=null&&u.justOne?null:[])})}else{const o=n.virtual(c,u);i&&o.get(i)}}),r||n.add(V.createGenericSchema(s)),n},createModel({mongoose:s,name:t,schema:e,virtuals:r=[],pagination:n=!0,aggregate:c=!0,middlewares:u=[]}){if(!t)throw new Error("Model name is required.");if(s.models[t])return s.models[t];const i=V.createSchema({mongoose:s,schema:e,virtuals:r});return(n||c)&&V.applyPlugins(i,[n&&W,c&&K]),V.applyMiddlewares(i,u),s.model(t,i)},validator:{isRequired(){return function(s){return l(this,null,function*(){return!J.validate.isEmpty(s)})}},isUnique(s){return function(t){return l(this,null,function*(){if(!Array.isArray(s)||s.length===0)throw new Error("Fields must be a non-empty array of strings.");const e={$or:s.map(n=>({[n]:t}))};return!(yield this.constructor.exists(e))})}},matchesRegex(s){return function(t){return l(this,null,function*(){if(!Array.isArray(s)||s.some(e=>!(e instanceof RegExp)))throw new Error("regexArray must be an array of valid RegExp objects.");return s.every(e=>e.test(t))})}}},migrate:b(O({},k),{setConfig:s=>{const t=`// This file is automatically generated by the Cyberskill CLI.
2
+ module.exports = ${JSON.stringify(s,null,4)}`;P.writeFileSync(T.PATH.MIGRATE_MONGO_CONFIG,t);const e=`
3
+ ${T.MIGRATE_MONGO_CONFIG}
4
+ `;P.pathExistsSync(T.PATH.GIT_IGNORE)?P.readFileSync(T.PATH.GIT_IGNORE,"utf-8").split(`
5
+ `).includes(T.MIGRATE_MONGO_CONFIG)||P.appendFileSync(T.PATH.GIT_IGNORE,e):P.writeFileSync(T.PATH.GIT_IGNORE,e)}}),regexify(s,t){if(!s)return{};let e=I.cloneDeep(s);if(!t||t.length===0)return e;for(const r of t){const n=r.toString().split("."),c=$.getNestedValue(e,n);if(typeof c=="string"&&c.length>0){const u={$regex:`.*${Q.regexSearchMapper(c)}.*`,$options:"i"};e=$.setNestedValue(e,n,u)}}return e},isDynamicVirtual(s){return!!(s&&typeof s.ref=="function")}};function se(s){return s!==null&&typeof s=="object"&&"toObject"in s&&typeof s.toObject=="function"}function F(s,t){if(!s||!t||t.length===0)return s;const e=new Set(t.map(r=>r.name));if(Array.isArray(s)){const r=s.filter(n=>{if(typeof n=="string")return!e.has(n);if(typeof n=="object"&&n!==null){const c=n;return!e.has(c.path||c.populate||"")}return!0});return r.length>0?r:void 0}if(typeof s=="string")return e.has(s)?void 0:s;if(typeof s=="object"&&s!==null){const r=s,n=r.path||r.populate||"";return e.has(n)?void 0:s}return s}function ne(s,t,e){if(!s.length||!t||!(e!=null&&e.ref))return[];const r=new Map;return s.forEach(n=>{try{const c=e.ref(n);if(c==null)return;const u=typeof c=="string"?c:String(c);if(u&&u.trim()!==""){const i=re(u);r.has(i)||r.set(i,[]),r.get(i).push(n)}}catch(c){d.catchError(new Error(`Dynamic ref function failed for virtual "${t}": ${c instanceof Error?c.message:String(c)}`))}}),Array.from(r.entries()).map(([n,c])=>({model:n,docs:c}))}function L(s,t,e,r,n){return l(this,null,function*(){if(!t.length||!e.length||!r)return t;const c=e.filter(o=>{if(Array.isArray(r))return r.length>0&&r.some(a=>typeof a=="string"?a===o.name:a.path===o.name);if(typeof r=="string")return r===o.name;if(typeof r=="object"&&r!==null){const a=r;return a.path&&a.path===o.name||a.populate&&a.populate===o.name}return!1});if(c.length===0)return t;const u=I.cloneDeep(t.map(o=>se(o)?o.toObject():o));u.forEach(o=>{c.forEach(({name:a,options:f})=>{if(!(a in o)){const h=o;h[a]=f.count?0:f.justOne?null:[]}})});const i=new Map;for(const o of c){const{name:a,options:f}=o,h=ne(u,a,f);for(const S of h){i.has(S.model)||i.set(S.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const m=i.get(S.model);m.virtuals.find(N=>N.name===a)||(m.virtuals.push(o),m.localValueSets.set(a,new Set));const M=m.localValueSets.get(a);S.docs.forEach(N=>{const w=N[f.localField];if(w!=null){const _=String(w);M.add(_);let D=-1;const R=N;R.id!==void 0?D=u.findIndex(A=>A.id===R.id):R._id!==void 0&&(D=u.findIndex(A=>{var E,y,p,g;return((y=(E=A._id)==null?void 0:E.toString)==null?void 0:y.call(E))===((g=(p=R._id)==null?void 0:p.toString)==null?void 0:g.call(p))})),D!==-1&&(m.docsByLocalValue.has(_)||m.docsByLocalValue.set(_,[]),m.docsByLocalValue.get(_).push(D))}})}}return yield Promise.all(Array.from(i.entries()).map(o=>l(null,[o],function*([a,f]){const h=s.models[a];if(!h)return;const S=new Set;if(f.localValueSets.forEach(_=>{_.forEach(D=>S.add(D))}),S.size===0)return;const m=[...new Set(f.virtuals.map(_=>_.options.foreignField))],M=Array.from(S);let N;m.length===1?N={[String(m[0])]:{$in:M}}:N={$or:m.map(_=>({[_]:{$in:M}}))};const w=yield h.find(N,n).lean();for(const _ of f.virtuals){const{name:D,options:R}=_,A=w.filter(E=>{const y=E[R.foreignField];return y!=null&&S.has(String(y))});if(R.count){const E=new Map;A.forEach(y=>{var p;const g=(p=y[R.foreignField])==null?void 0:p.toString();g&&E.set(g,(E.get(g)||0)+1)}),f.localValueSets.get(D).forEach(y=>{const p=f.docsByLocalValue.get(y)||[],g=E.get(y)||0;p.forEach(C=>{const x=u[C];x[D]===void 0&&(x[D]=g)})})}else{const E=new Map;A.forEach(y=>{var p;const g=(p=y[R.foreignField])==null?void 0:p.toString();g&&(E.has(g)||E.set(g,[]),E.get(g).push(y))}),f.localValueSets.get(D).forEach(y=>{const p=f.docsByLocalValue.get(y)||[],g=E.get(y)||[],C=R.justOne?g[0]||null:g;p.forEach(x=>{const B=u[x];B[D]=C})})}}}))),u})}class ce{constructor(t,e){te(this,"collection"),this.collection=t.collection(e)}createOne(t){return l(this,null,function*(){try{const e=O(O({},V.createGenericFields()),t);return(yield this.collection.insertOne(e)).acknowledged?{success:!0,message:"Document created successfully",result:e}:{success:!1,message:"Document creation failed",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(e){return d.catchError(e)}})}createMany(t){return l(this,null,function*(){try{const e=t.map(n=>O(O({},V.createGenericFields()),n)),r=yield this.collection.insertMany(e);return r.insertedCount===0?{success:!1,message:"No documents were inserted",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:`${r.insertedCount} documents created successfully`,result:e}}catch(e){return d.catchError(e)}})}findOne(t){return l(this,null,function*(){try{const e=yield this.collection.findOne(t);return e?{success:!0,message:"Document found",result:e}:{success:!1,message:"Document not found",code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(e){return d.catchError(e)}})}findAll(){return l(this,arguments,function*(t={}){try{return{success:!0,message:"Documents retrieved successfully",result:yield this.collection.find(t).toArray()}}catch(e){return d.catchError(e)}})}count(){return l(this,arguments,function*(t={}){try{const e=yield this.collection.countDocuments(t);return{success:!0,message:`${e} documents counted successfully`,result:e}}catch(e){return d.catchError(e)}})}updateOne(t,e){return l(this,null,function*(){try{const r=yield this.collection.updateOne(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document updated successfully",result:r}}catch(r){return d.catchError(r)}})}updateMany(t,e){return l(this,null,function*(){try{const r=yield this.collection.updateMany(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents updated successfully",result:r}}catch(r){return d.catchError(r)}})}deleteOne(t){return l(this,null,function*(){try{const e=yield this.collection.deleteOne(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document deleted successfully",result:e}}catch(e){return d.catchError(e)}})}deleteMany(t){return l(this,null,function*(){try{const e=yield this.collection.deleteMany(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents deleted successfully",result:e}}catch(e){return d.catchError(e)}})}}class ue{constructor(t){this.model=t}getModelName(){return this.model.modelName}getDynamicVirtuals(){return this.model.schema.statics._dynamicVirtuals}populateDynamicVirtualsForDocument(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();if(r&&r.length>0){const n=yield L(this.model.base,[t],r,e);return n&&n[0]?n[0]:t}return t})}populateDynamicVirtualsForDocuments(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();return r&&r.length>0&&t.length>0?yield L(this.model.base,t,r,e):t})}findOne(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=this.model.findOne(t,e,r),u=this.getDynamicVirtuals(),i=F(n,u);i&&c.populate(i);const o=yield c.exec();return o?{success:!0,result:yield this.populateDynamicVirtualsForDocument(o,n)}:{success:!1,message:`No ${this.getModelName()} found.`,code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(c){return d.catchError(c)}})}findAll(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=this.model.find(t,e,r),u=this.getDynamicVirtuals(),i=F(n,u);i&&c.populate(i);const o=yield c.exec();return{success:!0,result:yield this.populateDynamicVirtualsForDocuments(o,n)}}catch(c){return d.catchError(c)}})}findPaging(){return l(this,arguments,function*(t={},e={}){try{const r=this.getDynamicVirtuals(),n=O({},e);e.populate&&(n.populate=F(e.populate,r));const c=yield this.model.paginate(t,n),u=yield this.populateDynamicVirtualsForDocuments(c.docs,e.populate);return{success:!0,result:b(O({},c),{docs:u})}}catch(r){return d.catchError(r)}})}findPagingAggregate(t){return l(this,arguments,function*(e,r={}){try{const n=this.getDynamicVirtuals(),c=O({},r);r.populate&&(c.populate=F(r.populate,n));const u=yield this.model.aggregatePaginate(this.model.aggregate(e),c),i=yield this.populateDynamicVirtualsForDocuments(u.docs,r.populate);return{success:!0,result:b(O({},u),{docs:i})}}catch(n){return d.catchError(n)}})}count(){return l(this,arguments,function*(t={}){try{return{success:!0,result:yield this.model.countDocuments(t)}}catch(e){return d.catchError(e)}})}createOne(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.create(t)}}catch(e){return d.catchError(e)}})}createMany(t){return l(this,arguments,function*(e,r={}){try{return{success:!0,result:(yield this.model.insertMany(e,r)).map(u=>u instanceof H.Document?u.toObject():null).filter(u=>u!==null)}}catch(n){return d.catchError(n)}})}updateOne(){return l(this,arguments,function*(t={},e={},r={}){try{const n=yield this.model.findOneAndUpdate(t,e,O({new:!0},r)).exec();return n?{success:!0,result:n}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(n){return d.catchError(n)}})}updateMany(){return l(this,arguments,function*(t={},e={},r={}){try{return{success:!0,result:yield this.model.updateMany(t,e,r).exec()}}catch(n){return d.catchError(n)}})}deleteOne(){return l(this,arguments,function*(t={},e={}){try{const r=yield this.model.findOneAndDelete(t,e).exec();return r?{success:!0,result:r}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:v.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return d.catchError(r)}})}deleteMany(){return l(this,arguments,function*(t={},e={}){try{const r=yield this.model.deleteMany(t,e).exec();return r.deletedCount===0?{success:!1,message:"No documents found to delete.",code:v.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:r}}catch(r){return d.catchError(r)}})}createShortId(t,e=4){return l(this,null,function*(){try{const n=Array.from({length:10},(i,o)=>j.generateShortId(t,o+e)),u=(yield Promise.all(n.map(i=>this.model.exists({shortId:i})))).findIndex(i=>!i);if(u!==-1){const i=n[u];if(i)return{success:!0,result:i}}return{success:!1,message:"Failed to create a unique shortId",code:v.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return d.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,filter:n}){const c=O({},n!=null?n:{});return r?b(O({},c),{$or:[{[`slug.${e}`]:t},{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]}):b(O({},c),{$or:[{slug:t},{slugHistory:t}]})}createUniqueSlug(t){return l(this,arguments,function*({slug:e,field:r,isObject:n,filter:c}){const u=j.generateSlug(e),o=Array.from({length:100},(h,S)=>S===0?u:`${u}-${S}`),f=(yield Promise.all(o.map(h=>this.model.exists(this.createSlugQuery({slug:h,field:r,isObject:n,filter:c}))))).findIndex(h=>!h);if(f!==-1){const h=o[f];if(h)return h}return`${u}-${Date.now()}`})}createSlug(t){return l(this,arguments,function*({field:e,from:r,filter:n}){try{const c=r[e];return I.isObject(c)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(c).map(a=>l(this,[a],function*([f,h]){const S=yield this.createUniqueSlug({slug:h,field:f,isObject:!0,filter:n});return[f,S]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:c,field:e,isObject:!1,filter:n})}}catch(c){return d.catchError(c)}})}checkSlug(t){return l(this,arguments,function*({slug:e,field:r,from:n,filter:c}){try{const u=n[r];if(I.isObject(u)){const h=Object.values(u).map(m=>j.generateSlug(m));return(yield Promise.all(h.map(m=>this.model.exists(this.createSlugQuery({slug:m,field:r,isObject:!0,filter:c}))))).some(m=>m)?{success:!0,result:!0}:{success:!0,result:!1}}const o=j.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:o,field:r,isObject:!1,filter:c})))!==null}}catch(u){return d.catchError(u)}})}aggregate(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return d.catchError(e)}})}}exports.MongoController=ce;exports.MongooseController=ue;exports.mongo=V;
@@ -262,6 +262,28 @@ export declare class MongooseController<T extends Partial<C_Document>> {
262
262
  * @returns The name of the model.
263
263
  */
264
264
  private getModelName;
265
+ /**
266
+ * Gets the dynamic virtuals configuration from the model schema.
267
+ *
268
+ * @returns Array of dynamic virtual configurations or undefined if none exist.
269
+ */
270
+ private getDynamicVirtuals;
271
+ /**
272
+ * Populates dynamic virtuals for a single document.
273
+ *
274
+ * @param result - The document to populate dynamic virtuals for.
275
+ * @param populate - The populate options to determine which virtuals to populate.
276
+ * @returns The document with dynamic virtuals populated.
277
+ */
278
+ private populateDynamicVirtualsForDocument;
279
+ /**
280
+ * Populates dynamic virtuals for an array of documents.
281
+ *
282
+ * @param results - The documents to populate dynamic virtuals for.
283
+ * @param populate - The populate options to determine which virtuals to populate.
284
+ * @returns The documents with dynamic virtuals populated.
285
+ */
286
+ private populateDynamicVirtualsForDocuments;
265
287
  /**
266
288
  * Finds a single document with optional population and projection.
267
289
  * Automatically handles dynamic virtual population if configured.