@kyro-cms/core 0.12.34 → 0.12.36
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-BGO2NFKB.cjs +1 -0
- package/dist/{bootstrap-6G6HI26Z.js → bootstrap-VVIT6YBP.js} +1 -1
- package/dist/chunk-7MBZYLME.js +1 -0
- package/dist/{chunk-II4F6XUG.js → chunk-FVRNWRSG.js} +2 -2
- package/dist/{chunk-TMKROUQA.cjs → chunk-KKIBNWRL.cjs} +1 -1
- package/dist/{chunk-7R5IPQ5F.js → chunk-LCXPMPBU.js} +1 -1
- package/dist/chunk-QBJT7XLN.cjs +1 -0
- package/dist/{chunk-C2AS7MZJ.cjs → chunk-WNVWRRWE.cjs} +2 -2
- package/dist/cli/index.cjs +38 -44
- package/dist/cli/index.js +38 -44
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/integration.cjs +1 -1
- package/dist/integration.js +1 -1
- package/package.json +4 -3
- package/dist/bootstrap-ETJ6QNGR.cjs +0 -1
- package/dist/chunk-4XZABBHF.cjs +0 -1
- package/dist/chunk-6MSPBK3W.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{a as RedisAuthAdapter}from'./chunk-QOCHBPMK.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-SZNM3F5V.js';export{a as kyro}from'./chunk-II4F6XUG.js';export{s as AnalyticsPlugin,t as CommentsPlugin,a as ConfigValidationError,y as Kyro,p as KyroPlugin,A as LocalAdapter,q as PluginManager,l as Registry,u as ReviewsPlugin,r as SEOPlugin,v as WishlistPlugin,x as applyCollectionOverrides,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,z as createKyro,B as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,w as presetPlugins,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-DZMIMB5W.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.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-UHFDH3PG.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-INB4LNA6.js';import'./chunk-5SEHX7ON.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-LHW4R367.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-PP7W5UKL.js';import {l,n,m,p,q as q$1}from'./chunk-4DJYAD4L.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,t as MediaService,o as createAuditContext,u as createHonoApp,e as createLocalStorage,v as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,s as isEdgeRuntime,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-4DJYAD4L.js';import {k as k$1,l as l$1}from'./chunk-6J27P5D6.js';export{j as ConfigService,k as EmailTransport,l as PasswordPolicy,i as getEmailTemplates,g as renderAccountLocked,a as renderBaseLayout,f as renderMagicLink,e as renderPasswordChanged,c as renderResetPassword,h as renderUserInvite,b as renderVerifyEmail,d as renderWelcome}from'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import {a as a$2}from'./chunk-IKOXCJYO.js';export{a as SQLiteAuthAdapter}from'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-FVZ5RFLO.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-5KSRMBEO.js';import {a as a$3}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-VGQ4VUG6.js';import {a as a$1}from'./chunk-6ROHVUXF.js';export{a as MongoDBAuthAdapter}from'./chunk-6ROHVUXF.js';import {a as a$4}from'./chunk-5KOQYQEE.js';export{a as AbstractBaseAdapter}from'./chunk-5KOQYQEE.js';import {a}from'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import W,{randomBytes}from'crypto';import {readFileSync}from'fs';import Me,{join,resolve}from'path';import {z as z$1}from'zod';export{z}from'zod';import {createStorage}from'unstorage';import Jr from'unstorage/drivers/indexedb';import eo from'unstorage/drivers/fs';async function Re(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 Cr(s,e){return Re(s,e)}var R=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 ve(s){return new R(s)}var v=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(c=>({type:"text",value:String(c)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let a=i.cols.map(c=>c.name);return i.rows.map(c=>{let l={};return a.forEach((d,u)=>{l[d]=c[u]?.value??null;}),l})}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 De(s){return new v(s)}var Rr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},x=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...Rr,...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),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),a.expire(r,Math.ceil(n/1e3)+3600),await a.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,a)=>(a+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};}};var vr={"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}},P=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...vr,...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,a=this.redis.pipeline();a.zremrangebyscore(o,0,i),a.zcard(o),a.zadd(o,n,`${n}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let l=(await a.exec())?.[1]?.[1]||0;if(l>=r.max){let d=await this.redis.zrange(o,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:r.max-l-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(),a=i-o.window,c=this.redis.pipeline();c.zremrangebyscore(n,0,a),c.zcard(n),c.zadd(n,i,`${i}:${Math.random()}`),c.expire(n,Math.ceil(o.window/1e3)+1);let d=(await c.exec())?.[1]?.[1]||0;if(d>=o.max){let u=await this.redis.zrange(n,0,0,"WITHSCORES"),p=u.length>1?parseInt(u[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:p,retryAfter:Math.ceil((p-i)/1e3)}}return {allowed:true,remaining:o.max-d-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 a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:n+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var T=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')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).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,a={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,a),this.refreshTokens.set(n,r),a}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')).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}};var k=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 a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:n,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function g(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Ie(){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 Lr(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:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=h("DATABASE_URL","");if(o){let n,i;try{n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}catch{a(["postgres","drizzle-orm"]),n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}let a$1=i.default(o,{onnotice:()=>{}}),c=n(a$1);return new a$3({db:c})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=h("MONGODB_URI","");if(o){let n;try{n=(await import('mongodb')).MongoClient;}catch{a(["mongodb"]),n=(await import('mongodb')).MongoClient;}let i=new n(o);await i.connect();let c=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",l=i.db(c);return new a$1({db:l})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new T}}async function $(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:u}=await import('./redis-adapter-NN3H4GRX.js'),p=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),m=new u({url:p,tls:y});await m.connect?.(),r=m;}else {let u=s||Ie();r=await Lr(u),r.connect&&await r.connect();}let o=e?await k$1.fromConfig(e).catch(()=>null)||k$1.fromEnv()||void 0:k$1.fromEnv()||void 0,n$1=new l$1({minLength:g("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:g("PASSWORD_PREVENT_REUSE",5),maxLength:g("PASSWORD_MAX_LENGTH",128)}),i,a,c;if(t){let p=r.redis;i=new x(p,{maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new P(p,{"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c=new n(p,g("AUDIT_LOG_RETENTION_DAYS",30));}else i=new k({maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c=A("AUDIT_LOG_ENABLED",true)?new p(g("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let l=new q$1({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),d=t?"distributed":s||Ie();return {authAdapter:r,databaseType:d,email:o,passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c,routes:l}}var Ee=$().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Er=12,Or="24h",Ur="7d",U=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Or,refreshExpiresIn:t.refreshExpiresIn??Ur,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Er};}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');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'),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');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 Vr(s,e){return new U(s,e)}function V(){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={...V(),...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 _r(s,e){return new _(s,e)}function Mr(s){return s==="published"}function Hr(s){return s==="draft"}function Fr(s){return s==="archived"}function Nr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Br(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Oe(s){return {collections:Nr(s.collections),globals:Br(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 Kr=Oe;function $r(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:n,url:i}=s;if(!e)return "";let a=e.siteName||"",c=r||t?.defaultTitle||a,l=t?.titleTemplate,d=t?.separator||" | ",u=t?.siteNameInTitle!==false,p=l?l.replace(/\{\{title\}\}/g,c).replace(/\{\{siteName\}\}/g,u?a:"").replace(/\{\{separator\}\}/g,d).replace(/\s+/g," ").trim():c,y=o||t?.defaultDescription||e.siteDescription||"",m=n||e.siteOgImage?.url||"",D=i||e.siteUrl||"",f=`
|
|
1
|
+
export{a as RedisAuthAdapter}from'./chunk-QOCHBPMK.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-SZNM3F5V.js';export{a as kyro}from'./chunk-FVRNWRSG.js';export{s as AnalyticsPlugin,t as CommentsPlugin,a as ConfigValidationError,y as Kyro,p as KyroPlugin,A as LocalAdapter,q as PluginManager,l as Registry,u as ReviewsPlugin,r as SEOPlugin,v as WishlistPlugin,x as applyCollectionOverrides,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,z as createKyro,B as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,w as presetPlugins,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-DZMIMB5W.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-7MBZYLME.js';import'./chunk-NZ35PV5R.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-UHFDH3PG.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-INB4LNA6.js';import'./chunk-5SEHX7ON.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-LHW4R367.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-PP7W5UKL.js';import {l,n,m,p,q as q$1}from'./chunk-4DJYAD4L.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,t as MediaService,o as createAuditContext,u as createHonoApp,e as createLocalStorage,v as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,s as isEdgeRuntime,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-4DJYAD4L.js';import {k as k$1,l as l$1}from'./chunk-6J27P5D6.js';export{j as ConfigService,k as EmailTransport,l as PasswordPolicy,i as getEmailTemplates,g as renderAccountLocked,a as renderBaseLayout,f as renderMagicLink,e as renderPasswordChanged,c as renderResetPassword,h as renderUserInvite,b as renderVerifyEmail,d as renderWelcome}from'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import {a as a$2}from'./chunk-IKOXCJYO.js';export{a as SQLiteAuthAdapter}from'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-FVZ5RFLO.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-5KSRMBEO.js';import {a as a$3}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-VGQ4VUG6.js';import {a as a$1}from'./chunk-6ROHVUXF.js';export{a as MongoDBAuthAdapter}from'./chunk-6ROHVUXF.js';import {a as a$4}from'./chunk-5KOQYQEE.js';export{a as AbstractBaseAdapter}from'./chunk-5KOQYQEE.js';import {a}from'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import W,{randomBytes}from'crypto';import {readFileSync}from'fs';import Me,{join,resolve}from'path';import {z as z$1}from'zod';export{z}from'zod';import {createStorage}from'unstorage';import Jr from'unstorage/drivers/indexedb';import eo from'unstorage/drivers/fs';async function Re(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 Cr(s,e){return Re(s,e)}var R=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 ve(s){return new R(s)}var v=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(c=>({type:"text",value:String(c)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let a=i.cols.map(c=>c.name);return i.rows.map(c=>{let l={};return a.forEach((d,u)=>{l[d]=c[u]?.value??null;}),l})}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 De(s){return new v(s)}var Rr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},x=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...Rr,...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),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),a.expire(r,Math.ceil(n/1e3)+3600),await a.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,a)=>(a+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};}};var vr={"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}},P=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...vr,...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,a=this.redis.pipeline();a.zremrangebyscore(o,0,i),a.zcard(o),a.zadd(o,n,`${n}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let l=(await a.exec())?.[1]?.[1]||0;if(l>=r.max){let d=await this.redis.zrange(o,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:r.max-l-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(),a=i-o.window,c=this.redis.pipeline();c.zremrangebyscore(n,0,a),c.zcard(n),c.zadd(n,i,`${i}:${Math.random()}`),c.expire(n,Math.ceil(o.window/1e3)+1);let d=(await c.exec())?.[1]?.[1]||0;if(d>=o.max){let u=await this.redis.zrange(n,0,0,"WITHSCORES"),p=u.length>1?parseInt(u[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:p,retryAfter:Math.ceil((p-i)/1e3)}}return {allowed:true,remaining:o.max-d-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 a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:n+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var T=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')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).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,a={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,a),this.refreshTokens.set(n,r),a}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')).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}};var k=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 a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:n,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function g(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Ie(){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 Lr(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:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=h("DATABASE_URL","");if(o){let n,i;try{n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}catch{a(["postgres","drizzle-orm"]),n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}let a$1=i.default(o,{onnotice:()=>{}}),c=n(a$1);return new a$3({db:c})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=h("MONGODB_URI","");if(o){let n;try{n=(await import('mongodb')).MongoClient;}catch{a(["mongodb"]),n=(await import('mongodb')).MongoClient;}let i=new n(o);await i.connect();let c=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",l=i.db(c);return new a$1({db:l})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new T}}async function $(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:u}=await import('./redis-adapter-NN3H4GRX.js'),p=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),m=new u({url:p,tls:y});await m.connect?.(),r=m;}else {let u=s||Ie();r=await Lr(u),r.connect&&await r.connect();}let o=e?await k$1.fromConfig(e).catch(()=>null)||k$1.fromEnv()||void 0:k$1.fromEnv()||void 0,n$1=new l$1({minLength:g("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:g("PASSWORD_PREVENT_REUSE",5),maxLength:g("PASSWORD_MAX_LENGTH",128)}),i,a,c;if(t){let p=r.redis;i=new x(p,{maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new P(p,{"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c=new n(p,g("AUDIT_LOG_RETENTION_DAYS",30));}else i=new k({maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c=A("AUDIT_LOG_ENABLED",true)?new p(g("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let l=new q$1({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),d=t?"distributed":s||Ie();return {authAdapter:r,databaseType:d,email:o,passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c,routes:l}}var Ee=$().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Er=12,Or="24h",Ur="7d",U=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Or,refreshExpiresIn:t.refreshExpiresIn??Ur,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Er};}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');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'),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');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 Vr(s,e){return new U(s,e)}function V(){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={...V(),...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 _r(s,e){return new _(s,e)}function Mr(s){return s==="published"}function Hr(s){return s==="draft"}function Fr(s){return s==="archived"}function Nr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Br(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Oe(s){return {collections:Nr(s.collections),globals:Br(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 Kr=Oe;function $r(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:n,url:i}=s;if(!e)return "";let a=e.siteName||"",c=r||t?.defaultTitle||a,l=t?.titleTemplate,d=t?.separator||" | ",u=t?.siteNameInTitle!==false,p=l?l.replace(/\{\{title\}\}/g,c).replace(/\{\{siteName\}\}/g,u?a:"").replace(/\{\{separator\}\}/g,d).replace(/\s+/g," ").trim():c,y=o||t?.defaultDescription||e.siteDescription||"",m=n||e.siteOgImage?.url||"",D=i||e.siteUrl||"",f=`
|
|
2
2
|
<title>${p}</title>
|
|
3
3
|
<meta name="description" content="${y}">
|
|
4
4
|
`;e.siteFavicon?.url&&(f+=`
|
package/dist/integration.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkWNVWRRWE_cjs=require('./chunk-WNVWRRWE.cjs');require('./chunk-AHSFSERC.cjs');module.exports=chunkWNVWRRWE_cjs.a;
|
package/dist/integration.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as default}from'./chunk-
|
|
1
|
+
export{a as default}from'./chunk-FVRNWRSG.js';import'./chunk-5J6HXUF6.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kyro-cms/core",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.36",
|
|
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"
|
|
@@ -185,14 +185,16 @@
|
|
|
185
185
|
"nodemailer": "^8.0.4",
|
|
186
186
|
"ora": "^8.2.0",
|
|
187
187
|
"postgres": "^3.4.8",
|
|
188
|
+
"prompts": "^2.4.2",
|
|
188
189
|
"sharp": "^0.34.5",
|
|
189
190
|
"unstorage": "^1.17.5",
|
|
190
191
|
"ws": "^8.18.0",
|
|
191
192
|
"zod": "^3.24.0",
|
|
192
193
|
"zod-to-json-schema": "^3.25.2",
|
|
193
|
-
"@kyro-cms/ai": "0.12.
|
|
194
|
+
"@kyro-cms/ai": "0.12.36"
|
|
194
195
|
},
|
|
195
196
|
"devDependencies": {
|
|
197
|
+
"@tailwindcss/vite": "^4.0.0",
|
|
196
198
|
"@types/better-sqlite3": "^7.6.13",
|
|
197
199
|
"@types/jsonwebtoken": "^9.0.9",
|
|
198
200
|
"@types/node": "^22.13.0",
|
|
@@ -206,7 +208,6 @@
|
|
|
206
208
|
"prettier": "^3.5.0",
|
|
207
209
|
"react": "^19.2.7",
|
|
208
210
|
"tailwindcss": "^4.0.0",
|
|
209
|
-
"@tailwindcss/vite": "^4.0.0",
|
|
210
211
|
"tsup": "^8.5.1",
|
|
211
212
|
"typescript": "^5.7.3",
|
|
212
213
|
"typescript-eslint": "^8.59.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunk4XZABBHF_cjs=require('./chunk-4XZABBHF.cjs');require('./chunk-5K4YG5DA.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-HOP4D5XZ.cjs'),require('./chunk-AHSFSERC.cjs');Object.defineProperty(exports,"autoBootstrap",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.d}});Object.defineProperty(exports,"bootstrapAdmin",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.a}});Object.defineProperty(exports,"bootstrapWithRetry",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.e}});Object.defineProperty(exports,"checkBootstrapRequired",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.b}});Object.defineProperty(exports,"getBootstrapFromEnv",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.c}});
|
package/dist/chunk-4XZABBHF.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunk5K4YG5DA_cjs=require('./chunk-5K4YG5DA.cjs'),chunkHOP4D5XZ_cjs=require('./chunk-HOP4D5XZ.cjs');async function f(t){let{adminEmail:e,adminPassword:r,adminRole:o="super_admin",tenantId:i,emailConfig:a,sendWelcomeEmail:c=false}=t,s=t.authAdapter||new chunkHOP4D5XZ_cjs.a({path:t.authDbPath||"./data/auth.db"});try{await s.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let l=new chunk5K4YG5DA_cjs.l().validate(r);if(!l.valid)return await s.disconnect?.(),{success:false,error:`Invalid password: ${l.errors.join(", ")}`};if(await s.findUserByEmail(e))return await s.disconnect?.(),{success:false,error:"Admin user already exists"};try{let n=await s.createUser({email:e,password:r,role:o||"admin",tenantId:i});if(await s.updateUser?.(n.id,{emailVerified:!0}),c&&a){let u=new chunk5K4YG5DA_cjs.k(a),w=u.getTemplates().welcome(e.split("@")[0]);await u.send({to:e,...w});}return await s.disconnect?.(),{success:!0,user:n}}catch(n){return await s.disconnect?.(),{success:false,error:n instanceof Error?n.message:"Failed to create admin user"}}}async function y(t,e){return !await t.findUserByEmail(e)}function A(){let t=process.env.KYRO_ADMIN_EMAIL,e=process.env.KYRO_ADMIN_PASSWORD;return !t||!e?null:{authDbPath:process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:t,adminPassword:e,adminRole:process.env.KYRO_ADMIN_ROLE||"super_admin",tenantId:process.env.KYRO_ADMIN_TENANT_ID,emailConfig:process.env.SMTP_HOST?{provider:"smtp",smtp:{host:process.env.SMTP_HOST,port:parseInt(process.env.SMTP_PORT||"587",10),secure:process.env.SMTP_SECURE==="true",auth:{user:process.env.SMTP_USER||"",pass:process.env.SMTP_PASS||""}},from:process.env.SMTP_FROM||"noreply@example.com",fromName:process.env.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:process.env.KYRO_ADMIN_SEND_WELCOME==="true"}}async function T(t){let e=A();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await f(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function v(t,e=3,r=2e3){let o="";for(let i=0;i<e;i++){let a=await f(t);if(a.success||(o=a.error||"Unknown error",o.includes("already exists")))return a;i<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${o}`}}exports.a=f;exports.b=y;exports.c=A;exports.d=T;exports.e=v;
|
package/dist/chunk-6MSPBK3W.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {l,k}from'./chunk-6J27P5D6.js';import {a}from'./chunk-IKOXCJYO.js';async function f(t){let{adminEmail:e,adminPassword:r,adminRole:o="super_admin",tenantId:i,emailConfig:a$1,sendWelcomeEmail:c=false}=t,s=t.authAdapter||new a({path:t.authDbPath||"./data/auth.db"});try{await s.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let l$1=new l().validate(r);if(!l$1.valid)return await s.disconnect?.(),{success:false,error:`Invalid password: ${l$1.errors.join(", ")}`};if(await s.findUserByEmail(e))return await s.disconnect?.(),{success:false,error:"Admin user already exists"};try{let n=await s.createUser({email:e,password:r,role:o||"admin",tenantId:i});if(await s.updateUser?.(n.id,{emailVerified:!0}),c&&a$1){let u=new k(a$1),w=u.getTemplates().welcome(e.split("@")[0]);await u.send({to:e,...w});}return await s.disconnect?.(),{success:!0,user:n}}catch(n){return await s.disconnect?.(),{success:false,error:n instanceof Error?n.message:"Failed to create admin user"}}}async function y(t,e){return !await t.findUserByEmail(e)}function A(){let t=process.env.KYRO_ADMIN_EMAIL,e=process.env.KYRO_ADMIN_PASSWORD;return !t||!e?null:{authDbPath:process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:t,adminPassword:e,adminRole:process.env.KYRO_ADMIN_ROLE||"super_admin",tenantId:process.env.KYRO_ADMIN_TENANT_ID,emailConfig:process.env.SMTP_HOST?{provider:"smtp",smtp:{host:process.env.SMTP_HOST,port:parseInt(process.env.SMTP_PORT||"587",10),secure:process.env.SMTP_SECURE==="true",auth:{user:process.env.SMTP_USER||"",pass:process.env.SMTP_PASS||""}},from:process.env.SMTP_FROM||"noreply@example.com",fromName:process.env.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:process.env.KYRO_ADMIN_SEND_WELCOME==="true"}}async function T(t){let e=A();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await f(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function v(t,e=3,r=2e3){let o="";for(let i=0;i<e;i++){let a=await f(t);if(a.success||(o=a.error||"Unknown error",o.includes("already exists")))return a;i<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${o}`}}export{f as a,y as b,A as c,T as d,v as e};
|