@cyberskill/shared 2.4.0 → 2.6.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.
@@ -1,5 +1,5 @@
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=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("lodash-es"),B=require("migrate-mongo"),H=require("mongoose"),k=require("mongoose-aggregate-paginate-v2"),K=require("mongoose-paginate-v2"),$=require("uuid"),N=require("../../util/object/object.util.cjs"),W=require("../../util/common/common.util.cjs"),M=require("../fs/fs.util.cjs"),T=require("../path/path.constant.cjs"),Q=require("../../util/validate/validate.util.cjs"),j=require("../../util/string/string.util.cjs"),D=require("../../constant/response-status.cjs"),f=require("../log/log.util.cjs");var J=Object.defineProperty,X=Object.defineProperties,Y=Object.getOwnPropertyDescriptors,G=Object.getOwnPropertySymbols,Z=Object.prototype.hasOwnProperty,ee=Object.prototype.propertyIsEnumerable,U=(s,t,e)=>t in s?J(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)&&U(s,e,t[e]);if(G)for(var e of G(t))ee.call(t,e)&&U(s,e,t[e]);return s},P=(s,t)=>X(s,Y(t)),te=(s,t,e)=>U(s,typeof t!="symbol"?t+"":t,e),l=(s,t,e)=>new Promise((r,n)=>{var c=u=>{try{i(e.next(u))}catch(a){n(a)}},o=u=>{try{i(e.throw(u))}catch(a){n(a)}},i=u=>u.done?r(u.value):Promise.resolve(u.value).then(c,o);i((e=e.apply(s,t)).next())});function re(s){return s===s.toUpperCase()?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():s}const A={createGenericFields(){return{id:$.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:$.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:o,get:i})=>{if(A.isDynamicVirtual(o)){const u=n.statics;u._dynamicVirtuals||(u._dynamicVirtuals=[]),u._dynamicVirtuals.push({name:c,options:o});const a=n.virtual(c);i?a.get(i):a.get(function(){var d;return((d=this._populated)==null?void 0:d[c])||(o!=null&&o.count?0:o!=null&&o.justOne?null:[])})}else{const u=n.virtual(c,o);i&&u.get(i)}}),r||n.add(A.createGenericSchema(s)),n},createModel({mongoose:s,name:t,schema:e,virtuals:r=[],pagination:n=!0,aggregate:c=!0,middlewares:o=[]}){if(!t)throw new Error("Model name is required.");if(s.models[t])return s.models[t];const i=A.createSchema({mongoose:s,schema:e,virtuals:r});return(n||c)&&A.applyPlugins(i,[n&&K,c&&k]),A.applyMiddlewares(i,o),s.model(t,i)},validator:{isRequired(){return function(s){return l(this,null,function*(){return!Q.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:P(O({},B),{setConfig:s=>{const t=`// This file is automatically generated by the Cyberskill CLI.
2
+ module.exports = ${JSON.stringify(s,null,4)}`;M.writeFileSync(T.PATH.MIGRATE_MONGO_CONFIG,t);const e=`
3
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;
4
+ `;M.pathExistsSync(T.PATH.GIT_IGNORE)?M.readFileSync(T.PATH.GIT_IGNORE,"utf-8").split(`
5
+ `).includes(T.MIGRATE_MONGO_CONFIG)||M.appendFileSync(T.PATH.GIT_IGNORE,e):M.writeFileSync(T.PATH.GIT_IGNORE,e)}}),regexify(s,t){if(!s)return{};let e=q.cloneDeep(s);if(!t||t.length===0)return e;for(const r of t){const n=r.toString().split("."),c=N.getNestedValue(e,n);if(typeof c=="string"&&c.length>0){const o={$regex:`.*${W.regexSearchMapper(c)}.*`,$options:"i"};e=N.setNestedValue(e,n,o)}}return e},isDynamicVirtual(s){return!!(s&&typeof s.ref=="function")},getNewRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?t.filter(c=>!r.result.some(o=>e(o,c))):t})},getExistingRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?r.result.filter(c=>t.some(o=>e(c,o))):[]})}};function ne(s){return s!==null&&typeof s=="object"&&"toObject"in s&&typeof s.toObject=="function"}function I(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 se(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 o=typeof c=="string"?c:String(c);if(o&&o.trim()!==""){const i=re(o);r.has(i)||r.set(i,[]),r.get(i).push(n)}}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(([n,c])=>({model:n,docs:c}))}function z(s,t,e,r,n){return l(this,null,function*(){if(!t.length||!e.length||!r)return t;const c=e.filter(u=>{if(Array.isArray(r))return r.length>0&&r.some(a=>typeof a=="string"?a===u.name:a.path===u.name);if(typeof r=="string")return r===u.name;if(typeof r=="object"&&r!==null){const a=r;return a.path&&a.path===u.name||a.populate&&a.populate===u.name}return!1});if(c.length===0)return t;const o=q.cloneDeep(t.map(u=>ne(u)?u.toObject():u));o.forEach(u=>{c.forEach(({name:a,options:d})=>{if(!(a in u)){const h=u;h[a]=d.count?0:d.justOne?null:[]}})});const i=new Map;for(const u of c){const{name:a,options:d}=u,h=se(o,a,d);for(const E of h){i.has(E.model)||i.set(E.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const m=i.get(E.model);m.virtuals.find(V=>V.name===a)||(m.virtuals.push(u),m.localValueSets.set(a,new Set));const b=m.localValueSets.get(a);E.docs.forEach(V=>{const x=V[d.localField];if(x!=null){const _=String(x);b.add(_);let R=-1;const v=V;v.id!==void 0?R=o.findIndex(F=>F.id===v.id):v._id!==void 0&&(R=o.findIndex(F=>{var S,g,p,y;return((g=(S=F._id)==null?void 0:S.toString)==null?void 0:g.call(S))===((y=(p=v._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(i.entries()).map(u=>l(null,[u],function*([a,d]){const h=s.models[a];if(!h)return;const E=new Set;if(d.localValueSets.forEach(_=>{_.forEach(R=>E.add(R))}),E.size===0)return;const m=[...new Set(d.virtuals.map(_=>_.options.foreignField))],b=Array.from(E);let V;m.length===1?V={[String(m[0])]:{$in:b}}:V={$or:m.map(_=>({[_]:{$in:b}}))};const x=yield h.find(V,n).lean();for(const _ of d.virtuals){const{name:R,options:v}=_,F=x.filter(S=>{const g=S[v.foreignField];return g!=null&&E.has(String(g))});if(v.count){const S=new Map;F.forEach(g=>{var p;const y=(p=g[v.foreignField])==null?void 0:p.toString();y&&S.set(y,(S.get(y)||0)+1)}),d.localValueSets.get(R).forEach(g=>{const p=d.docsByLocalValue.get(g)||[],y=S.get(g)||0;p.forEach(w=>{const C=o[w];C[R]===void 0&&(C[R]=y)})})}else{const S=new Map;F.forEach(g=>{var p;const y=(p=g[v.foreignField])==null?void 0:p.toString();y&&(S.has(y)||S.set(y,[]),S.get(y).push(g))}),d.localValueSets.get(R).forEach(g=>{const p=d.docsByLocalValue.get(g)||[],y=S.get(g)||[],w=v.justOne?y[0]||null:y;p.forEach(C=>{const L=o[C];L[R]=w})})}}}))),o})}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({},A.createGenericFields()),t);return(yield this.collection.insertOne(e)).acknowledged?{success:!0,message:"Document created successfully",result:e}:{success:!1,message:"Document creation failed",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(e){return f.catchError(e)}})}createMany(t){return l(this,null,function*(){try{const e=t.map(n=>O(O({},A.createGenericFields()),n)),r=yield this.collection.insertMany(e);return r.insertedCount===0?{success:!1,message:"No documents were inserted",code:D.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 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:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(e){return f.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 f.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 f.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:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document updated successfully",result:r}}catch(r){return f.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:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents updated successfully",result:r}}catch(r){return f.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:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document deleted successfully",result:e}}catch(e){return f.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:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents deleted successfully",result:e}}catch(e){return f.catchError(e)}})}}class oe{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 z(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 z(this.model.base,t,r,e):t})}findOne(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=N.normalizeMongoFilter(t),o=this.model.findOne(c,e,r),i=this.getDynamicVirtuals(),u=I(n,i);u&&o.populate(u);const a=yield o.exec();return a?{success:!0,result:yield this.populateDynamicVirtualsForDocument(a,n)}:{success:!1,message:`No ${this.getModelName()} found.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(c){return f.catchError(c)}})}findAll(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=N.normalizeMongoFilter(t),o=this.model.find(c,e,r),i=this.getDynamicVirtuals(),u=I(n,i);u&&o.populate(u);const a=yield o.exec();return{success:!0,result:yield this.populateDynamicVirtualsForDocuments(a,n)}}catch(c){return f.catchError(c)}})}findPaging(){return l(this,arguments,function*(t={},e={}){try{const r=N.normalizeMongoFilter(t),n=this.getDynamicVirtuals(),c=O({},e);e.populate&&(c.populate=I(e.populate,n));const o=yield this.model.paginate(r,c),i=yield this.populateDynamicVirtualsForDocuments(o.docs,e.populate);return{success:!0,result:P(O({},o),{docs:i})}}catch(r){return f.catchError(r)}})}findPagingAggregate(t){return l(this,arguments,function*(e,r={}){try{const n=this.getDynamicVirtuals(),c=O({},r);r.populate&&(c.populate=I(r.populate,n));const o=yield this.model.aggregatePaginate(this.model.aggregate(e),c),i=yield this.populateDynamicVirtualsForDocuments(o.docs,r.populate);return{success:!0,result:P(O({},o),{docs:i})}}catch(n){return f.catchError(n)}})}count(){return l(this,arguments,function*(t={}){try{const e=N.normalizeMongoFilter(t);return{success:!0,result:yield this.model.countDocuments(e)}}catch(e){return f.catchError(e)}})}createOne(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.create(t)}}catch(e){return f.catchError(e)}})}createMany(t){return l(this,arguments,function*(e,r={}){try{return{success:!0,result:(yield this.model.insertMany(e,r)).map(o=>o instanceof H.Document?o.toObject():null).filter(o=>o!==null)}}catch(n){return f.catchError(n)}})}updateOne(){return l(this,arguments,function*(t={},e={},r={}){try{const n=N.normalizeMongoFilter(t),c=yield this.model.findOneAndUpdate(n,e,O({new:!0},r)).exec();return c?{success:!0,result:c}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(n){return f.catchError(n)}})}updateMany(){return l(this,arguments,function*(t={},e={},r={}){try{const n=N.normalizeMongoFilter(t);return{success:!0,result:yield this.model.updateMany(n,e,r).exec()}}catch(n){return f.catchError(n)}})}deleteOne(){return l(this,arguments,function*(t={},e={}){try{const r=N.normalizeMongoFilter(t),n=yield this.model.findOneAndDelete(r,e).exec();return n?{success:!0,result:n}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return f.catchError(r)}})}deleteMany(){return l(this,arguments,function*(t={},e={}){try{const r=N.normalizeMongoFilter(t),n=yield this.model.deleteMany(r,e).exec();return n.deletedCount===0?{success:!1,message:"No documents found to delete.",code:D.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:n}}catch(r){return f.catchError(r)}})}createShortId(t,e=4){return l(this,null,function*(){try{const n=Array.from({length:10},(i,u)=>j.generateShortId(t,u+e)),o=(yield Promise.all(n.map(i=>this.model.exists({shortId:i})))).findIndex(i=>!i);if(o!==-1){const i=n[o];if(i)return{success:!0,result:i}}return{success:!1,message:"Failed to create a unique shortId",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return f.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,filter:n}){const c=O({},n!=null?n:{});return r?P(O({},c),{$or:[{[`slug.${e}`]:t},{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]}):P(O({},c),{$or:[{slug:t},{slugHistory:t}]})}createUniqueSlug(t){return l(this,arguments,function*({slug:e,field:r,isObject:n,filter:c}){const o=j.generateSlug(e),u=Array.from({length:100},(h,E)=>E===0?o:`${o}-${E}`),d=(yield Promise.all(u.map(h=>this.model.exists(this.createSlugQuery({slug:h,field:r,isObject:n,filter:c}))))).findIndex(h=>!h);if(d!==-1){const h=u[d];if(h)return h}return`${o}-${Date.now()}`})}createSlug(t){return l(this,arguments,function*({field:e,from:r,filter:n}){try{const c=r[e];return q.isObject(c)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(c).map(a=>l(this,[a],function*([d,h]){const E=yield this.createUniqueSlug({slug:h,field:d,isObject:!0,filter:n});return[d,E]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:c,field:e,isObject:!1,filter:n})}}catch(c){return f.catchError(c)}})}checkSlug(t){return l(this,arguments,function*({slug:e,field:r,from:n,filter:c}){try{const o=n[r];if(q.isObject(o)){const h=Object.values(o).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 u=j.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:u,field:r,isObject:!1,filter:c})))!==null}}catch(o){return f.catchError(o)}})}aggregate(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return f.catchError(e)}})}}exports.MongoController=ce;exports.MongooseController=oe;exports.mongo=A;
@@ -41,11 +41,11 @@ export declare const mongo: {
41
41
  * @param mongoose - The Mongoose instance to create the schema with.
42
42
  * @returns A Mongoose schema with generic document fields.
43
43
  */
44
- createGenericSchema(mongoose: typeof mongooseRaw): mongooseRaw.Schema<I_GenericDocument, mongooseRaw.Model<I_GenericDocument, any, any, any, mongooseRaw.Document<unknown, any, I_GenericDocument, any> & I_GenericDocument & Required<{
44
+ createGenericSchema(mongoose: typeof mongooseRaw): mongooseRaw.Schema<I_GenericDocument, mongooseRaw.Model<I_GenericDocument, any, any, any, mongooseRaw.Document<unknown, any, I_GenericDocument, any, {}> & I_GenericDocument & Required<{
45
45
  _id: unknown;
46
46
  }> & {
47
47
  __v: number;
48
- }, any>, {}, {}, {}, {}, mongooseRaw.DefaultSchemaOptions, I_GenericDocument, mongooseRaw.Document<unknown, {}, mongooseRaw.FlatRecord<I_GenericDocument>, {}> & mongooseRaw.FlatRecord<I_GenericDocument> & Required<{
48
+ }, any>, {}, {}, {}, {}, mongooseRaw.DefaultSchemaOptions, I_GenericDocument, mongooseRaw.Document<unknown, {}, mongooseRaw.FlatRecord<I_GenericDocument>, {}, mongooseRaw.ResolveSchemaOptions<mongooseRaw.DefaultSchemaOptions>> & mongooseRaw.FlatRecord<I_GenericDocument> & Required<{
49
49
  _id: unknown;
50
50
  }> & {
51
51
  __v: number;
@@ -137,9 +137,9 @@ export declare const mongo: {
137
137
  }) => void;
138
138
  init(): Promise<void>;
139
139
  create(description: string): Promise<string>;
140
- up(db: import('mongodb').Db, client: import('mongodb').MongoClient): Promise<string[]>;
141
- down(db: import('mongodb').Db, client: import('mongodb').MongoClient): Promise<string[]>;
142
- status(db: import('mongodb').Db): Promise<migrate.MigrationStatus[]>;
140
+ up(db: mongooseRaw.mongo.Db, client: mongooseRaw.mongo.MongoClient): Promise<string[]>;
141
+ down(db: mongooseRaw.mongo.Db, client: mongooseRaw.mongo.MongoClient): Promise<string[]>;
142
+ status(db: mongooseRaw.mongo.Db): Promise<migrate.MigrationStatus[]>;
143
143
  database: typeof migrate.database;
144
144
  config: typeof migrate.config;
145
145
  };
@@ -160,6 +160,22 @@ export declare const mongo: {
160
160
  * @returns True if the options contain a dynamic ref function.
161
161
  */
162
162
  isDynamicVirtual<T, R extends string = string>(options?: T_VirtualOptions<T, R>): options is I_DynamicVirtualOptions<T, R>;
163
+ /**
164
+ * Generic utility function to get new records from the database
165
+ * @param controller - MongoController instance
166
+ * @param recordsToCheck - Array of records to check
167
+ * @param filterFn - Function to determine if a record already exists
168
+ * @returns Array of records that don't exist in the database
169
+ */
170
+ getNewRecords<T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean): Promise<T[]>;
171
+ /**
172
+ * Generic utility function to get existing records that match the filter criteria
173
+ * @param controller - MongoController instance
174
+ * @param recordsToCheck - Array of records to check
175
+ * @param filterFn - Function to determine if a record exists
176
+ * @returns Array of existing records that match the filter criteria
177
+ */
178
+ getExistingRecords<T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean): Promise<T_WithId<T>[]>;
163
179
  };
164
180
  /**
165
181
  * MongoDB native driver controller for direct database operations.