@h3ravel/arquebus 0.2.13 → 0.2.15
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.
- package/bin/index.cjs +1 -1
- package/bin/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/migrations/index.cjs +1 -1
- package/dist/migrations/index.d.cts +4 -7
- package/dist/migrations/index.d.ts +4 -7
- package/dist/migrations/index.js +1 -1
- package/package.json +3 -3
package/bin/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t=require("commander"),e=require("fs/promises"),s=require("chalk"),i=require("escalade/sync"),r=require("path"),n=require("resolve-from"),a=require("radashi"),o=require("dayjs/plugin/advancedFormat.js"),h=require("dayjs"),c=require("knex"),u=require("collect.js"),l=require("pluralize"),g=require("fs"),d=require("url"),y=require("dotenv"),m="undefined"!=typeof document?document.currentScript:null;function f(t){return t&&t.__esModule?t:{default:t}}var p=f(e),w=f(s),b=f(i),C=f(r),v=f(n),P=f(o),K=f(h),N=f(c),R=f(u),A=f(l),x=Object.defineProperty,S=C.default.join,T=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(w.default.green("✓"),this.textFormat(t,w.default.bgGreen),"\n"),e&&process.exit(0)},info:(t,e=!1)=>{console.log(w.default.blue("ℹ"),this.textFormat(t,w.default.bgBlue),"\n"),e&&process.exit(0)},error:(t,e=!0)=>{t instanceof Error?(t.message&&console.error(w.default.red("✖"),this.textFormat(t.message,w.default.bgRed)),console.error(w.default.red(`${t.detail?`${t.detail}\n`:""}${t.stack}`),"\n")):console.error(w.default.red("✖"),this.textFormat(t,w.default.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=C.default.join(i,"package.json"),n=v.default.silent(e??process.cwd(),r);if(n)return C.default.join(C.default.dirname(n),s.join("/"))}static async getMigrationPaths(t,e,s,i){return i?[S(t,i)]:[...e.getPaths(),S(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,w.default.gray(".".repeat(r)),e)}static async fileExists(t){try{return await e.access(t),!0}catch{return!1}}static findUpConfig(t,e,s){return b.default(t,(t,i)=>{for(const t of s){const s=`${e}.${t}`;if(i.includes(s))return s}return!1})}},q=class t{static CREATE_PATTERNS=[/^create_(\w+)_table$/,/^create_(\w+)$/];static CHANGE_PATTERNS=[/.+_(to|from|in)_(\w+)_table$/,/.+_(to|from|in)_(\w+)$/];static guess(e){for(const s of t.CREATE_PATTERNS){const t=e.match(s);if(t)return[t[1],!0]}for(const s of t.CHANGE_PATTERNS){const t=e.match(s);if(t)return[t[2],!1]}return[]}},D=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 k(t){const e=await p.default.readdir(t),s=[];for(const i of e){const e=`${t}/${i}`,r=await p.default.stat(e);if(r.isFile())s.push(e);else if(r.isDirectory()){const t=await k(e);s.push(...t)}}return s}var E=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,w.default.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 k(s));return e.filter(Boolean).reduce((t,e)=>(t[this.getMigrationName(e)]=e,t),{})}getMigrationName(t){return C.default.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,w.default.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(w.default.green(t),w.default.gray(`${Math.floor(r)}ms`),!1!==i?w.default.green("✔"):w.default.red("✘"))}}},M={};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)x(t,s,{get:e[s],enumerable:!0})})(M,{compose:()=>_}),K.default.extend(P.default);var F=t=>a.camel(`relation_${t}`),I=t=>a.camel(`scope_${t}`),O=t=>a.camel(`attribute_${t}`),Q=t=>a.camel(`get_${t}_attribute`),j=(t,e)=>{const s=e(t);return s instanceof Promise?s.then(()=>t):t},{compose:W}=M,$=t=>Array.isArray(t)?t.reduce((t,e)=>t.concat($(e)),[]):[t],B=t=>a.trim(a.snake(t.replace(/[^a-zA-Z0-9_-]/g,"-")),"_-"),L=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}},H=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?.()}},U=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}},J=class extends(W(H,U)){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 Ct?t.attributes[this.ownerKey]:t;return this.child[this.foreignKey]=e,t instanceof Ct?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()}},z=class t extends u.Collection{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,s=null){if(this.isEmpty())return this;const i=(await this.first().newModelQuery().whereIn(this.first().getKeyName(),this.modelKeys()).select(this.first().getKeyName()).withAggregate(t,e,s).get()).keyBy(this.first().getKeyName()),r=a.diff(Object.keys(i.first().getAttributes()),[i.first().getKeyName()]);return this.each(t=>{const e=a.pick(i.get(t.getKey()).getAttributes(),r);t.fill(e).syncOriginalAttributes(...r)}),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 Pt?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=a.omit(this.getDictionary(),t);return new this.constructor(Object.values(e))}intersect(t){const e=new this.constructor;if(a.isEmpty(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 Pt&&(t=t.getKey()),a.isArray(t)?this.isEmpty()?new this.constructor:this.whereIn(this.first().getKeyName(),t):(u.collect(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=a.pick(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}}}},G=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,e=!0){let s,i={attached:[],detached:[],updated:[]};const r=await this.getCurrentlyAttachedPivots(),n=0===r.length?[]:r.map(t=>t.toData()).pluck(this.relatedPivotKey).all().map(t=>String(t)),o=a.diff(n,Object.keys(s=this.formatRecordsList(this.parseIds(t))));return e&&o.length>0&&(await this.detach(o),i.detached=this.castKeys(o)),i=a.assign(i,await this.attachNew(s,n,!1)),i}syncWithoutDetaching(t){return this.sync(t,!1)}syncWithPivotValues(t,e,s=!0){return this.sync(u.collect(this.parseIds(t)).mapWithKeys(t=>[t,e]),s)}withPivot(t){return this.pivotColumns=this.pivotColumns.concat(a.isArray(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 u.collect(t).mapWithKeys((t,e)=>(a.isArray(t)||([e,t]=[t,{}]),[e,t])).all()}async getCurrentlyAttachedPivots(){const t=this.newPivotQuery();return(await t.get()).map(t=>(this.using||vt).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,e,s,i){const[r,n]=this.extractAttachIdAndAttributes(t,e,s);return a.assign(this.baseAttachRecord(r,i),n)}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.isArray(e)?[t,{...e,...s}]:[e,s]}hasPivotColumn(t){return this.pivotColumns.includes(t)}parseIds(t){return t instanceof Ct?[t[this.relatedKey]]:t instanceof z?t.pluck(this.relatedKey).all():a.isArray(t)?t:[t]}},V=class extends Error{constructor(t,e){super(t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t}},Y=class extends V{model;ids=[];constructor(){super("")}setModel(t,e=[]){return this.model=t,this.ids=a.isArray(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}},Z=class extends V{},X=class extends V{},tt=class extends(W(H,G)){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 z([]))}),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 z([])}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 z(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 Y).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=a.omit(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 a.isEqual(t,["*"])&&(t=[this.related.getTable()+".*"]),t.concat(this.aliasedPivotColumns())}aliasedPivotColumns(){const t=[this.foreignPivotKey,this.relatedPivotKey];return u.collect(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 z([])),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)}},et=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 z([]),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 z?t:new z(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)}},st=class t{constructor(){if(this.constructor===t)throw new Error("Scope cannot be instantiated")}apply(t,e){throw new Error("apply not implemented")}},it=class{},rt=class t extends it{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=a.snake(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 e=this.model.getUpdatedAtColumn();return t=a.assign({[e]: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 st?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=I(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=a.omit(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 e={};if("function"==typeof t[1]){const e=this.parseWithRelations({[t[0]]:t[1]});return this.eagerLoad=a.assign(this.eagerLoad,e),this}const s=$(t);if(0===s.length)return this;for(const t of s){let s;"string"==typeof t?s={[t]:t=>t}:"object"==typeof t&&(s=t),e=a.assign(e,s)}return this.eagerLoad=a.assign(this.eagerLoad,this.parseWithRelations(e)),this}has(t,e=">=",s=1,i="and",r=null){if(a.isString(t)){if(t.includes("."))return this.hasNested(t,e,s,i,r);t=this.getRelationWithoutConstraints(F(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,e,s=null){if(0===t.length)return this;t=$([t]);let i={};for(const e of t){let t;"string"==typeof e?t={[e]:t=>t}:"object"==typeof e&&(t=e),i=a.assign(i,t)}t=i;const r=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 n=this.parseWithRelations(t);for(let t in n){const i=n[t],o=t.split(" ");let h,c;3===o.length&&"as"===o[1].toLocaleLowerCase()&&([t,h]=[o[0],o[2]]);const u=this.getRelationWithoutConstraints(F(t));if(s){const t=this.query._single.table===u.query.query._single.table?`${u.getRelationCountHash(!1)}.${e}`:e,i="*"===e?e:u.getRelated().qualifyColumn(t);c="exists"===s?i:`${s}(${i})`}else c=e;const l=u.getRelationExistenceQuery(u.getRelated().newModelQuery(),this,r.raw(c));i(l),h=h||a.snake(`${t} ${s} ${e}`.replace("/[^[:alnum:][:space:]_]/u","")),"exists"===s?this.select(r.raw(`exists(${l.toSql().sql}) as ${h}`)):this.selectSub(s?l:l.limit(1),h)}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 H)return[e.toSql().sql,e.toSql().bindings];if(a.isString(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 H.noConstraints(()=>this.getModel()[t]())}withCount(...t){return this.withAggregate($(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 r=t[i];if(a.isString(r)||Number.isFinite(parseInt(r)))continue;const[n,o]=this.parseNameAndAttributeSelectionConstraint(i,r);s=Object.assign({},s,{[`${e}${n}`]:o},this.prepareNestedWithRelationships(r,`${e}${n}`)),t=a.omit(t,[i])}for(const i in t){const r=t[i];let n=i,o=r;a.isString(r)&&([n,o]=this.parseNameAndAttributeSelectionConstraint(r)),s[`${e}${n}`]=this.combineConstraints([o,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 tt?e.related.getTable()+"."+t:t))}]}related(t){if("function"!=typeof this.model[F(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new Z(e)}return this.model[F(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 Y).setModel(this.model.constructor.name);return e}async findOrFail(...t){const e=await this.find(...t);if(a.isArray(t[0])){if(e.count()!==t[0].length)throw(new Y).setModel(this.model.constructor.name,a.diff(t[0],e.modelKeys()));return e}if(null===e)throw(new Y).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={},e={}){const s=await this.where(t).first();return null!==s?s:this.newModelInstance(a.assign(t,e))}async firstOrCreate(t={},e={}){const s=await this.where(t).first();return null!==s?s:j(this.newModelInstance(a.assign(t,e)),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.isArray(t)||t instanceof z?await this.findMany(t,e):await this.where(this.model.getKeyName(),t).first(e)}async findMany(t,e=["*"]){return t instanceof z&&(t=t.modelKeys()),0===(t=a.isArray(t)?t:[t]).length?new z([]):await this.whereIn(this.model.getKeyName(),t).get(e)}async pluck(t){const e=await this.query.pluck(t);return new z(e)}async destroy(t){if(t instanceof z&&(t=t.modelKeys()),t instanceof u.Collection&&(t=t.all()),0===(t=a.isArray(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 z(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 et(r,parseInt(i),e,t)}async getModels(...t){return(t=a.flat(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[F(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new Z(e)}const e=H.noConstraints(()=>this.model.newInstance(this.model.attributes)[F(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 z(t.map(t=>{if(!this.model)return t;return this.model.newFromBuilder(t)}))}},nt=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")}},at=t=>class extends t{static castTypeCache={};attributes={};original={};casts={};changes={};appends=[];setAppends(t){return this.appends=t,this}append(...t){const e=$(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=$(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=$(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=(i=t,a.camel(`set_${i}_attribute`));var i;if("function"==typeof this[s])return this[s](e),this;const r=O(t);if("function"==typeof this[r]){const s=this[r]().set||(e=>{this.attributes[t]=e});return this.attributes={...this.attributes,...this.normalizeCastClassResponse(t,s(e,this.attributes))},this}const n=this.getCasts()[t];return this.isCustomCast(n)&&"string"!=typeof n&&(e=n.set(this,t,e,this.attributes)??""),"json"===n&&(e=JSON.stringify(e)),"collection"===n&&(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=Q(t);if("function"==typeof this[e])return this[e](this.attributes[t],this.attributes);const s=O(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 R.default(JSON.parse(e))}catch{return R.default([])}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=a.omit(t,[e])),this.visible.length>0&&!1===this.visible.includes(e)&&(t=a.omit(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]=K.default(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[Q(t)])return this[Q(t)](e);if("function"==typeof this[O(t)]){return this[O(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?K.default(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 nt&&(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=a.flat(e)).length>0)||e.includes(this.getCastType(t)))}withDayjs(t){return K.default(t)}isCustomCast(t){return"function"==typeof t&&new t instanceof nt}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 K.default(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 K.default(e).startOf("day").toDate()}},ot=t=>class extends t{static globalScopes;static addGlobalScope(t,e=null){if("string"==typeof t&&e instanceof st)return this.globalScopes=a.set(this.globalScopes??{},this.name+"."+t,e),e;if(t instanceof st)return this.globalScopes=a.set(this.globalScopes??{},this.name+"."+t.constructor.name,t),t;throw new X("Global scope must be an instance of Scope.")}static hasGlobalScope(t){return null!==this.getGlobalScope(t)}static getGlobalScope(t){return"string"==typeof t?a.get(this.globalScopes,this.name+"."+t):a.get(this.globalScopes,this.name+"."+t.constructor.name)}static getAllGlobalScopes(){return this.globalScopes}static setAllGlobalScopes(t){this.globalScopes=t}getGlobalScopes(){return a.get(this.constructor.globalScopes,this.constructor.name,{})}},ht=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}},ct=t=>class extends t{static hooks=null;static addHook(t,e){this.hooks instanceof ht==!1&&(this.hooks=new ht),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 ht!=!1)return await this.constructor.hooks.exec(t,[this,e])}},ut=t=>class extends t{getRelationValue(t,e,s){const i=t[e];return"one"===s?i[0]:new z(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 R.default(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 z?t:new z(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 z?e:new z(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(W(H,ut)){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 z([]))}),t}async getResults(){return null!==this.getParentKey()?await this.query.get():new z([])}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}buildDictionary(t){const e=this.getForeignKeyName();return u.collect(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))}},gt=class extends(W(H,ut,U)){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])}},dt=class extends H{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 Y).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.isArray(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 Y).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}},yt=class extends(W(dt,U)){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()}},mt=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=a.omit(this.relations,[t]),this}relationLoaded(t){return void 0!==this.relations[t]}related(t){if("function"!=typeof this[F(t)]){const e=`Model [${this.constructor.name}]'s relation [${t}] doesn't exist.`;throw new Z(e)}return this[F(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 e=t,a.snake(e.substring(8));var e}joiningTable(t,e=null){return[e?e.joiningTableSegment():B(t.name),this.joiningTableSegment()].sort().join("_").toLocaleLowerCase()}joiningTableSegment(){return B(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 gt(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 J(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 tt(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 yt(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 dt(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}},ft=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())}},pt=t=>class extends t{hidden=[];visible=[];makeVisible(...t){const e=$(t);return this.visible.length>0&&(this.visible=[...this.visible,...e]),this.hidden=a.diff(this.hidden,e),this}makeHidden(t,...e){const s=$([...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}},wt=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())}},bt=W(class{},at,pt,mt,ft,ct,ot,wt),Ct=class t extends bt{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[F(s)])e.setAttribute(s,t[s]);else{const i=e[F(s)](),r=i.getRelated().constructor;i instanceof gt||i instanceof J?e.setRelation(s,r.make(t[s])):(i instanceof lt||i instanceof tt)&&Array.isArray(t[s])&&e.setRelation(s,new z(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 B(this.constructor.name)+"_"+this.getKeyName()}getConnectionName(){return this.connection}getTable(){return this.table||A.default(B(this.constructor.name))}getConnection(){return this.constructor.resolver?this.constructor.resolver.getConnection(this.connection):Rt.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[I(t)]}callNamedScope(t,e){return this[I(t)](...e)}setTable(t){return this.table=t,this}newCollection(t=[]){return new z(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 z([this]).loadAggregate(t,e,s),this}async loadCount(...t){return t=$(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 a.assign(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(R.default(this.relations).reject(t=>t instanceof vt).keys().all()),this.syncOriginal(),this}newPivot(t,e,s,i,r=null){return r?r.fromRawAttributes(t,e,s,i):vt.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 z?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)}},vt=class extends Ct{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]}},Pt=Ct,Kt=class{},Nt=class t extends Kt{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 et(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}},Rt=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 connection(t=null){return this.getInstance().getConnection(t)}static setConnectorFactory(t){this.connectorFactory=t}static getConnectorFactory(){return this.connectorFactory??N.default}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 Nt(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=C.default.resolve("arquebus.config.js"),i=C.default.resolve("arquebus.config.ts"),r=this.getInstance();if(g.existsSync(s))return e=(await import(s)).default,t&&r.addConnection(e,e.client),e;if(g.existsSync(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=Ct;if("plugins"in e&&(s=W(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 L==!1)throw new Error('Attribute must be an instance of "Attribute"');this.models[t].prototype[O(s)]=()=>e.attributes?.[s]}if("relations"in e)for(const s in e.relations)this.models[t].prototype[F(s)]=function(){return e.relations?.[s](this)};if("scopes"in e)for(const s in e.scopes)this.models[t].prototype[I(s)]=e.scopes[s];return this.models[t].setConnectionResolver(this),this.models[t]}},At=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 T.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 T.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 T.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";t.skipConnection||(Rt.addConnection(t,"default"),Object.entries(t.connections||{}).forEach(([t,e])=>{Rt.addConnection(e,t)}));const s=new D(Rt,e),i=new E(s,Rt);return{arquebus:Rt,migrator:i}}},xt=class{constructor(t,e="js"){this.customStubPath=t,this.type=e}postCreate=[];async create(t,e,s,i=!1){const r=this.getStub(s,i),n=this.getPath(t,e);return await this.ensureDirectoryExists(C.default.dirname(n)),await p.default.writeFile(n,this.populateStub(r,s)),await this.firePostCreateHooks(s,n),n}async publish(t,e){const s=await p.default.readdir(this.customStubPath??"");await this.ensureDirectoryExists(t);for(const i of s){const s=C.default.join(this.customStubPath??"",i),r=C.default.join(t,i);await p.default.copyFile(s,r),e&&e(i,s,r)}}getStub(t,e=!1){let s;if(t)if(e){const t=C.default.join(this.customStubPath??"",`migration.create-${this.type}.stub`);s=g.existsSync(t)?t:this.stubPath(`/migration.create-${this.type}.stub`)}else{const t=C.default.join(this.customStubPath??"",`migration.update-${this.type}.stub`);s=g.existsSync(t)?t:this.stubPath(`/migration.update-${this.type}.stub`)}else{const t=C.default.join(this.customStubPath??"",`migration-${this.type}.stub`);console.log("\n",t,"---"),s=g.existsSync(t)?t:this.stubPath(`/migration-${this.type}.stub`)}return g.readFileSync(s,"utf-8")}populateStub(t,e){return null!==e&&(t=t.replace(/DummyTable|{{\s*table\s*}}/g,e)),t}getClassName(t){return t.replace(/_+([a-z])/g,(t,e)=>e.toUpperCase())}getPath(t,e){const s=K.default().format("YYYY_MM_DD_HHmmss");return C.default.join(e,`${s}_${t}.${this.type}`)}async firePostCreateHooks(t,e){for(const s of this.postCreate)await s(t,e)}afterCreate(t){this.postCreate.push(t)}async ensureDirectoryExists(t){await p.default.mkdir(t,{recursive:!0})}stubPath(t=""){const e=this.getDirname({url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href});return C.default.join(e,"stubs",t)}getDirname(t){if("undefined"!=typeof __dirname)return __dirname;if(t&&t.url)return r.dirname(d.fileURLToPath(t.url));throw new Error("Unable to determine dirname")}},St="0.2.11";(class s{cwd;output=T.output();config={};basePath="";modulePath;configPath;modulePackage;constructor(t){this.basePath=t??("true"===process.env.TEST?"test/cli":"")}terminateNotFound(){this.output.error(`ERROR: Arquebus config not found. Run ${w.default.italic.black.bgGray("arquebus init")} first.`)}static init(){y.config({quiet:!0});const t=new s;Promise.all([t.loadPaths(),t.loadConfig()]).then(([t,e])=>e.run())}async loadPaths(){this.cwd=C.default.join(process.cwd(),this.basePath),this.configPath=T.findUpConfig(this.cwd,"arquebus.config",["js","ts","cjs"])??void 0,this.modulePath=T.findModulePkg("@h3ravel/arquebus",this.cwd)??"";try{this.modulePackage=await import(C.default.join(this.modulePath,"package.json"))}catch{this.modulePackage={version:"N/A"}}return this}async loadConfig(){try{this.config=(await import(this.configPath??"----")).default,this.config.migrations?.path&&await e.mkdir(C.default.join(this.cwd,this.config.migrations?.path),{recursive:!0})}catch{this.config={}}return this}async run(){const s=["Arquebus CLI version:",w.default.green(St)].join(" "),i=["Arquebus Local version:",w.default.green(this.modulePackage.version||"None")].join(" ");t.program.name("arquebus").version(`${s}\n${i}`),t.program.command("init").description("Create a fresh Arquebus config.").addArgument(new t.Argument("[type]","Type of config to generate.").choices(["js","ts"]).default("js","generates a js config")).action(async t=>{this.modulePath||this.output.error(["ERROR: No local arquebus install found"," Try running: npm install arquebus --save"]),this.configPath&&this.output.error(`ERROR: ${this.configPath} already exists`);try{const s=`./arquebus.config.${t}`,i=await e.readFile(C.default.join(this.modulePath,`/src/stubs/arquebus.config-${t}.stub`),{encoding:"utf8"});await e.writeFile(C.default.join(this.cwd,s),i),this.output.success(`Initialized: Arquebus has been initialized as ${s}`)}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate:make <name>").description("Create a new migration file.").addOption(new t.Option("-l, --type [string]","Type of migration file to generate.").choices(["js","ts"]).default("js","generates a js migration file")).option("-t, --table [string]","The table to migrate").option("-c, --create [string]","The table to be created").option("-p, --path [path]","The path to the migrations directory.").action(async(t,e)=>{this.configPath||this.terminateNotFound();try{t=a.snake(t);const s=C.default.join(this.cwd,e.path??this.config.migrations?.path??"./migrations");let i=e.table,r=e.create||!1;if(i||"string"!=typeof r||(i=r,r=!0),!i){const e=q.guess(t);i=e[0],r=!!e[1]}this.output.info("INFO: Creating Migration");const n=new xt(void 0,e.type),o=await n.create(t,s,i,r);this.output.success(`INFO: Migration Created \n ${w.default.gray(C.default.basename(o))}`,!0)}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate:publish <package>").description("Publish any migration files from packages.").option("-p, --path [path]","The path to the migrations directory.").action(async(t,e)=>{this.configPath||this.terminateNotFound();try{const s=T.findModulePkg(t)??"",i=C.default.join(this.cwd,e.path??this.config.migrations?.path??"./migrations"),r=await import(C.default.join(s,"package.json"));s||this.output.error(`ERROR: package ${t} not found`);const n=new xt(C.default.join(s,r.migrations??"migrations"));this.output.info(`INFO: Publishing migrations from ${w.default.italic.gray(r.name+"@"+r.version)}`),await n.publish(i,t=>{T.twoColumnDetail(t,w.default.green("PUBLISHED"))})}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate").description("Run all pending migrations.").option("-s, --step [number]","Force the migrations to be run so they can be rolled back individually.").option("-p, --path [path]","The path to the migrations directory.").action(async t=>{this.configPath||this.terminateNotFound();const e=t.path?C.default.join(this.cwd,t.path):this.cwd;try{await new At(e).run(this.config,t,!0)}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate:rollback").description("Rollback the last database migration.").option("-s, --step [number]","The number of migrations to be reverted.").option("-p, --path [path]","The path to the migrations directory.").action(async t=>{this.configPath||this.terminateNotFound();const e=t.path?C.default.join(this.cwd,t.path):this.cwd;try{await new At(e,void 0,(t,e)=>{e&&this.output[e](t)}).rollback(this.config,t,!0)}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate:status").description("Show the status of each migration.").option("-p, --path [path]","The path to the migrations directory.").action(async t=>{this.configPath||this.terminateNotFound();const e=t.path?C.default.join(this.cwd,t.path):this.cwd;try{const s=await new At(e,void 0,(t,e)=>{e&&this.output[e](t)}).status(this.config,t,!0);s.length>0?(T.twoColumnDetail(w.default.gray("Migration name"),w.default.gray("Batch / Status")),s.forEach(t=>{const e=t.ran?`[${t.batch}] ${w.default.green("Ran")}`:w.default.yellow("Pending");T.twoColumnDetail(t.name,e)})):console.log("No migrations found")}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("model:make <name>").description("Create a new Model file.").addOption(new t.Option("-l, --type [string]","Type of migration file to generate.").choices(["js","ts"]).default("js","generates a js migration file")).option("--force","Force creation if model already exists.",!1).option("-p, --path [path]","The path to the models directory.").action(async(t,s)=>{this.configPath||this.terminateNotFound();const i=C.default.join(this.cwd,s.path??this.config.models?.path??"./models",t.toLowerCase()+"."+s.type);try{!s.force&&await T.fileExists(i)&&this.output.error("ERROR: Model already exists."),await e.mkdir(C.default.dirname(i),{recursive:!0});const r=C.default.join(this.modulePath,`src/stubs/model-${s.type}.stub`);let n=await e.readFile(r,"utf-8");n=n.replace(/{{ name }}/g,t),await e.writeFile(i,n),this.output.success(`Created Model: ${i}`)}catch(t){this.output.error("ERROR: "+t)}}),await t.program.parseAsync(process.argv),process.exit(0)}}).init();
|
|
1
|
+
"use strict";var t=require("commander"),e=require("fs/promises"),s=require("chalk"),i=require("escalade/sync"),r=require("path"),n=require("resolve-from"),a=require("radashi"),o=require("dayjs/plugin/advancedFormat.js"),h=require("dayjs"),c=require("knex"),u=require("collect.js"),l=require("pluralize"),g=require("fs"),d=require("url"),y=require("dotenv"),m="undefined"!=typeof document?document.currentScript:null;function f(t){return t&&t.__esModule?t:{default:t}}var p=f(e),w=f(s),b=f(i),C=f(r),v=f(n),P=f(o),K=f(h),N=f(c),R=f(u),A=f(l),x=Object.defineProperty,S=C.default.join,T=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(w.default.green("✓"),this.textFormat(t,w.default.bgGreen),"\n"),e&&process.exit(0)},info:(t,e=!1)=>{console.log(w.default.blue("ℹ"),this.textFormat(t,w.default.bgBlue),"\n"),e&&process.exit(0)},error:(t,e=!0)=>{t instanceof Error?(t.message&&console.error(w.default.red("✖"),this.textFormat(t.message,w.default.bgRed)),console.error(w.default.red(`${t.detail?`${t.detail}\n`:""}${t.stack}`),"\n")):console.error(w.default.red("✖"),this.textFormat(t,w.default.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=C.default.join(i,"package.json"),n=v.default.silent(e??process.cwd(),r);if(n)return C.default.join(C.default.dirname(n),s.join("/"))}static async getMigrationPaths(t,e,s,i){return i?[S(t,i)]:[...e.getPaths(),S(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,w.default.gray(".".repeat(r)),e)}static async fileExists(t){try{return await e.access(t),!0}catch{return!1}}static findUpConfig(t,e,s){return b.default(t,(t,i)=>{for(const t of s){const s=`${e}.${t}`;if(i.includes(s))return s}return!1})}},q=class t{static CREATE_PATTERNS=[/^create_(\w+)_table$/,/^create_(\w+)$/];static CHANGE_PATTERNS=[/.+_(to|from|in)_(\w+)_table$/,/.+_(to|from|in)_(\w+)$/];static guess(e){for(const s of t.CREATE_PATTERNS){const t=e.match(s);if(t)return[t[1],!0]}for(const s of t.CHANGE_PATTERNS){const t=e.match(s);if(t)return[t[2],!1]}return[]}},D=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 k(t){const e=await p.default.readdir(t),s=[];for(const i of e){const e=`${t}/${i}`,r=await p.default.stat(e);if(r.isFile())s.push(e);else if(r.isDirectory()){const t=await k(e);s.push(...t)}}return s}var E=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,w.default.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 k(s));return e.filter(Boolean).reduce((t,e)=>(t[this.getMigrationName(e)]=e,t),{})}getMigrationName(t){return C.default.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,w.default.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(w.default.green(t),w.default.gray(`${Math.floor(r)}ms`),!1!==i?w.default.green("✔"):w.default.red("✘"))}}},M={};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)x(t,s,{get:e[s],enumerable:!0})})(M,{compose:()=>_}),K.default.extend(P.default);var F=t=>a.camel(`relation_${t}`),I=t=>a.camel(`scope_${t}`),O=t=>a.camel(`attribute_${t}`),Q=t=>a.camel(`get_${t}_attribute`),j=(t,e)=>{const s=e(t);return s instanceof Promise?s.then(()=>t):t},{compose:W}=M,$=t=>Array.isArray(t)?t.reduce((t,e)=>t.concat($(e)),[]):[t],B=t=>a.trim(a.snake(t.replace(/[^a-zA-Z0-9_-]/g,"-")),"_-"),L=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}},H=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?.()}},U=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}},J=class extends(W(H,U)){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 Ct?t.attributes[this.ownerKey]:t;return this.child[this.foreignKey]=e,t instanceof Ct?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()}},z=class t extends u.Collection{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,s=null){if(this.isEmpty())return this;const i=(await this.first().newModelQuery().whereIn(this.first().getKeyName(),this.modelKeys()).select(this.first().getKeyName()).withAggregate(t,e,s).get()).keyBy(this.first().getKeyName()),r=a.diff(Object.keys(i.first().getAttributes()),[i.first().getKeyName()]);return this.each(t=>{const e=a.pick(i.get(t.getKey()).getAttributes(),r);t.fill(e).syncOriginalAttributes(...r)}),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 Pt?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=a.omit(this.getDictionary(),t);return new this.constructor(Object.values(e))}intersect(t){const e=new this.constructor;if(a.isEmpty(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 Pt&&(t=t.getKey()),a.isArray(t)?this.isEmpty()?new this.constructor:this.whereIn(this.first().getKeyName(),t):(u.collect(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=a.pick(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}}}},G=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,e=!0){let s,i={attached:[],detached:[],updated:[]};const r=await this.getCurrentlyAttachedPivots(),n=0===r.length?[]:r.map(t=>t.toData()).pluck(this.relatedPivotKey).all().map(t=>String(t)),o=a.diff(n,Object.keys(s=this.formatRecordsList(this.parseIds(t))));return e&&o.length>0&&(await this.detach(o),i.detached=this.castKeys(o)),i=a.assign(i,await this.attachNew(s,n,!1)),i}syncWithoutDetaching(t){return this.sync(t,!1)}syncWithPivotValues(t,e,s=!0){return this.sync(u.collect(this.parseIds(t)).mapWithKeys(t=>[t,e]),s)}withPivot(t){return this.pivotColumns=this.pivotColumns.concat(a.isArray(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 u.collect(t).mapWithKeys((t,e)=>(a.isArray(t)||([e,t]=[t,{}]),[e,t])).all()}async getCurrentlyAttachedPivots(){const t=this.newPivotQuery();return(await t.get()).map(t=>(this.using||vt).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,e,s,i){const[r,n]=this.extractAttachIdAndAttributes(t,e,s);return a.assign(this.baseAttachRecord(r,i),n)}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.isArray(e)?[t,{...e,...s}]:[e,s]}hasPivotColumn(t){return this.pivotColumns.includes(t)}parseIds(t){return t instanceof Ct?[t[this.relatedKey]]:t instanceof z?t.pluck(this.relatedKey).all():a.isArray(t)?t:[t]}},V=class extends Error{constructor(t,e){super(t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t}},Y=class extends V{model;ids=[];constructor(){super("")}setModel(t,e=[]){return this.model=t,this.ids=a.isArray(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}},Z=class extends V{},X=class extends V{},tt=class extends(W(H,G)){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 z([]))}),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 z([])}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 z(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 Y).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=a.omit(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 a.isEqual(t,["*"])&&(t=[this.related.getTable()+".*"]),t.concat(this.aliasedPivotColumns())}aliasedPivotColumns(){const t=[this.foreignPivotKey,this.relatedPivotKey];return u.collect(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 z([])),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)}},et=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 z([]),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 z?t:new z(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)}},st=class t{constructor(){if(this.constructor===t)throw new Error("Scope cannot be instantiated")}apply(t,e){throw new Error("apply not implemented")}},it=class{},rt=class t extends it{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=a.snake(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 e=this.model.getUpdatedAtColumn();return t=a.assign({[e]: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 st?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=I(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=a.omit(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 e={};if("function"==typeof t[1]){const e=this.parseWithRelations({[t[0]]:t[1]});return this.eagerLoad=a.assign(this.eagerLoad,e),this}const s=$(t);if(0===s.length)return this;for(const t of s){let s;"string"==typeof t?s={[t]:t=>t}:"object"==typeof t&&(s=t),e=a.assign(e,s)}return this.eagerLoad=a.assign(this.eagerLoad,this.parseWithRelations(e)),this}has(t,e=">=",s=1,i="and",r=null){if(a.isString(t)){if(t.includes("."))return this.hasNested(t,e,s,i,r);t=this.getRelationWithoutConstraints(F(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,e,s=null){if(0===t.length)return this;t=$([t]);let i={};for(const e of t){let t;"string"==typeof e?t={[e]:t=>t}:"object"==typeof e&&(t=e),i=a.assign(i,t)}t=i;const r=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 n=this.parseWithRelations(t);for(let t in n){const i=n[t],o=t.split(" ");let h,c;3===o.length&&"as"===o[1].toLocaleLowerCase()&&([t,h]=[o[0],o[2]]);const u=this.getRelationWithoutConstraints(F(t));if(s){const t=this.query._single.table===u.query.query._single.table?`${u.getRelationCountHash(!1)}.${e}`:e,i="*"===e?e:u.getRelated().qualifyColumn(t);c="exists"===s?i:`${s}(${i})`}else c=e;const l=u.getRelationExistenceQuery(u.getRelated().newModelQuery(),this,r.raw(c));i(l),h=h||a.snake(`${t} ${s} ${e}`.replace("/[^[:alnum:][:space:]_]/u","")),"exists"===s?this.select(r.raw(`exists(${l.toSql().sql}) as ${h}`)):this.selectSub(s?l:l.limit(1),h)}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 H)return[e.toSql().sql,e.toSql().bindings];if(a.isString(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 H.noConstraints(()=>this.getModel()[t]())}withCount(...t){return this.withAggregate($(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 r=t[i];if(a.isString(r)||Number.isFinite(parseInt(r)))continue;const[n,o]=this.parseNameAndAttributeSelectionConstraint(i,r);s=Object.assign({},s,{[`${e}${n}`]:o},this.prepareNestedWithRelationships(r,`${e}${n}`)),t=a.omit(t,[i])}for(const i in t){const r=t[i];let n=i,o=r;a.isString(r)&&([n,o]=this.parseNameAndAttributeSelectionConstraint(r)),s[`${e}${n}`]=this.combineConstraints([o,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 tt?e.related.getTable()+"."+t:t))}]}related(t){if("function"!=typeof this.model[F(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new Z(e)}return this.model[F(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 Y).setModel(this.model.constructor.name);return e}async findOrFail(...t){const e=await this.find(...t);if(a.isArray(t[0])){if(e.count()!==t[0].length)throw(new Y).setModel(this.model.constructor.name,a.diff(t[0],e.modelKeys()));return e}if(null===e)throw(new Y).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={},e={}){const s=await this.where(t).first();return null!==s?s:this.newModelInstance(a.assign(t,e))}async firstOrCreate(t={},e={}){const s=await this.where(t).first();return null!==s?s:j(this.newModelInstance(a.assign(t,e)),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.isArray(t)||t instanceof z?await this.findMany(t,e):await this.where(this.model.getKeyName(),t).first(e)}async findMany(t,e=["*"]){return t instanceof z&&(t=t.modelKeys()),0===(t=a.isArray(t)?t:[t]).length?new z([]):await this.whereIn(this.model.getKeyName(),t).get(e)}async pluck(t){const e=await this.query.pluck(t);return new z(e)}async destroy(t){if(t instanceof z&&(t=t.modelKeys()),t instanceof u.Collection&&(t=t.all()),0===(t=a.isArray(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 z(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 et(r,parseInt(i),e,t)}async getModels(...t){return(t=a.flat(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[F(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new Z(e)}const e=H.noConstraints(()=>this.model.newInstance(this.model.attributes)[F(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 z(t.map(t=>{if(!this.model)return t;return this.model.newFromBuilder(t)}))}},nt=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")}},at=t=>class extends t{static castTypeCache={};attributes={};original={};casts={};changes={};appends=[];setAppends(t){return this.appends=t,this}append(...t){const e=$(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=$(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=$(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=(i=t,a.camel(`set_${i}_attribute`));var i;if("function"==typeof this[s])return this[s](e),this;const r=O(t);if("function"==typeof this[r]){const s=this[r]().set||(e=>{this.attributes[t]=e});return this.attributes={...this.attributes,...this.normalizeCastClassResponse(t,s(e,this.attributes))},this}const n=this.getCasts()[t];return this.isCustomCast(n)&&"string"!=typeof n&&(e=n.set(this,t,e,this.attributes)??""),"json"===n&&(e=JSON.stringify(e)),"collection"===n&&(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=Q(t);if("function"==typeof this[e])return this[e](this.attributes[t],this.attributes);const s=O(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 R.default(JSON.parse(e))}catch{return R.default([])}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=a.omit(t,[e])),this.visible.length>0&&!1===this.visible.includes(e)&&(t=a.omit(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]=K.default(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[Q(t)])return this[Q(t)](e);if("function"==typeof this[O(t)]){return this[O(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?K.default(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 nt&&(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=a.flat(e)).length>0)||e.includes(this.getCastType(t)))}withDayjs(t){return K.default(t)}isCustomCast(t){return"function"==typeof t&&new t instanceof nt}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 K.default(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 K.default(e).startOf("day").toDate()}},ot=t=>class extends t{static globalScopes;static addGlobalScope(t,e=null){if("string"==typeof t&&e instanceof st)return this.globalScopes=a.set(this.globalScopes??{},this.name+"."+t,e),e;if(t instanceof st)return this.globalScopes=a.set(this.globalScopes??{},this.name+"."+t.constructor.name,t),t;throw new X("Global scope must be an instance of Scope.")}static hasGlobalScope(t){return null!==this.getGlobalScope(t)}static getGlobalScope(t){return"string"==typeof t?a.get(this.globalScopes,this.name+"."+t):a.get(this.globalScopes,this.name+"."+t.constructor.name)}static getAllGlobalScopes(){return this.globalScopes}static setAllGlobalScopes(t){this.globalScopes=t}getGlobalScopes(){return a.get(this.constructor.globalScopes,this.constructor.name,{})}},ht=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}},ct=t=>class extends t{static hooks=null;static addHook(t,e){this.hooks instanceof ht==!1&&(this.hooks=new ht),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 ht!=!1)return await this.constructor.hooks.exec(t,[this,e])}},ut=t=>class extends t{getRelationValue(t,e,s){const i=t[e];return"one"===s?i[0]:new z(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 R.default(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 z?t:new z(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 z?e:new z(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(W(H,ut)){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 z([]))}),t}async getResults(){return null!==this.getParentKey()?await this.query.get():new z([])}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}buildDictionary(t){const e=this.getForeignKeyName();return u.collect(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))}},gt=class extends(W(H,ut,U)){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])}},dt=class extends H{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 Y).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.isArray(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 Y).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}},yt=class extends(W(dt,U)){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()}},mt=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=a.omit(this.relations,[t]),this}relationLoaded(t){return void 0!==this.relations[t]}related(t){if("function"!=typeof this[F(t)]){const e=`Model [${this.constructor.name}]'s relation [${t}] doesn't exist.`;throw new Z(e)}return this[F(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 e=t,a.snake(e.substring(8));var e}joiningTable(t,e=null){return[e?e.joiningTableSegment():B(t.name),this.joiningTableSegment()].sort().join("_").toLocaleLowerCase()}joiningTableSegment(){return B(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 gt(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 J(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 tt(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 yt(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 dt(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}},ft=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())}},pt=t=>class extends t{hidden=[];visible=[];makeVisible(...t){const e=$(t);return this.visible.length>0&&(this.visible=[...this.visible,...e]),this.hidden=a.diff(this.hidden,e),this}makeHidden(t,...e){const s=$([...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}},wt=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())}},bt=W(class{},at,pt,mt,ft,ct,ot,wt),Ct=class t extends bt{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[F(s)])e.setAttribute(s,t[s]);else{const i=e[F(s)](),r=i.getRelated().constructor;i instanceof gt||i instanceof J?e.setRelation(s,r.make(t[s])):(i instanceof lt||i instanceof tt)&&Array.isArray(t[s])&&e.setRelation(s,new z(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 B(this.constructor.name)+"_"+this.getKeyName()}getConnectionName(){return this.connection}getTable(){return this.table||A.default(B(this.constructor.name))}getConnection(){return this.constructor.resolver?this.constructor.resolver.getConnection(this.connection):Rt.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[I(t)]}callNamedScope(t,e){return this[I(t)](...e)}setTable(t){return this.table=t,this}newCollection(t=[]){return new z(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 z([this]).loadAggregate(t,e,s),this}async loadCount(...t){return t=$(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 a.assign(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(R.default(this.relations).reject(t=>t instanceof vt).keys().all()),this.syncOriginal(),this}newPivot(t,e,s,i,r=null){return r?r.fromRawAttributes(t,e,s,i):vt.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 z?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)}},vt=class extends Ct{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]}},Pt=Ct,Kt=class{},Nt=class t extends Kt{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 et(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}},Rt=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 connection(t=null){return this.getInstance().getConnection(t)}static setConnectorFactory(t){this.connectorFactory=t}static getConnectorFactory(){return this.connectorFactory??N.default}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 Nt(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=C.default.resolve("arquebus.config.js"),i=C.default.resolve("arquebus.config.ts"),r=this.getInstance();if(g.existsSync(s))return e=(await import(s)).default,t&&r.addConnection(e,e.client),e;if(g.existsSync(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=Ct;if("plugins"in e&&(s=W(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 L==!1)throw new Error('Attribute must be an instance of "Attribute"');this.models[t].prototype[O(s)]=()=>e.attributes?.[s]}if("relations"in e)for(const s in e.relations)this.models[t].prototype[F(s)]=function(){return e.relations?.[s](this)};if("scopes"in e)for(const s in e.scopes)this.models[t].prototype[I(s)]=e.scopes[s];return this.models[t].setConnectionResolver(this),this.models[t]}},At=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 T.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 T.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 T.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&&(Rt.addConnection(t,"default"),Object.entries(t.connections||{}).forEach(([t,e])=>{Rt.addConnection(e,t)}));const s=new D(Rt,e),i=new E(s,Rt);return{arquebus:Rt,migrator:i}}},xt=class{constructor(t,e="js"){this.customStubPath=t,this.type=e}postCreate=[];async create(t,e,s,i=!1){const r=this.getStub(s,i),n=this.getPath(t,e);return await this.ensureDirectoryExists(C.default.dirname(n)),await p.default.writeFile(n,this.populateStub(r,s)),await this.firePostCreateHooks(s,n),n}async publish(t,e){const s=await p.default.readdir(this.customStubPath??"");await this.ensureDirectoryExists(t);for(const i of s){const s=C.default.join(this.customStubPath??"",i),r=C.default.join(t,i);await p.default.copyFile(s,r),e&&e(i,s,r)}}getStub(t,e=!1){let s;if(t)if(e){const t=C.default.join(this.customStubPath??"",`migration.create-${this.type}.stub`);s=g.existsSync(t)?t:this.stubPath(`/migration.create-${this.type}.stub`)}else{const t=C.default.join(this.customStubPath??"",`migration.update-${this.type}.stub`);s=g.existsSync(t)?t:this.stubPath(`/migration.update-${this.type}.stub`)}else{const t=C.default.join(this.customStubPath??"",`migration-${this.type}.stub`);console.log("\n",t,"---"),s=g.existsSync(t)?t:this.stubPath(`/migration-${this.type}.stub`)}return g.readFileSync(s,"utf-8")}populateStub(t,e){return null!==e&&(t=t.replace(/DummyTable|{{\s*table\s*}}/g,e)),t}getClassName(t){return t.replace(/_+([a-z])/g,(t,e)=>e.toUpperCase())}getPath(t,e){const s=K.default().format("YYYY_MM_DD_HHmmss");return C.default.join(e,`${s}_${t}.${this.type}`)}async firePostCreateHooks(t,e){for(const s of this.postCreate)await s(t,e)}afterCreate(t){this.postCreate.push(t)}async ensureDirectoryExists(t){await p.default.mkdir(t,{recursive:!0})}stubPath(t=""){const e=this.getDirname({url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href});return C.default.join(e,"stubs",t)}getDirname(t){if("undefined"!=typeof __dirname)return __dirname;if(t&&t.url)return r.dirname(d.fileURLToPath(t.url));throw new Error("Unable to determine dirname")}},St="0.2.14";(class s{cwd;output=T.output();config={};basePath="";modulePath;configPath;modulePackage;constructor(t){this.basePath=t??("true"===process.env.TEST?"test/cli":"")}terminateNotFound(){this.output.error(`ERROR: Arquebus config not found. Run ${w.default.italic.black.bgGray("arquebus init")} first.`)}static init(){y.config({quiet:!0});const t=new s;Promise.all([t.loadPaths(),t.loadConfig()]).then(([t,e])=>e.run())}async loadPaths(){this.cwd=C.default.join(process.cwd(),this.basePath),this.configPath=T.findUpConfig(this.cwd,"arquebus.config",["js","ts","cjs"])??void 0,this.modulePath=T.findModulePkg("@h3ravel/arquebus",this.cwd)??"";try{this.modulePackage=await import(C.default.join(this.modulePath,"package.json"))}catch{this.modulePackage={version:"N/A"}}return this}async loadConfig(){try{this.config=(await import(this.configPath??"----")).default,this.config.migrations?.path&&await e.mkdir(C.default.join(this.cwd,this.config.migrations?.path),{recursive:!0})}catch{this.config={}}return this}async run(){const s=["Arquebus CLI version:",w.default.green(St)].join(" "),i=["Arquebus Local version:",w.default.green(this.modulePackage.version||"None")].join(" ");t.program.name("arquebus").version(`${s}\n${i}`),t.program.command("init").description("Create a fresh Arquebus config.").addArgument(new t.Argument("[type]","Type of config to generate.").choices(["js","ts"]).default("js","generates a js config")).action(async t=>{this.modulePath||this.output.error(["ERROR: No local arquebus install found"," Try running: npm install arquebus --save"]),this.configPath&&this.output.error(`ERROR: ${this.configPath} already exists`);try{const s=`./arquebus.config.${t}`,i=await e.readFile(C.default.join(this.modulePath,`/src/stubs/arquebus.config-${t}.stub`),{encoding:"utf8"});await e.writeFile(C.default.join(this.cwd,s),i),this.output.success(`Initialized: Arquebus has been initialized as ${s}`)}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate:make <name>").description("Create a new migration file.").addOption(new t.Option("-l, --type [string]","Type of migration file to generate.").choices(["js","ts"]).default("js","generates a js migration file")).option("-t, --table [string]","The table to migrate").option("-c, --create [string]","The table to be created").option("-p, --path [path]","The path to the migrations directory.").action(async(t,e)=>{this.configPath||this.terminateNotFound();try{t=a.snake(t);const s=C.default.join(this.cwd,e.path??this.config.migrations?.path??"./migrations");let i=e.table,r=e.create||!1;if(i||"string"!=typeof r||(i=r,r=!0),!i){const e=q.guess(t);i=e[0],r=!!e[1]}this.output.info("INFO: Creating Migration");const n=new xt(void 0,e.type),o=await n.create(t,s,i,r);this.output.success(`INFO: Migration Created \n ${w.default.gray(C.default.basename(o))}`,!0)}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate:publish <package>").description("Publish any migration files from packages.").option("-p, --path [path]","The path to the migrations directory.").action(async(t,e)=>{this.configPath||this.terminateNotFound();try{const s=T.findModulePkg(t)??"",i=C.default.join(this.cwd,e.path??this.config.migrations?.path??"./migrations"),r=await import(C.default.join(s,"package.json"));s||this.output.error(`ERROR: package ${t} not found`);const n=new xt(C.default.join(s,r.migrations??"migrations"));this.output.info(`INFO: Publishing migrations from ${w.default.italic.gray(r.name+"@"+r.version)}`),await n.publish(i,t=>{T.twoColumnDetail(t,w.default.green("PUBLISHED"))})}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate").description("Run all pending migrations.").option("-s, --step [number]","Force the migrations to be run so they can be rolled back individually.").option("-p, --path [path]","The path to the migrations directory.").action(async t=>{this.configPath||this.terminateNotFound();const e=t.path?C.default.join(this.cwd,t.path):this.cwd;try{await new At(e).run(this.config,t,!0)}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate:rollback").description("Rollback the last database migration.").option("-s, --step [number]","The number of migrations to be reverted.").option("-p, --path [path]","The path to the migrations directory.").action(async t=>{this.configPath||this.terminateNotFound();const e=t.path?C.default.join(this.cwd,t.path):this.cwd;try{await new At(e,void 0,(t,e)=>{e&&this.output[e](t)}).rollback(this.config,t,!0)}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("migrate:status").description("Show the status of each migration.").option("-p, --path [path]","The path to the migrations directory.").action(async t=>{this.configPath||this.terminateNotFound();const e=t.path?C.default.join(this.cwd,t.path):this.cwd;try{const s=await new At(e,void 0,(t,e)=>{e&&this.output[e](t)}).status(this.config,t,!0);s.length>0?(T.twoColumnDetail(w.default.gray("Migration name"),w.default.gray("Batch / Status")),s.forEach(t=>{const e=t.ran?`[${t.batch}] ${w.default.green("Ran")}`:w.default.yellow("Pending");T.twoColumnDetail(t.name,e)})):console.log("No migrations found")}catch(t){this.output.error("ERROR: "+t)}}),t.program.command("model:make <name>").description("Create a new Model file.").addOption(new t.Option("-l, --type [string]","Type of migration file to generate.").choices(["js","ts"]).default("js","generates a js migration file")).option("--force","Force creation if model already exists.",!1).option("-p, --path [path]","The path to the models directory.").action(async(t,s)=>{this.configPath||this.terminateNotFound();const i=C.default.join(this.cwd,s.path??this.config.models?.path??"./models",t.toLowerCase()+"."+s.type);try{!s.force&&await T.fileExists(i)&&this.output.error("ERROR: Model already exists."),await e.mkdir(C.default.dirname(i),{recursive:!0});const r=C.default.join(this.modulePath,`src/stubs/model-${s.type}.stub`);let n=await e.readFile(r,"utf-8");n=n.replace(/{{ name }}/g,t),await e.writeFile(i,n),this.output.success(`Created Model: ${i}`)}catch(t){this.output.error("ERROR: "+t)}}),await t.program.parseAsync(process.argv),process.exit(0)}}).init();
|