@kyro-cms/core 0.12.55 → 0.12.56
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-4MVLIR77.cjs → chunk-3I6T73A5.cjs} +9 -9
- package/dist/{chunk-5YQ2HVHD.js → chunk-5BIZIO6T.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-AIE7BKVY.js → chunk-E555R77V.js} +1 -1
- package/dist/chunk-FJPY42VZ.cjs +20 -0
- package/dist/{chunk-V65273ZG.cjs → chunk-KJ3I35YV.cjs} +3 -3
- package/dist/{chunk-BU6O3TP7.js → chunk-KNOFTUQV.js} +24 -24
- package/dist/chunk-LVHWORV4.js +3 -0
- package/dist/chunk-PCN6QV3Z.js +21 -0
- package/dist/chunk-PCVQNVSU.cjs +19 -0
- package/dist/{chunk-6KUL2BSA.cjs → chunk-TDGSIF5H.cjs} +24 -24
- package/dist/{chunk-M645XO2L.js → chunk-UZEDY2UL.js} +1 -1
- package/dist/{chunk-QEZKIR5V.cjs → chunk-VV47TO2O.cjs} +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;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {D,A}from'./chunk-
|
|
1
|
+
import {D,A}from'./chunk-UZEDY2UL.js';import {e}from'./chunk-BAXBE4JD.js';import {fb}from'./chunk-5BIZIO6T.js';import {a as a$1}from'./chunk-R25WLKX4.js';import {c}from'./chunk-KNOFTUQV.js';import {a}from'./chunk-ZWDBPEXL.js';import {a as a$2}from'./chunk-5ZEYOFAK.js';import {g}from'./chunk-Y2YAKDEQ.js';import w from'kyro:config';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g();var r=null,l=null;async function b(){if(!r){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e$1=w.default||w,t=e$1.adapter,o=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||o)){let s=globalThis.DB;e$1.adapter=new c({type:"sqlite",client:s}),D.info("Hot-swapped to D1 DrizzleAdapter");}r=A(e$1),await r.init();let a$3=e$1.adapter,p=a$3&&a$3.dialect&&(a$3.dialect==="postgres"||a$3.dialect==="sqlite"),c$1=a$3&&a$3.dialect==="mongodb",n;if(p)a$3.dialect==="postgres"?n=new a({db:a$3.client}):a$3.dialect==="sqlite"&&(n=new fb({db:a$3.rawClient||a$3.client}));else if(o&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";n=new a$1({path:s});}else c$1&&(n=new a$2({adapter:a$3}));if(n?.connect)try{await n.connect();}catch(s){D.warn("Auth connect warning:",s);}try{await r.loadSettings();}catch(s){D.warn("loadSettings warning:",s);}try{await e(n);}catch(s){D.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=r;}catch(e){throw r=null,l=null,D.error("Init failed, will retry:",e),e}}}async function E(e){let t=globalThis.DB?globalThis:null;try{let{env:o}=await import('cloudflare:workers');o&&(t=o);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),l||(l=b()),await l;}var _={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function T(e){return r?r.settings?.access?.apiAccess?.[e]??_[e]??true:_[e]??true}var R=async e=>{if(!r)try{await Promise.race([E(e),new Promise((t,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let o=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(o===`${a}/graphql`&&typeof r.getGraphQL=="function"){if(!T("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await r.getGraphQL().fetch(e.request,e.locals);return new Response(n.body,n)}if(o.startsWith(`${a}/trpc/`)&&typeof r.getTRPC=="function"){if(!T("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await r.getTRPC().fetch(e.request,e.locals);return new Response(n.body,n)}return await(await r.getREST()).fetch(e.request,e.locals)}catch(t){return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:t?.message||String(t),stack:t?.stack}),{status:500,headers:{"Content-Type":"application/json"}})}},N=R;export{r as a,E as b,R as c,N as d};
|
|
@@ -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;
|