@h3ravel/arquebus 0.3.0 → 0.3.2

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 (34) hide show
  1. package/README.md +1 -1
  2. package/bin/index.cjs +4419 -1
  3. package/bin/index.d.cts +1 -1
  4. package/bin/index.d.ts +1 -1
  5. package/bin/index.js +4384 -1
  6. package/dist/browser/index.cjs +1269 -1
  7. package/dist/browser/index.d.cts +1222 -1202
  8. package/dist/browser/index.d.ts +1222 -1202
  9. package/dist/browser/index.js +1217 -1
  10. package/dist/index.cjs +4181 -1
  11. package/dist/index.d.cts +1306 -1280
  12. package/dist/index.d.ts +1306 -1280
  13. package/dist/index.js +4116 -1
  14. package/dist/migrations/chunk-PECeCxCb.js +15 -0
  15. package/dist/migrations/index.cjs +4064 -1
  16. package/dist/migrations/index.d.cts +1250 -1243
  17. package/dist/migrations/index.d.ts +1247 -1243
  18. package/dist/migrations/index.js +3994 -1
  19. package/package.json +3 -3
  20. package/bin/cli.cjs +0 -4942
  21. package/bin/cli.d.cts +0 -18
  22. package/bin/cli.d.ts +0 -18
  23. package/bin/cli.js +0 -4907
  24. package/bin/utils.js +0 -141
  25. /package/{bin → dist}/migrations/stubs/migration-js.stub +0 -0
  26. /package/{bin → dist}/migrations/stubs/migration-ts.stub +0 -0
  27. /package/{bin → dist}/migrations/stubs/migration.create-js.stub +0 -0
  28. /package/{bin → dist}/migrations/stubs/migration.create-ts.stub +0 -0
  29. /package/{bin → dist}/migrations/stubs/migration.update-js.stub +0 -0
  30. /package/{bin → dist}/migrations/stubs/migration.update-ts.stub +0 -0
  31. /package/{bin → dist}/stubs/arquebus.config-js.stub +0 -0
  32. /package/{bin → dist}/stubs/arquebus.config-ts.stub +0 -0
  33. /package/{bin → dist}/stubs/model-js.stub +0 -0
  34. /package/{bin → dist}/stubs/model-ts.stub +0 -0
package/dist/index.js CHANGED
@@ -1 +1,4116 @@
1
- import{trim as t,assign as e,diff as s,pick as i,omit as r,isEmpty as n,isArray as a,isEqual as o,isString as h,snake as l,flat as c,set as u,get as g,camel as d,dash as y,isNullish as m}from"radashi";import p from"dayjs/plugin/advancedFormat.js";import f from"dayjs";import w,{collect as b,Collection as C}from"collect.js";import v from"knex";import K from"path";import{existsSync as P}from"fs";import N from"pluralize";import A from"chalk";import D,{access as x}from"fs/promises";import T from"escalade/sync";import R from"resolve-from";var S=Object.defineProperty,q=class t{get;set;withCaching=!1;withObjectCaching=!0;constructor({get:t=null,set:e=null}){this.get=t,this.set=e}static make({get:e=null,set:s=null}){return new t({get:e,set:s})}static get(e){return new t({get:e})}static set(e){return new t({set:e})}withoutObjectCaching(){return this.withObjectCaching=!1,this}shouldCache(){return this.withCaching=!0,this}},M=class extends Error{constructor(t,e){super(t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t}},k=class extends M{model;ids=[];constructor(){super("")}setModel(t,e=[]){return this.model=t,this.ids=a(e)?e:[e],this.message=`No query results for model [${t}]`,this.ids.length>0?this.message+=" "+this.ids.join(", "):this.message+=".",this}getModel(){return this.model}getIds(){return this.ids}},I=class extends M{},E=class extends M{},Q={};function _(t,...e){return e.reduce((t,e)=>"function"==typeof e&&e.prototype?class extends t{constructor(...t){super(...t),Object.getOwnPropertyNames(e.prototype).forEach(t=>{"constructor"!==t&&Object.defineProperty(this,t,Object.getOwnPropertyDescriptor(e.prototype,t))})}}:"function"==typeof e?e(t):t,t)}((t,e)=>{for(var s in e)S(t,s,{get:e[s],enumerable:!0})})(Q,{compose:()=>_}),f.extend(p);var F=(t="YYYY-MM-DD HH:mm:ss")=>f().format(t),O=t=>l(t.substring(8)),W=t=>l(t.substring(5)),B=t=>d(`relation_${t}`),H=t=>d(`scope_${t}`),j=t=>d(`attribute_${t}`),L=t=>d(`get_${t}_attribute`),U=t=>d(`set_${t}_attribute`),$=t=>t.substring(3,t.length-9).toLowerCase(),J=(t,e)=>{const s=e(t);return s instanceof Promise?s.then(()=>t):t},{compose:z}=Q,G=t=>Array.isArray(t)?t.reduce((t,e)=>t.concat(G(e)),[]):[t],V=e=>t(y(e.replace(/[^a-zA-Z0-9_-]/g,"-")),"_-"),Y=e=>t(l(e.replace(/[^a-zA-Z0-9_-]/g,"-")),"_-"),Z=t=>t,X=class{query;parent;related;eagerKeysWereEmpty=!1;static constraints=!0;static selfJoinCount=0;constructor(t,e){this.query=t,this.parent=e,this.related=this.query.model}static extend(t){for(const e in t)this.prototype[e]=t[e]}static noConstraints(t){const e=this.constraints;this.constraints=!1;try{return t()}finally{this.constraints=e}}asProxy(){return new Proxy(this,{get:function(t,e){return void 0!==t[e]?t[e]:"string"==typeof e&&"function"==typeof t.query[e]?(...s)=>(t.query[e](...s),t.asProxy()):void 0}})}getRelated(){return this.related}getKeys(t,e){return t.map(t=>e?t.attributes[e]:t.getKey()).sort()}getRelationQuery(){return this.query}whereInEager(t,e,s,i=null){(i||this.query)[t](e,s),0===s.length&&(this.eagerKeysWereEmpty=!0)}whereInMethod(t,e){return"whereIn"}getEager(){return this.eagerKeysWereEmpty?this.query.getModel().newCollection():this.get()}async get(t=["*"]){return await this.query.get(t)}async first(t=["*"]){return await this.query.first(t)}async paginate(...t){return await this.query.paginate(...t)}async count(...t){return await this.query.clearSelect().count(...t)}toSql(){return this.query.toSql()}addConstraints(){}getRelationCountHash(t=!0){return"arquebus_reserved_"+(t?this.constructor.selfJoinCount++:this.constructor.selfJoinCount)}getRelationExistenceQuery(t,e,s=["*"]){return t.select(s).whereColumn(this.getQualifiedParentKeyName(),"=",this.getExistenceCompareKey())}getRelationExistenceCountQuery(t,e){const s=this.related.getConnection();return this.getRelationExistenceQuery(t,e,s.raw("count(*)"))}getQualifiedParentKeyName(){return this.parent.getQualifiedKeyName()}getExistenceCompareKey(){return this.getQualifiedForeignKeyName?.()}},tt=t=>class extends t{_withDefault;withDefault(t=!0){return this._withDefault=t,this}getDefaultFor(t){if(!this._withDefault)return null;const e=this.newRelatedInstanceFor(t);if("function"==typeof this._withDefault)return this._withDefault(e,t)||e;if("object"==typeof this._withDefault)for(const t in this._withDefault)e.setAttribute(t,this._withDefault[t]);return e}},et=class extends(z(X,tt)){foreignKey;ownerKey;child;relationName;constructor(t,e,s,i,r){return super(t,e),this.foreignKey=s,this.ownerKey=i,this.child=e,this.relationName=r,this.addConstraints(),this.asProxy()}async getResults(){if(null===this.child[this.foreignKey])return this.getDefaultFor(this.parent);return await this.query.first()||this.getDefaultFor(this.parent)}match(t,e,s){const i=this.foreignKey,r=this.ownerKey,n={};return e.map(t=>{const e=t.attributes[r];n[e]=t}),t.map(t=>{const e=t[i];void 0!==n[e]&&t.setRelation(s,n[e])}),t}getQualifiedForeignKeyName(){return this.child.qualifyColumn(this.foreignKey)}getRelationExistenceQuery(t,e,s=["*"]){return e.getQuery()._single.table===t.getQuery()._single.table?this.getRelationExistenceQueryForSelfRelation(t,e,s):t.select(s).whereColumn(this.getQualifiedForeignKeyName(),"=",t.qualifyColumn(this.ownerKey))}getRelationExistenceQueryForSelfRelation(t,e,s=["*"]){const i=this.getRelationCountHash();return t.select(s).from(t.getModel().getTable()+" as "+i),t.getModel().setTable(i),t.whereColumn(`${i}.${this.ownerKey}`,"=",this.getQualifiedForeignKeyName())}initRelation(t,e){return t.forEach(t=>{t.setRelation(e,this.getDefaultFor(t))}),t}addEagerConstraints(t){const e=`${this.related.getTable()}.${this.ownerKey}`;this.query.whereIn(e,this.getEagerModelKeys(t))}getEagerModelKeys(t){const e=[];return t.forEach(t=>{const s=t[this.foreignKey];null!=s&&e.push(s)}),e.sort(),[...new Set(e)]}associate(t){const e=t instanceof Kt?t.attributes[this.ownerKey]:t;return this.child[this.foreignKey]=e,t instanceof Kt?this.child.setRelation(this.relationName,t):this.child.unsetRelation(this.relationName),this.child}dissociate(){return this.child[this.foreignKey]=null,this.child.setRelation(this.relationName,null)}addConstraints(){if(this.constructor.constraints){const t=this.related.getTable();this.query.where(`${t}.${this.ownerKey}`,"=",this.child[this.foreignKey])}}newRelatedInstanceFor(t){return this.related.newInstance()}},st=class t{constructor(){if(this.constructor===t)throw new Error("CastsAttributes cannot be instantiated")}static get(t,e,s,i){throw new Error("get not implemented")}static set(t,e,s,i){throw new Error("set not implemented")}},it=t=>class extends t{static castTypeCache={};attributes={};original={};casts={};changes={};appends=[];setAppends(t){return this.appends=t,this}append(...t){const e=G(t);return this.appends=[...this.appends,...e],this}normalizeCastClassResponse(t,e){return"Object"===e?.constructor?.name?e:{[t]:e}}syncOriginal(){return this.original=this.getAttributes(),this}syncChanges(){return this.changes=this.getDirty(),this}syncOriginalAttribute(t){this.syncOriginalAttributes(t)}syncOriginalAttributes(...t){t=G(t);const e=this.getAttributes();for(const s of t)this.original[s]=e[s];return this}isDirty(...t){const e=this.getDirty();if(0===(t=G(t)).length)return Object.keys(e).length>0;for(const s of t)if(s in e)return!0;return!1}getDirty(){const t={},e=this.getAttributes();for(const s in e){const i=e[s];this.originalIsEquivalent(s)||(t[s]=i)}return t}originalIsEquivalent(t){if(void 0===this.original[t])return!1;return this.attributes[t]===this.original[t]}setAttributes(t){this.attributes={...t}}setRawAttributes(t,e=!1){return this.attributes=t,e&&this.syncOriginal(),this}getAttributes(){return{...this.attributes}}setAttribute(t,e){const s=U(t);if("function"==typeof this[s])return this[s](e),this;const i=j(t);if("function"==typeof this[i]){const s=this[i]().set||(e=>{this.attributes[t]=e});return this.attributes={...this.attributes,...this.normalizeCastClassResponse(t,s(e,this.attributes))},this}const r=this.getCasts()[t];return this.isCustomCast(r)&&"string"!=typeof r&&(e=r.set(this,t,e,this.attributes)??""),"json"===r&&(e=JSON.stringify(e)),"collection"===r&&(e=JSON.stringify(e)),null!==e&&this.isDateAttribute(t)&&(e=this.fromDateTime(e)),this.attributes[t]=e,this}getAttribute(t){if(!t)return;const e=L(t);if("function"==typeof this[e])return this[e](this.attributes[t],this.attributes);const s=j(t);if("function"==typeof this[s]){return this[s]().get(this.attributes[t],this.attributes)}return t in this.attributes?this.hasCast(t)?this.castAttribute(t,this.attributes[t]):this.getDates().includes(t)?this.asDateTime(this.attributes[t]):this.attributes[t]:t in this.relations?this.relations[t]:void 0}castAttribute(t,e){const s=this.getCastType(t);if(!s)return e;if(null===e)return e;switch(s){case"int":case"integer":return parseInt(e);case"real":case"float":case"double":return parseFloat(e);case"decimal":return this.asDecimal(e,s.split(":")[1]);case"string":return String(e);case"bool":case"boolean":return Boolean(e);case"object":case"json":try{return JSON.parse(e)}catch{return null}case"collection":try{return w(JSON.parse(e))}catch{return w([])}case"date":return this.asDate(e);case"datetime":case"custom_datetime":return this.asDateTime(e);case"timestamp":return this.asTimestamp(e)}return this.isCustomCast(s)?s.get(this,t,e,this.attributes):e}attributesToData(){let t={...this.attributes};for(const e in t)this.hidden.includes(e)&&(t=r(t,[e])),this.visible.length>0&&!1===this.visible.includes(e)&&(t=r(t,[e]));for(const e of this.getDates())void 0!==t[e]&&(t[e]=this.serializeDate(this.asDateTime(t[e])));const e=this.getCasts();for(const s in e){const i=e[s];s in t!=!1&&(t[s]=this.castAttribute(s,t[s]),s in t&&["date","datetime"].includes(String(i))&&(t[s]=this.serializeDate(t[s])),s in t&&this.isCustomDateTimeCast(i)&&(t[s]=f(t[s]).format(String(i).split(":")[1])))}for(const e of this.appends)t[e]=this.mutateAttribute(e,null);return t}mutateAttribute(t,e){if("function"==typeof this[L(t)])return this[L(t)](e);if("function"==typeof this[j(t)]){return this[j(t)]().get(t,this.attributes)}return t in this?this[t]:e}mutateAttributeForArray(t,e){}isDateAttribute(t){return this.getDates().includes(t)||this.isDateCastable(t)}serializeDate(t){return t?f(t).toISOString():null}getDates(){return this.usesTimestamps()?[this.getCreatedAtColumn(),this.getUpdatedAtColumn()]:[]}getCasts(){return this.getIncrementing()?{[this.getKeyName()]:this.getKeyType(),...this.casts}:this.casts}getCastType(t){const e=this.getCasts()[t];let s,i;return"string"==typeof e?s=e:new e instanceof st&&(s=e.name),s&&void 0!==this.getConstructor().castTypeCache[s]?this.getConstructor().castTypeCache[s]:(i=this.isCustomDateTimeCast(e)?"custom_datetime":this.isDecimalCast(e)?"decimal":this.isCustomCast(e)?e:String(e).toLocaleLowerCase().trim(),this.getConstructor()[s]=i)}hasCast(t,e=[]){return t in this.casts&&(!((e=c(e)).length>0)||e.includes(this.getCastType(t)))}withDayjs(t){return f(t)}isCustomCast(t){return"function"==typeof t&&new t instanceof st}isCustomDateTimeCast(t){return"string"==typeof t&&(t.startsWith("date:")||t.startsWith("datetime:"))}isDecimalCast(t){return"string"==typeof t&&t.startsWith("decimal:")}isDateCastable(t){return this.hasCast(t,["date","datetime"])}fromDateTime(t){return f(this.asDateTime(t)).format(this.getDateFormat())}getDateFormat(){return this.dateFormat||"YYYY-MM-DD HH:mm:ss"}asDecimal(t,e){return parseFloat(t).toFixed(e)}asDateTime(t){return null===t?null:t instanceof Date?t:"number"==typeof t?new Date(1e3*t):new Date(t)}asDate(t){const e=this.asDateTime(t);return f(e).startOf("day").toDate()}},rt=class t{constructor(){if(this.constructor===t)throw new Error("Scope cannot be instantiated")}apply(t,e){throw new Error("apply not implemented")}},nt=t=>class extends t{static globalScopes;static addGlobalScope(t,e=null){if("string"==typeof t&&e instanceof rt)return this.globalScopes=u(this.globalScopes??{},this.name+"."+t,e),e;if(t instanceof rt)return this.globalScopes=u(this.globalScopes??{},this.name+"."+t.constructor.name,t),t;throw new E("Global scope must be an instance of Scope.")}static hasGlobalScope(t){return null!==this.getGlobalScope(t)}static getGlobalScope(t){return g(this.globalScopes,"string"==typeof t?this.name+"."+t:this.name+"."+t.constructor.name)}static getAllGlobalScopes(){return this.globalScopes}static setAllGlobalScopes(t){this.globalScopes=t}getGlobalScopes(){return g(this.constructor.globalScopes,this.constructor.name,{})}},at=class{hooks={creating:[],created:[],updating:[],updated:[],saving:[],saved:[],deleting:[],deleted:[],restoring:[],restored:[],trashed:[],forceDeleting:[],forceDeleted:[]};add(t,e){this.hooks[t].push(e)}async exec(t,e){const s=this.hooks[t]??[];for(const t of s)await t(...e);return!0}},ot=t=>class extends t{static hooks=null;static addHook(t,e){this.hooks instanceof at==!1&&(this.hooks=new at),this.hooks.add(t,e)}static creating(t){this.addHook("creating",t)}static created(t){this.addHook("created",t)}static updating(t){this.addHook("updating",t)}static updated(t){this.addHook("updated",t)}static saving(t){this.addHook("saving",t)}static saved(t){this.addHook("saved",t)}static deleting(t){this.addHook("deleting",t)}static deleted(t){this.addHook("deleted",t)}static restoring(t){this.addHook("restoring",t)}static restored(t){this.addHook("restored",t)}static trashed(t){this.addHook("trashed",t)}static forceDeleted(t){this.addHook("forceDeleted",t)}async execHooks(t,e){if(this.constructor.hooks instanceof at!=!1)return await this.constructor.hooks.exec(t,[this,e])}},ht=t=>class extends t{getRelationValue(t,e,s){const i=t[e];return"one"===s?i[0]:new At(i)}matchOneOrMany(t,e,s,i){const r=this.buildDictionary(e);return t.map(t=>{const e=t.attributes[this.localKey];void 0!==r[e]&&t.setRelation(s,this.getRelationValue(r,e,i))}),t}buildDictionary(t){const e=this.getForeignKeyName();return w(t).mapToDictionary(t=>[t[e],t]).all()}async save(t){return this.setForeignAttributesForCreate(t),!!await t.save()&&t}async saveMany(t){return await Promise.all(t.map(async t=>{await this.save(t)})),t instanceof At?t:new At(t)}async create(t={}){return await J(this.related.constructor.init(t),async t=>{this.setForeignAttributesForCreate(t),await t.save()})}async createMany(t){const e=await Promise.all(t.map(async t=>await this.create(t)));return e instanceof At?e:new At(e)}setForeignAttributesForCreate(t){t[this.getForeignKeyName()]=this.getParentKey()}getForeignKeyName(){const t=this.getQualifiedForeignKeyName().split(".");return t[t.length-1]}getParentKey(){return this.parent.attributes[this.localKey]}getQualifiedForeignKeyName(){return this.foreignKey}getExistenceCompareKey(){return this.getQualifiedForeignKeyName()}addConstraints(){if(this.constructor.constraints){const t=this.getRelationQuery();t.where(this.foreignKey,"=",this.getParentKey()),t.whereNotNull(this.foreignKey)}}},lt=class extends(z(X,ht)){foreignKey;localKey;constructor(t,e,s,i){return super(t,e),this.foreignKey=s,this.localKey=i,this.addConstraints(),this.asProxy()}initRelation(t,e){return t.map(t=>{t.setRelation(e,new At([]))}),t}async getResults(){return null!==this.getParentKey()?await this.query.get():new At([])}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}buildDictionary(t){const e=this.getForeignKeyName();return b(t).mapToDictionary(t=>[t[e],t]).all()}match(t,e,s){return this.matchOneOrMany(t,e,s,"many")}addEagerConstraints(t){this.query.whereIn(this.foreignKey,this.getKeys(t,this.localKey))}},ct=class extends(z(X,ht,tt)){foreignKey;localKey;constructor(t,e,s,i){return super(t,e),this.foreignKey=s,this.localKey=i,this.addConstraints(),this.asProxy()}initRelation(t,e){return t.map(t=>{t.setRelation(e,this.getDefaultFor(t))}),t}matchOne(t,e,s){return this.matchOneOrMany(t,e,s,"one")}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}async getResults(){if(null===this.getParentKey())return this.getDefaultFor(this.parent);return await this.query.first()||this.getDefaultFor(this.parent)}match(t,e,s){return this.matchOneOrMany(t,e,s,"one")}addEagerConstraints(t){this.query.whereIn(this.foreignKey,this.getKeys(t,this.localKey))}newRelatedInstanceFor(t){return this.related.newInstance().setAttribute(this.getForeignKeyName(),t[this.localKey])}},ut=class extends X{throughParent;farParent;firstKey;secondKey;localKey;secondLocalKey;constructor(t,e,s,i,r,n,a){return super(t,s),this.localKey=n,this.firstKey=i,this.secondKey=r,this.farParent=e,this.throughParent=s,this.secondLocalKey=a,this.asProxy()}addConstraints(){const t=this.farParent[this.localKey];this.performJoin(),this.constructor.constraints&&this.query.where(this.getQualifiedFirstKeyName(),"=",t)}performJoin(t=null){t=t||this.query;const e=this.getQualifiedFarKeyName();t.join(this.throughParent.getTable(),this.getQualifiedParentKeyName(),"=",e),this.throughParentSoftDeletes()&&t.withGlobalScope("SoftDeletableHasManyThrough",t=>{t.whereNull(this.throughParent.getQualifiedDeletedAtColumn())})}getQualifiedParentKeyName(){return this.parent.qualifyColumn(this.secondLocalKey)}throughParentSoftDeletes(){return void 0!==this.throughParent.pluginInitializers.SoftDeletes}withTrashedParents(){return this.query.withoutGlobalScope("SoftDeletableHasManyThrough"),this}addEagerConstraints(t){const e=this.whereInMethod(this.farParent,this.localKey);this.whereInEager(e,this.getQualifiedFirstKeyName(),this.getKeys(t,this.localKey))}initRelation(t,e){for(const s of t)s.setRelation(e,this.related.newCollection());return t}match(t,e,s){const i=this.buildDictionary(e);for(const e of t){const t=this.getDictionaryKey(e.getAttribute(this.localKey));void 0!==i[t]&&e.setRelation(s,this.related.newCollection(i[t]))}return t}buildDictionary(t){const e={};for(const s of t)void 0===e[s.laravel_through_key]&&(e[s.laravel_through_key]=[]),e[s.laravel_through_key].push(s);return e}async firstOrNew(t){return await this.where(t).first()||this.related.newInstance(t)}async updateOrCreate(t,e={}){return J(await this.firstOrCreate(t,e),async t=>{t.wasRecentlyCreated||await t.fill(e).save()})}async firstWhere(t,e=null,s=null,i="and"){return await this.where(t,e,s,i).first()}async first(t=["*"]){const e=await this.take(1).get(t);return e.count()>0?e.first():null}async firstOrFail(t=["*"]){const e=await this.first(t);if(e)return e;throw(new k).setModel(this.related.constructor)}async firstOr(t=["*"],e=null){"function"==typeof t&&(e=t,t=["*"]);const s=await this.first(t);return s||e?.()}async find(t,e=["*"]){return a(t)?await this.findMany(t,e):await this.where(this.getRelated().getQualifiedKeyName(),"=",t).first(e)}async findMany(t,e=["*"]){return 0===t.length?this.getRelated().newCollection():await this.whereIn(this.getRelated().getQualifiedKeyName(),t).get(e)}async findOrFail(t,e=["*"]){const s=await this.find(t,e);if(Array.isArray(t)){if(s.count()===t.length)return s}else if(s)return s;throw(new k).setModel(this.related.constructor,t)}async getResults(){return this.farParent[this.localKey]?await this.get():this.related.newCollection()}async get(t=["*"]){const e=this.prepareQueryBuilder(t);let s=await e.getModels();return s.count()>0&&(s=await e.eagerLoadRelations(s)),this.related.newCollection(s)}async paginate(t=null,e=["*"],s="page",i=null){return this.query.addSelect(this.shouldSelect(e)),await this.query.paginate(t,e,s,i)}shouldSelect(t=["*"]){return"*"==t?.at(0)&&(t=[this.related.getTable()+".*"]),[...t,this.getQualifiedFirstKeyName()+" as laravel_through_key"]}async chunk(t,e){return await this.prepareQueryBuilder().chunk(t,e)}prepareQueryBuilder(t=["*"]){const e=this.query.applyScopes();return e.addSelect(this.shouldSelect(e.getQuery().columns?[]:t))}getRelationExistenceQuery(t,e,s=["*"]){return e.getQuery().from===t.getQuery().from?this.getRelationExistenceQueryForSelfRelation(t,e,s):e.getQuery().from===this.throughParent.getTable()?this.getRelationExistenceQueryForThroughSelfRelation(t,e,s):(this.performJoin(t),t.select(s).where(this.getQualifiedLocalKeyName(),"=",this.getQualifiedFirstKeyName()))}getRelationExistenceQueryForSelfRelation(t,e,s=["*"]){const i=this.getRelationCountHash();return t.from(t.getModel().getTable()+" as "+i),t.join(this.throughParent.getTable(),this.getQualifiedParentKeyName(),"=",i+"."+this.secondKey),this.throughParentSoftDeletes()&&t.whereNull(this.throughParent.getQualifiedDeletedAtColumn()),t.getModel().setTable(i),t.select(s).whereColumn(e.getQuery().from+"."+this.localKey,"=",this.getQualifiedFirstKeyName())}getRelationExistenceQueryForThroughSelfRelation(t,e,s=["*"]){const i=this.getRelationCountHash(),r=this.throughParent.getTable()+" as "+i;return t.join(r,i+"."+this.secondLocalKey,"=",this.getQualifiedFarKeyName()),this.throughParentSoftDeletes()&&t.whereNull(i+"."+this.throughParent.getDeletedAtColumn()),t.select(s).where(e.getQuery().from+"."+this.localKey,"=",i+"."+this.firstKey)}getQualifiedFarKeyName(){return this.getQualifiedForeignKeyName()}getFirstKeyName(){return this.firstKey}getQualifiedFirstKeyName(){return this.throughParent.qualifyColumn(this.firstKey)}getForeignKeyName(){return this.secondKey}getQualifiedForeignKeyName(){return this.related.qualifyColumn(this.secondKey)}getLocalKeyName(){return this.localKey}getQualifiedLocalKeyName(){return this.farParent.qualifyColumn(this.localKey)}getSecondLocalKeyName(){return this.secondLocalKey}},gt=class extends(z(ut,tt)){async getResults(){return await this.first()||this.getDefaultFor(this.farParent)}initRelation(t,e){for(const s of t)s.setRelation(e,this.getDefaultFor(s));return t}match(t,e,s){const i=this.buildDictionary(e);for(const e of t){const t=this.getDictionaryKey(e.getAttribute(this.localKey));if(void 0!==i[t]){const r=i[t];e.setRelation(s,r[0])}}return t}newRelatedInstanceFor(t){return this.related.newInstance()}},dt=t=>class extends t{relations={};getRelation(t){return this.relations[t]}setRelation(t,e){return this.relations[t]=e,this}unsetRelation(t){return this.relations=r(this.relations,[t]),this}relationLoaded(t){return void 0!==this.relations[t]}related(t){if("function"!=typeof this[B(t)]){const e=`Model [${this.constructor.name}]'s relation [${t}] doesn't exist.`;throw new I(e)}return this[B(t)]()}async getRelated(t){return await this.related(t).getResults()}relationsToData(){const t={};for(const e in this.relations)this.hidden.includes(e)||this.visible.length>0&&!1===this.visible.includes(e)||(t[e]=this.relations[e]instanceof Array?this.relations[e].map(t=>t.toData()):null===this.relations[e]?null:this.relations[e].toData());return t}guessBelongsToRelation(){const t=(new Error).stack.split("\n")[2].split(" ")[5];return O(t)}joiningTable(t,e=null){return[e?e.joiningTableSegment():Y(t.name),this.joiningTableSegment()].sort().join("_").toLocaleLowerCase()}joiningTableSegment(){return Y(this.constructor.name)}hasOne(t,e=null,s=null){const i=t.query(),r=new t;return e=e||this.getForeignKey(),s=s||this.getKeyName(),new ct(i,this,r.getTable()+"."+e,s)}hasMany(t,e=null,s=null){const i=t.query(),r=new t;return e=e||this.getForeignKey(),s=s||this.getKeyName(),new lt(i,this,r.getTable()+"."+e,s)}belongsTo(t,e=null,s=null,i=null){const r=t.query(),n=new t;return e=e||n.getForeignKey(),s=s||n.getKeyName(),i=i||this.guessBelongsToRelation(),new et(r,this,e,s,i)}belongsToMany(t,e=null,s=null,i=null,r=null,n=null){const a=t.query(),o=new t;return e=e||this.joiningTable(t,o),s=s||this.getForeignKey(),i=i||o.getForeignKey(),r=r||this.getKeyName(),n=n||o.getKeyName(),new xt(a,this,e,s,i,r,n)}hasOneThrough(t,e,s=null,i=null,r=null,n=null){e=new e;const a=t.query();return s=s||this.getForeignKey(),i=i||e.getForeignKey(),new gt(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}hasManyThrough(t,e,s=null,i=null,r=null,n=null){e=new e;const a=t.query();return s=s||this.getForeignKey(),i=i||e.getForeignKey(),new ut(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}},yt=t=>class extends t{static CREATED_AT="created_at";static UPDATED_AT="updated_at";static DELETED_AT="deleted_at";timestamps=!0;dateFormat="YYYY-MM-DD HH:mm:ss";usesTimestamps(){return this.timestamps}updateTimestamps(){const t=this.freshTimestampString(),e=this.getUpdatedAtColumn();e&&!this.isDirty(e)&&this.setUpdatedAt(t);const s=this.getCreatedAtColumn();return this.exists||!s||this.isDirty(s)||this.setCreatedAt(t),this}getCreatedAtColumn(){return this.constructor.CREATED_AT}getUpdatedAtColumn(){return this.constructor.UPDATED_AT}setCreatedAt(t){return this.attributes[this.getCreatedAtColumn()]=t,this}setUpdatedAt(t){return this.attributes[this.getUpdatedAtColumn()]=t,this}freshTimestamp(){const t=new Date;return t.setMilliseconds(0),t}freshTimestampString(){return this.fromDateTime(this.freshTimestamp())}},mt=t=>class extends t{hidden=[];visible=[];makeVisible(...t){const e=G(t);return this.visible.length>0&&(this.visible=[...this.visible,...e]),this.hidden=s(this.hidden,e),this}makeHidden(t,...e){const s=G([...t,...e]);return this.hidden.length>0&&(this.hidden=[...this.hidden,...s]),this}getHidden(){return this.hidden}getVisible(){return this.visible}setHidden(t){return this.hidden=t,this}setVisible(t){return this.visible=t,this}},pt=t=>class extends t{useUniqueIds=!1;usesUniqueIds(){return this.useUniqueIds}uniqueIds(){return[]}newUniqueId(){return null}setUniqueIds(){const t=this.uniqueIds();for(const e of t)null!==this[e]&&void 0!==this[e]||(this[e]=this.newUniqueId())}},ft=class{static formatter;_items;_total;_perPage;_lastPage;_currentPage;hasMore=!1;options={};static setFormatter(t){if("function"!=typeof t&&null!=t)throw new Error("Paginator formatter must be a function or null");this.formatter=t}constructor(t,e,s,i=1,r={}){this.options=r;for(const t in r){const e=r[t];this[t]=e}this._items=new At([]),this._total=e,this._perPage=parseInt(String(s)),this._lastPage=Math.max(Math.ceil(e/s),1),this._currentPage=i,this.setItems(t)}setItems(t){this._items=t instanceof At?t:new At(t),this.hasMore=this._items.count()>this._perPage,this._items=this._items.slice(0,this._perPage)}firstItem(){return this.count()>0?(this._currentPage-1)*this._perPage+1:null}lastItem(){return this.count()>0?(this.firstItem()??0)+this.count()-1:null}hasMorePages(){return this._currentPage<this._lastPage}get(t){return this._items.get(t)}count(){return this._items.count()}items(){return this._items}map(t){return this._items.map(t)}currentPage(){return this._currentPage}onFirstPage(){return 1===this._currentPage}perPage(){return this._perPage}lastPage(){return this._lastPage}total(){return this._total}toData(){return this.constructor.formatter&&"function"==typeof this.constructor.formatter?this.constructor.formatter(this):{current_page:this._currentPage,data:this._items.toData(),per_page:this._perPage,total:this._total,last_page:this._lastPage,count:this.count()}}toJSON(){return this.toData()}toJson(...t){return JSON.stringify(this.toData(),...t)}},wt=class{},bt=class t extends wt{model;schema;connector;constructor(t,e){return super(),this.connector=e(t),this.asProxy()}asProxy(){return new Proxy(this,{get:function(t,e){return void 0!==t[e]?t[e]:["destroy","schema"].includes(e)?t.connector.schema:["select","from","where","orWhere","whereColumn","whereRaw","whereNot","orWhereNot","whereIn","orWhereIn","whereNotIn","orWhereNotIn","whereNull","orWhereNull","whereNotNull","orWhereNotNull","whereExists","orWhereExists","whereNotExists","orWhereNotExists","whereBetween","orWhereBetween","whereNotBetween","orWhereNotBetween","whereLike","orWhereLike","whereILike","orWhereILike","whereJsonObject","whereJsonPath","whereJsonSupersetOf","whereJsonSubsetOf","join","joinRaw","leftJoin","leftOuterJoin","rightJoin","rightOuterJoin","crossJoin","transacting","groupBy","groupByRaw","returning","having","havingRaw","havingBetween","limit","offset","orderBy","orderByRaw","union","insert","forUpdate","forShare","distinct","clearOrder","clear","clearSelect","clearWhere","clearHaving","clearGroup"].includes(e)?(...s)=>(t.connector[e](...s),t.asProxy()):t.connector[e]},set:function(t,e,s){return void 0!==t[e]?(t[e]=s,t):(t.connector[e]=s,t)}})}async beginTransaction(){return await this.connector.transaction()}table(e){const s=this.connector.table(e);return new t(null,()=>s)}transaction(e){return e?this.connector.transaction(s=>e(new t(null,()=>s))):e}async find(t,e=["*"]){return await this.connector.where("id",t).first(...e)}async get(t=["*"]){return await this.connector}async exists(){return null!==await this.connector.first()}skip(...t){return this.offset(...t)}take(...t){return this.limit(...t)}async chunk(t,e){if(0===this.connector._statements.filter(t=>"order"===t.grouping).length)throw new Error("You must specify an orderBy clause when using this function.");let s,i=1;do{const r=this.clone(),n=await r.forPage(i,t).get();if(s=n.length,0==s)break;if(!1===await e(n,i))return!1;i++}while(s===t);return!0}async paginate(t=1,e=15){const s=this.clone(),i=await s.clearOrder().count("*");let r;if(i>0){const s=(t-1)*e;this.take(e).skip(s),r=await this.get()}else r=[];return new ft(r,parseInt(i),e,t)}forPage(t=1,e=15){return this.offset((t-1)*e).limit(e)}toSQL(...t){return this.connector.toSQL(...t)}async count(t){const[{aggregate:e}]=await this.connector.count(t,{as:"aggregate"});return Number(e)}async min(t){const[{aggregate:e}]=await this.connector.min(t,{as:"aggregate"});return Number(e)}async max(t){const[{aggregate:e}]=await this.connector.max(t,{as:"aggregate"});return Number(e)}async sum(t){const[{aggregate:e}]=await this.connector.sum(t,{as:"aggregate"});return Number(e)}async avg(t){const[{aggregate:e}]=await this.connector.avg(t,{as:"aggregate"});return Number(e)}clone(){const e=this.connector.clone();return new t(null,()=>e)}async delete(){return await this.connector.delete()}async insert(...t){return await this.connector.insert(...t)}async update(...t){return await this.connector.update(...t)}destroy(...t){return this.connector.destroy(...t)}get _statements(){return this.connector._statements}get _single(){return this.connector._single}get from(){return this.connector.from}},Ct=class t{static connectorFactory=null;static instance=null;manager;connections;models;constructor(){this.manager={},this.connections={},this.models={}}getConstructor(){return this.constructor}static getInstance(){return null===this.instance&&(this.instance=new t),this.instance}static fire(t=null){return this.getInstance().getConnection(t)}static connection(t=null){return this.fire(t)}static setConnectorFactory(t){this.connectorFactory=t}static getConnectorFactory(){return this.connectorFactory??v}static addConnection(t,e="default"){return this.getInstance().addConnection(t,e)}static beginTransaction(t=null){return this.getInstance().beginTransaction(t)}static transaction(t,e=null){return this.getInstance().transaction(t,e)}static table(t,e=null){return this.getInstance().table(t,e)}static schema(t=null){return this.getInstance().schema(t)}static async destroyAll(){await this.getInstance().destroyAll()}static createModel(t,e){return this.getInstance().createModel(t,e)}connection(t=null){return this.getConnection(t)}getConnection(e=null){if(e=e||"default",void 0===this.manager[e]){const s=new bt(this.connections[e],t.getConnectorFactory());this.manager[e]=s}return this.manager[e]}addConnection(t,e="default"){this.connections[e]={...t,connection:{...t.connection,dateStrings:!0,typeCast:function(t,e){return"JSON"===t.type?t.string("utf8"):e()}}}}static async autoLoad(t=!0){let e;const s=K.resolve("arquebus.config.js"),i=K.resolve("arquebus.config.ts"),r=this.getInstance();if(P(s))return e=(await import(s)).default,t&&r.addConnection(e,e.client),e;if(P(i)){if("production"!==process.env.NODE_ENV)return e=(await import(i)).default,t&&r.addConnection(e,e.client),e;throw new Error("arquebus.config.ts found in production without build step")}return{}}beginTransaction(t=null){return this.connection(t).beginTransaction()}transaction(t,e=null){return this.connection(e).transaction(t)}table(t,e=null){return this.connection(e).table(t)}schema(t=null){return this.connection(t).schema}async destroyAll(){await Promise.all(Object.values(this.manager).map(t=>t?.destroy()))}createModel(t,e={}){let s=Kt;if("plugins"in e&&(s=z(s,...e.plugins??[])),this.models={...this.models,[t]:class extends s{table=e?.table??null;connection=e?.connection??null;timestamps=e?.timestamps??!0;primaryKey=e?.primaryKey??"id";keyType=e?.keyType??"int";incrementing=e?.incrementing??!0;with=e?.with??[];casts=e?.casts??{};static CREATED_AT=e?.CREATED_AT??"created_at";static UPDATED_AT=e?.UPDATED_AT??"updated_at";static DELETED_AT=e?.DELETED_AT??"deleted_at"}},"attributes"in e)for(const s in e.attributes){if(e.attributes[s]instanceof q==!1)throw new Error('Attribute must be an instance of "Attribute"');this.models[t].prototype[j(s)]=()=>e.attributes?.[s]}if("relations"in e)for(const s in e.relations)this.models[t].prototype[B(s)]=function(){return e.relations?.[s](this)};if("scopes"in e)for(const s in e.scopes)this.models[t].prototype[H(s)]=e.scopes[s];return this.models[t].setConnectionResolver(this),this.models[t]}},vt=z(class{},it,mt,dt,yt,ot,nt,pt),Kt=class t extends vt{primaryKey="id";builder=null;table=null;keyType="int";incrementing=!0;withCount=[];perPage=15;static globalScopes={};static pluginInitializers={};static _booted={};static resolver;connection=null;eagerLoad={};exists=!1;with=[];trx=null;constructor(t={}){return super(),this.bootIfNotBooted(),this.initializePlugins(),this.syncOriginal(),this.fill(t),this.asProxy()}static query(t=null){return(new this).newQuery(t)}static on(t=null){const e=new this;return e.setConnection(t),e.newQuery()}static init(t={}){return new this(t)}static extend(t,e){t(this,e)}static make(t={}){const e=new this;for(const s in t)if("function"!=typeof e[B(s)])e.setAttribute(s,t[s]);else{const i=e[B(s)](),r=i.getRelated().constructor;i instanceof ct||i instanceof et?e.setRelation(s,r.make(t[s])):(i instanceof lt||i instanceof xt)&&Array.isArray(t[s])&&e.setRelation(s,new At(t[s].map(t=>r.make(t))))}return e}getConstructor(){return this.constructor}bootIfNotBooted(){void 0===this.constructor._booted[this.constructor.name]&&(this.constructor._booted[this.constructor.name]=!0,this.constructor.booting(),this.initialize(),this.constructor.boot(),this.constructor.booted())}static booting(){}static boot(){}static booted(){}static setConnectionResolver(t){this.resolver=t}initialize(){}initializePlugins(){if(void 0!==this.constructor.pluginInitializers[this.constructor.name])for(const t of this.constructor.pluginInitializers[this.constructor.name])this[t]()}addPluginInitializer(t){this.constructor.pluginInitializers[this.constructor.name]||(this.constructor.pluginInitializers[this.constructor.name]=[]),this.constructor.pluginInitializers[this.constructor.name].push(t)}newInstance(t={},e=!1){const s=new this.constructor;return s.exists=e,s.setConnection(this.getConnectionName()),s.setTable(this.getTable()),s.fill(t),s}newFromBuilder(t={},e=null){const s=this.newInstance({},!0);return s.setRawAttributes(t,!0),s.setConnection(e||this.getConnectionName()),s}asProxy(){return new Proxy(this,{get:function(t,e){return void 0!==t[e]?t[e]:"string"==typeof e?t.getAttribute(e):void 0},set:function(t,e,s){return void 0!==t[e]&&"function"!=typeof t?(t[e]=s,t):"string"==typeof e?t.setAttribute(e,s):t}})}getKey(){return this.getAttribute(this.getKeyName())}getKeyName(){return this.primaryKey}getForeignKey(){return Y(this.constructor.name)+"_"+this.getKeyName()}getConnectionName(){return this.connection}getTable(){return this.table||N(Y(this.constructor.name))}getConnection(){return this.constructor.resolver?this.constructor.resolver.getConnection(this.connection):Ct.connection(this.connection)}setConnection(t){return this.connection=t,this}getKeyType(){return this.keyType}newQuery(t=null){return this.addGlobalScopes(this.newQueryWithoutScopes(t))}newQueryWithoutScopes(t=null){return this.newModelQuery(t).with(this.with).withCount(this.withCount)}newModelQuery(t=null){return new Rt(t||this.getConnection()).setModel(this)}addGlobalScopes(t){const e=this.getGlobalScopes();for(const s in e){const i=e[s];t.withGlobalScope(s,i)}return t}hasNamedScope(t){return"function"==typeof this[H(t)]}callNamedScope(t,e){return this[H(t)](...e)}setTable(t){return this.table=t,this}newCollection(t=[]){return new At(t)}async load(...t){const e=this.constructor.query().with(...t);return await e.eagerLoadRelations([this]),this}async loadAggregate(t,e,s=null){return console.log(t),await new At([this]).loadAggregate(t,e,s),this}async loadCount(...t){return t=G(t),await this.loadAggregate(t,"*","count")}async loadMax(t,e){return await this.loadAggregate(t,e,"max")}async loadMin(t,e){return await this.loadAggregate(t,e,"min")}async loadSum(t,e){return await this.loadAggregate(t,e,"sum")}async increment(t,e=1,s={},i={}){return await this.incrementOrDecrement(t,e,s,"increment",i)}async decrement(t,e=1,s={},i={}){return await this.incrementOrDecrement(t,e,s,"decrement",i)}async incrementOrDecrement(t,e,s,i,r){const n=this.newModelQuery(r.client);if(!this.exists)return await n[i](t,e,s);this.attributes[t]=this[t]+("increment"===i?e:-1*e);for(const t in s)this.attributes[t]=s[t];return await this.execHooks("updating",r),await J(await n.where(this.getKeyName(),this.getKey())[i](t,e,s),async()=>{this.syncChanges(),await this.execHooks("updated",r),this.syncOriginalAttribute(t)})}toData(){return e(this.attributesToData(),this.relationsToData())}toJSON(){return this.toData()}toJson(...t){return JSON.stringify(this.toData(),...t)}toString(){return this.toJson()}fill(t){for(const e in t)this.setAttribute(e,t[e]);return this}transacting(t){return this.trx=t,this}trashed(){return null!==this[this.getDeletedAtColumn()]}getIncrementing(){return this.incrementing}setIncrementing(t){return this.incrementing=t,this}async save(t={}){const e=this.newModelQuery(t.client);let s;if(await this.execHooks("saving",t),this.exists)if(!1===this.isDirty())s=!0;else{await this.execHooks("updating",t),this.usesTimestamps()&&this.updateTimestamps();const i=this.getDirty();Object.keys(i).length>0&&(await e.where(this.getKeyName(),this.getKey()).query.update(i),this.syncChanges(),await this.execHooks("updated",t)),s=!0}else{this.usesUniqueIds()&&this.setUniqueIds(),await this.execHooks("creating",t),this.usesTimestamps()&&this.updateTimestamps();const i=this.getAttributes();if(this.getIncrementing()){const t=this.getKeyName(),s=await e.insert([i],[t]);this.setAttribute(t,s[0]?.[t]||s[0])}else Object.keys(i).length>0&&await e.insert(i);this.exists=!0,await this.execHooks("created",t),s=!0}return s&&(await this.execHooks("saved",t),this.syncOriginal()),s}async update(t={},e={}){if(!this.exists)return!1;for(const e in t)this[e]=t[e];return await this.save(e)}async delete(t={}){return await this.execHooks("deleting",t),await this.performDeleteOnModel(t),await this.execHooks("deleted",t),!0}async performDeleteOnModel(t={}){await this.setKeysForSaveQuery(this.newModelQuery(t.client)).delete(),this.exists=!1}setKeysForSaveQuery(t){return t.where(this.getKeyName(),"=",this.getKey()),t}async forceDelete(t={}){return await this.delete(t)}fresh(){if(this.exists)return this.constructor.query().where(this.getKeyName(),this.getKey()).first()}async refresh(){if(!this.exists)return Promise.resolve(void 0);const t=await this.constructor.query().where(this.getKeyName(),this.getKey()).first();return this.attributes={...t.attributes},await this.load(w(this.relations).reject(t=>t instanceof Pt).keys().all()),this.syncOriginal(),this}newPivot(t,e,s,i,r=null){return r?r.fromRawAttributes(t,e,s,i):Pt.fromAttributes(t,e,s,i)}qualifyColumn(t){return t.includes(".")?t:`${this.getTable()}.${t}`}getQualifiedKeyName(){return this.qualifyColumn(this.getKeyName())}async push(t={}){if(!await this.save(t))return!1;for(const e in this.relations){let s=this.relations[e];s=s instanceof At?s.all():[s];for(const e of s)if(!await e.push(t))return!1}return!0}is(e){return e&&e instanceof t&&this.getKey()===e.getKey()&&this.getTable()===e.getTable()&&this.getConnectionName()===e.getConnectionName()}isNot(t){return!this.is(t)}},Pt=class extends Kt{incrementing=!1;guarded=[];pivotParent=null;foreignKey=null;relatedKey=null;setPivotKeys(t,e){return this.foreignKey=t,this.relatedKey=e,this}static fromRawAttributes(t,e,s,i=!1){const r=this.fromAttributes(t,{},s,i);return r.timestamps=r.hasTimestampAttributes(e),r.attributes=e,r.exists=i,r}static fromAttributes(t,e,s,i=!1){const r=new this;return r.timestamps=r.hasTimestampAttributes(e),r.setConnection(t.connection).setTable(s).fill(e).syncOriginal(),r.pivotParent=t,r.exists=i,r}hasTimestampAttributes(t=null){return void 0!==(t||this.attributes)[this.constructor.CREATED_AT]}},Nt=Kt,At=class t extends C{newConstructor(...t){return new(this.getConstructor())(...t)}getConstructor(){return this.constructor}async load(...t){if(this.isNotEmpty()){const e=this.first().constructor.query().with(...t),s=await e.eagerLoadRelations(this.items);return this.newConstructor(s)}return this}async loadAggregate(t,e,r=null){if(this.isEmpty())return this;const n=(await this.first().newModelQuery().whereIn(this.first().getKeyName(),this.modelKeys()).select(this.first().getKeyName()).withAggregate(t,e,r).get()).keyBy(this.first().getKeyName()),a=s(Object.keys(n.first().getAttributes()),[n.first().getKeyName()]);return this.each(t=>{const e=i(n.get(t.getKey()).getAttributes(),a);t.fill(e).syncOriginalAttributes(...a)}),this}loadCount(t){return this.loadAggregate(t,"*","count")}loadMax(t,e){return this.loadAggregate(t,e,"max")}loadMin(t,e){return this.loadAggregate(t,e,"min")}loadSum(t,e){return this.loadAggregate(t,e,"sum")}loadAvg(t,e){return this.loadAggregate(t,e,"avg")}mapThen(t){return Promise.all(this.map(t))}modelKeys(){return this.all().map(t=>t.getKey())}contains(t,e,s){return arguments.length>1?super.contains(t,s??e):t instanceof Nt?super.contains(e=>e.is(t)):super.contains(e=>e.getKey()==t)}diff(t){const e=new this.constructor,s=this.getDictionary(t);return this.items.map(t=>{void 0===s[t.getKey()]&&e.add(t)}),e}except(t){const e=r(this.getDictionary(),t);return new this.constructor(Object.values(e))}intersect(t){const e=new this.constructor;if(n(t))return e;const s=this.getDictionary(t);for(const t of this.items)void 0!==s[t.getKey()]&&e.add(t);return e}unique(t,e=!1){return t?super.unique(t):new this.constructor(Object.values(this.getDictionary()))}find(t,e=null){return t instanceof Nt&&(t=t.getKey()),a(t)?this.isEmpty()?new this.constructor:this.whereIn(this.first().getKeyName(),t):(b(this.items).first(e=>e.getKey()==t),this.items.filter(e=>e.getKey()==t)[0]||e)}async fresh(...t){if(this.isEmpty())return new this.constructor;const e=this.first(),s=(await e.newQuery().with(...t).whereIn(e.getKeyName(),this.modelKeys()).get()).getDictionary();return this.filter(t=>t.exists&&void 0!==s[t.getKey()]).map(t=>s[t.getKey()])}makeVisible(t){return this.each(e=>{e.makeVisible(t)})}makeHidden(t){return this.each(e=>{e.makeHidden(t)})}append(t){return this.each(e=>{e.append(t)})}only(e){if(null===e)return new t(this.items);const s=i(this.getDictionary(),e);return new this.constructor(Object.values(s))}getDictionary(t){t=t||this.items;const e={};return t.map(t=>{e[t.getKey()]=t}),e}toQuery(){const t=this.first();if(!t)throw new Error("Unable to create query for empty collection.");const e=t.constructor.name;if(this.filter(t=>!(t instanceof e)).isNotEmpty())throw new Error("Unable to create query for collection with mixed types.");return t.newModelQuery().whereKey(this.modelKeys())}toData(){return this.all().map(t=>"function"==typeof t.toData?t.toData():t)}toJSON(){return this.toData()}toJson(...t){return JSON.stringify(this.toData(),...t)}[Symbol.iterator]=()=>{const t=this.items,e=this.items.length;let s=0;return{next:()=>s<e?{value:t[s++],done:!1}:{done:!0}}}},Dt=t=>class extends t{newExistingPivot(t=[]){return this.newPivot(t,!0)}newPivot(t=[],e=!1){return this.related.newPivot(this.parent,t,this.getTable(),e,this.using).setPivotKeys(this.foreignPivotKey,this.relatedPivotKey)}async attach(t,e={},s=!0){this.using?await this.attachUsingCustomClass(t,e):await this.newPivotStatement().insert(this.formatAttachRecords(this.parseIds(t),e))}async detach(t,e=!0){let s;if(this.using&&null!==t&&0==this.pivotWheres.length&&0==this.pivotWhereIns.length&&0==this.pivotWhereNulls.length)s=await this.detachUsingCustomClass(t);else{const e=this.newPivotQuery();if(null!==t){if(0==(t=this.parseIds(t)).length)return 0;e.whereIn(this.getQualifiedRelatedPivotKeyName(),t)}s=await e.delete()}return s}async sync(t,i=!0){let r,n={attached:[],detached:[],updated:[]};const a=await this.getCurrentlyAttachedPivots(),o=0===a.length?[]:a.map(t=>t.toData()).pluck(this.relatedPivotKey).all().map(t=>String(t)),h=s(o,Object.keys(r=this.formatRecordsList(this.parseIds(t))));return i&&h.length>0&&(await this.detach(h),n.detached=this.castKeys(h)),n=e(n,await this.attachNew(r,o,!1)),n}syncWithoutDetaching(t){return this.sync(t,!1)}syncWithPivotValues(t,e,s=!0){return this.sync(b(this.parseIds(t)).mapWithKeys(t=>[t,e]),s)}withPivot(t){return this.pivotColumns=this.pivotColumns.concat(a(t)?t:Array.prototype.slice.call(t)),this}async attachNew(t,e,s=!0){const i={attached:[],updated:[]};for(const r in t){const n=t[r];e.includes(r)?Object.keys(n).length>0&&await this.updateExistingPivot(r,n,s)&&i.updated.push(this.castKey(r)):(await this.attach(r,n,s),i.attached.push(this.castKey(r)))}return i}async updateExistingPivot(t,e,s=!0){if(this.using&&this.pivotWheres.length>0&&this.pivotWhereInspivotWheres.length>0&&this.pivotWhereNullspivotWheres.length>0)return await this.updateExistingPivotUsingCustomClass(t,e,s);this.hasPivotColumn(this.updatedAt())&&(e=this.addTimestampsToAttachment(e,!0));return this.newPivotStatementForId(this.parseId(t)).update(this.castAttributes(e))}addTimestampsToAttachment(t,e=!1){let s=this.parent.freshTimestamp();if(this.using){s=(new this.using).fromDateTime(s)}return!e&&this.hasPivotColumn(this.createdAt())&&(t[this.createdAt()]=s),this.hasPivotColumn(this.updatedAt())&&(t[this.updatedAt()]=s),t}async updateExistingPivotUsingCustomClass(t,e,s){const i=await this.getCurrentlyAttachedPivots().where(this.foreignPivotKey,this.parent[this.parentKey]).where(this.relatedPivotKey,this.parseId(t)).first(),r=!!i&&i.fill(e).isDirty();return r&&await i.save(),parseInt(r)}formatRecordsList(t){return b(t).mapWithKeys((t,e)=>(a(t)||([e,t]=[t,{}]),[e,t])).all()}async getCurrentlyAttachedPivots(){const t=this.newPivotQuery();return(await t.get()).map(t=>(this.using||Pt).fromRawAttributes(this.parent,t,this.getTable(),!0).setPivotKeys(this.foreignPivotKey,this.relatedPivotKey))}castKeys(t){return t.map(t=>this.castKey(t))}castKey(t){return this.getTypeSwapValue(this.related.getKeyType(),t)}getTypeSwapValue(t,e){switch(t.toLowerCase()){case"int":case"integer":return parseInt(e);case"real":case"float":case"double":return parseFloat(e);case"string":return String(e);default:return e}}newPivotQuery(){const t=this.newPivotStatement();return this.pivotWheres.map(e=>{t.where(...e)}),this.pivotWhereIns.map(e=>{t.whereIn(...e)}),this.pivotWhereNulls.map(e=>{t.whereNull(...e)}),t.where(this.getQualifiedForeignPivotKeyName(),this.parent[this.parentKey])}async detachUsingCustomClass(t){let e=0;for(const s in this.parseIds(t))e+=await this.newPivot({[this.foreignPivotKey]:this.parent[this.parentKey],[this.relatedPivotKey]:s},!0).delete();return e}newPivotStatement(){const t=this.parent.newQuery();return t.setTable(this.table),t}async attachUsingCustomClass(t,e){const s=this.formatAttachRecords(this.parseIds(t),e);await Promise.all(s.map(async t=>{await this.newPivot(t,!1).save()}))}formatAttachRecords(t,e){const s=[],i=this.hasPivotColumn(this.createdAt())||this.hasPivotColumn(this.updatedAt());for(const r in t){const n=t[r];s.push(this.formatAttachRecord(r,n,e,i))}return s}formatAttachRecord(t,s,i,r){const[n,a]=this.extractAttachIdAndAttributes(t,s,i);return e(this.baseAttachRecord(n,r),a)}baseAttachRecord(t,e){let s={};return s[this.relatedPivotKey]=t,s[this.foreignPivotKey]=this.parent[this.parentKey],e&&(s=this.addTimestampsToAttachment(s)),this.pivotValues.map(t=>{s[t.column]=t.value}),s}extractAttachIdAndAttributes(t,e,s){return a(e)?[t,{...e,...s}]:[e,s]}hasPivotColumn(t){return this.pivotColumns.includes(t)}parseIds(t){return t instanceof Kt?[t[this.relatedKey]]:t instanceof At?t.pluck(this.relatedKey).all():a(t)?t:[t]}},xt=class extends(z(X,Dt)){table;foreignPivotKey;relatedPivotKey;parentKey;relatedKey;pivotColumns=[];pivotValues=[];pivotWheres=[];pivotWhereIns=[];pivotWhereNulls=[];accessor="pivot";using;pivotCreatedAt;pivotUpdatedAt;constructor(t,e,s,i,r,n,a){return super(t,e),this.table=s,this.foreignPivotKey=i,this.relatedPivotKey=r,this.parentKey=n,this.relatedKey=a,this.addConstraints(),this.asProxy()}initRelation(t,e){return t.map(t=>{t.setRelation(e,new At([]))}),t}addConstraints(){this.performJoin(),this.constructor.constraints&&this.addWhereConstraints()}performJoin(t=null){return(t=t||this.query).join(this.getTable(),this.getQualifiedRelatedKeyName(),"=",this.qualifyPivotColumn(this.relatedPivotKey)),this}getTable(){return this.table}getQualifiedRelatedKeyName(){return this.related.qualifyColumn(this.relatedKey)}async getResults(){return null!==this.parent[this.parentKey]?await this.get():new At([])}addWhereConstraints(){return this.query.where(this.getQualifiedForeignPivotKeyName(),"=",this.parent[this.parentKey]),this}async get(t){const e=this.query.applyScopes();t=e.query?._statements?.find(t=>"columns"==t.grouping)?[]:t;let s=await e.select(this.shouldSelect(t)).getModels();return this.hydratePivotRelation(s),s.length>0&&(s=await e.eagerLoadRelations(s)),new At(s)}async first(t=["*"]){const e=await this.take(1).get(t);return e.count()>0?e.first():null}async firstOrFail(t=["*"]){const e=await this.first(t);if(null!==e)return e;throw(new k).setModel(this.related.constructor)}async paginate(t=1,e=15,s=["*"]){return this.query.select(this.shouldSelect(s)),J(await this.query.paginate(t,e),t=>{this.hydratePivotRelation(t.items())})}async chunk(t,e){return await this.prepareQueryBuilder().chunk(t,async(t,s)=>(this.hydratePivotRelation(t.all()),await e(t,s)))}setUsing(t){return this.using=t,this}as(t){return this.accessor=t,this}prepareQueryBuilder(){return this.query.select(this.shouldSelect())}hydratePivotRelation(t){t.map(t=>{t.setRelation(this.accessor,this.newExistingPivot(this.migratePivotAttributes(t)))})}migratePivotAttributes(t){const e={};for(const s in t.attributes){const i=t.attributes[s];s.startsWith("pivot_")&&(e[s.substring(6)]=i,t.attributes=r(t.attributes,[s]))}return e}withTimestamps(t=null,e=null){return this.pivotCreatedAt=t,this.pivotUpdatedAt=e,this.withPivot(this.createdAt(),this.updatedAt())}shouldSelect(t=["*"]){return o(t,["*"])&&(t=[this.related.getTable()+".*"]),t.concat(this.aliasedPivotColumns())}aliasedPivotColumns(){const t=[this.foreignPivotKey,this.relatedPivotKey];return b(t.concat(this.pivotColumns)).map(t=>this.qualifyPivotColumn(t)+" as pivot_"+t).unique().all()}qualifyPivotColumn(t){return t.includes(".")?t:this.getTable()+"."+t}match(t,e,s){const i=this.buildDictionary(e);return t.map(t=>{const e=t.getKey();void 0!==i[e]&&t.setRelation(s,i[e])}),t}buildDictionary(t){const e={};return t.map(t=>{const s=t[this.accessor][this.foreignPivotKey];void 0===e[s]&&(e[s]=new At([])),e[s].push(t)}),e}addEagerConstraints(t){this.query.whereIn(this.getQualifiedForeignPivotKeyName(),this.getKeys(t,this.parentKey))}getQualifiedForeignPivotKeyName(){return this.qualifyPivotColumn(this.foreignPivotKey)}getQualifiedRelatedPivotKeyName(){return this.qualifyPivotColumn(this.relatedPivotKey)}wherePivot(t,e=null,s=null,i="and"){return this.pivotWheres.push(Array.prototype.slice.call(arguments)),this.where(this.qualifyPivotColumn(t),e,s,i)}wherePivotBetween(t,e,s="and",i=!1){return this.whereBetween(this.qualifyPivotColumn(t),e,s,i)}orWherePivotBetween(t,e){return this.wherePivotBetween(t,e,"or")}wherePivotNotBetween(t,e,s="and"){return this.wherePivotBetween(t,e,s,!0)}orWherePivotNotBetween(t,e){return this.wherePivotBetween(t,e,"or",!0)}wherePivotIn(t,e,s="and",i=!1){return this.whereIn(this.qualifyPivotColumn(t),e,s,i)}orWherePivot(t,e=null,s=null){return this.wherePivot(t,e,s,"or")}orWherePivotIn(t,e){return this.wherePivotIn(t,e,"or")}wherePivotNotIn(t,e,s="and"){return this.wherePivotIn(t,e,s,!0)}orWherePivotNotIn(t,e){return this.wherePivotNotIn(t,e,"or")}wherePivotNull(t,e="and",s=!1){return this.whereNull(this.qualifyPivotColumn(t),e,s)}wherePivotNotNull(t,e="and"){return this.wherePivotNull(t,e,!0)}orWherePivotNull(t,e=!1){return this.wherePivotNull(t,"or",e)}orWherePivotNotNull(t){return this.orWherePivotNull(t,!0)}orderByPivot(t,e="asc"){return this.orderBy(this.qualifyPivotColumn(t),e)}createdAt(){return this.pivotCreatedAt||this.parent.getCreatedAtColumn()}updatedAt(){return this.pivotUpdatedAt||this.parent.getUpdatedAtColumn()}getExistenceCompareKey(){return this.getQualifiedForeignPivotKeyName()}getRelationExistenceQuery(t,e,s=["*"]){return e.getQuery()._single.table==t.getQuery()._single.table?this.getRelationExistenceQueryForSelfJoin(t,e,s):(this.performJoin(t),super.getRelationExistenceQuery(t,e,s))}getRelationExistenceQueryForSelfJoin(t,e,s=["*"]){const i=this.getRelationCountHash();return t.select(s).from(this.related.getTable()+" as "+i),this.related.setTable(i),this.performJoin(t),super.getRelationExistenceQuery(t,e,s)}},Tt=class{},Rt=class t extends Tt{query;connection;model;actions;localMacros={};eagerLoad={};globalScopes={};onDeleteCallback;constructor(t){return super(),this.query=t,this.asProxy()}asProxy(){return new Proxy(this,{get(t,e){if(void 0!==t[e])return t[e];if(["select","from","where","orWhere","whereColumn","whereRaw","whereNot","orWhereNot","whereIn","orWhereIn","whereNotIn","orWhereNotIn","whereNull","orWhereNull","whereNotNull","orWhereNotNull","whereExists","orWhereExists","whereNotExists","orWhereNotExists","whereBetween","orWhereBetween","whereNotBetween","orWhereNotBetween","whereLike","orWhereLike","whereILike","orWhereILike","whereJsonObject","whereJsonPath","whereJsonSupersetOf","whereJsonSubsetOf","join","joinRaw","leftJoin","leftOuterJoin","rightJoin","rightOuterJoin","crossJoin","transacting","groupBy","groupByRaw","returning","having","havingRaw","havingBetween","limit","offset","orderBy","orderByRaw","union","insert","forUpdate","forShare","distinct","clearOrder","clear","clearSelect","clearWhere","clearHaving","clearGroup"].includes(e))return(...s)=>(t.query[e](...s),t.asProxy());if(["avg","max","min","sum","count"].includes(e))return s=>{const i=t.asProxy();return i.applyScopes(),s=s||"count"!==e?s:"*",i.query[e](s)};if("string"==typeof e){if(t.hasMacro(e)){const s=t.asProxy();return(...t)=>s.localMacros[e](s,...t)}if(t.hasNamedScope(e)){const s=t.asProxy();return(...t)=>(s.callNamedScope(e,t),s)}if(e.startsWith("where")){const s=l(e.substring(5));return(...e)=>(t.query.where(s,...e),t.asProxy())}}}})}orWhere(...t){if("function"==typeof t[0]){const e=t[0];return this.query.orWhere(t=>{this.query=t,e(this)}),this}return this.query.orWhere(...t),this}async chunk(t,e){let s,i=1;do{this.enforceOrderBy();const r=this.clone(),n=await r.forPage(i,t).get();if(s=n.count(),0==s)break;if(!1===await e(n,i))return!1;i++}while(s===t);return!0}enforceOrderBy(){0===this.query._statements.filter(t=>"order"===t.grouping).length&&this.orderBy(this.model.getQualifiedKeyName(),"asc")}clone(){const t=this.query.clone(),e=new this.constructor(t);return e.connection=this.connection,e.setModel(this.model),e.globalScopes={...this.globalScopes},e.localMacros={...this.localMacros},e.eagerLoad={...this.eagerLoad},e}forPage(t,e=15){return this.offset((t-1)*e).limit(e)}insert(...t){return this.query.insert(...t)}update(t){return this.applyScopes(),this.query.update(this.addUpdatedAtColumn(t))}increment(t,e=1,s={}){this.applyScopes();const i=this.model.getConnection();return this.query.update(this.addUpdatedAtColumn({...s,[t]:i.raw(`${t} + ${e}`)}))}decrement(t,e=1,s={}){this.applyScopes();const i=this.model.getConnection();return this.query.update(this.addUpdatedAtColumn({...s,[t]:i.raw(`${t} - ${e}`)}))}addUpdatedAtColumn(t){if(!this.model.usesTimestamps()||null===this.model.getUpdatedAtColumn())return t;const s=this.model.getUpdatedAtColumn();return t=e({[s]:this.model.freshTimestampString()},t)}delete(){return this.onDeleteCallback?this.onDeleteCallback(this):this.query.delete()}onDelete(t){this.onDeleteCallback=t}forceDelete(){return this.query.delete()}async create(t={}){return await J(this.newModelInstance(t),async t=>{await t.save({client:this.query})})}newModelInstance(t={}){return this.model.newInstance(t).setConnection(this.model.getConnectionName())}getQuery(){return this.query}getModel(){return this.model}setModel(t){return this.model=t,"function"==typeof this.query?.client?.table?this.query=this.query.client.table(this.model.getTable()):this.query=this.query.table(this.model.getTable()),this}qualifyColumn(t){return this.model.qualifyColumn(t)}setTable(t){return this.query=this.query.table(t),this}applyScopes(){if(!this.globalScopes)return this;for(const t in this.globalScopes){const e=this.globalScopes[t];e instanceof rt?e.apply(this,this.getModel()):e(this)}return this}hasNamedScope(t){return this.model&&this.model.hasNamedScope(t)}callNamedScope(t,e){return this.model.callNamedScope(t,[this,...e])}callScope(t,e=[]){return t(this,...e)||this}scopes(t){return t.map(t=>{const e=H(t);"function"==typeof this.model[e]&&(this.globalScopes[t]=this.model[e])}),this}withGlobalScope(t,e){return this.globalScopes[t]=e,"function"==typeof e.extend&&e.extend(this),this}withoutGlobalScope(t){return"string"!=typeof t&&(t=t.constructor.name),this.globalScopes=r(this.globalScopes,[t]),this}macro(t,e){return this.localMacros[t]=e,this}hasMacro(t){return t in this.localMacros}getMacro(t){return this.localMacros[t]}with(...t){let s={};if("function"==typeof t[1]){const s=this.parseWithRelations({[t[0]]:t[1]});return this.eagerLoad=e(this.eagerLoad,s),this}const i=G(t);if(0===i.length)return this;for(const t of i){let i;"string"==typeof t?i={[t]:t=>t}:"object"==typeof t&&(i=t),s=e(s,i)}return this.eagerLoad=e(this.eagerLoad,this.parseWithRelations(s)),this}has(t,e=">=",s=1,i="and",r=null){if(h(t)){if(t.includes("."))return this.hasNested(t,e,s,i,r);t=this.getRelationWithoutConstraints(B(t))}const n=t[this.canUseExistsForExistenceCheck(e,s)?"getRelationExistenceQuery":"getRelationExistenceCountQuery"](t.getRelated().newModelQuery(),this);return r&&r(n),this.addHasWhere(n,t,e,s,i)}orHas(t,e=">=",s=1){return this.has(t,e,s,"or")}doesntHave(t,e="and",s=null){return this.has(t,"<",1,e,s)}orDoesntHave(t){return this.doesntHave(t,"or")}whereHas(t,e=null,s=">=",i=1){return this.has(t,s,i,"and",e)}orWhereHas(t,e=null,s=">=",i=1){return this.has(t,s,i,"or",e)}whereRelation(t,...e){const s=e.shift();return this.whereHas(t,t=>{"function"==typeof s?s(t):t.where(s,...e)})}orWhereRelation(t,...e){const s=e.shift();return this.orWhereHas(t,function(t){"function"==typeof s?s(t):t.where(s,...e)})}hasNested(t,e=">=",s=1,i="and",r=null){t=t.split(".");const n="<"===e&&1===s;n&&(e=">=",s=1);const a=i=>(t.length>1?i.whereHas(t.shift(),a):i.has(t.shift(),e,s,"and",r),null);return this.has(t.shift(),n?"<":">=",1,i,a)}canUseExistsForExistenceCheck(t,e){return(">="===t||"<"===t)&&1===e}addHasWhere(t,e,s,i,r){return t.mergeConstraintsFrom(e.getQuery()),this.canUseExistsForExistenceCheck(s,i)?this.addWhereExistsQuery(t.getQuery(),r,"<"===s&&1===i):this.addWhereCountQuery(t.getQuery(),s,i,r)}addWhereExistsQuery(t,e="and",s=!1){const i=s?"NotExists":"Exists";return this["and"===e?"where"+i:"orWhere"+i](t.connector),this}addWhereCountQuery(t,e=">=",s=1,i="and"){const r=this.model.getConnection();return this.where(r.raw("("+t.toSQL().sql+")"),e,"number"==typeof s?r.raw(s):s,i)}withAggregate(t,s,i=null){if(0===t.length)return this;t=G([t]);let r={};for(const s of t){let t;"string"==typeof s?t={[s]:t=>t}:"object"==typeof s&&(t=s),r=e(r,t)}t=r;const n=this.model.getConnection();0===this.query._statements.filter(t=>"columns"==t.grouping).map(t=>t.value).flat().length&&this.query.select([this.query._single.table+".*"]);const a=this.parseWithRelations(t);for(let t in a){const e=a[t],r=t.split(" ");let o,h;3===r.length&&"as"===r[1].toLocaleLowerCase()&&([t,o]=[r[0],r[2]]);const c=this.getRelationWithoutConstraints(B(t));if(i){const t=this.query._single.table===c.query.query._single.table?`${c.getRelationCountHash(!1)}.${s}`:s,e="*"===s?s:c.getRelated().qualifyColumn(t);h="exists"===i?e:`${i}(${e})`}else h=s;const u=c.getRelationExistenceQuery(c.getRelated().newModelQuery(),this,n.raw(h));e(u),o=o||l(`${t} ${i} ${s}`.replace("/[^[:alnum:][:space:]_]/u","")),"exists"===i?this.select(n.raw(`exists(${u.toSql().sql}) as ${o}`)):this.selectSub(i?u:u.limit(1),o)}return this}toSql(){const t=this.clone();return t.applyScopes(),t.query.toSQL()}mergeConstraintsFrom(t){return this}selectSub(t,e){const[s,i]=this.createSub(t),r=this.model.getConnection();return this.select(r.raw("("+s+") as "+e,i))}createSub(t){return this.parseSub(t)}parseSub(e){if(e instanceof t||e instanceof X)return[e.toSql().sql,e.toSql().bindings];if(h(e))return[e,[]];throw new Error("A subquery must be a query builder instance, a Closure, or a string.")}prependDatabaseNameIfCrossDatabaseQuery(t){if(t.query._single.table!==this.query._single.table){const e=t.query._single.table;t.query._single.table.startsWith(e)||t.query._single.table.contains(".")||t.from(e+"."+t.from)}return t}getRelationWithoutConstraints(t){return X.noConstraints(()=>this.getModel()[t]())}withCount(...t){return this.withAggregate(G(t),"*","count")}withMax(t,e){return this.withAggregate(t,e,"max")}withMin(t,e){return this.withAggregate(t,e,"min")}withAvg(t,e){return this.withAggregate(t,e,"avg")}withSum(t,e){return this.withAggregate(t,e,"sum")}withExists(t){return this.withAggregate(t,"*","exists")}parseWithRelations(t){if(0===t.length)return[];let e={};const s=this.prepareNestedWithRelationships(t);for(const t in s)e=this.addNestedWiths(t,e),e[t]=s[t];return e}addNestedWiths(t,e){const s=[];return t.split(".").map(t=>{s.push(t);const i=s.join(".");void 0===e[i]&&(e[i]=()=>{})}),e}prepareNestedWithRelationships(t,e=""){let s={};""!==e&&(e+=".");for(const i in t){const n=t[i];if(h(n)||Number.isFinite(parseInt(n)))continue;const[a,o]=this.parseNameAndAttributeSelectionConstraint(i,n);s=Object.assign({},s,{[`${e}${a}`]:o},this.prepareNestedWithRelationships(n,`${e}${a}`)),t=r(t,[i])}for(const i in t){const r=t[i];let n=i,a=r;h(r)&&([n,a]=this.parseNameAndAttributeSelectionConstraint(r)),s[`${e}${n}`]=this.combineConstraints([a,s[`${e}${n}`]||(()=>{})])}return s}combineConstraints(t){return e=>(t.map(t=>{e=t(e)||e}),e)}parseNameAndAttributeSelectionConstraint(t,e){return t.includes(":")?this.createSelectWithConstraint(t):[t,e]}createSelectWithConstraint(t){return[t.split(":")[0],e=>{e.select(t.split(":")[1].split(",").map(t=>t.includes(".")?t:e instanceof xt?e.related.getTable()+"."+t:t))}]}related(t){if("function"!=typeof this.model[B(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new I(e)}return this.model[B(t)]()}take(...t){return this.limit(...t)}skip(...t){return this.offset(...t)}async first(...t){this.applyScopes(),this.limit(1);let e=await this.getModels(t);return e.length>0&&(e=await this.eagerLoadRelations(e)),e[0]||null}async firstOrFail(...t){const e=await this.first(...t);if(null===e)throw(new k).setModel(this.model.constructor.name);return e}async findOrFail(...t){const e=await this.find(...t);if(a(t[0])){if(e.count()!==t[0].length)throw(new k).setModel(this.model.constructor.name,s(t[0],e.modelKeys()));return e}if(null===e)throw(new k).setModel(this.model.constructor.name,t[0]);return e}async findOrNew(t,e=["*"]){const s=await this.find(t,e);return null!==s?s:this.newModelInstance()}async firstOrNew(t={},s={}){const i=await this.where(t).first();return null!==i?i:this.newModelInstance(e(t,s))}async firstOrCreate(t={},s={}){const i=await this.where(t).first();return null!==i?i:J(this.newModelInstance(e(t,s)),async t=>{await t.save({client:this.query})})}async updateOrCreate(t,e={}){return await J(await this.firstOrNew(t),async t=>{await t.fill(e).save({client:this.query})})}latest(t="id"){return null===t&&(t=this.model.getCreatedAtColumn()||"created_at"),this.query.orderBy(t,"desc"),this}oldest(t="id"){return null===t&&(t=this.model.getCreatedAtColumn()||"created_at"),this.query.orderBy(t,"asc"),this}async find(t,e){return a(t)||t instanceof At?await this.findMany(t,e):await this.where(this.model.getKeyName(),t).first(e)}async findMany(t,e=["*"]){return t instanceof At&&(t=t.modelKeys()),0===(t=a(t)?t:[t]).length?new At([]):await this.whereIn(this.model.getKeyName(),t).get(e)}async pluck(t){const e=await this.query.pluck(t);return new At(e)}async destroy(t){if(t instanceof At&&(t=t.modelKeys()),t instanceof C&&(t=t.all()),0===(t=a(t)?t:Array.prototype.slice.call(t)).length)return 0;const e=this.model.newInstance().getKeyName();let s=0;const i=await this.model.newModelQuery().whereIn(e,t).get();for(const t of i)await t.delete()&&s++;return s}async get(t=["*"]){this.applyScopes();let e=await this.getModels(t);return e.length>0&&(e=await this.eagerLoadRelations(e)),new At(e)}async all(t=["*"]){return await this.model.newModelQuery().get(t)}async paginate(t=1,e=10){t=t||1,e=e||this?.model?.perPage||15,this.applyScopes();const s=this.query.clone(),i=await s.clearOrder().clearSelect().count(this.primaryKey);let r=[];if(i>0){const s=(t-1)*(e??10);this.take(e).skip(s),r=await this.getModels(),r.length>0&&(r=await this.eagerLoadRelations(r))}else r=[];return new ft(r,parseInt(i),e,t)}async getModels(...t){return(t=c(t)).length>0&&0==this.query._statements.filter(t=>"columns"==t.grouping).length&&"*"!==t[0]&&this.query.select(...t),this.hydrate(await this.query.get()).all()}getRelation(t){if("function"!=typeof this.model[B(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new I(e)}const e=X.noConstraints(()=>this.model.newInstance(this.model.attributes)[B(t)]()),s=this.relationsNestedUnder(t);return Object.keys(s).length>0&&e.query.with(s),e.asProxy()}relationsNestedUnder(t){const e={};for(const s in this.eagerLoad){const i=this.eagerLoad[s];this.isNestedUnder(t,s)&&(e[s.substring((t+".").length)]=i)}return e}isNestedUnder(t,e){return e.includes(".")&&e.startsWith(t+".")}async eagerLoadRelation(t,e,s){const i=this.getRelation(e);return i.addEagerConstraints(t),s(i),i.match(i.initRelation(t,e),await i.get(),e)}async eagerLoadRelations(t){for(const e in this.eagerLoad){const s=this.eagerLoad[e];e.includes(".")||(t=await this.eagerLoadRelation(t,e,s))}return t}hydrate(t){return new At(t.map(t=>{if(!this.model)return t;return this.model.newFromBuilder(t)}))}},St=t=>class extends t{useUniqueIds=!0;uniqueIds(){return[this.getKeyName()]}getKeyType(){return this.uniqueIds().includes(this.getKeyName())?"string":this.keyType}getIncrementing(){return!this.uniqueIds().includes(this.getKeyName())&&this.incrementing}},qt=class{resolver;table;connection=null;constructor(t,e){this.resolver=t,this.table=e}async getRan(){return await this.getTable().orderBy("batch","asc").orderBy("migration","asc").pluck("migration")}async getMigrations(t){const e=this.getTable().where("batch",">=","1");return await e.orderBy("batch","desc").orderBy("migration","desc").take(t).get()}async getMigrationsByBatch(t){return await this.getTable().where("batch",t).orderBy("migration","desc").get()}async getLast(){const t=this.getTable().where("batch",await this.getLastBatchNumber());return await t.orderBy("migration","desc").get()}async getMigrationBatches(){const t=await this.getTable().select("batch","migration").orderBy("batch","asc").orderBy("migration","asc").get(),e={};return t.map(t=>{e[t.migration]=t.batch}),e}async log(t,e){await this.getTable().insert({migration:t,batch:e})}async delete(t){await this.getTable().where("migration",t.migration).delete()}async getNextBatchNumber(){return await this.getLastBatchNumber()+1}async getLastBatchNumber(){return await this.getTable().max("batch")}async createRepository(){const t=this.getConnection().schema;await t.createTable(this.table,function(t){t.increments("id"),t.string("migration"),t.integer("batch")})}repositoryExists(){return this.getConnection().schema.hasTable(this.table)}async deleteRepository(){const t=this.getConnection().schema;await t.drop(this.table)}getTable(){return this.getConnection().table(this.table)}getConnection(){return this.resolver.connection(this.connection)}setSource(t){this.connection=t}};async function Mt(t){const e=await D.readdir(t),s=[];for(const i of e){const e=`${t}/${i}`,r=await D.stat(e);if(r.isFile())s.push(e);else if(r.isDirectory()){const t=await Mt(e);s.push(...t)}}return s}var kt=class{events=null;repository;files;resolver;connection;paths=[];output=null;constructor(t,e=null,s=null,i=null){this.repository=t,this.files=s,this.resolver=e,this.events=i}async run(t=[],e={}){const s=await this.getMigrationFiles(t),i=await this.repository.getRan(),r=this.pendingMigrations(s,i);return await this.runPending(r,e),r}pendingMigrations(t,e){return Object.values(t).filter(t=>!e.includes(this.getMigrationName(t)))}async runPending(t,e={}){if(0===t.length)return void this.write("Nothing to migrate");let s=await this.repository.getNextBatchNumber();const i=e.pretend||!1,r=e.step||!1;this.write("Running migrations.");for(const e of t)await this.runUp(e,s,i),r&&s++}async runUp(t,e,s){const i=await this.resolvePath(t),r=this.getMigrationName(t);await this.writeTask(r,()=>this.runMigration(i,"up")),await this.repository.log(r,e)}async runDown(t,e,s){const i=await this.resolvePath(t),r=this.getMigrationName(t);await this.writeTask(r,()=>this.runMigration(i,"down")),await this.repository.delete(e)}async rollback(t=[],e={}){const s=await this.getMigrationsForRollback(e);return 0===s.length?(this.write("Nothing to rollback."),[]):await this.rollbackMigrations(s,t,e)}async getMigrationsForRollback(t){return t.step&&t.step>0?await this.repository.getMigrations(t.step):t.batch&&t.batch>0?await this.repository.getMigrationsByBatch(t.batch):await this.repository.getLast()}async rollbackMigrations(t,e,s){const i=[],r=await this.getMigrationFiles(e);this.write("Rolling back migrations.");for(const e of t){const t=r[e.migration];t?(i.push(t),await this.runDown(t,e,s.pretend||!1)):this.writeTwoColumns(e.migration,A.yellow("Migration not found"))}return i}reset(t=[],e=!1){return this.repository.getRan().then(t=>t.reverse()),[]}resetMigrations(t,e,s=!1){return this.rollbackMigrations(t,e,{pretend:s})}async runMigration(t,e){const s=this.resolveConnection(t.getConnection()),i=async s=>{"function"==typeof t[e]&&await this.runMethod(s,t,e)};t.withinTransaction?await s.transaction(i):await i(s)}async runMethod(t,e,s){await(e[s]?.(t.schema,t))}async resolvePath(t){try{return new((await import(t)).default)}catch{}return new class{}}getMigrationClass(t){return t.split("_").slice(4).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}async getMigrationFiles(t){const e=[];for(const s of t)s.endsWith(".js")||s.endsWith(".ts")?e.push(s):e.push(...await Mt(s));return e.filter(Boolean).reduce((t,e)=>(t[this.getMigrationName(e)]=e,t),{})}getMigrationName(t){return K.basename(t).replace(".js","")}path(t){this.paths=Array.from(new Set([...this.paths,t]))}getPaths(){return this.paths}getConnection(){return this.connection}resolveConnection(t){return this.resolver.connection(t||this.connection)}getRepository(){return this.repository}repositoryExists(){return this.repository.repositoryExists()}async hasRunAnyMigrations(){const t=await this.repository.getRan();return await this.repositoryExists()&&t.length>0}deleteRepository(){this.repository.deleteRepository()}setOutput(t){return this.output=t,this}write(...t){this.output&&console.log(...t)}writeTwoColumns(t,...e){const s=e.join(" "),i=/\x1b\[\d+m/g,r=Math.min(process.stdout.columns,100),n=Math.max(r-t.replace(i,"").length-s.replace(i,"").length-10,0);this.write(t,A.gray(".".repeat(n)),s)}async writeTask(t,e){const s=process.hrtime();let i=!1;try{i=await(e||(()=>!0))()}finally{const e=process.hrtime(s),r=(1e9*e[0]+e[1])/1e6;this.writeTwoColumns(A.green(t),A.gray(`${Math.floor(r)}ms`),!1!==i?A.green("✔"):A.red("✘"))}}},It=K.join,Et=class{static textFormat(t,e){return String(t).split(":").map((t,s,i)=>0==s&&i.length>1?e(" "+t+": "):t).join("")}static output(){return{success:(t,e=!1)=>{console.log(A.green("✓"),this.textFormat(t,A.bgGreen),"\n"),e&&process.exit(0)},info:(t,e=!1)=>{console.log(A.blue("ℹ"),this.textFormat(t,A.bgBlue),"\n"),e&&process.exit(0)},error:(t,e=!0)=>{t instanceof Error?(t.message&&console.error(A.red("✖"),this.textFormat(t.message,A.bgRed)),console.error(A.red(`${t.detail?`${t.detail}\n`:""}${t.stack}`),"\n")):console.error(A.red("✖"),this.textFormat(t,A.bgRed),"\n"),e&&process.exit(1)},quiet:()=>{process.exit(0)}}}static findModulePkg(t,e){const s=t.replace(/\\/g,"/").split("/");let i="";s.length>0&&"@"===s[0][0]&&(i+=s.shift()+"/"),i+=s.shift();const r=K.join(i,"package.json"),n=R.silent(e??process.cwd(),r);if(n)return K.join(K.dirname(n),s.join("/"))}static async getMigrationPaths(t,e,s,i){return i?[It(t,i)]:[...e.getPaths(),It(t,s)]}static twoColumnDetail(t,e){const s=/\x1b\[\d+m/g,i=Math.min(process.stdout.columns,100),r=Math.max(i-t.replace(s,"").length-e.replace(s,"").length-10,0);return console.log(t,A.gray(".".repeat(r)),e)}static async fileExists(t){try{return await x(t),!0}catch{return!1}}static findUpConfig(t,e,s){return T(t,(t,i)=>{for(const t of s){const s=`${e}.${t}`;if(i.includes(s))return s}return!1})}},Qt=class{constructor(t,e,s){this.basePath=t,this.customStubPath=e,this.callback=s??((t="")=>{})}callback;async run(t,e={},s=!1){const{arquebus:i,migrator:r}=await this.setupConnection(t);await this.prepareDatabase(r);const n=await Et.getMigrationPaths(this.basePath??process.cwd(),r,t.migrations.path,e.path);await r.setOutput(!0).run(n,{step:e.step,pretend:e.pretend}),s&&await i.destroyAll()}async rollback(t,e={},s=!1){const{arquebus:i,migrator:r}=await this.setupConnection(t),n=await Et.getMigrationPaths(this.basePath??process.cwd(),r,t.migrations.path,e.path);await r.setOutput(!0).rollback(n,{step:e.step||0,pretend:e.pretend,batch:e.batch||0}),s&&await i.destroyAll()}async prepareDatabase(t){await t.repositoryExists()||(this.callback("INFO: Preparing database.","info"),this.callback("INFO: Creating migration table...","info"),await t.repository.createRepository(),this.callback("SUCCESS: Migration table created successfully.","success"))}async status(t,e={},s=!1){const{arquebus:i,migrator:r}=await this.setupConnection(t),n=async()=>await r.getMigrationFiles(await Et.getMigrationPaths(this.basePath??process.cwd(),r,t.migrations.path,e.path));await r.repositoryExists()||this.callback("ERROR: Migration table does not exist.","error");const a=await r.repository.getRan(),o=await r.getRepository().getMigrationBatches(),h=await async function(t,e){const s=await n();return Object.values(s).map(s=>{const i=r.getMigrationName(s);return{name:i,ran:t.includes(i),batch:t.includes(i)?e[i]:null}})}(a,o);return s&&await i.destroyAll(),h}async setupConnection(t){const e=t?.migrations?.table||"migrations";!0!==t.skipConnection&&(Ct.addConnection(t,"default"),Object.entries(t.connections||{}).forEach(([t,e])=>{Ct.addConnection(e,t)}));const s=new qt(Ct,e),i=new kt(s,Ct);return{arquebus:Ct,migrator:i}}},_t=class{},Ft=class extends _t{connection;withinTransaction=!0;getConnection(){return this.connection}},Ot=Pt,Wt=class extends rt{extensions=["Restore","RestoreOrCreate","CreateOrRestore","WithTrashed","WithoutTrashed","OnlyTrashed"];apply(t,e){t.whereNull(e.getQualifiedDeletedAtColumn())}extend(t){for(const e of this.extensions)this[`add${e}`](t);t.onDelete(async t=>{const e=this.getDeletedAtColumn(t);return await t.update({[e]:t.getModel().freshTimestampString()})})}getDeletedAtColumn(t){return(t=>{for(const e of t)if("join"===e?.grouping)return!0;return!1})(t.getQuery()._statements)?t.getModel().getQualifiedDeletedAtColumn():t.getModel().getDeletedAtColumn()}addRestore(t){t.macro("restore",t=>(t.withTrashed(),t.update({[t.getModel().getDeletedAtColumn()]:null})))}addRestoreOrCreate(t){t.macro("restoreOrCreate",async(t,e={},s={})=>(t.withTrashed(),J(await t.firstOrCreate(e,s),async t=>{await t.restore()})))}addCreateOrRestore(t){t.macro("createOrRestore",async(t,e={},s={})=>(t.withTrashed(),J(await t.createOrFirst(e,s),async t=>{await t.restore()})))}addWithTrashed(t){t.macro("withTrashed",(t,e=!0)=>e?t.withoutGlobalScope(this):t.withoutTrashed())}addWithoutTrashed(t){t.macro("withoutTrashed",t=>{const e=t.getModel();return t.withoutGlobalScope(this).whereNull(e.getQualifiedDeletedAtColumn()),t})}addOnlyTrashed(t){t.macro("onlyTrashed",t=>{const e=t.getModel();return t.withoutGlobalScope(this).whereNotNull(e.getQualifiedDeletedAtColumn()),t})}},Bt=t=>class extends t{forceDeleting=!1;static bootSoftDeletes(){this.addGlobalScope(new Wt)}initialize(){super.initialize(),this.constructor.bootSoftDeletes(),this.addPluginInitializer("initializeSoftDeletes")}initializeSoftDeletes(){void 0===this.casts[this.getDeletedAtColumn()]&&(this.casts[this.getDeletedAtColumn()]="datetime")}async forceDelete(){return!1!==this.execHooks("forceDeleting")&&(this.forceDeleting=!0,J(await this.delete(),t=>{this.forceDeleting=!1,t&&this.execHooks("forceDeleted",!1)}))}forceDeleteQuietly(){return this.withoutEvents(()=>this.forceDelete())}async performDeleteOnModel(t={}){return this.forceDeleting?J(await this.setKeysForSaveQuery(this.newModelQuery()).forceDelete(),()=>{this.exists=!1}):await this.runSoftDelete(t)}async runSoftDelete(t={}){const e=this.setKeysForSaveQuery(this.newModelQuery()),s=this.freshTimestamp(),i={[this.getDeletedAtColumn()]:this.fromDateTime(s)};this[this.getDeletedAtColumn()]=s,this.usesTimestamps()&&this.getUpdatedAtColumn()&&(this[this.getUpdatedAtColumn()]=s,i[this.getUpdatedAtColumn()]=this.fromDateTime(s)),await e.update(i),this.syncOriginalAttributes(Object.keys(i)),this.execHooks("trashed",t)}async restore(t={}){if(!1===this.execHooks("restoring",t))return!1;this[this.getDeletedAtColumn()]=null,this.exists=!0;const e=await this.save();return this.execHooks("restored",t),e}restoreQuietly(){return this.withoutEvents(()=>this.restore())}trashed(){return!m(this[this.getDeletedAtColumn()])}static softDeleted(t){this.addHook("trashed",t)}static restoring(t){this.addHook("restoring",t)}static restored(t){this.addHook("restored",t)}static forceDeleting(t){this.addHook("forceDeleting",t)}static forceDeleted(t){this.addHook("forceDeleted",t)}isForceDeleting(){return this.forceDeleting}getDeletedAtColumn(){return this.constructor.DELETED_AT||"deleted_at"}getQualifiedDeletedAtColumn(){return this.qualifyColumn(this.getDeletedAtColumn())}},Ht=(t,e,s={})=>{const{paginated:i}=s;return i?new ft(e.data.map(e=>t.make(e)),e.total,e.per_page,e.current_page):Array.isArray(e)?new At(e.map(e=>t.make(e))):t.make(e)},jt=(t,e)=>new At(e.map(e=>t.make(e))),Lt=(t,e)=>new ft(e.data.map(e=>t.make(e)),e.total,e.per_page,e.current_page);export{q as Attribute,Rt as Builder,st as CastsAttributes,At as Collection,St as HasUniqueIds,E as InvalidArgumentError,Qt as Migrate,Ft as Migration,Nt as Model,k as ModelNotFoundError,ft as Paginator,Ot as Pivot,bt as QueryBuilder,I as RelationNotFoundError,rt as Scope,Bt as SoftDeletes,Ct as arquebus,z as compose,Z as defineConfig,G as flattenDeep,j as getAttrMethod,$ as getAttrName,L as getGetterMethod,B as getRelationMethod,O as getRelationName,H as getScopeMethod,W as getScopeName,U as getSetterMethod,V as kebabCase,Ht as make,jt as makeCollection,Lt as makePaginator,F as now,Y as snakeCase,J as tap};
1
+ import "node:module";
2
+ import { assign, camel, dash, diff, flat, get, isArray, isEmpty, isEqual, isNullish, isString, omit, pick, set, snake, trim } from "radashi";
3
+ import advancedFormat from "dayjs/plugin/advancedFormat.js";
4
+ import dayjs from "dayjs";
5
+ import collect$1, { Collection, collect } from "collect.js";
6
+ import Knex$1 from "knex";
7
+ import path from "path";
8
+ import { existsSync } from "fs";
9
+ import pluralize from "pluralize";
10
+ import color from "chalk";
11
+ import fs from "node:fs/promises";
12
+ import { access } from "fs/promises";
13
+ import escalade from "escalade/sync";
14
+ import resolveFrom from "resolve-from";
15
+
16
+ //#region rolldown:runtime
17
+ var __defProp = Object.defineProperty;
18
+ var __export = (all) => {
19
+ let target = {};
20
+ for (var name in all) __defProp(target, name, {
21
+ get: all[name],
22
+ enumerable: true
23
+ });
24
+ return target;
25
+ };
26
+
27
+ //#endregion
28
+ //#region src/casts/attribute.ts
29
+ var Attribute = class Attribute {
30
+ get;
31
+ set;
32
+ withCaching = false;
33
+ withObjectCaching = true;
34
+ constructor({ get: get$1 = null, set: set$1 = null }) {
35
+ this.get = get$1;
36
+ this.set = set$1;
37
+ }
38
+ static make({ get: get$1 = null, set: set$1 = null }) {
39
+ return new Attribute({
40
+ get: get$1,
41
+ set: set$1
42
+ });
43
+ }
44
+ static get(get$1) {
45
+ return new Attribute({ get: get$1 });
46
+ }
47
+ static set(set$1) {
48
+ return new Attribute({ set: set$1 });
49
+ }
50
+ withoutObjectCaching() {
51
+ this.withObjectCaching = false;
52
+ return this;
53
+ }
54
+ shouldCache() {
55
+ this.withCaching = true;
56
+ return this;
57
+ }
58
+ };
59
+ var attribute_default = Attribute;
60
+
61
+ //#endregion
62
+ //#region src/errors.ts
63
+ var BaseError = class extends Error {
64
+ constructor(message, _entity) {
65
+ super(message);
66
+ Error.captureStackTrace(this, this.constructor);
67
+ this.name = this.constructor.name;
68
+ this.message = message;
69
+ }
70
+ };
71
+ var ModelNotFoundError = class extends BaseError {
72
+ model;
73
+ ids = [];
74
+ constructor() {
75
+ super("");
76
+ }
77
+ setModel(model, ids = []) {
78
+ this.model = model;
79
+ this.ids = isArray(ids) ? ids : [ids];
80
+ this.message = `No query results for model [${model}]`;
81
+ if (this.ids.length > 0) this.message += " " + this.ids.join(", ");
82
+ else this.message += ".";
83
+ return this;
84
+ }
85
+ getModel() {
86
+ return this.model;
87
+ }
88
+ getIds() {
89
+ return this.ids;
90
+ }
91
+ };
92
+ var RelationNotFoundError = class extends BaseError {};
93
+ var InvalidArgumentError = class extends BaseError {};
94
+
95
+ //#endregion
96
+ //#region src/mixin.ts
97
+ var mixin_exports = /* @__PURE__ */ __export({ compose: () => compose$1 });
98
+ /**
99
+ * Compose function that merges multiple classes and mixins
100
+ *
101
+ * @example
102
+ * const SomePlugin = <TBase extends new (...args: any[]) => TGeneric> (Base: TBase) => {
103
+ * return class extends Base {
104
+ * pluginAttribtue = 'plugin'
105
+ * pluginMethod () {
106
+ * return this.pluginAttribtue
107
+ * }
108
+ * }
109
+ * }
110
+ *
111
+ * // Base class
112
+ * class Model {
113
+ * make () {
114
+ * console.log('make')
115
+ * }
116
+ * pluginMethod (id: string) {
117
+ * }
118
+ * }
119
+ *
120
+ * class User extends compose(
121
+ * Model,
122
+ * SomePlugin,
123
+ * ) {
124
+ * relationPosts () {
125
+ * return 'hasMany Posts'
126
+ * }
127
+ * }
128
+ *
129
+ * const user = new User()
130
+ * user.make() // from Model
131
+ * user.pluginMethod() // from SomePlugin
132
+ * user.relationPosts() // from User
133
+ *
134
+ * console.log(user.pluginMethod('w')) // "plugin"
135
+ * console.log(user.pluginMethod()) // "plugin"
136
+ * console.log(user.relationPosts()) // "hasMany Posts"
137
+ *
138
+ * @param Base
139
+ * @param mixins
140
+ * @returns
141
+ */
142
+ function compose$1(Base, ...mixins) {
143
+ /**
144
+ * Apply each mixin or class in sequence
145
+ */
146
+ return mixins.reduce((acc, mixin) => {
147
+ if (typeof mixin === "function" && mixin.prototype)
148
+ /**
149
+ * If it's a class constructor, extend it
150
+ */
151
+ return class extends acc {
152
+ constructor(...args) {
153
+ super(...args);
154
+ /**
155
+ * Copy instance properties from mixin prototype
156
+ */
157
+ Object.getOwnPropertyNames(mixin.prototype).forEach((name) => {
158
+ if (name !== "constructor") Object.defineProperty(this, name, Object.getOwnPropertyDescriptor(mixin.prototype, name));
159
+ });
160
+ }
161
+ };
162
+ else if (typeof mixin === "function")
163
+ /**
164
+ * If it's a mixin function, call it with current class
165
+ */
166
+ return mixin(acc);
167
+ return acc;
168
+ }, Base);
169
+ }
170
+
171
+ //#endregion
172
+ //#region src/utils.ts
173
+ dayjs.extend(advancedFormat);
174
+ const now = (format = "YYYY-MM-DD HH:mm:ss") => dayjs().format(format);
175
+ const getRelationName = (relationMethod) => {
176
+ return snake(relationMethod.substring(8));
177
+ };
178
+ const getScopeName = (scopeMethod) => {
179
+ return snake(scopeMethod.substring(5));
180
+ };
181
+ const getRelationMethod = (relation) => {
182
+ return camel(`relation_${relation}`);
183
+ };
184
+ const getScopeMethod = (scope) => {
185
+ return camel(`scope_${scope}`);
186
+ };
187
+ const getAttrMethod = (attr) => {
188
+ return camel(`attribute_${attr}`);
189
+ };
190
+ const getGetterMethod = (attr) => {
191
+ return camel(`get_${attr}_attribute`);
192
+ };
193
+ const getSetterMethod = (attr) => {
194
+ return camel(`set_${attr}_attribute`);
195
+ };
196
+ const getAttrName = (attrMethod) => {
197
+ return attrMethod.substring(3, attrMethod.length - 9).toLowerCase();
198
+ };
199
+ /**
200
+ * Tap into a model a collection instance
201
+ *
202
+ * @param instance
203
+ * @param callback
204
+ * @returns
205
+ */
206
+ const tap = (instance, callback) => {
207
+ const result = callback(instance);
208
+ return result instanceof Promise ? result.then(() => instance) : instance;
209
+ };
210
+ const { compose } = mixin_exports;
211
+ const flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
212
+ const kebabCase = (str) => trim(dash(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
213
+ const snakeCase = (str) => trim(snake(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
214
+ const defineConfig = (config) => {
215
+ return config;
216
+ };
217
+
218
+ //#endregion
219
+ //#region src/relations/relation.ts
220
+ var Relation = class {
221
+ query;
222
+ parent;
223
+ related;
224
+ eagerKeysWereEmpty = false;
225
+ static constraints = true;
226
+ static selfJoinCount = 0;
227
+ constructor(query, parent) {
228
+ this.query = query;
229
+ this.parent = parent;
230
+ this.related = this.query.model;
231
+ }
232
+ static extend(trait) {
233
+ for (const methodName in trait) this.prototype[methodName] = trait[methodName];
234
+ }
235
+ static noConstraints(callback) {
236
+ const previous = this.constraints;
237
+ this.constraints = false;
238
+ try {
239
+ return callback();
240
+ } finally {
241
+ this.constraints = previous;
242
+ }
243
+ }
244
+ asProxy() {
245
+ return new Proxy(this, { get: function(target, prop) {
246
+ if (typeof target[prop] !== "undefined") return target[prop];
247
+ if (typeof prop === "string") {
248
+ if (typeof target.query[prop] === "function") return (...args) => {
249
+ target.query[prop](...args);
250
+ return target.asProxy();
251
+ };
252
+ }
253
+ } });
254
+ }
255
+ getRelated() {
256
+ return this.related;
257
+ }
258
+ getKeys(models, key) {
259
+ return models.map((model) => key ? model.attributes[key] : model.getKey()).sort();
260
+ }
261
+ getRelationQuery() {
262
+ return this.query;
263
+ }
264
+ whereInEager(whereIn, key, modelKeys, query = null) {
265
+ (query || this.query)[whereIn](key, modelKeys);
266
+ if (modelKeys.length === 0) this.eagerKeysWereEmpty = true;
267
+ }
268
+ whereInMethod(model, key) {
269
+ return "whereIn";
270
+ }
271
+ getEager() {
272
+ return this.eagerKeysWereEmpty ? this.query.getModel().newCollection() : this.get();
273
+ }
274
+ async get(columns = ["*"]) {
275
+ return await this.query.get(columns);
276
+ }
277
+ async first(columns = ["*"]) {
278
+ return await this.query.first(columns);
279
+ }
280
+ async paginate(...args) {
281
+ return await this.query.paginate(...args);
282
+ }
283
+ async count(...args) {
284
+ return await this.query.clearSelect().count(...args);
285
+ }
286
+ toSql() {
287
+ return this.query.toSql();
288
+ }
289
+ addConstraints() {}
290
+ getRelationCountHash(incrementJoinCount = true) {
291
+ return "arquebus_reserved_" + (incrementJoinCount ? this.constructor.selfJoinCount++ : this.constructor.selfJoinCount);
292
+ }
293
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
294
+ return query.select(columns).whereColumn(this.getQualifiedParentKeyName(), "=", this.getExistenceCompareKey());
295
+ }
296
+ getRelationExistenceCountQuery(query, parentQuery) {
297
+ const db = this.related.getConnection();
298
+ return this.getRelationExistenceQuery(query, parentQuery, db.raw("count(*)"));
299
+ }
300
+ getQualifiedParentKeyName() {
301
+ return this.parent.getQualifiedKeyName();
302
+ }
303
+ getExistenceCompareKey() {
304
+ var _this$getQualifiedFor;
305
+ return (_this$getQualifiedFor = this.getQualifiedForeignKeyName) === null || _this$getQualifiedFor === void 0 ? void 0 : _this$getQualifiedFor.call(this);
306
+ }
307
+ };
308
+ var relation_default = Relation;
309
+
310
+ //#endregion
311
+ //#region src/relations/concerns/supports-default-models.ts
312
+ const SupportsDefaultModels = (Relation$1) => {
313
+ return class extends Relation$1 {
314
+ _withDefault;
315
+ withDefault(callback = true) {
316
+ this._withDefault = callback;
317
+ return this;
318
+ }
319
+ getDefaultFor(parent) {
320
+ if (!this._withDefault) return null;
321
+ const instance = this.newRelatedInstanceFor(parent);
322
+ if (typeof this._withDefault === "function") return this._withDefault(instance, parent) || instance;
323
+ if (typeof this._withDefault === "object") for (const key in this._withDefault) instance.setAttribute(key, this._withDefault[key]);
324
+ return instance;
325
+ }
326
+ };
327
+ };
328
+ var supports_default_models_default = SupportsDefaultModels;
329
+
330
+ //#endregion
331
+ //#region src/relations/belongs-to.ts
332
+ var BelongsTo = class extends compose(relation_default, supports_default_models_default) {
333
+ foreignKey;
334
+ ownerKey;
335
+ child;
336
+ relationName;
337
+ constructor(query, child, foreignKey, ownerKey, relationName) {
338
+ super(query, child);
339
+ this.foreignKey = foreignKey;
340
+ this.ownerKey = ownerKey;
341
+ this.child = child;
342
+ this.relationName = relationName;
343
+ this.addConstraints();
344
+ return this.asProxy();
345
+ }
346
+ async getResults() {
347
+ if (this.child[this.foreignKey] === null) return this.getDefaultFor(this.parent);
348
+ return await this.query.first() || this.getDefaultFor(this.parent);
349
+ }
350
+ match(models, results, relation) {
351
+ const foreign = this.foreignKey;
352
+ const owner = this.ownerKey;
353
+ const dictionary = {};
354
+ results.map((result) => {
355
+ const attribute = result.attributes[owner];
356
+ dictionary[attribute] = result;
357
+ });
358
+ models.map((model) => {
359
+ const attribute = model[foreign];
360
+ if (dictionary[attribute] !== void 0) model.setRelation(relation, dictionary[attribute]);
361
+ });
362
+ return models;
363
+ }
364
+ getQualifiedForeignKeyName() {
365
+ return this.child.qualifyColumn(this.foreignKey);
366
+ }
367
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
368
+ if (parentQuery.getQuery()._single.table === query.getQuery()._single.table) return this.getRelationExistenceQueryForSelfRelation(query, parentQuery, columns);
369
+ return query.select(columns).whereColumn(this.getQualifiedForeignKeyName(), "=", query.qualifyColumn(this.ownerKey));
370
+ }
371
+ getRelationExistenceQueryForSelfRelation(query, parentQuery, columns = ["*"]) {
372
+ const hash = this.getRelationCountHash();
373
+ query.select(columns).from(query.getModel().getTable() + " as " + hash);
374
+ query.getModel().setTable(hash);
375
+ return query.whereColumn(`${hash}.${this.ownerKey}`, "=", this.getQualifiedForeignKeyName());
376
+ }
377
+ initRelation(models, relation) {
378
+ models.forEach((model) => {
379
+ model.setRelation(relation, this.getDefaultFor(model));
380
+ });
381
+ return models;
382
+ }
383
+ addEagerConstraints(models) {
384
+ const key = `${this.related.getTable()}.${this.ownerKey}`;
385
+ this.query.whereIn(key, this.getEagerModelKeys(models));
386
+ }
387
+ getEagerModelKeys(models) {
388
+ const keys = [];
389
+ models.forEach((model) => {
390
+ const value = model[this.foreignKey];
391
+ if (value !== null && value !== void 0) keys.push(value);
392
+ });
393
+ keys.sort();
394
+ return [...new Set(keys)];
395
+ }
396
+ associate(model) {
397
+ const ownerKey = model instanceof Model ? model.attributes[this.ownerKey] : model;
398
+ this.child[this.foreignKey] = ownerKey;
399
+ if (model instanceof Model) this.child.setRelation(this.relationName, model);
400
+ else this.child.unsetRelation(this.relationName);
401
+ return this.child;
402
+ }
403
+ dissociate() {
404
+ this.child[this.foreignKey] = null;
405
+ return this.child.setRelation(this.relationName, null);
406
+ }
407
+ addConstraints() {
408
+ if (this.constructor.constraints) {
409
+ const table = this.related.getTable();
410
+ this.query.where(`${table}.${this.ownerKey}`, "=", this.child[this.foreignKey]);
411
+ }
412
+ }
413
+ newRelatedInstanceFor(_parent) {
414
+ return this.related.newInstance();
415
+ }
416
+ };
417
+ var belongs_to_default = BelongsTo;
418
+
419
+ //#endregion
420
+ //#region src/casts-attributes.ts
421
+ var CastsAttributes = class CastsAttributes {
422
+ constructor() {
423
+ if (this.constructor === CastsAttributes) throw new Error("CastsAttributes cannot be instantiated");
424
+ }
425
+ static get(_model, _key, _value, _attributes) {
426
+ throw new Error("get not implemented");
427
+ }
428
+ static set(_model, _key, _value, _attributes) {
429
+ throw new Error("set not implemented");
430
+ }
431
+ };
432
+ var casts_attributes_default = CastsAttributes;
433
+
434
+ //#endregion
435
+ //#region src/concerns/has-attributes.ts
436
+ const HasAttributes = (Model$1) => {
437
+ return class extends Model$1 {
438
+ static castTypeCache = {};
439
+ attributes = {};
440
+ original = {};
441
+ casts = {};
442
+ changes = {};
443
+ appends = [];
444
+ setAppends(appends) {
445
+ this.appends = appends;
446
+ return this;
447
+ }
448
+ append(...keys) {
449
+ const appends = flattenDeep(keys);
450
+ this.appends = [...this.appends, ...appends];
451
+ return this;
452
+ }
453
+ normalizeCastClassResponse(key, value) {
454
+ var _value$constructor;
455
+ return (value === null || value === void 0 || (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name) === "Object" ? value : { [key]: value };
456
+ }
457
+ syncOriginal() {
458
+ this.original = this.getAttributes();
459
+ return this;
460
+ }
461
+ syncChanges() {
462
+ this.changes = this.getDirty();
463
+ return this;
464
+ }
465
+ syncOriginalAttribute(attribute) {
466
+ this.syncOriginalAttributes(attribute);
467
+ }
468
+ syncOriginalAttributes(...attributes) {
469
+ attributes = flattenDeep(attributes);
470
+ const modelAttributes = this.getAttributes();
471
+ for (const attribute of attributes) this.original[attribute] = modelAttributes[attribute];
472
+ return this;
473
+ }
474
+ isDirty(...attributes) {
475
+ const changes = this.getDirty();
476
+ attributes = flattenDeep(attributes);
477
+ if (attributes.length === 0) return Object.keys(changes).length > 0;
478
+ for (const attribute of attributes) if (attribute in changes) return true;
479
+ return false;
480
+ }
481
+ getDirty() {
482
+ const dirty = {};
483
+ const attributes = this.getAttributes();
484
+ for (const key in attributes) {
485
+ const value = attributes[key];
486
+ if (!this.originalIsEquivalent(key)) dirty[key] = value;
487
+ }
488
+ return dirty;
489
+ }
490
+ originalIsEquivalent(key) {
491
+ if (this.original[key] === void 0) return false;
492
+ const attribute = this.attributes[key];
493
+ const original = this.original[key];
494
+ if (attribute === original) return true;
495
+ else return false;
496
+ }
497
+ setAttributes(attributes) {
498
+ this.attributes = { ...attributes };
499
+ }
500
+ setRawAttributes(attributes, sync = false) {
501
+ this.attributes = attributes;
502
+ if (sync) this.syncOriginal();
503
+ return this;
504
+ }
505
+ getAttributes() {
506
+ return { ...this.attributes };
507
+ }
508
+ setAttribute(key, value) {
509
+ const setterMethod = getSetterMethod(key);
510
+ if (typeof this[setterMethod] === "function") {
511
+ this[setterMethod](value);
512
+ return this;
513
+ }
514
+ const attrMethod = getAttrMethod(key);
515
+ if (typeof this[attrMethod] === "function") {
516
+ const callback = this[attrMethod]().set || ((value$1) => {
517
+ this.attributes[key] = value$1;
518
+ });
519
+ this.attributes = {
520
+ ...this.attributes,
521
+ ...this.normalizeCastClassResponse(key, callback(value, this.attributes))
522
+ };
523
+ return this;
524
+ }
525
+ const castType = this.getCasts()[key];
526
+ if (this.isCustomCast(castType) && typeof castType !== "string") value = castType.set(this, key, value, this.attributes) ?? "";
527
+ if (castType === "json") value = JSON.stringify(value);
528
+ if (castType === "collection") value = JSON.stringify(value);
529
+ if (value !== null && this.isDateAttribute(key)) value = this.fromDateTime(value);
530
+ this.attributes[key] = value;
531
+ return this;
532
+ }
533
+ getAttribute(key) {
534
+ if (!key) return;
535
+ const getterMethod = getGetterMethod(key);
536
+ if (typeof this[getterMethod] === "function") return this[getterMethod](this.attributes[key], this.attributes);
537
+ const attrMethod = getAttrMethod(key);
538
+ if (typeof this[attrMethod] === "function") return this[attrMethod]().get(this.attributes[key], this.attributes);
539
+ if (key in this.attributes) {
540
+ if (this.hasCast(key)) return this.castAttribute(key, this.attributes[key]);
541
+ if (this.getDates().includes(key)) return this.asDateTime(this.attributes[key]);
542
+ return this.attributes[key];
543
+ }
544
+ if (key in this.relations) return this.relations[key];
545
+ }
546
+ castAttribute(key, value) {
547
+ const castType = this.getCastType(key);
548
+ if (!castType) return value;
549
+ if (value === null) return value;
550
+ switch (castType) {
551
+ case "int":
552
+ case "integer": return parseInt(value);
553
+ case "real":
554
+ case "float":
555
+ case "double": return parseFloat(value);
556
+ case "decimal": return this.asDecimal(value, castType.split(":")[1]);
557
+ case "string": return String(value);
558
+ case "bool":
559
+ case "boolean": return Boolean(value);
560
+ case "object":
561
+ case "json": try {
562
+ return JSON.parse(value);
563
+ } catch {
564
+ return null;
565
+ }
566
+ case "collection": try {
567
+ return collect$1(JSON.parse(value));
568
+ } catch {
569
+ return collect$1([]);
570
+ }
571
+ case "date": return this.asDate(value);
572
+ case "datetime":
573
+ case "custom_datetime": return this.asDateTime(value);
574
+ case "timestamp": return this.asTimestamp(value);
575
+ }
576
+ if (this.isCustomCast(castType)) return castType.get(this, key, value, this.attributes);
577
+ return value;
578
+ }
579
+ attributesToData() {
580
+ let attributes = { ...this.attributes };
581
+ for (const key in attributes) {
582
+ if (this.hidden.includes(key)) attributes = omit(attributes, [key]);
583
+ if (this.visible.length > 0 && this.visible.includes(key) === false) attributes = omit(attributes, [key]);
584
+ }
585
+ for (const key of this.getDates()) {
586
+ if (attributes[key] === void 0) continue;
587
+ attributes[key] = this.serializeDate(this.asDateTime(attributes[key]));
588
+ }
589
+ const casts = this.getCasts();
590
+ for (const key in casts) {
591
+ const value = casts[key];
592
+ if (key in attributes === false) continue;
593
+ attributes[key] = this.castAttribute(key, attributes[key]);
594
+ if (key in attributes && ["date", "datetime"].includes(String(value))) attributes[key] = this.serializeDate(attributes[key]);
595
+ if (key in attributes && this.isCustomDateTimeCast(value)) attributes[key] = dayjs(attributes[key]).format(String(value).split(":")[1]);
596
+ }
597
+ for (const key of this.appends) attributes[key] = this.mutateAttribute(key, null);
598
+ return attributes;
599
+ }
600
+ mutateAttribute(key, value) {
601
+ if (typeof this[getGetterMethod(key)] === "function") return this[getGetterMethod(key)](value);
602
+ else if (typeof this[getAttrMethod(key)] === "function") return this[getAttrMethod(key)]().get(key, this.attributes);
603
+ else if (key in this) return this[key];
604
+ return value;
605
+ }
606
+ mutateAttributeForArray(_key, _value) {}
607
+ isDateAttribute(key) {
608
+ return this.getDates().includes(key) || this.isDateCastable(key);
609
+ }
610
+ serializeDate(date) {
611
+ return date ? dayjs(date).toISOString() : null;
612
+ }
613
+ getDates() {
614
+ return this.usesTimestamps() ? [this.getCreatedAtColumn(), this.getUpdatedAtColumn()] : [];
615
+ }
616
+ getCasts() {
617
+ if (this.getIncrementing()) return {
618
+ [this.getKeyName()]: this.getKeyType(),
619
+ ...this.casts
620
+ };
621
+ return this.casts;
622
+ }
623
+ getCastType(key) {
624
+ const castType = this.getCasts()[key];
625
+ let castTypeCacheKey;
626
+ if (typeof castType === "string") castTypeCacheKey = castType;
627
+ else if (new castType() instanceof casts_attributes_default) castTypeCacheKey = castType.name;
628
+ if (castTypeCacheKey && this.getConstructor().castTypeCache[castTypeCacheKey] !== void 0) return this.getConstructor().castTypeCache[castTypeCacheKey];
629
+ let convertedCastType;
630
+ if (this.isCustomDateTimeCast(castType)) convertedCastType = "custom_datetime";
631
+ else if (this.isDecimalCast(castType)) convertedCastType = "decimal";
632
+ else if (this.isCustomCast(castType)) convertedCastType = castType;
633
+ else convertedCastType = String(castType).toLocaleLowerCase().trim();
634
+ return this.getConstructor()[castTypeCacheKey] = convertedCastType;
635
+ }
636
+ hasCast(key, types = []) {
637
+ if (key in this.casts) {
638
+ types = flat(types);
639
+ return types.length > 0 ? types.includes(this.getCastType(key)) : true;
640
+ }
641
+ return false;
642
+ }
643
+ withDayjs(date) {
644
+ return dayjs(date);
645
+ }
646
+ isCustomCast(cast) {
647
+ return typeof cast === "function" && new cast() instanceof casts_attributes_default;
648
+ }
649
+ isCustomDateTimeCast(cast) {
650
+ if (typeof cast !== "string") return false;
651
+ return cast.startsWith("date:") || cast.startsWith("datetime:");
652
+ }
653
+ isDecimalCast(cast) {
654
+ if (typeof cast !== "string") return false;
655
+ return cast.startsWith("decimal:");
656
+ }
657
+ isDateCastable(key) {
658
+ return this.hasCast(key, ["date", "datetime"]);
659
+ }
660
+ fromDateTime(value) {
661
+ return dayjs(this.asDateTime(value)).format(this.getDateFormat());
662
+ }
663
+ getDateFormat() {
664
+ return this.dateFormat || "YYYY-MM-DD HH:mm:ss";
665
+ }
666
+ asDecimal(value, decimals) {
667
+ return parseFloat(value).toFixed(decimals);
668
+ }
669
+ asDateTime(value) {
670
+ if (value === null) return null;
671
+ if (value instanceof Date) return value;
672
+ if (typeof value === "number") return /* @__PURE__ */ new Date(value * 1e3);
673
+ return new Date(value);
674
+ }
675
+ asDate(value) {
676
+ const date = this.asDateTime(value);
677
+ return dayjs(date).startOf("day").toDate();
678
+ }
679
+ };
680
+ };
681
+ var has_attributes_default = HasAttributes;
682
+
683
+ //#endregion
684
+ //#region src/scope.ts
685
+ var Scope = class Scope {
686
+ constructor() {
687
+ if (this.constructor === Scope) throw new Error("Scope cannot be instantiated");
688
+ }
689
+ apply(_builder, _model) {
690
+ throw new Error("apply not implemented");
691
+ }
692
+ };
693
+ var scope_default = Scope;
694
+
695
+ //#endregion
696
+ //#region src/concerns/has-global-scopes.ts
697
+ const HasGlobalScopes = (Model$1) => {
698
+ return class extends Model$1 {
699
+ static globalScopes;
700
+ static addGlobalScope(scope, implementation = null) {
701
+ if (typeof scope === "string" && implementation instanceof scope_default) {
702
+ this.globalScopes = set(this.globalScopes ?? {}, this.name + "." + scope, implementation);
703
+ return implementation;
704
+ } else if (scope instanceof scope_default) {
705
+ this.globalScopes = set(this.globalScopes ?? {}, this.name + "." + scope.constructor.name, scope);
706
+ return scope;
707
+ }
708
+ throw new InvalidArgumentError("Global scope must be an instance of Scope.");
709
+ }
710
+ static hasGlobalScope(scope) {
711
+ return this.getGlobalScope(scope) !== null;
712
+ }
713
+ static getGlobalScope(scope) {
714
+ if (typeof scope === "string") return get(this.globalScopes, this.name + "." + scope);
715
+ return get(this.globalScopes, this.name + "." + scope.constructor.name);
716
+ }
717
+ static getAllGlobalScopes() {
718
+ return this.globalScopes;
719
+ }
720
+ static setAllGlobalScopes(scopes) {
721
+ this.globalScopes = scopes;
722
+ }
723
+ getGlobalScopes() {
724
+ return get(this.constructor.globalScopes, this.constructor.name, {});
725
+ }
726
+ };
727
+ };
728
+ var has_global_scopes_default = HasGlobalScopes;
729
+
730
+ //#endregion
731
+ //#region src/hooks.ts
732
+ var Hooks = class {
733
+ hooks = {
734
+ creating: [],
735
+ created: [],
736
+ updating: [],
737
+ updated: [],
738
+ saving: [],
739
+ saved: [],
740
+ deleting: [],
741
+ deleted: [],
742
+ restoring: [],
743
+ restored: [],
744
+ trashed: [],
745
+ forceDeleting: [],
746
+ forceDeleted: []
747
+ };
748
+ add(hook, callback) {
749
+ this.hooks[hook].push(callback);
750
+ }
751
+ async exec(hook, data) {
752
+ const callbacks = this.hooks[hook] ?? [];
753
+ for (const callback of callbacks) await callback(...data);
754
+ return true;
755
+ }
756
+ };
757
+ var hooks_default = Hooks;
758
+
759
+ //#endregion
760
+ //#region src/concerns/has-hooks.ts
761
+ const HasHooks = (Model$1) => {
762
+ return class extends Model$1 {
763
+ static hooks = null;
764
+ static addHook(hook, callback) {
765
+ if (this.hooks instanceof hooks_default === false) this.hooks = new hooks_default();
766
+ this.hooks.add(hook, callback);
767
+ }
768
+ static creating(callback) {
769
+ this.addHook("creating", callback);
770
+ }
771
+ static created(callback) {
772
+ this.addHook("created", callback);
773
+ }
774
+ static updating(callback) {
775
+ this.addHook("updating", callback);
776
+ }
777
+ static updated(callback) {
778
+ this.addHook("updated", callback);
779
+ }
780
+ static saving(callback) {
781
+ this.addHook("saving", callback);
782
+ }
783
+ static saved(callback) {
784
+ this.addHook("saved", callback);
785
+ }
786
+ static deleting(callback) {
787
+ this.addHook("deleting", callback);
788
+ }
789
+ static deleted(callback) {
790
+ this.addHook("deleted", callback);
791
+ }
792
+ static restoring(callback) {
793
+ this.addHook("restoring", callback);
794
+ }
795
+ static restored(callback) {
796
+ this.addHook("restored", callback);
797
+ }
798
+ static trashed(callback) {
799
+ this.addHook("trashed", callback);
800
+ }
801
+ static forceDeleted(callback) {
802
+ this.addHook("forceDeleted", callback);
803
+ }
804
+ async execHooks(hook, options) {
805
+ if (this.constructor.hooks instanceof hooks_default === false) return;
806
+ return await this.constructor.hooks.exec(hook, [this, options]);
807
+ }
808
+ };
809
+ };
810
+ var has_hooks_default = HasHooks;
811
+
812
+ //#endregion
813
+ //#region src/relations/has-one-or-many.ts
814
+ const HasOneOrMany = (Relation$1) => {
815
+ return class extends Relation$1 {
816
+ getRelationValue(dictionary, key, type) {
817
+ const value = dictionary[key];
818
+ return type === "one" ? value[0] : new collection_default(value);
819
+ }
820
+ matchOneOrMany(models, results, relation, type) {
821
+ const dictionary = this.buildDictionary(results);
822
+ models.map((model) => {
823
+ const key = model.attributes[this.localKey];
824
+ if (dictionary[key] !== void 0) model.setRelation(relation, this.getRelationValue(dictionary, key, type));
825
+ });
826
+ return models;
827
+ }
828
+ buildDictionary(results) {
829
+ const foreign = this.getForeignKeyName();
830
+ return collect$1(results).mapToDictionary((result) => [result[foreign], result]).all();
831
+ }
832
+ async save(model) {
833
+ this.setForeignAttributesForCreate(model);
834
+ return await model.save() ? model : false;
835
+ }
836
+ async saveMany(models) {
837
+ await Promise.all(models.map(async (model) => {
838
+ await this.save(model);
839
+ }));
840
+ return models instanceof collection_default ? models : new collection_default(models);
841
+ }
842
+ async create(attributes = {}) {
843
+ return await tap(this.related.constructor.init(attributes), async (instance) => {
844
+ this.setForeignAttributesForCreate(instance);
845
+ await instance.save();
846
+ });
847
+ }
848
+ async createMany(records) {
849
+ const instances = await Promise.all(records.map(async (record) => {
850
+ return await this.create(record);
851
+ }));
852
+ return instances instanceof collection_default ? instances : new collection_default(instances);
853
+ }
854
+ setForeignAttributesForCreate(model) {
855
+ model[this.getForeignKeyName()] = this.getParentKey();
856
+ }
857
+ getForeignKeyName() {
858
+ const segments = this.getQualifiedForeignKeyName().split(".");
859
+ return segments[segments.length - 1];
860
+ }
861
+ getParentKey() {
862
+ return this.parent.attributes[this.localKey];
863
+ }
864
+ getQualifiedForeignKeyName() {
865
+ return this.foreignKey;
866
+ }
867
+ getExistenceCompareKey() {
868
+ return this.getQualifiedForeignKeyName();
869
+ }
870
+ addConstraints() {
871
+ if (this.constructor.constraints) {
872
+ const query = this.getRelationQuery();
873
+ query.where(this.foreignKey, "=", this.getParentKey());
874
+ query.whereNotNull(this.foreignKey);
875
+ }
876
+ }
877
+ };
878
+ };
879
+ var has_one_or_many_default = HasOneOrMany;
880
+
881
+ //#endregion
882
+ //#region src/relations/has-many.ts
883
+ var HasMany = class extends compose(relation_default, has_one_or_many_default) {
884
+ foreignKey;
885
+ localKey;
886
+ constructor(query, parent, foreignKey, localKey) {
887
+ super(query, parent);
888
+ this.foreignKey = foreignKey;
889
+ this.localKey = localKey;
890
+ this.addConstraints();
891
+ return this.asProxy();
892
+ }
893
+ initRelation(models, relation) {
894
+ models.map((model) => {
895
+ model.setRelation(relation, new collection_default([]));
896
+ });
897
+ return models;
898
+ }
899
+ async getResults() {
900
+ return this.getParentKey() !== null ? await this.query.get() : new collection_default([]);
901
+ }
902
+ getForeignKeyName() {
903
+ var _this$foreignKey;
904
+ const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
905
+ return segments === null || segments === void 0 ? void 0 : segments.pop();
906
+ }
907
+ buildDictionary(results) {
908
+ const foreign = this.getForeignKeyName();
909
+ return collect(results).mapToDictionary((result) => [result[foreign], result]).all();
910
+ }
911
+ match(models, results, relation) {
912
+ return this.matchOneOrMany(models, results, relation, "many");
913
+ }
914
+ addEagerConstraints(models) {
915
+ this.query.whereIn(this.foreignKey, this.getKeys(models, this.localKey));
916
+ }
917
+ };
918
+ var has_many_default = HasMany;
919
+
920
+ //#endregion
921
+ //#region src/relations/has-one.ts
922
+ var HasOne = class extends compose(relation_default, has_one_or_many_default, supports_default_models_default) {
923
+ foreignKey;
924
+ localKey;
925
+ constructor(query, parent, foreignKey, localKey) {
926
+ super(query, parent);
927
+ this.foreignKey = foreignKey;
928
+ this.localKey = localKey;
929
+ this.addConstraints();
930
+ return this.asProxy();
931
+ }
932
+ initRelation(models, relation) {
933
+ models.map((model) => {
934
+ model.setRelation(relation, this.getDefaultFor(model));
935
+ });
936
+ return models;
937
+ }
938
+ matchOne(models, results, relation) {
939
+ return this.matchOneOrMany(models, results, relation, "one");
940
+ }
941
+ getForeignKeyName() {
942
+ var _this$foreignKey;
943
+ const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
944
+ return segments === null || segments === void 0 ? void 0 : segments.pop();
945
+ }
946
+ async getResults() {
947
+ if (this.getParentKey() === null) return this.getDefaultFor(this.parent);
948
+ return await this.query.first() || this.getDefaultFor(this.parent);
949
+ }
950
+ match(models, results, relation) {
951
+ return this.matchOneOrMany(models, results, relation, "one");
952
+ }
953
+ addEagerConstraints(models) {
954
+ this.query.whereIn(this.foreignKey, this.getKeys(models, this.localKey));
955
+ }
956
+ newRelatedInstanceFor(parent) {
957
+ return this.related.newInstance().setAttribute(this.getForeignKeyName(), parent[this.localKey]);
958
+ }
959
+ };
960
+ var has_one_default = HasOne;
961
+
962
+ //#endregion
963
+ //#region src/relations/has-many-through.ts
964
+ var HasManyThrough = class extends relation_default {
965
+ throughParent;
966
+ farParent;
967
+ firstKey;
968
+ secondKey;
969
+ localKey;
970
+ secondLocalKey;
971
+ constructor(query, farParent, throughParent, firstKey, secondKey, localKey, secondLocalKey) {
972
+ super(query, throughParent);
973
+ this.localKey = localKey;
974
+ this.firstKey = firstKey;
975
+ this.secondKey = secondKey;
976
+ this.farParent = farParent;
977
+ this.throughParent = throughParent;
978
+ this.secondLocalKey = secondLocalKey;
979
+ return this.asProxy();
980
+ }
981
+ addConstraints() {
982
+ const localValue = this.farParent[this.localKey];
983
+ this.performJoin();
984
+ if (this.constructor.constraints) this.query.where(this.getQualifiedFirstKeyName(), "=", localValue);
985
+ }
986
+ performJoin(query = null) {
987
+ query = query || this.query;
988
+ const farKey = this.getQualifiedFarKeyName();
989
+ query.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", farKey);
990
+ if (this.throughParentSoftDeletes()) query.withGlobalScope("SoftDeletableHasManyThrough", (query$1) => {
991
+ query$1.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
992
+ });
993
+ }
994
+ getQualifiedParentKeyName() {
995
+ return this.parent.qualifyColumn(this.secondLocalKey);
996
+ }
997
+ throughParentSoftDeletes() {
998
+ return this.throughParent.pluginInitializers["SoftDeletes"] !== void 0;
999
+ }
1000
+ withTrashedParents() {
1001
+ this.query.withoutGlobalScope("SoftDeletableHasManyThrough");
1002
+ return this;
1003
+ }
1004
+ addEagerConstraints(models) {
1005
+ const whereIn = this.whereInMethod(this.farParent, this.localKey);
1006
+ this.whereInEager(whereIn, this.getQualifiedFirstKeyName(), this.getKeys(models, this.localKey));
1007
+ }
1008
+ initRelation(models, relation) {
1009
+ for (const model of models) model.setRelation(relation, this.related.newCollection());
1010
+ return models;
1011
+ }
1012
+ match(models, results, relation) {
1013
+ const dictionary = this.buildDictionary(results);
1014
+ for (const model of models) {
1015
+ const key = this.getDictionaryKey(model.getAttribute(this.localKey));
1016
+ if (dictionary[key] !== void 0) model.setRelation(relation, this.related.newCollection(dictionary[key]));
1017
+ }
1018
+ return models;
1019
+ }
1020
+ buildDictionary(results) {
1021
+ const dictionary = {};
1022
+ for (const result of results) {
1023
+ if (dictionary[result.laravel_through_key] === void 0) dictionary[result.laravel_through_key] = [];
1024
+ dictionary[result.laravel_through_key].push(result);
1025
+ }
1026
+ return dictionary;
1027
+ }
1028
+ async firstOrNew(attributes) {
1029
+ return await this.where(attributes).first() || this.related.newInstance(attributes);
1030
+ }
1031
+ async updateOrCreate(attributes, values = {}) {
1032
+ return tap(await this.firstOrCreate(attributes, values), async (instance) => {
1033
+ if (!instance.wasRecentlyCreated) await instance.fill(values).save();
1034
+ });
1035
+ }
1036
+ async firstWhere(column, operator = null, value = null, boolean = "and") {
1037
+ return await this.where(column, operator, value, boolean).first();
1038
+ }
1039
+ async first(columns = ["*"]) {
1040
+ const results = await this.take(1).get(columns);
1041
+ return results.count() > 0 ? results.first() : null;
1042
+ }
1043
+ async firstOrFail(columns = ["*"]) {
1044
+ const model = await this.first(columns);
1045
+ if (model) return model;
1046
+ throw new ModelNotFoundError().setModel(this.related.constructor);
1047
+ }
1048
+ async firstOr(columns = ["*"], callback = null) {
1049
+ if (typeof columns === "function") {
1050
+ callback = columns;
1051
+ columns = ["*"];
1052
+ }
1053
+ const model = await this.first(columns);
1054
+ if (model) return model;
1055
+ return callback === null || callback === void 0 ? void 0 : callback();
1056
+ }
1057
+ async find(id, columns = ["*"]) {
1058
+ if (isArray(id)) return await this.findMany(id, columns);
1059
+ return await this.where(this.getRelated().getQualifiedKeyName(), "=", id).first(columns);
1060
+ }
1061
+ async findMany(ids, columns = ["*"]) {
1062
+ if (ids.length === 0) return this.getRelated().newCollection();
1063
+ return await this.whereIn(this.getRelated().getQualifiedKeyName(), ids).get(columns);
1064
+ }
1065
+ async findOrFail(id, columns = ["*"]) {
1066
+ const result = await this.find(id, columns);
1067
+ if (Array.isArray(id)) {
1068
+ if (result.count() === id.length) return result;
1069
+ } else if (result) return result;
1070
+ throw new ModelNotFoundError().setModel(this.related.constructor, id);
1071
+ }
1072
+ async getResults() {
1073
+ return this.farParent[this.localKey] ? await this.get() : this.related.newCollection();
1074
+ }
1075
+ async get(columns = ["*"]) {
1076
+ const builder = this.prepareQueryBuilder(columns);
1077
+ let models = await builder.getModels();
1078
+ if (models.count() > 0) models = await builder.eagerLoadRelations(models);
1079
+ return this.related.newCollection(models);
1080
+ }
1081
+ async paginate(perPage = null, columns = ["*"], pageName = "page", page = null) {
1082
+ this.query.addSelect(this.shouldSelect(columns));
1083
+ return await this.query.paginate(perPage, columns, pageName, page);
1084
+ }
1085
+ shouldSelect(columns = ["*"]) {
1086
+ if ((columns === null || columns === void 0 ? void 0 : columns.at(0)) == "*") columns = [this.related.getTable() + ".*"];
1087
+ return [...columns, this.getQualifiedFirstKeyName() + " as laravel_through_key"];
1088
+ }
1089
+ async chunk(count, callback) {
1090
+ return await this.prepareQueryBuilder().chunk(count, callback);
1091
+ }
1092
+ prepareQueryBuilder(columns = ["*"]) {
1093
+ const builder = this.query.applyScopes();
1094
+ return builder.addSelect(this.shouldSelect(builder.getQuery().columns ? [] : columns));
1095
+ }
1096
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
1097
+ if (parentQuery.getQuery().from === query.getQuery().from) return this.getRelationExistenceQueryForSelfRelation(query, parentQuery, columns);
1098
+ if (parentQuery.getQuery().from === this.throughParent.getTable()) return this.getRelationExistenceQueryForThroughSelfRelation(query, parentQuery, columns);
1099
+ this.performJoin(query);
1100
+ return query.select(columns).where(this.getQualifiedLocalKeyName(), "=", this.getQualifiedFirstKeyName());
1101
+ }
1102
+ getRelationExistenceQueryForSelfRelation(query, parentQuery, columns = ["*"]) {
1103
+ const hash = this.getRelationCountHash();
1104
+ query.from(query.getModel().getTable() + " as " + hash);
1105
+ query.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", hash + "." + this.secondKey);
1106
+ if (this.throughParentSoftDeletes()) query.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
1107
+ query.getModel().setTable(hash);
1108
+ return query.select(columns).whereColumn(parentQuery.getQuery().from + "." + this.localKey, "=", this.getQualifiedFirstKeyName());
1109
+ }
1110
+ getRelationExistenceQueryForThroughSelfRelation(query, parentQuery, columns = ["*"]) {
1111
+ const hash = this.getRelationCountHash();
1112
+ const table = this.throughParent.getTable() + " as " + hash;
1113
+ query.join(table, hash + "." + this.secondLocalKey, "=", this.getQualifiedFarKeyName());
1114
+ if (this.throughParentSoftDeletes()) query.whereNull(hash + "." + this.throughParent.getDeletedAtColumn());
1115
+ return query.select(columns).where(parentQuery.getQuery().from + "." + this.localKey, "=", hash + "." + this.firstKey);
1116
+ }
1117
+ getQualifiedFarKeyName() {
1118
+ return this.getQualifiedForeignKeyName();
1119
+ }
1120
+ getFirstKeyName() {
1121
+ return this.firstKey;
1122
+ }
1123
+ getQualifiedFirstKeyName() {
1124
+ return this.throughParent.qualifyColumn(this.firstKey);
1125
+ }
1126
+ getForeignKeyName() {
1127
+ return this.secondKey;
1128
+ }
1129
+ getQualifiedForeignKeyName() {
1130
+ return this.related.qualifyColumn(this.secondKey);
1131
+ }
1132
+ getLocalKeyName() {
1133
+ return this.localKey;
1134
+ }
1135
+ getQualifiedLocalKeyName() {
1136
+ return this.farParent.qualifyColumn(this.localKey);
1137
+ }
1138
+ getSecondLocalKeyName() {
1139
+ return this.secondLocalKey;
1140
+ }
1141
+ };
1142
+ var has_many_through_default = HasManyThrough;
1143
+
1144
+ //#endregion
1145
+ //#region src/relations/has-one-through.ts
1146
+ var HasOneThrough = class extends compose(has_many_through_default, supports_default_models_default) {
1147
+ async getResults() {
1148
+ return await this.first() || this.getDefaultFor(this.farParent);
1149
+ }
1150
+ initRelation(models, relation) {
1151
+ for (const model of models) model.setRelation(relation, this.getDefaultFor(model));
1152
+ return models;
1153
+ }
1154
+ match(models, results, relation) {
1155
+ const dictionary = this.buildDictionary(results);
1156
+ for (const model of models) {
1157
+ const key = this.getDictionaryKey(model.getAttribute(this.localKey));
1158
+ if (dictionary[key] !== void 0) {
1159
+ const value = dictionary[key];
1160
+ model.setRelation(relation, value[0]);
1161
+ }
1162
+ }
1163
+ return models;
1164
+ }
1165
+ newRelatedInstanceFor(_parent) {
1166
+ return this.related.newInstance();
1167
+ }
1168
+ };
1169
+ var has_one_through_default = HasOneThrough;
1170
+
1171
+ //#endregion
1172
+ //#region src/concerns/has-relations.ts
1173
+ const HasRelations = (Model$1) => {
1174
+ return class extends Model$1 {
1175
+ relations = {};
1176
+ getRelation(relation) {
1177
+ return this.relations[relation];
1178
+ }
1179
+ setRelation(relation, value) {
1180
+ this.relations[relation] = value;
1181
+ return this;
1182
+ }
1183
+ unsetRelation(relation) {
1184
+ this.relations = omit(this.relations, [relation]);
1185
+ return this;
1186
+ }
1187
+ relationLoaded(relation) {
1188
+ return this.relations[relation] !== void 0;
1189
+ }
1190
+ related(relation) {
1191
+ if (typeof this[getRelationMethod(relation)] !== "function") {
1192
+ const message = `Model [${this.constructor.name}]'s relation [${relation}] doesn't exist.`;
1193
+ throw new RelationNotFoundError(message);
1194
+ }
1195
+ return this[getRelationMethod(relation)]();
1196
+ }
1197
+ async getRelated(relation) {
1198
+ return await this.related(relation).getResults();
1199
+ }
1200
+ relationsToData() {
1201
+ const data = {};
1202
+ for (const key in this.relations) {
1203
+ if (this.hidden.includes(key)) continue;
1204
+ if (this.visible.length > 0 && this.visible.includes(key) === false) continue;
1205
+ data[key] = this.relations[key] instanceof Array ? this.relations[key].map((item) => item.toData()) : this.relations[key] === null ? null : this.relations[key].toData();
1206
+ }
1207
+ return data;
1208
+ }
1209
+ guessBelongsToRelation() {
1210
+ const functionName = (/* @__PURE__ */ new Error()).stack.split("\n")[2].split(" ")[5];
1211
+ return getRelationName(functionName);
1212
+ }
1213
+ joiningTable(related, instance = null) {
1214
+ return [instance ? instance.joiningTableSegment() : snakeCase(related.name), this.joiningTableSegment()].sort().join("_").toLocaleLowerCase();
1215
+ }
1216
+ joiningTableSegment() {
1217
+ return snakeCase(this.constructor.name);
1218
+ }
1219
+ hasOne(related, foreignKey = null, localKey = null) {
1220
+ const query = related.query();
1221
+ const instance = new related();
1222
+ foreignKey = foreignKey || this.getForeignKey();
1223
+ localKey = localKey || this.getKeyName();
1224
+ return new has_one_default(query, this, instance.getTable() + "." + foreignKey, localKey);
1225
+ }
1226
+ hasMany(related, foreignKey = null, localKey = null) {
1227
+ const query = related.query();
1228
+ const instance = new related();
1229
+ foreignKey = foreignKey || this.getForeignKey();
1230
+ localKey = localKey || this.getKeyName();
1231
+ return new has_many_default(query, this, instance.getTable() + "." + foreignKey, localKey);
1232
+ }
1233
+ belongsTo(related, foreignKey = null, ownerKey = null, relation = null) {
1234
+ const query = related.query();
1235
+ const instance = new related();
1236
+ foreignKey = foreignKey || instance.getForeignKey();
1237
+ ownerKey = ownerKey || instance.getKeyName();
1238
+ relation = relation || this.guessBelongsToRelation();
1239
+ return new belongs_to_default(query, this, foreignKey, ownerKey, relation);
1240
+ }
1241
+ belongsToMany(related, table = null, foreignPivotKey = null, relatedPivotKey = null, parentKey = null, relatedKey = null) {
1242
+ const query = related.query();
1243
+ const instance = new related();
1244
+ table = table || this.joiningTable(related, instance);
1245
+ foreignPivotKey = foreignPivotKey || this.getForeignKey();
1246
+ relatedPivotKey = relatedPivotKey || instance.getForeignKey();
1247
+ parentKey = parentKey || this.getKeyName();
1248
+ relatedKey = relatedKey || instance.getKeyName();
1249
+ return new belongs_to_many_default(query, this, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey);
1250
+ }
1251
+ hasOneThrough(related, through, firstKey = null, secondKey = null, localKey = null, secondLocalKey = null) {
1252
+ through = new through();
1253
+ const query = related.query();
1254
+ firstKey = firstKey || this.getForeignKey();
1255
+ secondKey = secondKey || through.getForeignKey();
1256
+ return new has_one_through_default(query, this, through, firstKey, secondKey, localKey || this.getKeyName(), secondLocalKey || through.getKeyName());
1257
+ }
1258
+ hasManyThrough(related, through, firstKey = null, secondKey = null, localKey = null, secondLocalKey = null) {
1259
+ through = new through();
1260
+ const query = related.query();
1261
+ firstKey = firstKey || this.getForeignKey();
1262
+ secondKey = secondKey || through.getForeignKey();
1263
+ return new has_many_through_default(query, this, through, firstKey, secondKey, localKey || this.getKeyName(), secondLocalKey || through.getKeyName());
1264
+ }
1265
+ };
1266
+ };
1267
+ var has_relations_default = HasRelations;
1268
+
1269
+ //#endregion
1270
+ //#region src/concerns/has-timestamps.ts
1271
+ const HasTimestamps = (Model$1) => {
1272
+ return class extends Model$1 {
1273
+ static CREATED_AT = "created_at";
1274
+ static UPDATED_AT = "updated_at";
1275
+ static DELETED_AT = "deleted_at";
1276
+ timestamps = true;
1277
+ dateFormat = "YYYY-MM-DD HH:mm:ss";
1278
+ usesTimestamps() {
1279
+ return this.timestamps;
1280
+ }
1281
+ updateTimestamps() {
1282
+ const time = this.freshTimestampString();
1283
+ const updatedAtColumn = this.getUpdatedAtColumn();
1284
+ if (updatedAtColumn && !this.isDirty(updatedAtColumn)) this.setUpdatedAt(time);
1285
+ const createdAtColumn = this.getCreatedAtColumn();
1286
+ if (!this.exists && createdAtColumn && !this.isDirty(createdAtColumn)) this.setCreatedAt(time);
1287
+ return this;
1288
+ }
1289
+ getCreatedAtColumn() {
1290
+ return this.constructor.CREATED_AT;
1291
+ }
1292
+ getUpdatedAtColumn() {
1293
+ return this.constructor.UPDATED_AT;
1294
+ }
1295
+ setCreatedAt(value) {
1296
+ this.attributes[this.getCreatedAtColumn()] = value;
1297
+ return this;
1298
+ }
1299
+ setUpdatedAt(value) {
1300
+ this.attributes[this.getUpdatedAtColumn()] = value;
1301
+ return this;
1302
+ }
1303
+ freshTimestamp() {
1304
+ const time = /* @__PURE__ */ new Date();
1305
+ time.setMilliseconds(0);
1306
+ return time;
1307
+ }
1308
+ freshTimestampString() {
1309
+ return this.fromDateTime(this.freshTimestamp());
1310
+ }
1311
+ };
1312
+ };
1313
+ var has_timestamps_default = HasTimestamps;
1314
+
1315
+ //#endregion
1316
+ //#region src/concerns/hides-attributes.ts
1317
+ const HidesAttributes = (Model$1) => {
1318
+ return class extends Model$1 {
1319
+ hidden = [];
1320
+ visible = [];
1321
+ makeVisible(...keys) {
1322
+ const visible = flattenDeep(keys);
1323
+ if (this.visible.length > 0) this.visible = [...this.visible, ...visible];
1324
+ this.hidden = diff(this.hidden, visible);
1325
+ return this;
1326
+ }
1327
+ makeHidden(key, ...keys) {
1328
+ const hidden = flattenDeep([...key, ...keys]);
1329
+ if (this.hidden.length > 0) this.hidden = [...this.hidden, ...hidden];
1330
+ return this;
1331
+ }
1332
+ getHidden() {
1333
+ return this.hidden;
1334
+ }
1335
+ getVisible() {
1336
+ return this.visible;
1337
+ }
1338
+ setHidden(hidden) {
1339
+ this.hidden = hidden;
1340
+ return this;
1341
+ }
1342
+ setVisible(visible) {
1343
+ this.visible = visible;
1344
+ return this;
1345
+ }
1346
+ };
1347
+ };
1348
+ var hides_attributes_default = HidesAttributes;
1349
+
1350
+ //#endregion
1351
+ //#region src/concerns/unique-ids.ts
1352
+ const UniqueIds = (Model$1) => {
1353
+ return class extends Model$1 {
1354
+ useUniqueIds = false;
1355
+ usesUniqueIds() {
1356
+ return this.useUniqueIds;
1357
+ }
1358
+ uniqueIds() {
1359
+ return [];
1360
+ }
1361
+ newUniqueId() {
1362
+ return null;
1363
+ }
1364
+ setUniqueIds() {
1365
+ const uniqueIds = this.uniqueIds();
1366
+ for (const column of uniqueIds) if (this[column] === null || this[column] === void 0) this[column] = this.newUniqueId();
1367
+ }
1368
+ };
1369
+ };
1370
+ var unique_ids_default = UniqueIds;
1371
+
1372
+ //#endregion
1373
+ //#region src/paginator.ts
1374
+ var Paginator = class {
1375
+ static formatter;
1376
+ _items;
1377
+ _total;
1378
+ _perPage;
1379
+ _lastPage;
1380
+ _currentPage;
1381
+ hasMore = false;
1382
+ options = {};
1383
+ static setFormatter(formatter) {
1384
+ if (typeof formatter !== "function" && formatter !== null && formatter !== void 0) throw new Error("Paginator formatter must be a function or null");
1385
+ this.formatter = formatter;
1386
+ }
1387
+ constructor(items, total, perPage, currentPage = 1, options = {}) {
1388
+ this.options = options;
1389
+ for (const key in options) this[key] = options[key];
1390
+ this._items = new collection_default([]);
1391
+ this._total = total;
1392
+ this._perPage = parseInt(String(perPage));
1393
+ this._lastPage = Math.max(Math.ceil(total / perPage), 1);
1394
+ this._currentPage = currentPage;
1395
+ this.setItems(items);
1396
+ }
1397
+ setItems(items) {
1398
+ this._items = items instanceof collection_default ? items : new collection_default(items);
1399
+ this.hasMore = this._items.count() > this._perPage;
1400
+ this._items = this._items.slice(0, this._perPage);
1401
+ }
1402
+ firstItem() {
1403
+ return this.count() > 0 ? (this._currentPage - 1) * this._perPage + 1 : null;
1404
+ }
1405
+ lastItem() {
1406
+ return this.count() > 0 ? (this.firstItem() ?? 0) + this.count() - 1 : null;
1407
+ }
1408
+ hasMorePages() {
1409
+ return this._currentPage < this._lastPage;
1410
+ }
1411
+ get(index) {
1412
+ return this._items.get(index);
1413
+ }
1414
+ count() {
1415
+ return this._items.count();
1416
+ }
1417
+ items() {
1418
+ return this._items;
1419
+ }
1420
+ map(callback) {
1421
+ return this._items.map(callback);
1422
+ }
1423
+ currentPage() {
1424
+ return this._currentPage;
1425
+ }
1426
+ onFirstPage() {
1427
+ return this._currentPage === 1;
1428
+ }
1429
+ perPage() {
1430
+ return this._perPage;
1431
+ }
1432
+ lastPage() {
1433
+ return this._lastPage;
1434
+ }
1435
+ total() {
1436
+ return this._total;
1437
+ }
1438
+ toData() {
1439
+ if (this.constructor.formatter && typeof this.constructor.formatter === "function") return this.constructor.formatter(this);
1440
+ return {
1441
+ current_page: this._currentPage,
1442
+ data: this._items.toData(),
1443
+ per_page: this._perPage,
1444
+ total: this._total,
1445
+ last_page: this._lastPage,
1446
+ count: this.count()
1447
+ };
1448
+ }
1449
+ toJSON() {
1450
+ return this.toData();
1451
+ }
1452
+ toJson(...args) {
1453
+ return JSON.stringify(this.toData(), ...args);
1454
+ }
1455
+ };
1456
+ var paginator_default = Paginator;
1457
+
1458
+ //#endregion
1459
+ //#region src/query-builder.ts
1460
+ const Inference$2 = class {};
1461
+ var QueryBuilder = class QueryBuilder extends Inference$2 {
1462
+ model;
1463
+ schema;
1464
+ connector;
1465
+ constructor(config, connector) {
1466
+ super();
1467
+ this.connector = connector(config);
1468
+ return this.asProxy();
1469
+ }
1470
+ asProxy() {
1471
+ return new Proxy(this, {
1472
+ get: function(target, prop) {
1473
+ if (typeof target[prop] !== "undefined") return target[prop];
1474
+ if (["destroy", "schema"].includes(prop)) return target.connector.schema;
1475
+ if ([
1476
+ "select",
1477
+ "from",
1478
+ "where",
1479
+ "orWhere",
1480
+ "whereColumn",
1481
+ "whereRaw",
1482
+ "whereNot",
1483
+ "orWhereNot",
1484
+ "whereIn",
1485
+ "orWhereIn",
1486
+ "whereNotIn",
1487
+ "orWhereNotIn",
1488
+ "whereNull",
1489
+ "orWhereNull",
1490
+ "whereNotNull",
1491
+ "orWhereNotNull",
1492
+ "whereExists",
1493
+ "orWhereExists",
1494
+ "whereNotExists",
1495
+ "orWhereNotExists",
1496
+ "whereBetween",
1497
+ "orWhereBetween",
1498
+ "whereNotBetween",
1499
+ "orWhereNotBetween",
1500
+ "whereLike",
1501
+ "orWhereLike",
1502
+ "whereILike",
1503
+ "orWhereILike",
1504
+ "whereJsonObject",
1505
+ "whereJsonPath",
1506
+ "whereJsonSupersetOf",
1507
+ "whereJsonSubsetOf",
1508
+ "join",
1509
+ "joinRaw",
1510
+ "leftJoin",
1511
+ "leftOuterJoin",
1512
+ "rightJoin",
1513
+ "rightOuterJoin",
1514
+ "crossJoin",
1515
+ "transacting",
1516
+ "groupBy",
1517
+ "groupByRaw",
1518
+ "returning",
1519
+ "having",
1520
+ "havingRaw",
1521
+ "havingBetween",
1522
+ "limit",
1523
+ "offset",
1524
+ "orderBy",
1525
+ "orderByRaw",
1526
+ "union",
1527
+ "insert",
1528
+ "forUpdate",
1529
+ "forShare",
1530
+ "distinct",
1531
+ "clearOrder",
1532
+ "clear",
1533
+ "clearSelect",
1534
+ "clearWhere",
1535
+ "clearHaving",
1536
+ "clearGroup"
1537
+ ].includes(prop)) return (...args) => {
1538
+ target.connector[prop](...args);
1539
+ return target.asProxy();
1540
+ };
1541
+ return target.connector[prop];
1542
+ },
1543
+ set: function(target, prop, value) {
1544
+ if (typeof target[prop] !== "undefined") {
1545
+ target[prop] = value;
1546
+ return target;
1547
+ }
1548
+ target.connector[prop] = value;
1549
+ return target;
1550
+ }
1551
+ });
1552
+ }
1553
+ async beginTransaction() {
1554
+ return await this.connector.transaction();
1555
+ }
1556
+ table(table) {
1557
+ const c = this.connector.table(table);
1558
+ return new QueryBuilder(null, () => c);
1559
+ }
1560
+ transaction(callback) {
1561
+ if (callback) return this.connector.transaction((trx) => {
1562
+ return callback(new QueryBuilder(null, () => trx));
1563
+ });
1564
+ return callback;
1565
+ }
1566
+ async find(id, columns = ["*"]) {
1567
+ return await this.connector.where("id", id).first(...columns);
1568
+ }
1569
+ async get(_columns = ["*"]) {
1570
+ return await this.connector;
1571
+ }
1572
+ async exists() {
1573
+ return await this.connector.first() !== null;
1574
+ }
1575
+ skip(...args) {
1576
+ return this.offset(...args);
1577
+ }
1578
+ take(...args) {
1579
+ return this.limit(...args);
1580
+ }
1581
+ async chunk(count, callback) {
1582
+ if (this.connector._statements.filter((item) => item.grouping === "order").length === 0) throw new Error("You must specify an orderBy clause when using this function.");
1583
+ let page = 1;
1584
+ let countResults;
1585
+ do {
1586
+ const results = await this.clone().forPage(page, count).get();
1587
+ countResults = results.length;
1588
+ if (countResults == 0) break;
1589
+ if (await callback(results, page) === false) return false;
1590
+ page++;
1591
+ } while (countResults === count);
1592
+ return true;
1593
+ }
1594
+ async paginate(page = 1, perPage = 15) {
1595
+ const total = await this.clone().clearOrder().count("*");
1596
+ let results;
1597
+ if (total > 0) {
1598
+ const skip = (page - 1) * perPage;
1599
+ this.take(perPage).skip(skip);
1600
+ results = await this.get();
1601
+ } else results = [];
1602
+ return new paginator_default(results, parseInt(total), perPage, page);
1603
+ }
1604
+ forPage(page = 1, perPage = 15) {
1605
+ return this.offset((page - 1) * perPage).limit(perPage);
1606
+ }
1607
+ toSQL(...args) {
1608
+ return this.connector.toSQL(...args);
1609
+ }
1610
+ async count(column) {
1611
+ const [{ aggregate }] = await this.connector.count(column, { as: "aggregate" });
1612
+ return Number(aggregate);
1613
+ }
1614
+ async min(column) {
1615
+ const [{ aggregate }] = await this.connector.min(column, { as: "aggregate" });
1616
+ return Number(aggregate);
1617
+ }
1618
+ async max(column) {
1619
+ const [{ aggregate }] = await this.connector.max(column, { as: "aggregate" });
1620
+ return Number(aggregate);
1621
+ }
1622
+ async sum(column) {
1623
+ const [{ aggregate }] = await this.connector.sum(column, { as: "aggregate" });
1624
+ return Number(aggregate);
1625
+ }
1626
+ async avg(column) {
1627
+ const [{ aggregate }] = await this.connector.avg(column, { as: "aggregate" });
1628
+ return Number(aggregate);
1629
+ }
1630
+ clone() {
1631
+ const c = this.connector.clone();
1632
+ return new QueryBuilder(null, () => c);
1633
+ }
1634
+ async delete() {
1635
+ return await this.connector.delete();
1636
+ }
1637
+ async insert(...args) {
1638
+ return await this.connector.insert(...args);
1639
+ }
1640
+ async update(...args) {
1641
+ return await this.connector.update(...args);
1642
+ }
1643
+ destroy(...args) {
1644
+ return this.connector.destroy(...args);
1645
+ }
1646
+ get _statements() {
1647
+ return this.connector._statements;
1648
+ }
1649
+ get _single() {
1650
+ return this.connector._single;
1651
+ }
1652
+ get from() {
1653
+ return this.connector.from;
1654
+ }
1655
+ };
1656
+ var query_builder_default = QueryBuilder;
1657
+
1658
+ //#endregion
1659
+ //#region src/arquebus.ts
1660
+ var arquebus = class arquebus {
1661
+ static connectorFactory = null;
1662
+ static instance = null;
1663
+ manager;
1664
+ connections;
1665
+ models;
1666
+ constructor() {
1667
+ this.manager = {};
1668
+ this.connections = {};
1669
+ this.models = {};
1670
+ }
1671
+ getConstructor() {
1672
+ return this.constructor;
1673
+ }
1674
+ static getInstance() {
1675
+ if (this.instance === null) this.instance = new arquebus();
1676
+ return this.instance;
1677
+ }
1678
+ /**
1679
+ * Initialize a new database connection
1680
+ *
1681
+ * @returns
1682
+ */
1683
+ static fire(connection = null) {
1684
+ return this.getInstance().getConnection(connection);
1685
+ }
1686
+ /**
1687
+ * Initialize a new database connection
1688
+ *
1689
+ * This is an alias of `arquebus.fire()` and will be removed in the future
1690
+ *
1691
+ * @deprecated since version 0.3.0
1692
+ * @alias fire
1693
+ *
1694
+ * @returns
1695
+ */
1696
+ static connection(connection = null) {
1697
+ return this.fire(connection);
1698
+ }
1699
+ static setConnectorFactory(connectorFactory) {
1700
+ this.connectorFactory = connectorFactory;
1701
+ }
1702
+ static getConnectorFactory() {
1703
+ return this.connectorFactory ?? Knex$1;
1704
+ }
1705
+ static addConnection(config, name = "default") {
1706
+ return this.getInstance().addConnection(config, name);
1707
+ }
1708
+ static beginTransaction(connection = null) {
1709
+ return this.getInstance().beginTransaction(connection);
1710
+ }
1711
+ static transaction(callback, connection = null) {
1712
+ return this.getInstance().transaction(callback, connection);
1713
+ }
1714
+ static table(name, connection = null) {
1715
+ return this.getInstance().table(name, connection);
1716
+ }
1717
+ static schema(connection = null) {
1718
+ return this.getInstance().schema(connection);
1719
+ }
1720
+ static async destroyAll() {
1721
+ await this.getInstance().destroyAll();
1722
+ }
1723
+ static createModel(name, options) {
1724
+ return this.getInstance().createModel(name, options);
1725
+ }
1726
+ connection(connection = null) {
1727
+ return this.getConnection(connection);
1728
+ }
1729
+ getConnection(name = null) {
1730
+ name = name || "default";
1731
+ if (this.manager[name] === void 0) {
1732
+ const queryBuilder = new query_builder_default(this.connections[name], arquebus.getConnectorFactory());
1733
+ this.manager[name] = queryBuilder;
1734
+ }
1735
+ return this.manager[name];
1736
+ }
1737
+ addConnection(config, name = "default") {
1738
+ this.connections[name] = {
1739
+ ...config,
1740
+ connection: {
1741
+ ...config.connection,
1742
+ dateStrings: true,
1743
+ typeCast: function(field, next) {
1744
+ if (field.type === "JSON") return field.string("utf8");
1745
+ return next();
1746
+ }
1747
+ }
1748
+ };
1749
+ }
1750
+ /**
1751
+ * Autoload the config file
1752
+ *
1753
+ * @param addConnection
1754
+ * @default true
1755
+ * If set to `false` we will no attempt add the connection, we
1756
+ * will just go ahead and return the config
1757
+ *
1758
+ * @returns
1759
+ */
1760
+ static async autoLoad(addConnection = true) {
1761
+ let config;
1762
+ const jsPath = path.resolve("arquebus.config.js");
1763
+ const tsPath = path.resolve("arquebus.config.ts");
1764
+ const instance = this.getInstance();
1765
+ if (existsSync(jsPath)) {
1766
+ config = (await import(jsPath)).default;
1767
+ if (addConnection) instance.addConnection(config, config.client);
1768
+ return config;
1769
+ }
1770
+ if (existsSync(tsPath)) if (process.env.NODE_ENV !== "production") {
1771
+ config = (await import(tsPath)).default;
1772
+ if (addConnection) instance.addConnection(config, config.client);
1773
+ return config;
1774
+ } else throw new Error("arquebus.config.ts found in production without build step");
1775
+ return {};
1776
+ }
1777
+ beginTransaction(connection = null) {
1778
+ return this.connection(connection).beginTransaction();
1779
+ }
1780
+ transaction(callback, connection = null) {
1781
+ return this.connection(connection).transaction(callback);
1782
+ }
1783
+ table(name, connection = null) {
1784
+ return this.connection(connection).table(name);
1785
+ }
1786
+ schema(connection = null) {
1787
+ return this.connection(connection).schema;
1788
+ }
1789
+ async destroyAll() {
1790
+ await Promise.all(Object.values(this.manager).map((connection) => {
1791
+ return connection === null || connection === void 0 ? void 0 : connection.destroy();
1792
+ }));
1793
+ }
1794
+ createModel(name, options = {}) {
1795
+ let BaseModel$1 = Model;
1796
+ if ("plugins" in options) BaseModel$1 = compose(BaseModel$1, ...options.plugins ?? []);
1797
+ this.models = {
1798
+ ...this.models,
1799
+ [name]: class extends BaseModel$1 {
1800
+ table = (options === null || options === void 0 ? void 0 : options.table) ?? null;
1801
+ connection = (options === null || options === void 0 ? void 0 : options.connection) ?? null;
1802
+ timestamps = (options === null || options === void 0 ? void 0 : options.timestamps) ?? true;
1803
+ primaryKey = (options === null || options === void 0 ? void 0 : options.primaryKey) ?? "id";
1804
+ keyType = (options === null || options === void 0 ? void 0 : options.keyType) ?? "int";
1805
+ incrementing = (options === null || options === void 0 ? void 0 : options.incrementing) ?? true;
1806
+ with = (options === null || options === void 0 ? void 0 : options.with) ?? [];
1807
+ casts = (options === null || options === void 0 ? void 0 : options.casts) ?? {};
1808
+ static CREATED_AT = (options === null || options === void 0 ? void 0 : options.CREATED_AT) ?? "created_at";
1809
+ static UPDATED_AT = (options === null || options === void 0 ? void 0 : options.UPDATED_AT) ?? "updated_at";
1810
+ static DELETED_AT = (options === null || options === void 0 ? void 0 : options.DELETED_AT) ?? "deleted_at";
1811
+ }
1812
+ };
1813
+ if ("attributes" in options) for (const attribute in options.attributes) {
1814
+ if (options.attributes[attribute] instanceof attribute_default === false) throw new Error("Attribute must be an instance of \"Attribute\"");
1815
+ this.models[name].prototype[getAttrMethod(attribute)] = () => {
1816
+ var _options$attributes;
1817
+ return (_options$attributes = options.attributes) === null || _options$attributes === void 0 ? void 0 : _options$attributes[attribute];
1818
+ };
1819
+ }
1820
+ if ("relations" in options) for (const relation in options.relations) this.models[name].prototype[getRelationMethod(relation)] = function() {
1821
+ var _options$relations;
1822
+ return (_options$relations = options.relations) === null || _options$relations === void 0 ? void 0 : _options$relations[relation](this);
1823
+ };
1824
+ if ("scopes" in options) for (const scope in options.scopes) this.models[name].prototype[getScopeMethod(scope)] = options.scopes[scope];
1825
+ this.models[name].setConnectionResolver(this);
1826
+ return this.models[name];
1827
+ }
1828
+ };
1829
+ var arquebus_default = arquebus;
1830
+
1831
+ //#endregion
1832
+ //#region src/model.ts
1833
+ const BaseModel = compose(class {}, has_attributes_default, hides_attributes_default, has_relations_default, has_timestamps_default, has_hooks_default, has_global_scopes_default, unique_ids_default);
1834
+ var Model = class Model extends BaseModel {
1835
+ primaryKey = "id";
1836
+ builder = null;
1837
+ table = null;
1838
+ keyType = "int";
1839
+ incrementing = true;
1840
+ withCount = [];
1841
+ perPage = 15;
1842
+ static globalScopes = {};
1843
+ static pluginInitializers = {};
1844
+ static _booted = {};
1845
+ static resolver;
1846
+ connection = null;
1847
+ eagerLoad = {};
1848
+ exists = false;
1849
+ with = [];
1850
+ trx = null;
1851
+ constructor(attributes = {}) {
1852
+ super();
1853
+ this.bootIfNotBooted();
1854
+ this.initializePlugins();
1855
+ this.syncOriginal();
1856
+ this.fill(attributes);
1857
+ return this.asProxy();
1858
+ }
1859
+ static query(trx = null) {
1860
+ return new this().newQuery(trx);
1861
+ }
1862
+ static on(connection = null) {
1863
+ const instance = new this();
1864
+ instance.setConnection(connection);
1865
+ return instance.newQuery();
1866
+ }
1867
+ static init(attributes = {}) {
1868
+ return new this(attributes);
1869
+ }
1870
+ static extend(plugin, options) {
1871
+ plugin(this, options);
1872
+ }
1873
+ static make(attributes = {}) {
1874
+ const instance = new this();
1875
+ for (const attribute in attributes) if (typeof instance[getRelationMethod(attribute)] !== "function") instance.setAttribute(attribute, attributes[attribute]);
1876
+ else {
1877
+ const relation = instance[getRelationMethod(attribute)]();
1878
+ const related = relation.getRelated().constructor;
1879
+ if (relation instanceof has_one_default || relation instanceof belongs_to_default) instance.setRelation(attribute, related.make(attributes[attribute]));
1880
+ else if ((relation instanceof has_many_default || relation instanceof belongs_to_many_default) && Array.isArray(attributes[attribute])) instance.setRelation(attribute, new collection_default(attributes[attribute].map((item) => related.make(item))));
1881
+ }
1882
+ return instance;
1883
+ }
1884
+ getConstructor() {
1885
+ return this.constructor;
1886
+ }
1887
+ bootIfNotBooted() {
1888
+ if (this.constructor._booted[this.constructor.name] === void 0) {
1889
+ this.constructor._booted[this.constructor.name] = true;
1890
+ this.constructor.booting();
1891
+ this.initialize();
1892
+ this.constructor.boot();
1893
+ this.constructor.booted();
1894
+ }
1895
+ }
1896
+ static booting() {}
1897
+ static boot() {}
1898
+ static booted() {}
1899
+ static setConnectionResolver(resolver) {
1900
+ this.resolver = resolver;
1901
+ }
1902
+ initialize() {}
1903
+ initializePlugins() {
1904
+ if (typeof this.constructor.pluginInitializers[this.constructor.name] === "undefined") return;
1905
+ for (const method of this.constructor.pluginInitializers[this.constructor.name]) this[method]();
1906
+ }
1907
+ addPluginInitializer(method) {
1908
+ if (!this.constructor.pluginInitializers[this.constructor.name]) this.constructor.pluginInitializers[this.constructor.name] = [];
1909
+ this.constructor.pluginInitializers[this.constructor.name].push(method);
1910
+ }
1911
+ newInstance(attributes = {}, exists = false) {
1912
+ const model = new this.constructor();
1913
+ model.exists = exists;
1914
+ model.setConnection(this.getConnectionName());
1915
+ model.setTable(this.getTable());
1916
+ model.fill(attributes);
1917
+ return model;
1918
+ }
1919
+ newFromBuilder(attributes = {}, connection = null) {
1920
+ const model = this.newInstance({}, true);
1921
+ model.setRawAttributes(attributes, true);
1922
+ model.setConnection(connection || this.getConnectionName());
1923
+ return model;
1924
+ }
1925
+ asProxy() {
1926
+ return new Proxy(this, {
1927
+ get: function(target, prop) {
1928
+ if (target[prop] !== void 0) return target[prop];
1929
+ if (typeof prop === "string") return target.getAttribute(prop);
1930
+ },
1931
+ set: function(target, prop, value) {
1932
+ if (target[prop] !== void 0 && typeof target !== "function") {
1933
+ target[prop] = value;
1934
+ return target;
1935
+ }
1936
+ if (typeof prop === "string") return target.setAttribute(prop, value);
1937
+ return target;
1938
+ }
1939
+ });
1940
+ }
1941
+ getKey() {
1942
+ return this.getAttribute(this.getKeyName());
1943
+ }
1944
+ getKeyName() {
1945
+ return this.primaryKey;
1946
+ }
1947
+ getForeignKey() {
1948
+ return snakeCase(this.constructor.name) + "_" + this.getKeyName();
1949
+ }
1950
+ getConnectionName() {
1951
+ return this.connection;
1952
+ }
1953
+ getTable() {
1954
+ return this.table || pluralize(snakeCase(this.constructor.name));
1955
+ }
1956
+ getConnection() {
1957
+ if (this.constructor.resolver) return this.constructor.resolver.getConnection(this.connection);
1958
+ return arquebus_default.fire(this.connection);
1959
+ }
1960
+ setConnection(connection) {
1961
+ this.connection = connection;
1962
+ return this;
1963
+ }
1964
+ getKeyType() {
1965
+ return this.keyType;
1966
+ }
1967
+ newQuery(trx = null) {
1968
+ return this.addGlobalScopes(this.newQueryWithoutScopes(trx));
1969
+ }
1970
+ newQueryWithoutScopes(trx = null) {
1971
+ return this.newModelQuery(trx).with(this.with).withCount(this.withCount);
1972
+ }
1973
+ newModelQuery(trx = null) {
1974
+ return new builder_default(trx || this.getConnection()).setModel(this);
1975
+ }
1976
+ addGlobalScopes(builder) {
1977
+ const globalScopes = this.getGlobalScopes();
1978
+ for (const identifier in globalScopes) {
1979
+ const scope = globalScopes[identifier];
1980
+ builder.withGlobalScope(identifier, scope);
1981
+ }
1982
+ return builder;
1983
+ }
1984
+ hasNamedScope(name) {
1985
+ const scope = getScopeMethod(name);
1986
+ return typeof this[scope] === "function";
1987
+ }
1988
+ callNamedScope(scope, parameters) {
1989
+ const scopeMethod = getScopeMethod(scope);
1990
+ return this[scopeMethod](...parameters);
1991
+ }
1992
+ setTable(table) {
1993
+ this.table = table;
1994
+ return this;
1995
+ }
1996
+ newCollection(models = []) {
1997
+ return new collection_default(models);
1998
+ }
1999
+ async load(...relations) {
2000
+ await this.constructor.query().with(...relations).eagerLoadRelations([this]);
2001
+ return this;
2002
+ }
2003
+ async loadAggregate(relations, column, callback = null) {
2004
+ console.log(relations);
2005
+ await new collection_default([this]).loadAggregate(relations, column, callback);
2006
+ return this;
2007
+ }
2008
+ async loadCount(...relations) {
2009
+ relations = flattenDeep(relations);
2010
+ return await this.loadAggregate(relations, "*", "count");
2011
+ }
2012
+ async loadMax(relations, column) {
2013
+ return await this.loadAggregate(relations, column, "max");
2014
+ }
2015
+ async loadMin(relations, column) {
2016
+ return await this.loadAggregate(relations, column, "min");
2017
+ }
2018
+ async loadSum(relations, column) {
2019
+ return await this.loadAggregate(relations, column, "sum");
2020
+ }
2021
+ async increment(column, amount = 1, extra = {}, options = {}) {
2022
+ return await this.incrementOrDecrement(column, amount, extra, "increment", options);
2023
+ }
2024
+ async decrement(column, amount = 1, extra = {}, options = {}) {
2025
+ return await this.incrementOrDecrement(column, amount, extra, "decrement", options);
2026
+ }
2027
+ async incrementOrDecrement(column, amount, extra, method, options) {
2028
+ const query = this.newModelQuery(options.client);
2029
+ if (!this.exists) return await query[method](column, amount, extra);
2030
+ this.attributes[column] = this[column] + (method === "increment" ? amount : amount * -1);
2031
+ for (const key in extra) this.attributes[key] = extra[key];
2032
+ await this.execHooks("updating", options);
2033
+ return await tap(await query.where(this.getKeyName(), this.getKey())[method](column, amount, extra), async () => {
2034
+ this.syncChanges();
2035
+ await this.execHooks("updated", options);
2036
+ this.syncOriginalAttribute(column);
2037
+ });
2038
+ }
2039
+ toData() {
2040
+ return assign(this.attributesToData(), this.relationsToData());
2041
+ }
2042
+ toJSON() {
2043
+ return this.toData();
2044
+ }
2045
+ toJson(...args) {
2046
+ return JSON.stringify(this.toData(), ...args);
2047
+ }
2048
+ toString() {
2049
+ return this.toJson();
2050
+ }
2051
+ fill(attributes) {
2052
+ for (const key in attributes) this.setAttribute(key, attributes[key]);
2053
+ return this;
2054
+ }
2055
+ transacting(trx) {
2056
+ this.trx = trx;
2057
+ return this;
2058
+ }
2059
+ trashed() {
2060
+ return this[this.getDeletedAtColumn()] !== null;
2061
+ }
2062
+ getIncrementing() {
2063
+ return this.incrementing;
2064
+ }
2065
+ setIncrementing(value) {
2066
+ this.incrementing = value;
2067
+ return this;
2068
+ }
2069
+ async save(options = {}) {
2070
+ const query = this.newModelQuery(options.client);
2071
+ let saved;
2072
+ await this.execHooks("saving", options);
2073
+ if (this.exists) if (this.isDirty() === false) saved = true;
2074
+ else {
2075
+ await this.execHooks("updating", options);
2076
+ if (this.usesTimestamps()) this.updateTimestamps();
2077
+ const dirty = this.getDirty();
2078
+ if (Object.keys(dirty).length > 0) {
2079
+ await query.where(this.getKeyName(), this.getKey()).query.update(dirty);
2080
+ this.syncChanges();
2081
+ await this.execHooks("updated", options);
2082
+ }
2083
+ saved = true;
2084
+ }
2085
+ else {
2086
+ if (this.usesUniqueIds()) this.setUniqueIds();
2087
+ await this.execHooks("creating", options);
2088
+ if (this.usesTimestamps()) this.updateTimestamps();
2089
+ const attributes = this.getAttributes();
2090
+ if (this.getIncrementing()) {
2091
+ var _data$;
2092
+ const keyName = this.getKeyName();
2093
+ const data = await query.insert([attributes], [keyName]);
2094
+ this.setAttribute(keyName, ((_data$ = data[0]) === null || _data$ === void 0 ? void 0 : _data$[keyName]) || data[0]);
2095
+ } else if (Object.keys(attributes).length > 0) await query.insert(attributes);
2096
+ this.exists = true;
2097
+ await this.execHooks("created", options);
2098
+ saved = true;
2099
+ }
2100
+ if (saved) {
2101
+ await this.execHooks("saved", options);
2102
+ this.syncOriginal();
2103
+ }
2104
+ return saved;
2105
+ }
2106
+ async update(attributes = {}, options = {}) {
2107
+ if (!this.exists) return false;
2108
+ for (const key in attributes) this[key] = attributes[key];
2109
+ return await this.save(options);
2110
+ }
2111
+ async delete(options = {}) {
2112
+ await this.execHooks("deleting", options);
2113
+ await this.performDeleteOnModel(options);
2114
+ await this.execHooks("deleted", options);
2115
+ return true;
2116
+ }
2117
+ async performDeleteOnModel(options = {}) {
2118
+ await this.setKeysForSaveQuery(this.newModelQuery(options.client)).delete();
2119
+ this.exists = false;
2120
+ }
2121
+ setKeysForSaveQuery(query) {
2122
+ query.where(this.getKeyName(), "=", this.getKey());
2123
+ return query;
2124
+ }
2125
+ async forceDelete(options = {}) {
2126
+ return await this.delete(options);
2127
+ }
2128
+ fresh() {
2129
+ if (!this.exists) return;
2130
+ return this.constructor.query().where(this.getKeyName(), this.getKey()).first();
2131
+ }
2132
+ async refresh() {
2133
+ if (!this.exists) return Promise.resolve(void 0);
2134
+ this.attributes = { ...(await this.constructor.query().where(this.getKeyName(), this.getKey()).first()).attributes };
2135
+ await this.load(collect$1(this.relations).reject((relation) => {
2136
+ return relation instanceof Pivot;
2137
+ }).keys().all());
2138
+ this.syncOriginal();
2139
+ return this;
2140
+ }
2141
+ newPivot(parent, attributes, table, exists, using = null) {
2142
+ return using ? using.fromRawAttributes(parent, attributes, table, exists) : Pivot.fromAttributes(parent, attributes, table, exists);
2143
+ }
2144
+ qualifyColumn(column) {
2145
+ if (column.includes(".")) return column;
2146
+ return `${this.getTable()}.${column}`;
2147
+ }
2148
+ getQualifiedKeyName() {
2149
+ return this.qualifyColumn(this.getKeyName());
2150
+ }
2151
+ async push(options = {}) {
2152
+ if (!await this.save(options)) return false;
2153
+ for (const relation in this.relations) {
2154
+ let models = this.relations[relation];
2155
+ models = models instanceof collection_default ? models.all() : [models];
2156
+ for (const model of models) if (!await model.push(options)) return false;
2157
+ }
2158
+ return true;
2159
+ }
2160
+ is(model) {
2161
+ return model && model instanceof Model && this.getKey() === model.getKey() && this.getTable() === model.getTable() && this.getConnectionName() === model.getConnectionName();
2162
+ }
2163
+ isNot(model) {
2164
+ return !this.is(model);
2165
+ }
2166
+ };
2167
+ var Pivot = class extends Model {
2168
+ incrementing = false;
2169
+ guarded = [];
2170
+ pivotParent = null;
2171
+ foreignKey = null;
2172
+ relatedKey = null;
2173
+ setPivotKeys(foreignKey, relatedKey) {
2174
+ this.foreignKey = foreignKey;
2175
+ this.relatedKey = relatedKey;
2176
+ return this;
2177
+ }
2178
+ static fromRawAttributes(parent, attributes, table, exists = false) {
2179
+ const instance = this.fromAttributes(parent, {}, table, exists);
2180
+ instance.timestamps = instance.hasTimestampAttributes(attributes);
2181
+ instance.attributes = attributes;
2182
+ instance.exists = exists;
2183
+ return instance;
2184
+ }
2185
+ static fromAttributes(parent, attributes, table, exists = false) {
2186
+ const instance = new this();
2187
+ instance.timestamps = instance.hasTimestampAttributes(attributes);
2188
+ instance.setConnection(parent.connection).setTable(table).fill(attributes).syncOriginal();
2189
+ instance.pivotParent = parent;
2190
+ instance.exists = exists;
2191
+ return instance;
2192
+ }
2193
+ hasTimestampAttributes(attributes = null) {
2194
+ return (attributes || this.attributes)[this.constructor.CREATED_AT] !== void 0;
2195
+ }
2196
+ };
2197
+ var model_default = Model;
2198
+
2199
+ //#endregion
2200
+ //#region src/collection.ts
2201
+ var Collection$1 = class Collection$1 extends Collection {
2202
+ newConstructor(...args) {
2203
+ return new (this.getConstructor())(...args);
2204
+ }
2205
+ getConstructor() {
2206
+ return this.constructor;
2207
+ }
2208
+ async load(...relations) {
2209
+ if (this.isNotEmpty()) {
2210
+ const items = await this.first().constructor.query().with(...relations).eagerLoadRelations(this.items);
2211
+ return this.newConstructor(items);
2212
+ }
2213
+ return this;
2214
+ }
2215
+ async loadAggregate(relations, column, action = null) {
2216
+ if (this.isEmpty()) return this;
2217
+ const models = (await this.first().newModelQuery().whereIn(this.first().getKeyName(), this.modelKeys()).select(this.first().getKeyName()).withAggregate(relations, column, action).get()).keyBy(this.first().getKeyName());
2218
+ const attributes = diff(Object.keys(models.first().getAttributes()), [models.first().getKeyName()]);
2219
+ this.each((model) => {
2220
+ const extraAttributes = pick(models.get(model.getKey()).getAttributes(), attributes);
2221
+ model.fill(extraAttributes).syncOriginalAttributes(...attributes);
2222
+ });
2223
+ return this;
2224
+ }
2225
+ loadCount(relations) {
2226
+ return this.loadAggregate(relations, "*", "count");
2227
+ }
2228
+ loadMax(relation, column) {
2229
+ return this.loadAggregate(relation, column, "max");
2230
+ }
2231
+ loadMin(relation, column) {
2232
+ return this.loadAggregate(relation, column, "min");
2233
+ }
2234
+ loadSum(relation, column) {
2235
+ return this.loadAggregate(relation, column, "sum");
2236
+ }
2237
+ loadAvg(relation, column) {
2238
+ return this.loadAggregate(relation, column, "avg");
2239
+ }
2240
+ mapThen(callback) {
2241
+ return Promise.all(this.map(callback));
2242
+ }
2243
+ modelKeys() {
2244
+ return this.all().map((item) => item.getKey());
2245
+ }
2246
+ contains(key, operator, value) {
2247
+ if (arguments.length > 1) return super.contains(key, value ?? operator);
2248
+ if (key instanceof model_default) return super.contains((model) => {
2249
+ return model.is(key);
2250
+ });
2251
+ return super.contains((model) => {
2252
+ return model.getKey() == key;
2253
+ });
2254
+ }
2255
+ diff(items) {
2256
+ const diff$1 = new this.constructor();
2257
+ const dictionary = this.getDictionary(items);
2258
+ this.items.map((item) => {
2259
+ if (dictionary[item.getKey()] === void 0) diff$1.add(item);
2260
+ });
2261
+ return diff$1;
2262
+ }
2263
+ except(keys) {
2264
+ const dictionary = omit(this.getDictionary(), keys);
2265
+ return new this.constructor(Object.values(dictionary));
2266
+ }
2267
+ intersect(items) {
2268
+ const intersect = new this.constructor();
2269
+ if (isEmpty(items)) return intersect;
2270
+ const dictionary = this.getDictionary(items);
2271
+ for (const item of this.items) if (dictionary[item.getKey()] !== void 0) intersect.add(item);
2272
+ return intersect;
2273
+ }
2274
+ unique(key, _strict = false) {
2275
+ if (key) return super.unique(key);
2276
+ return new this.constructor(Object.values(this.getDictionary()));
2277
+ }
2278
+ find(key, defaultValue = null) {
2279
+ if (key instanceof model_default) key = key.getKey();
2280
+ if (isArray(key)) {
2281
+ if (this.isEmpty()) return new this.constructor();
2282
+ return this.whereIn(this.first().getKeyName(), key);
2283
+ }
2284
+ collect(this.items).first((model) => {
2285
+ return model.getKey() == key;
2286
+ });
2287
+ return this.items.filter((model) => {
2288
+ return model.getKey() == key;
2289
+ })[0] || defaultValue;
2290
+ }
2291
+ async fresh(...args) {
2292
+ if (this.isEmpty()) return new this.constructor();
2293
+ const model = this.first();
2294
+ const freshModels = (await model.newQuery().with(...args).whereIn(model.getKeyName(), this.modelKeys()).get()).getDictionary();
2295
+ return this.filter((model$1) => {
2296
+ return model$1.exists && freshModels[model$1.getKey()] !== void 0;
2297
+ }).map((model$1) => {
2298
+ return freshModels[model$1.getKey()];
2299
+ });
2300
+ }
2301
+ makeVisible(attributes) {
2302
+ return this.each((item) => {
2303
+ item.makeVisible(attributes);
2304
+ });
2305
+ }
2306
+ makeHidden(attributes) {
2307
+ return this.each((item) => {
2308
+ item.makeHidden(attributes);
2309
+ });
2310
+ }
2311
+ append(attributes) {
2312
+ return this.each((item) => {
2313
+ item.append(attributes);
2314
+ });
2315
+ }
2316
+ only(keys) {
2317
+ if (keys === null) return new Collection$1(this.items);
2318
+ const dictionary = pick(this.getDictionary(), keys);
2319
+ return new this.constructor(Object.values(dictionary));
2320
+ }
2321
+ getDictionary(items) {
2322
+ items = !items ? this.items : items;
2323
+ const dictionary = {};
2324
+ items.map((value) => {
2325
+ dictionary[value.getKey()] = value;
2326
+ });
2327
+ return dictionary;
2328
+ }
2329
+ toQuery() {
2330
+ const model = this.first();
2331
+ if (!model) throw new Error("Unable to create query for empty collection.");
2332
+ const modelName = model.constructor.name;
2333
+ if (this.filter((model$1) => {
2334
+ return !(model$1 instanceof modelName);
2335
+ }).isNotEmpty()) throw new Error("Unable to create query for collection with mixed types.");
2336
+ return model.newModelQuery().whereKey(this.modelKeys());
2337
+ }
2338
+ toData() {
2339
+ return this.all().map((item) => typeof item.toData == "function" ? item.toData() : item);
2340
+ }
2341
+ toJSON() {
2342
+ return this.toData();
2343
+ }
2344
+ toJson(...args) {
2345
+ return JSON.stringify(this.toData(), ...args);
2346
+ }
2347
+ [Symbol.iterator] = () => {
2348
+ const items = this.items;
2349
+ const length = this.items.length;
2350
+ let n = 0;
2351
+ return { next() {
2352
+ return n < length ? {
2353
+ value: items[n++],
2354
+ done: false
2355
+ } : { done: true };
2356
+ } };
2357
+ };
2358
+ };
2359
+ var collection_default = Collection$1;
2360
+
2361
+ //#endregion
2362
+ //#region src/relations/concerns/interacts-with-pivot-table.ts
2363
+ const InteractsWithPivotTable = (Relation$1) => {
2364
+ return class extends Relation$1 {
2365
+ newExistingPivot(attributes = []) {
2366
+ return this.newPivot(attributes, true);
2367
+ }
2368
+ newPivot(attributes = [], exists = false) {
2369
+ return this.related.newPivot(this.parent, attributes, this.getTable(), exists, this.using).setPivotKeys(this.foreignPivotKey, this.relatedPivotKey);
2370
+ }
2371
+ async attach(id, attributes = {}, _touch = true) {
2372
+ if (this.using) await this.attachUsingCustomClass(id, attributes);
2373
+ else await this.newPivotStatement().insert(this.formatAttachRecords(this.parseIds(id), attributes));
2374
+ }
2375
+ async detach(ids, _touch = true) {
2376
+ let results;
2377
+ if (this.using && ids !== null && this.pivotWheres.length == 0 && this.pivotWhereIns.length == 0 && this.pivotWhereNulls.length == 0) results = await this.detachUsingCustomClass(ids);
2378
+ else {
2379
+ const query = this.newPivotQuery();
2380
+ if (ids !== null) {
2381
+ ids = this.parseIds(ids);
2382
+ if (ids.length == 0) return 0;
2383
+ query.whereIn(this.getQualifiedRelatedPivotKeyName(), ids);
2384
+ }
2385
+ results = await query.delete();
2386
+ }
2387
+ return results;
2388
+ }
2389
+ async sync(ids, detaching = true) {
2390
+ let changes = {
2391
+ attached: [],
2392
+ detached: [],
2393
+ updated: []
2394
+ };
2395
+ let records;
2396
+ const results = await this.getCurrentlyAttachedPivots();
2397
+ const current = results.length === 0 ? [] : results.map((result) => result.toData()).pluck(this.relatedPivotKey).all().map((i) => String(i));
2398
+ const detach = diff(current, Object.keys(records = this.formatRecordsList(this.parseIds(ids))));
2399
+ if (detaching && detach.length > 0) {
2400
+ await this.detach(detach);
2401
+ changes.detached = this.castKeys(detach);
2402
+ }
2403
+ changes = assign(changes, await this.attachNew(records, current, false));
2404
+ return changes;
2405
+ }
2406
+ syncWithoutDetaching(ids) {
2407
+ return this.sync(ids, false);
2408
+ }
2409
+ syncWithPivotValues(ids, values, detaching = true) {
2410
+ return this.sync(collect(this.parseIds(ids)).mapWithKeys((id) => {
2411
+ return [id, values];
2412
+ }), detaching);
2413
+ }
2414
+ withPivot(columns) {
2415
+ this.pivotColumns = this.pivotColumns.concat(isArray(columns) ? columns : Array.prototype.slice.call(columns));
2416
+ return this;
2417
+ }
2418
+ async attachNew(records, current, touch = true) {
2419
+ const changes = {
2420
+ attached: [],
2421
+ updated: []
2422
+ };
2423
+ for (const id in records) {
2424
+ const attributes = records[id];
2425
+ if (!current.includes(id)) {
2426
+ await this.attach(id, attributes, touch);
2427
+ changes.attached.push(this.castKey(id));
2428
+ } else if (Object.keys(attributes).length > 0 && await this.updateExistingPivot(id, attributes, touch)) changes.updated.push(this.castKey(id));
2429
+ }
2430
+ return changes;
2431
+ }
2432
+ async updateExistingPivot(id, attributes, touch = true) {
2433
+ if (this.using && this.pivotWheres.length > 0 && this.pivotWhereInspivotWheres.length > 0 && this.pivotWhereNullspivotWheres.length > 0) return await this.updateExistingPivotUsingCustomClass(id, attributes, touch);
2434
+ if (this.hasPivotColumn(this.updatedAt())) attributes = this.addTimestampsToAttachment(attributes, true);
2435
+ return this.newPivotStatementForId(this.parseId(id)).update(this.castAttributes(attributes));
2436
+ }
2437
+ addTimestampsToAttachment(record, exists = false) {
2438
+ let fresh = this.parent.freshTimestamp();
2439
+ if (this.using) fresh = new this.using().fromDateTime(fresh);
2440
+ if (!exists && this.hasPivotColumn(this.createdAt())) record[this.createdAt()] = fresh;
2441
+ if (this.hasPivotColumn(this.updatedAt())) record[this.updatedAt()] = fresh;
2442
+ return record;
2443
+ }
2444
+ async updateExistingPivotUsingCustomClass(id, attributes, _touch) {
2445
+ const pivot = await this.getCurrentlyAttachedPivots().where(this.foreignPivotKey, this.parent[this.parentKey]).where(this.relatedPivotKey, this.parseId(id)).first();
2446
+ const updated = pivot ? pivot.fill(attributes).isDirty() : false;
2447
+ if (updated) await pivot.save();
2448
+ return parseInt(updated);
2449
+ }
2450
+ formatRecordsList(records) {
2451
+ return collect(records).mapWithKeys((attributes, id) => {
2452
+ if (!isArray(attributes)) [id, attributes] = [attributes, {}];
2453
+ return [id, attributes];
2454
+ }).all();
2455
+ }
2456
+ async getCurrentlyAttachedPivots() {
2457
+ return (await this.newPivotQuery().get()).map((record) => {
2458
+ return (this.using || Pivot).fromRawAttributes(this.parent, record, this.getTable(), true).setPivotKeys(this.foreignPivotKey, this.relatedPivotKey);
2459
+ });
2460
+ }
2461
+ castKeys(keys) {
2462
+ return keys.map((v) => {
2463
+ return this.castKey(v);
2464
+ });
2465
+ }
2466
+ castKey(key) {
2467
+ return this.getTypeSwapValue(this.related.getKeyType(), key);
2468
+ }
2469
+ getTypeSwapValue(type, value) {
2470
+ switch (type.toLowerCase()) {
2471
+ case "int":
2472
+ case "integer": return parseInt(value);
2473
+ case "real":
2474
+ case "float":
2475
+ case "double": return parseFloat(value);
2476
+ case "string": return String(value);
2477
+ default: return value;
2478
+ }
2479
+ }
2480
+ newPivotQuery() {
2481
+ const query = this.newPivotStatement();
2482
+ this.pivotWheres.map((args) => {
2483
+ query.where(...args);
2484
+ });
2485
+ this.pivotWhereIns.map((args) => {
2486
+ query.whereIn(...args);
2487
+ });
2488
+ this.pivotWhereNulls.map((args) => {
2489
+ query.whereNull(...args);
2490
+ });
2491
+ return query.where(this.getQualifiedForeignPivotKeyName(), this.parent[this.parentKey]);
2492
+ }
2493
+ async detachUsingCustomClass(ids) {
2494
+ let results = 0;
2495
+ for (const id in this.parseIds(ids)) results += await this.newPivot({
2496
+ [this.foreignPivotKey]: this.parent[this.parentKey],
2497
+ [this.relatedPivotKey]: id
2498
+ }, true).delete();
2499
+ return results;
2500
+ }
2501
+ newPivotStatement() {
2502
+ const builder = this.parent.newQuery();
2503
+ builder.setTable(this.table);
2504
+ return builder;
2505
+ }
2506
+ async attachUsingCustomClass(id, attributes) {
2507
+ const records = this.formatAttachRecords(this.parseIds(id), attributes);
2508
+ await Promise.all(records.map(async (record) => {
2509
+ await this.newPivot(record, false).save();
2510
+ }));
2511
+ }
2512
+ formatAttachRecords(ids, attributes) {
2513
+ const records = [];
2514
+ const hasTimestamps = this.hasPivotColumn(this.createdAt()) || this.hasPivotColumn(this.updatedAt());
2515
+ for (const key in ids) {
2516
+ const value = ids[key];
2517
+ records.push(this.formatAttachRecord(key, value, attributes, hasTimestamps));
2518
+ }
2519
+ return records;
2520
+ }
2521
+ formatAttachRecord(key, value, attributes, hasTimestamps) {
2522
+ const [id, newAttributes] = this.extractAttachIdAndAttributes(key, value, attributes);
2523
+ return assign(this.baseAttachRecord(id, hasTimestamps), newAttributes);
2524
+ }
2525
+ baseAttachRecord(id, timed) {
2526
+ let record = {};
2527
+ record[this.relatedPivotKey] = id;
2528
+ record[this.foreignPivotKey] = this.parent[this.parentKey];
2529
+ if (timed) record = this.addTimestampsToAttachment(record);
2530
+ this.pivotValues.map((value) => {
2531
+ record[value.column] = value.value;
2532
+ });
2533
+ return record;
2534
+ }
2535
+ extractAttachIdAndAttributes(key, value, newAttributes) {
2536
+ return isArray(value) ? [key, {
2537
+ ...value,
2538
+ ...newAttributes
2539
+ }] : [value, newAttributes];
2540
+ }
2541
+ hasPivotColumn(column) {
2542
+ return this.pivotColumns.includes(column);
2543
+ }
2544
+ parseIds(value) {
2545
+ if (value instanceof Model) return [value[this.relatedKey]];
2546
+ if (value instanceof collection_default) return value.pluck(this.relatedKey).all();
2547
+ return isArray(value) ? value : [value];
2548
+ }
2549
+ };
2550
+ };
2551
+ var interacts_with_pivot_table_default = InteractsWithPivotTable;
2552
+
2553
+ //#endregion
2554
+ //#region src/relations/belongs-to-many.ts
2555
+ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot_table_default) {
2556
+ table;
2557
+ foreignPivotKey;
2558
+ relatedPivotKey;
2559
+ parentKey;
2560
+ relatedKey;
2561
+ pivotColumns = [];
2562
+ pivotValues = [];
2563
+ pivotWheres = [];
2564
+ pivotWhereIns = [];
2565
+ pivotWhereNulls = [];
2566
+ accessor = "pivot";
2567
+ using;
2568
+ pivotCreatedAt;
2569
+ pivotUpdatedAt;
2570
+ constructor(query, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
2571
+ super(query, parent);
2572
+ this.table = table;
2573
+ this.foreignPivotKey = foreignPivotKey;
2574
+ this.relatedPivotKey = relatedPivotKey;
2575
+ this.parentKey = parentKey;
2576
+ this.relatedKey = relatedKey;
2577
+ this.addConstraints();
2578
+ return this.asProxy();
2579
+ }
2580
+ initRelation(models, relation) {
2581
+ models.map((model) => {
2582
+ model.setRelation(relation, new collection_default([]));
2583
+ });
2584
+ return models;
2585
+ }
2586
+ addConstraints() {
2587
+ this.performJoin();
2588
+ if (this.constructor.constraints) this.addWhereConstraints();
2589
+ }
2590
+ performJoin(query = null) {
2591
+ query = query || this.query;
2592
+ query.join(this.getTable(), this.getQualifiedRelatedKeyName(), "=", this.qualifyPivotColumn(this.relatedPivotKey));
2593
+ return this;
2594
+ }
2595
+ getTable() {
2596
+ return this.table;
2597
+ }
2598
+ getQualifiedRelatedKeyName() {
2599
+ return this.related.qualifyColumn(this.relatedKey);
2600
+ }
2601
+ async getResults() {
2602
+ return this.parent[this.parentKey] !== null ? await this.get() : new collection_default([]);
2603
+ }
2604
+ addWhereConstraints() {
2605
+ this.query.where(this.getQualifiedForeignPivotKeyName(), "=", this.parent[this.parentKey]);
2606
+ return this;
2607
+ }
2608
+ async get(columns) {
2609
+ var _builder$query;
2610
+ const builder = this.query.applyScopes();
2611
+ columns = ((_builder$query = builder.query) === null || _builder$query === void 0 || (_builder$query = _builder$query._statements) === null || _builder$query === void 0 ? void 0 : _builder$query.find((item) => item.grouping == "columns")) ? [] : columns;
2612
+ let models = await builder.select(this.shouldSelect(columns)).getModels();
2613
+ this.hydratePivotRelation(models);
2614
+ if (models.length > 0) models = await builder.eagerLoadRelations(models);
2615
+ return new collection_default(models);
2616
+ }
2617
+ async first(columns = ["*"]) {
2618
+ const results = await this.take(1).get(columns);
2619
+ return results.count() > 0 ? results.first() : null;
2620
+ }
2621
+ async firstOrFail(columns = ["*"]) {
2622
+ const model = await this.first(columns);
2623
+ if (model !== null) return model;
2624
+ throw new ModelNotFoundError().setModel(this.related.constructor);
2625
+ }
2626
+ async paginate(page = 1, perPage = 15, columns = ["*"]) {
2627
+ this.query.select(this.shouldSelect(columns));
2628
+ return tap(await this.query.paginate(page, perPage), (paginator) => {
2629
+ this.hydratePivotRelation(paginator.items());
2630
+ });
2631
+ }
2632
+ async chunk(count, callback) {
2633
+ return await this.prepareQueryBuilder().chunk(count, async (results, page) => {
2634
+ this.hydratePivotRelation(results.all());
2635
+ return await callback(results, page);
2636
+ });
2637
+ }
2638
+ setUsing(model) {
2639
+ this.using = model;
2640
+ return this;
2641
+ }
2642
+ as(accessor) {
2643
+ this.accessor = accessor;
2644
+ return this;
2645
+ }
2646
+ prepareQueryBuilder() {
2647
+ return this.query.select(this.shouldSelect());
2648
+ }
2649
+ hydratePivotRelation(models) {
2650
+ models.map((model) => {
2651
+ model.setRelation(this.accessor, this.newExistingPivot(this.migratePivotAttributes(model)));
2652
+ });
2653
+ }
2654
+ migratePivotAttributes(model) {
2655
+ const values = {};
2656
+ for (const key in model.attributes) {
2657
+ const value = model.attributes[key];
2658
+ if (key.startsWith("pivot_")) {
2659
+ values[key.substring(6)] = value;
2660
+ model.attributes = omit(model.attributes, [key]);
2661
+ }
2662
+ }
2663
+ return values;
2664
+ }
2665
+ withTimestamps(createdAt = null, updatedAt = null) {
2666
+ this.pivotCreatedAt = createdAt;
2667
+ this.pivotUpdatedAt = updatedAt;
2668
+ return this.withPivot(this.createdAt(), this.updatedAt());
2669
+ }
2670
+ shouldSelect(columns = ["*"]) {
2671
+ if (isEqual(columns, ["*"])) columns = [this.related.getTable() + ".*"];
2672
+ return columns.concat(this.aliasedPivotColumns());
2673
+ }
2674
+ aliasedPivotColumns() {
2675
+ const defaults = [this.foreignPivotKey, this.relatedPivotKey];
2676
+ return collect(defaults.concat(this.pivotColumns)).map((column) => {
2677
+ return this.qualifyPivotColumn(column) + " as pivot_" + column;
2678
+ }).unique().all();
2679
+ }
2680
+ qualifyPivotColumn(column) {
2681
+ return column.includes(".") ? column : this.getTable() + "." + column;
2682
+ }
2683
+ match(models, results, relation) {
2684
+ const dictionary = this.buildDictionary(results);
2685
+ models.map((model) => {
2686
+ const key = model.getKey();
2687
+ if (dictionary[key] !== void 0) model.setRelation(relation, dictionary[key]);
2688
+ });
2689
+ return models;
2690
+ }
2691
+ buildDictionary(results) {
2692
+ const dictionary = {};
2693
+ results.map((result) => {
2694
+ const value = result[this.accessor][this.foreignPivotKey];
2695
+ if (dictionary[value] === void 0) dictionary[value] = new collection_default([]);
2696
+ dictionary[value].push(result);
2697
+ });
2698
+ return dictionary;
2699
+ }
2700
+ addEagerConstraints(models) {
2701
+ this.query.whereIn(this.getQualifiedForeignPivotKeyName(), this.getKeys(models, this.parentKey));
2702
+ }
2703
+ getQualifiedForeignPivotKeyName() {
2704
+ return this.qualifyPivotColumn(this.foreignPivotKey);
2705
+ }
2706
+ getQualifiedRelatedPivotKeyName() {
2707
+ return this.qualifyPivotColumn(this.relatedPivotKey);
2708
+ }
2709
+ wherePivot(column, operator = null, value = null, boolean = "and") {
2710
+ this.pivotWheres.push(Array.prototype.slice.call(arguments));
2711
+ return this.where(this.qualifyPivotColumn(column), operator, value, boolean);
2712
+ }
2713
+ wherePivotBetween(column, values, boolean = "and", not = false) {
2714
+ return this.whereBetween(this.qualifyPivotColumn(column), values, boolean, not);
2715
+ }
2716
+ orWherePivotBetween(column, values) {
2717
+ return this.wherePivotBetween(column, values, "or");
2718
+ }
2719
+ wherePivotNotBetween(column, values, boolean = "and") {
2720
+ return this.wherePivotBetween(column, values, boolean, true);
2721
+ }
2722
+ orWherePivotNotBetween(column, values) {
2723
+ return this.wherePivotBetween(column, values, "or", true);
2724
+ }
2725
+ wherePivotIn(column, values, boolean = "and", not = false) {
2726
+ return this.whereIn(this.qualifyPivotColumn(column), values, boolean, not);
2727
+ }
2728
+ orWherePivot(column, operator = null, value = null) {
2729
+ return this.wherePivot(column, operator, value, "or");
2730
+ }
2731
+ orWherePivotIn(column, values) {
2732
+ return this.wherePivotIn(column, values, "or");
2733
+ }
2734
+ wherePivotNotIn(column, values, boolean = "and") {
2735
+ return this.wherePivotIn(column, values, boolean, true);
2736
+ }
2737
+ orWherePivotNotIn(column, values) {
2738
+ return this.wherePivotNotIn(column, values, "or");
2739
+ }
2740
+ wherePivotNull(column, boolean = "and", not = false) {
2741
+ return this.whereNull(this.qualifyPivotColumn(column), boolean, not);
2742
+ }
2743
+ wherePivotNotNull(column, boolean = "and") {
2744
+ return this.wherePivotNull(column, boolean, true);
2745
+ }
2746
+ orWherePivotNull(column, not = false) {
2747
+ return this.wherePivotNull(column, "or", not);
2748
+ }
2749
+ orWherePivotNotNull(column) {
2750
+ return this.orWherePivotNull(column, true);
2751
+ }
2752
+ orderByPivot(column, direction = "asc") {
2753
+ return this.orderBy(this.qualifyPivotColumn(column), direction);
2754
+ }
2755
+ createdAt() {
2756
+ return this.pivotCreatedAt || this.parent.getCreatedAtColumn();
2757
+ }
2758
+ updatedAt() {
2759
+ return this.pivotUpdatedAt || this.parent.getUpdatedAtColumn();
2760
+ }
2761
+ getExistenceCompareKey() {
2762
+ return this.getQualifiedForeignPivotKeyName();
2763
+ }
2764
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
2765
+ if (parentQuery.getQuery()._single.table == query.getQuery()._single.table) return this.getRelationExistenceQueryForSelfJoin(query, parentQuery, columns);
2766
+ this.performJoin(query);
2767
+ return super.getRelationExistenceQuery(query, parentQuery, columns);
2768
+ }
2769
+ getRelationExistenceQueryForSelfJoin(query, parentQuery, columns = ["*"]) {
2770
+ const hash = this.getRelationCountHash();
2771
+ query.select(columns).from(this.related.getTable() + " as " + hash);
2772
+ this.related.setTable(hash);
2773
+ this.performJoin(query);
2774
+ return super.getRelationExistenceQuery(query, parentQuery, columns);
2775
+ }
2776
+ };
2777
+ var belongs_to_many_default = BelongsToMany;
2778
+
2779
+ //#endregion
2780
+ //#region src/builder.ts
2781
+ const Inference$1 = class {};
2782
+ var Builder = class Builder extends Inference$1 {
2783
+ query;
2784
+ connection;
2785
+ model;
2786
+ actions;
2787
+ localMacros = {};
2788
+ eagerLoad = {};
2789
+ globalScopes = {};
2790
+ onDeleteCallback;
2791
+ constructor(query) {
2792
+ super();
2793
+ this.query = query;
2794
+ return this.asProxy();
2795
+ }
2796
+ asProxy() {
2797
+ return new Proxy(this, { get(target, prop) {
2798
+ if (typeof target[prop] !== "undefined") return target[prop];
2799
+ if ([
2800
+ "select",
2801
+ "from",
2802
+ "where",
2803
+ "orWhere",
2804
+ "whereColumn",
2805
+ "whereRaw",
2806
+ "whereNot",
2807
+ "orWhereNot",
2808
+ "whereIn",
2809
+ "orWhereIn",
2810
+ "whereNotIn",
2811
+ "orWhereNotIn",
2812
+ "whereNull",
2813
+ "orWhereNull",
2814
+ "whereNotNull",
2815
+ "orWhereNotNull",
2816
+ "whereExists",
2817
+ "orWhereExists",
2818
+ "whereNotExists",
2819
+ "orWhereNotExists",
2820
+ "whereBetween",
2821
+ "orWhereBetween",
2822
+ "whereNotBetween",
2823
+ "orWhereNotBetween",
2824
+ "whereLike",
2825
+ "orWhereLike",
2826
+ "whereILike",
2827
+ "orWhereILike",
2828
+ "whereJsonObject",
2829
+ "whereJsonPath",
2830
+ "whereJsonSupersetOf",
2831
+ "whereJsonSubsetOf",
2832
+ "join",
2833
+ "joinRaw",
2834
+ "leftJoin",
2835
+ "leftOuterJoin",
2836
+ "rightJoin",
2837
+ "rightOuterJoin",
2838
+ "crossJoin",
2839
+ "transacting",
2840
+ "groupBy",
2841
+ "groupByRaw",
2842
+ "returning",
2843
+ "having",
2844
+ "havingRaw",
2845
+ "havingBetween",
2846
+ "limit",
2847
+ "offset",
2848
+ "orderBy",
2849
+ "orderByRaw",
2850
+ "union",
2851
+ "insert",
2852
+ "forUpdate",
2853
+ "forShare",
2854
+ "distinct",
2855
+ "clearOrder",
2856
+ "clear",
2857
+ "clearSelect",
2858
+ "clearWhere",
2859
+ "clearHaving",
2860
+ "clearGroup"
2861
+ ].includes(prop)) return (...args) => {
2862
+ target.query[prop](...args);
2863
+ return target.asProxy();
2864
+ };
2865
+ if ([
2866
+ "avg",
2867
+ "max",
2868
+ "min",
2869
+ "sum",
2870
+ "count"
2871
+ ].includes(prop)) return (column) => {
2872
+ const instance = target.asProxy();
2873
+ instance.applyScopes();
2874
+ column = !column && prop === "count" ? "*" : column;
2875
+ return instance.query[prop](column);
2876
+ };
2877
+ if (typeof prop === "string") {
2878
+ if (target.hasMacro(prop)) {
2879
+ const instance = target.asProxy();
2880
+ return (...args) => {
2881
+ return instance.localMacros[prop](instance, ...args);
2882
+ };
2883
+ }
2884
+ if (target.hasNamedScope(prop)) {
2885
+ const instance = target.asProxy();
2886
+ return (...args) => {
2887
+ instance.callNamedScope(prop, args);
2888
+ return instance;
2889
+ };
2890
+ }
2891
+ if (prop.startsWith("where")) {
2892
+ const column = snake(prop.substring(5));
2893
+ return (...args) => {
2894
+ target.query.where(column, ...args);
2895
+ return target.asProxy();
2896
+ };
2897
+ }
2898
+ }
2899
+ } });
2900
+ }
2901
+ orWhere(...args) {
2902
+ if (typeof args[0] === "function") {
2903
+ const callback = args[0];
2904
+ this.query.orWhere((query) => {
2905
+ this.query = query;
2906
+ callback(this);
2907
+ });
2908
+ return this;
2909
+ }
2910
+ this.query.orWhere(...args);
2911
+ return this;
2912
+ }
2913
+ async chunk(count, callback) {
2914
+ let page = 1;
2915
+ let countResults;
2916
+ do {
2917
+ this.enforceOrderBy();
2918
+ const results = await this.clone().forPage(page, count).get();
2919
+ countResults = results.count();
2920
+ if (countResults == 0) break;
2921
+ if (await callback(results, page) === false) return false;
2922
+ page++;
2923
+ } while (countResults === count);
2924
+ return true;
2925
+ }
2926
+ enforceOrderBy() {
2927
+ if (this.query._statements.filter((item) => item.grouping === "order").length === 0) this.orderBy(this.model.getQualifiedKeyName(), "asc");
2928
+ }
2929
+ clone() {
2930
+ const query = this.query.clone();
2931
+ const builder = new this.constructor(query);
2932
+ builder.connection = this.connection;
2933
+ builder.setModel(this.model);
2934
+ builder.globalScopes = { ...this.globalScopes };
2935
+ builder.localMacros = { ...this.localMacros };
2936
+ builder.eagerLoad = { ...this.eagerLoad };
2937
+ return builder;
2938
+ }
2939
+ forPage(page, perPage = 15) {
2940
+ return this.offset((page - 1) * perPage).limit(perPage);
2941
+ }
2942
+ insert(...args) {
2943
+ return this.query.insert(...args);
2944
+ }
2945
+ update(values) {
2946
+ this.applyScopes();
2947
+ return this.query.update(this.addUpdatedAtColumn(values));
2948
+ }
2949
+ increment(column, amount = 1, extra = {}) {
2950
+ this.applyScopes();
2951
+ const db = this.model.getConnection();
2952
+ return this.query.update(this.addUpdatedAtColumn({
2953
+ ...extra,
2954
+ [column]: db.raw(`${column} + ${amount}`)
2955
+ }));
2956
+ }
2957
+ decrement(column, amount = 1, extra = {}) {
2958
+ this.applyScopes();
2959
+ const db = this.model.getConnection();
2960
+ return this.query.update(this.addUpdatedAtColumn({
2961
+ ...extra,
2962
+ [column]: db.raw(`${column} - ${amount}`)
2963
+ }));
2964
+ }
2965
+ addUpdatedAtColumn(values) {
2966
+ if (!this.model.usesTimestamps() || this.model.getUpdatedAtColumn() === null) return values;
2967
+ const column = this.model.getUpdatedAtColumn();
2968
+ values = assign({ [column]: this.model.freshTimestampString() }, values);
2969
+ return values;
2970
+ }
2971
+ delete() {
2972
+ if (this.onDeleteCallback) return this.onDeleteCallback(this);
2973
+ return this.query.delete();
2974
+ }
2975
+ onDelete(callback) {
2976
+ this.onDeleteCallback = callback;
2977
+ }
2978
+ forceDelete() {
2979
+ return this.query.delete();
2980
+ }
2981
+ async create(attributes = {}) {
2982
+ return await tap(this.newModelInstance(attributes), async (instance) => {
2983
+ await instance.save({ client: this.query });
2984
+ });
2985
+ }
2986
+ newModelInstance(attributes = {}) {
2987
+ return this.model.newInstance(attributes).setConnection(this.model.getConnectionName());
2988
+ }
2989
+ getQuery() {
2990
+ return this.query;
2991
+ }
2992
+ getModel() {
2993
+ return this.model;
2994
+ }
2995
+ setModel(model) {
2996
+ var _this$query;
2997
+ this.model = model;
2998
+ if (typeof ((_this$query = this.query) === null || _this$query === void 0 || (_this$query = _this$query.client) === null || _this$query === void 0 ? void 0 : _this$query.table) == "function") this.query = this.query.client.table(this.model.getTable());
2999
+ else this.query = this.query.table(this.model.getTable());
3000
+ return this;
3001
+ }
3002
+ qualifyColumn(column) {
3003
+ return this.model.qualifyColumn(column);
3004
+ }
3005
+ setTable(table) {
3006
+ this.query = this.query.table(table);
3007
+ return this;
3008
+ }
3009
+ applyScopes() {
3010
+ if (!this.globalScopes) return this;
3011
+ for (const identifier in this.globalScopes) {
3012
+ const scope = this.globalScopes[identifier];
3013
+ if (scope instanceof scope_default) scope.apply(this, this.getModel());
3014
+ else scope(this);
3015
+ }
3016
+ return this;
3017
+ }
3018
+ hasNamedScope(name) {
3019
+ return this.model && this.model.hasNamedScope(name);
3020
+ }
3021
+ callNamedScope(scope, parameters) {
3022
+ return this.model.callNamedScope(scope, [this, ...parameters]);
3023
+ }
3024
+ callScope(scope, parameters = []) {
3025
+ return scope(this, ...parameters) || this;
3026
+ }
3027
+ scopes(scopes) {
3028
+ scopes.map((scopeName) => {
3029
+ const scopeMethod = getScopeMethod(scopeName);
3030
+ if (typeof this.model[scopeMethod] === "function") this.globalScopes[scopeName] = this.model[scopeMethod];
3031
+ });
3032
+ return this;
3033
+ }
3034
+ withGlobalScope(identifier, scope) {
3035
+ this.globalScopes[identifier] = scope;
3036
+ if (typeof scope.extend === "function") scope.extend(this);
3037
+ return this;
3038
+ }
3039
+ withoutGlobalScope(scope) {
3040
+ if (typeof scope !== "string") scope = scope.constructor.name;
3041
+ this.globalScopes = omit(this.globalScopes, [scope]);
3042
+ return this;
3043
+ }
3044
+ macro(name, callback) {
3045
+ this.localMacros[name] = callback;
3046
+ return this;
3047
+ }
3048
+ hasMacro(name) {
3049
+ return name in this.localMacros;
3050
+ }
3051
+ getMacro(name) {
3052
+ return this.localMacros[name];
3053
+ }
3054
+ with(...args) {
3055
+ let eagerLoads = {};
3056
+ if (typeof args[1] === "function") {
3057
+ const eagerLoad = this.parseWithRelations({ [args[0]]: args[1] });
3058
+ this.eagerLoad = assign(this.eagerLoad, eagerLoad);
3059
+ return this;
3060
+ }
3061
+ const relations = flattenDeep(args);
3062
+ if (relations.length === 0) return this;
3063
+ for (const relation of relations) {
3064
+ let eagerLoad;
3065
+ if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
3066
+ else if (typeof relation === "object") eagerLoad = relation;
3067
+ eagerLoads = assign(eagerLoads, eagerLoad);
3068
+ }
3069
+ this.eagerLoad = assign(this.eagerLoad, this.parseWithRelations(eagerLoads));
3070
+ return this;
3071
+ }
3072
+ has(relation, operator = ">=", count = 1, boolean = "and", callback = null) {
3073
+ if (isString(relation)) {
3074
+ if (relation.includes(".")) return this.hasNested(relation, operator, count, boolean, callback);
3075
+ relation = this.getRelationWithoutConstraints(getRelationMethod(relation));
3076
+ }
3077
+ const method = this.canUseExistsForExistenceCheck(operator, count) ? "getRelationExistenceQuery" : "getRelationExistenceCountQuery";
3078
+ const hasQuery = relation[method](relation.getRelated().newModelQuery(), this);
3079
+ if (callback) callback(hasQuery);
3080
+ return this.addHasWhere(hasQuery, relation, operator, count, boolean);
3081
+ }
3082
+ orHas(relation, operator = ">=", count = 1) {
3083
+ return this.has(relation, operator, count, "or");
3084
+ }
3085
+ doesntHave(relation, boolean = "and", callback = null) {
3086
+ return this.has(relation, "<", 1, boolean, callback);
3087
+ }
3088
+ orDoesntHave(relation) {
3089
+ return this.doesntHave(relation, "or");
3090
+ }
3091
+ whereHas(relation, callback = null, operator = ">=", count = 1) {
3092
+ return this.has(relation, operator, count, "and", callback);
3093
+ }
3094
+ orWhereHas(relation, callback = null, operator = ">=", count = 1) {
3095
+ return this.has(relation, operator, count, "or", callback);
3096
+ }
3097
+ whereRelation(relation, ...args) {
3098
+ const column = args.shift();
3099
+ return this.whereHas(relation, (query) => {
3100
+ if (typeof column === "function") column(query);
3101
+ else query.where(column, ...args);
3102
+ });
3103
+ }
3104
+ orWhereRelation(relation, ...args) {
3105
+ const column = args.shift();
3106
+ return this.orWhereHas(relation, function(query) {
3107
+ if (typeof column === "function") column(query);
3108
+ else query.where(column, ...args);
3109
+ });
3110
+ }
3111
+ hasNested(relations, operator = ">=", count = 1, boolean = "and", callback = null) {
3112
+ relations = relations.split(".");
3113
+ const doesntHave = operator === "<" && count === 1;
3114
+ if (doesntHave) {
3115
+ operator = ">=";
3116
+ count = 1;
3117
+ }
3118
+ const closure = (q) => {
3119
+ if (relations.length > 1) q.whereHas(relations.shift(), closure);
3120
+ else q.has(relations.shift(), operator, count, "and", callback);
3121
+ return null;
3122
+ };
3123
+ return this.has(relations.shift(), doesntHave ? "<" : ">=", 1, boolean, closure);
3124
+ }
3125
+ canUseExistsForExistenceCheck(operator, count) {
3126
+ return (operator === ">=" || operator === "<") && count === 1;
3127
+ }
3128
+ addHasWhere(hasQuery, relation, operator, count, boolean) {
3129
+ hasQuery.mergeConstraintsFrom(relation.getQuery());
3130
+ return this.canUseExistsForExistenceCheck(operator, count) ? this.addWhereExistsQuery(hasQuery.getQuery(), boolean, operator === "<" && count === 1) : this.addWhereCountQuery(hasQuery.getQuery(), operator, count, boolean);
3131
+ }
3132
+ addWhereExistsQuery(query, boolean = "and", not = false) {
3133
+ const type = not ? "NotExists" : "Exists";
3134
+ const method = boolean === "and" ? "where" + type : "orWhere" + type;
3135
+ this[method](query.connector);
3136
+ return this;
3137
+ }
3138
+ addWhereCountQuery(query, operator = ">=", count = 1, boolean = "and") {
3139
+ const db = this.model.getConnection();
3140
+ return this.where(db.raw("(" + query.toSQL().sql + ")"), operator, typeof count === "number" ? db.raw(count) : count, boolean);
3141
+ }
3142
+ withAggregate(relations, column, action = null) {
3143
+ if (relations.length === 0) return this;
3144
+ relations = flattenDeep([relations]);
3145
+ let eagerLoads = {};
3146
+ for (const relation of relations) {
3147
+ let eagerLoad;
3148
+ if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
3149
+ else if (typeof relation === "object") eagerLoad = relation;
3150
+ eagerLoads = assign(eagerLoads, eagerLoad);
3151
+ }
3152
+ relations = eagerLoads;
3153
+ const db = this.model.getConnection();
3154
+ if (this.query._statements.filter((item) => item.grouping == "columns").map((item) => item.value).flat().length === 0) this.query.select([this.query._single.table + ".*"]);
3155
+ const parses = this.parseWithRelations(relations);
3156
+ for (let name in parses) {
3157
+ const constraints = parses[name];
3158
+ const segments = name.split(" ");
3159
+ let alias, expression;
3160
+ if (segments.length === 3 && segments[1].toLocaleLowerCase() === "as") [name, alias] = [segments[0], segments[2]];
3161
+ const relation = this.getRelationWithoutConstraints(getRelationMethod(name));
3162
+ if (action) {
3163
+ const hashedColumn = this.query._single.table === relation.query.query._single.table ? `${relation.getRelationCountHash(false)}.${column}` : column;
3164
+ const wrappedColumn = column === "*" ? column : relation.getRelated().qualifyColumn(hashedColumn);
3165
+ expression = action === "exists" ? wrappedColumn : `${action}(${wrappedColumn})`;
3166
+ } else expression = column;
3167
+ const query = relation.getRelationExistenceQuery(relation.getRelated().newModelQuery(), this, db.raw(expression));
3168
+ constraints(query);
3169
+ alias = alias || snake(`${name} ${action} ${column}`.replace("/[^[:alnum:][:space:]_]/u", ""));
3170
+ if (action === "exists") this.select(db.raw(`exists(${query.toSql().sql}) as ${alias}`));
3171
+ else this.selectSub(action ? query : query.limit(1), alias);
3172
+ }
3173
+ return this;
3174
+ }
3175
+ toSql() {
3176
+ const query = this.clone();
3177
+ query.applyScopes();
3178
+ return query.query.toSQL();
3179
+ }
3180
+ mergeConstraintsFrom(_from) {
3181
+ return this;
3182
+ }
3183
+ selectSub(query, as) {
3184
+ const [querySub, bindings] = this.createSub(query);
3185
+ const db = this.model.getConnection();
3186
+ return this.select(db.raw("(" + querySub + ") as " + as, bindings));
3187
+ }
3188
+ createSub(query) {
3189
+ return this.parseSub(query);
3190
+ }
3191
+ parseSub(query) {
3192
+ if (query instanceof Builder || query instanceof relation_default) return [query.toSql().sql, query.toSql().bindings];
3193
+ else if (isString(query)) return [query, []];
3194
+ else throw new Error("A subquery must be a query builder instance, a Closure, or a string.");
3195
+ }
3196
+ prependDatabaseNameIfCrossDatabaseQuery(query) {
3197
+ if (query.query._single.table !== this.query._single.table) {
3198
+ const databaseName = query.query._single.table;
3199
+ if (!query.query._single.table.startsWith(databaseName) && !query.query._single.table.contains(".")) query.from(databaseName + "." + query.from);
3200
+ }
3201
+ return query;
3202
+ }
3203
+ getRelationWithoutConstraints(relation) {
3204
+ return relation_default.noConstraints(() => {
3205
+ return this.getModel()[relation]();
3206
+ });
3207
+ }
3208
+ withCount(...args) {
3209
+ return this.withAggregate(flattenDeep(args), "*", "count");
3210
+ }
3211
+ withMax(relation, column) {
3212
+ return this.withAggregate(relation, column, "max");
3213
+ }
3214
+ withMin(relation, column) {
3215
+ return this.withAggregate(relation, column, "min");
3216
+ }
3217
+ withAvg(relation, column) {
3218
+ return this.withAggregate(relation, column, "avg");
3219
+ }
3220
+ withSum(relation, column) {
3221
+ return this.withAggregate(relation, column, "sum");
3222
+ }
3223
+ withExists(relation) {
3224
+ return this.withAggregate(relation, "*", "exists");
3225
+ }
3226
+ parseWithRelations(relations) {
3227
+ if (relations.length === 0) return [];
3228
+ let results = {};
3229
+ const constraintsMap = this.prepareNestedWithRelationships(relations);
3230
+ for (const name in constraintsMap) {
3231
+ results = this.addNestedWiths(name, results);
3232
+ results[name] = constraintsMap[name];
3233
+ }
3234
+ return results;
3235
+ }
3236
+ addNestedWiths(name, results) {
3237
+ const progress = [];
3238
+ name.split(".").map((segment) => {
3239
+ progress.push(segment);
3240
+ const last = progress.join(".");
3241
+ if (results[last] === void 0) results[last] = () => {};
3242
+ });
3243
+ return results;
3244
+ }
3245
+ prepareNestedWithRelationships(relations, prefix = "") {
3246
+ let preparedRelationships = {};
3247
+ if (prefix !== "") prefix += ".";
3248
+ for (const key in relations) {
3249
+ const value = relations[key];
3250
+ if (isString(value) || Number.isFinite(parseInt(value))) continue;
3251
+ const [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(key, value);
3252
+ preparedRelationships = Object.assign({}, preparedRelationships, { [`${prefix}${attribute}`]: attributeSelectConstraint }, this.prepareNestedWithRelationships(value, `${prefix}${attribute}`));
3253
+ relations = omit(relations, [key]);
3254
+ }
3255
+ for (const key in relations) {
3256
+ const value = relations[key];
3257
+ let attribute = key, attributeSelectConstraint = value;
3258
+ if (isString(value)) [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(value);
3259
+ preparedRelationships[`${prefix}${attribute}`] = this.combineConstraints([attributeSelectConstraint, preparedRelationships[`${prefix}${attribute}`] || (() => {})]);
3260
+ }
3261
+ return preparedRelationships;
3262
+ }
3263
+ combineConstraints(constraints) {
3264
+ return (builder) => {
3265
+ constraints.map((constraint) => {
3266
+ builder = constraint(builder) || builder;
3267
+ });
3268
+ return builder;
3269
+ };
3270
+ }
3271
+ parseNameAndAttributeSelectionConstraint(name, value) {
3272
+ return name.includes(":") ? this.createSelectWithConstraint(name) : [name, value];
3273
+ }
3274
+ createSelectWithConstraint(name) {
3275
+ return [name.split(":")[0], (query) => {
3276
+ query.select(name.split(":")[1].split(",").map((column) => {
3277
+ if (column.includes(".")) return column;
3278
+ return query instanceof belongs_to_many_default ? query.related.getTable() + "." + column : column;
3279
+ }));
3280
+ }];
3281
+ }
3282
+ related(relation) {
3283
+ if (typeof this.model[getRelationMethod(relation)] !== "function") {
3284
+ const message = `Model [${this.model.constructor.name}]'s relation [${relation}] doesn't exist.`;
3285
+ throw new RelationNotFoundError(message);
3286
+ }
3287
+ return this.model[getRelationMethod(relation)]();
3288
+ }
3289
+ take(...args) {
3290
+ return this.limit(...args);
3291
+ }
3292
+ skip(...args) {
3293
+ return this.offset(...args);
3294
+ }
3295
+ async first(...columns) {
3296
+ this.applyScopes();
3297
+ this.limit(1);
3298
+ let models = await this.getModels(columns);
3299
+ if (models.length > 0) models = await this.eagerLoadRelations(models);
3300
+ return models[0] || null;
3301
+ }
3302
+ async firstOrFail(...columns) {
3303
+ const data = await this.first(...columns);
3304
+ if (data === null) throw new ModelNotFoundError().setModel(this.model.constructor.name);
3305
+ return data;
3306
+ }
3307
+ async findOrFail(...args) {
3308
+ const data = await this.find(...args);
3309
+ if (isArray(args[0])) {
3310
+ if (data.count() !== args[0].length) throw new ModelNotFoundError().setModel(this.model.constructor.name, diff(args[0], data.modelKeys()));
3311
+ return data;
3312
+ }
3313
+ if (data === null) throw new ModelNotFoundError().setModel(this.model.constructor.name, args[0]);
3314
+ return data;
3315
+ }
3316
+ async findOrNew(id, columns = ["*"]) {
3317
+ const model = await this.find(id, columns);
3318
+ if (model !== null) return model;
3319
+ return this.newModelInstance();
3320
+ }
3321
+ async firstOrNew(attributes = {}, values = {}) {
3322
+ const instance = await this.where(attributes).first();
3323
+ if (instance !== null) return instance;
3324
+ return this.newModelInstance(assign(attributes, values));
3325
+ }
3326
+ async firstOrCreate(attributes = {}, values = {}) {
3327
+ const instance = await this.where(attributes).first();
3328
+ if (instance !== null) return instance;
3329
+ return tap(this.newModelInstance(assign(attributes, values)), async (instance$1) => {
3330
+ await instance$1.save({ client: this.query });
3331
+ });
3332
+ }
3333
+ async updateOrCreate(attributes, values = {}) {
3334
+ return await tap(await this.firstOrNew(attributes), async (instance) => {
3335
+ await instance.fill(values).save({ client: this.query });
3336
+ });
3337
+ }
3338
+ latest(column = "id") {
3339
+ if (column === null) column = this.model.getCreatedAtColumn() || "created_at";
3340
+ this.query.orderBy(column, "desc");
3341
+ return this;
3342
+ }
3343
+ oldest(column = "id") {
3344
+ if (column === null) column = this.model.getCreatedAtColumn() || "created_at";
3345
+ this.query.orderBy(column, "asc");
3346
+ return this;
3347
+ }
3348
+ async find(id, columns) {
3349
+ if (isArray(id) || id instanceof collection_default) return await this.findMany(id, columns);
3350
+ return await this.where(this.model.getKeyName(), id).first(columns);
3351
+ }
3352
+ async findMany(ids, columns = ["*"]) {
3353
+ if (ids instanceof collection_default) ids = ids.modelKeys();
3354
+ ids = isArray(ids) ? ids : [ids];
3355
+ if (ids.length === 0) return new collection_default([]);
3356
+ return await this.whereIn(this.model.getKeyName(), ids).get(columns);
3357
+ }
3358
+ async pluck(column) {
3359
+ const data = await this.query.pluck(column);
3360
+ return new collection_default(data);
3361
+ }
3362
+ async destroy(ids) {
3363
+ if (ids instanceof collection_default) ids = ids.modelKeys();
3364
+ if (ids instanceof Collection) ids = ids.all();
3365
+ ids = isArray(ids) ? ids : Array.prototype.slice.call(ids);
3366
+ if (ids.length === 0) return 0;
3367
+ const key = this.model.newInstance().getKeyName();
3368
+ let count = 0;
3369
+ const models = await this.model.newModelQuery().whereIn(key, ids).get();
3370
+ for (const model of models) if (await model.delete()) count++;
3371
+ return count;
3372
+ }
3373
+ async get(columns = ["*"]) {
3374
+ this.applyScopes();
3375
+ let models = await this.getModels(columns);
3376
+ if (models.length > 0) models = await this.eagerLoadRelations(models);
3377
+ return new collection_default(models);
3378
+ }
3379
+ async all(columns = ["*"]) {
3380
+ return await this.model.newModelQuery().get(columns);
3381
+ }
3382
+ async paginate(page = 1, perPage = 10) {
3383
+ var _this;
3384
+ page = page || 1;
3385
+ perPage = perPage || ((_this = this) === null || _this === void 0 || (_this = _this.model) === null || _this === void 0 ? void 0 : _this.perPage) || 15;
3386
+ this.applyScopes();
3387
+ const total = await this.query.clone().clearOrder().clearSelect().count(this.primaryKey);
3388
+ let results = [];
3389
+ if (total > 0) {
3390
+ const skip = (page - 1) * (perPage ?? 10);
3391
+ this.take(perPage).skip(skip);
3392
+ results = await this.getModels();
3393
+ if (results.length > 0) results = await this.eagerLoadRelations(results);
3394
+ } else results = [];
3395
+ return new paginator_default(results, parseInt(total), perPage, page);
3396
+ }
3397
+ async getModels(...columns) {
3398
+ columns = flat(columns);
3399
+ if (columns.length > 0) {
3400
+ if (this.query._statements.filter((item) => item.grouping == "columns").length == 0 && columns[0] !== "*") this.query.select(...columns);
3401
+ }
3402
+ return this.hydrate(await this.query.get()).all();
3403
+ }
3404
+ getRelation(name) {
3405
+ if (typeof this.model[getRelationMethod(name)] !== "function") {
3406
+ const message = `Model [${this.model.constructor.name}]'s relation [${name}] doesn't exist.`;
3407
+ throw new RelationNotFoundError(message);
3408
+ }
3409
+ const relation = relation_default.noConstraints(() => this.model.newInstance(this.model.attributes)[getRelationMethod(name)]());
3410
+ const nested = this.relationsNestedUnder(name);
3411
+ if (Object.keys(nested).length > 0) relation.query.with(nested);
3412
+ return relation.asProxy();
3413
+ }
3414
+ relationsNestedUnder(relation) {
3415
+ const nested = {};
3416
+ for (const name in this.eagerLoad) {
3417
+ const constraints = this.eagerLoad[name];
3418
+ if (this.isNestedUnder(relation, name)) nested[name.substring((relation + ".").length)] = constraints;
3419
+ }
3420
+ return nested;
3421
+ }
3422
+ isNestedUnder(relation, name) {
3423
+ return name.includes(".") && name.startsWith(relation + ".");
3424
+ }
3425
+ async eagerLoadRelation(models, name, constraints) {
3426
+ const relation = this.getRelation(name);
3427
+ relation.addEagerConstraints(models);
3428
+ constraints(relation);
3429
+ return relation.match(relation.initRelation(models, name), await relation.get(), name);
3430
+ }
3431
+ async eagerLoadRelations(models) {
3432
+ for (const name in this.eagerLoad) {
3433
+ const constraints = this.eagerLoad[name];
3434
+ if (!name.includes(".")) models = await this.eagerLoadRelation(models, name, constraints);
3435
+ }
3436
+ return models;
3437
+ }
3438
+ hydrate(items) {
3439
+ return new collection_default(items.map((item) => {
3440
+ if (!this.model) return item;
3441
+ return this.model.newFromBuilder(item);
3442
+ }));
3443
+ }
3444
+ };
3445
+ var builder_default = Builder;
3446
+
3447
+ //#endregion
3448
+ //#region src/concerns/has-unique-ids.ts
3449
+ const HasUniqueIds = (Model$1) => {
3450
+ return class extends Model$1 {
3451
+ useUniqueIds = true;
3452
+ uniqueIds() {
3453
+ return [this.getKeyName()];
3454
+ }
3455
+ getKeyType() {
3456
+ if (this.uniqueIds().includes(this.getKeyName())) return "string";
3457
+ return this.keyType;
3458
+ }
3459
+ getIncrementing() {
3460
+ if (this.uniqueIds().includes(this.getKeyName())) return false;
3461
+ return this.incrementing;
3462
+ }
3463
+ };
3464
+ };
3465
+ var has_unique_ids_default = HasUniqueIds;
3466
+
3467
+ //#endregion
3468
+ //#region src/migrations/migration-repository.ts
3469
+ var MigrationRepository = class {
3470
+ resolver;
3471
+ table;
3472
+ connection = null;
3473
+ constructor(resolver, table) {
3474
+ this.resolver = resolver;
3475
+ this.table = table;
3476
+ }
3477
+ async getRan() {
3478
+ return await this.getTable().orderBy("batch", "asc").orderBy("migration", "asc").pluck("migration");
3479
+ }
3480
+ async getMigrations(steps) {
3481
+ return await this.getTable().where("batch", ">=", "1").orderBy("batch", "desc").orderBy("migration", "desc").take(steps).get();
3482
+ }
3483
+ async getMigrationsByBatch(batch) {
3484
+ return await this.getTable().where("batch", batch).orderBy("migration", "desc").get();
3485
+ }
3486
+ async getLast() {
3487
+ return await this.getTable().where("batch", await this.getLastBatchNumber()).orderBy("migration", "desc").get();
3488
+ }
3489
+ async getMigrationBatches() {
3490
+ const migrations = await this.getTable().select("batch", "migration").orderBy("batch", "asc").orderBy("migration", "asc").get();
3491
+ const migrationBatches = {};
3492
+ migrations.map((migration) => {
3493
+ migrationBatches[migration.migration] = migration.batch;
3494
+ });
3495
+ return migrationBatches;
3496
+ }
3497
+ async log(file, batch) {
3498
+ await this.getTable().insert({
3499
+ migration: file,
3500
+ batch
3501
+ });
3502
+ }
3503
+ async delete(migration) {
3504
+ await this.getTable().where("migration", migration.migration).delete();
3505
+ }
3506
+ async getNextBatchNumber() {
3507
+ return await this.getLastBatchNumber() + 1;
3508
+ }
3509
+ async getLastBatchNumber() {
3510
+ return await this.getTable().max("batch");
3511
+ }
3512
+ async createRepository() {
3513
+ await this.getConnection().schema.createTable(this.table, function(table) {
3514
+ table.increments("id");
3515
+ table.string("migration");
3516
+ table.integer("batch");
3517
+ });
3518
+ }
3519
+ repositoryExists() {
3520
+ return this.getConnection().schema.hasTable(this.table);
3521
+ }
3522
+ async deleteRepository() {
3523
+ await this.getConnection().schema.drop(this.table);
3524
+ }
3525
+ getTable() {
3526
+ return this.getConnection().table(this.table);
3527
+ }
3528
+ getConnection() {
3529
+ return this.resolver.connection(this.connection);
3530
+ }
3531
+ setSource(name) {
3532
+ this.connection = name;
3533
+ }
3534
+ };
3535
+ var migration_repository_default = MigrationRepository;
3536
+
3537
+ //#endregion
3538
+ //#region src/migrations/migrator.ts
3539
+ async function glob(folderPath) {
3540
+ const files = await fs.readdir(folderPath);
3541
+ const allFiles = [];
3542
+ for (const file of files) {
3543
+ const filePath = `${folderPath}/${file}`;
3544
+ const stats = await fs.stat(filePath);
3545
+ if (stats.isFile()) allFiles.push(filePath);
3546
+ else if (stats.isDirectory()) {
3547
+ const subFiles = await glob(filePath);
3548
+ allFiles.push(...subFiles);
3549
+ }
3550
+ }
3551
+ return allFiles;
3552
+ }
3553
+ var Migrator = class {
3554
+ events = null;
3555
+ repository;
3556
+ files;
3557
+ resolver;
3558
+ connection;
3559
+ paths = [];
3560
+ output = null;
3561
+ constructor(repository, resolver = null, files = null, dispatcher = null) {
3562
+ this.repository = repository;
3563
+ this.files = files;
3564
+ this.resolver = resolver;
3565
+ this.events = dispatcher;
3566
+ }
3567
+ async run(paths = [], options = {}) {
3568
+ const files = await this.getMigrationFiles(paths);
3569
+ const ran = await this.repository.getRan();
3570
+ const migrations = this.pendingMigrations(files, ran);
3571
+ await this.runPending(migrations, options);
3572
+ return migrations;
3573
+ }
3574
+ pendingMigrations(files, ran) {
3575
+ return Object.values(files).filter((file) => !ran.includes(this.getMigrationName(file)));
3576
+ }
3577
+ async runPending(migrations, options = {}) {
3578
+ if (migrations.length === 0) {
3579
+ this.write("Nothing to migrate");
3580
+ return;
3581
+ }
3582
+ let batch = await this.repository.getNextBatchNumber();
3583
+ const pretend = options.pretend || false;
3584
+ const step = options.step || false;
3585
+ this.write("Running migrations.");
3586
+ for (const file of migrations) {
3587
+ await this.runUp(file, batch, pretend);
3588
+ if (step) batch++;
3589
+ }
3590
+ }
3591
+ async runUp(file, batch, _pretend) {
3592
+ const migration = await this.resolvePath(file);
3593
+ const name = this.getMigrationName(file);
3594
+ await this.writeTask(name, () => this.runMigration(migration, "up"));
3595
+ await this.repository.log(name, batch);
3596
+ }
3597
+ async runDown(file, migration, _pretend) {
3598
+ const instance = await this.resolvePath(file);
3599
+ const name = this.getMigrationName(file);
3600
+ await this.writeTask(name, () => this.runMigration(instance, "down"));
3601
+ await this.repository.delete(migration);
3602
+ }
3603
+ async rollback(paths = [], options = {}) {
3604
+ const migrations = await this.getMigrationsForRollback(options);
3605
+ if (migrations.length === 0) {
3606
+ this.write("Nothing to rollback.");
3607
+ return [];
3608
+ }
3609
+ return await this.rollbackMigrations(migrations, paths, options);
3610
+ }
3611
+ async getMigrationsForRollback(options) {
3612
+ if (options.step && options.step > 0) return await this.repository.getMigrations(options.step);
3613
+ if (options.batch && options.batch > 0) return await this.repository.getMigrationsByBatch(options.batch);
3614
+ return await this.repository.getLast();
3615
+ }
3616
+ async rollbackMigrations(migrations, paths, options) {
3617
+ const rolledBack = [];
3618
+ const files = await this.getMigrationFiles(paths);
3619
+ this.write("Rolling back migrations.");
3620
+ for (const migration of migrations) {
3621
+ const file = files[migration.migration];
3622
+ if (!file) {
3623
+ this.writeTwoColumns(migration.migration, color.yellow("Migration not found"));
3624
+ continue;
3625
+ }
3626
+ rolledBack.push(file);
3627
+ await this.runDown(file, migration, options.pretend || false);
3628
+ }
3629
+ return rolledBack;
3630
+ }
3631
+ reset(_paths = [], _pretend = false) {
3632
+ this.repository.getRan().then((r) => r.reverse());
3633
+ return [];
3634
+ }
3635
+ resetMigrations(migrations, paths, pretend = false) {
3636
+ return this.rollbackMigrations(migrations, paths, { pretend });
3637
+ }
3638
+ async runMigration(migration, method) {
3639
+ const connection = this.resolveConnection(migration.getConnection());
3640
+ const callback = async (trx) => {
3641
+ if (typeof migration[method] === "function") await this.runMethod(trx, migration, method);
3642
+ };
3643
+ if (migration.withinTransaction) await connection.transaction(callback);
3644
+ else await callback(connection);
3645
+ }
3646
+ async runMethod(connection, migration, method) {
3647
+ var _migration$method;
3648
+ await ((_migration$method = migration[method]) === null || _migration$method === void 0 ? void 0 : _migration$method.call(migration, connection.schema, connection));
3649
+ }
3650
+ async resolvePath(filePath) {
3651
+ try {
3652
+ return new (await (import(filePath))).default();
3653
+ } catch {}
3654
+ return new class {}();
3655
+ }
3656
+ getMigrationClass(migrationName) {
3657
+ return migrationName.split("_").slice(4).map((str) => str.charAt(0).toUpperCase() + str.slice(1)).join("");
3658
+ }
3659
+ async getMigrationFiles(paths) {
3660
+ const files = [];
3661
+ for (const p of paths) {
3662
+ if (p.endsWith(".js") || p.endsWith(".ts")) {
3663
+ files.push(p);
3664
+ continue;
3665
+ }
3666
+ files.push(...await glob(p));
3667
+ }
3668
+ return files.filter(Boolean).reduce((result, file) => {
3669
+ result[this.getMigrationName(file)] = file;
3670
+ return result;
3671
+ }, {});
3672
+ }
3673
+ getMigrationName(filePath) {
3674
+ return path.basename(filePath).replace(".js", "");
3675
+ }
3676
+ path(p) {
3677
+ this.paths = Array.from(new Set([...this.paths, p]));
3678
+ }
3679
+ getPaths() {
3680
+ return this.paths;
3681
+ }
3682
+ getConnection() {
3683
+ return this.connection;
3684
+ }
3685
+ resolveConnection(connection) {
3686
+ return this.resolver.connection(connection || this.connection);
3687
+ }
3688
+ getRepository() {
3689
+ return this.repository;
3690
+ }
3691
+ repositoryExists() {
3692
+ return this.repository.repositoryExists();
3693
+ }
3694
+ async hasRunAnyMigrations() {
3695
+ const ran = await this.repository.getRan();
3696
+ return await this.repositoryExists() && ran.length > 0;
3697
+ }
3698
+ deleteRepository() {
3699
+ this.repository.deleteRepository();
3700
+ }
3701
+ setOutput(output) {
3702
+ this.output = output;
3703
+ return this;
3704
+ }
3705
+ write(...args) {
3706
+ if (this.output) console.log(...args);
3707
+ }
3708
+ writeTwoColumns(name, ...args) {
3709
+ const value = args.join(" ");
3710
+ const regex = /\x1b\[\d+m/g;
3711
+ const width = Math.min(process.stdout.columns, 100);
3712
+ const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
3713
+ this.write(name, color.gray(".".repeat(dots)), value);
3714
+ }
3715
+ async writeTask(description, task) {
3716
+ const startTime = process.hrtime();
3717
+ let result = false;
3718
+ try {
3719
+ result = await (task || (() => true))();
3720
+ } finally {
3721
+ const endTime = process.hrtime(startTime);
3722
+ const duration = (endTime[0] * 1e9 + endTime[1]) / 1e6;
3723
+ this.writeTwoColumns(color.green(description), color.gray(`${Math.floor(duration)}ms`), result !== false ? color.green("✔") : color.red("✘"));
3724
+ }
3725
+ }
3726
+ };
3727
+ var migrator_default = Migrator;
3728
+
3729
+ //#endregion
3730
+ //#region src/cli/utils.ts
3731
+ const join = path.join;
3732
+ var Utils = class {
3733
+ /**
3734
+ * Wraps text with chalk
3735
+ *
3736
+ * @param txt
3737
+ * @param color
3738
+ * @returns
3739
+ */
3740
+ static textFormat(txt, color$1) {
3741
+ return String(txt).split(":").map((e, i, a) => i == 0 && a.length > 1 ? color$1(" " + e + ": ") : e).join("");
3742
+ }
3743
+ /**
3744
+ * Ouput formater object
3745
+ *
3746
+ * @returns
3747
+ */
3748
+ static output() {
3749
+ return {
3750
+ success: (msg, exit = false) => {
3751
+ console.log(color.green("✓"), this.textFormat(msg, color.bgGreen), "\n");
3752
+ if (exit) process.exit(0);
3753
+ },
3754
+ info: (msg, exit = false) => {
3755
+ console.log(color.blue("ℹ"), this.textFormat(msg, color.bgBlue), "\n");
3756
+ if (exit) process.exit(0);
3757
+ },
3758
+ error: (msg, exit = true) => {
3759
+ if (msg instanceof Error) {
3760
+ if (msg.message) console.error(color.red("✖"), this.textFormat(msg.message, color.bgRed));
3761
+ console.error(color.red(`${msg.detail ? `${msg.detail}\n` : ""}${msg.stack}`), "\n");
3762
+ } else console.error(color.red("✖"), this.textFormat(msg, color.bgRed), "\n");
3763
+ if (exit) process.exit(1);
3764
+ },
3765
+ quiet: () => {
3766
+ process.exit(0);
3767
+ }
3768
+ };
3769
+ }
3770
+ static findModulePkg(moduleId, cwd) {
3771
+ const parts = moduleId.replace(/\\/g, "/").split("/");
3772
+ let packageName = "";
3773
+ if (parts.length > 0 && parts[0][0] === "@") packageName += parts.shift() + "/";
3774
+ packageName += parts.shift();
3775
+ const packageJson = path.join(packageName, "package.json");
3776
+ const resolved = resolveFrom.silent(cwd ?? process.cwd(), packageJson);
3777
+ if (!resolved) return;
3778
+ return path.join(path.dirname(resolved), parts.join("/"));
3779
+ }
3780
+ static async getMigrationPaths(cwd, migrator, defaultPath, path$1) {
3781
+ if (path$1) return [join(cwd, path$1)];
3782
+ return [...migrator.getPaths(), join(cwd, defaultPath)];
3783
+ }
3784
+ static twoColumnDetail(name, value) {
3785
+ const regex = /\x1b\[\d+m/g;
3786
+ const width = Math.min(process.stdout.columns, 100);
3787
+ const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
3788
+ return console.log(name, color.gray(".".repeat(dots)), value);
3789
+ }
3790
+ /**
3791
+ * Check if file exists
3792
+ *
3793
+ * @param path
3794
+ * @returns
3795
+ */
3796
+ static async fileExists(path$1) {
3797
+ try {
3798
+ await access(path$1);
3799
+ return true;
3800
+ } catch {
3801
+ return false;
3802
+ }
3803
+ }
3804
+ static findUpConfig(cwd, name, extensions) {
3805
+ return escalade(cwd, (_dir, names) => {
3806
+ for (const ext of extensions) {
3807
+ const filename = `${name}.${ext}`;
3808
+ if (names.includes(filename)) return filename;
3809
+ }
3810
+ return false;
3811
+ });
3812
+ }
3813
+ };
3814
+
3815
+ //#endregion
3816
+ //#region src/migrate.ts
3817
+ var Migrate = class {
3818
+ callback;
3819
+ constructor(basePath, customStubPath, callback) {
3820
+ this.basePath = basePath;
3821
+ this.customStubPath = customStubPath;
3822
+ this.callback = callback ?? ((_ = "") => {});
3823
+ }
3824
+ /**
3825
+ * Runs all pending migrations
3826
+ *
3827
+ * @param config
3828
+ * @param options
3829
+ * @param destroyAll
3830
+ */
3831
+ async run(config, options = {}, destroyAll = false) {
3832
+ const { arquebus: arquebus$1, migrator } = await this.setupConnection(config);
3833
+ await this.prepareDatabase(migrator);
3834
+ const paths = await Utils.getMigrationPaths(this.basePath ?? process.cwd(), migrator, config.migrations.path, options.path);
3835
+ await migrator.setOutput(true).run(paths, {
3836
+ step: options.step,
3837
+ pretend: options.pretend
3838
+ });
3839
+ if (destroyAll) await arquebus$1.destroyAll();
3840
+ }
3841
+ /**
3842
+ * Rollback the last migration
3843
+ *
3844
+ * @param config
3845
+ * @param options
3846
+ * @param destroyAll
3847
+ */
3848
+ async rollback(config, options = {}, destroyAll = false) {
3849
+ const { arquebus: arquebus$1, migrator } = await this.setupConnection(config);
3850
+ const paths = await Utils.getMigrationPaths(this.basePath ?? process.cwd(), migrator, config.migrations.path, options.path);
3851
+ await migrator.setOutput(true).rollback(paths, {
3852
+ step: options.step || 0,
3853
+ pretend: options.pretend,
3854
+ batch: options.batch || 0
3855
+ });
3856
+ if (destroyAll) await arquebus$1.destroyAll();
3857
+ }
3858
+ /**
3859
+ * Prepares the database for migration
3860
+ *
3861
+ * @param migrator
3862
+ */
3863
+ async prepareDatabase(migrator) {
3864
+ if (!await migrator.repositoryExists()) {
3865
+ this.callback("INFO: Preparing database.", "info");
3866
+ this.callback("INFO: Creating migration table...", "info");
3867
+ await migrator.repository.createRepository();
3868
+ this.callback("SUCCESS: Migration table created successfully.", "success");
3869
+ }
3870
+ }
3871
+ /**
3872
+ * Check the status of available migrations
3873
+ *
3874
+ * @param config
3875
+ * @param options
3876
+ * @param destroyAll
3877
+ * @returns
3878
+ */
3879
+ async status(config, options = {}, destroyAll = false) {
3880
+ const { arquebus: arquebus$1, migrator } = await this.setupConnection(config);
3881
+ const getAllMigrationFiles = async () => {
3882
+ return await migrator.getMigrationFiles(await Utils.getMigrationPaths(this.basePath ?? process.cwd(), migrator, config.migrations.path, options.path));
3883
+ };
3884
+ async function getStatusFor(ran$1, batches$1) {
3885
+ const files = await getAllMigrationFiles();
3886
+ return Object.values(files).map((migration) => {
3887
+ const migrationName = migrator.getMigrationName(migration);
3888
+ return {
3889
+ name: migrationName,
3890
+ ran: ran$1.includes(migrationName),
3891
+ batch: ran$1.includes(migrationName) ? batches$1[migrationName] : null
3892
+ };
3893
+ });
3894
+ }
3895
+ if (!await migrator.repositoryExists()) this.callback("ERROR: Migration table does not exist.", "error");
3896
+ const ran = await migrator.repository.getRan();
3897
+ const batches = await migrator.getRepository().getMigrationBatches();
3898
+ const migrations = await getStatusFor(ran, batches);
3899
+ if (destroyAll) await arquebus$1.destroyAll();
3900
+ return migrations;
3901
+ }
3902
+ /**
3903
+ * Setup the database connection
3904
+ *
3905
+ * @param config
3906
+ * @returns
3907
+ */
3908
+ async setupConnection(config) {
3909
+ var _config$migrations;
3910
+ const table = (config === null || config === void 0 || (_config$migrations = config.migrations) === null || _config$migrations === void 0 ? void 0 : _config$migrations.table) || "migrations";
3911
+ if (config.skipConnection !== true) {
3912
+ arquebus_default.addConnection(config, "default");
3913
+ Object.entries(config.connections || {}).forEach(([name, connection]) => {
3914
+ arquebus_default.addConnection(connection, name);
3915
+ });
3916
+ }
3917
+ const repository = new migration_repository_default(arquebus_default, table);
3918
+ const migrator = new migrator_default(repository, arquebus_default);
3919
+ return {
3920
+ arquebus: arquebus_default,
3921
+ migrator
3922
+ };
3923
+ }
3924
+ };
3925
+
3926
+ //#endregion
3927
+ //#region src/migrations/migration.ts
3928
+ const Inference = class {};
3929
+ var Migration = class extends Inference {
3930
+ connection;
3931
+ withinTransaction = true;
3932
+ getConnection() {
3933
+ return this.connection;
3934
+ }
3935
+ };
3936
+ var migration_default = Migration;
3937
+
3938
+ //#endregion
3939
+ //#region src/pivot.ts
3940
+ var pivot_default = Pivot;
3941
+
3942
+ //#endregion
3943
+ //#region src/soft-deleting-scope.ts
3944
+ const hasJoins = (statements) => {
3945
+ for (const statement of statements) if ((statement === null || statement === void 0 ? void 0 : statement.grouping) === "join") return true;
3946
+ return false;
3947
+ };
3948
+ var SoftDeletingScope = class extends scope_default {
3949
+ extensions = [
3950
+ "Restore",
3951
+ "RestoreOrCreate",
3952
+ "CreateOrRestore",
3953
+ "WithTrashed",
3954
+ "WithoutTrashed",
3955
+ "OnlyTrashed"
3956
+ ];
3957
+ apply(builder, model) {
3958
+ builder.whereNull(model.getQualifiedDeletedAtColumn());
3959
+ }
3960
+ extend(builder) {
3961
+ for (const extension of this.extensions) this[`add${extension}`](builder);
3962
+ builder.onDelete(async (builder$1) => {
3963
+ const column = this.getDeletedAtColumn(builder$1);
3964
+ return await builder$1.update({ [column]: builder$1.getModel().freshTimestampString() });
3965
+ });
3966
+ }
3967
+ getDeletedAtColumn(builder) {
3968
+ if (hasJoins(builder.getQuery()._statements)) return builder.getModel().getQualifiedDeletedAtColumn();
3969
+ return builder.getModel().getDeletedAtColumn();
3970
+ }
3971
+ addRestore(builder) {
3972
+ builder.macro("restore", (builder$1) => {
3973
+ builder$1.withTrashed();
3974
+ return builder$1.update({ [builder$1.getModel().getDeletedAtColumn()]: null });
3975
+ });
3976
+ }
3977
+ addRestoreOrCreate(builder) {
3978
+ builder.macro("restoreOrCreate", async (builder$1, attributes = {}, values = {}) => {
3979
+ builder$1.withTrashed();
3980
+ return tap(await builder$1.firstOrCreate(attributes, values), async (instance) => {
3981
+ await instance.restore();
3982
+ });
3983
+ });
3984
+ }
3985
+ addCreateOrRestore(builder) {
3986
+ builder.macro("createOrRestore", async (builder$1, attributes = {}, values = {}) => {
3987
+ builder$1.withTrashed();
3988
+ return tap(await builder$1.createOrFirst(attributes, values), async (instance) => {
3989
+ await instance.restore();
3990
+ });
3991
+ });
3992
+ }
3993
+ addWithTrashed(builder) {
3994
+ builder.macro("withTrashed", (builder$1, withTrashed = true) => {
3995
+ if (!withTrashed) return builder$1.withoutTrashed();
3996
+ return builder$1.withoutGlobalScope(this);
3997
+ });
3998
+ }
3999
+ addWithoutTrashed(builder) {
4000
+ builder.macro("withoutTrashed", (builder$1) => {
4001
+ const model = builder$1.getModel();
4002
+ builder$1.withoutGlobalScope(this).whereNull(model.getQualifiedDeletedAtColumn());
4003
+ return builder$1;
4004
+ });
4005
+ }
4006
+ addOnlyTrashed(builder) {
4007
+ builder.macro("onlyTrashed", (builder$1) => {
4008
+ const model = builder$1.getModel();
4009
+ builder$1.withoutGlobalScope(this).whereNotNull(model.getQualifiedDeletedAtColumn());
4010
+ return builder$1;
4011
+ });
4012
+ }
4013
+ };
4014
+ var soft_deleting_scope_default = SoftDeletingScope;
4015
+
4016
+ //#endregion
4017
+ //#region src/soft-deletes.ts
4018
+ const softDeletes = (Model$1) => {
4019
+ return class extends Model$1 {
4020
+ forceDeleting = false;
4021
+ static bootSoftDeletes() {
4022
+ this.addGlobalScope(new soft_deleting_scope_default());
4023
+ }
4024
+ initialize() {
4025
+ super.initialize();
4026
+ this.constructor.bootSoftDeletes();
4027
+ this.addPluginInitializer("initializeSoftDeletes");
4028
+ }
4029
+ initializeSoftDeletes() {
4030
+ if (this.casts[this.getDeletedAtColumn()] === void 0) this.casts[this.getDeletedAtColumn()] = "datetime";
4031
+ }
4032
+ async forceDelete() {
4033
+ if (this.execHooks("forceDeleting") === false) return false;
4034
+ this.forceDeleting = true;
4035
+ return tap(await this.delete(), (deleted) => {
4036
+ this.forceDeleting = false;
4037
+ if (deleted) this.execHooks("forceDeleted", false);
4038
+ });
4039
+ }
4040
+ forceDeleteQuietly() {
4041
+ return this.withoutEvents(() => this.forceDelete());
4042
+ }
4043
+ async performDeleteOnModel(options = {}) {
4044
+ if (this.forceDeleting) return tap(await this.setKeysForSaveQuery(this.newModelQuery()).forceDelete(), () => {
4045
+ this.exists = false;
4046
+ });
4047
+ return await this.runSoftDelete(options);
4048
+ }
4049
+ async runSoftDelete(options = {}) {
4050
+ const query = this.setKeysForSaveQuery(this.newModelQuery());
4051
+ const time = this.freshTimestamp();
4052
+ const columns = { [this.getDeletedAtColumn()]: this.fromDateTime(time) };
4053
+ this[this.getDeletedAtColumn()] = time;
4054
+ if (this.usesTimestamps() && this.getUpdatedAtColumn()) {
4055
+ this[this.getUpdatedAtColumn()] = time;
4056
+ columns[this.getUpdatedAtColumn()] = this.fromDateTime(time);
4057
+ }
4058
+ await query.update(columns);
4059
+ this.syncOriginalAttributes(Object.keys(columns));
4060
+ this.execHooks("trashed", options);
4061
+ }
4062
+ async restore(options = {}) {
4063
+ if (this.execHooks("restoring", options) === false) return false;
4064
+ this[this.getDeletedAtColumn()] = null;
4065
+ this.exists = true;
4066
+ const result = await this.save();
4067
+ this.execHooks("restored", options);
4068
+ return result;
4069
+ }
4070
+ restoreQuietly() {
4071
+ return this.withoutEvents(() => this.restore());
4072
+ }
4073
+ trashed() {
4074
+ return !isNullish(this[this.getDeletedAtColumn()]);
4075
+ }
4076
+ static softDeleted(callback) {
4077
+ this.addHook("trashed", callback);
4078
+ }
4079
+ static restoring(callback) {
4080
+ this.addHook("restoring", callback);
4081
+ }
4082
+ static restored(callback) {
4083
+ this.addHook("restored", callback);
4084
+ }
4085
+ static forceDeleting(callback) {
4086
+ this.addHook("forceDeleting", callback);
4087
+ }
4088
+ static forceDeleted(callback) {
4089
+ this.addHook("forceDeleted", callback);
4090
+ }
4091
+ isForceDeleting() {
4092
+ return this.forceDeleting;
4093
+ }
4094
+ getDeletedAtColumn() {
4095
+ return this.constructor.DELETED_AT || "deleted_at";
4096
+ }
4097
+ getQualifiedDeletedAtColumn() {
4098
+ return this.qualifyColumn(this.getDeletedAtColumn());
4099
+ }
4100
+ };
4101
+ };
4102
+ var soft_deletes_default = softDeletes;
4103
+
4104
+ //#endregion
4105
+ //#region src/index.ts
4106
+ const make = (model, data, options = {}) => {
4107
+ const { paginated } = options;
4108
+ if (paginated) return new paginator_default(data.data.map((item) => model.make(item)), data.total, data.per_page, data.current_page);
4109
+ if (Array.isArray(data)) return new collection_default(data.map((item) => model.make(item)));
4110
+ return model.make(data);
4111
+ };
4112
+ const makeCollection = (model, data) => new collection_default(data.map((item) => model.make(item)));
4113
+ const makePaginator = (model, data) => new paginator_default(data.data.map((item) => model.make(item)), data.total, data.per_page, data.current_page);
4114
+
4115
+ //#endregion
4116
+ export { attribute_default as Attribute, builder_default as Builder, casts_attributes_default as CastsAttributes, collection_default as Collection, has_unique_ids_default as HasUniqueIds, InvalidArgumentError, Migrate, migration_default as Migration, model_default as Model, ModelNotFoundError, paginator_default as Paginator, pivot_default as Pivot, query_builder_default as QueryBuilder, RelationNotFoundError, scope_default as Scope, soft_deletes_default as SoftDeletes, arquebus_default as arquebus, compose, defineConfig, flattenDeep, getAttrMethod, getAttrName, getGetterMethod, getRelationMethod, getRelationName, getScopeMethod, getScopeName, getSetterMethod, kebabCase, make, makeCollection, makePaginator, now, snakeCase, tap };