@kyro-cms/core 0.12.58 → 0.12.61
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/{bootstrap-IGHJFNYG.js → bootstrap-WB6FDH2T.js} +1 -1
- package/dist/bootstrap-XDT4MRML.cjs +1 -0
- package/dist/{chunk-YZNFCSCE.js → chunk-26MOA3HJ.js} +10 -10
- package/dist/{chunk-ECFZEY5B.cjs → chunk-3XLXKGEU.cjs} +1 -1
- package/dist/{chunk-QLUMJS5W.cjs → chunk-4FHWIGHO.cjs} +10 -10
- package/dist/chunk-4ZWLNGLS.js +2 -0
- package/dist/{chunk-VOQUO2EZ.cjs → chunk-5DWQGEM2.cjs} +22 -22
- package/dist/{chunk-OXGJOYEO.js → chunk-637PTUHF.js} +1 -1
- package/dist/chunk-6QWX3DEB.cjs +120 -0
- package/dist/{chunk-ZMG7Z3KF.js → chunk-75BFTYBS.js} +23 -23
- package/dist/{chunk-YZEMLLD2.js → chunk-AWQGDMOE.js} +3 -3
- package/dist/chunk-D6SDGHY6.js +2 -0
- package/dist/{chunk-MP5VC5ER.cjs → chunk-FP5UK272.cjs} +1 -1
- package/dist/{chunk-AK754S3T.cjs → chunk-FSL3NLRT.cjs} +2 -2
- package/dist/{chunk-RTHJ6SS5.js → chunk-GQGFNTDZ.js} +1 -1
- package/dist/chunk-HKYBQYAJ.cjs +19 -0
- package/dist/{chunk-TDGSIF5H.cjs → chunk-JU3UAZRY.cjs} +10 -11
- package/dist/chunk-KMFLHGD5.cjs +1 -0
- package/dist/{chunk-XP56DE7A.js → chunk-KWGB3YNI.js} +90 -78
- package/dist/{chunk-KBJ4XZWF.cjs → chunk-LOP464VR.cjs} +1 -1
- package/dist/{chunk-R25WLKX4.js → chunk-N6MNQIQU.js} +101 -101
- package/dist/{chunk-BHR7OAU4.cjs → chunk-OPTVCCQQ.cjs} +101 -101
- package/dist/chunk-RDFGJHEG.js +2 -0
- package/dist/chunk-RILJCH6H.js +121 -0
- package/dist/{chunk-KCHPADCH.cjs → chunk-SOCBJPYB.cjs} +1 -1
- package/dist/chunk-T4JJVUGT.js +20 -0
- package/dist/{chunk-BAXBE4JD.js → chunk-TBTQXIHP.js} +1 -1
- package/dist/{chunk-KNOFTUQV.js → chunk-VJODUKKM.js} +11 -12
- package/dist/{chunk-VKXWJOWI.cjs → chunk-XTTGHN3D.cjs} +90 -78
- package/dist/{chunk-DUO523BH.cjs → chunk-ZHA446FA.cjs} +1 -1
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.js +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +2 -1
- package/dist/drizzle/index.d.ts +2 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/fields/index.cjs +1 -1
- package/dist/fields/index.js +1 -1
- package/dist/graphql/index.cjs +1 -1
- package/dist/graphql/index.d.cts +2 -0
- package/dist/graphql/index.d.ts +2 -0
- package/dist/graphql/index.js +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +7 -9
- package/dist/index.d.ts +7 -9
- package/dist/index.js +5 -5
- package/dist/{local-2IFOTHAA.js → local-4MZ7KOL3.js} +1 -1
- package/dist/{local-UESCNPQP.cjs → local-NDTKWJQ6.cjs} +1 -1
- package/dist/postgres-auth-adapter-SK3N3OSS.js +1 -1
- package/dist/postgres-auth-adapter-ZO6HK5AK.cjs +1 -1
- package/dist/postgres-js-GXZX3AGZ.cjs +1 -0
- package/dist/{postgres-js-4CI7FMYS.js → postgres-js-WE3NBRFO.js} +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.d.cts +3 -3
- package/dist/rest/index.d.ts +3 -3
- package/dist/rest/index.js +1 -1
- package/dist/{sqlite-adapter-4TPNROJK.js → sqlite-adapter-52PL52VU.js} +1 -1
- package/dist/{sqlite-adapter-ZTABLT2X.cjs → sqlite-adapter-MNNZZXGX.cjs} +1 -1
- package/dist/trpc/index.cjs +1 -1
- package/dist/trpc/index.js +1 -1
- package/package.json +2 -2
- package/dist/bootstrap-FTVBJ47D.cjs +0 -1
- package/dist/chunk-5LPNEYK5.cjs +0 -1
- package/dist/chunk-72VOOMJI.js +0 -20
- package/dist/chunk-KFEJPRC4.js +0 -265
- package/dist/chunk-PA4ZZREG.js +0 -2
- package/dist/chunk-PCVQNVSU.cjs +0 -19
- package/dist/chunk-SQBTIMWF.js +0 -2
- package/dist/chunk-X4RTM5AQ.js +0 -2
- package/dist/chunk-Z2XEW5RL.cjs +0 -264
- package/dist/postgres-js-3Y54EXVQ.cjs +0 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-
|
|
2
|
-
g();g();g();g();async function He(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function $r(s,e){return He(s,e)}g();g();g();var E=class extends a$4{connectionString;constructor(e){super(),this.connectionString=e.connectionString;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.connectionString)throw new Error("NeonAdapter: Connection string is required.");try{let r=await fetch(`${this.connectionString}/sql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e,params:t})});return r.ok?(await r.json()).rows||[]:[]}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function Fe(s){return new E(s)}g();var O=class extends a$4{url;authToken;constructor(e){super(),this.url=e.url.replace(/^libsql:\/\//,"https://"),this.authToken=e.authToken;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.url)throw new Error("TursoAdapter: Database URL is required.");try{let r={"Content-Type":"application/json"};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`);let o=await fetch(`${this.url}/v2/pipeline`,{method:"POST",headers:r,body:JSON.stringify({requests:[{type:"execute",stmt:{sql:e,args:t.map(l=>({type:"text",value:String(l)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let c=i.cols.map(l=>l.name);return i.rows.map(l=>{let p={};return c.forEach((g,m)=>{p[g]=l[m]?.value??null;}),p})}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function Be(s){return new O(s)}g();g();g();g();var zr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},R=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...zr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),n=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return n&&n>new Date?{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:o}:n&&n<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),n=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),n>=this.config.maxAttempts){let i=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:n}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-n),totalAttempts:n}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),n=t||this.config.lockDuration,i=new Date(o+n),c=this.redis.pipeline();c.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),c.expire(r,Math.ceil(n/1e3)+3600),await c.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(n=>new Date(parseInt(n,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((i,c)=>(c+1)%this.config.maxAttempts===0).length,n=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:n?new Date(parseInt(n,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};g();var jr={"auth:login":{window:9e5,max:5},"auth:register":{window:36e5,max:3},"auth:forgot":{window:36e5,max:3},"auth:reset":{window:36e5,max:5},"auth:verify":{window:36e5,max:5},"api:general":{window:6e4,max:100},"api:authenticated":{window:6e4,max:200}},v=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...jr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window,c=this.redis.pipeline();c.zremrangebyscore(o,0,i),c.zcard(o),c.zadd(o,n,`${n}:${Math.random()}`),c.expire(o,Math.ceil(r.window/1e3)+1);let p=(await c.exec())?.[1]?.[1]||0;if(p>=r.max){let g=await this.redis.zrange(o,0,0,"WITHSCORES"),m=g.length>1?parseInt(g[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:m,retryAfter:Math.ceil((m-n)/1e3)}}return {allowed:true,remaining:r.max-p-1,resetAt:n+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],n=this.getKey(`user:${e}:${t}`,r),i=Date.now(),c=i-o.window,l=this.redis.pipeline();l.zremrangebyscore(n,0,c),l.zcard(n),l.zadd(n,i,`${i}:${Math.random()}`),l.expire(n,Math.ceil(o.window/1e3)+1);let g=(await l.exec())?.[1]?.[1]||0;if(g>=o.max){let m=await this.redis.zrange(n,0,0,"WITHSCORES"),f=m.length>1?parseInt(m[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:f,retryAfter:Math.ceil((f-i)/1e3)}}return {allowed:true,remaining:o.max-g-1,resetAt:i+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window;await this.redis.zremrangebyscore(o,0,i);let c=await this.redis.zcard(o);return {count:c,limit:r.max,remaining:Math.max(0,r.max-c),resetAt:n+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};g();g();g();var D=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),n={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,n),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),n}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('./bcryptjs-ZEEHSMAG.js')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('./bcryptjs-ZEEHSMAG.js')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),i=new Date,c={id:r,userId:e,token:o,refreshToken:n,expiresAt:new Date(i.getTime()+86400*1e3).toISOString(),createdAt:i.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,c),this.refreshTokens.set(n,r),c}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),n=(await import('./bcryptjs-ZEEHSMAG.js')).default;for(let i of o)if(await n.compare(e,i))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(n=>n.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(n=>e.action.includes(String(n.action))):o=o.filter(n=>n.action===e.action)),e.resource&&(o=o.filter(n=>n.resource===e.resource)),e.success!==void 0&&(o=o.filter(n=>n.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};g();var I=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:n}=r;return n!==null&&n>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(n),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let n=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=n.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,n=new Date(r+o),i=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};i.attempts=this.config.maxAttempts,i.lockedAt=r,i.lockedUntil=n.getTime(),this.storage.set(e,i);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),n=null,i=this.storage.get(e);i&&i.lockedAt!==null&&(n=new Date(i.lockedAt));let c=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:n,averageAttemptsBeforeLockout:c}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function b(s,e=""){return process.env[s]||e}function P(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function y(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Ke(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Gr(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$2({path:b("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=b("DATABASE_URL","");if(o){let n,i;try{n=(await import('./postgres-js-4CI7FMYS.js')).drizzle,i=await import('./src-QBADSZV4.js');}catch{a(["postgres","drizzle-orm"]),n=(await import('./postgres-js-4CI7FMYS.js')).drizzle,i=await import('./src-QBADSZV4.js');}let c=i.default(o,{onnotice:()=>{}}),l=n(c);return new a$3({db:l})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=b("MONGODB_URI","");if(o){let n;try{let g=await import('./lib-XXYYUPMW.js');n=g.MongoClient??g.default?.MongoClient;}catch{a(["mongodb"]);let m=await import('./lib-XXYYUPMW.js');n=m.MongoClient??m.default?.MongoClient;}let i=new n(o);await i.connect();let l=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",p=i.db(l);return new a$1({db:p})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}default:return new D}}async function G(s,e){let t=P("KYRO_DISTRIBUTED",false),r$1;if(t){let{RedisAuthAdapter:m}=await import('./redis-adapter-QPCTMF55.js'),f=b("REDIS_URL","redis://localhost:6379"),w=P("REDIS_TLS",false),h=new m({url:f,tls:w});await h.connect?.(),r$1=h;}else {let m=s||Ke();r$1=await Gr(m),r$1.connect&&await r$1.connect();}let o=e?await q.fromConfig(e).catch(()=>null)||q.fromEnv()||void 0:q.fromEnv()||void 0,n=new r({minLength:y("PASSWORD_MIN_LENGTH",12),requireUppercase:P("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:P("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:P("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:P("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:y("PASSWORD_PREVENT_REUSE",5),maxLength:y("PASSWORD_MAX_LENGTH",128)}),i,c,l;if(t){let f=r$1.redis;i=new R(f,{maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new v(f,{"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l=new bb(f,y("AUDIT_LOG_RETENTION_DAYS",30));}else i=new I({maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new ab({"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l=P("AUDIT_LOG_ENABLED",true)?new db(y("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let p=new eb({redis:r$1,email:o,jwtSecret:b("APP_SECRET","change-me"),jwtExpiresIn:b("JWT_EXPIRES_IN","24h"),jwtIssuer:b("JWT_ISSUER","kyro-cms"),jwtAudience:b("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n,lockout:i,rateLimiter:c,auditLogger:l,baseUrl:b("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:P("EMAIL_VERIFICATION_REQUIRED",true)}),g=t?"distributed":s||Ke();return {authAdapter:r$1,databaseType:g,email:o,passwordPolicy:n,lockout:i,rateLimiter:c,auditLogger:l,routes:p}}var $e=G().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Qr=12,Yr="24h",Jr="7d",K=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Yr,refreshExpiresIn:t.refreshExpiresIn??Jr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Qr};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('./jsonwebtoken-OD67R5JS.js');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('./jsonwebtoken-OD67R5JS.js'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('./bcryptjs-ZEEHSMAG.js');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function Xr(s,e){return new K(s,e)}g();g();function N(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var $=class{adapter;config;constructor(e,t){this.adapter=e,this.config={...N(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},n=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),n}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let n=r.slice(this.config.maxVersionsPerDocument);for(let i of n)if(i.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Zr(s,e){return new $(s,e)}function eo(s){return s==="published"}function to(s){return s==="draft"}function ro(s){return s==="archived"}g();function oo(s){return s?Array.isArray(s)?s:Object.values(s):[]}function so(s){return s?Array.isArray(s)?s:Object.values(s):[]}function ze(s){return {collections:oo(s.collections),globals:so(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var no=ze;g();function io(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:n,url:i}=s;if(!e)return "";let c=e.siteName||"",l=r||t?.defaultTitle||c,p=t?.titleTemplate,g=t?.separator||" | ",m=t?.siteNameInTitle!==false,f=p?p.replace(/\{\{title\}\}/g,l).replace(/\{\{siteName\}\}/g,m?c:"").replace(/\{\{separator\}\}/g,g).replace(/\s+/g," ").trim():l,w=o||t?.defaultDescription||e.siteDescription||"",h=n||e.siteOgImage?.url||"",V=i||e.siteUrl||"",A=`
|
|
1
|
+
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-T4JJVUGT.js';export{a as RedisAuthAdapter}from'./chunk-M75VGFCI.js';import {a as a$5}from'./chunk-RPRGGGIW.js';export{k as allGlobalSettings,q as blogCollections,l as coreGlobalSettings,V as createTemplateConfig,r as ecommerceCollections,s as ecommerceGlobals,t as kitchenSinkCollections,v as mediaCollections,a as minimalCollections,U as templateCollections}from'./chunk-KCQBV3MA.js';export{a as kyro}from'./chunk-PCN6QV3Z.js';import {f}from'./chunk-26MOA3HJ.js';export{t as AnalyticsPlugin,u as CommentsPlugin,a as ConfigValidationError,z as Kyro,q as KyroPlugin,C as Logger,r as PluginManager,m as Registry,v as ReviewsPlugin,s as SEOPlugin,w as WishlistPlugin,y as applyCollectionOverrides,i as collectionToCreateZod,j as collectionToUpdateZod,k as collectionToWhereZod,h as collectionToZod,A as createKyro,B as createKyroHandler,p as createRegistry,g as fieldToZod,n as getRegistry,l as globalToZod,D as logger,x as presetPlugins,o as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal,f as z}from'./chunk-26MOA3HJ.js';export{e as autoBootstrap,a as bootstrapAdmin,f as bootstrapWithRetry,d as getBootstrapFromEnv}from'./chunk-TBTQXIHP.js';import'./chunk-LWM4WABU.js';export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-7FXEXHK6.js';export{q as ALL_FIELD_TYPES,n as COMPLEX_FIELD_TYPES,p as LAYOUT_FIELD_TYPES,m as PRIMITIVE_FIELD_TYPES,o as RELATIONAL_FIELD_TYPES,d as isArrayField,f as isBlocksField,e as isGroupField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,t as normalizeRichTextValue,u as renderRichText,s as richTextStyles}from'./chunk-ZRIBWDYJ.js';import'./chunk-D6SDGHY6.js';export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'./chunk-4ZWLNGLS.js';export{J as buildGraphQLSchema,K as createGraphQLSchema}from'./chunk-75BFTYBS.js';import {bb,ab,db,eb}from'./chunk-RILJCH6H.js';export{bb as AuditLogger,db as InMemoryAuditLogger,ab as InMemoryRateLimiter,gb as MediaService,cb as createAuditContext,ib as createKyroApp,_a as createLocalStorage,jb as createRESTAPI,fb as isEdgeRuntime,Za as resolveProvider}from'./chunk-RILJCH6H.js';import {q,r}from'./chunk-KWGB3YNI.js';export{p as ConfigService,q as EmailTransport,r as PasswordPolicy,o as getEmailTemplates,n as renderAbandonedCart,g as renderAccountLocked,a as renderBaseLayout,f as renderMagicLink,i as renderNewLogin,j as renderOrderConfirmation,l as renderOrderDelivered,m as renderOrderRefunded,k as renderOrderShipped,e as renderPasswordChanged,c as renderResetPassword,h as renderUserInvite,b as renderVerifyEmail,d as renderWelcome}from'./chunk-KWGB3YNI.js';import'./chunk-OLRCZ6E3.js';import {a as a$2}from'./chunk-N6MNQIQU.js';export{a as SQLiteAuthAdapter}from'./chunk-N6MNQIQU.js';import {f as f$1}from'./chunk-6TPICJ2L.js';export{c as getAppSecret,d as getEncryptionKey,e as getSessionConfig,b as loadSecrets,a as setDbAdapter}from'./chunk-6TPICJ2L.js';import'./chunk-YENNL5HG.js';import'./chunk-W45TLOOT.js';import'./chunk-IKGVPXMK.js';import'./chunk-YUUXFD73.js';import'./chunk-LVBHOZZF.js';import'./chunk-OBYAIJVU.js';import'./chunk-JRUQ5ABB.js';import'./chunk-CIVA6SKW.js';import'./chunk-WPM6LFCY.js';import'./chunk-U6KFONKM.js';import'./chunk-TYQYKKWJ.js';import'./chunk-L2QXP26Q.js';export{d as ALL_WEBHOOK_EVENTS,e as WEBHOOK_COLLECTION,f as WEBHOOK_DELIVERY_COLLECTION,c as WEBHOOK_EVENTS,m as WebhookService,k as buildDeliveryRecord,l as createTestPayload,n as createWebhookService,i as deliverWebhook,j as deliverWithRetry,h as generateWebhookSecret,g as signPayload}from'./chunk-AWQGDMOE.js';export{h as evaluateAccess,j as getWhereClause,i as mergeWhereClauses}from'./chunk-GQGFNTDZ.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-5M3FKE2V.js';import'./chunk-7MNDQU6K.js';import'./chunk-QDBGBDCT.js';export{g as DrizzleAdapter,f as collectionToDrizzleSchema,b as createDatabase,h as createDrizzleAdapter,e as fieldToDrizzleType,c as runMigrations,d as seedDefaultRoles}from'./chunk-VJODUKKM.js';import'./chunk-JV4HJBXW.js';import {a as a$3}from'./chunk-ZWDBPEXL.js';export{a as PostgresAuthAdapter}from'./chunk-ZWDBPEXL.js';import'./chunk-47CXBWMA.js';import'./chunk-EML5FDUU.js';import'./chunk-637PTUHF.js';import'./chunk-N5POANYV.js';import'./chunk-HRAY65XH.js';import'./chunk-2HA6EKXX.js';import'./chunk-FLMUMPDE.js';import'./chunk-3NSZZCOJ.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-LVHWORV4.js';import {a as a$1}from'./chunk-5ZEYOFAK.js';export{a as MongoDBAuthAdapter}from'./chunk-5ZEYOFAK.js';import {a as a$4}from'./chunk-SLMIYECU.js';export{a as AbstractBaseAdapter}from'./chunk-SLMIYECU.js';import {a}from'./chunk-P6JITOFF.js';import'./chunk-7NH7H3WA.js';import'./chunk-VVVCCB6R.js';import'./chunk-TBHNE4VV.js';import {g}from'./chunk-Y2YAKDEQ.js';import ee,{randomBytes}from'crypto';import {readFileSync}from'fs';import Xe,{join,resolve}from'path';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g();g();g();g();async function He(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function $r(s,e){return He(s,e)}g();g();var E=class extends a$4{connectionString;constructor(e){super(),this.connectionString=e.connectionString;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.connectionString)throw new Error("NeonAdapter: Connection string is required.");try{let r=await fetch(`${this.connectionString}/sql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e,params:t})});return r.ok?(await r.json()).rows||[]:[]}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function Fe(s){return new E(s)}g();var O=class extends a$4{url;authToken;constructor(e){super(),this.url=e.url.replace(/^libsql:\/\//,"https://"),this.authToken=e.authToken;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.url)throw new Error("TursoAdapter: Database URL is required.");try{let r={"Content-Type":"application/json"};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`);let o=await fetch(`${this.url}/v2/pipeline`,{method:"POST",headers:r,body:JSON.stringify({requests:[{type:"execute",stmt:{sql:e,args:t.map(l=>({type:"text",value:String(l)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let c=i.cols.map(l=>l.name);return i.rows.map(l=>{let p={};return c.forEach((g,m)=>{p[g]=l[m]?.value??null;}),p})}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function Ke(s){return new O(s)}g();g();g();g();var zr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},R=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...zr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),n=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return n&&n>new Date?{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:o}:n&&n<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),n=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),n>=this.config.maxAttempts){let i=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:n}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-n),totalAttempts:n}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),n=t||this.config.lockDuration,i=new Date(o+n),c=this.redis.pipeline();c.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),c.expire(r,Math.ceil(n/1e3)+3600),await c.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(n=>new Date(parseInt(n,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((i,c)=>(c+1)%this.config.maxAttempts===0).length,n=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:n?new Date(parseInt(n,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};g();var jr={"auth:login":{window:9e5,max:5},"auth:register":{window:36e5,max:3},"auth:forgot":{window:36e5,max:3},"auth:reset":{window:36e5,max:5},"auth:verify":{window:36e5,max:5},"api:general":{window:6e4,max:100},"api:authenticated":{window:6e4,max:200}},v=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...jr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window,c=this.redis.pipeline();c.zremrangebyscore(o,0,i),c.zcard(o),c.zadd(o,n,`${n}:${Math.random()}`),c.expire(o,Math.ceil(r.window/1e3)+1);let p=(await c.exec())?.[1]?.[1]||0;if(p>=r.max){let g=await this.redis.zrange(o,0,0,"WITHSCORES"),m=g.length>1?parseInt(g[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:m,retryAfter:Math.ceil((m-n)/1e3)}}return {allowed:true,remaining:r.max-p-1,resetAt:n+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],n=this.getKey(`user:${e}:${t}`,r),i=Date.now(),c=i-o.window,l=this.redis.pipeline();l.zremrangebyscore(n,0,c),l.zcard(n),l.zadd(n,i,`${i}:${Math.random()}`),l.expire(n,Math.ceil(o.window/1e3)+1);let g=(await l.exec())?.[1]?.[1]||0;if(g>=o.max){let m=await this.redis.zrange(n,0,0,"WITHSCORES"),f=m.length>1?parseInt(m[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:f,retryAfter:Math.ceil((f-i)/1e3)}}return {allowed:true,remaining:o.max-g-1,resetAt:i+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window;await this.redis.zremrangebyscore(o,0,i);let c=await this.redis.zcard(o);return {count:c,limit:r.max,remaining:Math.max(0,r.max-c),resetAt:n+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};g();g();g();var D=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),n={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,n),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),n}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('./bcryptjs-ZEEHSMAG.js')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('./bcryptjs-ZEEHSMAG.js')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),i=new Date,c={id:r,userId:e,token:o,refreshToken:n,expiresAt:new Date(i.getTime()+86400*1e3).toISOString(),createdAt:i.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,c),this.refreshTokens.set(n,r),c}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),n=(await import('./bcryptjs-ZEEHSMAG.js')).default;for(let i of o)if(await n.compare(e,i))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(n=>n.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(n=>e.action.includes(String(n.action))):o=o.filter(n=>n.action===e.action)),e.resource&&(o=o.filter(n=>n.resource===e.resource)),e.success!==void 0&&(o=o.filter(n=>n.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};g();var I=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:n}=r;return n!==null&&n>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(n),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let n=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=n.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,n=new Date(r+o),i=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};i.attempts=this.config.maxAttempts,i.lockedAt=r,i.lockedUntil=n.getTime(),this.storage.set(e,i);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),n=null,i=this.storage.get(e);i&&i.lockedAt!==null&&(n=new Date(i.lockedAt));let c=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:n,averageAttemptsBeforeLockout:c}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function b(s,e=""){return process.env[s]||e}function P(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function y(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Be(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Gr(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$2({path:b("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=b("DATABASE_URL","");if(o){let n,i;try{n=(await import('./postgres-js-WE3NBRFO.js')).drizzle,i=await import('./src-QBADSZV4.js');}catch{a(["postgres","drizzle-orm"]),n=(await import('./postgres-js-WE3NBRFO.js')).drizzle,i=await import('./src-QBADSZV4.js');}let c=i.default(o,{onnotice:()=>{}}),l=n(c);return new a$3({db:l})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=b("MONGODB_URI","");if(o){let n;try{let g=await import('./lib-XXYYUPMW.js');n=g.MongoClient??g.default?.MongoClient;}catch{a(["mongodb"]);let m=await import('./lib-XXYYUPMW.js');n=m.MongoClient??m.default?.MongoClient;}let i=new n(o);await i.connect();let l=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",p=i.db(l);return new a$1({db:p})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}default:return new D}}async function G(s,e){let t=P("KYRO_DISTRIBUTED",false),r$1;if(t){let{RedisAuthAdapter:m}=await import('./redis-adapter-QPCTMF55.js'),f=b("REDIS_URL","redis://localhost:6379"),w=P("REDIS_TLS",false),h=new m({url:f,tls:w});await h.connect?.(),r$1=h;}else {let m=s||Be();r$1=await Gr(m),r$1.connect&&await r$1.connect();}let o=e?await q.fromConfig(e).catch(()=>null)||q.fromEnv()||void 0:q.fromEnv()||void 0,n=new r({minLength:y("PASSWORD_MIN_LENGTH",12),requireUppercase:P("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:P("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:P("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:P("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:y("PASSWORD_PREVENT_REUSE",5),maxLength:y("PASSWORD_MAX_LENGTH",128)}),i,c,l;if(t){let f=r$1.redis;i=new R(f,{maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new v(f,{"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l=new bb(f,y("AUDIT_LOG_RETENTION_DAYS",30));}else i=new I({maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new ab({"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l=P("AUDIT_LOG_ENABLED",true)?new db(y("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let p=new eb({redis:r$1,email:o,jwtSecret:b("APP_SECRET","change-me"),jwtExpiresIn:b("JWT_EXPIRES_IN","24h"),jwtIssuer:b("JWT_ISSUER","kyro-cms"),jwtAudience:b("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n,lockout:i,rateLimiter:c,auditLogger:l,baseUrl:b("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:P("EMAIL_VERIFICATION_REQUIRED",true)}),g=t?"distributed":s||Be();return {authAdapter:r$1,databaseType:g,email:o,passwordPolicy:n,lockout:i,rateLimiter:c,auditLogger:l,routes:p}}var $e=G().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Qr=12,Yr="24h",Jr="7d",B=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Yr,refreshExpiresIn:t.refreshExpiresIn??Jr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Qr};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('./jsonwebtoken-OD67R5JS.js');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('./jsonwebtoken-OD67R5JS.js'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('./bcryptjs-ZEEHSMAG.js');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function Xr(s,e){return new B(s,e)}g();g();function N(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var $=class{adapter;config;constructor(e,t){this.adapter=e,this.config={...N(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},n=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),n}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let n=r.slice(this.config.maxVersionsPerDocument);for(let i of n)if(i.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Zr(s,e){return new $(s,e)}function eo(s){return s==="published"}function to(s){return s==="draft"}function ro(s){return s==="archived"}g();function oo(s){return s?Array.isArray(s)?s:Object.values(s):[]}function so(s){return s?Array.isArray(s)?s:Object.values(s):[]}function ze(s){return {collections:oo(s.collections),globals:so(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var no=ze;g();function io(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:n,url:i}=s;if(!e)return "";let c=e.siteName||"",l=r||t?.defaultTitle||c,p=t?.titleTemplate,g=t?.separator||" | ",m=t?.siteNameInTitle!==false,f=p?p.replace(/\{\{title\}\}/g,l).replace(/\{\{siteName\}\}/g,m?c:"").replace(/\{\{separator\}\}/g,g).replace(/\s+/g," ").trim():l,w=o||t?.defaultDescription||e.siteDescription||"",h=n||e.siteOgImage?.url||"",V=i||e.siteUrl||"",A=`
|
|
3
3
|
<title>${f}</title>
|
|
4
4
|
<meta name="description" content="${w}">
|
|
5
5
|
`;e.siteFavicon?.url&&(A+=`
|
|
@@ -41,11 +41,11 @@ g();g();g();g();async function He(s,e){let t=e.data;for(let r of s){let o=await
|
|
|
41
41
|
`),r&&(o+=`
|
|
42
42
|
<!-- Plausible Analytics -->
|
|
43
43
|
<script defer data-domain="${r}" src="https://plausible.io/js/script.js"></script>
|
|
44
|
-
`),o}g();var co={facebook:{label:"Facebook"},twitter:{label:"Twitter / X"},instagram:{label:"Instagram"},linkedin:{label:"LinkedIn"},youtube:{label:"YouTube"},tiktok:{label:"TikTok"},pinterest:{label:"Pinterest"},discord:{label:"Discord"},twitch:{label:"Twitch"},github:{label:"GitHub"},mastodon:{label:"Mastodon"}},lo=["facebook","twitter","instagram","linkedin","youtube","tiktok","pinterest","discord","twitch","github","mastodon"];function je(s){if(!s)return [];let e=s.showAll===true,t=[];for(let r of lo){let o=s[r];if(!o||["tiktok","pinterest","discord","twitch","github","mastodon"].includes(r)&&!e)continue;let i=co[r];t.push({platform:r,url:o,label:i?.label||r});}return t}async function uo(s,e){try{let t=await s.findOne({collection:"_globals_social-settings",where:{},draft:e?.draft??!1});return je(t)}catch{return []}}g();function We(s){return s?{storeName:s.storeName,storeEmail:s.storeEmail,storePhone:s.storePhone,address:s.address,currency:s.currency,tax:s.tax,shipping:s.shipping,orders:s.orders}:{}}async function po(s,e){try{let t=await s.findOne({collection:"_globals_store-settings",where:{},draft:e?.draft??!1});return We(t)}catch{return {}}}g();function qe(s){return s?{testMode:s.testMode,provider:s.provider,stripe:s.stripe,paypal:s.paypal,square:s.square,methods:s.methods,bankTransfer:s.bankTransfer}:{}}async function go(s,e){try{let t=await s.findOne({collection:"_globals_payment-settings",where:{},draft:e?.draft??!1});return qe(t)}catch{return {}}}g();g();g();g();g();function
|
|
44
|
+
`),o}g();var co={facebook:{label:"Facebook"},twitter:{label:"Twitter / X"},instagram:{label:"Instagram"},linkedin:{label:"LinkedIn"},youtube:{label:"YouTube"},tiktok:{label:"TikTok"},pinterest:{label:"Pinterest"},discord:{label:"Discord"},twitch:{label:"Twitch"},github:{label:"GitHub"},mastodon:{label:"Mastodon"}},lo=["facebook","twitter","instagram","linkedin","youtube","tiktok","pinterest","discord","twitch","github","mastodon"];function je(s){if(!s)return [];let e=s.showAll===true,t=[];for(let r of lo){let o=s[r];if(!o||["tiktok","pinterest","discord","twitch","github","mastodon"].includes(r)&&!e)continue;let i=co[r];t.push({platform:r,url:o,label:i?.label||r});}return t}async function uo(s,e){try{let t=await s.findOne({collection:"_globals_social-settings",where:{},draft:e?.draft??!1});return je(t)}catch{return []}}g();function We(s){return s?{storeName:s.storeName,storeEmail:s.storeEmail,storePhone:s.storePhone,address:s.address,currency:s.currency,tax:s.tax,shipping:s.shipping,orders:s.orders}:{}}async function po(s,e){try{let t=await s.findOne({collection:"_globals_store-settings",where:{},draft:e?.draft??!1});return We(t)}catch{return {}}}g();function qe(s){return s?{testMode:s.testMode,provider:s.provider,stripe:s.stripe,paypal:s.paypal,square:s.square,methods:s.methods,bankTransfer:s.bankTransfer}:{}}async function go(s,e){try{let t=await s.findOne({collection:"_globals_payment-settings",where:{},draft:e?.draft??!1});return qe(t)}catch{return {}}}g();g();g();g();g();function T(s){return new Promise((e,t)=>{s.oncomplete=s.onsuccess=()=>e(s.result),s.onabort=s.onerror=()=>t(s.error);})}function Y(s,e){let t,r=()=>{if(t)return t;let o=indexedDB.open(s);return o.onupgradeneeded=()=>o.result.createObjectStore(e),t=T(o),t.then(n=>{n.onclose=()=>t=void 0;},()=>{t=void 0;}),t};return (o,n)=>r().then(i=>n(i.transaction(e,o).objectStore(e)))}var Q;function U(){return Q||(Q=Y("keyval-store","keyval")),Q}function z(s,e=U()){return e("readonly",t=>T(t.get(s)))}function J(s,e,t=U()){return t("readwrite",r=>(r.put(e,s),T(r.transaction)))}function Ge(s,e=U()){return e("readwrite",t=>(t.delete(s),T(t.transaction)))}function Qe(s=U()){return s("readwrite",e=>(e.clear(),T(e.transaction)))}function mo(s,e){return s.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue());},T(s.transaction)}function Ye(s=U()){return s("readonly",e=>{if(e.getAllKeys)return T(e.getAllKeys());let t=[];return mo(e,r=>t.push(r.key)).then(()=>t)})}var fo="idb-keyval",Je=(s={})=>{let e=s.base&&s.base.length>0?`${s.base}:`:"",t=o=>e+o,r;return s.dbName&&s.storeName&&(r=Y(s.dbName,s.storeName)),{name:fo,options:s,async hasItem(o){return await z(t(o),r)!==void 0},async getItem(o){return await z(t(o),r)??null},async getItemRaw(o){return await z(t(o),r)??null},setItem(o,n){return J(t(o),n,r)},setItemRaw(o,n){return J(t(o),n,r)},removeItem(o){return Ge(t(o),r)},getKeys(){return Ye(r)},clear(){return Qe(r)}}};async function X(s={}){let{namespace:e="kyro",ttl:t}=s,r=f$1({driver:Je({dbName:"kyro-cms",storeName:e})}),o=e?`${e}:`:"";return {storage:{getItem:async i=>{let c=`${o}${i}`,l=await r.getItem(c);if(l==null)return null;try{let p=JSON.parse(l);return p.expiry&&Date.now()>p.expiry?(await r.removeItem(c),null):p.value}catch{return l}},setItem:async(i,c)=>{let l=`${o}${i}`,p=JSON.stringify(t?{value:c,expiry:Date.now()+t}:{value:c});await r.setItem(l,p);},removeItem:async i=>{await r.removeItem(`${o}${i}`);}},cleanup:async()=>{await r.dispose?.();}}}g();g();function Z(s){let e=s||process.env.APP_SECRET||process.env.AUTH_SECRET||"development-secret-key";return ee.createHash("sha256").update(e).digest("hex")}function ho(s,e){let t=ee.randomBytes(16),r=ee.createCipheriv("aes-256-gcm",Buffer.from(e,"hex").subarray(0,32),t),o=r.update(s,"utf8","hex");o+=r.final("hex");let n=r.getAuthTag().toString("hex");return `${t.toString("hex")}:${n}:${o}`}function Ao(s,e){let[t,r,o]=s.split(":"),n=Buffer.from(t,"hex"),i=Buffer.from(r,"hex"),c=ee.createDecipheriv("aes-256-gcm",Buffer.from(e,"hex").subarray(0,32),n);c.setAuthTag(i);let l=c.update(o,"hex","utf8");return l+=c.final("utf8"),l}async function te(s={}){let{namespace:e="kyro",ttl:t,encryption:r=true,secret:o,basePath:n}=s,i=n?Xe.join(n,".astro","kyro.json"):Xe.join(process.cwd(),".astro","kyro.json"),c=f$1({driver:a$5({base:i})}),l=r?Z(o):null,p=e?`${e}:`:"";return {storage:{getItem:async g=>{let m=`${p}${g}`,f=await c.getItem(m);if(f==null)return null;try{let w=l?Ao(f,l):f,h=JSON.parse(w);return h.expiry&&Date.now()>h.expiry?(await c.removeItem(m),null):h.value}catch{return f}},setItem:async(g,m)=>{let f=`${p}${g}`,w=JSON.stringify(t?{value:m,expiry:Date.now()+t}:{value:m});await c.setItem(f,l?ho(w,l):w);},removeItem:async g=>{await c.removeItem(`${p}${g}`);}},cleanup:async()=>{await c.dispose?.();}}}async function re(s){let{environment:e,adapter:t,connectionString:r,encryption:o}=s,n=process.env.APP_SECRET||process.env.AUTH_SECRET,i={enabled:o?.enabled??true,algorithm:o?.algorithm};return e==="browser"?X({namespace:"kyro"}):te({namespace:"kyro",encryption:i.enabled,secret:n})}async function Ze(s){let e={...s,encryption:{enabled:true,algorithm:s.encryption?.algorithm}};return re(e)}g();function wo(s){return {name:"kyro-loader",load:async e=>{let{store:t,logger:r,parseData:o}=e;r.info(`Loading Kyro CMS collection: "${s.collection}"`);try{let n=[];t.clear();for(let i of n){let c=String(i.id||i._id),l=await o({id:c,data:i});t.set({id:c,data:l,digest:JSON.stringify(l)});}r.info(`Successfully synced ${n.length} entries for "${s.collection}" into Astro store.`);}catch(n){r.error(`Failed to load Kyro collection "${s.collection}": ${n.message}`);}},schema:f.object({id:f.string(),createdAt:f.string().optional(),updatedAt:f.string().optional()}).passthrough()}}g();function bo(s){return {input:s.schema||f.object({}).passthrough(),handler:async(t,r)=>{try{return {success:!0,collection:s.collection,action:s.action,data:t,timestamp:new Date().toISOString()}}catch(o){return {success:false,error:o.message||"CMS Action Execution Failed"}}}}}g();function So(s={}){let e=s.protectedRoutes||[],t=s.loginPath||"/admin/login",r=s.cookieName||"kyro_session";return async(o,n)=>{let{request:i,cookies:c,redirect:l,locals:p}=o,g=new URL(i.url),m=c?.get?.(r)?.value||i.headers.get("authorization")?.replace("Bearer ",""),f=null;return m&&(f={id:"user_1",email:"admin@kyro-cms.com",role:"admin"}),p.kyroUser=f,e.some(h=>new RegExp("^"+h.replace(/\*/g,".*")+"$").test(g.pathname))&&!f?l(`${t}?redirect=${encodeURIComponent(g.pathname)}`):n()}}g();function Po(s){let e=s?.collections||[],t=`// Auto-generated by Kyro CMS
|
|
45
45
|
declare module 'kyro:collections' {
|
|
46
46
|
export interface KyroCollections {
|
|
47
47
|
`;for(let r of e){let o=r.name||r.slug;t+=` '${o}': Record<string, any>;
|
|
48
48
|
`;}return t+=` }
|
|
49
49
|
}
|
|
50
|
-
`,t}g();function
|
|
51
|
-
export{R as AccountLockout,
|
|
50
|
+
`,t}g();function xo(s={}){return {APP_SECRET:{context:"server",access:"secret",type:"string",optional:false},DATABASE_URL:{context:"server",access:"secret",type:"string",optional:!s.requireDatabase},PUBLIC_KYRO_URL:{context:"client",access:"public",type:"string",optional:true,default:"http://localhost:4321"}}}
|
|
51
|
+
export{R as AccountLockout,B as Auth,I as InMemoryAccountLockout,D as InMemoryAuthAdapter,E as NeonAdapter,v as RateLimiter,O as TursoAdapter,$ as VersionManager,$e as authConfig,Xr as createAuth,G as createAuthConfig,Ze as createAuthStorage,Fe as createNeonAdapter,re as createStorage,Ke as createTursoAdapter,Zr as createVersionManager,ze as defineConfig,no as defineKyroConfig,ao as generateAnalyticsTags,Po as generateKyroAstroTypes,io as generateSeoTags,N as getDefaultDraftPublishConfig,go as getPaymentConfig,qe as getPaymentConfigFromSettings,uo as getSocialLinks,je as getSocialLinksFromSettings,po as getStoreConfig,We as getStoreConfigFromSettings,ro as isArchived,to as isDraft,eo as isPublished,bo as kyroAction,So as kyroAuthMiddleware,xo as kyroEnvSchema,wo as kyroLoader,$r as runFieldHooks,He as runHooks};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-
|
|
1
|
+
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-T4JJVUGT.js';import'./chunk-SLMIYECU.js';import'./chunk-VVVCCB6R.js';import'./chunk-TBHNE4VV.js';import'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkHKYBQYAJ_cjs=require('./chunk-HKYBQYAJ.cjs');require('./chunk-VQ53TFYA.cjs'),require('./chunk-ZOVH6QT5.cjs'),require('./chunk-7WMMKGEO.cjs'),require('./chunk-BUNLC3II.cjs');Object.defineProperty(exports,"LocalAdapter",{enumerable:true,get:function(){return chunkHKYBQYAJ_cjs.a}});Object.defineProperty(exports,"createLocalAdapter",{enumerable:true,get:function(){return chunkHKYBQYAJ_cjs.b}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as PostgresAuthAdapter}from'./chunk-ZWDBPEXL.js';import'./chunk-47CXBWMA.js';import'./chunk-EML5FDUU.js';import'./chunk-
|
|
1
|
+
export{a as PostgresAuthAdapter}from'./chunk-ZWDBPEXL.js';import'./chunk-47CXBWMA.js';import'./chunk-EML5FDUU.js';import'./chunk-HRAY65XH.js';import'./chunk-FLMUMPDE.js';import'./chunk-3NSZZCOJ.js';import'./chunk-7NH7H3WA.js';import'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var chunkXBQ6HV3T_cjs=require('./chunk-XBQ6HV3T.cjs');require('./chunk-7JWQ2PZP.cjs'),require('./chunk-NGNJSUGL.cjs'),require('./chunk-
|
|
1
|
+
'use strict';var chunkXBQ6HV3T_cjs=require('./chunk-XBQ6HV3T.cjs');require('./chunk-7JWQ2PZP.cjs'),require('./chunk-NGNJSUGL.cjs'),require('./chunk-BCEE4NBZ.cjs'),require('./chunk-BAVN7VDR.cjs'),require('./chunk-VRZC4TTF.cjs'),require('./chunk-HTYVI2HK.cjs'),require('./chunk-BUNLC3II.cjs');Object.defineProperty(exports,"PostgresAuthAdapter",{enumerable:true,get:function(){return chunkXBQ6HV3T_cjs.a}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkSOCBJPYB_cjs=require('./chunk-SOCBJPYB.cjs');require('./chunk-GNOSG3PK.cjs'),require('./chunk-BCEE4NBZ.cjs'),require('./chunk-LY7N3UHH.cjs'),require('./chunk-BAVN7VDR.cjs'),require('./chunk-VRZC4TTF.cjs'),require('./chunk-BUNLC3II.cjs');Object.defineProperty(exports,"PostgresJsDatabase",{enumerable:true,get:function(){return chunkSOCBJPYB_cjs.e}});Object.defineProperty(exports,"PostgresJsPreparedQuery",{enumerable:true,get:function(){return chunkSOCBJPYB_cjs.b}});Object.defineProperty(exports,"PostgresJsSession",{enumerable:true,get:function(){return chunkSOCBJPYB_cjs.c}});Object.defineProperty(exports,"PostgresJsTransaction",{enumerable:true,get:function(){return chunkSOCBJPYB_cjs.d}});Object.defineProperty(exports,"drizzle",{enumerable:true,get:function(){return chunkSOCBJPYB_cjs.f}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{e as PostgresJsDatabase,b as PostgresJsPreparedQuery,c as PostgresJsSession,d as PostgresJsTransaction,f as drizzle}from'./chunk-
|
|
1
|
+
export{e as PostgresJsDatabase,b as PostgresJsPreparedQuery,c as PostgresJsSession,d as PostgresJsTransaction,f as drizzle}from'./chunk-637PTUHF.js';import'./chunk-N5POANYV.js';import'./chunk-HRAY65XH.js';import'./chunk-2HA6EKXX.js';import'./chunk-FLMUMPDE.js';import'./chunk-3NSZZCOJ.js';import'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
package/dist/rest/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk6QWX3DEB_cjs=require('../chunk-6QWX3DEB.cjs');require('../chunk-XTTGHN3D.cjs'),require('../chunk-HPYH7GTS.cjs'),require('../chunk-OPTVCCQQ.cjs'),require('../chunk-O4YE57OS.cjs'),require('../chunk-MCIZG4A3.cjs'),require('../chunk-35PGCW3S.cjs'),require('../chunk-UNYXWPLZ.cjs'),require('../chunk-PITMDQYN.cjs'),require('../chunk-GIS6X43A.cjs'),require('../chunk-LEBM6ZSZ.cjs'),require('../chunk-GNEVCEJU.cjs'),require('../chunk-ZO3YB5DK.cjs'),require('../chunk-3VXEK5ZW.cjs'),require('../chunk-EZIDQBXI.cjs'),require('../chunk-LQ3YZTPU.cjs'),require('../chunk-MVX2PYJJ.cjs'),require('../chunk-FSL3NLRT.cjs'),require('../chunk-ZHA446FA.cjs'),require('../chunk-JU3UAZRY.cjs'),require('../chunk-7ACHOBWY.cjs'),require('../chunk-XBQ6HV3T.cjs'),require('../chunk-7JWQ2PZP.cjs'),require('../chunk-NGNJSUGL.cjs'),require('../chunk-SOCBJPYB.cjs'),require('../chunk-GNOSG3PK.cjs'),require('../chunk-BCEE4NBZ.cjs'),require('../chunk-LY7N3UHH.cjs'),require('../chunk-BAVN7VDR.cjs'),require('../chunk-VRZC4TTF.cjs'),require('../chunk-7DUKWHRN.cjs'),require('../chunk-VQ53TFYA.cjs'),require('../chunk-F4ITQ6XQ.cjs'),require('../chunk-HTYVI2HK.cjs'),require('../chunk-ZOVH6QT5.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"createKyroApp",{enumerable:true,get:function(){return chunk6QWX3DEB_cjs.ib}});Object.defineProperty(exports,"createRESTAPI",{enumerable:true,get:function(){return chunk6QWX3DEB_cjs.jb}});
|
package/dist/rest/index.d.cts
CHANGED
|
@@ -5,7 +5,7 @@ import { j as createWebhookService } from '../WebhookService-DgIx21X-.cjs';
|
|
|
5
5
|
import '../types-euTszc-1.cjs';
|
|
6
6
|
import 'zod';
|
|
7
7
|
|
|
8
|
-
interface
|
|
8
|
+
interface KyroAppOptions {
|
|
9
9
|
registry: Registry;
|
|
10
10
|
db: BaseAdapter;
|
|
11
11
|
authSecret?: string;
|
|
@@ -40,7 +40,7 @@ interface HonoAppOptions {
|
|
|
40
40
|
};
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
|
-
declare function
|
|
43
|
+
declare function createKyroApp(options: KyroAppOptions): Promise<Hono>;
|
|
44
44
|
declare function createRESTAPI(registry: Registry, db: BaseAdapter, options?: {
|
|
45
45
|
authSecret?: string;
|
|
46
46
|
user?: User;
|
|
@@ -53,4 +53,4 @@ declare function createRESTAPI(registry: Registry, db: BaseAdapter, options?: {
|
|
|
53
53
|
webhookService?: ReturnType<typeof createWebhookService>;
|
|
54
54
|
}): Promise<Hono>;
|
|
55
55
|
|
|
56
|
-
export { type
|
|
56
|
+
export { type KyroAppOptions, createKyroApp, createRESTAPI };
|
package/dist/rest/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { j as createWebhookService } from '../WebhookService-CZf_na-J.js';
|
|
|
5
5
|
import '../types-euTszc-1.js';
|
|
6
6
|
import 'zod';
|
|
7
7
|
|
|
8
|
-
interface
|
|
8
|
+
interface KyroAppOptions {
|
|
9
9
|
registry: Registry;
|
|
10
10
|
db: BaseAdapter;
|
|
11
11
|
authSecret?: string;
|
|
@@ -40,7 +40,7 @@ interface HonoAppOptions {
|
|
|
40
40
|
};
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
|
-
declare function
|
|
43
|
+
declare function createKyroApp(options: KyroAppOptions): Promise<Hono>;
|
|
44
44
|
declare function createRESTAPI(registry: Registry, db: BaseAdapter, options?: {
|
|
45
45
|
authSecret?: string;
|
|
46
46
|
user?: User;
|
|
@@ -53,4 +53,4 @@ declare function createRESTAPI(registry: Registry, db: BaseAdapter, options?: {
|
|
|
53
53
|
webhookService?: ReturnType<typeof createWebhookService>;
|
|
54
54
|
}): Promise<Hono>;
|
|
55
55
|
|
|
56
|
-
export { type
|
|
56
|
+
export { type KyroAppOptions, createKyroApp, createRESTAPI };
|
package/dist/rest/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{ib as
|
|
1
|
+
export{ib as createKyroApp,jb as createRESTAPI}from'../chunk-RILJCH6H.js';import'../chunk-KWGB3YNI.js';import'../chunk-OLRCZ6E3.js';import'../chunk-N6MNQIQU.js';import'../chunk-6TPICJ2L.js';import'../chunk-YENNL5HG.js';import'../chunk-W45TLOOT.js';import'../chunk-IKGVPXMK.js';import'../chunk-YUUXFD73.js';import'../chunk-LVBHOZZF.js';import'../chunk-OBYAIJVU.js';import'../chunk-JRUQ5ABB.js';import'../chunk-CIVA6SKW.js';import'../chunk-WPM6LFCY.js';import'../chunk-U6KFONKM.js';import'../chunk-TYQYKKWJ.js';import'../chunk-L2QXP26Q.js';import'../chunk-AWQGDMOE.js';import'../chunk-GQGFNTDZ.js';import'../chunk-VJODUKKM.js';import'../chunk-JV4HJBXW.js';import'../chunk-ZWDBPEXL.js';import'../chunk-47CXBWMA.js';import'../chunk-EML5FDUU.js';import'../chunk-637PTUHF.js';import'../chunk-N5POANYV.js';import'../chunk-HRAY65XH.js';import'../chunk-2HA6EKXX.js';import'../chunk-FLMUMPDE.js';import'../chunk-3NSZZCOJ.js';import'../chunk-5ZEYOFAK.js';import'../chunk-SLMIYECU.js';import'../chunk-P6JITOFF.js';import'../chunk-7NH7H3WA.js';import'../chunk-VVVCCB6R.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as SQLiteAuthAdapter}from'./chunk-
|
|
1
|
+
export{a as SQLiteAuthAdapter}from'./chunk-N6MNQIQU.js';import'./chunk-7NH7H3WA.js';import'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkOPTVCCQQ_cjs=require('./chunk-OPTVCCQQ.cjs');require('./chunk-HTYVI2HK.cjs'),require('./chunk-BUNLC3II.cjs');Object.defineProperty(exports,"SQLiteAuthAdapter",{enumerable:true,get:function(){return chunkOPTVCCQQ_cjs.a}});
|
package/dist/trpc/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkFP5UK272_cjs=require('../chunk-FP5UK272.cjs');require('../chunk-FSL3NLRT.cjs'),require('../chunk-ZHA446FA.cjs'),require('../chunk-ZOVH6QT5.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"createContext",{enumerable:true,get:function(){return chunkFP5UK272_cjs.a}});Object.defineProperty(exports,"createCountProcedure",{enumerable:true,get:function(){return chunkFP5UK272_cjs.g}});Object.defineProperty(exports,"createCreateProcedure",{enumerable:true,get:function(){return chunkFP5UK272_cjs.d}});Object.defineProperty(exports,"createDeleteProcedure",{enumerable:true,get:function(){return chunkFP5UK272_cjs.f}});Object.defineProperty(exports,"createDynamicRouter",{enumerable:true,get:function(){return chunkFP5UK272_cjs.h}});Object.defineProperty(exports,"createFindByIDProcedure",{enumerable:true,get:function(){return chunkFP5UK272_cjs.c}});Object.defineProperty(exports,"createFindProcedure",{enumerable:true,get:function(){return chunkFP5UK272_cjs.b}});Object.defineProperty(exports,"createKyroServer",{enumerable:true,get:function(){return chunkFP5UK272_cjs.i}});Object.defineProperty(exports,"createUpdateProcedure",{enumerable:true,get:function(){return chunkFP5UK272_cjs.e}});
|
package/dist/trpc/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'../chunk-
|
|
1
|
+
export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'../chunk-4ZWLNGLS.js';import'../chunk-AWQGDMOE.js';import'../chunk-GQGFNTDZ.js';import'../chunk-VVVCCB6R.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kyro-cms/core",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.61",
|
|
4
4
|
"description": "Astro-native headless CMS with multi-database adapters, multi-protocol APIs, and multi-vendor support",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=22"
|
|
@@ -191,7 +191,7 @@
|
|
|
191
191
|
"ws": "^8.18.0",
|
|
192
192
|
"zod": "^3.24.0",
|
|
193
193
|
"zod-to-json-schema": "^3.25.2",
|
|
194
|
-
"@kyro-cms/ai": "0.12.
|
|
194
|
+
"@kyro-cms/ai": "0.12.61"
|
|
195
195
|
},
|
|
196
196
|
"devDependencies": {
|
|
197
197
|
"@tailwindcss/vite": "^4.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkECFZEY5B_cjs=require('./chunk-ECFZEY5B.cjs');require('./chunk-VKXWJOWI.cjs'),require('./chunk-HPYH7GTS.cjs'),require('./chunk-BHR7OAU4.cjs'),require('./chunk-VRZC4TTF.cjs'),require('./chunk-HTYVI2HK.cjs'),require('./chunk-BUNLC3II.cjs');Object.defineProperty(exports,"autoBootstrap",{enumerable:true,get:function(){return chunkECFZEY5B_cjs.e}});Object.defineProperty(exports,"bootstrapAdmin",{enumerable:true,get:function(){return chunkECFZEY5B_cjs.a}});Object.defineProperty(exports,"bootstrapWithRetry",{enumerable:true,get:function(){return chunkECFZEY5B_cjs.f}});Object.defineProperty(exports,"buildBootstrapConfig",{enumerable:true,get:function(){return chunkECFZEY5B_cjs.c}});Object.defineProperty(exports,"checkBootstrapRequired",{enumerable:true,get:function(){return chunkECFZEY5B_cjs.b}});Object.defineProperty(exports,"getBootstrapFromEnv",{enumerable:true,get:function(){return chunkECFZEY5B_cjs.d}});
|
package/dist/chunk-5LPNEYK5.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');chunkBUNLC3II_cjs.h();function a(){return {name:"seo",type:"group",label:"SEO Settings",fields:[{name:"metaTitle",type:"text",label:"Meta Title",admin:{description:"The title used for search engines (recommended < 60 chars).",autoGenerate:"title"}},{name:"metaDescription",type:"textarea",label:"Meta Description",admin:{description:"A brief summary for search engines (recommended < 160 chars).",autoGenerate:"content"}},{name:"keywords",type:"text",label:"Keywords",admin:{description:"Comma-separated list of keywords for this page."}},{name:"ogImage",type:"upload",label:"OpenGraph Image",relationTo:"media",admin:{description:"The image shown when the post is shared on social media (Facebook, LinkedIn)."}},{name:"twitter",type:"group",label:"Twitter Card",fields:[{name:"title",type:"text",label:"Twitter Title"},{name:"description",type:"textarea",label:"Twitter Description"},{name:"image",type:"upload",label:"Twitter Image",relationTo:"media"}]},{name:"advanced",type:"group",label:"Advanced Search Settings",fields:[{name:"noindex",type:"checkbox",label:"Hide from search engines (noindex)",defaultValue:false},{name:"nofollow",type:"checkbox",label:"Do not follow links (nofollow)",defaultValue:false},{name:"canonicalUrl",type:"text",label:"Canonical URL Override",admin:{description:"Leave empty to use the default canonical URL."}},{name:"structuredData",type:"code",label:"JSON-LD Structured Data",admin:{description:"Custom JSON-LD schema for this specific page."}}]}]}}exports.a=a;
|
package/dist/chunk-72VOOMJI.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
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};
|