@mobtakronio/schemakit
Version:
Dynamic entity management system with runtime schema creation, validation, and CRUD operations for Node.js backends.
1 lines • 58.4 kB
JavaScript
var k=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var a=(i,e)=>k(i,"name",{value:e,configurable:!0});var j=(i,e)=>()=>(i&&(e=i(i=0)),e);var Ce=(i,e)=>{for(var t in e)k(i,t,{get:e[t],enumerable:!0})},ve=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Se(e))!Ae.call(i,r)&&r!==t&&k(i,r,{get:()=>e[r],enumerable:!(n=xe(e,r))||n.enumerable});return i};var Ie=i=>ve(k({},"__esModule",{value:!0}),i);var Y,p,A,de,C,ue,v,fe,I,pe,N,ye,O,me,P,m,E=j(()=>{"use strict";Y=class Y extends Error{constructor(e,t={}){super(e),this.name="SchemaKitError",this.code=t.code||"UNEXPECTED_ERROR",t.cause!==void 0&&(this.cause=t.cause),t.context&&(this.context=t.context)}toJSON(){return{name:this.name,message:this.message,code:this.code,context:this.context,stack:this.stack,cause:this.cause instanceof Error?typeof this.cause.toJSON=="function"?this.cause.toJSON():{name:this.cause.name,message:this.cause.message,stack:this.cause.stack}:this.cause}}getContext(){return this.context||{}}};a(Y,"SchemaKitError");p=Y,A=class A extends p{constructor(e,t,n={}){super("Validation failed",{code:A.ERROR_CODE,cause:n.cause,context:{entityName:t,errorCount:e.length,...n.context}}),this.name="ValidationError",this.entityName=t,this.errors=e}};a(A,"ValidationError"),A.ERROR_CODE="VALIDATION_FAILED";de=A,C=class C extends p{constructor(e,t,n={}){super(e,{code:C.ERROR_CODE,cause:n.cause,context:{entityName:t,...n.context}}),this.name="SchemaError",this.entityName=t}};a(C,"SchemaError"),C.ERROR_CODE="SCHEMA_ERROR";ue=C,v=class v extends p{constructor(e,t,n={}){super(`Entity ${e} with id ${t} not found`,{code:v.ERROR_CODE,cause:n.cause,context:{entityName:e,id:t,...n.context}}),this.name="EntityNotFoundError",this.entityName=e,this.id=t}};a(v,"EntityNotFoundError"),v.ERROR_CODE="NOT_FOUND";fe=v,I=class I extends p{constructor(e,t,n={}){super(`Permission denied for ${e} on ${t}`,{code:I.ERROR_CODE,cause:n.cause,context:{action:e,entityName:t,...n.context}}),this.name="PermissionError",this.action=e,this.entityName=t}};a(I,"PermissionError"),I.ERROR_CODE="PERMISSION_DENIED";pe=I,N=class N extends p{constructor(e,t,n={}){super(`Workflow ${e} failed at action ${t}`,{code:N.ERROR_CODE,cause:n.cause,context:{workflowName:e,action:t,...n.context}}),this.name="WorkflowError",this.workflowName=e,this.action=t}};a(N,"WorkflowError"),N.ERROR_CODE="WORKFLOW_ERROR";ye=N,O=class O extends p{constructor(e,t={}){super(`Failed to load schema for entity ${e}`,{code:O.ERROR_CODE,cause:t.cause,context:{entityName:e,...t.context}}),this.name="SchemaLoadError",this.entityName=e}};a(O,"SchemaLoadError"),O.ERROR_CODE="SCHEMA_LOAD_ERROR";me=O,P=class P extends p{constructor(e,t={}){let n=t.cause instanceof Error?`Database operation '${e}' failed: ${t.cause.message}`:`Database operation '${e}' failed`;super(n,{code:P.ERROR_CODE,cause:t.cause,context:{operation:e,...t.context}}),this.name="DatabaseError",this.operation=e}};a(P,"DatabaseError"),P.ERROR_CODE="DATABASE_ERROR";m=P});var G={};Ce(G,{DrizzleAdapter:()=>F,SqlBuilder:()=>f});var f,M,F,U=j(()=>{"use strict";V();E();f={quoteIdent(i,e){return String(i).split(".").map(r=>{if(!/^[_a-zA-Z][_a-zA-Z0-9]*$/.test(r))throw new Error(`Invalid identifier: ${i}`);return e==="mysql"?`\`${r}\``:`"${r}"`}).join(".")},placeholder(i,e){return e==="postgres"?`$${i+1}`:"?"},normalizeDirection(i){return(i||"ASC").toUpperCase()==="DESC"?"DESC":"ASC"},buildWhere(i=[],e){let t=[],n=[];for(let r of i){let s=(r.operator||"eq").toLowerCase(),o=f.quoteIdent(String(r.field),e);if(s==="contains"||s==="startswith"||s==="endswith"){let u=String(r.value??"");s==="contains"&&(u=`%${u}%`),s==="startswith"&&(u=`${u}%`),s==="endswith"&&(u=`%${u}`),t.push(`${o} LIKE ${f.placeholder(n.length,e)}`),n.push(u);continue}if(s==="in"||s==="nin"){let u=Array.isArray(r.value)?r.value:[];if(u.length===0){t.push(s==="in"?"1=0":"1=1");continue}let y=u.map((w,T)=>f.placeholder(n.length+T,e));t.push(`${o} ${s==="in"?"IN":"NOT IN"} (${y.join(", ")})`),n.push(...u);continue}let l={eq:"=",neq:"!=",gt:">",lt:"<",gte:">=",lte:"<=",like:"LIKE"}[s]||"=",d=f.placeholder(n.length,e);t.push(`${o} ${l} ${d}`),n.push(r.value)}return{clause:t.length?`WHERE ${t.join(" AND ")}`:"",params:n}},buildOrderBy(i=[],e){return!i||i.length===0?"":`ORDER BY ${i.map(t=>{let n=f.quoteIdent(String(t.field),e),r=t.direction||t.dir;return`${n} ${f.normalizeDirection(r)}`}).join(", ")}`},buildPagination(i={}){let e=[];return i.limit!=null&&e.push(`LIMIT ${Number(i.limit)}`),i.offset!=null&&e.push(`OFFSET ${Number(i.offset)}`),e.join(" ")},buildSelect(i,e,t,n){let r=f.quoteIdent(i,n),{clause:s,params:o}=f.buildWhere(e,n),c=f.buildOrderBy(t.orderBy,n),l=f.buildPagination(t);return{sql:[`SELECT * FROM ${r}`,s,c,l].filter(Boolean).join(" "),params:o}},buildInsert(i,e,t){let n=f.quoteIdent(i,t),s=Object.keys(e).map(l=>f.quoteIdent(l,t)),o=Object.values(e),c=o.map((l,d)=>f.placeholder(d,t));return{sql:`INSERT INTO ${n} (${s.join(", ")}) VALUES (${c.join(", ")})`,params:o}},buildUpdate(i,e,t,n,r="id"){let s=f.quoteIdent(i,n),o=Object.keys(t),c=o.map((y,w)=>`${f.quoteIdent(y,n)} = ${f.placeholder(w,n)}`),l=f.placeholder(o.length,n),d=`UPDATE ${s} SET ${c.join(", ")} WHERE ${f.quoteIdent(r,n)} = ${l}`,u=[...Object.values(t),e];return{sql:d,params:u}},buildDelete(i,e,t,n="id"){return{sql:`DELETE FROM ${f.quoteIdent(i,t)} WHERE ${f.quoteIdent(n,t)} = ${f.placeholder(0,t)}`,params:[e]}},buildCount(i,e,t){let n=f.quoteIdent(i,t),{clause:r,params:s}=f.buildWhere(e,t);return{sql:`SELECT COUNT(*) as count FROM ${n} ${r}`.trim(),params:s}}},M=class M extends R{constructor(t={}){super(t);this.db=null;this.client=null;this.sql=null;this.dbType=t.type||"sqlite"}async connect(){if(!this.db){try{let t=await import("drizzle-orm");this.sql=t.sql}catch{throw new m("connect",{cause:new Error("drizzle-orm is not installed"),context:{dependency:"drizzle-orm"}})}this.dbType==="postgres"?await this.connectPostgres():this.dbType==="mysql"?await this.connectMySQL():await this.connectSQLite()}}async disconnect(){try{this.dbType!=="sqlite"&&this.client?.end?await this.client.end():this.dbType==="sqlite"&&this.client?.close&&this.client.close(),this.db=null,this.client=null}catch(t){throw new m("disconnect",{cause:t})}}isConnected(){return this.db!==null}async query(t,n=[]){await this.ensureConnected();try{let r=this.createSqlQuery(t,n),s=await this.db.execute(r);return Array.isArray(s)?s:s.rows||[]}catch(r){throw new m("query",{cause:r,context:{sql:t,params:n}})}}async execute(t,n=[]){await this.ensureConnected();try{let r=this.createSqlQuery(t,n),s=await this.db.execute(r);return this.extractExecMeta(s)}catch(r){throw new m("execute",{cause:r,context:{sql:t,params:n}})}}async transaction(t){await this.ensureConnected();try{return await this.db.transaction(async n=>{let r=new M(this.config);return r.db=n,r.sql=this.sql,r.dbType=this.dbType,t(r)})}catch(n){throw new m("transaction",{cause:n})}}async tableExists(t,n){return this.dbType==="sqlite"?(await this.query(`SELECT name FROM sqlite_master WHERE type='table' AND name=${this.valuePlaceholder(1)} LIMIT 1`,[n])).length>0:this.dbType==="postgres"?!!(await this.query(`SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = ${this.valuePlaceholder(0)} AND table_name = ${this.valuePlaceholder(1)}) as exists`,[t,n]))[0]?.exists:!!(await this.query(`SELECT EXISTS (SELECT * FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ${this.valuePlaceholder(0)}) as \`exists\``,[n]))[0]?.exists}async createTable(t,n){let r=[],s=[];for(let l of n){let d=[f.quoteIdent(l.name,this.dbType),this.mapDataType(l.type)];if(l.autoIncrement&&d.push("GENERATED ALWAYS AS IDENTITY"),l.default!==void 0&&d.push("DEFAULT "+this.formatDefault(l.default)),l.notNull&&!l.primaryKey&&d.push("NOT NULL"),l.unique&&d.push("UNIQUE"),l.primaryKey&&d.push("PRIMARY KEY"),r.push(d.join(" ")),l.references){let u=l.references,y=[`FOREIGN KEY (${f.quoteIdent(l.name,this.dbType)})`,`REFERENCES ${f.quoteIdent(u.table,this.dbType)}(${f.quoteIdent(u.column,this.dbType)})`];u.onDelete&&y.push(`ON DELETE ${u.onDelete}`),u.onUpdate&&y.push(`ON UPDATE ${u.onUpdate}`),s.push(y.join(" "))}}let o=s.length?`${r.join(", ")}, ${s.join(", ")}`:r.join(", "),c=`CREATE TABLE IF NOT EXISTS ${f.quoteIdent(t,this.dbType)} (${o})`;await this.execute(c)}async getTableColumns(t){if(this.dbType==="sqlite")return(await this.query(`PRAGMA table_info(${f.quoteIdent(t,this.dbType)})`)).map(s=>({name:s.name,type:s.type,notNull:!!s.notnull,default:s.dflt_value,primaryKey:!!s.pk}));if(this.dbType==="postgres"){let r=`SELECT column_name as name, data_type as type, is_nullable = 'NO' as "notNull", column_default as "default" FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ${this.valuePlaceholder(0)} ORDER BY ordinal_position`;return this.query(r,[t])}let n=`SELECT COLUMN_NAME as name, DATA_TYPE as type, IS_NULLABLE = 'NO' as notNull, COLUMN_DEFAULT as \`default\` FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${this.valuePlaceholder(0)} ORDER BY ORDINAL_POSITION`;return this.query(n,[t])}async select(t,n,r){let{sql:s,params:o}=f.buildSelect(t,n,r,this.dbType);return this.query(s,o)}async insert(t,n){try{let{sql:r,params:s}=f.buildInsert(t,n,this.dbType);return this.dbType==="postgres"?(await this.query(`${r} RETURNING *`,s))[0]||{...n}:{id:(await this.execute(r,s)).lastInsertId,...n}}catch(r){throw new m("execute",{cause:r,context:{sql:`INSERT INTO ${t}`,params:n}})}}async update(t,n,r,s){try{let{sql:o,params:c}=f.buildUpdate(t,r,s,this.dbType,n);if((await this.execute(o,c)).changes===0)throw new Error(`No record found with id: ${r}`);return{id:r,...s}}catch(o){throw new m("execute",{cause:o,context:{sql:`UPDATE ${t}`,params:{idField:n,id:r,...s}}})}}async delete(t,n,r){try{let{sql:s,params:o}=f.buildDelete(t,r,this.dbType,n);if((await this.execute(s,o)).changes===0)throw new Error(`No record found with id: ${r}`)}catch(s){throw new m("execute",{cause:s,context:{sql:`DELETE FROM ${t}`,params:{idField:n,id:r}}})}}async count(t,n){let{sql:r,params:s}=f.buildCount(t,n,this.dbType),o=await this.query(r,s);return Number(o[0]?.count)||0}async findById(t,n){let r=f.quoteIdent(t,this.dbType),s=f.quoteIdent("id",this.dbType),o=`SELECT * FROM ${r} WHERE ${s} = ${this.valuePlaceholder(0)} LIMIT 1`;return(await this.query(o,[n]))[0]||null}async createSchema(t){this.dbType==="postgres"?await this.execute(`CREATE SCHEMA IF NOT EXISTS ${f.quoteIdent(t,this.dbType)}`):this.dbType==="mysql"&&await this.execute(`CREATE DATABASE IF NOT EXISTS ${f.quoteIdent(t,this.dbType)}`)}async dropSchema(t){this.dbType==="postgres"?await this.execute(`DROP SCHEMA IF EXISTS ${f.quoteIdent(t,this.dbType)} CASCADE`):this.dbType==="mysql"&&await this.execute(`DROP DATABASE IF EXISTS ${f.quoteIdent(t,this.dbType)}`)}async listSchemas(){return this.dbType==="sqlite"?["main"]:this.dbType==="postgres"?(await this.query("SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema', 'pg_catalog', 'pg_toast')")).map(r=>r.schema_name):(await this.query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')")).map(n=>n.SCHEMA_NAME)}async ensureConnected(){this.db||await this.connect()}valuePlaceholder(t){return f.placeholder(t,this.dbType)}createSqlQuery(t,n){if(!this.sql)return{sql:t,params:n};if(n.length===0)return this.sql.raw(t);let r=this.sql;if(r&&typeof r.fromList=="function"){let s=[],o=this.dbType==="postgres"?/\$\d+/:/\?/,c=t.split(o);for(let l=0;l<c.length;l++)c[l]&&s.push(r.raw(c[l])),l<c.length-1&&l<n.length&&s.push(n[l]);return r.fromList(s)}return{sql:t,params:n}}extractExecMeta(t){return this.dbType==="postgres"?{changes:t.rowCount||0,lastInsertId:t.rows?.[0]?.id}:this.dbType==="mysql"?{changes:t.affectedRows||0,lastInsertId:t.insertId}:{changes:t.changes||0,lastInsertId:t.lastInsertRowid}}mapDataType(t){return{postgres:{string:"VARCHAR(255)",text:"TEXT",integer:"INTEGER",boolean:"BOOLEAN",date:"DATE",datetime:"TIMESTAMP",json:"JSONB",uuid:"UUID"},mysql:{string:"VARCHAR(255)",text:"TEXT",integer:"INT",boolean:"BOOLEAN",date:"DATE",datetime:"DATETIME",json:"JSON"},sqlite:{string:"TEXT",text:"TEXT",integer:"INTEGER",boolean:"INTEGER",date:"TEXT",datetime:"TEXT",json:"TEXT"}}[this.dbType]?.[t.toLowerCase()]||t.toUpperCase()}formatDefault(t){return t===null?"NULL":t==="CURRENT_TIMESTAMP"?"CURRENT_TIMESTAMP":typeof t=="string"?`'${t.replace(/'/g,"''")}'`:typeof t=="boolean"&&this.dbType==="sqlite"?t?"1":"0":String(t)}async connectPostgres(){let t,n;try{t=(await import("pg")).Client}catch{throw new Error("pg is not installed")}try{n=(await import("drizzle-orm/node-postgres")).drizzle}catch{throw new Error("drizzle-orm node-postgres not available")}let s=typeof this.config.connectionString=="string"&&this.config.connectionString.length>0?{connectionString:this.config.connectionString,ssl:this.config.ssl?{rejectUnauthorized:!1}:void 0}:{host:this.config.host||"localhost",port:this.config.port||5432,database:this.config.database||"postgres",user:this.config.user,password:this.config.password,ssl:this.config.ssl?{rejectUnauthorized:!1}:void 0},o=new t(s);await o.connect(),this.client=o,this.db=n(o)}async connectMySQL(){let t,n;try{t=await import("mysql2/promise")}catch{throw new Error("mysql2 is not installed")}try{n=(await import("drizzle-orm/mysql2")).drizzle}catch{throw new Error("drizzle-orm mysql2 not available")}this.client=await t.createConnection({host:this.config.host||"localhost",port:this.config.port||3306,database:this.config.database,user:this.config.user,password:this.config.password}),this.db=n(this.client)}async connectSQLite(){let t,n;try{t=(await import("better-sqlite3")).default}catch{throw new Error("better-sqlite3 is not installed")}try{n=(await import("drizzle-orm/better-sqlite3")).drizzle}catch{throw new Error("drizzle-orm better-sqlite3 not available")}let r=this.config.filename||":memory:";this.client=new t(r),this.client?.pragma?.("foreign_keys = ON"),r!==":memory:"&&this.client?.pragma?.("journal_mode = WAL"),this.db=n(this.client)}get drizzleInstance(){return this.db}};a(M,"DrizzleAdapter");F=M});var J,R,V=j(()=>{"use strict";E();J=class J{constructor(e={}){this.config=e}static async create(e="sqlite",t={}){switch(e.toLowerCase()){case"sqlite":case"postgres":case"mysql":let n=await Promise.resolve().then(()=>(U(),G));return new n.DrizzleAdapter({...t,type:e});default:throw new m("create",{cause:new Error(`Unsupported adapter type: ${e}`)})}}static createSync(e="sqlite",t={}){switch(e.toLowerCase()){case"sqlite":case"postgres":case"mysql":let n=(U(),Ie(G));return new n.DrizzleAdapter({...t,type:e});default:throw new m("create",{cause:new Error(`Unsupported adapter type: ${e}`)})}}};a(J,"DatabaseAdapter");R=J});V();var x="public";var X=class X{constructor(e){this.adapter=null;this._isQueryBuilder=!1;this._select=[];this._from="";this._where=[];this._orWhere=[];this._orderBy=[];this.tenantId=e.tenantId||x,this.adapterConfig={type:e.adapter,config:e.config||{}},this.multiTenancy=e.multiTenancy||{strategy:"column",columnName:"tenant_id"}}async init(){this.adapter||(this.adapter=await R.create(this.adapterConfig.type,this.adapterConfig.config))}async ensureAdapter(){this.adapter||await this.init()}resolveTableName(e){switch(this.multiTenancy.strategy){case"schema":return`${this.tenantId}.${e}`;case"table-prefix":let t=this.multiTenancy.separator||"_";return`${this.tenantId}${t}${e}`;case"column":case"none":default:return e}}addTenantFilter(e){if(this.multiTenancy.strategy==="column"&&this.tenantId!==x){let t=this.multiTenancy.columnName||"tenant_id";return[...e,{field:t,operator:"eq",value:this.tenantId}]}return e}addTenantData(e){if(this.multiTenancy.strategy==="column"&&this.tenantId!==x){let t=this.multiTenancy.columnName||"tenant_id";return{...e,[t]:this.tenantId}}return e}fork(){let e=Object.create(this);return e._isQueryBuilder=!0,e._select=[],e._from="",e._where=[],e._orWhere=[],e._orderBy=[],e._limit=void 0,e._offset=void 0,e}asBuilder(){return this._isQueryBuilder?this:this.fork()}select(e){let t=this.asBuilder();return t._select=Array.isArray(e)?e:[e],t}from(e){let t=this.asBuilder();return t._from=e,t}where(e){let t=this.asBuilder();return t._where.push(e),t}orWhere(e){let t=this.asBuilder();return t._orWhere.push(e),t}orderBy(e,t="ASC"){let n=this.asBuilder();return n._orderBy.push({field:e,dir:t}),n}limit(e){let t=this.asBuilder();return t._limit=e,t}offset(e){let t=this.asBuilder();return t._offset=e,t}buildFilters(){let e=[];for(let t of this._where){if(t.field&&t.operator){let{field:n,operator:r,value:s}=t;e.push({field:n,value:s,operator:r});continue}for(let n in t){let r=t[n];Array.isArray(r)?e.push({field:n,value:r,operator:"in"}):r===null?e.push({field:n,value:r,operator:"isNull"}):e.push({field:n,value:r,operator:"eq"})}}return e}buildOptions(){let e={};return this._orderBy.length>0&&(e.orderBy=this._orderBy),this._limit!==void 0&&(e.limit=this._limit),this._offset!==void 0&&(e.offset=this._offset),this._select.length>0&&(e.select=this._select),e}async get(e){await this.ensureAdapter();let t=this.buildFilters(),n=this.addTenantFilter(t),r=this.buildOptions(),s=e||this._from,o=this.resolveTableName(s),c=await this.adapter.select(o,n,r);return this.reset(),c}async insert(e,t){await this.ensureAdapter();let n=this.resolveTableName(e),r=this.addTenantData(t),s=await this.adapter.insert(n,r);return this.reset(),s}async update(e,t){await this.ensureAdapter();let n=this.resolveTableName(e),r=this.addTenantData(t),o=this.buildFilters()[0],c=o?.value,l=o?.field||"id",d=await this.adapter.update(n,l,c,r);return this.reset(),d}async delete(e){await this.ensureAdapter();let t=this.resolveTableName(e),r=this.buildFilters()[0],s=r?.value,o=r?.field||"id",c=await this.adapter.delete(t,o,s);return this.reset(),c}reset(){return this._select=[],this._from="",this._where=[],this._orWhere=[],this._orderBy=[],this._limit=void 0,this._offset=void 0,this}async getAdapter(){return await this.ensureAdapter(),this.adapter}async raw(e,t){return await this.ensureAdapter(),this.adapter.query(e,t)}async transaction(e){return await this.ensureAdapter(),this.adapter.transaction(async t=>{let n=Object.create(this);return n.adapter=t,e(n)})}withTenant(e){let t=Object.create(this);return t.tenantId=e,t._select=[],t._from="",t._where=[],t._orWhere=[],t._orderBy=[],t._limit=void 0,t}getTenantId(){return this.tenantId}getMultiTenancyConfig(){return{...this.multiTenancy}}async createTenantSchema(e){if(this.multiTenancy.strategy!=="schema")throw new Error("Schema creation is only supported for schema-based multi-tenancy");await this.ensureAdapter(),await this.adapter.createSchema(e)}async dropTenantSchema(e){if(this.multiTenancy.strategy!=="schema")throw new Error("Schema dropping is only supported for schema-based multi-tenancy");await this.ensureAdapter(),await this.adapter.dropSchema(e)}async listTenantSchemas(){if(this.multiTenancy.strategy!=="schema")throw new Error("Schema listing is only supported for schema-based multi-tenancy");return await this.ensureAdapter(),this.adapter.listSchemas()}};a(X,"DB");var $=X;E();function he(i){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)}a(he,"isValidIdentifier");function ge(i,e){if(i==null)return i;switch(e){case"string":return String(i);case"integer":{let t=Number(i);return Number.isFinite(t)?Math.trunc(t):i}case"number":{let t=Number(i);return Number.isFinite(t)?t:i}case"boolean":if(typeof i=="boolean")return i;if(typeof i=="string"){let t=i.toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return!!i;case"datetime":{if(i instanceof Date)return i;let t=new Date(String(i));return isNaN(t.getTime())?i:t.toISOString()}case"json":if(typeof i=="string")try{return JSON.parse(i)}catch{return i}return i;case"array":return Array.isArray(i)?i:[i];default:return i}}a(ge,"coerceType");var Z=class Z{constructor(){this.name="simple"}buildSchema(e,t,n){let r={},s=new Set;for(let o of t)r[o.field_name]={type:o.field_type,required:!!o.field_is_required},s.add(o.field_name);return{entityId:e,fieldMap:r,allowedKeys:s,unknownFieldPolicy:n?.unknownFieldPolicy??"strip"}}validate(e,t,n){if(typeof n!="object"||n===null)return{ok:!1,errors:[{path:"",message:"Invalid payload",code:"invalid"}]};let r={},s=[];for(let[o,c]of Object.entries(n)){if(!he(o)||!t.allowedKeys.has(o)){t.unknownFieldPolicy==="error"&&s.push({path:o,message:"Unknown field",code:"unknown"});continue}let l=t.fieldMap[o];r[o]=ge(c,l.type)}for(let[o,c]of Object.entries(t.fieldMap))if(c.required&&(r[o]===void 0||r[o]===null)){if(e==="update"&&r[o]===void 0)continue;s.push({path:o,message:"Field is required",code:"required"})}return s.length>0?{ok:!1,errors:s}:{ok:!0,data:r}}sanitizeFilters(e,t){let n={},r=[];for(let[s,o]of Object.entries(t)){if(!he(s)||!e.allowedKeys.has(s)){r.push({path:s,message:"Unknown filter field",code:"unknown"});continue}let c=e.fieldMap[s];n[s]=ge(o,c.type)}return{filters:n,errors:r.length?r:void 0}}};a(Z,"SimpleValidationAdapter");var D=Z;var te=class te{constructor(e){this.restrictions={}}setRoleRestrictions(e){this.restrictions=e}getExposedConditions(e){let t=e.user?.roles||[];for(let n of t){let r=this.restrictions[n]?.[0];if(r?.conditions)return r.conditions.filter(s=>s.exposed)}return[]}};a(te,"RLSPermissionManager");var ee=te,ne=class ne{constructor(e,t,n,r,s){this.db=e;this.entityName=t;this.tableName=n;this.fields=r;this.views=s;this.rlsManager=null}setRLSRestrictions(e){this.rlsManager||(this.rlsManager=new ee(this.db)),this.rlsManager.setRoleRestrictions(e)}async executeView(e,t={},n={}){let r=this.views.find(w=>w.view_name===e);if(!r)throw new Error(`View '${e}' not found for entity '${this.entityName}'`);let s=this.db.select("*").from(this.tableName);s=this.applyViewSelect(s,r),s=this.applyViewFilters(s,r),s=this.applyUserFilters(s,n),s=this.applySorting(s,r),s=await this.applyRLSRestrictions(s,t);let{page:o,limit:c,offset:l}=this.resolvePagination(n);c&&(s=s.limit(c)),l&&typeof s.offset=="function"&&(s=s.offset(l));let d=await(s?.get?s.get():this.db.get()),u=d.length;try{if(typeof this.db.getAdapter=="function"){let T=await this.db.getAdapter(),Re=this.buildCountFilters(r,n,t);T&&typeof T.count=="function"&&(u=await T.count(this.tableName,Re))}}catch{u=d.length}let y={results:d,total:u,fields:this.fields,meta:{entityName:this.entityName,viewName:e}};return n.stats&&(y.stats=this.buildDefaultStats(u)),y}applyViewSelect(e,t){return t.view_fields&&t.view_fields.length>0&&(e=this.db.select(t.view_fields).from(this.tableName)),e}applyViewFilters(e,t){if(t.view_filters)for(let[n,r]of Object.entries(t.view_filters))e=e.where({[n]:r});else if(t.view_query_config?.filters)for(let[n,r]of Object.entries(t.view_query_config.filters))e=e.where({[n]:r});return e}applyUserFilters(e,t){if(t.filters)for(let[n,r]of Object.entries(t.filters))e=e.where({[n]:r});return e}applySorting(e,t){let n=t.view_sort||t.view_query_config?.sorting||[];if(n.length>0){for(let s of n){let o=String(s.direction||"asc").toUpperCase();e=e.orderBy(s.field,o)}return e}let r=this.fields.find(s=>s.field_name==="id")?.field_name||this.fields.find(s=>/_id$/i.test(s.field_name))?.field_name||this.fields[0]?.field_name;return r||(r={system_entities:"entity_id",system_fields:"field_id",system_permissions:"permission_id",system_views:"view_id",system_workflows:"workflow_id",system_rls:"rls_id"}[this.tableName]||"id"),e.orderBy(r,"DESC")}resolvePagination(e){let t=Math.max(1,e.pagination?.page||1),n=Math.max(1,e.pagination?.limit||10),r=(t-1)*n;return{page:t,limit:n,offset:r}}buildDefaultStats(e){return[{id:null,title:"All",total:e,filterType:"group",processHubRoles:[],buttons:[],items:[],isDefault:!1}]}buildCountFilters(e,t,n){let r=[];if(e.view_filters)for(let[s,o]of Object.entries(e.view_filters))r.push({field:s,value:o,operator:"eq"});else if(e.view_query_config?.filters)for(let[s,o]of Object.entries(e.view_query_config.filters))r.push({field:s,value:o,operator:"eq"});if(t.filters)for(let[s,o]of Object.entries(t.filters))r.push({field:s,value:o,operator:"eq"});return n.user?.id&&r.push({field:"created_by",value:n.user.id,operator:"eq"}),r}async applyRLSRestrictions(e,t){if(!this.rlsManager||!t.user)return e;try{return t.user?.id&&(e=e.where({created_by:t.user.id})),e}catch(n){return console.warn("Failed to apply RLS restrictions:",n),e}}getExposedConditions(e){return this.rlsManager?this.rlsManager.getExposedConditions(e):[]}};a(ne,"ViewManager");var B=ne;function g(i,e){if(typeof i!="string")return e;try{return JSON.parse(i)}catch{return e}}a(g,"safeJsonParse");function ut(i,e=!1){try{return JSON.stringify(i,null,e?2:0)}catch{return""}}a(ut,"safeJsonStringify");function ft(i){if(typeof i!="string")return!1;try{return JSON.parse(i),!0}catch{return!1}}a(ft,"isValidJson");function pt(i,e){return i==null?e:typeof i=="string"?g(i,e):typeof i=="object"?i:e}a(pt,"parseJsonField");function yt(i){if(i===null||typeof i!="object")return i;try{return JSON.parse(JSON.stringify(i))}catch{return i}}a(yt,"deepClone");function Ne(i,e){let t={...i};for(let n in e)if(e.hasOwnProperty(n)){let r=e[n],s=t[n];b(r)&&b(s)?t[n]=Ne(s,r):t[n]=r}return t}a(Ne,"deepMerge");function b(i){return i!==null&&typeof i=="object"&&i.constructor===Object&&Object.prototype.toString.call(i)==="[object Object]"}a(b,"isPlainObject");function mt(i,e,t){if(!i||typeof i!="object")return t;let n=e.split("."),r=i;for(let s of n){if(r==null||!(s in r))return t;r=r[s]}return r}a(mt,"getNestedProperty");function Oe(i,e,t){let n=e.split("."),r=i;for(let s=0;s<n.length-1;s++){let o=n[s];(!(o in r)||!b(r[o]))&&(r[o]={}),r=r[o]}return r[n[n.length-1]]=t,i}a(Oe,"setNestedProperty");function Pe(i,e=!1){let t={};for(let n in i)if(i.hasOwnProperty(n)){let r=i[n];if(r===void 0||e&&r===null)continue;if(b(r)){let s=Pe(r,e);Object.keys(s).length>0&&(t[n]=s)}else t[n]=r}return t}a(Pe,"removeUndefinedValues");function we(i){if(!b(i))return i;let e={};for(let t in i)if(i.hasOwnProperty(t)){let n=t.replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),r=i[t];b(r)?e[n]=we(r):Array.isArray(r)?e[n]=r.map(s=>b(s)?we(s):s):e[n]=r}return e}a(we,"toCamelCase");function be(i){if(!b(i))return i;let e={};for(let t in i)if(i.hasOwnProperty(t)){let n=t.replace(/[A-Z]/g,s=>`_${s.toLowerCase()}`),r=i[t];b(r)?e[n]=be(r):Array.isArray(r)?e[n]=r.map(s=>b(s)?be(s):s):e[n]=r}return e}a(be,"toSnakeCase");function ht(i,e){let t={};for(let n of e)n in i&&(t[n]=i[n]);return t}a(ht,"pick");function gt(i,e){let t={...i};for(let n of e)delete t[n];return t}a(gt,"omit");function $e(i,e){if(i===e)return!0;if(i===null||e===null||i===void 0||e===void 0)return i===e;if(typeof i!=typeof e)return!1;if(typeof i!="object")return i===e;if(Array.isArray(i)!==Array.isArray(e))return!1;let t=Object.keys(i),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r of t)if(!n.includes(r)||!$e(i[r],e[r]))return!1;return!0}a($e,"deepEqual");function qe(i,e=""){let t={};for(let n in i)if(i.hasOwnProperty(n)){let r=e?`${e}.${n}`:n,s=i[n];b(s)?Object.assign(t,qe(s,r)):t[r]=s}return t}a(qe,"flattenObject");function wt(i){let e={};for(let t in i)i.hasOwnProperty(t)&&Oe(e,t,i[t]);return e}a(wt,"unflattenObject");var ie=class ie{constructor(e){this.db=e}async loadEntityDefinition(e){let t=await this.db.select("*").from("system_entities").where({entity_name:e}).get(),n=Array.isArray(t)?t:[t];if(!n.length||!n[0])return null;let r=n[0];return r.metadata&&typeof r.metadata=="string"&&(r.metadata=g(r.metadata,{})),r}async loadFields(e){return(await this.db.select("*").from("system_fields").where({field_entity_id:e}).get()).map(n=>({...n,metadata:n.metadata&&typeof n.metadata=="string"?g(n.metadata,{}):n.metadata,validation_rules:n.validation_rules&&typeof n.validation_rules=="string"?g(n.validation_rules,{}):n.validation_rules}))}async loadPermissions(e){return(await this.db.select("*").from("system_permissions").where({permission_entity_id:e,permission_status:"active"}).get()).map(n=>({...n,conditions:n.conditions&&typeof n.conditions=="string"?g(n.conditions,{}):n.conditions}))}async loadWorkflows(e){return(await this.db.select("*").from("system_workflows").where({workflow_entity_id:e,workflow_status:"active"}).get()).map(n=>({...n,conditions:n.conditions&&typeof n.conditions=="string"?g(n.conditions,{}):n.conditions,actions:n.actions&&typeof n.actions=="string"?g(n.actions,[]):n.actions}))}async loadRLS(e){try{let t=await this.db.select("*").from("system_rls").where({rls_entity_id:e,rls_is_active:!0}).get();return(Array.isArray(t)?t:[]).map(r=>({...r,rls_config:r.rls_config&&typeof r.rls_config=="string"?g(r.rls_config,{relationbetweenconditions:"and",conditions:[]}):r.rls_config}))}catch{return[]}}async loadViews(e){return(await this.db.select("*").from("system_views").where({view_entity_id:e}).get()).map(n=>({...n,view_fields:typeof n.view_fields=="string"?g(n.view_fields,[]):n.view_fields,view_filters:typeof n.view_filters=="string"?g(n.view_filters,{}):n.view_filters,view_joins:typeof n.view_joins=="string"?g(n.view_joins,[]):n.view_joins,view_sort:typeof n.view_sort=="string"?g(n.view_sort,[]):n.view_sort}))}};a(ie,"MetadataLoader");var z=ie;var re=class re{constructor(e,t){this.permissions=e;this.rls=t}async check(e,t){let n=t.user?.roles||["public"],r=this.permissions().some(s=>n.includes(s.permission_role)&&s.permission_action===e&&s.permission_is_allowed)}buildRLSConditions(e){let t=[];for(let n of this.rls())n.rls_config?.conditions&&t.push(...n.rls_config.conditions);return t}resolveRLSValue(e,t){if(typeof e=="string"){if(e==="currentUser.id"||e==="$context.user.id")return t.user?.id;if(e==="currentUser.department"||e==="$context.user.department")return t.user?.department}return e}selectEffectiveRole(e,t){let n=e.filter(s=>Object.prototype.hasOwnProperty.call(t,s));if(n.length===0)return;let r=n.map(s=>({r:s,n:Number(s)})).filter(s=>Number.isFinite(s.n));return r.length>0?r.sort((s,o)=>o.n-s.n)[0].r:n[0]}buildQueryFilters(e,t={}){let n=[],r=e.user?.roles||[],s={};for(let d of this.rls()){let u=d.rls_config;u&&u.role&&(s[u.role]=u.rules||u.conditions?[u]:[u])}let o=this.selectEffectiveRole(r,s),l=(o?s[o]?.[0]:void 0)?.conditions||[];for(let d of l){let u=(d.op||d.operator||"eq").toLowerCase(),y=d.value;d.exposed&&t[d.field]!=null&&(y=t[d.field]),y=this.resolveRLSValue(y,e);let w=this.mapOperator(u);n.push({field:d.field,operator:w,value:y})}return n}getExposedConditions(e){let t=e.user?.roles||[],n={};for(let o of this.rls()){let c=o.rls_config;c&&c.role&&(n[c.role]=c.rules||c.conditions?[c]:[c])}let r=this.selectEffectiveRole(t,n);return((r?n[r]?.[0]:void 0)?.conditions||[]).filter(o=>o.exposed)}mapOperator(e){return{eq:"eq",neq:"neq",ne:"neq",gt:"gt",gte:"gte",lt:"lt",lte:"lte",like:"like",contains:"contains",startswith:"startswith",endswith:"endswith",in:"in",notin:"nin",nin:"nin"}[e]||"eq"}};a(re,"PermissionGuard");var W=re;var se=class se{constructor(e,t){this.db=e;this.tableName=t}async select(e={},t){let n=this.db.select(t?.select||"*").from(this.tableName);for(let[r,s]of Object.entries(e))n=n.where({[r]:s});if(t?.orderBy)for(let r of t.orderBy)n=n.orderBy(r.field,(r.direction||"ASC").toUpperCase());return t?.limit!=null&&(n=n.limit(t.limit)),n.get()}async findById(e,t){let n=await this.db.select("*").from(this.tableName).where({[e]:t}).get();return n&&n.length>0?n[0]:null}async insert(e){return this.db.insert(this.tableName,e)}async update(e,t,n){return this.db.where({[e]:t}).update(this.tableName,n)}async delete(e,t){await this.db.where({[e]:t}).delete(this.tableName)}};a(se,"EntityRepository");var K=se;import*as _e from"crypto";function q(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){let e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}a(q,"generateId");function Ct(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();try{return _e.randomUUID()}catch{return q()}}a(Ct,"generateUUID");function Le(){return Math.random().toString(36).substring(2,10)}a(Le,"generateShortId");function vt(i,e){let n=(e.get(i)||0)+1;return e.set(i,n),n.toString()}a(vt,"generateSequentialId");function It(){let i=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`${i}-${e}`}a(It,"generateTimestampId");function Nt(i){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(i)}a(Nt,"isValidUUID");function Ot(i,e="_"){return`${i}${e}${Le()}`}a(Ot,"generatePrefixedId");function H(){return new Date().toISOString()}a(H,"getCurrentTimestamp");function Te(i){if(i==null)return null;if(i instanceof Date)return isNaN(i.getTime())?null:i;if(typeof i=="string"){if(i.toLowerCase()==="datetime('now')")return new Date;let e=new Date(i);return isNaN(e.getTime())?null:e}if(typeof i=="number"){let e=new Date(i);return isNaN(e.getTime())?null:e}return null}a(Te,"parseDate");function qt(i,e="iso"){if(!i||isNaN(i.getTime()))throw new Error("Invalid date provided");switch(e.toLowerCase()){case"iso":return i.toISOString();case"date":return i.toISOString().split("T")[0];case"time":return i.toISOString().split("T")[1].split(".")[0];case"datetime":return i.toISOString().replace("T"," ").split(".")[0];case"timestamp":return i.getTime().toString();case"locale":return i.toLocaleString();case"localedate":return i.toLocaleDateString();case"localetime":return i.toLocaleTimeString();default:return ke(i,e)}}a(qt,"formatDate");function ke(i,e){let t=i.getUTCFullYear(),n=String(i.getUTCMonth()+1).padStart(2,"0"),r=String(i.getUTCDate()).padStart(2,"0"),s=String(i.getUTCHours()).padStart(2,"0"),o=String(i.getUTCMinutes()).padStart(2,"0"),c=String(i.getUTCSeconds()).padStart(2,"0");return e.replace(/YYYY/g,t.toString()).replace(/MM/g,n).replace(/DD/g,r).replace(/HH/g,s).replace(/mm/g,o).replace(/ss/g,c)}a(ke,"formatDateCustom");function Lt(i){return Te(i)!==null}a(Lt,"isValidDate");function kt(i){let e=new Date(i);return e.setHours(0,0,0,0),e}a(kt,"getStartOfDay");function Ft(i){let e=new Date(i);return e.setHours(23,59,59,999),e}a(Ft,"getEndOfDay");function Mt(i,e){let t=new Date(i);return t.setDate(t.getDate()+e),t}a(Mt,"addDays");function Ut(i,e){let t=new Date(i);return t.setHours(t.getHours()+e),t}a(Ut,"addHours");function Vt(i,e){let t=new Date(i);return t.setMinutes(t.getMinutes()+e),t}a(Vt,"addMinutes");function Bt(i,e){let t=e.getTime()-i.getTime();return Math.floor(t/(1e3*60*60*24))}a(Bt,"getDaysDifference");function zt(i,e){let t=e.getTime()-i.getTime();return Math.floor(t/(1e3*60*60))}a(zt,"getHoursDifference");function Fe(i,e){return i.getFullYear()===e.getFullYear()&&i.getMonth()===e.getMonth()&&i.getDate()===e.getDate()}a(Fe,"isSameDay");function Wt(i){return Fe(i,new Date)}a(Wt,"isToday");function Kt(i){return i.getTime()<Date.now()}a(Kt,"isPast");function Ht(i){return i.getTime()>Date.now()}a(Ht,"isFuture");function Qt(i){return new Date(i.getTime()+i.getTimezoneOffset()*6e4)}a(Qt,"toUTC");function jt(i){return new Date(i.getTime()-i.getTimezoneOffset()*6e4)}a(jt,"fromUTC");function Yt(i,e=new Date){let t=e.getFullYear()-i.getFullYear(),n=e.getMonth()-i.getMonth();return(n<0||n===0&&e.getDate()<i.getDate())&&t--,t}a(Yt,"getAge");function Gt(i){if(i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"'))return i.slice(1,-1);if(i.toLowerCase()==="datetime('now')")return H();if(i==="1"||i.toLowerCase()==="true")return!0;if(i==="0"||i.toLowerCase()==="false")return!1;if(/^\d+$/.test(i))return parseInt(i,10);if(/^\d+\.\d+$/.test(i))return parseFloat(i);let e=Te(i);return e?e.toISOString():i}a(Gt,"parseValue");function Q(i){return`${i}_id`}a(Q,"getPrimaryKeyColumn");function De(i,e,t,n){let r=Q(e),s=i.id||i[r]||q(),o=H(),c=typeof n=="string"&&n.startsWith("system_"),l={...i,[`${e}_created_at`]:o,[`${e}_modified_at`]:o,...t.user?.id&&{[`${e}_created_by`]:t.user.id,[`${e}_modified_by`]:t.user.id}};return c?(delete l.id,delete l[r],l):{...l,id:s,[r]:s}}a(De,"buildCreateRow");function Ee(i,e,t){let n=Q(e),r=H(),s={...i,[`${e}_modified_at`]:r,...t.user?.id&&{[`${e}_modified_by`]:t.user.id}};return delete s.id,delete s[n],s}a(Ee,"buildUpdateRow");var h=class h{constructor(e,t,n){this.initialized=!1;this.validationAdapter=null;this.compiledSchema=null;this.unknownFieldPolicy="strip";this.fields=[];this.permissions=[];this.workflow=[];this.rls=[];this.views=[];this.entityDefinition=null;this.tableName="";this.viewManager=null;this.permissionGuard=null;this.repository=null;this.entityName=e,this.tenantId=t,this.db=n,this.metadataLoader=new z(n),this.validationAdapter=new D}static create(e,t,n){let r=`${t}:${e}`;if(h.cache.has(r))return h.cache.get(r);let s=new h(e,t,n);return h.cache.set(r,s),s}get isInitialized(){return this.initialized}get name(){return this.entityName}get tenant(){return this.tenantId}setValidation(e,t){if(this.validationAdapter=e,t&&(this.unknownFieldPolicy=t),this.initialized){let n=this.entityDefinition?.entity_id||`${this.tenantId}:${this.entityName}`;this.compiledSchema=this.validationAdapter.buildSchema(n,this.fields,{unknownFieldPolicy:this.unknownFieldPolicy})}else this.compiledSchema=null}async initialize(e={}){if(!this.initialized)try{this.entityDefinition=await this.metadataLoader.loadEntityDefinition(this.entityName);let t=this.entityDefinition;if(!t)throw new Error(`Entity '${this.entityName}' not found`);let n=t.entity_id;this.fields=await this.metadataLoader.loadFields(n),this.permissions=await this.metadataLoader.loadPermissions(n),this.workflow=await this.metadataLoader.loadWorkflows(n),this.views=await this.metadataLoader.loadViews(n),this.rls=await this.metadataLoader.loadRLS(n),this.tableName=t.entity_table_name||this.entityName,await this.ensureTable(),this.repository=new K(this.db,this.tableName),this.permissionGuard=new W(()=>this.permissions,()=>this.rls);let r=t.entity_id||`${this.tenantId}:${this.entityName}`;this.compiledSchema=this.validationAdapter.buildSchema(r,this.fields,{unknownFieldPolicy:this.unknownFieldPolicy}),this.viewManager=new B(this.db,this.entityName,this.tableName,this.fields,this.views),this.initialized=!0}catch(t){throw new p(`Failed to initialize entity '${this.entityName}': ${t instanceof Error?t.message:String(t)}`,{code:"ENTITY_INITIALIZATION_FAILED",cause:t})}}async view(e,t={},n={}){if(await this.ensureInitialized(),!this.viewManager)throw new p("ViewManager not initialized");return this.viewManager.executeView(e,n,t)}async get(e={},t={}){await this.ensureInitialized();let n={...t,tenantId:this.tenantId};await this.permissionGuard.check("read",n);let r={...e};for(let s of this.permissionGuard.buildRLSConditions(n))r[s.field]=this.permissionGuard.resolveRLSValue(s.value,n);return this.repository.select(r)}async getById(e,t={}){await this.ensureInitialized();let n={...t,tenantId:this.tenantId};await this.permissionGuard.check("read",n);let r=this.getPrimaryKeyFieldName();return this.repository.findById(r,e)}async insert(e,t={}){await this.ensureInitialized();let n={...t,tenantId:this.tenantId};await this.permissionGuard.check("create",n);let r=this.validationAdapter.validate("create",this.compiledSchema,e);if(!r.ok){let l=r.errors||[],d=l.map(u=>`${u.path}: ${u.message}`).join("; ");throw new p(`Validation failed${d?`: ${d}`:""}`,{code:"VALIDATION_FAILED",context:l})}e=r.data;let s=this.getColumnPrefix(),o=De(e,s,n,this.tableName),c=await this.repository.insert(o);return await this.executeWorkflows("create",null,c,n),c}async update(e,t,n={}){await this.ensureInitialized();let r={...n,tenantId:this.tenantId};await this.permissionGuard.check("update",r);let s=this.validationAdapter.validate("update",this.compiledSchema,t);if(!s.ok){let y=s.errors||[],w=y.map(T=>`${T.path}: ${T.message}`).join("; ");throw new p(`Validation failed${w?`: ${w}`:""}`,{code:"VALIDATION_FAILED",context:y})}t=s.data;let o=await this.getById(e,r);if(!o)throw new p(`Record not found: ${this.entityName} with ID ${e}`);let c=this.entityDefinition?.entity_column_prefix||this.tableName,l=Ee(t,c,r),d=this.getPrimaryKeyFieldName();await this.repository.update(d,e,l);let u={...o,...l};return await this.executeWorkflows("update",o,u,r),u}async delete(e,t={}){await this.ensureInitialized();let n={...t,tenantId:this.tenantId};await this.permissionGuard.check("delete",n);let r=await this.getById(e,n);if(!r)throw new p(`Record not found: ${this.entityName} with ID ${e}`);let s=this.getPrimaryKeyFieldName();return await this.repository.delete(s,e),await this.executeWorkflows("delete",r,null,n),!0}getColumnPrefix(){let e=this.entityDefinition?.entity_column_prefix,t=a(s=>s.replace(/_+$/g,""),"sanitize");if(typeof e=="string"&&e.trim().length>0)return t(e.trim());let r={system_entities:"entity",system_fields:"field",system_permissions:"permission",system_views:"view",system_workflows:"workflow",system_rls:"rls"}[this.tableName];return r||this.tableName}getPrimaryKeyFieldName(){return Q(this.getColumnPrefix())}async ensureInitialized(){this.initialized||await this.initialize()}validateData(e,t){}validateFieldType(e,t){switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"integer":return Number.isInteger(e);case"boolean":return typeof e=="boolean";case"date":case"datetime":return e instanceof Date||typeof e=="string"&&!isNaN(Date.parse(e));case"json":case"object":return typeof e=="object";case"array":return Array.isArray(e);default:return!0}}async executeWorkflows(e,t,n,r){}async ensureTable(){}static clearCache(e,t){e&&t?h.cache.delete(`${t}:${e}`):e?Array.from(h.cache.keys()).filter(r=>r.endsWith(`:${e}`)).forEach(r=>h.cache.delete(r)):h.cache.clear()}static getCacheStats(){return{size:h.cache.size,entities:Array.from(h.cache.keys())}}};a(h,"Entity"),h.cache=new Map;var S=h;S.prototype.setValidation=S.prototype.setValidation||function(){this.validationAdapter=new D};E();var ae=class ae{constructor(e){this.tableSchemas={};this.schema="public";this.databaseAdapter=e}async isInstalled(){try{return await this.databaseAdapter.tableExists(this.schema,"system_entities")}catch{return!1}}async createSystemTables(){let e=[{name:"entity_id",type:"integer",primaryKey:!0,notNull:!0,autoIncrement:!0},{name:"entity_tenant_id",type:"string"},{name:"entity_status",type:"string",default:"active"},{name:"entity_weight",type:"integer",default:0},{name:"entity_column_prefix",type:"string"},{name:"entity_created_at",type:"datetime",notNull:!0,default:"CURRENT_TIMESTAMP"},{name:"entity_created_by",type:"string"},{name:"entity_modified_at",type:"datetime",notNull:!0,default:"CURRENT_TIMESTAMP"},{name:"entity_modified_by",type:"string"},{name:"entity_name",type:"string",notNull:!0,unique:!0},{name:"entity_table_name",type:"string",notNull:!0},{name:"entity_display_name",type:"string",notNull:!0},{name:"entity_description",type:"text"},{name:"entity_metadata",type:"text"}];await this.databaseAdapter.createTable(`${this.schema}.system_entities`,e),this.tableSchemas.system_entities=e;let t=[{name:"field_id",type:"integer",primaryKey:!0,notNull:!0,autoIncrement:!0},{name:"field_tenant_id",type:"string"},{name:"field_status",type:"string",default:"active"},{name:"field_weight",type:"integer",default:0},{name:"field_created_at",type:"datetime",notNull:!0,default:"CURRENT_TIMESTAMP"},{name:"field_created_by",type:"string"},{name:"field_modified_at",type:"datetime",notNull:!0,default:"CURRENT_TIMESTAMP"},{name:"field_modified_by",type:"string"},{name:"field_entity_id",type:"integer",notNull:!0,references:{table:`${this.schema}.system_entities`,column:"entity_id",onDelete:"CASCADE"}},{name:"field_name",type:"string",notNull:!0},{name:"field_type",type:"string",notNull:!0},{name:"field_is_required",type:"boolean",notNull:!0,default:!1},{name:"field_is_unique",type:"boolean",notNull:!0,default:!1},{name:"field_default_value",type:"text"},{name:"field_validation_rules",type:"text"},{name:"field_display_name",type:"string",notNull:!0},{name:"field_description",type:"text"},{name:"field_reference_entity",type:"string"},{name:"field_metadata",type:"text"}];await this.databaseAdapter.createTable(`${this.schema}.system_fields`,t),this.tableSchemas.system_fields=t;let n=[{name:"permission_id",type:"integer",primaryKey:!0,notNull:!0,autoIncrement:!0},{name:"permission_tenant_id",type:"string"},{name:"permission_status",type:"string",default:"active"},{name:"permission_weight",type:"integer",default:0},{name:"permission_created_at",type:"datetime",notNull:!0,default:"CURRENT_TIMESTAMP"},{name:"permission_created_by",type:"string"},{name:"permission_modified_at",type:"datetime",notNull:!0,default:"CURRENT_TIMESTAMP"},{name:"permission_modified_by",type:"string"},{name:"permission_entity_id",type:"integer",notNull:!0,references:{table:`${this.schema}.system_entities`,column:"entity_id",onDelete:"CASCADE"}},{name:"permission_role",type:"string",notNull:!0},{name:"permission_action",type:"string",notNull:!0},{name:"permission_conditions",type:"text"},{name:"permission_is_allowed",type:"boolean",notNull:!0,default:!0},{name:"permission_field_permissions",type:"text"}];await this.databaseAdapter.createTable(`${this.schema}.system_permissions`,n),this.tableSchemas.system_permissions=n;let r=[{name:"view_id",type:"integer",primaryKey:!0,notNull:!0,autoIncrement:!0},{name:"view_tenant_id",type:"string"},{name:"view_status",type:"string",default:"active"},{name:"view_weight",type:"integer",default:0},{name:"view_created_at",type:"datetime",default:"CURRENT_TIMESTAMP"},{name:"view_created_by",type:"string"},{name:"view_modified_at",type:"datetime",default:"CURRENT_TIMESTAMP"},{name:"view_modified_by",type:"string"},{name:"view_slot",type:"integer",default:0},{name:"view_entity_id",type:"integer",notNull:!0,references:{table:`${this.schema}.system_entities`,column:"entity_id",onDelete:"CASCADE"}},{name:"view_name",type:"string",notNull:!0},{name:"view_fields",type:"text"},{name:"view_filters",type:"text"},{name:"view_joins",type:"text"},{name:"view_sort",type:"text"},{name:"view_title",type:"string"}];await this.databaseAdapter.createTable(`${this.schema}.system_views`,r),this.tableSchemas.system_views=r;let s=[{name:"workflow_id",type:"integer",primaryKey:!0,notNull:!0,autoIncrement:!0},{name:"workflow_tenant_id",type:"string"},{name:"workflow_status",type:"string",default:"active"},{name:"workflow_weight",type:"integer",default:0},{name:"workflow_created_at",type:"datetime",default:"CURRENT_TIMESTAMP"},{name:"workflow_created_by",type:"string"},{name:"workflow_modified_at",type:"datetime",default:"CURRENT_TIMESTAMP"},{name:"workflow_modified_by",type:"string"},{name:"workflow_entity_id",type:"integer",notNull:!0,references:{table:`${this.schema}.system_entities`,column:"entity_id",onDelete:"CASCADE"}},{name:"workflow_name",type:"string",notNull:!0},{name:"workflow_trigger_event",type:"string",notNull:!0},{name:"workflow_conditions",type:"text"},{name:"workflow_actions",type:"text",notNull:!0},{name:"workflow_metadata",type:"text"}];await this.databaseAdapter.createTable(`${this.schema}.system_workflows`,s),this.tableSchemas.system_workflows=s;let o=[{name:"rls_id",type:"integer",primaryKey:!0,notNull:!0,autoIncrement:!0},{name:"rls_tenant_id",type:"string"},{name:"rls_status",type:"string",default:"active"},{name:"rls_weight",type:"integer",default:0},{name:"rls_created_at",type:"datetime",notNull:!0,default:"CURRENT_TIMESTAMP"},{name:"rls_created_by",type:"string"},{name:"rls_modified_at",type:"datetime",notNull:!0,default:"CURRENT_TIMESTAMP"},{name:"rls_modified_by",type:"string"},{name:"rls_entity_id",type:"integer",notNull:!0,references:{table:`${this.schema}.system_entities`,column:"entity_id",onDelete:"CASCADE"}},{name:"rls_role",type:"string",notNull:!0},{name:"rls_view_id",type:"string"},{name:"rls_config",type:"text",notNull:!0}];await this.databaseAdapter.createTable(`${this.schema}.system_rls`,o),this.tableSchemas.system_rls=o}async seedSystemData(){let e=new Date().toISOString(),t=[{id:1,name:"system_entities",display:"System Entities",table:"system_entities"},{id:2,name:"system_fields",display:"System Fields",table:"system_fields"},{id:3,name:"system_permissions",display:"System Permissions",table:"system_permissions"},{id:4,name:"system_views",display:"System Views",table:"system_views"},{id:5,name:"system_workflows",display:"System Workflows",table:"system_workflows"},{id:6,name:"system_rls",display:"System RLS",table:"system_rls"}],n=new Map;for(let s of t)n.set(s.table,s.id.toString()),await this.databaseAdapter.insert(`${this.schema}.system_entities`,{entity_name:s.name,entity_table_name:s.table,entity_display_name:s.display,entity_status:"active",entity_weight:0,entity_created_at:e,entity_modified_at:e});let r=a(s=>s.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase()),"toDisplay");for(let[s,o]of Object.entries(this.tableSchemas)){let c=n.get(s)||q(),l=0;for(let d of o){let u={field_entity_id:c,field_name:d.name,field_type:d.type,field_is_required:!!(d.notNull&&!d.autoIncrement&&!d.primaryKey),field_is_unique:!!d.unique,field_default_value:d.default??null,field_display_name:r(d.name),field_reference_entity:d.references?.table||null,field_is_primary_key:!!d.primaryKey,field_status:"active",field_weight:l++,field_created_at:e,field_modified_at:e};await this.databaseAdapter.insert(`${this.schema}.system_fields`,u)}}}async install(e){if(this.schema=e,!await this.isInstalled())try{await this.databaseAdapter.createSchema(this.schema),await this.createSystemTables(),await this.seedSystemData()}catch(t){let n=t instanceof Error?t.message:String(t);throw new p(`Failed to install database: ${n}`,{cause:t instanceof Error?t:new Error(String(t))})}}async ensureReady(){await this.isInstalled()||await this.install(this.schema)}};a(ae,"InstallManager");var L=ae;E();var le=class le{constructor(e={}){this.options=e;let t="sqlite",n={};if(typeof e.adapter=="string"&&(t=e.adapter,n=e.config||{}),!new Set(["sq