@kyro-cms/core 0.12.55 → 0.12.57
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/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +1 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +1 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/{chunk-5YQ2HVHD.js → chunk-5VGYVQPY.js} +10 -10
- package/dist/chunk-5ZEYOFAK.js +2 -0
- package/dist/chunk-6KERPHAL.cjs +2 -0
- package/dist/chunk-72VOOMJI.js +20 -0
- package/dist/chunk-7DUKWHRN.cjs +1 -0
- package/dist/chunk-FJPY42VZ.cjs +20 -0
- package/dist/{chunk-BU6O3TP7.js → chunk-KNOFTUQV.js} +24 -24
- package/dist/{chunk-4MVLIR77.cjs → chunk-LBYY3W2D.cjs} +9 -9
- package/dist/chunk-LVHWORV4.js +3 -0
- package/dist/chunk-PCN6QV3Z.js +21 -0
- package/dist/chunk-PCVQNVSU.cjs +19 -0
- package/dist/{chunk-QEZKIR5V.cjs → chunk-Q4B2IRX7.cjs} +1 -1
- package/dist/{chunk-M645XO2L.js → chunk-R3KFYDRS.js} +1 -1
- package/dist/{chunk-V65273ZG.cjs → chunk-T63QLFLZ.cjs} +3 -3
- package/dist/{chunk-6KUL2BSA.cjs → chunk-TDGSIF5H.cjs} +24 -24
- package/dist/{chunk-AIE7BKVY.js → chunk-WDDKRBSY.js} +1 -1
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +1 -14
- package/dist/index.d.ts +1 -14
- package/dist/index.js +8 -8
- package/dist/integration.cjs +1 -1
- package/dist/integration.js +1 -1
- package/dist/{local-3V3XEQUY.js → local-2IFOTHAA.js} +1 -1
- package/dist/{local-YCWBUF3R.cjs → local-UESCNPQP.cjs} +1 -1
- package/dist/{mongo-auth-adapter-W3HLB7OR.cjs → mongo-auth-adapter-EUHAYWJ6.cjs} +1 -1
- package/dist/{mongo-auth-adapter-QDXVHREJ.js → mongo-auth-adapter-FW7ATYQ6.js} +1 -1
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-CMQYYIGC.js +0 -21
- package/dist/chunk-LELK3TYX.js +0 -3
- package/dist/chunk-OW3HFVPX.cjs +0 -20
- package/dist/chunk-PRMILS4Y.js +0 -20
- package/dist/chunk-UT7RGIYS.js +0 -2
- package/dist/chunk-WJBQ2NBD.cjs +0 -1
- package/dist/chunk-XDE7CFV6.cjs +0 -19
- package/dist/chunk-ZKHTFR5S.cjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-7NH7H3WA.js';import {g as g$1,e}from'./chunk-Y2YAKDEQ.js';import {randomUUID,randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g$1();var c=e(a(),1);var g=class{db;adapter;prefix;sessionTTL;refreshTokenTTL;indexesEnsured=false;constructor(e){this.db=e.db,this.adapter=e.adapter,this.prefix=e.collectionPrefix||"",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}getDatabase(){let e=typeof this.db=="function"?this.db():this.db;if(!e&&this.adapter&&(this.adapter.db?e=this.adapter.db:this.adapter.client&&(this.adapter.db=this.adapter.client.db(this.adapter.database||"kyro_cms"),e=this.adapter.db)),!e&&globalThis.__KYRO_INSTANCE__?.db){let s=globalThis.__KYRO_INSTANCE__.db;s.db?e=s.db:s.client&&(s.db=s.client.db(s.database||"kyro_cms"),e=s.db);}if(!e)throw new Error("MongoDB database not initialized");return e}col(e){return this.getDatabase().collection(`${this.prefix}${e}`)}async connect(){this.adapter&&!this.adapter.connected&&await this.adapter.connect(),this.indexesEnsured||await this.ensureIndexes();}async disconnect(){}async ensureIndexes(){await this.col("users").createIndex({email:1},{unique:true}),await this.col("users").createIndex({tenantId:1}),await this.col("users").createIndex({role:1}),await this.col("sessions").createIndex({token:1},{unique:true}),await this.col("sessions").createIndex({refreshToken:1}),await this.col("sessions").createIndex({userId:1}),await this.col("sessions").createIndex({expiresAt:1},{expireAfterSeconds:0}),await this.col("audit_logs").createIndex({timestamp:-1}),await this.col("audit_logs").createIndex({userId:1}),await this.col("audit_logs").createIndex({action:1}),await this.col("audit_logs").createIndex({resource:1}),await this.col("password_history").createIndex({userId:1,createdAt:-1}),await this.col("lockouts").createIndex({userId:1},{unique:true}),await this.col("lockouts").createIndex({lockedUntil:1}),this.indexesEnsured=true;}async createUser(e){let s=randomUUID(),t=new Date,i=await this.hashPassword(e.password),r={_id:s,name:e.name||null,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",avatar:e.avatar||null,tenantId:e.tenantId||null,emailVerified:false,locked:false,lastLogin:null,failedLoginAttempts:0,createdAt:t,updatedAt:t};return await this.col("users").insertOne(r),this.docToAuthUser(r)}async findUserByEmail(e){let s=await this.col("users").findOne({email:e.toLowerCase()});return s?this.docToAuthUser(s):null}async findUserById(e){let s=await this.col("users").findOne({_id:e});return s?this.docToAuthUser(s):null}async updateUser(e,s){let t={updatedAt:new Date};s.name!==void 0&&(t.name=s.name),s.email!==void 0&&(t.email=s.email),s.passwordHash!==void 0&&(t.passwordHash=s.passwordHash),s.role!==void 0&&(t.role=s.role),s.avatar!==void 0&&(t.avatar=s.avatar),s.tenantId!==void 0&&(t.tenantId=s.tenantId),s.emailVerified!==void 0&&(t.emailVerified=s.emailVerified),s.locked!==void 0&&(t.locked=s.locked),s.lastLogin!==void 0&&(t.lastLogin=s.lastLogin?new Date(s.lastLogin):null),s.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=s.failedLoginAttempts);let i=await this.col("users").findOneAndUpdate({_id:e},{$set:t},{returnDocument:"after"});return i?this.docToAuthUser(i):null}async deleteUser(e){return (await this.col("users").deleteOne({_id:e})).deletedCount>0}async verifyPassword(e,s){let t=await this.findUserByEmail(e);if(!t)return null;let i=await this.col("users").findOne({email:e.toLowerCase()},{projection:{passwordHash:1}});return i?.passwordHash&&await c.default.compare(s,i.passwordHash)?t:null}async hashPassword(e){return c.default.hash(e,12)}async createSession(e,s){let t=randomUUID(),i=randomBytes(32).toString("base64url"),r=randomBytes(32).toString("base64url"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:r,ipAddress:s?.ipAddress||null,userAgent:s?.userAgent||null,expiresAt:u,createdAt:o};return await this.col("sessions").insertOne(d),this.docToSession(d)}async findSessionByToken(e){let s=await this.col("sessions").findOne({token:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async findSessionByRefreshToken(e){let s=await this.col("sessions").findOne({refreshToken:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async deleteSession(e){return (await this.col("sessions").deleteOne({_id:e})).deletedCount>0}async deleteUserSessions(e){return (await this.col("sessions").deleteMany({userId:e})).deletedCount}async hasAnyUsers(){return await this.col("users").countDocuments()>0}async addPasswordToHistory(e,s){await this.col("password_history").insertOne({userId:e,passwordHash:s,createdAt:new Date});}async getPasswordHistory(e,s=5){return (await this.col("password_history").find({userId:e}).sort({createdAt:-1}).limit(s).toArray()).map(i=>i.passwordHash)}async isPasswordInHistory(e,s,t=5){let i=await this.getPasswordHistory(s,t);for(let r of i)if(await c.default.compare(e,r))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:r,resource:o,resourceId:u,success:d,startDate:f,endDate:h}=e,a={};i&&(a.userId=i),r&&(Array.isArray(r)?a.action={$in:r}:a.action=r),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(f||h)&&(a.timestamp={},f&&(a.timestamp.$gte=f),h&&(a.timestamp.$lte=h));let w=await this.col("audit_logs").countDocuments(a);return {logs:(await this.col("audit_logs").find(a).sort({timestamp:-1}).skip(t).limit(s).toArray()).map(n=>({id:n._id,timestamp:n.timestamp,action:n.action,userId:n.userId||void 0,userEmail:n.userEmail||void 0,role:n.role||void 0,resource:n.resource,resourceId:n.resourceId||void 0,changes:n.changes||void 0,ipAddress:n.ipAddress||void 0,userAgent:n.userAgent||void 0,success:n.success,error:n.error||void 0,metadata:n.metadata||void 0})),total:w}}async createAuditLog(e){let s=randomUUID(),t=new Date;return await this.col("audit_logs").insertOne({_id:s,action:e.action,userId:e.userId||null,userEmail:e.userEmail||null,role:e.role||null,resource:e.resource,resourceId:e.resourceId||null,changes:e.changes||null,ipAddress:e.ipAddress||null,userAgent:e.userAgent||null,success:e.success,error:e.error||null,metadata:e.metadata||null,timestamp:t}),{...e,id:s,timestamp:t}}docToAuthUser(e){return {id:e._id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,tenantId:e.tenantId||void 0,avatar:e.avatar||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?.toISOString?.()||e.lastLogin||void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:e.createdAt?.toISOString?.()||e.createdAt,updatedAt:e.updatedAt?.toISOString?.()||e.updatedAt}}docToSession(e){return {id:e._id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:e.expiresAt?.toISOString?.()||e.expiresAt,createdAt:e.createdAt?.toISOString?.()||e.createdAt,ipAddress:e.ipAddress||void 0,userAgent:e.userAgent||void 0}}async createEmailVerificationToken(e){let s=randomBytes(32).toString("hex"),t=new Date(Date.now()+1440*60*1e3),i=await import('./lib-XXYYUPMW.js'),r=i.ObjectId??i.default?.ObjectId;return await this.db.collection("email_verifications").insertOne({userId:new r(e),token:s,expiresAt:t,createdAt:new Date}),{token:s,expiresAt:t}}async verifyEmailToken(e){let s=await this.db.collection("email_verifications").findOne({token:e});return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.collection("users").updateOne({_id:s.userId},{$set:{emailVerified:true}}),await this.db.collection("email_verifications").deleteOne({_id:s._id}),{success:true,userId:s.userId.toString()}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=randomBytes(32).toString("hex"),i=new Date(Date.now()+3600*1e3),r=await import('./lib-XXYYUPMW.js'),o=r.ObjectId??r.default?.ObjectId;return await this.db.collection("password_resets").insertOne({userId:new o(s.id),token:t,expiresAt:i,createdAt:new Date}),{token:t,expiresAt:i}}async resetPasswordWithToken(e,s){let t=await this.db.collection("password_resets").findOne({token:e});if(!t)return {success:false,error:"Invalid reset token"};if(t.expiresAt<new Date)return {success:false,error:"Reset token has expired"};if(t.usedAt)return {success:false,error:"Reset token has already been used"};let i=await this.hashPassword(s);return await this.db.collection("users").updateOne({_id:t.userId},{$set:{passwordHash:i,updatedAt:new Date}}),await this.db.collection("password_resets").updateOne({_id:t._id},{$set:{usedAt:new Date}}),await this.db.collection("sessions").deleteMany({userId:t.userId}),{success:true}}};export{g as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();var b=class extends chunkVQ53TFYA_cjs.a{dialect="mongodb";client;db;database;connectionString;constructor(o){if(super(),o.connectionString){this.connectionString=o.connectionString;try{let e=new URL(o.connectionString);this.database=e.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database="kyro_cms";}}else this.client=o.client,this.database=o.database;}async connect(){if(this.connectionString&&!this.client){let o;try{let e=await import('./lib-5QYYN6ML.cjs');o=e.MongoClient??e.default?.MongoClient;}catch{chunkF4ITQ6XQ_cjs.a(["mongodb"]);let n=await import('./lib-5QYYN6ML.cjs');o=n.MongoClient??n.default?.MongoClient;}this.client=new o(this.connectionString),await this.client.connect();}this.db=this.client.db(this.database),this.connected=true;}async disconnect(){this.client&&(await this.client.close(),this.connected=false);}getMongoCollection(o){if(!this.db)throw new Error("MongoDB not connected");return this.db.collection(o)}async find(o){let{collection:e,where:n={},sort:s,limit:t=10,page:i=1,tenantId:r,select:a,draft:d}=o,l=this.getCollectionConfig(e),f=this.getMongoCollection(e),g={...n};this.tenantContext&&l.tenantScoped&&(g=chunkVQ53TFYA_cjs.c({where:g},e,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let u=this.buildFilter(g,l.tenantScoped?r:void 0),c=l.fields.find(p=>p.name==="status"),h=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(p=>p.value==="published");!d&&h&&(u.status="published");let y=this.parseSort(s),O={[y.field]:y.direction==="asc"?1:-1},$=(i-1)*t,[x,M]=await Promise.all([f.find(u).sort(O).skip($).limit(t).project(this.buildProjection(a)).toArray(),f.countDocuments(u)]),C=x.map(p=>this.processResult(p,l));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(p=>chunkVQ53TFYA_cjs.d(p,e,this.tenantContext,chunkVQ53TFYA_cjs.b))),d&&(C=await Promise.all(C.map(async p=>{let m=await this.getMongoCollection(`${e}_versions`).findOne({document_id:p.id},{sort:{createdAt:-1}});if(m){let P=typeof m.data=="string"?JSON.parse(m.data):m.data&&typeof m.data=="object"?m.data:{};return {...p,...P,status:p.status,_hasUnpublishedChanges:m.status==="draft"}}return p}))),{docs:C,...this.calculatePagination(i,t,M)}}async findByID(o){let{collection:e,id:n,tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e);if(this.tenantContext&&i.tenantScoped){let u={_id:n,tenantId:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(u,e,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let a={_id:n};s&&i.tenantScoped&&(a.tenantId=s);let d=i.fields.find(u=>u.name==="status"),l=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(u=>u.value==="published");!t&&l&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status,_hasUnpublishedChanges:c.status==="draft"};}}return g}async create(o){let{collection:e,data:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.prepareData(n,t),a=r.id||this.generateId();delete r.id;let d={...r,_id:a};return s&&t.tenantScoped&&(d.tenantId=s),await i.insertOne(d),this.processResult(d,t)}async update(o){let{collection:e,id:n,data:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a={_id:n};t&&i.tenantScoped&&(a.tenantId=t);let d=this.prepareData(s,i),l=await r.findOneAndUpdate(a,{$set:d},{returnDocument:"after"});if(!l)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(l,i)}async delete(o){let{collection:e,id:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r={_id:n};s&&t.tenantScoped&&(r.tenantId=s);let a=await i.findOneAndDelete(r);if(!a)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(a,t)}async count(o){let{collection:e,where:n={},tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.buildFilter(n,t.tenantScoped?s:void 0);return i.countDocuments(r)}async findOne(o){let{collection:e,where:n={},tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildFilter(n,i.tenantScoped?s:void 0),d=i.fields.find(u=>u.name==="status"),l=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(u=>u.value==="published");!t&&l&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status};}}return g}async findVersions(o){let{collection:e,documentId:n,sort:s,limit:t=10,page:i=1,tenantId:r}=o,a=this.getCollectionConfig(e),d=this.getMongoCollection(`${e}_versions`),l={document_id:n,autosave:{$ne:true}};r&&a.tenantScoped&&(l.tenant_id=r);let f=(i-1)*t,g=this.parseSort(s),u={[g.field]:g.direction==="asc"?1:-1},[c,h]=await Promise.all([d.find(l).sort(u).skip(f).limit(t).toArray(),d.countDocuments(l)]);return {docs:c.map(y=>this.processResult(y,{})),...this.calculatePagination(i,t,h)}}async findVersionByID(o){let{collection:e,versionId:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(`${e}_versions`),r={_id:n};s&&t.tenantScoped&&(r.tenant_id=s);let a=await i.findOne(r);return a?this.processResult(a,{}):null}async createVersion(o){let{collection:e,documentId:n,data:s,status:t,createdBy:i,changeDescription:r,tenantId:a,autosave:d}=o,l=this.getCollectionConfig(e),f=this.getMongoCollection(`${e}_versions`);if(d){let c={document_id:n,collection_slug:e,autosave:true};a&&l.tenantScoped&&(c.tenant_id=a);let h=await f.findOne(c);if(h){let y=new Date().toISOString();return await f.updateOne({_id:h._id},{$set:{data:s,status:t,updatedAt:y}}),this.processResult({...h,data:s,status:t,updatedAt:y},{})}}let g=new Date().toISOString(),u={_id:this.generateId(),document_id:n,collection_slug:e,data:s,status:t,autosave:d===true,created_by:i,change_description:r,createdAt:g,updatedAt:g};if(a&&l.tenantScoped&&(u.tenant_id=a),await f.insertOne(u),!d){let c=this.getCollectionConfig(e);c.versions?.maxPerDoc&&await this.deleteVersions({collection:e,documentId:n,keepLatest:c.versions.maxPerDoc,tenantId:a});}return this.processResult(u,{})}async updateLatestVersion(o){return this.createVersion({...o,autosave:true})}async deleteVersions(o){let{collection:e,documentId:n,keepLatest:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(`${e}_versions`);if(s){let a={document_id:n,autosave:{$ne:true}};t&&i.tenantScoped&&(a.tenant_id=t);let l=(await r.find(a).sort({createdAt:-1}).limit(s).project({_id:1}).toArray()).map(f=>f._id);l.length>0&&await r.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:l},...t&&i.tenantScoped?{tenant_id:t}:{}});}else {let a={document_id:n};t&&i.tenantScoped&&(a.tenant_id=t),await r.deleteMany(a);}}async migrate(){for(let o of this.collections.values()){let e=this.getMongoCollection(o.slug);await e.createIndex({_id:1}),o.tenantScoped&&await e.createIndex({tenantId:1}),o.timestamps&&await e.createIndex({createdAt:-1});for(let n of o.fields)n.unique&&n.name&&await e.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await e.createIndex({[n.name]:1});}}getCollectionConfig(o){if(o.startsWith("_globals_")){let n=o.replace("_globals_",""),s=this.globals.get(n);if(!s)throw new Error(`Global "${n}" not found`);return s}let e=this.collections.get(o);if(!e)throw new Error(`Collection "${o}" not found`);return e}buildFilter(o={},e){let n={};e&&(n.tenantId=e);for(let[s,t]of Object.entries(o))if(s==="AND"&&Array.isArray(t)){let i=t.map(r=>this.buildFilter(r));Object.assign(n,...i);}else if(s==="OR"&&Array.isArray(t))n.$or=t.map(i=>this.buildFilter(i));else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let i={};if(t.equals!==void 0){n[s==="id"?"_id":s]=t.equals;continue}t.not_equals!==void 0&&(i.$ne=t.not_equals),t.in!==void 0&&(i.$in=t.in),t.not_in!==void 0&&(i.$nin=t.not_in),t.greater_than!==void 0&&(i.$gt=t.greater_than),t.greater_than_equal!==void 0&&(i.$gte=t.greater_than_equal),t.less_than!==void 0&&(i.$lt=t.less_than),t.less_than_equal!==void 0&&(i.$lte=t.less_than_equal),t.like!==void 0&&(i.$regex=new RegExp(t.like.replace(/%/g,".*"),"i")),t.not_like!==void 0&&(i.$not=new RegExp(t.not_like.replace(/%/g,".*"),"i")),t.contains!==void 0&&(i.$regex=new RegExp(`.*${t.contains}.*`,"i")),t.exists!==void 0&&(i.$exists=t.exists),Object.keys(i).length>0&&(n[s==="id"?"_id":s]=i);}else n[s==="id"?"_id":s]=t;return n}buildProjection(o){if(!o||o.length===0)return;let e={_id:1};for(let n of o)e[n]=1;return e}processResult(o,e){if(!o)return null;let n={...o};for(let s of Object.keys(n))/^\d+$/.test(s)&&delete n[s];return o._id&&(n.id=o._id,delete n._id),delete n.__v,n.createdAt&&(n.createdAt=new Date(n.createdAt).toISOString()),n.updatedAt&&(n.updatedAt=new Date(n.updatedAt).toISOString()),chunkZOVH6QT5_cjs.a(n)}generateId(){let o=Date.now().toString(16).padStart(12,"0"),e=crypto.randomBytes(6).toString("hex");return o+e}};function V(v){return new b(v)}
|
|
2
|
+
exports.a=b;exports.b=V;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {a,c,b,d}from'./chunk-SLMIYECU.js';import {a as a$1}from'./chunk-VVVCCB6R.js';import {g}from'./chunk-Y2YAKDEQ.js';import {createRequire}from'module';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g();g();var R;function x(){return R||(R=createRequire("file:///")("node:sqlite").DatabaseSync,R)}function N(T){let e=[];for(let a of T)if(a.type==="tabs"&&"tabs"in a)for(let s of a.tabs)e.push(...N(s.fields));else a.type==="row"&&"fields"in a?e.push(...N(a.fields)):a.type==="collapsible"&&"fields"in a?e.push(...N(a.fields)):e.push(a);return e}function B(T,e){let a=e,s=T[a.name];if(a.type==="json"||a.type==="richtext"||a.type==="array"||a.type==="group"||a.type==="blocks"||a.type==="list"||a.type==="relationship-block")try{s=s?JSON.parse(s):null;}catch{s=null;}if(a.type==="checkbox"&&(s=!!s),a.type==="date"&&s)try{let i=new Date(s);isNaN(i.getTime())?s=null:s=i.toISOString();}catch{s=null;}if((a.type==="upload"||a.type==="image")&&s)try{let i=JSON.parse(s);Array.isArray(i)?s=i.map(o=>typeof o=="object"&&o!==null?o:{id:o}):s=typeof i=="object"?i:{id:i};}catch{s={id:s};}if(a.type==="relationship"&&s)try{let i=JSON.parse(s);Array.isArray(i),s=i;}catch{s={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:s};}if(a.type==="list"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}if(a.type==="relationship-block"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}return s}function P(T,e){return Array.isArray(T)?T.map(a=>{if(!a||typeof a!="object")return a;let s=a.data?{...a.data}:void 0;if(!s)return a;let i=e.find(o=>o.slug===a.type||o.slug===a.slug);if(!i||!Array.isArray(i.fields))return a;for(let o of i.fields){if(o.name&&(o.type==="upload"||o.type==="image")&&s[o.name]){let t=s[o.name];Array.isArray(t)?s[o.name]=t.map(n=>typeof n=="string"?{id:n}:n):typeof t=="string"&&(s[o.name]={id:t});}if(o.type==="blocks"&&o.name&&s[o.name]){let t=o.blocks||[];s[o.name]=P(s[o.name],t);}}return {...a,data:s}}):T}function O(T,e){try{return T.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var L=class extends a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(!this.db)this.db=new(x())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(x())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),a=s=>{let i=e(s),o=t=>typeof t=="boolean"?t?1:0:t===void 0?null:t;return new Proxy(i,{get(t,n,r){if(n==="all")return (...c)=>t.all(...c.map(o));if(n==="get")return (...c)=>t.get(...c.map(o));if(n==="run")return (...c)=>t.run(...c.map(o));let l=Reflect.get(t,n,r);return typeof l=="function"?l.bind(t):l}})};a.__wrapped=true,this.db.prepare=a;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(e,a){let s=a||this.getTableNameFor(e.slug),i=["id TEXT PRIMARY KEY"];for(let n of N(e.fields)){if(!n.name||n.name==="id")continue;let r=this.fieldToSQL(n);r&&i.push(r);}let o=N(e.fields);o.some(n=>n.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(n=>n.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(n=>n.name==="status")||i.push("status TEXT DEFAULT 'draft'"),o.some(n=>n.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let t=O(this.db,s);if(t.length===0){let n=`CREATE TABLE IF NOT EXISTS ${s} (${i.join(", ")})`;this.db.exec(n),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${r.name} ON ${s}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${r.name}_unique ON ${s}(${this.col(r.name)})`);}else {let n=new Set(t);for(let r of i){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!n.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
|
|
4
|
+
id TEXT PRIMARY KEY,
|
|
5
|
+
collection_slug TEXT NOT NULL,
|
|
6
|
+
document_id TEXT NOT NULL,
|
|
7
|
+
tenant_id TEXT,
|
|
8
|
+
version INTEGER NOT NULL,
|
|
9
|
+
status TEXT NOT NULL DEFAULT 'draft',
|
|
10
|
+
autosave INTEGER NOT NULL DEFAULT 0,
|
|
11
|
+
data TEXT NOT NULL,
|
|
12
|
+
created_by TEXT,
|
|
13
|
+
change_description TEXT,
|
|
14
|
+
published_at TEXT,
|
|
15
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
16
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
17
|
+
)
|
|
18
|
+
`);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(e,a){let s=a.replace(/^-/,""),i=O(this.db,e);if(!i.includes(s)){if(s==="created_at"&&i.includes("createdAt"))return '"createdAt"';if(s==="createdAt"&&i.includes("created_at"))return '"created_at"';if(s==="updated_at"&&i.includes("updatedAt"))return '"updatedAt"';if(s==="updatedAt"&&i.includes("updated_at"))return '"updated_at"'}return this.col(s)}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let a=e.replace("_globals_","");return {isGlobal:true,globalSlug:a,tableName:`global_${a.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:a,where:s={},sort:i,limit:o=10,page:t=1,tenantId:n,draft:r=false}=e,l=this.parseGlobalsSlug(a),c$1=l.isGlobal?this.globals.get(l.globalSlug):this.getCollection(a);this.ensureTable(c$1,l.tableName);let d$1=l.tableName,b$1=`SELECT * FROM ${d$1}`,u=[],f=[],p={...s};this.tenantContext&&c$1.tenantScoped&&(p=c({where:p},a,this.tenantContext,b).where||{});let E=c$1.fields.find(h=>h.name==="status"),m=E?.type==="select"&&Array.isArray(E.options)&&E.options.some(h=>h.value==="published");!r&&m&&(f.push("status = ?"),u.push("published")),n&&c$1.tenantScoped&&(f.push("tenant_id = ?"),u.push(n));for(let[h,y]of Object.entries(p)){if(h==="AND"||h==="OR")continue;let S=this.resolveCol(d$1,h);typeof y=="object"&&y!==null?(y.equals!==void 0&&(f.push(`${S} = ?`),u.push(y.equals)),y.in!==void 0&&(f.push(`${S} IN (${y.in.map(()=>"?").join(", ")})`),u.push(...y.in)),y.not_equals!==void 0&&(f.push(`${S} != ?`),u.push(y.not_equals))):(f.push(`${S} = ?`),u.push(y));}f.length>0&&(b$1+=` WHERE ${f.join(" AND ")}`);let g=i||"-createdAt",U=this.resolveCol(d$1,g),w=g.startsWith("-")?"DESC":"ASC";b$1+=` ORDER BY ${U} ${w}`;let M=b$1.replace("SELECT *","SELECT COUNT(*) as count"),D=this.db.prepare(M).get(...u)?.count||0;b$1+=" LIMIT ? OFFSET ?",u.push(o,(t-1)*o);let A=this.db.prepare(b$1).all(...u).map(h=>this.rowToDoc(h,c$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(A=A.filter(h=>d(h,a,this.tenantContext,b))),r&&(A=await Promise.all(A.map(async h=>{let y=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(a,h.id);if(y){let S=y.data?JSON.parse(y.data):{};return a$1({...h,...S,status:h.status,_hasUnpublishedChanges:y.status==="draft"})}return h}))),A=A.map(h=>a$1(h)),{docs:A,totalDocs:D,limit:o,totalPages:Math.ceil(D/o),page:t,pagingCounter:(t-1)*o+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(D/o),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(D/o)?t+1:null}}async findByID(e){let{collection:a,id:s,tenantId:i,draft:o=false}=e,t=this.parseGlobalsSlug(a),n=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(a);this.ensureTable(n,t.tableName);let l=`SELECT * FROM ${t.tableName} WHERE id = ?`,c=[s];if(this.tenantContext&&n.tenantScoped){let p={id:s,tenant_id:this.tenantContext.tenantId};if(!d(p,a,this.tenantContext,b))return null}let d$1=n.fields.find(p=>p.name==="status"),b$1=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(p=>p.value==="published");!o&&b$1&&(l+=" AND status = ?",c.push("published")),i&&n.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i));let u=this.db.prepare(l).get(...c);if(!u)return null;let f=this.rowToDoc(u,n);if(o){let p=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(a,f.id);if(p){let E=p.data?JSON.parse(p.data):{};f={...f,...E,status:f.status,_hasUnpublishedChanges:p.status==="draft"};}}return a$1(f)}async create(e){let{collection:a,data:s,tenantId:i}=e,o=this.parseGlobalsSlug(a),t=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(t,o.tableName);let n=o.tableName,r=o.isGlobal?o.globalSlug:s.id||this.generateId(),l=this.prepareData(s,t);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,i&&t.tenantScoped&&(l.tenant_id=i);let d=Object.keys(l),b=O(this.db,n),u={};for(let g of d)b.includes(g)&&(u[g]=l[g]);let f=Object.keys(u),p=f.map(g=>this.col(g)),E=f.map(()=>"?").join(", "),m=Object.values(u).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${n} (${p.join(", ")}) VALUES (${E})`).run(...m),this.ensureVersionsTable(),this.findByID({collection:a,id:r,tenantId:i,draft:true})}async update(e){let{collection:a,id:s,data:i,tenantId:o}=e,t=this.parseGlobalsSlug(a),n=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(a);this.ensureTable(n,t.tableName);let r=t.tableName,l=this.prepareData(i,n);l.updated_at=new Date().toISOString();let c=O(this.db,r),d={};for(let m of Object.keys(l))c.includes(m)&&(d[m]=l[m]);let u=Object.keys(d).map(m=>`${this.col(m)} = ?`).join(", "),f=Object.values(d).map(m=>m!==null&&typeof m=="object"?JSON.stringify(m):m),p=`UPDATE ${r} SET ${u} WHERE id = ?`,E=[...f,s];return o&&n.tenantScoped&&(p+=" AND tenant_id = ?",E.push(o)),this.db.prepare(p).run(...E),this.ensureVersionsTable(),this.findByID({collection:a,id:s,tenantId:o,draft:true})}async delete(e){let{collection:a,id:s,tenantId:i}=e,o=this.parseGlobalsSlug(a),t=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(t,o.tableName),this.ensureVersionsTable();let n=await this.findByID({collection:a,id:s,tenantId:i,draft:true});if(!n)throw new Error(`Document not found: ${a}/${s}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[s];return i&&t.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i)),this.db.prepare(l).run(...c),n}async count(e){let{collection:a,tenantId:s}=e,i=this.parseGlobalsSlug(a),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(a);this.ensureTable(o,i.tableName);let n=`SELECT COUNT(*) as count FROM ${i.tableName}`,r=[];return s&&o.tenantScoped&&(n+=" WHERE tenant_id = ?",r.push(s)),this.db.prepare(n).get(...r)?.count||0}async findOne(e){let a=this.parseGlobalsSlug(e.collection);if(a.isGlobal){let i=this.globals.get(a.globalSlug);if(!i)throw new Error(`Global "${a.globalSlug}" not found in adapter`);this.ensureTable(i,a.tableName);let o=`SELECT * FROM ${a.tableName}`,t=[],n=[],r=i.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!e.draft&&i.versions&&l&&t.push("status = 'published'"),t.length>0&&(o+=` WHERE ${t.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...n);if(c){let d=this.rowToDoc(c,i);if(e.draft){let b=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,a.globalSlug);if(b){let u=b.data?JSON.parse(b.data):{};d={...d,...u,status:d.status,_hasUnpublishedChanges:b.status==="draft"};}}return d}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:a,documentId:s,tenantId:i,limit:o=20,page:t=1}=e,n=["collection_slug = ?","document_id = ?","autosave = 0"],r=[a,s];i?(n.push("tenant_id = ?"),r.push(i)):n.push("tenant_id IS NULL");let l=`WHERE ${n.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,b=(t-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,b).map(p=>this.rowToVersion(p)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:t,pagingCounter:(t-1)*o+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(d/o),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(d/o)?t+1:null}}async findVersionByID(e){this.ensureVersionsTable();let a=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return a?this.rowToVersion(a):null}async createVersion(e){this.ensureVersionsTable();let a=new Date().toISOString();if(e.autosave){let n=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[e.collection,e.documentId];e.tenantId?(n+=" AND tenant_id = ?",r.push(e.tenantId)):n+=" AND tenant_id IS NULL",n+=" LIMIT 1";let l=this.db.prepare(n).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,a,l.id);let c=await this.findVersionByID({collection:e.collection,versionId:l.id});if(c)return c}}let s=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
|
|
19
|
+
id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
|
|
20
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e.collection,e.documentId,e.tenantId??null,o,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?a:null,a,a),!e.autosave){let r=this.collections.get(e.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:r,tenantId:e.tenantId});}return await this.findVersionByID({collection:e.collection,versionId:s})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:a,documentId:s,keepLatest:i,tenantId:o}=e;if(i&&i>0){let t=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(a,s),n=0,r=[];for(let l of t)l.status==="published"||l.autosave===1||(n++,n>i&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let t=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,n=[a,s];o&&(t+=" AND tenant_id = ?",n.push(o)),this.db.prepare(t).run(...n);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,a){let s={},i=N(a.fields),o=(t,n)=>{let r=t;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return n!=null?JSON.stringify(n):null;if(r.type==="checkbox")return n?1:0;if(r.type==="number")return n!==null&&n!==""?Number(n):null;if(r.type==="upload"||r.type==="image"){if(n==null)return null;if(Array.isArray(n)){let l=n.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof n=="string"?n:typeof n=="object"?JSON.stringify(n):String(n)}else if(t.type==="relationship"){if(n==null)return null;if(Array.isArray(n)){let l=n.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:t.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof n=="string"?n:typeof n=="object"?JSON.stringify({relationTo:t.relationTo,value:n.id||n}):String(n)}return n};for(let t of i){if(!t.name||t.name==="id"||a.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===t.name))))continue;let r=e[t.name];r!==void 0&&(s[t.name]=o(t,r));}for(let t of a.fields)if(t.type==="tabs"&&"tabs"in t&&t.name){let n=e[t.name];if(n&&typeof n=="object"){for(let r of t.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=n[l.name];c!==void 0&&(s[l.name]=o(l,c));}}}return s}rowToDoc(e,a){let s={id:e.id};for(let i of N(a.fields)){if(!i.name||i.name==="id")continue;let o=i,t=e[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{t=t?JSON.parse(t):null;}catch{t=null;}if(o.type==="blocks"&&t&&Array.isArray(t)){let n=o.blocks||[];t=P(t,n);}if(i.type==="checkbox"&&(t=!!t),i.type==="date"&&t)try{let n=new Date(t);isNaN(n.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${i.name}":`,t),t=null):t=n.toISOString();}catch{t=null;}if((i.type==="upload"||i.type==="image")&&t)try{let n=JSON.parse(t);Array.isArray(n)?t=n.map(r=>typeof r=="object"&&r!==null?r:{id:r}):t=typeof n=="object"?n:{id:n};}catch{t={id:t};}if(i.type==="relationship"&&t)try{let n=JSON.parse(t);Array.isArray(n),t=n;}catch{t={relationTo:Array.isArray(i.relationTo)?i.relationTo[0]:i.relationTo,value:t};}s[i.name]=t;}for(let i of a.fields)if(!(!i.name||i.name==="id"||i.name==="row"||i.name==="collapsible")&&i.type==="tabs"&&"tabs"in i){let o={};for(let t of i.tabs)for(let n of t.fields)n.name&&n.name!=="id"&&(o[n.name]=B(e,n));s[i.name]=o;}if(a.timestamps){let i=e.createdAt||e.created_at,o=e.updatedAt||e.updated_at;if(i)try{let t=new Date(i);isNaN(t.getTime())||(s.createdAt=t.toISOString());}catch{}if(o)try{let t=new Date(o);isNaN(t.getTime())||(s.updatedAt=t.toISOString());}catch{}}a.tenantScoped&&(s.tenantId=e.tenant_id),s.status=e.status??"published",s.hasDraft=e.hasDraft?!!e.hasDraft:false;for(let i of Object.keys(s))/^\d+$/.test(i)&&delete s[i];return s}generateId(){let e=Date.now().toString(16).padStart(12,"0"),a=randomBytes(6).toString("hex");return e+a}getMediaById(e){try{let a=this.getTableNameFor("media"),s=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${a} WHERE id = ?`).get(e);if(s)return {id:s.id,url:s.url,thumbnailUrl:s.thumbnail_url||s.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((a,s)=>{let i=this.db.transaction(async()=>e({db:this.db}));try{let o=i();a(o);}catch(o){s(o);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function k(T){return new L(T||{})}export{L as a,k as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkHTYVI2HK_cjs=require('./chunk-HTYVI2HK.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();var c=chunkBUNLC3II_cjs.e(chunkHTYVI2HK_cjs.a(),1);var g=class{db;adapter;prefix;sessionTTL;refreshTokenTTL;indexesEnsured=false;constructor(e){this.db=e.db,this.adapter=e.adapter,this.prefix=e.collectionPrefix||"",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}getDatabase(){let e=typeof this.db=="function"?this.db():this.db;if(!e&&this.adapter&&(this.adapter.db?e=this.adapter.db:this.adapter.client&&(this.adapter.db=this.adapter.client.db(this.adapter.database||"kyro_cms"),e=this.adapter.db)),!e&&globalThis.__KYRO_INSTANCE__?.db){let s=globalThis.__KYRO_INSTANCE__.db;s.db?e=s.db:s.client&&(s.db=s.client.db(s.database||"kyro_cms"),e=s.db);}if(!e)throw new Error("MongoDB database not initialized");return e}col(e){return this.getDatabase().collection(`${this.prefix}${e}`)}async connect(){this.adapter&&!this.adapter.connected&&await this.adapter.connect(),this.indexesEnsured||await this.ensureIndexes();}async disconnect(){}async ensureIndexes(){await this.col("users").createIndex({email:1},{unique:true}),await this.col("users").createIndex({tenantId:1}),await this.col("users").createIndex({role:1}),await this.col("sessions").createIndex({token:1},{unique:true}),await this.col("sessions").createIndex({refreshToken:1}),await this.col("sessions").createIndex({userId:1}),await this.col("sessions").createIndex({expiresAt:1},{expireAfterSeconds:0}),await this.col("audit_logs").createIndex({timestamp:-1}),await this.col("audit_logs").createIndex({userId:1}),await this.col("audit_logs").createIndex({action:1}),await this.col("audit_logs").createIndex({resource:1}),await this.col("password_history").createIndex({userId:1,createdAt:-1}),await this.col("lockouts").createIndex({userId:1},{unique:true}),await this.col("lockouts").createIndex({lockedUntil:1}),this.indexesEnsured=true;}async createUser(e){let s=crypto.randomUUID(),t=new Date,i=await this.hashPassword(e.password),r={_id:s,name:e.name||null,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",avatar:e.avatar||null,tenantId:e.tenantId||null,emailVerified:false,locked:false,lastLogin:null,failedLoginAttempts:0,createdAt:t,updatedAt:t};return await this.col("users").insertOne(r),this.docToAuthUser(r)}async findUserByEmail(e){let s=await this.col("users").findOne({email:e.toLowerCase()});return s?this.docToAuthUser(s):null}async findUserById(e){let s=await this.col("users").findOne({_id:e});return s?this.docToAuthUser(s):null}async updateUser(e,s){let t={updatedAt:new Date};s.name!==void 0&&(t.name=s.name),s.email!==void 0&&(t.email=s.email),s.passwordHash!==void 0&&(t.passwordHash=s.passwordHash),s.role!==void 0&&(t.role=s.role),s.avatar!==void 0&&(t.avatar=s.avatar),s.tenantId!==void 0&&(t.tenantId=s.tenantId),s.emailVerified!==void 0&&(t.emailVerified=s.emailVerified),s.locked!==void 0&&(t.locked=s.locked),s.lastLogin!==void 0&&(t.lastLogin=s.lastLogin?new Date(s.lastLogin):null),s.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=s.failedLoginAttempts);let i=await this.col("users").findOneAndUpdate({_id:e},{$set:t},{returnDocument:"after"});return i?this.docToAuthUser(i):null}async deleteUser(e){return (await this.col("users").deleteOne({_id:e})).deletedCount>0}async verifyPassword(e,s){let t=await this.findUserByEmail(e);if(!t)return null;let i=await this.col("users").findOne({email:e.toLowerCase()},{projection:{passwordHash:1}});return i?.passwordHash&&await c.default.compare(s,i.passwordHash)?t:null}async hashPassword(e){return c.default.hash(e,12)}async createSession(e,s){let t=crypto.randomUUID(),i=crypto.randomBytes(32).toString("base64url"),r=crypto.randomBytes(32).toString("base64url"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:r,ipAddress:s?.ipAddress||null,userAgent:s?.userAgent||null,expiresAt:u,createdAt:o};return await this.col("sessions").insertOne(d),this.docToSession(d)}async findSessionByToken(e){let s=await this.col("sessions").findOne({token:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async findSessionByRefreshToken(e){let s=await this.col("sessions").findOne({refreshToken:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async deleteSession(e){return (await this.col("sessions").deleteOne({_id:e})).deletedCount>0}async deleteUserSessions(e){return (await this.col("sessions").deleteMany({userId:e})).deletedCount}async hasAnyUsers(){return await this.col("users").countDocuments()>0}async addPasswordToHistory(e,s){await this.col("password_history").insertOne({userId:e,passwordHash:s,createdAt:new Date});}async getPasswordHistory(e,s=5){return (await this.col("password_history").find({userId:e}).sort({createdAt:-1}).limit(s).toArray()).map(i=>i.passwordHash)}async isPasswordInHistory(e,s,t=5){let i=await this.getPasswordHistory(s,t);for(let r of i)if(await c.default.compare(e,r))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:r,resource:o,resourceId:u,success:d,startDate:f,endDate:h}=e,a={};i&&(a.userId=i),r&&(Array.isArray(r)?a.action={$in:r}:a.action=r),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(f||h)&&(a.timestamp={},f&&(a.timestamp.$gte=f),h&&(a.timestamp.$lte=h));let w=await this.col("audit_logs").countDocuments(a);return {logs:(await this.col("audit_logs").find(a).sort({timestamp:-1}).skip(t).limit(s).toArray()).map(n=>({id:n._id,timestamp:n.timestamp,action:n.action,userId:n.userId||void 0,userEmail:n.userEmail||void 0,role:n.role||void 0,resource:n.resource,resourceId:n.resourceId||void 0,changes:n.changes||void 0,ipAddress:n.ipAddress||void 0,userAgent:n.userAgent||void 0,success:n.success,error:n.error||void 0,metadata:n.metadata||void 0})),total:w}}async createAuditLog(e){let s=crypto.randomUUID(),t=new Date;return await this.col("audit_logs").insertOne({_id:s,action:e.action,userId:e.userId||null,userEmail:e.userEmail||null,role:e.role||null,resource:e.resource,resourceId:e.resourceId||null,changes:e.changes||null,ipAddress:e.ipAddress||null,userAgent:e.userAgent||null,success:e.success,error:e.error||null,metadata:e.metadata||null,timestamp:t}),{...e,id:s,timestamp:t}}docToAuthUser(e){return {id:e._id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,tenantId:e.tenantId||void 0,avatar:e.avatar||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?.toISOString?.()||e.lastLogin||void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:e.createdAt?.toISOString?.()||e.createdAt,updatedAt:e.updatedAt?.toISOString?.()||e.updatedAt}}docToSession(e){return {id:e._id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:e.expiresAt?.toISOString?.()||e.expiresAt,createdAt:e.createdAt?.toISOString?.()||e.createdAt,ipAddress:e.ipAddress||void 0,userAgent:e.userAgent||void 0}}async createEmailVerificationToken(e){let s=crypto.randomBytes(32).toString("hex"),t=new Date(Date.now()+1440*60*1e3),i=await import('./lib-5QYYN6ML.cjs'),r=i.ObjectId??i.default?.ObjectId;return await this.db.collection("email_verifications").insertOne({userId:new r(e),token:s,expiresAt:t,createdAt:new Date}),{token:s,expiresAt:t}}async verifyEmailToken(e){let s=await this.db.collection("email_verifications").findOne({token:e});return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.collection("users").updateOne({_id:s.userId},{$set:{emailVerified:true}}),await this.db.collection("email_verifications").deleteOne({_id:s._id}),{success:true,userId:s.userId.toString()}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=crypto.randomBytes(32).toString("hex"),i=new Date(Date.now()+3600*1e3),r=await import('./lib-5QYYN6ML.cjs'),o=r.ObjectId??r.default?.ObjectId;return await this.db.collection("password_resets").insertOne({userId:new o(s.id),token:t,expiresAt:i,createdAt:new Date}),{token:t,expiresAt:i}}async resetPasswordWithToken(e,s){let t=await this.db.collection("password_resets").findOne({token:e});if(!t)return {success:false,error:"Invalid reset token"};if(t.expiresAt<new Date)return {success:false,error:"Reset token has expired"};if(t.usedAt)return {success:false,error:"Reset token has already been used"};let i=await this.hashPassword(s);return await this.db.collection("users").updateOne({_id:t.userId},{$set:{passwordHash:i,updatedAt:new Date}}),await this.db.collection("password_resets").updateOne({_id:t._id},{$set:{usedAt:new Date}}),await this.db.collection("sessions").deleteMany({userId:t.userId}),{success:true}}};exports.a=g;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
'use strict';var chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),r=require('path'),m=require('fs');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var r__default=/*#__PURE__*/_interopDefault(r);var m__default=/*#__PURE__*/_interopDefault(m);chunkBUNLC3II_cjs.h();var l=o=>{let s=r__default.default.join(process.cwd(),"node_modules","@kyro-cms","core"),e=r__default.default.resolve(s,"src",`${o}.ts`);return m__default.default.existsSync(e)?e:r__default.default.resolve(s,"dist",`${o}.js`)},g=l("api-handler"),A=l("api-handler-graphql"),P=l("api-handler-trpc"),S=["@kyro-cms/core","@kyro-cms/admin","@kyro-cms/astro","@kyro-cms/ai"],x=["@kyro-cms/connect"],R=[...S,...x],_=["better-sqlite3","pg","mongodb","ioredis","sharp","ssh2","cpu-features","ssh2-sftp-client","nodemailer","jsonwebtoken","@mapbox/node-pre-gyp","mock-aws-s3","aws-sdk","nock","cloudflare:workers"],N=["crypto","node:crypto","module","node:module","fs","node:fs","fs/promises","node:fs/promises","path","node:path","util","node:util","stream","node:stream","events","node:events","url","node:url","http","node:http","https","node:https","os","node:os","child_process","node:child_process","assert","node:assert","zlib","node:zlib","buffer","node:buffer"],h=[...S,..._],O=[...R,...N,..._];function k(o={}){let{configPath:s="./kyro.config.ts",apiPath:e="/api",adminPath:a="/admin",admin:v=true,enableGraphQL:c=false,enableTRPC:p=false,enableWebSocket:u=false}=o;return {name:"@kyro-cms/core",hooks:{"astro:config:setup":async({config:y,updateConfig:E,injectRoute:i,logger:n})=>{if(n.info(`Setting up Kyro CMS (API: ${e}, Admin: ${a})`),e===a)throw new Error(`Kyro CMS: apiPath and adminPath cannot be the same ("${e}")`);let d=r__default.default.resolve(y.root.pathname,s),b=d;m__default.default.existsSync(d)||n.warn(`Kyro config file not found at ${s}. The API will fail to boot if collections are needed.`),E({security:{checkOrigin:false},vite:{ssr:{external:O},build:{rollupOptions:{external:h}},optimizeDeps:{exclude:h},server:{watch:{ignored:["**/*.db","**/*.db-*","**/data/**","**/public/uploads/**","**/.kyro/**"]}},plugins:[{name:"use-sync-external-store-shim-fix",enforce:"pre",resolveId(t){if(t==="use-sync-external-store/shim"||t==="use-sync-external-store/shim/index.js")return "\0virtual:use-sync-external-store-shim";if(t==="use-sync-external-store/shim/with-selector"||t==="use-sync-external-store/shim/with-selector.js")return "\0virtual:use-sync-external-store-shim-with-selector"},load(t){if(t==="\0virtual:use-sync-external-store-shim")return 'export { useSyncExternalStore } from "react";';if(t==="\0virtual:use-sync-external-store-shim-with-selector")return `
|
|
2
|
+
import { useSyncExternalStore, useMemo } from "react";
|
|
3
|
+
export function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
|
|
4
|
+
const memoizedSelector = useMemo(() => {
|
|
5
|
+
let last, lastSnap, hasMemo = false;
|
|
6
|
+
return (snap) => {
|
|
7
|
+
if (!hasMemo || !Object.is(lastSnap, snap)) {
|
|
8
|
+
const next = selector(snap);
|
|
9
|
+
if (!hasMemo || !(isEqual ? isEqual(last, next) : Object.is(last, next))) {
|
|
10
|
+
last = next; lastSnap = snap; hasMemo = true;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
return last;
|
|
14
|
+
};
|
|
15
|
+
}, [selector, isEqual]);
|
|
16
|
+
const getSelection = () => memoizedSelector(getSnapshot());
|
|
17
|
+
const getServerSelection = getServerSnapshot != null ? () => memoizedSelector(getServerSnapshot()) : undefined;
|
|
18
|
+
return useSyncExternalStore(subscribe, getSelection, getServerSelection);
|
|
19
|
+
}
|
|
20
|
+
`}}],resolve:{alias:{"kyro:config":b}},define:{__KYRO_API_PATH__:JSON.stringify(e),__KYRO_ADMIN_PATH__:JSON.stringify(a),__KYRO_ENABLE_GRAPHQL__:JSON.stringify(c),__KYRO_ENABLE_TRPC__:JSON.stringify(p),__KYRO_ENABLE_WS__:JSON.stringify(u)}}}),i({pattern:`${e}/[...path]`,entrypoint:g}),c&&(i({pattern:`${e}/graphql`,entrypoint:A}),n.info(`GraphQL endpoint enabled at ${e}/graphql`)),p&&(i({pattern:`${e}/trpc/[...path]`,entrypoint:P}),n.info(`tRPC endpoint enabled at ${e}/trpc`)),u&&n.info("WebSocket support enabled (auto-starts at first request)");}}}}exports.a=k;
|
|
@@ -1,45 +1,45 @@
|
|
|
1
1
|
import {a as a$4,f}from'./chunk-OXGJOYEO.js';import {a as a$5}from'./chunk-2HA6EKXX.js';import {c,a as a$2,b,e,h}from'./chunk-JV4HJBXW.js';import {n,M as M$1,p,q,o,w,E,s,t,u,v}from'./chunk-HRAY65XH.js';import {ia,oa,fa,ma,$,ha,ca,pa,ra,J}from'./chunk-3NSZZCOJ.js';import {a,c as c$1,b as b$1,d}from'./chunk-SLMIYECU.js';import {a as a$1}from'./chunk-P6JITOFF.js';import {a as a$3}from'./chunk-VVVCCB6R.js';import {g}from'./chunk-Y2YAKDEQ.js';import {randomBytes}from'crypto';import {mkdir}from'fs/promises';import {resolve,dirname}from'path';import {createRequire}from'module';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
-
g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}function L(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Ie(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let
|
|
3
|
-
`)}function le(f,t){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let s=t.find(
|
|
4
|
-
CREATE TABLE IF NOT EXISTS "${
|
|
2
|
+
g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}function L(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Ie(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let n=L(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
|
|
3
|
+
`)}function le(f,t){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let s=t.find(n=>n.slug===i.type||n.slug===i.slug);if(!s||!Array.isArray(s.fields))return i;for(let n of s.fields){if(n.name&&(n.type==="upload"||n.type==="image")&&e[n.name]){let r=e[n.name];Array.isArray(r)?e[n.name]=r.map(a=>typeof a=="string"?{id:a}:a):typeof r=="string"&&(e[n.name]={id:r});}if(n.type==="blocks"&&n.name&&e[n.name]){let r=n.blocks||[];e[n.name]=le(e[n.name],r);}}return {...i,data:e}}):f}var M=class extends a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let n=e[s.name];n&&typeof n=="string"&&(e[s.name]=new Date(n));}for(let s of i.fields){let r=L(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let o={};for(let[c,d]of Object.entries(a)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===c);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&d?o[c]=Array.isArray(d)||typeof d=="object"?JSON.stringify(d):d:o[c]=d;}e[s.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let a=t[s.name];a!=null&&(e[s.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=L(s,this.dialect);(n==="timestamp"||n==="jsonb"||n==="decimal"||n==="integer"||n==="numeric"||n==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-4CI7FMYS.js')).drizzle;}catch{a$1(["postgres","drizzle-orm"]),t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-4CI7FMYS.js')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}catch{a$1(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('./d1-HPB6B253.js');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e$1=this.getTableName(t.slug),s={id:i?ia("id").primaryKey():oa("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=L(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c$1;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c$1=c(o);break;case "integer":c$1=a$2(o);break;case "decimal":case "numeric":c$1=b(o);break;case "boolean":c$1=a$2(o,{mode:"boolean"});break;case "timestamp":c$1=c(o);break;case "jsonb":c$1=c(o);break;default:c$1=c(o);}else switch(r){case "varchar":c$1=pa(o,{length:255});break;case "integer":c$1=ca(o);break;case "decimal":c$1=ha(o);break;case "boolean":c$1=$(o);break;case "timestamp":c$1=ma(o);break;case "jsonb":c$1=fa(o);break;default:c$1=ia(o);}n.required||(c$1=c$1.default(null)),s[a]=c$1;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?c("created_at").default(new Date().toISOString()):ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?c("updated_at").default(new Date().toISOString()):ma("updated_at").defaultNow()),e$1!=="users"&&e$1!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?c("status").default("draft"):pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?a$2("hasDraft",{mode:"boolean"}).default(false):$("hasDraft").default(false))),this.dialect==="sqlite"?e(e$1,s):ra(e$1,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),c=e.fields.some(u=>u.name==="status"),d=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
5
5
|
${u},
|
|
6
6
|
${r}
|
|
7
|
-
${
|
|
7
|
+
${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
8
8
|
${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
9
9
|
${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
|
|
10
10
|
${d?"":'"hasDraft" BOOLEAN DEFAULT false'}
|
|
11
11
|
)
|
|
12
12
|
`);}else i.push(`
|
|
13
|
-
CREATE TABLE IF NOT EXISTS "${
|
|
13
|
+
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
14
14
|
"id" TEXT PRIMARY KEY,
|
|
15
15
|
${r}
|
|
16
|
-
${
|
|
16
|
+
${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
17
17
|
${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
18
18
|
${c?"":`"status" TEXT DEFAULT 'draft',`}
|
|
19
19
|
${d?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
20
20
|
)
|
|
21
21
|
`);}if(i.length>0)if(this.dialect==="postgres")await this.executeRaw(J.raw(i.join(`;
|
|
22
|
-
`)));else for(let e of i)await this.executeRaw(J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=L(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),
|
|
23
|
-
`)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let
|
|
24
|
-
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:
|
|
22
|
+
`)));else for(let e of i)await this.executeRaw(J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=L(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),n=this.columnSqlType(e,i);return `"${s}" ${n} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(t){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(t,i){let e={},s=t.slug.startsWith("_globals_"),n=t.fields.some(c=>c.name==="createdAt"),r=t.fields.some(c=>c.name==="updatedAt"),a=t.fields.some(c=>c.name==="status"),o=t.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',n||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of t.fields){if(!c.name||c.name==="id")continue;let d=this.getColumnSqlDefinition(c,this.dialect),u=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=d;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(J`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.executeRaw(J`PRAGMA table_info("${J.raw(i)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(r=>!e.has(r));if(n.length>0){let r=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(J.raw(r.join(`;
|
|
23
|
+
`)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=L(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
|
|
24
|
+
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n$1=10,page:r=1,tenantId:a,select:o,draft:c}=t,d$1=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&d$1.tenantScoped&&(m=c$1({where:m},i,this.tenantContext,b$1).where||{});let g=this.buildWhereClause(m,d$1,u,a),y=d$1.fields.find(h=>h.name==="status"),p$1=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c&&u.status&&p$1&&g.push(n(u.status,"published"));let b=this.parseSort(s),_=!c&&u.status&&p$1?{...m,status:"published"}:m,ue=await this.count({collection:i,where:_,tenantId:a}),fe=(r-1)*n$1,P=[];try{let h=u[b.field]||u.createdAt||u.id,R=b.direction==="asc"?h:M$1(h),A=this.client.select().from(u);g.length>0&&(A=A.where(p(...g))),P=await A.orderBy(R).limit(n$1).offset(fe);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let N=P.map(h=>this.processResult(h,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(h=>d(h,i,this.tenantContext,b$1))),c&&(N=await Promise.all(N.map(async h=>{let R=await this.executeRaw(J`
|
|
25
25
|
SELECT * FROM kyro_versions
|
|
26
26
|
WHERE collection_slug = ${i}
|
|
27
27
|
AND document_id = ${h.id}
|
|
28
28
|
ORDER BY created_at DESC
|
|
29
29
|
LIMIT 1
|
|
30
|
-
`);if(R.length>0){let
|
|
30
|
+
`);if(R.length>0){let A=R[0],pe=typeof A.data=="string"?JSON.parse(A.data):A.data;return {...h,...pe,status:h.status,_hasUnpublishedChanges:A.status==="draft"}}return h}))),{docs:N,...this.calculatePagination(r,n$1,ue)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n$1}=t,r=this.getCollection(i),a=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?D(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!d(p,i,this.tenantContext,b$1))return null}let c=[n(a.id,o)];s&&a.tenantId&&c.push(n(a.tenantId,s));let d$1=r.fields.find(p=>p.name==="status"),u=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(p=>p.value==="published");!n$1&&a.status&&u&&c.push(n(a.status,"published"));let m=c.length>1?p(...c):c[0],g=await this.client.select().from(a).where(m);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n$1){let p=await this.executeRaw(J`
|
|
31
31
|
SELECT * FROM kyro_versions
|
|
32
32
|
WHERE collection_slug = ${i}
|
|
33
33
|
AND document_id = ${y.id}
|
|
34
34
|
ORDER BY created_at DESC
|
|
35
35
|
LIMIT 1
|
|
36
|
-
`);if(p.length>0){let
|
|
36
|
+
`);if(p.length>0){let b=p[0],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n$1}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?D(e):e,d=[n(a.id,c)];n$1&&a.tenantId&&d.push(n(a.tenantId,n$1));let u=await this.client.update(a).set(o).where(p(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n$1=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?D(e):e,o=[n(r.id,a)];s&&r.tenantId&&o.push(n(r.tenantId,s));let c=await this.client.delete(r).where(p(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],n$1)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:J`count(*)`}).from(r);a.length>0&&(o=o.where(p(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n$1}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),m=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n$1&&c.status&&m&&(d=d.where(n(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n$1){let p=await this.executeRaw(J`
|
|
37
37
|
SELECT * FROM kyro_versions
|
|
38
38
|
WHERE collection_slug = ${i}
|
|
39
|
-
AND document_id = ${
|
|
39
|
+
AND document_id = ${a}
|
|
40
40
|
ORDER BY created_at DESC
|
|
41
41
|
LIMIT 1
|
|
42
|
-
`);if(p.length>0){let
|
|
42
|
+
`);if(p.length>0){let b=p[0],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),c=await this.executeRaw(J`
|
|
43
43
|
SELECT count(*) as count
|
|
44
44
|
FROM kyro_versions
|
|
45
45
|
WHERE collection_slug = ${i}
|
|
@@ -55,27 +55,27 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
|
|
|
55
55
|
${r&&o.tenantScoped?J`AND tenant_id = ${r}`:J``}
|
|
56
56
|
ORDER BY created_at DESC
|
|
57
57
|
LIMIT ${s}
|
|
58
|
-
OFFSET ${
|
|
59
|
-
`)).map(m=>({...m,data:typeof m.data=="string"?JSON.parse(m.data):m.data})),...this.calculatePagination(
|
|
58
|
+
OFFSET ${a}
|
|
59
|
+
`)).map(m=>({...m,data:typeof m.data=="string"?JSON.parse(m.data):m.data})),...this.calculatePagination(n,s,d)}}async findVersionByID(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=await this.executeRaw(J`
|
|
60
60
|
SELECT * FROM kyro_versions
|
|
61
61
|
WHERE id = ${t.versionId}
|
|
62
62
|
AND collection_slug = ${t.collection}
|
|
63
63
|
${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
|
|
64
64
|
LIMIT 1
|
|
65
|
-
`);if(e.length===0)return null;let s=e[0];return {...s,data:typeof s.data=="string"?JSON.parse(s.data):s.data}}async createVersion(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=new Date().toISOString();if(t.autosave){let
|
|
65
|
+
`);if(e.length===0)return null;let s=e[0];return {...s,data:typeof s.data=="string"?JSON.parse(s.data):s.data}}async createVersion(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=new Date().toISOString();if(t.autosave){let n=await this.executeRaw(J`
|
|
66
66
|
SELECT * FROM kyro_versions
|
|
67
67
|
WHERE collection_slug = ${t.collection}
|
|
68
68
|
AND document_id = ${t.documentId}
|
|
69
69
|
AND autosave = 1
|
|
70
70
|
${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
|
|
71
71
|
LIMIT 1
|
|
72
|
-
`);if(
|
|
72
|
+
`);if(n.length>0)return await this.executeRaw(J`
|
|
73
73
|
UPDATE kyro_versions
|
|
74
74
|
SET data = ${JSON.stringify(t.data)},
|
|
75
75
|
status = ${t.status},
|
|
76
76
|
updated_at = ${e}
|
|
77
|
-
WHERE id = ${
|
|
78
|
-
`),this.findVersionByID({collection:t.collection,versionId:
|
|
77
|
+
WHERE id = ${n[0].id}
|
|
78
|
+
`),this.findVersionByID({collection:t.collection,versionId:n[0].id,tenantId:t.tenantId})}let s=Math.random().toString(36).substring(2,15);if(await this.executeRaw(J`
|
|
79
79
|
INSERT INTO kyro_versions (
|
|
80
80
|
id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
|
|
81
81
|
) VALUES (
|
|
@@ -83,7 +83,7 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
|
|
|
83
83
|
${JSON.stringify(t.data)}, ${t.status}, ${t.autosave?1:0}, ${t.createdBy||null},
|
|
84
84
|
${t.changeDescription||null}, ${e}, ${e}
|
|
85
85
|
)
|
|
86
|
-
`),!t.autosave){let
|
|
86
|
+
`),!t.autosave){let n=this.getCollection(t.collection);n.versions?.maxPerDoc&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:n.versions.maxPerDoc,tenantId:t.tenantId});}return this.findVersionByID({collection:t.collection,versionId:s,tenantId:t.tenantId})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection);if(t.keepLatest){let s=(await this.executeRaw(J`
|
|
87
87
|
SELECT id FROM kyro_versions
|
|
88
88
|
WHERE collection_slug = ${t.collection}
|
|
89
89
|
AND document_id = ${t.documentId}
|
|
@@ -91,18 +91,18 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
|
|
|
91
91
|
${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
|
|
92
92
|
ORDER BY created_at DESC
|
|
93
93
|
LIMIT ${t.keepLatest}
|
|
94
|
-
`)).map(
|
|
94
|
+
`)).map(n=>n.id);s.length>0&&await this.executeRaw(J`
|
|
95
95
|
DELETE FROM kyro_versions
|
|
96
96
|
WHERE collection_slug = ${t.collection}
|
|
97
97
|
AND document_id = ${t.documentId}
|
|
98
98
|
AND autosave = 0
|
|
99
|
-
AND id NOT IN (${J.join(s.map(
|
|
99
|
+
AND id NOT IN (${J.join(s.map(n=>J`${n}`),J`, `)})
|
|
100
100
|
`);}else await this.executeRaw(J`
|
|
101
101
|
DELETE FROM kyro_versions
|
|
102
102
|
WHERE collection_slug = ${t.collection}
|
|
103
103
|
AND document_id = ${t.documentId}
|
|
104
104
|
${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
|
|
105
|
-
`);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t$1,i,e,s$1){let
|
|
105
|
+
`);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t$1,i,e,s$1){let n$1=[];s$1&&i.tenantScoped&&e.tenantId&&n$1.push(n(e.tenantId,s$1));for(let[r,a]of Object.entries(t$1))if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=D(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:D(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(o=>typeof o=="string"?D(o):o)}))),r==="AND"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n$1.push(p(...o));}else if(r==="OR"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n$1.push(q(...o));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let o$1=e[r];if(!o$1)continue;a.equals!==void 0&&n$1.push(n(o$1,a.equals)),a.not_equals!==void 0&&n$1.push(o(o$1,a.not_equals)),a.in&&Array.isArray(a.in)&&n$1.push(w(o$1,a.in)),a.like!==void 0&&n$1.push(E(o$1,a.like)),a.contains!==void 0&&n$1.push(E(o$1,`%${a.contains}%`)),a.greater_than!==void 0&&n$1.push(s(o$1,a.greater_than)),a.greater_than_equal!==void 0&&n$1.push(t(o$1,a.greater_than_equal)),a.less_than!==void 0&&n$1.push(u(o$1,a.less_than)),a.less_than_equal!==void 0&&n$1.push(v(o$1,a.less_than_equal));}else {let o=e[r];o&&n$1.push(n(o,a));}return n$1}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let n=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();n!==s.name&&e[n]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[n],delete e[n]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let n=s;if(e[n.name]&&typeof e[n.name]=="string")try{let r=JSON.parse(e[n.name]);e[n.name]=r;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let r=n.blocks||[];e[n.name]=le(e[n.name],r);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let r of s.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let o=e[s.name][a.name];if(typeof o=="string")try{let c=JSON.parse(o);e[s.name][a.name]=Array.isArray(c)?c.map(d=>d&&typeof d=="object"&&typeof d.id=="string"?d.id:String(d||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else o&&typeof o=="object"&&(e[s.name][a.name]=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[s.name]=="string")try{let r=JSON.parse(e[s.name]);if(typeof r=="object"&&r!==null){e[s.name]=r;continue}}catch{}let n={};for(let r of s.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let o=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(a.type==="upload"||a.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}n[a.name]=o,delete e[a.name];}e[s.name]=n;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),a$3(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
|
|
106
106
|
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
107
107
|
id text PRIMARY KEY,
|
|
108
108
|
collection_slug text NOT NULL,
|
|
@@ -130,5 +130,5 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
|
|
|
130
130
|
created_at text NOT NULL,
|
|
131
131
|
updated_at text NOT NULL
|
|
132
132
|
)
|
|
133
|
-
`,await this.executeRaw(J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let
|
|
133
|
+
`,await this.executeRaw(J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new a$4().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new h().sqlToQuery(t);i=n.sql,e=n.params;}else if(t&&typeof t.toSQL=="function"){let n=t.toSQL();i=n.sql,e=n.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let n=s.prepare(i);return (e.length>0?await n.bind(...e).all():await n.all()).results||[]}if(typeof this.client?.execute=="function"){let n=await this.client.execute(t);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}return []}};function $e(f){return new M(f)}g();var x;function Ee(){return x||(x=createRequire("file:///")("node:sqlite").DatabaseSync,x)}function we(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function de(){return randomBytes(16).toString("hex")}async function Pe(){let f$1=we();if(f$1==="sqlite"){let r=resolve(process.cwd(),"data","kyro.db");await mkdir(dirname(r),{recursive:true});let a=new(Ee())(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f$1,genId:de}}let t=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",i=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",s=a$5(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:f(s),dialect:f$1,genId:de}}async function je(f,t){}async function Be(f){let{roles:t}=await import('./schema-YFMSJK2P.js');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
|
|
134
134
|
export{L as a,Ie as b,M as c,$e as d,de as e,Pe as f,je as g,Be as h};
|