@kyro-cms/core 0.13.6 → 0.13.8

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.
Files changed (39) hide show
  1. package/dist/api-handler-graphql.cjs +1 -1
  2. package/dist/api-handler-graphql.js +1 -1
  3. package/dist/api-handler-trpc.cjs +1 -1
  4. package/dist/api-handler-trpc.js +1 -1
  5. package/dist/api-handler.cjs +1 -1
  6. package/dist/api-handler.js +1 -1
  7. package/dist/browser-JDBMVAJX.js +2 -0
  8. package/dist/browser-XEN42GDP.cjs +1 -0
  9. package/dist/{chunk-A4XM33WO.js → chunk-3RIGRHON.js} +1 -1
  10. package/dist/{chunk-TG5YQ4PB.cjs → chunk-MCK2QRAU.cjs} +2 -2
  11. package/dist/{chunk-HACW42ZZ.cjs → chunk-O2SA56P2.cjs} +2 -2
  12. package/dist/chunk-O6I26T6A.js +3 -0
  13. package/dist/{chunk-VQWOCGJ2.cjs → chunk-PPGZHOYR.cjs} +1 -1
  14. package/dist/{chunk-N25DOGLQ.js → chunk-SYE3OS5T.js} +1 -1
  15. package/dist/{chunk-YLP3EKTQ.js → chunk-TVWHTVLI.js} +1 -1
  16. package/dist/chunk-UE7DTBD7.cjs +1 -0
  17. package/dist/chunk-XL64URKD.cjs +2 -0
  18. package/dist/chunk-YNBJGPIU.js +2 -0
  19. package/dist/cli/index.cjs +17 -17
  20. package/dist/cli/index.js +13 -13
  21. package/dist/index-B_39z2jP.d.cts +217 -0
  22. package/dist/index-xqpVL2Zq.d.ts +217 -0
  23. package/dist/index.cjs +13 -13
  24. package/dist/index.d.cts +2 -31
  25. package/dist/index.d.ts +2 -31
  26. package/dist/index.js +14 -14
  27. package/dist/{mongo-auth-adapter-33M5ENM7.cjs → mongo-auth-adapter-22MV3TI3.cjs} +1 -1
  28. package/dist/{mongo-auth-adapter-4ITULS2P.js → mongo-auth-adapter-66PWVRZW.js} +1 -1
  29. package/dist/mongodb/index.cjs +1 -1
  30. package/dist/mongodb/index.d.cts +3 -130
  31. package/dist/mongodb/index.d.ts +3 -130
  32. package/dist/mongodb/index.js +1 -1
  33. package/dist/rest/index.cjs +1 -1
  34. package/dist/rest/index.js +1 -1
  35. package/package.json +2 -1
  36. package/dist/chunk-CIWLQXB2.js +0 -2
  37. package/dist/chunk-GDLMPZKD.cjs +0 -2
  38. package/dist/chunk-NBBAMC2X.cjs +0 -1
  39. package/dist/chunk-VWXHW74B.js +0 -3
@@ -1,2 +0,0 @@
1
- import h from'bcryptjs';import {randomUUID,randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
- var p=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),n={_id:s,name:e.name||null,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",avatar:e.avatar||null,tenantId:e.tenantId||null,metadata:e.metadata||null,emailVerified:false,locked:false,lastLogin:null,failedLoginAttempts:0,createdAt:t,updatedAt:t};return await this.col("users").insertOne(n),this.docToAuthUser(n)}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.metadata!==void 0&&(t.metadata=s.metadata),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 h.compare(s,i.passwordHash)?t:null}async hashPassword(e){return h.hash(e,12)}async createSession(e,s){let t=randomUUID(),i=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:n,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 n of i)if(await h.compare(e,n))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:n,resource:o,resourceId:u,success:d,startDate:c,endDate:f}=e,a={};i&&(a.userId=i),n&&(Array.isArray(n)?a.action={$in:n}:a.action=n),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(c||f)&&(a.timestamp={},c&&(a.timestamp.$gte=c),f&&(a.timestamp.$lte=f));let g=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(r=>({id:r._id,timestamp:r.timestamp,action:r.action,userId:r.userId||void 0,userEmail:r.userEmail||void 0,role:r.role||void 0,resource:r.resource,resourceId:r.resourceId||void 0,changes:r.changes||void 0,ipAddress:r.ipAddress||void 0,userAgent:r.userAgent||void 0,success:r.success,error:r.error||void 0,metadata:r.metadata||void 0})),total:g}}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,avatar:e.avatar||void 0,tenantId:e.tenantId||void 0,metadata:e.metadata||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('mongodb'),n=i.ObjectId??i.default?.ObjectId;return await this.db.collection("email_verifications").insertOne({userId:new n(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),n=await import('mongodb'),o=n.ObjectId??n.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{p as a};
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkO4PPZOVI_cjs=require('./chunk-O4PPZOVI.cjs'),chunkJJY2F6NL_cjs=require('./chunk-JJY2F6NL.cjs'),chunkOXEJCIOA_cjs=require('./chunk-OXEJCIOA.cjs'),chunkJHFD3IAU_cjs=require('./chunk-JHFD3IAU.cjs'),crypto=require('crypto');var b=class extends chunkO4PPZOVI_cjs.a{dialect="mongodb";client;db;database;connectionString;constructor(i){if(super(),i.connectionString){this.connectionString=i.connectionString;try{let e=new URL(i.connectionString);this.database=e.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database="kyro_cms";}}else this.client=i.client,this.database=i.database;}async connect(){if(this.connectionString&&!this.client){let i;try{let e=await import('mongodb');i=e.MongoClient??e.default?.MongoClient;}catch{chunkJJY2F6NL_cjs.a(["mongodb"]);let n=await import('mongodb');i=n.MongoClient??n.default?.MongoClient;}this.client=new i(this.connectionString),await this.client.connect();}else if(this.client&&typeof this.client.connect=="function")try{await this.client.connect();}catch{}this.client&&(this.db=this.client.db(this.database),this.connected=true);}async disconnect(){this.client&&(await this.client.close(),this.connected=false);}getMongoCollection(i){if(!this.db&&this.client&&(this.db=this.client.db(this.database),this.connected=true),!this.db)throw new Error("MongoDB not connected");return this.db.collection(i)}async find(i){let{collection:e,where:n={},sort:s,limit:t=10,page:o=1,tenantId:r,select:a,draft:l}=i,d=this.getCollectionConfig(e),f=this.getMongoCollection(e),u={...n};this.tenantContext&&d.tenantScoped&&(u=chunkO4PPZOVI_cjs.c({where:u},e,this.tenantContext,chunkO4PPZOVI_cjs.b).where||{});let g=this.buildFilter(u,d.tenantScoped?r:void 0),c=d.fields.find(h=>h.name==="status"),p=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(h=>h.value==="published");!l&&p&&(g.status="published");let y=this.parseSort(s),R={[y.field]:y.direction==="asc"?1:-1},$=(o-1)*t,[O,x]=await Promise.all([f.find(g).sort(R).skip($).limit(t).project(this.buildProjection(a)).toArray(),f.countDocuments(g)]),C=O.map(h=>this.processResult(h,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(h=>chunkO4PPZOVI_cjs.d(h,e,this.tenantContext,chunkO4PPZOVI_cjs.b))),l&&(C=await Promise.all(C.map(async h=>{let m=await this.getMongoCollection(`${e}_versions`).findOne({document_id:h.id},{sort:{createdAt:-1}});if(m){let M=typeof m.data=="string"?JSON.parse(m.data):m.data&&typeof m.data=="object"?m.data:{};return {...h,...M,status:h.status,_hasUnpublishedChanges:m.status==="draft"}}return h}))),{docs:C,...this.calculatePagination(o,t,x)}}buildIdFilter(i,e,n){let s=String(i||""),t=/^[0-9a-fA-F]{24}$/.test(s),o=[{_id:s},{id:s},{slug:s},{orderNumber:s}];if(t)try{let{ObjectId:a}=chunkJHFD3IAU_cjs.a("mongodb");o.unshift({_id:new a(s)});}catch{}let r={$or:o};return e&&n?.tenantScoped&&(r.tenantId=e),r}async findByID(i){let{collection:e,id:n,tenantId:s,draft:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e);if(this.tenantContext&&o.tenantScoped){let g={_id:n,tenantId:this.tenantContext.tenantId};if(!chunkO4PPZOVI_cjs.d(g,e,this.tenantContext,chunkO4PPZOVI_cjs.b))return null}let a=this.buildIdFilter(n,s,o),l=o.fields.find(g=>g.name==="status"),d=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(g=>g.value==="published");!t&&d&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let u=this.processResult(f,o);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:u.id},{sort:{createdAt:-1}});if(c){let p=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};u={...u,...p,status:u.status,_hasUnpublishedChanges:c.status==="draft"};}}return u}async create(i){let{collection:e,data:n,tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r=this.prepareData(n,t),a=r.id||this.generateId();delete r.id;let l={...r,_id:a};return s&&t.tenantScoped&&(l.tenantId=s),await o.insertOne(l),this.processResult(l,t)}async update(i){let{collection:e,id:n,data:s,tenantId:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildIdFilter(n,t,o),l=this.prepareData(s,o),d=await r.findOneAndUpdate(a,{$set:l},{returnDocument:"after"});if(!d)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(d,o)}async delete(i){let{collection:e,id:n,tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r=this.buildIdFilter(n,s,t),a=await o.findOneAndDelete(r);if(!a)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(a,t)}async count(i){let{collection:e,where:n={},tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r=this.buildFilter(n,t.tenantScoped?s:void 0);return o.countDocuments(r)}async findOne(i){let{collection:e,where:n={},tenantId:s,draft:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildFilter(n,o.tenantScoped?s:void 0),l=o.fields.find(g=>g.name==="status"),d=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(g=>g.value==="published");!t&&d&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let u=this.processResult(f,o);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:u.id},{sort:{createdAt:-1}});if(c){let p=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};u={...u,...p,status:u.status};}}return u}async findVersions(i){let{collection:e,documentId:n,sort:s,limit:t=10,page:o=1,tenantId:r}=i,a=this.getCollectionConfig(e),l=this.getMongoCollection(`${e}_versions`),d={document_id:n,autosave:{$ne:true}};r&&a.tenantScoped&&(d.tenant_id=r);let f=(o-1)*t,u=this.parseSort(s),g={[u.field]:u.direction==="asc"?1:-1},[c,p]=await Promise.all([l.find(d).sort(g).skip(f).limit(t).toArray(),l.countDocuments(d)]);return {docs:c.map(y=>this.processResult(y,{})),...this.calculatePagination(o,t,p)}}async findVersionByID(i){let{collection:e,versionId:n,tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(`${e}_versions`),r={_id:n};s&&t.tenantScoped&&(r.tenant_id=s);let a=await o.findOne(r);return a?this.processResult(a,{}):null}async createVersion(i){let{collection:e,documentId:n,data:s,status:t,createdBy:o,changeDescription:r,tenantId:a,autosave:l}=i,d=this.getCollectionConfig(e),f=this.getMongoCollection(`${e}_versions`);if(l){let c={document_id:n,collection_slug:e,autosave:true};a&&d.tenantScoped&&(c.tenant_id=a);let p=await f.findOne(c);if(p){let y=new Date().toISOString();return await f.updateOne({_id:p._id},{$set:{data:s,status:t,updatedAt:y}}),this.processResult({...p,data:s,status:t,updatedAt:y},{})}}let u=new Date().toISOString(),g={_id:this.generateId(),document_id:n,collection_slug:e,data:s,status:t,autosave:l===true,created_by:o,change_description:r,createdAt:u,updatedAt:u};if(a&&d.tenantScoped&&(g.tenant_id=a),await f.insertOne(g),!l){let c=this.getCollectionConfig(e);c.versions?.maxPerDoc&&await this.deleteVersions({collection:e,documentId:n,keepLatest:c.versions.maxPerDoc,tenantId:a});}return this.processResult(g,{})}async updateLatestVersion(i){return this.createVersion({...i,autosave:true})}async deleteVersions(i){let{collection:e,documentId:n,keepLatest:s,tenantId:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(`${e}_versions`);if(s){let a={document_id:n,autosave:{$ne:true}};t&&o.tenantScoped&&(a.tenant_id=t);let d=(await r.find(a).sort({createdAt:-1}).limit(s).project({_id:1}).toArray()).map(f=>f._id);d.length>0&&await r.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:d},...t&&o.tenantScoped?{tenant_id:t}:{}});}else {let a={document_id:n};t&&o.tenantScoped&&(a.tenant_id=t),await r.deleteMany(a);}}async migrate(){for(let i of this.collections.values()){let e=this.getMongoCollection(i.slug);await e.createIndex({_id:1}),i.tenantScoped&&await e.createIndex({tenantId:1}),i.timestamps&&await e.createIndex({createdAt:-1});for(let n of i.fields)n.unique&&n.name&&await e.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await e.createIndex({[n.name]:1});}}getCollectionConfig(i){if(i.startsWith("_globals_")){let n=i.replace("_globals_",""),s=this.globals.get(n);if(!s)throw new Error(`Global "${n}" not found`);return s}let e=this.collections.get(i);if(!e)throw new Error(`Collection "${i}" not found`);return e}buildFilter(i={},e){let n={};e&&(n.tenantId=e);for(let[s,t]of Object.entries(i))if(s==="AND"&&Array.isArray(t)){let o=t.map(r=>this.buildFilter(r));Object.assign(n,...o);}else if(s==="OR"&&Array.isArray(t))n.$or=t.map(o=>this.buildFilter(o));else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o={};if(t.equals!==void 0){n[s==="id"?"_id":s]=t.equals;continue}t.not_equals!==void 0&&(o.$ne=t.not_equals),t.in!==void 0&&(o.$in=t.in),t.not_in!==void 0&&(o.$nin=t.not_in),t.greater_than!==void 0&&(o.$gt=t.greater_than),t.greater_than_equal!==void 0&&(o.$gte=t.greater_than_equal),t.less_than!==void 0&&(o.$lt=t.less_than),t.less_than_equal!==void 0&&(o.$lte=t.less_than_equal),t.like!==void 0&&(o.$regex=new RegExp(t.like.replace(/%/g,".*"),"i")),t.not_like!==void 0&&(o.$not=new RegExp(t.not_like.replace(/%/g,".*"),"i")),t.contains!==void 0&&(o.$regex=new RegExp(`.*${t.contains}.*`,"i")),t.exists!==void 0&&(o.$exists=t.exists),Object.keys(o).length>0&&(n[s==="id"?"_id":s]=o);}else n[s==="id"?"_id":s]=t;return n}buildProjection(i){if(!i||i.length===0)return;let e={_id:1};for(let n of i)e[n]=1;return e}processResult(i,e){if(!i)return null;let n={...i};for(let s of Object.keys(n))/^\d+$/.test(s)&&delete n[s];return i._id&&(n.id=String(i._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()),chunkOXEJCIOA_cjs.a(n)}generateId(){let i=Date.now().toString(16).padStart(12,"0"),e=crypto.randomBytes(6).toString("hex");return i+e}};function V(w){return new b(w)}
2
- exports.a=b;exports.b=V;
@@ -1 +0,0 @@
1
- 'use strict';var h=require('bcryptjs'),crypto=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var h__default=/*#__PURE__*/_interopDefault(h);var p=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),n={_id:s,name:e.name||null,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",avatar:e.avatar||null,tenantId:e.tenantId||null,metadata:e.metadata||null,emailVerified:false,locked:false,lastLogin:null,failedLoginAttempts:0,createdAt:t,updatedAt:t};return await this.col("users").insertOne(n),this.docToAuthUser(n)}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.metadata!==void 0&&(t.metadata=s.metadata),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 h__default.default.compare(s,i.passwordHash)?t:null}async hashPassword(e){return h__default.default.hash(e,12)}async createSession(e,s){let t=crypto.randomUUID(),i=crypto.randomBytes(32).toString("base64url"),n=crypto.randomBytes(32).toString("base64url"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:n,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 n of i)if(await h__default.default.compare(e,n))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:n,resource:o,resourceId:u,success:d,startDate:c,endDate:f}=e,a={};i&&(a.userId=i),n&&(Array.isArray(n)?a.action={$in:n}:a.action=n),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(c||f)&&(a.timestamp={},c&&(a.timestamp.$gte=c),f&&(a.timestamp.$lte=f));let g=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(r=>({id:r._id,timestamp:r.timestamp,action:r.action,userId:r.userId||void 0,userEmail:r.userEmail||void 0,role:r.role||void 0,resource:r.resource,resourceId:r.resourceId||void 0,changes:r.changes||void 0,ipAddress:r.ipAddress||void 0,userAgent:r.userAgent||void 0,success:r.success,error:r.error||void 0,metadata:r.metadata||void 0})),total:g}}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,avatar:e.avatar||void 0,tenantId:e.tenantId||void 0,metadata:e.metadata||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('mongodb'),n=i.ObjectId??i.default?.ObjectId;return await this.db.collection("email_verifications").insertOne({userId:new n(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),n=await import('mongodb'),o=n.ObjectId??n.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=p;
@@ -1,3 +0,0 @@
1
- import {a,c,b as b$1,d}from'./chunk-YNSKDTFG.js';import {a as a$1}from'./chunk-VLFM66BZ.js';import {a as a$3}from'./chunk-NGNXOXI5.js';import {a as a$2}from'./chunk-RLW6AQF2.js';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
- var b=class extends a{dialect="mongodb";client;db;database;connectionString;constructor(i){if(super(),i.connectionString){this.connectionString=i.connectionString;try{let e=new URL(i.connectionString);this.database=e.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database="kyro_cms";}}else this.client=i.client,this.database=i.database;}async connect(){if(this.connectionString&&!this.client){let i;try{let e=await import('mongodb');i=e.MongoClient??e.default?.MongoClient;}catch{a$1(["mongodb"]);let n=await import('mongodb');i=n.MongoClient??n.default?.MongoClient;}this.client=new i(this.connectionString),await this.client.connect();}else if(this.client&&typeof this.client.connect=="function")try{await this.client.connect();}catch{}this.client&&(this.db=this.client.db(this.database),this.connected=true);}async disconnect(){this.client&&(await this.client.close(),this.connected=false);}getMongoCollection(i){if(!this.db&&this.client&&(this.db=this.client.db(this.database),this.connected=true),!this.db)throw new Error("MongoDB not connected");return this.db.collection(i)}async find(i){let{collection:e,where:n={},sort:s,limit:t=10,page:o=1,tenantId:r,select:a,draft:l}=i,d$1=this.getCollectionConfig(e),f=this.getMongoCollection(e),u={...n};this.tenantContext&&d$1.tenantScoped&&(u=c({where:u},e,this.tenantContext,b$1).where||{});let g=this.buildFilter(u,d$1.tenantScoped?r:void 0),c$1=d$1.fields.find(h=>h.name==="status"),p=c$1?.type==="select"&&Array.isArray(c$1.options)&&c$1.options.some(h=>h.value==="published");!l&&p&&(g.status="published");let y=this.parseSort(s),R={[y.field]:y.direction==="asc"?1:-1},$=(o-1)*t,[O,x]=await Promise.all([f.find(g).sort(R).skip($).limit(t).project(this.buildProjection(a)).toArray(),f.countDocuments(g)]),C=O.map(h=>this.processResult(h,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(h=>d(h,e,this.tenantContext,b$1))),l&&(C=await Promise.all(C.map(async h=>{let m=await this.getMongoCollection(`${e}_versions`).findOne({document_id:h.id},{sort:{createdAt:-1}});if(m){let M=typeof m.data=="string"?JSON.parse(m.data):m.data&&typeof m.data=="object"?m.data:{};return {...h,...M,status:h.status,_hasUnpublishedChanges:m.status==="draft"}}return h}))),{docs:C,...this.calculatePagination(o,t,x)}}buildIdFilter(i,e,n){let s=String(i||""),t=/^[0-9a-fA-F]{24}$/.test(s),o=[{_id:s},{id:s},{slug:s},{orderNumber:s}];if(t)try{let{ObjectId:a}=a$2("mongodb");o.unshift({_id:new a(s)});}catch{}let r={$or:o};return e&&n?.tenantScoped&&(r.tenantId=e),r}async findByID(i){let{collection:e,id:n,tenantId:s,draft:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e);if(this.tenantContext&&o.tenantScoped){let g={_id:n,tenantId:this.tenantContext.tenantId};if(!d(g,e,this.tenantContext,b$1))return null}let a=this.buildIdFilter(n,s,o),l=o.fields.find(g=>g.name==="status"),d$1=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(g=>g.value==="published");!t&&d$1&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let u=this.processResult(f,o);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:u.id},{sort:{createdAt:-1}});if(c){let p=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};u={...u,...p,status:u.status,_hasUnpublishedChanges:c.status==="draft"};}}return u}async create(i){let{collection:e,data:n,tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r=this.prepareData(n,t),a=r.id||this.generateId();delete r.id;let l={...r,_id:a};return s&&t.tenantScoped&&(l.tenantId=s),await o.insertOne(l),this.processResult(l,t)}async update(i){let{collection:e,id:n,data:s,tenantId:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildIdFilter(n,t,o),l=this.prepareData(s,o),d=await r.findOneAndUpdate(a,{$set:l},{returnDocument:"after"});if(!d)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(d,o)}async delete(i){let{collection:e,id:n,tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r=this.buildIdFilter(n,s,t),a=await o.findOneAndDelete(r);if(!a)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(a,t)}async count(i){let{collection:e,where:n={},tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r=this.buildFilter(n,t.tenantScoped?s:void 0);return o.countDocuments(r)}async findOne(i){let{collection:e,where:n={},tenantId:s,draft:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildFilter(n,o.tenantScoped?s:void 0),l=o.fields.find(g=>g.name==="status"),d=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(g=>g.value==="published");!t&&d&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let u=this.processResult(f,o);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:u.id},{sort:{createdAt:-1}});if(c){let p=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};u={...u,...p,status:u.status};}}return u}async findVersions(i){let{collection:e,documentId:n,sort:s,limit:t=10,page:o=1,tenantId:r}=i,a=this.getCollectionConfig(e),l=this.getMongoCollection(`${e}_versions`),d={document_id:n,autosave:{$ne:true}};r&&a.tenantScoped&&(d.tenant_id=r);let f=(o-1)*t,u=this.parseSort(s),g={[u.field]:u.direction==="asc"?1:-1},[c,p]=await Promise.all([l.find(d).sort(g).skip(f).limit(t).toArray(),l.countDocuments(d)]);return {docs:c.map(y=>this.processResult(y,{})),...this.calculatePagination(o,t,p)}}async findVersionByID(i){let{collection:e,versionId:n,tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(`${e}_versions`),r={_id:n};s&&t.tenantScoped&&(r.tenant_id=s);let a=await o.findOne(r);return a?this.processResult(a,{}):null}async createVersion(i){let{collection:e,documentId:n,data:s,status:t,createdBy:o,changeDescription:r,tenantId:a,autosave:l}=i,d=this.getCollectionConfig(e),f=this.getMongoCollection(`${e}_versions`);if(l){let c={document_id:n,collection_slug:e,autosave:true};a&&d.tenantScoped&&(c.tenant_id=a);let p=await f.findOne(c);if(p){let y=new Date().toISOString();return await f.updateOne({_id:p._id},{$set:{data:s,status:t,updatedAt:y}}),this.processResult({...p,data:s,status:t,updatedAt:y},{})}}let u=new Date().toISOString(),g={_id:this.generateId(),document_id:n,collection_slug:e,data:s,status:t,autosave:l===true,created_by:o,change_description:r,createdAt:u,updatedAt:u};if(a&&d.tenantScoped&&(g.tenant_id=a),await f.insertOne(g),!l){let c=this.getCollectionConfig(e);c.versions?.maxPerDoc&&await this.deleteVersions({collection:e,documentId:n,keepLatest:c.versions.maxPerDoc,tenantId:a});}return this.processResult(g,{})}async updateLatestVersion(i){return this.createVersion({...i,autosave:true})}async deleteVersions(i){let{collection:e,documentId:n,keepLatest:s,tenantId:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(`${e}_versions`);if(s){let a={document_id:n,autosave:{$ne:true}};t&&o.tenantScoped&&(a.tenant_id=t);let d=(await r.find(a).sort({createdAt:-1}).limit(s).project({_id:1}).toArray()).map(f=>f._id);d.length>0&&await r.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:d},...t&&o.tenantScoped?{tenant_id:t}:{}});}else {let a={document_id:n};t&&o.tenantScoped&&(a.tenant_id=t),await r.deleteMany(a);}}async migrate(){for(let i of this.collections.values()){let e=this.getMongoCollection(i.slug);await e.createIndex({_id:1}),i.tenantScoped&&await e.createIndex({tenantId:1}),i.timestamps&&await e.createIndex({createdAt:-1});for(let n of i.fields)n.unique&&n.name&&await e.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await e.createIndex({[n.name]:1});}}getCollectionConfig(i){if(i.startsWith("_globals_")){let n=i.replace("_globals_",""),s=this.globals.get(n);if(!s)throw new Error(`Global "${n}" not found`);return s}let e=this.collections.get(i);if(!e)throw new Error(`Collection "${i}" not found`);return e}buildFilter(i={},e){let n={};e&&(n.tenantId=e);for(let[s,t]of Object.entries(i))if(s==="AND"&&Array.isArray(t)){let o=t.map(r=>this.buildFilter(r));Object.assign(n,...o);}else if(s==="OR"&&Array.isArray(t))n.$or=t.map(o=>this.buildFilter(o));else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o={};if(t.equals!==void 0){n[s==="id"?"_id":s]=t.equals;continue}t.not_equals!==void 0&&(o.$ne=t.not_equals),t.in!==void 0&&(o.$in=t.in),t.not_in!==void 0&&(o.$nin=t.not_in),t.greater_than!==void 0&&(o.$gt=t.greater_than),t.greater_than_equal!==void 0&&(o.$gte=t.greater_than_equal),t.less_than!==void 0&&(o.$lt=t.less_than),t.less_than_equal!==void 0&&(o.$lte=t.less_than_equal),t.like!==void 0&&(o.$regex=new RegExp(t.like.replace(/%/g,".*"),"i")),t.not_like!==void 0&&(o.$not=new RegExp(t.not_like.replace(/%/g,".*"),"i")),t.contains!==void 0&&(o.$regex=new RegExp(`.*${t.contains}.*`,"i")),t.exists!==void 0&&(o.$exists=t.exists),Object.keys(o).length>0&&(n[s==="id"?"_id":s]=o);}else n[s==="id"?"_id":s]=t;return n}buildProjection(i){if(!i||i.length===0)return;let e={_id:1};for(let n of i)e[n]=1;return e}processResult(i,e){if(!i)return null;let n={...i};for(let s of Object.keys(n))/^\d+$/.test(s)&&delete n[s];return i._id&&(n.id=String(i._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()),a$3(n)}generateId(){let i=Date.now().toString(16).padStart(12,"0"),e=randomBytes(6).toString("hex");return i+e}};function j(w){return new b(w)}
3
- export{b as a,j as b};