arcanajs 5.0.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/arcanajs.js.map +1 -1
- package/dist/arcanox.js +1 -1
- package/dist/arcanox.js.map +1 -1
- package/dist/cli/index.js +2 -1
- package/dist/cli/index.js.LICENSE.txt +14 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/lib/arcanox/Model.d.ts +7 -0
- package/dist/lib/arcanox/schema/Schema.d.ts +11 -0
- package/dist/lib/arcanox/types.d.ts +4 -2
- package/dist/lib/server/ArcanaJSServer.d.ts +0 -34
- package/dist/lib/server/DynamicRouter.d.ts +1 -1
- package/dist/types/express.d.ts +45 -0
- package/dist/types/global.d.ts +1 -0
- package/package.json +4 -1
package/dist/arcanox.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(()=>{"use strict";var __webpack_modules__={14:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{dynamicRequire:()=>dynamicRequire});const dynamicRequire=id=>{try{var _global$process;const e=global,t=null===(_global$process=e.process)||void 0===_global$process||null===(_global$process=_global$process.mainModule)||void 0===_global$process?void 0:_global$process.require;if(t)return t(id)}catch(e){}return eval("require")(id)}},590:(e,t,i)=>{i.d(t,{PostgresAdapter:()=>s});var r=i(14);class s{pool=null;client=null;async connect(e){var t,i;const{Pool:s}=(0,r.dynamicRequire)("pg");return this.pool=new s({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,ssl:e.ssl,min:(null===(t=e.pool)||void 0===t?void 0:t.min)||2,max:(null===(i=e.pool)||void 0===i?void 0:i.max)||10}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(e,t)).rows}async execute(e,t){if(!this.pool)throw new Error("Database not connected");return await this.pool.query(e,t)}async createTable(e,t){const i=`CREATE TABLE IF NOT EXISTS "${e}" (${t.map(e=>{let t=`"${e.name}" ${this.mapType(e.type,e.length)}`;return e.primary&&(t+=" PRIMARY KEY"),e.autoIncrement&&(t+=" GENERATED ALWAYS AS IDENTITY"),e.nullable||(t+=" NOT NULL"),e.unique&&(t+=" UNIQUE"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),t}).join(", ")})`;await this.execute(i)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS "${e}"`)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.tables \n WHERE table_schema = 'public' \n AND table_name = $1\n )",[e]))[0])||void 0===t?void 0:t.exists)||!1}async hasColumn(e,t){var i;return(null===(i=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.columns \n WHERE table_schema = 'public' \n AND table_name = $1 \n AND column_name = $2\n )",[e,t]))[0])||void 0===i?void 0:i.exists)||!1}async select(e,t){var i;let r=`SELECT ${(null===(i=t.columns)||void 0===i?void 0:i.join(", "))||"*"} FROM "${e}"`;const s=[];let a=1;if(t.joins&&t.joins.length>0)for(const e of t.joins)r+=` ${e.type} JOIN "${e.table}" ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(r+=" "+t.where.map((e,t)=>{const i=0===t?"WHERE":e.boolean,r=this.buildWhereCondition(e,s,a);return a=s.length+1,`${i} ${r}`}).join(" ")),t.orderBy&&t.orderBy.length>0&&(r+=` ORDER BY ${t.orderBy.map(e=>`"${e.column}" ${e.direction}`).join(", ")}`),t.limit&&(r+=" LIMIT $"+a++,s.push(t.limit)),t.offset&&(r+=" OFFSET $"+a++,s.push(t.offset)),await this.query(r,s)}async insert(e,t){const i=Object.keys(t),r=Object.values(t),s=r.map((e,t)=>`$${t+1}`).join(", "),a=`INSERT INTO "${e}" (${i.map(e=>`"${e}"`).join(", ")}) \n VALUES (${s}) \n RETURNING *`;return(await this.query(a,r))[0]}async update(e,t,i){const r=Object.keys(i),s=Object.values(i),a=`UPDATE "${e}" SET ${r.map((e,t)=>`"${e}" = $${t+1}`).join(", ")} WHERE id = $${r.length+1} RETURNING *`;return(await this.query(a,[...s,t]))[0]}async delete(e,t){const i=`DELETE FROM "${e}" WHERE id = $1`;return(await this.execute(i,[t])).rowCount>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.client=await this.pool.connect(),await this.client.query("BEGIN")}async commit(){if(!this.client)throw new Error("No active transaction");await this.client.query("COMMIT"),this.client.release(),this.client=null}async rollback(){if(!this.client)throw new Error("No active transaction");await this.client.query("ROLLBACK"),this.client.release(),this.client=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(e,t)).rows}buildWhereCondition(e,t,i){const r=`"${e.column}"`;switch(e.operator){case"IN":const s=e.value.map((e,t)=>`$${i+t}`).join(", ");return t.push(...e.value),`${r} IN (${s})`;case"NOT IN":const a=e.value.map((e,t)=>`$${i+t}`).join(", ");return t.push(...e.value),`${r} NOT IN (${a})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${r} BETWEEN $${i} AND $${i+1}`;case"IS NULL":return`${r} IS NULL`;case"IS NOT NULL":return`${r} IS NOT NULL`;default:return t.push(e.value),`${r} ${e.operator} $${i}`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INTEGER",bigInteger:"BIGINT",float:"REAL",double:"DOUBLE PRECISION",decimal:"DECIMAL",boolean:"BOOLEAN",date:"DATE",datetime:"TIMESTAMP",timestamp:"TIMESTAMP",json:"JSONB",uuid:"UUID"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"TRUE":"FALSE":e instanceof Date?`'${e.toISOString()}'`:String(e)}}},697:(e,t,i)=>{i.d(t,{MongoAdapter:()=>s});var r=i(14);class s{client=null;db=null;async connect(e){const{MongoClient:t}=(0,r.dynamicRequire)("mongodb"),i=`mongodb://${e.host}:${e.port}`;return this.client=new t(i,{auth:e.username&&e.password?{username:e.username,password:e.password}:void 0}),await this.client.connect(),this.db=this.client.db(e.database),{query:async(e,t)=>{throw new Error("Raw SQL queries are not supported in MongoDB adapter")},execute:async(e,t)=>{throw new Error("Raw SQL execution is not supported in MongoDB adapter")},close:async()=>{await this.disconnect()}}}async disconnect(){this.client&&(await this.client.close(),this.client=null,this.db=null)}async createTable(e,t){if(!this.db)throw new Error("Database not connected");await this.db.createCollection(e)}async dropTable(e){if(!this.db)throw new Error("Database not connected");await this.db.collection(e).drop()}async hasTable(e){if(!this.db)throw new Error("Database not connected");return(await this.db.listCollections({name:e}).toArray()).length>0}async hasColumn(e,t){return!0}async select(e,t){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(e),r=this.buildFilter(t.where||[]),s=this.buildProjection(t.columns);let a=i.find(r);if(s&&(a=a.project(s)),t.orderBy){const e={};t.orderBy.forEach(t=>{e[t.column]="ASC"===t.direction?1:-1}),a=a.sort(e)}return t.offset&&(a=a.skip(t.offset)),t.limit&&(a=a.limit(t.limit)),(await a.toArray()).map(e=>{const{_id:t,...i}=e;return{id:t,_id:t,...i}})}async insert(e,t){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(e),r={...t};r.id&&(r._id=r.id,delete r.id);const s=await i.insertOne(r);return{id:s.insertedId,_id:s.insertedId,...t}}async update(e,t,i){if(!this.db)throw new Error("Database not connected");const r=this.db.collection(e),s={_id:this.normalizeId(t)},a={$set:i};await r.updateOne(s,a);const n=await r.findOne(s);if(n){const{_id:e,...t}=n;return{id:e,_id:e,...t}}return null}async delete(e,t){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(e);return 1===(await i.deleteOne({_id:this.normalizeId(t)})).deletedCount}async beginTransaction(){}async raw(e,t=[]){if(!this.db)throw new Error("Database not connected");return"db"===e?this.db:await this.db.command(JSON.parse(e))}async commit(){}async rollback(){}buildFilter(e){const t={};return e.forEach(e=>{const i="id"===e.column?"_id":e.column;let r=e.value;switch("_id"===i&&(r=this.normalizeId(r)),e.operator){case"=":t[i]=r;break;case"!=":t[i]={$ne:r};break;case">":t[i]={$gt:r};break;case"<":t[i]={$lt:r};break;case">=":t[i]={$gte:r};break;case"<=":t[i]={$lte:r};break;case"IN":t[i]={$in:Array.isArray(r)?r:[r]};break;case"NOT IN":t[i]={$nin:Array.isArray(r)?r:[r]};break;case"LIKE":t[i]={$regex:new RegExp(r.replace(/%/g,".*"),"i")};break;case"IS NULL":t[i]=null;break;case"IS NOT NULL":t[i]={$ne:null}}}),t}buildProjection(e){if(!e||0===e.length||e.includes("*"))return null;const t={};return e.forEach(e=>{"id"===e||(t[e]=1)}),t}normalizeId(e){const{ObjectId:t}=(0,r.dynamicRequire)("mongodb");return e instanceof t?e:"string"==typeof e&&t.isValid(e)?new t(e):e}}},707:(e,t,i)=>{i.d(t,{MySQLAdapter:()=>s});var r=i(14);class s{pool=null;connection=null;async connect(e){var t;const i=(0,r.dynamicRequire)("mysql2/promise");return this.pool=i.createPool({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,waitForConnections:!0,connectionLimit:(null===(t=e.pool)||void 0===t?void 0:t.max)||10,queueLimit:0}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){if(!this.pool)throw new Error("Database not connected");const[i]=await this.pool.query(e,t);return i}async execute(e,t){if(!this.pool)throw new Error("Database not connected");const[i]=await this.pool.execute(e,t);return i}async createTable(e,t){const i=`CREATE TABLE IF NOT EXISTS \`${e}\` (${t.map(e=>{let t=`\`${e.name}\` ${this.mapType(e.type,e.length)}`;return e.unsigned&&(t+=" UNSIGNED"),e.autoIncrement&&(t+=" AUTO_INCREMENT"),e.nullable||(t+=" NOT NULL"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),e.primary&&(t+=" PRIMARY KEY"),e.unique&&(t+=" UNIQUE"),t}).join(", ")}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`;await this.execute(i)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS \`${e}\``)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT COUNT(*) as count FROM information_schema.tables \n WHERE table_schema = DATABASE() AND table_name = ?",[e]))[0])||void 0===t?void 0:t.count)>0}async hasColumn(e,t){var i;return(null===(i=(await this.query("SELECT COUNT(*) as count FROM information_schema.columns \n WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?",[e,t]))[0])||void 0===i?void 0:i.count)>0}async select(e,t){var i;let r=`SELECT ${(null===(i=t.columns)||void 0===i?void 0:i.join(", "))||"*"} FROM \`${e}\``;const s=[];if(t.joins&&t.joins.length>0)for(const e of t.joins)r+=` ${e.type} JOIN \`${e.table}\` ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(r+=" "+t.where.map((e,t)=>`${0===t?"WHERE":e.boolean} ${this.buildWhereCondition(e,s)}`).join(" ")),t.orderBy&&t.orderBy.length>0&&(r+=` ORDER BY ${t.orderBy.map(e=>`\`${e.column}\` ${e.direction}`).join(", ")}`),t.limit&&(r+=" LIMIT ?",s.push(t.limit)),t.offset&&(r+=" OFFSET ?",s.push(t.offset)),await this.query(r,s)}async insert(e,t){const i=Object.keys(t),r=Object.values(t),s=r.map(()=>"?").join(", "),a=`INSERT INTO \`${e}\` (${i.map(e=>`\`${e}\``).join(", ")}) VALUES (${s})`;return{id:(await this.execute(a,r)).insertId,...t}}async update(e,t,i){const r=Object.keys(i),s=Object.values(i),a=`UPDATE \`${e}\` SET ${r.map(e=>`\`${e}\` = ?`).join(", ")} WHERE id = ?`;return await this.execute(a,[...s,t]),{id:t,...i}}async delete(e,t){const i=`DELETE FROM \`${e}\` WHERE id = ?`;return(await this.execute(i,[t])).affectedRows>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.connection=await this.pool.getConnection(),await this.connection.beginTransaction()}async commit(){if(!this.connection)throw new Error("No active transaction");await this.connection.commit(),this.connection.release(),this.connection=null}async rollback(){if(!this.connection)throw new Error("No active transaction");await this.connection.rollback(),this.connection.release(),this.connection=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");const[i]=await this.pool.execute(e,t);return i}buildWhereCondition(e,t){const i=`\`${e.column}\``;switch(e.operator){case"IN":const r=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${i} IN (${r})`;case"NOT IN":const s=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${i} NOT IN (${s})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${i} BETWEEN ? AND ?`;case"IS NULL":return`${i} IS NULL`;case"IS NOT NULL":return`${i} IS NOT NULL`;default:return t.push(e.value),`${i} ${e.operator} ?`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INT",bigInteger:"BIGINT",float:"FLOAT",double:"DOUBLE",decimal:"DECIMAL(10,2)",boolean:"TINYINT(1)",date:"DATE",datetime:"DATETIME",timestamp:"TIMESTAMP",json:"JSON",uuid:"CHAR(36)"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"1":"0":e instanceof Date?`'${e.toISOString().slice(0,19).replace("T"," ")}'`:String(e)}}},896:e=>{e.exports=require("fs")},928:e=>{e.exports=require("path")},941:e=>{e.exports=require("@faker-js/faker")}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](i,i.exports,__webpack_require__),i.exports}getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var i=Object.create(null);__webpack_require__.r(i);var r={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;("object"==typeof s||"function"==typeof s)&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach(t=>r[t]=()=>e[t]);return r.default=()=>e,__webpack_require__.d(i,r),i},__webpack_require__.d=(e,t)=>{for(var i in t)__webpack_require__.o(t,i)&&!__webpack_require__.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{BelongsTo:()=>BelongsTo,BelongsToMany:()=>BelongsToMany,Blueprint:()=>Blueprint,DatabaseProvider:()=>DatabaseProvider,Factory:()=>Factory,HasMany:()=>HasMany,HasOne:()=>HasOne,Macroable:()=>Macroable,Migration:()=>Migration,MigrationRunner:()=>MigrationRunner,Model:()=>Model,MongoAdapter:()=>MongoAdapter.MongoAdapter,MySQLAdapter:()=>MySQLAdapter.MySQLAdapter,PostgresAdapter:()=>PostgresAdapter.PostgresAdapter,QueryBuilder:()=>QueryBuilder,Relation:()=>Relation,Schema:()=>Schema,Seeder:()=>Seeder});var MongoAdapter=__webpack_require__(697),MySQLAdapter=__webpack_require__(707),PostgresAdapter=__webpack_require__(590);class Macroable{static macros={};static macro(e,t){this.macros[e]=t,this.prototype[e]=t}static mixin(e){Object.keys(e).forEach(t=>{this.macro(t,e[t])})}static hasMacro(e){return!!this.macros[e]}}class QueryBuilder extends Macroable{selectColumns=["*"];whereClauses=[];orderByClauses=[];joinClauses=[];constructor(e,t){super(),this.tableName=e,this.adapter=t}select(...e){return this.selectColumns=e,this}where(e,t,i){return void 0===i&&(i=t,t="="),this.whereClauses.push({column:e,operator:t,value:i,boolean:"AND"}),this}orWhere(e,t,i){return void 0===i&&(i=t,t="="),this.whereClauses.push({column:e,operator:t,value:i,boolean:"OR"}),this}whereIn(e,t){return this.whereClauses.push({column:e,operator:"IN",value:t,boolean:"AND"}),this}whereNotIn(e,t){return this.whereClauses.push({column:e,operator:"NOT IN",value:t,boolean:"AND"}),this}whereBetween(e,t){return this.whereClauses.push({column:e,operator:"BETWEEN",value:t,boolean:"AND"}),this}whereNull(e){return this.whereClauses.push({column:e,operator:"IS NULL",value:null,boolean:"AND"}),this}whereNotNull(e){return this.whereClauses.push({column:e,operator:"IS NOT NULL",value:null,boolean:"AND"}),this}orderBy(e,t="ASC"){return this.orderByClauses.push({column:e,direction:t.toUpperCase()}),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}join(e,t,i,r,s="INNER"){return this.joinClauses.push({type:s,table:e,first:t,operator:i,second:r}),this}leftJoin(e,t,i,r){return this.join(e,t,i,r,"LEFT")}rightJoin(e,t,i,r){return this.join(e,t,i,r,"RIGHT")}eagerLoads=[];setModel(e){return this.model=e,this}with(e){return Array.isArray(e)?this.eagerLoads.push(...e):this.eagerLoads.push(e),this}async get(){const e={columns:this.selectColumns,where:this.whereClauses,orderBy:this.orderByClauses,limit:this.limitValue,offset:this.offsetValue,joins:this.joinClauses},t=await this.adapter.select(this.tableName,e);return this.eagerLoads.length>0&&this.model?await this.eagerLoadRelations(t):t}async eagerLoadRelations(e){if(0===e.length)return e;const t=e.map(e=>this.model.hydrate(e));for(const e of this.eagerLoads){const i=new this.model;if("function"!=typeof i[e])throw new Error(`Relation ${e} does not exist on ${this.model.name}`);const r=i[e]();r.addEagerConstraints(t);const s=await r.get();r.match(t,s,e)}return t}async first(){return this.limit(1),(await this.get())[0]||null}async find(e){return this.where("id",e).first()}async count(){this.selectColumns=["COUNT(*) as count"];const e=await this.first();return e?e.count:0}async pluck(e){return this.select(e),(await this.get()).map(t=>t[e])}async sum(e){this.selectColumns=[`SUM(${e}) as sum`];const t=await this.first();return t&&t.sum||0}async avg(e){this.selectColumns=[`AVG(${e}) as avg`];const t=await this.first();return t&&t.avg||0}async min(e){this.selectColumns=[`MIN(${e}) as min`];const t=await this.first();return t?t.min:null}async max(e){this.selectColumns=[`MAX(${e}) as max`];const t=await this.first();return t?t.max:null}async exists(){return await this.count()>0}async paginate(e=1,t=15){const i=await this.count(),r=(e-1)*t;return this.limit(t).offset(r),{data:await this.get(),total:i,perPage:t,currentPage:e,lastPage:Math.ceil(i/t)}}clone(){const e=new QueryBuilder(this.tableName,this.adapter);return e.selectColumns=[...this.selectColumns],e.whereClauses=[...this.whereClauses],e.orderByClauses=[...this.orderByClauses],e.joinClauses=[...this.joinClauses],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e}}class Relation{constructor(e,t){this.query=e,this.parent=t,this.related=e.model,this.addConstraints()}getQuery(){return this.query}async get(){return this.query.get()}async first(){return this.query.first()}}class BelongsTo extends Relation{constructor(e,t,i,r){super(e,t),this.foreignKey=i,this.ownerKey=r}addConstraints(){const e=this.parent.getAttribute(this.foreignKey);this.query.where(this.ownerKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.foreignKey)).filter(e=>null!==e);this.query.whereIn(this.ownerKey,t)}match(e,t,i){const r={};return t.forEach(e=>{const t=e.getAttribute(this.ownerKey);r[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.foreignKey);r[t]&&e.setRelation(i,r[t])}),e}}class BelongsToMany extends Relation{constructor(e,t,i,r,s,a,n){super(e,t),this.table=i,this.foreignPivotKey=r,this.relatedPivotKey=s,this.parentKey=a,this.relatedKey=n}addConstraints(){this.performJoin(),this.query.where(`${this.table}.${this.foreignPivotKey}`,"=",this.parent.getAttribute(this.parentKey))}performJoin(e){const t=e||this.query,i=this.related.prototype.getTable();return t.join(this.table,`${i}.${this.relatedKey}`,"=",`${this.table}.${this.relatedPivotKey}`),this}addEagerConstraints(e){this.performJoin();const t=e.map(e=>e.getAttribute(this.parentKey)).filter(e=>null!==e);this.query.whereIn(`${this.table}.${this.foreignPivotKey}`,t)}match(e,t,i){return e}}class HasMany extends Relation{constructor(e,t,i,r){super(e,t),this.foreignKey=i,this.localKey=r}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,i){const r={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);r[t]||(r[t]=[]),r[t].push(e)}),e.forEach(e=>{const t=e.getAttribute(this.localKey);r[t]?e.setRelation(i,r[t]):e.setRelation(i,[])}),e}}class HasOne extends Relation{constructor(e,t,i,r){super(e,t),this.foreignKey=i,this.localKey=r}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,i){const r={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);r[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.localKey);r[t]&&e.setRelation(i,r[t])}),e}}class Model extends Macroable{static primaryKey="id";static connection="default";attributes={};original={};relations={};exists=!1;fillable=[];guarded=["id"];hidden=[];visible=[];casts={};dates=[];timestamps=!0;createdAt="created_at";updatedAt="updated_at";softDeletes=!1;deletedAt="deleted_at";static setAdapter(e){this.adapter=e}static getTable(){if(this.tableName)return this.tableName;const e=this.name;return this.pluralize(this.snakeCase(e))}static query(){return new QueryBuilder(this.getTable(),this.adapter)}static async all(){return(await this.query().get()).map(e=>this.hydrate(e))}static async find(e){const t=await this.query().where(this.primaryKey,e).first();return t?this.hydrate(t):null}static async findOrFail(e){const t=await this.find(e);if(!t)throw new Error(`Model not found with ${this.primaryKey}: ${e}`);return t}static where(e,t,i){return this.query().where(e,t,i)}static async create(e){const t=new this;if(t.fill(e),t.timestamps){const e=new Date;t.attributes[t.createdAt]=e,t.attributes[t.updatedAt]=e}const i=await this.adapter.insert(this.getTable(),t.attributes),r=i[this.primaryKey]||i.id||i.insertId;return t.attributes[this.primaryKey]=r,"id"!==this.primaryKey&&(t.attributes.id=r),t.exists=!0,t.syncOriginal(),t}static async update(e,t){const i=await this.findOrFail(e);return await i.update(t),i}static async destroy(e){const t=await this.find(e);return!!t&&await t.delete()}static async firstOrCreate(e,t={}){const i=this.query();for(const[t,r]of Object.entries(e))i.where(t,r);const r=await i.first();return r?this.hydrate(r):await this.create({...e,...t})}static async updateOrCreate(e,t={}){const i=this.query();for(const[t,r]of Object.entries(e))i.where(t,r);const r=await i.first();if(r){const e=this.hydrate(r);return await e.update(t),e}return await this.create({...e,...t})}static hydrate(e){const t=new this;return t.attributes={...e},t.original={...e},t.exists=!0,t}fill(e){for(const[t,i]of Object.entries(e))this.isFillable(t)&&this.setAttribute(t,i);return this}isFillable(e){return this.fillable.length>0?this.fillable.includes(e):!this.guarded.includes(e)}setAttribute(e,t){const i=`set${this.studly(e)}Attribute`;"function"==typeof this[i]&&(t=this[i](t)),this.attributes[e]=this.castAttribute(e,t)}getAttribute(e){const t=`get${this.studly(e)}Attribute`;if("function"==typeof this[t])return this[t]();const i=this.attributes[e];return this.castAttribute(e,i,!0)}castAttribute(e,t,i=!1){if(null==t)return t;const r=this.casts[e];if(!r)return t;if(i)switch(r){case"int":case"integer":return parseInt(t);case"float":case"double":return parseFloat(t);case"string":return String(t);case"bool":case"boolean":return Boolean(t);case"array":case"json":return"string"==typeof t?JSON.parse(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}else switch(r){case"array":case"json":return"object"==typeof t?JSON.stringify(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}}async save(){const e=this.constructor;if(this.timestamps){const e=new Date;this.exists||(this.attributes[this.createdAt]=e),this.attributes[this.updatedAt]=e}if(this.exists){const t=this.attributes[e.primaryKey];await e.adapter.update(e.getTable(),t,this.attributes)}else{const t=await e.adapter.insert(e.getTable(),this.attributes),i=t[e.primaryKey]||t.id||t.insertId;this.attributes[e.primaryKey]=i,"id"!==e.primaryKey&&(this.attributes.id=i),this.exists=!0}return this.syncOriginal(),this}async update(e){return this.fill(e),await this.save()}async delete(){const e=this.constructor;if(this.softDeletes)return this.attributes[this.deletedAt]=new Date,await this.save(),!0;const t=this.attributes[e.primaryKey];return await e.adapter.delete(e.getTable(),t)}async forceDelete(){const e=this.constructor,t=this.attributes[e.primaryKey];return await e.adapter.delete(e.getTable(),t)}async restore(){return this.softDeletes&&(this.attributes[this.deletedAt]=null,await this.save()),this}syncOriginal(){this.original={...this.attributes}}getDirty(){const e={};for(const[t,i]of Object.entries(this.attributes))this.original[t]!==i&&(e[t]=i);return e}isDirty(){return Object.keys(this.getDirty()).length>0}constructor(e={}){super(),this.fill(e)}toJSON(){const e={};for(const[t,i]of Object.entries(this.attributes))this.hidden.includes(t)||this.visible.length>0&&!this.visible.includes(t)||(e[t]=this.getAttribute(t));for(const[t,i]of Object.entries(this.relations))e[t]=i;return e}hasOne(e,t,i){const r=new e,s=t||`${this.constructor.name.toLowerCase()}_id`,a=i||"id";return new HasOne(r.newQuery(),this,s,a)}hasMany(e,t,i){const r=new e,s=t||`${this.constructor.name.toLowerCase()}_id`,a=i||"id";return new HasMany(r.newQuery(),this,s,a)}belongsTo(e,t,i){const r=new e,s=t||`${r.constructor.name.toLowerCase()}_id`,a=i||"id";return new BelongsTo(r.newQuery(),this,s,a)}belongsToMany(e,t,i,r,s,a){const n=new e,o=t||this.guessPivotTable(n),c=i||`${this.constructor.name.toLowerCase()}_id`,l=r||`${n.constructor.name.toLowerCase()}_id`,u=s||"id",h=a||"id";return new BelongsToMany(n.newQuery(),this,o,c,l,u,h)}guessPivotTable(e){const t=[this.constructor.name.toLowerCase(),e.constructor.name.toLowerCase()];return t.sort(),t.join("_")}static with(e){return this.query().with(e)}setRelation(e,t){return this.relations[e]=t,this}getRelation(e){return this.relations[e]}relationLoaded(e){return void 0!==this.relations[e]}newQuery(){return this.constructor.query()}static snakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}static pluralize(e){return e.endsWith("y")?e.slice(0,-1)+"ies":e.endsWith("s")?e+"es":e+"s"}studly(e){return e.replace(/(^|_)(\w)/g,(e,t,i)=>i.toUpperCase())}}class ColumnBuilder{constructor(e,t,i){this.definition={name:e,type:t,length:i,nullable:!1}}nullable(){return this.definition.nullable=!0,this}default(e){return this.definition.default=e,this}unique(){return this.definition.unique=!0,this}primary(){return this.definition.primary=!0,this}autoIncrement(){return this.definition.autoIncrement=!0,this}unsigned(){return this.definition.unsigned=!0,this}getDefinition(){return this.definition}}class ForeignKeyBuilder{constructor(e){this.column=e}references(e){return this.referencedColumn=e,this}on(e){return this.referencedTable=e,this}onDelete(e){return this.onDeleteAction=e,this}onUpdate(e){return this.onUpdateAction=e,this}toSQL(){if(!this.referencedTable||!this.referencedColumn)throw new Error("Foreign key must reference a table and column");let e=`FOREIGN KEY (${this.column}) REFERENCES ${this.referencedTable}(${this.referencedColumn})`;return this.onDeleteAction&&(e+=` ON DELETE ${this.onDeleteAction}`),this.onUpdateAction&&(e+=` ON UPDATE ${this.onUpdateAction}`),e}}class Blueprint{columns=[];indexes=[];foreignKeys=[];primaryKeys=[];constructor(e){this.tableName=e}id(e="id"){const t=new ColumnBuilder(e,"bigInteger");return t.primary().autoIncrement().unsigned(),this.columns.push(t.getDefinition()),t}uuid(e="id"){const t=new ColumnBuilder(e,"uuid");return this.columns.push(t.getDefinition()),t}string(e,t=255){const i=new ColumnBuilder(e,"string",t);return this.columns.push(i.getDefinition()),i}text(e){const t=new ColumnBuilder(e,"text");return this.columns.push(t.getDefinition()),t}integer(e){const t=new ColumnBuilder(e,"integer");return this.columns.push(t.getDefinition()),t}bigInteger(e){const t=new ColumnBuilder(e,"bigInteger");return this.columns.push(t.getDefinition()),t}decimal(e,t=10,i=2){const r=new ColumnBuilder(e,"decimal");return this.columns.push(r.getDefinition()),r}float(e){const t=new ColumnBuilder(e,"float");return this.columns.push(t.getDefinition()),t}double(e){const t=new ColumnBuilder(e,"double");return this.columns.push(t.getDefinition()),t}boolean(e){const t=new ColumnBuilder(e,"boolean");return this.columns.push(t.getDefinition()),t}date(e){const t=new ColumnBuilder(e,"date");return this.columns.push(t.getDefinition()),t}datetime(e){const t=new ColumnBuilder(e,"datetime");return this.columns.push(t.getDefinition()),t}timestamp(e){const t=new ColumnBuilder(e,"timestamp");return this.columns.push(t.getDefinition()),t}timestamps(){this.timestamp("created_at").nullable(),this.timestamp("updated_at").nullable()}softDeletes(e="deleted_at"){return this.timestamp(e).nullable()}json(e){const t=new ColumnBuilder(e,"json");return this.columns.push(t.getDefinition()),t}enum(e,t){const i=new ColumnBuilder(e,"enum");return this.columns.push(i.getDefinition()),i}foreign(e){const t=new ForeignKeyBuilder(e);return this.foreignKeys.push(t),t}index(e,t){const i=Array.isArray(e)?e:[e];this.indexes.push({columns:i,unique:!1,name:t})}unique(e,t){const i=Array.isArray(e)?e:[e];this.indexes.push({columns:i,unique:!0,name:t})}primary(e){this.primaryKeys=Array.isArray(e)?e:[e]}getColumns(){return this.columns}getTableName(){return this.tableName}getIndexes(){return this.indexes}getForeignKeys(){return this.foreignKeys}}var dynamicRequire=__webpack_require__(14);class Schema{static setAdapter(e){this.adapter=e}static async create(e,t){const i=new Blueprint(e);t(i),await this.adapter.createTable(e,i.getColumns())}static async table(e,t){t(new Blueprint(e)),console.warn("Schema.table() is not fully implemented yet. Use migrations for complex alterations.")}static async drop(e){await this.adapter.dropTable(e)}static async dropIfExists(e){await this.hasTable(e)&&await this.drop(e)}static async rename(e,t){throw new Error("Schema.rename() not yet implemented")}static async hasTable(e){return await this.adapter.hasTable(e)}static async hasColumn(e,t){return await this.adapter.hasColumn(e,t)}static async getTables(){throw new Error("Schema.getTables() not yet implemented")}static async getColumns(e){throw new Error("Schema.getColumns() not yet implemented")}}class Migration{}class MigrationRunner{migrationsTable="migrations";constructor(e,t){this.adapter=e,this.migrationsPath=t}async ensureMigrationsTable(){await Schema.hasTable(this.migrationsTable)||await Schema.create(this.migrationsTable,e=>{e.id(),e.string("migration"),e.integer("batch"),e.timestamp("created_at").nullable()})}async getRanMigrations(){return await this.ensureMigrationsTable(),await this.adapter.select(this.migrationsTable,{orderBy:[{column:"batch",direction:"ASC"}]})}async getPendingMigrations(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,896,23)),t=(await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),(await this.getRanMigrations()).map(e=>e.migration));return e.readdirSync(this.migrationsPath).filter(e=>e.endsWith(".ts")||e.endsWith(".js")).filter(e=>!t.includes(e.replace(/\.(ts|js)$/,""))).sort()}async run(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),t=await this.getPendingMigrations();if(0===t.length)return void console.log("No pending migrations");const i=await this.getRanMigrations(),r=i.length>0?Math.max(...i.map(e=>e.batch))+1:1;console.log(`Running ${t.length} migration(s)...`);for(const i of t){const t=e.resolve(this.migrationsPath,i),s=i.replace(/\.(ts|js)$/,"");try{const e=new(await this.loadMigration(t));console.log(`Migrating: ${s}`),await e.up(),await this.adapter.insert(this.migrationsTable,{migration:s,batch:r,created_at:new Date}),console.log(`Migrated: ${s}`)}catch(e){throw console.error(`Failed to migrate ${s}:`,e),e}}console.log("Migrations completed successfully")}async rollback(e=1){const t=await this.getRanMigrations();if(0===t.length)return void console.log("No migrations to rollback");const i=Math.max(...t.map(e=>e.batch)),r=i-e+1,s=t.filter(e=>e.batch>=r&&e.batch<=i).reverse();console.log(`Rolling back ${s.length} migration(s)...`);const a=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23));for(const e of s){const t=a.resolve(this.migrationsPath,`${e.migration}.ts`);try{const i=new(await this.loadMigration(t));console.log(`Rolling back: ${e.migration}`),await i.down(),await this.adapter.delete(this.migrationsTable,e.id),console.log(`Rolled back: ${e.migration}`)}catch(t){throw console.error(`Failed to rollback ${e.migration}:`,t),t}}console.log("Rollback completed successfully")}async reset(){const e=await this.getRanMigrations(),t=Math.max(...e.map(e=>e.batch));await this.rollback(t)}async fresh(){await this.reset(),await this.run()}async status(){return(await this.getRanMigrations()).map(e=>({name:e.migration,batch:e.batch,ranAt:e.created_at||new Date}))}async loadMigration(e){const t=(0,dynamicRequire.dynamicRequire)(e),i=t.default||t;if(!i||"function"!=typeof i)throw new Error(`Migration file ${e} does not export a valid migration class`);const r=new i;if("function"!=typeof r.up||"function"!=typeof r.down)throw new Error(`Migration class in ${e} must implement up() and down() methods`);return i}}class Factory{constructor(){this.faker=__webpack_require__(941).faker}make(e={}){const t=new this.model,i={...this.definition(),...e};return t.fill(i),t}async create(e={}){const t=this.make(e);return await t.save(),t}async createMany(e,t={}){const i=[];for(let r=0;r<e;r++)i.push(await this.create(t));return i}}class Seeder{async call(e){const t=new e;await t.run()}}QueryBuilder.macro("populate",async function(e,t){const i=(await this.adapter.raw("db")).collection(this.tableName),r=(null==t?void 0:t.from)||`${e}s`,s=(null==t?void 0:t.localField)||`${e}_id`,a=(null==t?void 0:t.foreignField)||"_id",n=(null==t?void 0:t.as)||e,o=[];if(this.whereClauses&&this.whereClauses.length>0){var c,l;const e=(null===(c=(l=this.adapter).buildFilter)||void 0===c?void 0:c.call(l,this.whereClauses))||{};Object.keys(e).length>0&&o.push({$match:e})}if(null!=t&&t.select&&t.select.length>0){const e={};t.select.forEach(t=>{e[t]=1}),o.push({$lookup:{from:r,let:{localId:`$${s}`},pipeline:[{$match:{$expr:{$eq:[`$${a}`,"$$localId"]}}},{$project:e}],as:n}})}else o.push({$lookup:{from:r,localField:s,foreignField:a,as:n}});return o.push({$unwind:{path:`$${n}`,preserveNullAndEmptyArrays:!0}}),this.limitValue&&o.push({$limit:this.limitValue}),(await i.aggregate(o).toArray()).map(e=>{const{_id:t,...i}=e;return{id:t,_id:t,...i}})}),QueryBuilder.macro("exec",async function(){return await this.get()}),QueryBuilder.macro("aggregate",async function(e){const t=(await this.adapter.raw("db")).collection(this.tableName);return(await t.aggregate(e).toArray()).map(e=>{if(e._id){const{_id:t,...i}=e;return{id:t,_id:t,...i}}return e})});class ServiceProvider{constructor(e){this.app=e}register(){}boot(){}async shutdown(){}}class DatabaseProvider extends ServiceProvider{async register(){let e;console.log("⚙️ DatabaseProvider: Initializing...");try{e=this.app.container.resolve("DatabaseConfig"),console.log("✓ DatabaseProvider: Configuration loaded successfully")}catch(e){return void console.warn("⚠ DatabaseProvider: No configuration found - Skipping setup")}try{let t;switch(console.log(`⚙️ DatabaseProvider: Loading ${e.type} adapter...`),e.type){case"mysql":const{MySQLAdapter:i}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,707));t=new i;break;case"mongodb":const{MongoAdapter:r}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,697));t=new r;break;case"postgres":const{PostgresAdapter:s}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,590));t=new s;break;default:throw new Error(`Unsupported database type: ${e.type}`)}console.log(`✓ DatabaseProvider: ${e.type} adapter loaded`),this.app.container.singleton("DatabaseAdapter",()=>t),this.app.container.singleton("DBConnection",async()=>{console.log(`⚙️ DatabaseProvider: Connecting to ${e.type}...`);const i=await t.connect(e);return Model.setAdapter(t),Schema.setAdapter(t),console.log(`✓ DatabaseProvider: Connected to ${e.type} database '${e.database}'`),i}),console.log("✅ DatabaseProvider: Ready")}catch(e){throw console.error("✗ DatabaseProvider: Initialization failed",e),e}}async shutdown(){try{console.log("⚙️ DatabaseProvider: Closing connection...");const e=await this.app.container.make("DatabaseAdapter");await e.disconnect(),console.log("✓ DatabaseProvider: Connection closed")}catch(e){}}}var __webpack_export_target__=exports;for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__]=__webpack_exports__[__webpack_i__];__webpack_exports__.__esModule&&Object.defineProperty(__webpack_export_target__,"__esModule",{value:!0})})();
|
|
1
|
+
(()=>{"use strict";var __webpack_modules__={14:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{dynamicRequire:()=>dynamicRequire});const dynamicRequire=id=>{try{var _global$process;const e=global,t=null===(_global$process=e.process)||void 0===_global$process||null===(_global$process=_global$process.mainModule)||void 0===_global$process?void 0:_global$process.require;if(t)return t(id)}catch(e){}return eval("require")(id)}},590:(e,t,r)=>{r.d(t,{PostgresAdapter:()=>a});var i=r(14);class a{pool=null;client=null;async connect(e){var t,r;const{Pool:a}=(0,i.dynamicRequire)("pg");return this.pool=new a({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,ssl:e.ssl,min:(null===(t=e.pool)||void 0===t?void 0:t.min)||2,max:(null===(r=e.pool)||void 0===r?void 0:r.max)||10}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){const r=this.client||this.pool;if(!r)throw new Error("Database not connected");return(await r.query(e,t)).rows}async execute(e,t){const r=this.client||this.pool;if(!r)throw new Error("Database not connected");return await r.query(e,t)}async createTable(e,t){const r=`CREATE TABLE IF NOT EXISTS "${e}" (${t.map(e=>{let t=`"${e.name}" ${this.mapType(e.type,e.length)}`;return e.primary&&(t+=" PRIMARY KEY"),e.autoIncrement&&(t+=" GENERATED ALWAYS AS IDENTITY"),e.nullable||(t+=" NOT NULL"),e.unique&&(t+=" UNIQUE"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),t}).join(", ")})`;await this.execute(r)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS "${e}"`)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.tables \n WHERE table_schema = 'public' \n AND table_name = $1\n )",[e]))[0])||void 0===t?void 0:t.exists)||!1}async hasColumn(e,t){var r;return(null===(r=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.columns \n WHERE table_schema = 'public' \n AND table_name = $1 \n AND column_name = $2\n )",[e,t]))[0])||void 0===r?void 0:r.exists)||!1}async select(e,t){var r;let i=`SELECT ${(null===(r=t.columns)||void 0===r?void 0:r.join(", "))||"*"} FROM "${e}"`;const a=[];let s=1;if(t.joins&&t.joins.length>0)for(const e of t.joins)i+=` ${e.type} JOIN "${e.table}" ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(i+=" "+t.where.map((e,t)=>{const r=0===t?"WHERE":e.boolean,i=this.buildWhereCondition(e,a,s);return s=a.length+1,`${r} ${i}`}).join(" ")),t.orderBy&&t.orderBy.length>0&&(i+=` ORDER BY ${t.orderBy.map(e=>`"${e.column}" ${e.direction}`).join(", ")}`),t.limit&&(i+=" LIMIT $"+s++,a.push(t.limit)),t.offset&&(i+=" OFFSET $"+s++,a.push(t.offset)),await this.query(i,a)}async insert(e,t){const r=Object.keys(t),i=Object.values(t),a=i.map((e,t)=>`$${t+1}`).join(", "),s=`INSERT INTO "${e}" (${r.map(e=>`"${e}"`).join(", ")}) \n VALUES (${a}) \n RETURNING *`;return(await this.query(s,i))[0]}async update(e,t,r){const i=Object.keys(r),a=Object.values(r),s=`UPDATE "${e}" SET ${i.map((e,t)=>`"${e}" = $${t+1}`).join(", ")} WHERE id = $${i.length+1} RETURNING *`;return(await this.query(s,[...a,t]))[0]}async delete(e,t){const r=`DELETE FROM "${e}" WHERE id = $1`;return(await this.execute(r,[t])).rowCount>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.client=await this.pool.connect(),await this.client.query("BEGIN")}async commit(){if(!this.client)throw new Error("No active transaction");await this.client.query("COMMIT"),this.client.release(),this.client=null}async rollback(){if(!this.client)throw new Error("No active transaction");await this.client.query("ROLLBACK"),this.client.release(),this.client=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(e,t)).rows}buildWhereCondition(e,t,r){const i=`"${e.column}"`;switch(e.operator){case"IN":const a=e.value.map((e,t)=>`$${r+t}`).join(", ");return t.push(...e.value),`${i} IN (${a})`;case"NOT IN":const s=e.value.map((e,t)=>`$${r+t}`).join(", ");return t.push(...e.value),`${i} NOT IN (${s})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${i} BETWEEN $${r} AND $${r+1}`;case"IS NULL":return`${i} IS NULL`;case"IS NOT NULL":return`${i} IS NOT NULL`;default:return t.push(e.value),`${i} ${e.operator} $${r}`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INTEGER",bigInteger:"BIGINT",float:"REAL",double:"DOUBLE PRECISION",decimal:"DECIMAL",boolean:"BOOLEAN",date:"DATE",datetime:"TIMESTAMP",timestamp:"TIMESTAMP",json:"JSONB",uuid:"UUID"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"TRUE":"FALSE":e instanceof Date?`'${e.toISOString()}'`:String(e)}}},697:(e,t,r)=>{r.d(t,{MongoAdapter:()=>a});var i=r(14);class a{client=null;db=null;async connect(e){const{MongoClient:t}=(0,i.dynamicRequire)("mongodb"),r=e.url||e.uri||`mongodb://${e.host}:${e.port}`,a={};return!e.url&&!e.uri&&e.username&&e.password&&(a.auth={username:e.username,password:e.password}),this.client=new t(r,a),await this.client.connect(),this.db=this.client.db(e.database),{query:async(e,t)=>{throw new Error("Raw SQL queries are not supported in MongoDB adapter")},execute:async(e,t)=>{throw new Error("Raw SQL execution is not supported in MongoDB adapter")},close:async()=>{await this.disconnect()}}}async disconnect(){this.client&&(await this.client.close(),this.client=null,this.db=null)}async createTable(e,t){if(!this.db)throw new Error("Database not connected");await this.db.createCollection(e)}async dropTable(e){if(!this.db)throw new Error("Database not connected");await this.db.collection(e).drop()}async hasTable(e){if(!this.db)throw new Error("Database not connected");return(await this.db.listCollections({name:e}).toArray()).length>0}async hasColumn(e,t){return!0}async select(e,t){if(!this.db)throw new Error("Database not connected");const r=this.db.collection(e),i=this.buildFilter(t.where||[]),a=this.buildProjection(t.columns);let s=r.find(i);if(a&&(s=s.project(a)),t.orderBy){const e={};t.orderBy.forEach(t=>{e[t.column]="ASC"===t.direction?1:-1}),s=s.sort(e)}return t.offset&&(s=s.skip(t.offset)),t.limit&&(s=s.limit(t.limit)),(await s.toArray()).map(e=>{const{_id:t,...r}=e;return{id:t,_id:t,...r}})}async insert(e,t){if(!this.db)throw new Error("Database not connected");const r=this.db.collection(e),i={...t};i.id&&(i._id=i.id,delete i.id);const a=await r.insertOne(i);return{id:a.insertedId,_id:a.insertedId,...t}}async update(e,t,r){if(!this.db)throw new Error("Database not connected");const i=this.db.collection(e),a={_id:this.normalizeId(t)},s={$set:r},n=await i.findOneAndUpdate(a,s,{returnDocument:"after"});if(n){const{_id:e,...t}=n;return{id:e,_id:e,...t}}return null}async delete(e,t){if(!this.db)throw new Error("Database not connected");const r=this.db.collection(e);return 1===(await r.deleteOne({_id:this.normalizeId(t)})).deletedCount}async beginTransaction(){}async raw(e,t=[]){if(!this.db)throw new Error("Database not connected");return"db"===e?this.db:await this.db.command(JSON.parse(e))}async commit(){}async rollback(){}buildFilter(e){const t={};return e.forEach(e=>{const r="id"===e.column?"_id":e.column;let i=e.value;switch("_id"===r&&(i=this.normalizeId(i)),e.operator){case"=":t[r]=i;break;case"!=":t[r]={$ne:i};break;case">":t[r]={$gt:i};break;case"<":t[r]={$lt:i};break;case">=":t[r]={$gte:i};break;case"<=":t[r]={$lte:i};break;case"IN":t[r]={$in:Array.isArray(i)?i:[i]};break;case"NOT IN":t[r]={$nin:Array.isArray(i)?i:[i]};break;case"LIKE":t[r]={$regex:new RegExp(i.replace(/%/g,".*"),"i")};break;case"IS NULL":t[r]=null;break;case"IS NOT NULL":t[r]={$ne:null}}}),t}buildProjection(e){if(!e||0===e.length||e.includes("*"))return null;const t={};return e.forEach(e=>{"id"===e||(t[e]=1)}),t}normalizeId(e){const{ObjectId:t}=(0,i.dynamicRequire)("mongodb");return e instanceof t?e:"string"==typeof e&&t.isValid(e)?new t(e):e}}},707:(e,t,r)=>{r.d(t,{MySQLAdapter:()=>a});var i=r(14);class a{pool=null;connection=null;async connect(e){var t;const r=(0,i.dynamicRequire)("mysql2/promise");return this.pool=r.createPool({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,waitForConnections:!0,connectionLimit:(null===(t=e.pool)||void 0===t?void 0:t.max)||10,queueLimit:0}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){const r=this.connection||this.pool;if(!r)throw new Error("Database not connected");const[i]=await r.query(e,t);return i}async execute(e,t){const r=this.connection||this.pool;if(!r)throw new Error("Database not connected");const[i]=await r.execute(e,t);return i}async createTable(e,t){const r=`CREATE TABLE IF NOT EXISTS \`${e}\` (${t.map(e=>{let t=`\`${e.name}\` ${this.mapType(e.type,e.length)}`;return e.unsigned&&(t+=" UNSIGNED"),e.autoIncrement&&(t+=" AUTO_INCREMENT"),e.nullable||(t+=" NOT NULL"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),e.primary&&(t+=" PRIMARY KEY"),e.unique&&(t+=" UNIQUE"),t}).join(", ")}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`;await this.execute(r)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS \`${e}\``)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT COUNT(*) as count FROM information_schema.tables \n WHERE table_schema = DATABASE() AND table_name = ?",[e]))[0])||void 0===t?void 0:t.count)>0}async hasColumn(e,t){var r;return(null===(r=(await this.query("SELECT COUNT(*) as count FROM information_schema.columns \n WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?",[e,t]))[0])||void 0===r?void 0:r.count)>0}async select(e,t){var r;let i=`SELECT ${(null===(r=t.columns)||void 0===r?void 0:r.join(", "))||"*"} FROM \`${e}\``;const a=[];if(t.joins&&t.joins.length>0)for(const e of t.joins)i+=` ${e.type} JOIN \`${e.table}\` ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(i+=" "+t.where.map((e,t)=>`${0===t?"WHERE":e.boolean} ${this.buildWhereCondition(e,a)}`).join(" ")),t.orderBy&&t.orderBy.length>0&&(i+=` ORDER BY ${t.orderBy.map(e=>`\`${e.column}\` ${e.direction}`).join(", ")}`),t.limit&&(i+=" LIMIT ?",a.push(t.limit)),t.offset&&(i+=" OFFSET ?",a.push(t.offset)),await this.query(i,a)}async insert(e,t){const r=Object.keys(t),i=Object.values(t),a=i.map(()=>"?").join(", "),s=`INSERT INTO \`${e}\` (${r.map(e=>`\`${e}\``).join(", ")}) VALUES (${a})`;return{id:(await this.execute(s,i)).insertId,...t}}async update(e,t,r){const i=Object.keys(r),a=Object.values(r),s=`UPDATE \`${e}\` SET ${i.map(e=>`\`${e}\` = ?`).join(", ")} WHERE id = ?`;return await this.execute(s,[...a,t]),{id:t,...r}}async delete(e,t){const r=`DELETE FROM \`${e}\` WHERE id = ?`;return(await this.execute(r,[t])).affectedRows>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.connection=await this.pool.getConnection(),await this.connection.beginTransaction()}async commit(){if(!this.connection)throw new Error("No active transaction");await this.connection.commit(),this.connection.release(),this.connection=null}async rollback(){if(!this.connection)throw new Error("No active transaction");await this.connection.rollback(),this.connection.release(),this.connection=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");const[r]=await this.pool.execute(e,t);return r}buildWhereCondition(e,t){const r=`\`${e.column}\``;switch(e.operator){case"IN":const i=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${r} IN (${i})`;case"NOT IN":const a=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${r} NOT IN (${a})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${r} BETWEEN ? AND ?`;case"IS NULL":return`${r} IS NULL`;case"IS NOT NULL":return`${r} IS NOT NULL`;default:return t.push(e.value),`${r} ${e.operator} ?`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INT",bigInteger:"BIGINT",float:"FLOAT",double:"DOUBLE",decimal:"DECIMAL(10,2)",boolean:"TINYINT(1)",date:"DATE",datetime:"DATETIME",timestamp:"TIMESTAMP",json:"JSON",uuid:"CHAR(36)"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"1":"0":e instanceof Date?`'${e.toISOString().slice(0,19).replace("T"," ")}'`:String(e)}}},896:e=>{e.exports=require("fs")},928:e=>{e.exports=require("path")},941:e=>{e.exports=require("@faker-js/faker")}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](r,r.exports,__webpack_require__),r.exports}getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var r=Object.create(null);__webpack_require__.r(r);var i={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var a=2&t&&e;("object"==typeof a||"function"==typeof a)&&!~leafPrototypes.indexOf(a);a=getProto(a))Object.getOwnPropertyNames(a).forEach(t=>i[t]=()=>e[t]);return i.default=()=>e,__webpack_require__.d(r,i),r},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{BelongsTo:()=>BelongsTo,BelongsToMany:()=>BelongsToMany,Blueprint:()=>Blueprint,DatabaseProvider:()=>DatabaseProvider,Factory:()=>Factory,HasMany:()=>HasMany,HasOne:()=>HasOne,Macroable:()=>Macroable,Migration:()=>Migration,MigrationRunner:()=>MigrationRunner,Model:()=>Model,MongoAdapter:()=>MongoAdapter.MongoAdapter,MySQLAdapter:()=>MySQLAdapter.MySQLAdapter,PostgresAdapter:()=>PostgresAdapter.PostgresAdapter,QueryBuilder:()=>QueryBuilder,Relation:()=>Relation,Schema:()=>Schema,Seeder:()=>Seeder});var MongoAdapter=__webpack_require__(697),MySQLAdapter=__webpack_require__(707),PostgresAdapter=__webpack_require__(590);class Macroable{static macros={};static macro(e,t){this.macros[e]=t,this.prototype[e]=t}static mixin(e){Object.keys(e).forEach(t=>{this.macro(t,e[t])})}static hasMacro(e){return!!this.macros[e]}}class QueryBuilder extends Macroable{selectColumns=["*"];whereClauses=[];orderByClauses=[];joinClauses=[];constructor(e,t){super(),this.tableName=e,this.adapter=t}select(...e){return this.selectColumns=e,this}where(e,t,r){return void 0===r&&(r=t,t="="),this.whereClauses.push({column:e,operator:t,value:r,boolean:"AND"}),this}orWhere(e,t,r){return void 0===r&&(r=t,t="="),this.whereClauses.push({column:e,operator:t,value:r,boolean:"OR"}),this}whereIn(e,t){return this.whereClauses.push({column:e,operator:"IN",value:t,boolean:"AND"}),this}whereNotIn(e,t){return this.whereClauses.push({column:e,operator:"NOT IN",value:t,boolean:"AND"}),this}whereBetween(e,t){return this.whereClauses.push({column:e,operator:"BETWEEN",value:t,boolean:"AND"}),this}whereNull(e){return this.whereClauses.push({column:e,operator:"IS NULL",value:null,boolean:"AND"}),this}whereNotNull(e){return this.whereClauses.push({column:e,operator:"IS NOT NULL",value:null,boolean:"AND"}),this}orderBy(e,t="ASC"){return this.orderByClauses.push({column:e,direction:t.toUpperCase()}),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}join(e,t,r,i,a="INNER"){return this.joinClauses.push({type:a,table:e,first:t,operator:r,second:i}),this}leftJoin(e,t,r,i){return this.join(e,t,r,i,"LEFT")}rightJoin(e,t,r,i){return this.join(e,t,r,i,"RIGHT")}eagerLoads=[];setModel(e){return this.model=e,this}with(e){return Array.isArray(e)?this.eagerLoads.push(...e):this.eagerLoads.push(e),this}async get(){const e={columns:this.selectColumns,where:this.whereClauses,orderBy:this.orderByClauses,limit:this.limitValue,offset:this.offsetValue,joins:this.joinClauses},t=await this.adapter.select(this.tableName,e);return this.eagerLoads.length>0&&this.model?await this.eagerLoadRelations(t):t}async eagerLoadRelations(e){if(0===e.length)return e;const t=e.map(e=>this.model.hydrate(e));for(const e of this.eagerLoads){const r=new this.model;if("function"!=typeof r[e])throw new Error(`Relation ${e} does not exist on ${this.model.name}`);const i=r[e]();i.addEagerConstraints(t);const a=await i.get();i.match(t,a,e)}return t}async first(){return this.limit(1),(await this.get())[0]||null}async find(e){return this.where("id",e).first()}async count(){this.selectColumns=["COUNT(*) as count"];const e=await this.first();return e?e.count:0}async pluck(e){return this.select(e),(await this.get()).map(t=>t[e])}async sum(e){this.selectColumns=[`SUM(${e}) as sum`];const t=await this.first();return t&&t.sum||0}async avg(e){this.selectColumns=[`AVG(${e}) as avg`];const t=await this.first();return t&&t.avg||0}async min(e){this.selectColumns=[`MIN(${e}) as min`];const t=await this.first();return t?t.min:null}async max(e){this.selectColumns=[`MAX(${e}) as max`];const t=await this.first();return t?t.max:null}async exists(){return await this.count()>0}async paginate(e=1,t=15){const r=await this.count(),i=(e-1)*t;return this.limit(t).offset(i),{data:await this.get(),total:r,perPage:t,currentPage:e,lastPage:Math.ceil(r/t)}}clone(){const e=new QueryBuilder(this.tableName,this.adapter);return e.selectColumns=[...this.selectColumns],e.whereClauses=[...this.whereClauses],e.orderByClauses=[...this.orderByClauses],e.joinClauses=[...this.joinClauses],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e}}class Relation{constructor(e,t){this.query=e,this.parent=t,this.related=e.model,this.addConstraints()}getQuery(){return this.query}async get(){return this.query.get()}async first(){return this.query.first()}}class BelongsTo extends Relation{constructor(e,t,r,i){super(e,t),this.foreignKey=r,this.ownerKey=i}addConstraints(){const e=this.parent.getAttribute(this.foreignKey);this.query.where(this.ownerKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.foreignKey)).filter(e=>null!==e);this.query.whereIn(this.ownerKey,t)}match(e,t,r){const i={};return t.forEach(e=>{const t=e.getAttribute(this.ownerKey);i[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.foreignKey);i[t]&&e.setRelation(r,i[t])}),e}}class BelongsToMany extends Relation{constructor(e,t,r,i,a,s,n){super(e,t),this.table=r,this.foreignPivotKey=i,this.relatedPivotKey=a,this.parentKey=s,this.relatedKey=n}addConstraints(){this.performJoin(),this.query.where(`${this.table}.${this.foreignPivotKey}`,"=",this.parent.getAttribute(this.parentKey))}performJoin(e){const t=e||this.query,r=this.related.prototype.getTable();return t.join(this.table,`${r}.${this.relatedKey}`,"=",`${this.table}.${this.relatedPivotKey}`),this}addEagerConstraints(e){this.performJoin();const t=e.map(e=>e.getAttribute(this.parentKey)).filter(e=>null!==e);this.query.whereIn(`${this.table}.${this.foreignPivotKey}`,t)}match(e,t,r){return e}}class HasMany extends Relation{constructor(e,t,r,i){super(e,t),this.foreignKey=r,this.localKey=i}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,r){const i={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);i[t]||(i[t]=[]),i[t].push(e)}),e.forEach(e=>{const t=e.getAttribute(this.localKey);i[t]?e.setRelation(r,i[t]):e.setRelation(r,[])}),e}}class HasOne extends Relation{constructor(e,t,r,i){super(e,t),this.foreignKey=r,this.localKey=i}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,r){const i={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);i[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.localKey);i[t]&&e.setRelation(r,i[t])}),e}}class Model extends Macroable{static primaryKey="id";static connection="default";attributes={};original={};relations={};exists=!1;fillable=[];guarded=["id"];hidden=[];visible=[];casts={};dates=[];timestamps=!0;createdAt="created_at";updatedAt="updated_at";softDeletes=!1;deletedAt="deleted_at";static setAdapter(e){this.adapter=e}static getAdapter(){const e=this.adapter||global.ArcanaDatabaseAdapter;if(!e)throw new Error("Database adapter not set. Call Model.setAdapter() or ensure global.ArcanaDatabaseAdapter is set.");return e}static getTable(){if(this.tableName)return this.tableName;const e=this.name;return this.pluralize(this.snakeCase(e))}static query(){return new QueryBuilder(this.getTable(),this.getAdapter()).setModel(this)}static async all(){return(await this.query().get()).map(e=>this.hydrate(e))}static async find(e){const t=await this.query().where(this.primaryKey,e).first();return t?this.hydrate(t):null}static async findOrFail(e){const t=await this.find(e);if(!t)throw new Error(`Model not found with ${this.primaryKey}: ${e}`);return t}static where(e,t,r){return this.query().where(e,t,r)}static async create(e){const t=new this;if(t.fill(e),t.timestamps){const e=new Date;t.attributes[t.createdAt]=e,t.attributes[t.updatedAt]=e}const r=await this.getAdapter().insert(this.getTable(),t.attributes),i=r[this.primaryKey]||r.id||r.insertId;return t.attributes[this.primaryKey]=i,"id"!==this.primaryKey&&(t.attributes.id=i),t.exists=!0,t.syncOriginal(),t}static async update(e,t){const r=await this.findOrFail(e);return await r.update(t),r}static async destroy(e){const t=await this.find(e);return!!t&&await t.delete()}static async firstOrCreate(e,t={}){const r=this.query();for(const[t,i]of Object.entries(e))r.where(t,i);const i=await r.first();return i?this.hydrate(i):await this.create({...e,...t})}static async updateOrCreate(e,t={}){const r=this.query();for(const[t,i]of Object.entries(e))r.where(t,i);const i=await r.first();if(i){const e=this.hydrate(i);return await e.update(t),e}return await this.create({...e,...t})}static hydrate(e){const t=new this;return t.attributes={...e},t.original={...e},t.exists=!0,t}fill(e){for(const[t,r]of Object.entries(e))this.isFillable(t)&&this.setAttribute(t,r);return this}isFillable(e){return this.fillable.length>0?this.fillable.includes(e):!this.guarded.includes(e)}setAttribute(e,t){const r=`set${this.studly(e)}Attribute`;"function"==typeof this[r]&&(t=this[r](t)),this.attributes[e]=this.castAttribute(e,t)}getAttribute(e){const t=`get${this.studly(e)}Attribute`;if("function"==typeof this[t])return this[t]();const r=this.attributes[e];return this.castAttribute(e,r,!0)}castAttribute(e,t,r=!1){if(null==t)return t;const i=this.casts[e];if(!i)return t;if(r)switch(i){case"int":case"integer":return parseInt(t);case"float":case"double":return parseFloat(t);case"string":return String(t);case"bool":case"boolean":return Boolean(t);case"array":case"json":return"string"==typeof t?JSON.parse(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}else switch(i){case"array":case"json":return"object"==typeof t?JSON.stringify(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}}async save(){const e=this.constructor;if(this.timestamps){const e=new Date;this.exists||(this.attributes[this.createdAt]=e),this.attributes[this.updatedAt]=e}if(this.exists){const t=this.attributes[e.primaryKey];await e.getAdapter().update(e.getTable(),t,this.attributes)}else{const t=await e.getAdapter().insert(e.getTable(),this.attributes),r=t[e.primaryKey]||t.id||t.insertId;this.attributes[e.primaryKey]=r,"id"!==e.primaryKey&&(this.attributes.id=r),this.exists=!0}return this.syncOriginal(),this}async update(e){return this.fill(e),await this.save()}async delete(){const e=this.constructor;if(this.softDeletes)return this.attributes[this.deletedAt]=new Date,await this.save(),!0;const t=this.attributes[e.primaryKey];return await e.getAdapter().delete(e.getTable(),t)}async forceDelete(){const e=this.constructor,t=this.attributes[e.primaryKey];return await e.getAdapter().delete(e.getTable(),t)}async restore(){return this.softDeletes&&(this.attributes[this.deletedAt]=null,await this.save()),this}syncOriginal(){this.original={...this.attributes}}getDirty(){const e={};for(const[t,r]of Object.entries(this.attributes))this.original[t]!==r&&(e[t]=r);return e}isDirty(){return Object.keys(this.getDirty()).length>0}constructor(e={}){super(),this.fill(e)}toJSON(){const e={};for(const[t,r]of Object.entries(this.attributes))this.hidden.includes(t)||this.visible.length>0&&!this.visible.includes(t)||(e[t]=this.getAttribute(t));for(const[t,r]of Object.entries(this.relations))e[t]=r;return e}hasOne(e,t,r){const i=new e,a=t||`${this.constructor.name.toLowerCase()}_id`,s=r||"id";return new HasOne(i.newQuery(),this,a,s)}hasMany(e,t,r){const i=new e,a=t||`${this.constructor.name.toLowerCase()}_id`,s=r||"id";return new HasMany(i.newQuery(),this,a,s)}belongsTo(e,t,r){const i=new e,a=t||`${i.constructor.name.toLowerCase()}_id`,s=r||"id";return new BelongsTo(i.newQuery(),this,a,s)}belongsToMany(e,t,r,i,a,s){const n=new e,o=t||this.guessPivotTable(n),c=r||`${this.constructor.name.toLowerCase()}_id`,l=i||`${n.constructor.name.toLowerCase()}_id`,u=a||"id",h=s||"id";return new BelongsToMany(n.newQuery(),this,o,c,l,u,h)}guessPivotTable(e){const t=[this.constructor.name.toLowerCase(),e.constructor.name.toLowerCase()];return t.sort(),t.join("_")}static with(e){return this.query().with(e)}setRelation(e,t){return this.relations[e]=t,this}getRelation(e){return this.relations[e]}relationLoaded(e){return void 0!==this.relations[e]}newQuery(){return this.constructor.query()}static snakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}static pluralize(e){return e.endsWith("y")?e.slice(0,-1)+"ies":e.endsWith("s")?e+"es":e+"s"}studly(e){return e.replace(/(^|_)(\w)/g,(e,t,r)=>r.toUpperCase())}}class ColumnBuilder{constructor(e,t,r){this.definition={name:e,type:t,length:r,nullable:!1}}nullable(){return this.definition.nullable=!0,this}default(e){return this.definition.default=e,this}unique(){return this.definition.unique=!0,this}primary(){return this.definition.primary=!0,this}autoIncrement(){return this.definition.autoIncrement=!0,this}unsigned(){return this.definition.unsigned=!0,this}getDefinition(){return this.definition}}class ForeignKeyBuilder{constructor(e){this.column=e}references(e){return this.referencedColumn=e,this}on(e){return this.referencedTable=e,this}onDelete(e){return this.onDeleteAction=e,this}onUpdate(e){return this.onUpdateAction=e,this}toSQL(){if(!this.referencedTable||!this.referencedColumn)throw new Error("Foreign key must reference a table and column");let e=`FOREIGN KEY (${this.column}) REFERENCES ${this.referencedTable}(${this.referencedColumn})`;return this.onDeleteAction&&(e+=` ON DELETE ${this.onDeleteAction}`),this.onUpdateAction&&(e+=` ON UPDATE ${this.onUpdateAction}`),e}}class Blueprint{columns=[];indexes=[];foreignKeys=[];primaryKeys=[];constructor(e){this.tableName=e}id(e="id"){const t=new ColumnBuilder(e,"bigInteger");return t.primary().autoIncrement().unsigned(),this.columns.push(t.getDefinition()),t}uuid(e="id"){const t=new ColumnBuilder(e,"uuid");return this.columns.push(t.getDefinition()),t}string(e,t=255){const r=new ColumnBuilder(e,"string",t);return this.columns.push(r.getDefinition()),r}text(e){const t=new ColumnBuilder(e,"text");return this.columns.push(t.getDefinition()),t}integer(e){const t=new ColumnBuilder(e,"integer");return this.columns.push(t.getDefinition()),t}bigInteger(e){const t=new ColumnBuilder(e,"bigInteger");return this.columns.push(t.getDefinition()),t}decimal(e,t=10,r=2){const i=new ColumnBuilder(e,"decimal");return this.columns.push(i.getDefinition()),i}float(e){const t=new ColumnBuilder(e,"float");return this.columns.push(t.getDefinition()),t}double(e){const t=new ColumnBuilder(e,"double");return this.columns.push(t.getDefinition()),t}boolean(e){const t=new ColumnBuilder(e,"boolean");return this.columns.push(t.getDefinition()),t}date(e){const t=new ColumnBuilder(e,"date");return this.columns.push(t.getDefinition()),t}datetime(e){const t=new ColumnBuilder(e,"datetime");return this.columns.push(t.getDefinition()),t}timestamp(e){const t=new ColumnBuilder(e,"timestamp");return this.columns.push(t.getDefinition()),t}timestamps(){this.timestamp("created_at").nullable(),this.timestamp("updated_at").nullable()}softDeletes(e="deleted_at"){return this.timestamp(e).nullable()}json(e){const t=new ColumnBuilder(e,"json");return this.columns.push(t.getDefinition()),t}enum(e,t){const r=new ColumnBuilder(e,"enum");return this.columns.push(r.getDefinition()),r}foreign(e){const t=new ForeignKeyBuilder(e);return this.foreignKeys.push(t),t}index(e,t){const r=Array.isArray(e)?e:[e];this.indexes.push({columns:r,unique:!1,name:t})}unique(e,t){const r=Array.isArray(e)?e:[e];this.indexes.push({columns:r,unique:!0,name:t})}primary(e){this.primaryKeys=Array.isArray(e)?e:[e]}getColumns(){return this.columns}getTableName(){return this.tableName}getIndexes(){return this.indexes}getForeignKeys(){return this.foreignKeys}}var dynamicRequire=__webpack_require__(14);class Schema{static getAdapter(){const e=this.adapter||global.ArcanaDatabaseAdapter;if(!e)throw new Error("Database adapter not set. Call Schema.setAdapter() or ensure global.ArcanaDatabaseAdapter is set.");return e}static setAdapter(e){this.adapter=e}static async create(e,t){const r=new Blueprint(e);t(r),await this.getAdapter().createTable(e,r.getColumns())}static async table(e,t){t(new Blueprint(e)),console.warn("Schema.table() is not fully implemented yet. Use migrations for complex alterations.")}static async drop(e){await this.getAdapter().dropTable(e)}static async dropIfExists(e){await this.hasTable(e)&&await this.drop(e)}static async rename(e,t){throw new Error("Schema.rename() not yet implemented")}static async hasTable(e){return await this.getAdapter().hasTable(e)}static async hasColumn(e,t){return await this.getAdapter().hasColumn(e,t)}static async getTables(){throw new Error("Schema.getTables() not yet implemented")}static async getColumns(e){throw new Error("Schema.getColumns() not yet implemented")}}class Migration{}class MigrationRunner{migrationsTable="migrations";constructor(e,t){this.adapter=e,this.migrationsPath=t}async ensureMigrationsTable(){await Schema.hasTable(this.migrationsTable)||await Schema.create(this.migrationsTable,e=>{e.id(),e.string("migration"),e.integer("batch"),e.timestamp("created_at").nullable()})}async getRanMigrations(){return await this.ensureMigrationsTable(),await this.adapter.select(this.migrationsTable,{orderBy:[{column:"batch",direction:"ASC"}]})}async getPendingMigrations(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,896,23)),t=(await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),(await this.getRanMigrations()).map(e=>e.migration));return e.readdirSync(this.migrationsPath).filter(e=>e.endsWith(".ts")||e.endsWith(".js")).filter(e=>!t.includes(e.replace(/\.(ts|js)$/,""))).sort()}async run(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),t=await this.getPendingMigrations();if(0===t.length)return void console.log("No pending migrations");const r=await this.getRanMigrations(),i=r.length>0?Math.max(...r.map(e=>e.batch))+1:1;console.log(`Running ${t.length} migration(s)...`);for(const r of t){const t=e.resolve(this.migrationsPath,r),a=r.replace(/\.(ts|js)$/,"");try{const e=new(await this.loadMigration(t));console.log(`Migrating: ${a}`),await e.up(),await this.adapter.insert(this.migrationsTable,{migration:a,batch:i,created_at:new Date}),console.log(`Migrated: ${a}`)}catch(e){throw console.error(`Failed to migrate ${a}:`,e),e}}console.log("Migrations completed successfully")}async rollback(e=1){const t=await this.getRanMigrations();if(0===t.length)return void console.log("No migrations to rollback");const r=Math.max(...t.map(e=>e.batch)),i=r-e+1,a=t.filter(e=>e.batch>=i&&e.batch<=r).reverse();console.log(`Rolling back ${a.length} migration(s)...`);const s=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23));for(const e of a){const t=s.resolve(this.migrationsPath,`${e.migration}.ts`);try{const r=new(await this.loadMigration(t));console.log(`Rolling back: ${e.migration}`),await r.down(),await this.adapter.delete(this.migrationsTable,e.id),console.log(`Rolled back: ${e.migration}`)}catch(t){throw console.error(`Failed to rollback ${e.migration}:`,t),t}}console.log("Rollback completed successfully")}async reset(){const e=await this.getRanMigrations(),t=Math.max(...e.map(e=>e.batch));await this.rollback(t)}async fresh(){await this.reset(),await this.run()}async status(){return(await this.getRanMigrations()).map(e=>({name:e.migration,batch:e.batch,ranAt:e.created_at||new Date}))}async loadMigration(e){const t=(0,dynamicRequire.dynamicRequire)(e),r=t.default||t;if(!r||"function"!=typeof r)throw new Error(`Migration file ${e} does not export a valid migration class`);const i=new r;if("function"!=typeof i.up||"function"!=typeof i.down)throw new Error(`Migration class in ${e} must implement up() and down() methods`);return r}}class Factory{constructor(){this.faker=__webpack_require__(941).faker}make(e={}){const t=new this.model,r={...this.definition(),...e};return t.fill(r),t}async create(e={}){const t=this.make(e);return await t.save(),t}async createMany(e,t={}){const r=[];for(let i=0;i<e;i++)r.push(await this.create(t));return r}}class Seeder{async call(e){const t=new e;await t.run()}}QueryBuilder.macro("populate",async function(e,t){const r=(await this.adapter.raw("db")).collection(this.tableName),i=(null==t?void 0:t.from)||`${e}s`,a=(null==t?void 0:t.localField)||`${e}_id`,s=(null==t?void 0:t.foreignField)||"_id",n=(null==t?void 0:t.as)||e,o=[];if(this.whereClauses&&this.whereClauses.length>0){var c,l;const e=(null===(c=(l=this.adapter).buildFilter)||void 0===c?void 0:c.call(l,this.whereClauses))||{};Object.keys(e).length>0&&o.push({$match:e})}if(null!=t&&t.select&&t.select.length>0){const e={};t.select.forEach(t=>{e[t]=1}),o.push({$lookup:{from:i,let:{localId:`$${a}`},pipeline:[{$match:{$expr:{$eq:[`$${s}`,"$$localId"]}}},{$project:e}],as:n}})}else o.push({$lookup:{from:i,localField:a,foreignField:s,as:n}});return o.push({$unwind:{path:`$${n}`,preserveNullAndEmptyArrays:!0}}),this.limitValue&&o.push({$limit:this.limitValue}),(await r.aggregate(o).toArray()).map(e=>{const{_id:t,...r}=e;return{id:t,_id:t,...r}})}),QueryBuilder.macro("exec",async function(){return await this.get()}),QueryBuilder.macro("aggregate",async function(e){const t=(await this.adapter.raw("db")).collection(this.tableName);return(await t.aggregate(e).toArray()).map(e=>{if(e._id){const{_id:t,...r}=e;return{id:t,_id:t,...r}}return e})});class ServiceProvider{constructor(e){this.app=e}register(){}boot(){}async shutdown(){}}class DatabaseProvider extends ServiceProvider{async register(){let e;console.log("⚙️ DatabaseProvider: Initializing...");try{e=this.app.container.resolve("DatabaseConfig"),console.log("✓ DatabaseProvider: Configuration loaded successfully")}catch(e){return void console.warn("⚠ DatabaseProvider: No configuration found - Skipping setup")}try{let t;switch(console.log(`⚙️ DatabaseProvider: Loading ${e.type} adapter...`),e.type){case"mysql":const{MySQLAdapter:r}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,707));t=new r;break;case"mongodb":const{MongoAdapter:i}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,697));t=new i;break;case"postgres":const{PostgresAdapter:a}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,590));t=new a;break;default:throw new Error(`Unsupported database type: ${e.type}`)}console.log(`✓ DatabaseProvider: ${e.type} adapter loaded`),this.app.container.singleton("DatabaseAdapter",()=>t),this.app.container.singleton("DBConnection",async()=>{console.log(`⚙️ DatabaseProvider: Connecting to ${e.type}...`);const r=await t.connect(e);return Model.setAdapter(t),Schema.setAdapter(t),console.log(`✓ DatabaseProvider: Connected to ${e.type} database '${e.database}'`),r}),console.log("✅ DatabaseProvider: Ready")}catch(e){throw console.error("✗ DatabaseProvider: Initialization failed",e),e}}async shutdown(){try{console.log("⚙️ DatabaseProvider: Closing connection...");const e=await this.app.container.make("DatabaseAdapter");await e.disconnect(),console.log("✓ DatabaseProvider: Connection closed")}catch(e){}}}var __webpack_export_target__=exports;for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__]=__webpack_exports__[__webpack_i__];__webpack_exports__.__esModule&&Object.defineProperty(__webpack_export_target__,"__esModule",{value:!0})})();
|
|
2
2
|
//# sourceMappingURL=arcanox.js.map
|