@kyro-cms/core 0.13.7 → 0.13.9
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/browser-JDBMVAJX.js +2 -0
- package/dist/browser-XEN42GDP.cjs +1 -0
- package/dist/chunk-7QZYK4MT.cjs +132 -0
- package/dist/{chunk-PPGZHOYR.cjs → chunk-CXQ2AC27.cjs} +1 -1
- package/dist/{chunk-SYE3OS5T.js → chunk-FKJ7AX37.js} +1 -1
- package/dist/{chunk-MCK2QRAU.cjs → chunk-HUZ3P5OC.cjs} +2 -2
- package/dist/chunk-PMO2O77B.js +133 -0
- package/dist/{chunk-TVWHTVLI.js → chunk-VBSM5DZ5.js} +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/index.cjs +13 -13
- package/dist/index.js +14 -14
- package/package.json +2 -1
- package/dist/chunk-GWUHIIPO.cjs +0 -132
- package/dist/chunk-TJ6N5ZPZ.js +0 -133
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-ZE2X3FBU.js';export{a as RedisAuthAdapter}from'./chunk-V4SR7DU5.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-SEJ7LMYY.js';export{r as ALL_FIELD_TYPES,o as COMPLEX_FIELD_TYPES,q as LAYOUT_FIELD_TYPES,n as PRIMITIVE_FIELD_TYPES,p 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,u as normalizeRichTextValue,v as renderRichText,t as richTextStyles}from'./chunk-5BUAWCU6.js';export{a as kyro}from'./chunk-SZY25KAE.js';export{s as AnalyticsPlugin,t as CommentsPlugin,a as ConfigValidationError,x as FIELD_DEFINITION_KEYS,F as Kyro,p as KyroPlugin,I as Logger,q as PluginManager,l as Registry,u as ReviewsPlugin,r as SEOPlugin,v as WishlistPlugin,B as applyBlocksOverrides,D as applyCollectionOverrides,E as applyGlobalOverrides,C as applyTabsOverrides,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,G as createKyro,H as createKyroHandler,o as createRegistry,f as fieldToZod,z as flattenFieldOverrides,m as getRegistry,k as globalToZod,y as isFieldOverrideDefinition,J as logger,w as presetPlugins,n as resetRegistry,A as updateFieldByPath,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-
|
|
2
|
-
async function
|
|
1
|
+
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-ZE2X3FBU.js';export{a as RedisAuthAdapter}from'./chunk-V4SR7DU5.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-SEJ7LMYY.js';export{r as ALL_FIELD_TYPES,o as COMPLEX_FIELD_TYPES,q as LAYOUT_FIELD_TYPES,n as PRIMITIVE_FIELD_TYPES,p 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,u as normalizeRichTextValue,v as renderRichText,t as richTextStyles}from'./chunk-5BUAWCU6.js';export{a as kyro}from'./chunk-SZY25KAE.js';export{s as AnalyticsPlugin,t as CommentsPlugin,a as ConfigValidationError,x as FIELD_DEFINITION_KEYS,F as Kyro,p as KyroPlugin,I as Logger,q as PluginManager,l as Registry,u as ReviewsPlugin,r as SEOPlugin,v as WishlistPlugin,B as applyBlocksOverrides,D as applyCollectionOverrides,E as applyGlobalOverrides,C as applyTabsOverrides,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,G as createKyro,H as createKyroHandler,o as createRegistry,f as fieldToZod,z as flattenFieldOverrides,m as getRegistry,k as globalToZod,y as isFieldOverrideDefinition,J as logger,w as presetPlugins,n as resetRegistry,A as updateFieldByPath,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-FKJ7AX37.js';export{e as autoBootstrap,a as bootstrapAdmin,f as bootstrapWithRetry,d as getBootstrapFromEnv}from'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.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-GTAKGVUY.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-5RBGM5N5.js';import {g,f,i,j as j$1}from'./chunk-3RIGRHON.js';export{g as AuditLogger,i as InMemoryAuditLogger,f as InMemoryRateLimiter,l as MediaService,h as createAuditContext,n as createKyroApp,d as createLocalStorage,o as createRESTAPI,k as isEdgeRuntime,c as resolveProvider}from'./chunk-3RIGRHON.js';import {a}from'./chunk-FAG2645P.js';export{a as PasswordPolicy}from'./chunk-FAG2645P.js';import {a as a$2}from'./chunk-IIVBEZC2.js';export{a as SQLiteAuthAdapter}from'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';export{c as getAppSecret,d as getEncryptionKey,e as getSessionConfig,b as loadSecrets,a as setDbAdapter}from'./chunk-SBFVITY2.js';import {q}from'./chunk-5I3BM5TV.js';export{p as ConfigService,q as EmailTransport,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-5I3BM5TV.js';import'./chunk-W5GDZG64.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-OPKZYQV7.js';export{h as evaluateAccess,j as getWhereClause,i as mergeWhereClauses}from'./chunk-3N34WXBS.js';export{b as KyroPubSub,d as KyroWSServer,a as PubSub,e as createWSServer}from'./chunk-OXH6CANN.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,d as createDrizzleAdapter,a as fieldToDrizzleType}from'./chunk-PMO2O77B.js';export{b as createDatabase,c as runMigrations,d as seedDefaultRoles}from'./chunk-JXJTFBHG.js';import {a as a$4}from'./chunk-IIPSXKNV.js';export{a as PostgresAuthAdapter}from'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';export{a as MongoDBAdapter,b as createMongoDBAdapter,d as getMongoClient,c as getMongoDb}from'./chunk-O6I26T6A.js';import {a as a$1}from'./chunk-YNBJGPIU.js';export{a as MongoDBAuthAdapter}from'./chunk-YNBJGPIU.js';import {a as a$5}from'./chunk-YNSKDTFG.js';export{a as AbstractBaseAdapter}from'./chunk-YNSKDTFG.js';import {a as a$3}from'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';import q$1,{randomBytes}from'crypto';import {readFileSync}from'fs';import Ke,{join,resolve}from'path';import {z as z$1}from'zod';export{z}from'zod';import {createStorage}from'unstorage';import uo from'unstorage/drivers/fs';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
async function Ee(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 Ur(s,e){return Ee(s,e)}var E=class extends a$5{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 Oe(s){return new E(s)}var O=class extends a$5{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 f={};return a.forEach((m,d)=>{f[m]=c[d]?.value??null;}),f})}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 Ue(s){return new O(s)}var j=class{constructor(e){this.config=e;}config;css=[];addRule(e,t){let r=Object.entries(t).map(([o,n])=>` ${o}: ${n};`).join(`
|
|
3
3
|
`);return this.css.push(`${e} {
|
|
4
4
|
${r}
|
|
5
5
|
}`),this}addMediaQuery(e,t){return this.css.push(`@media (min-width: ${e}) {
|
|
@@ -7,10 +7,10 @@ ${r}
|
|
|
7
7
|
`)}
|
|
8
8
|
}`),this}generate(){return this.css.join(`
|
|
9
9
|
|
|
10
|
-
`)}};function
|
|
10
|
+
`)}};function _r(s){return {theme:{extend:{colors:s.colors||{},fontFamily:s.fonts||{},spacing:s.spacing||{},borderRadius:s.borderRadius||{},boxShadow:s.shadows||{},screens:s.breakpoints||{}}}}}var U={colors:{primary:"#3b82f6",secondary:"#6366f1",accent:"#ec4899",background:"#ffffff",surface:"#f9fafb",text:"#111827",textMuted:"#6b7280",border:"#e5e7eb",error:"#ef4444",warning:"#f59e0b",success:"#10b981",info:"#3b82f6"},fonts:{sans:"system-ui, -apple-system, sans-serif",serif:"Georgia, serif",mono:"Menlo, monospace"},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem","2xl":"3rem","3xl":"4rem"},borderRadius:{sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1)"}},Vr={colors:{primary:"#60a5fa",secondary:"#818cf8",accent:"#f472b6",background:"#111827",surface:"#1f2937",text:"#f9fafb",textMuted:"#9ca3af",border:"#374151",error:"#f87171",warning:"#fbbf24",success:"#34d399",info:"#60a5fa"},fonts:U.fonts,spacing:U.spacing,borderRadius:U.borderRadius,shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.3)",md:"0 4px 6px -1px rgb(0 0 0 / 0.4)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.5)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.6)"}},Fr={colors:{primary:"#FF6B35",secondary:"#1A1A2E",accent:"#16C79A",background:"#FFFFFF",surface:"#F8F9FA",text:"#1A1A2E",textMuted:"#6B7280",border:"#E5E7EB",error:"#EF4444",warning:"#F59E0B",success:"#16C79A",info:"#3B82F6"},fonts:{sans:'"Inter", "Satoshi", system-ui, sans-serif',serif:'"Playfair Display", Georgia, serif',mono:'"JetBrains Mono", monospace'},spacing:{xs:"0.125rem",sm:"0.25rem",md:"0.5rem",lg:"1rem",xl:"1.5rem","2xl":"2rem","3xl":"3rem","4xl":"4rem"},borderRadius:{sm:"0",md:"0",lg:"0",xl:"0",full:"9999px"},shadows:{sm:"0 1px 2px rgba(0,0,0,0.05)",md:"0 4px 6px rgba(0,0,0,0.07)",lg:"0 10px 15px rgba(0,0,0,0.1)",xl:"0 20px 25px rgba(0,0,0,0.15)"}};function _e(s){let e=[];if(s.colors)for(let[t,r]of Object.entries(s.colors))e.push(` --color-${t}: ${r};`);if(s.fonts)for(let[t,r]of Object.entries(s.fonts))e.push(` --font-${t}: ${r};`);if(s.spacing)for(let[t,r]of Object.entries(s.spacing))e.push(` --spacing-${t}: ${r};`);if(s.borderRadius)for(let[t,r]of Object.entries(s.borderRadius))e.push(` --radius-${t}: ${r};`);if(s.shadows)for(let[t,r]of Object.entries(s.shadows))e.push(` --shadow-${t}: ${r};`);return `:root {
|
|
11
11
|
${e.join(`
|
|
12
12
|
`)}
|
|
13
|
-
}`}function
|
|
13
|
+
}`}function Mr(s){let e=_e(s.theme||U),t=[];if(s.componentOverrides)for(let[r,o]of Object.entries(s.componentOverrides)){let n=Object.entries(o).map(([i,a])=>` ${i}: ${a};`).join(`
|
|
14
14
|
`);t.push(`${r} {
|
|
15
15
|
${n}
|
|
16
16
|
}`);}return `
|
|
@@ -18,28 +18,28 @@ ${n}
|
|
|
18
18
|
${s.customStyles||""}
|
|
19
19
|
${t.join(`
|
|
20
20
|
`)}
|
|
21
|
-
`}var Nr={text:{wrapper:{marginBottom:"var(--spacing-md)"},label:{display:"block",marginBottom:"var(--spacing-xs)",fontWeight:"500",color:"var(--color-text)"},input:{width:"100%",padding:"var(--spacing-sm) var(--spacing-md)",border:"1px solid var(--color-border)",borderRadius:"var(--radius-md)",fontSize:"0.875rem"},error:{color:"var(--color-error)",fontSize:"0.75rem",marginTop:"var(--spacing-xs)"}},number:{wrapper:{marginBottom:"var(--spacing-md)"},label:{display:"block",marginBottom:"var(--spacing-xs)",fontWeight:"500"},input:{width:"100%",padding:"var(--spacing-sm) var(--spacing-md)",border:"1px solid var(--color-border)",borderRadius:"var(--radius-md)"}},checkbox:{wrapper:{display:"flex",alignItems:"center",gap:"var(--spacing-sm)"},input:{width:"1rem",height:"1rem"},label:{cursor:"pointer"}},select:{wrapper:{marginBottom:"var(--spacing-md)"},input:{width:"100%",padding:"var(--spacing-sm) var(--spacing-md)",border:"1px solid var(--color-border)",borderRadius:"var(--radius-md)",backgroundColor:"white"}}};var Br={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},C=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...Br,...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 $r={"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}},R=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...$r,...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 m=(await a.exec())?.[1]?.[1]||0;if(m>=r.max){let f=await this.redis.zrange(o,0,0,"WITHSCORES"),d=f.length>1?parseInt(f[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:d,retryAfter:Math.ceil((d-n)/1e3)}}return {allowed:true,remaining:r.max-m-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 f=(await c.exec())?.[1]?.[1]||0;if(f>=o.max){let d=await this.redis.zrange(n,0,0,"WITHSCORES"),l=d.length>1?parseInt(d[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:l,retryAfter:Math.ceil((l-i)/1e3)}}return {allowed:true,remaining:o.max-f-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 v=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,name:e.name,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",avatar:e.avatar,tenantId:e.tenantId,metadata:e.metadata,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 D=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 w(s,e=""){return process.env[s]||e}function T(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function A(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Fe(){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 zr(s,e){let t=process.cwd(),r=t.endsWith("admin")?join(t,".."):t,o=resolve(r,"data","auth.db");switch(s){case "sqlite":return new a$2({path:w("KYRO_AUTH_DB_PATH",o)});case "postgres":{let n=w("DATABASE_URL","");if(n){let i,a;try{i=(await import('drizzle-orm/postgres-js')).drizzle,a=await import('postgres');}catch{a$3(["postgres","drizzle-orm"]),i=(await import('drizzle-orm/postgres-js')).drizzle,a=await import('postgres');}let c=a.default(n,{onnotice:()=>{}}),m=i(c);return new a$4({db:m})}return new a$2({path:w("KYRO_AUTH_DB_PATH",o)})}case "mongodb":{if(e)return new a$1({db:e.db||(typeof e=="function"?e:void 0),adapter:e,client:e.client});let n=globalThis;if(n.__KYRO_INSTANCE__?.db?.dialect==="mongodb"&&n.__KYRO_INSTANCE__.db.db)return new a$1({db:n.__KYRO_INSTANCE__.db.db,adapter:n.__KYRO_INSTANCE__.db,client:n.__KYRO_INSTANCE__.db.client});let i=w("MONGODB_URI","");if(i){let{getMongoClient:a}=await import('./mongodb/index.js'),c=await a({connectionString:i}),f=new URL(i).pathname.replace(/^\//,"")||"kyro_cms",d=c.db(f);return new a$1({db:d,client:c})}return new a$2({path:w("KYRO_AUTH_DB_PATH",o)})}default:return new v}}async function z(s,e){let t=T("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:d}=await import('./redis-adapter-GFH74CF4.js'),l=w("REDIS_URL","redis://localhost:6379"),b=T("REDIS_TLS",false),p=new d({url:l,tls:b});await p.connect?.(),r=p;}else {let d=s||Fe();r=await zr(d,e),r.connect&&await r.connect();}let o=e?await q$1.fromConfig(e).catch(()=>null)||q$1.fromEnv()||void 0:q$1.fromEnv()||void 0,n=new a({minLength:A("PASSWORD_MIN_LENGTH",12),requireUppercase:T("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:T("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:T("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:T("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:A("PASSWORD_PREVENT_REUSE",5),maxLength:A("PASSWORD_MAX_LENGTH",128)}),i$1,a$1,c;if(t){let l=r.redis;i$1=new C(l,{maxAttempts:A("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:A("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a$1=new R(l,{"auth:login":{window:A("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:A("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:A("RATE_LIMIT_WINDOW_MS",6e4),max:A("RATE_LIMIT_MAX_REQUESTS",100)}}),c=new g(l,A("AUDIT_LOG_RETENTION_DAYS",30));}else i$1=new D({maxAttempts:A("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:A("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a$1=new f({"auth:login":{window:A("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:A("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:A("RATE_LIMIT_WINDOW_MS",6e4),max:A("RATE_LIMIT_MAX_REQUESTS",100)}}),c=T("AUDIT_LOG_ENABLED",true)?new i(A("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let m=new j$1({redis:r,email:o,jwtSecret:w("APP_SECRET","change-me"),jwtExpiresIn:w("JWT_EXPIRES_IN","24h"),jwtIssuer:w("JWT_ISSUER","kyro-cms"),jwtAudience:w("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n,lockout:i$1,rateLimiter:a$1,auditLogger:c,baseUrl:w("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:T("EMAIL_VERIFICATION_REQUIRED",true)}),f$1=t?"distributed":s||Fe();return {authAdapter:r,databaseType:f$1,email:o,passwordPolicy:n,lockout:i$1,rateLimiter:a$1,auditLogger:c,routes:m}}var He=z().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Wr=12,qr="24h",Gr="7d",H=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??qr,refreshExpiresIn:t.refreshExpiresIn??Gr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Wr};}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 Yr(s,e){return new H(s,e)}function N(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var B=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 Qr(s,e){return new B(s,e)}function Jr(s){return s==="published"}function Xr(s){return s==="draft"}function Zr(s){return s==="archived"}function eo(s){return s?Array.isArray(s)?s:Object.values(s):[]}function to(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Ne(s){return {collections:eo(s.collections),globals:to(s.globals),adapter:s.adapter,storage:s.storage,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 ro=Ne;function oo(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,m=t?.titleTemplate,f=t?.separator||" | ",d=t?.siteNameInTitle!==false,l=m?m.replace(/\{\{title\}\}/g,c).replace(/\{\{siteName\}\}/g,d?a:"").replace(/\{\{separator\}\}/g,f).replace(/\s+/g," ").trim():c,b=o||t?.defaultDescription||e.siteDescription||"",p=n||e.siteOgImage?.url||"",h=i||e.siteUrl||"",y=`
|
|
21
|
+
`}var Hr={text:{wrapper:{marginBottom:"var(--spacing-md)"},label:{display:"block",marginBottom:"var(--spacing-xs)",fontWeight:"500",color:"var(--color-text)"},input:{width:"100%",padding:"var(--spacing-sm) var(--spacing-md)",border:"1px solid var(--color-border)",borderRadius:"var(--radius-md)",fontSize:"0.875rem"},error:{color:"var(--color-error)",fontSize:"0.75rem",marginTop:"var(--spacing-xs)"}},number:{wrapper:{marginBottom:"var(--spacing-md)"},label:{display:"block",marginBottom:"var(--spacing-xs)",fontWeight:"500"},input:{width:"100%",padding:"var(--spacing-sm) var(--spacing-md)",border:"1px solid var(--color-border)",borderRadius:"var(--radius-md)"}},checkbox:{wrapper:{display:"flex",alignItems:"center",gap:"var(--spacing-sm)"},input:{width:"1rem",height:"1rem"},label:{cursor:"pointer"}},select:{wrapper:{marginBottom:"var(--spacing-md)"},input:{width:"100%",padding:"var(--spacing-sm) var(--spacing-md)",border:"1px solid var(--color-border)",borderRadius:"var(--radius-md)",backgroundColor:"white"}}};var Br={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},C=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...Br,...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 Nr={"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}},R=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...Nr,...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 f=(await a.exec())?.[1]?.[1]||0;if(f>=r.max){let m=await this.redis.zrange(o,0,0,"WITHSCORES"),d=m.length>1?parseInt(m[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:d,retryAfter:Math.ceil((d-n)/1e3)}}return {allowed:true,remaining:r.max-f-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 m=(await c.exec())?.[1]?.[1]||0;if(m>=o.max){let d=await this.redis.zrange(n,0,0,"WITHSCORES"),l=d.length>1?parseInt(d[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:l,retryAfter:Math.ceil((l-i)/1e3)}}return {allowed:true,remaining:o.max-m-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 v=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,name:e.name,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",avatar:e.avatar,tenantId:e.tenantId,metadata:e.metadata,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 D=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 w(s,e=""){return process.env[s]||e}function T(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function A(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Ve(){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 jr(s,e){let t=process.cwd(),r=t.endsWith("admin")?join(t,".."):t,o=resolve(r,"data","auth.db");switch(s){case "sqlite":return new a$2({path:w("KYRO_AUTH_DB_PATH",o)});case "postgres":{let n=w("DATABASE_URL","");if(n){let i,a;try{i=(await import('drizzle-orm/postgres-js')).drizzle,a=await import('postgres');}catch{a$3(["postgres","drizzle-orm"]),i=(await import('drizzle-orm/postgres-js')).drizzle,a=await import('postgres');}let c=a.default(n,{onnotice:()=>{}}),f=i(c);return new a$4({db:f})}return new a$2({path:w("KYRO_AUTH_DB_PATH",o)})}case "mongodb":{if(e)return new a$1({db:e.db||(typeof e=="function"?e:void 0),adapter:e,client:e.client});let n=globalThis;if(n.__KYRO_INSTANCE__?.db?.dialect==="mongodb"&&n.__KYRO_INSTANCE__.db.db)return new a$1({db:n.__KYRO_INSTANCE__.db.db,adapter:n.__KYRO_INSTANCE__.db,client:n.__KYRO_INSTANCE__.db.client});let i=w("MONGODB_URI","");if(i){let{getMongoClient:a}=await import('./mongodb/index.js'),c=await a({connectionString:i}),m=new URL(i).pathname.replace(/^\//,"")||"kyro_cms",d=c.db(m);return new a$1({db:d,client:c})}return new a$2({path:w("KYRO_AUTH_DB_PATH",o)})}default:return new v}}async function z(s,e){let t=T("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:d}=await import('./redis-adapter-GFH74CF4.js'),l=w("REDIS_URL","redis://localhost:6379"),b=T("REDIS_TLS",false),p=new d({url:l,tls:b});await p.connect?.(),r=p;}else {let d=s||Ve();r=await jr(d,e),r.connect&&await r.connect();}let o=e?await q.fromConfig(e).catch(()=>null)||q.fromEnv()||void 0:q.fromEnv()||void 0,n=new a({minLength:A("PASSWORD_MIN_LENGTH",12),requireUppercase:T("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:T("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:T("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:T("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:A("PASSWORD_PREVENT_REUSE",5),maxLength:A("PASSWORD_MAX_LENGTH",128)}),i$1,a$1,c;if(t){let l=r.redis;i$1=new C(l,{maxAttempts:A("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:A("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a$1=new R(l,{"auth:login":{window:A("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:A("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:A("RATE_LIMIT_WINDOW_MS",6e4),max:A("RATE_LIMIT_MAX_REQUESTS",100)}}),c=new g(l,A("AUDIT_LOG_RETENTION_DAYS",30));}else i$1=new D({maxAttempts:A("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:A("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a$1=new f({"auth:login":{window:A("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:A("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:A("RATE_LIMIT_WINDOW_MS",6e4),max:A("RATE_LIMIT_MAX_REQUESTS",100)}}),c=T("AUDIT_LOG_ENABLED",true)?new i(A("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let f$1=new j$1({redis:r,email:o,jwtSecret:w("APP_SECRET","change-me"),jwtExpiresIn:w("JWT_EXPIRES_IN","24h"),jwtIssuer:w("JWT_ISSUER","kyro-cms"),jwtAudience:w("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n,lockout:i$1,rateLimiter:a$1,auditLogger:c,baseUrl:w("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:T("EMAIL_VERIFICATION_REQUIRED",true)}),m=t?"distributed":s||Ve();return {authAdapter:r,databaseType:m,email:o,passwordPolicy:n,lockout:i$1,rateLimiter:a$1,auditLogger:c,routes:f$1}}var Me=z().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var zr=12,Wr="24h",qr="7d",H=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Wr,refreshExpiresIn:t.refreshExpiresIn??qr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??zr};}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 Gr(s,e){return new H(s,e)}function B(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var N=class{adapter;config;constructor(e,t){this.adapter=e,this.config={...B(),...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 Yr(s,e){return new N(s,e)}function Qr(s){return s==="published"}function Jr(s){return s==="draft"}function Xr(s){return s==="archived"}function Zr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function eo(s){return s?Array.isArray(s)?s:Object.values(s):[]}function He(s){return {collections:Zr(s.collections),globals:eo(s.globals),adapter:s.adapter,storage:s.storage,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 to=He;function ro(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,f=t?.titleTemplate,m=t?.separator||" | ",d=t?.siteNameInTitle!==false,l=f?f.replace(/\{\{title\}\}/g,c).replace(/\{\{siteName\}\}/g,d?a:"").replace(/\{\{separator\}\}/g,m).replace(/\s+/g," ").trim():c,b=o||t?.defaultDescription||e.siteDescription||"",p=n||e.siteOgImage?.url||"",h=i||e.siteUrl||"",y=`
|
|
22
22
|
<title>${l}</title>
|
|
23
23
|
<meta name="description" content="${b}">
|
|
24
24
|
`;e.siteFavicon?.url&&(y+=`
|
|
25
25
|
<link rel="icon" type="${e.siteFavicon.mimeType||"image/x-icon"}" href="${e.siteFavicon.url}">`);let x=t?.meta?.robots;x&&(y+=`
|
|
26
|
-
<meta name="robots" content="${x}">`);let
|
|
27
|
-
<link rel="canonical" href="${
|
|
28
|
-
<meta property="og:type" content="${
|
|
26
|
+
<meta name="robots" content="${x}">`);let Q=t?.meta?.canonicalUrl||h;Q&&(y+=`
|
|
27
|
+
<link rel="canonical" href="${Q}">`);let We=t?.meta?.ogType||"website";y+=`
|
|
28
|
+
<meta property="og:type" content="${We}">
|
|
29
29
|
<meta property="og:title" content="${l}">
|
|
30
30
|
<meta property="og:description" content="${b}">
|
|
31
31
|
<meta property="og:site_name" content="${a}">
|
|
32
32
|
`,h&&(y+=`
|
|
33
33
|
<meta property="og:url" content="${h}">`),p&&(y+=`
|
|
34
34
|
<meta property="og:image" content="${p}">`),t?.social?.fbAppId&&(y+=`
|
|
35
|
-
<meta property="fb:app_id" content="${t.social.fbAppId}">`);let
|
|
36
|
-
<meta name="twitter:card" content="${
|
|
35
|
+
<meta property="fb:app_id" content="${t.social.fbAppId}">`);let qe=t?.social?.twitterCardType||"summary_large_image";return y+=`
|
|
36
|
+
<meta name="twitter:card" content="${qe}">
|
|
37
37
|
<meta name="twitter:title" content="${l}">
|
|
38
38
|
<meta name="twitter:description" content="${b}">
|
|
39
39
|
`,t?.social?.twitterHandle&&(y+=`
|
|
40
40
|
<meta name="twitter:site" content="${t.social.twitterHandle}">`),p&&(y+=`
|
|
41
41
|
<meta name="twitter:image" content="${p}">`),e.enableI18n&&e.i18n?.language&&(y+=`
|
|
42
|
-
<meta http-equiv="content-language" content="${e.i18n.language}">`),y}function
|
|
42
|
+
<meta http-equiv="content-language" content="${e.i18n.language}">`),y}function oo(s){if(!s||!s.analyticsEnabled||!s.analytics)return "";let{googleAnalyticsId:e,googleTagManagerId:t,plausibleDomain:r}=s.analytics,o="";return e&&(o+=`
|
|
43
43
|
<!-- Google Analytics -->
|
|
44
44
|
<script async src="https://www.googletagmanager.com/gtag/js?id=${e}"></script>
|
|
45
45
|
<script>
|
|
@@ -60,11 +60,11 @@ ${n}
|
|
|
60
60
|
`),r&&(o+=`
|
|
61
61
|
<!-- Plausible Analytics -->
|
|
62
62
|
<script defer data-domain="${r}" src="https://plausible.io/js/script.js"></script>
|
|
63
|
-
`),o}var
|
|
63
|
+
`),o}var so={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"}},no=["facebook","twitter","instagram","linkedin","youtube","tiktok","pinterest","discord","twitch","github","mastodon"];function Be(s){if(!s)return [];let e=s.showAll===true,t=[];for(let r of no){let o=s[r];if(!o||["tiktok","pinterest","discord","twitch","github","mastodon"].includes(r)&&!e)continue;let i=so[r];t.push({platform:r,url:o,label:i?.label||r});}return t}async function io(s,e){try{let t=await s.findOne({collection:"_globals_social-settings",where:{},draft:e?.draft??!1});return Be(t)}catch{return []}}function Ne(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 ao(s,e){try{let t=await s.findOne({collection:"_globals_store-settings",where:{},draft:e?.draft??!1});return Ne(t)}catch{return {}}}function $e(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 co(s,e){try{let t=await s.findOne({collection:"_globals_payment-settings",where:{},draft:e?.draft??!1});return $e(t)}catch{return {}}}function W(s){let e=s||process.env.APP_SECRET||process.env.AUTH_SECRET||"development-secret-key";return q$1.createHash("sha256").update(e).digest("hex")}function go(s,e){let t=q$1.randomBytes(16),r=q$1.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 mo(s,e){let[t,r,o]=s.split(":"),n=Buffer.from(t,"hex"),i=Buffer.from(r,"hex"),a=q$1.createDecipheriv("aes-256-gcm",Buffer.from(e,"hex").subarray(0,32),n);a.setAuthTag(i);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}async function G(s={}){let{namespace:e="kyro",ttl:t,encryption:r=true,secret:o,basePath:n}=s,i=n?Ke.join(n,".astro","kyro.json"):Ke.join(process.cwd(),".astro","kyro.json"),a=createStorage({driver:uo({base:i})}),c=r?W(o):null,f=e?`${e}:`:"";return {storage:{getItem:async m=>{let d=`${f}${m}`,l=await a.getItem(d);if(l==null)return null;try{let b=c?mo(l,c):l,p=JSON.parse(b);return p.expiry&&Date.now()>p.expiry?(await a.removeItem(d),null):p.value}catch{return l}},setItem:async(m,d)=>{let l=`${f}${m}`,b=JSON.stringify(t?{value:d,expiry:Date.now()+t}:{value:d});await a.setItem(l,c?go(b,c):b);},removeItem:async m=>{await a.removeItem(`${f}${m}`);}},cleanup:async()=>{await a.dispose?.();}}}async function Y(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};if(e==="browser"){let{createBrowserStorage:a}=await import('./browser-JDBMVAJX.js');return a({namespace:"kyro"})}return G({namespace:"kyro",encryption:i.enabled,secret:n})}async function je(s){let e={...s,encryption:{enabled:true,algorithm:s.encryption?.algorithm}};return Y(e)}function fo(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 a=String(i.id||i._id),c=await o({id:a,data:i});t.set({id:a,data:c,digest:JSON.stringify(c)});}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:z$1.object({id:z$1.string(),createdAt:z$1.string().optional(),updatedAt:z$1.string().optional()}).passthrough()}}function yo(s){return {input:s.schema||z$1.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"}}}}}function bo(s={}){let e=s.protectedRoutes||[],t=s.loginPath||"/admin/login",r=s.cookieName||"kyro_session";return async(o,n)=>{let{request:i,cookies:a,redirect:c,locals:f}=o,m=new URL(i.url),d=a?.get?.(r)?.value||i.headers.get("authorization")?.replace("Bearer ",""),l=null;return d&&(l={id:"user_1",email:"admin@kyro-cms.com",role:"admin"}),f.kyroUser=l,e.some(p=>new RegExp("^"+p.replace(/\*/g,".*")+"$").test(m.pathname))&&!l?c(`${t}?redirect=${encodeURIComponent(m.pathname)}`):n()}}function Ao(s){let e=s?.collections||[],t=`// Auto-generated by Kyro CMS
|
|
64
64
|
declare module 'kyro:collections' {
|
|
65
65
|
export interface KyroCollections {
|
|
66
66
|
`;for(let r of e){let o=r.name||r.slug;t+=` '${o}': Record<string, any>;
|
|
67
67
|
`;}return t+=` }
|
|
68
68
|
}
|
|
69
|
-
`,t}function
|
|
70
|
-
export{C as AccountLockout,H as Auth,j as CSSGenerator,D as InMemoryAccountLockout,v as InMemoryAuthAdapter,E as NeonAdapter,R as RateLimiter,O as TursoAdapter,
|
|
69
|
+
`,t}function wo(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"}}}function xo(s,e={}){let{idField:t="id",parentField:r="parent",slugField:o="slug",slugPrefix:n=true,basePath:i="",maxDepth:a=10}=e,c=new Map,f=[];for(let d of s){let l=d[t];l!=null&&c.set(l,{doc:d,id:l,slug:d[o],depth:0,path:"",fullPath:"",children:[]});}for(let d of s){let l=d[t],b=c.get(l);if(!b)continue;let p=d[r];p&&typeof p=="object"&&(p=p[t]||p.id||p._id),p&&c.has(p)?c.get(p).children.push(b):f.push(b);}function m(d,l,b){if(!(l>a))for(let p of d){p.depth=l;let h=p.slug||String(p.id),y="";n?y=b?`${b}/${h}`:i?`${i.replace(/\/$/,"")}/${h}`:`/${h}`:y=i?`${i.replace(/\/$/,"")}/${h}`:`/${h}`,p.path=y,p.fullPath=y,p.children.length>0&&m(p.children,l+1,p.path);}}return m(f,0,""),f}function ze(s,e,t={}){let r,o;Array.isArray(s)?(r=s,o=e):(o=s,r=e);let{idField:n="id",parentField:i="parent",labelField:a="title",slugField:c="slug",basePath:f=""}=t,m=new Map;for(let h of r){let y=h[n];y!=null&&m.set(y,h);}let d=[],l=o,b=new Set;for(;l!==void 0&&m.has(l)&&!b.has(l);){b.add(l);let h=m.get(l),y=h[a]||h.name||h.label||h[c]||String(l);d.unshift({id:l,label:y,slug:h[c]});let x=h[i];x&&typeof x=="object"&&(x=x[n]||x.id||x._id),l=x;}let p=f?f.replace(/\/$/,""):"";return d.map(h=>{let y=h.slug||String(h.id);return p=`${p}/${y}`,{...h,path:p}})}function To(s,e,t={}){let r=ze(s,e,t);return r[r.length-1]?.path||(t.basePath?t.basePath:"/")}function So(s){let e=[];function t(r){for(let o of r)e.push({doc:o.doc,id:o.id,depth:o.depth,path:o.path,fullPath:o.fullPath,hasChildren:o.children.length>0}),o.children.length>0&&t(o.children);}return t(s),e}
|
|
70
|
+
export{C as AccountLockout,H as Auth,j as CSSGenerator,D as InMemoryAccountLockout,v as InMemoryAuthAdapter,E as NeonAdapter,R as RateLimiter,O as TursoAdapter,N as VersionManager,Me as authConfig,xo as buildDocumentTree,Mr as createAdminStyling,Gr as createAuth,z as createAuthConfig,je as createAuthStorage,Oe as createNeonAdapter,Y as createStorage,Ue as createTursoAdapter,Yr as createVersionManager,Vr as defaultDarkTheme,Hr as defaultFieldStyling,U as defaultLightTheme,He as defineConfig,to as defineKyroConfig,Fr as ecommerce2026Theme,So as flattenDocumentTree,oo as generateAnalyticsTags,_e as generateCSSVariables,Ao as generateKyroAstroTypes,ro as generateSeoTags,_r as generateTailwindConfig,ze as getBreadcrumbs,B as getDefaultDraftPublishConfig,To as getNestedPath,co as getPaymentConfig,$e as getPaymentConfigFromSettings,io as getSocialLinks,Be as getSocialLinksFromSettings,ao as getStoreConfig,Ne as getStoreConfigFromSettings,Xr as isArchived,Jr as isDraft,Qr as isPublished,yo as kyroAction,bo as kyroAuthMiddleware,wo as kyroEnvSchema,fo as kyroLoader,Ur as runFieldHooks,Ee as runHooks};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kyro-cms/core",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.9",
|
|
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"
|
|
@@ -178,6 +178,7 @@
|
|
|
178
178
|
"postgres": "^3.4.8",
|
|
179
179
|
"prompts": "^2.4.2",
|
|
180
180
|
"sharp": "^0.34.5",
|
|
181
|
+
"idb-keyval": "^6.2.1",
|
|
181
182
|
"unstorage": "^1.17.5",
|
|
182
183
|
"ws": "^8.18.0",
|
|
183
184
|
"zod": "^3.24.0",
|
package/dist/chunk-GWUHIIPO.cjs
DELETED
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkYOJOVQIH_cjs=require('./chunk-YOJOVQIH.cjs'),chunkO4PPZOVI_cjs=require('./chunk-O4PPZOVI.cjs'),chunkJJY2F6NL_cjs=require('./chunk-JJY2F6NL.cjs'),chunkOXEJCIOA_cjs=require('./chunk-OXEJCIOA.cjs'),drizzleOrm=require('drizzle-orm'),pgCore=require('drizzle-orm/pg-core'),sqliteCore=require('drizzle-orm/sqlite-core');function b(m,t="postgres"){switch(m.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return m.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function j(m,t="postgres"){let i=m.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of m.fields){if(s.name==="id"||s.type==="password")continue;let n=b(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return m.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
|
|
2
|
-
`)}function N(m){if(typeof m!="string")return m;let t=m.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:m}var I=class extends chunkO4PPZOVI_cjs.a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let n=e[s.name];n&&typeof n=="string"&&(e[s.name]=new Date(n));}for(let s of i.fields){let r=b(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let o={};for(let[l,c]of Object.entries(a)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===l);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&c?o[l]=Array.isArray(c)||typeof c=="object"?JSON.stringify(c):c:o[l]=c;}e[s.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let a=t[s.name];a!=null&&(e[s.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=b(s,this.dialect);(n==="timestamp"||n==="jsonb"||n==="decimal"||n==="integer"||n==="numeric"||n==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('postgres')).default,i=(await import('drizzle-orm/postgres-js')).drizzle;}catch{chunkJJY2F6NL_cjs.a(["postgres","drizzle-orm"]),t=(await import('postgres')).default,i=(await import('drizzle-orm/postgres-js')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('drizzle-orm/better-sqlite3')).drizzle;}catch{chunkJJY2F6NL_cjs.a(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('drizzle-orm/better-sqlite3')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('drizzle-orm/d1');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e=this.getTableName(t.slug),s={id:i?pgCore.text("id").primaryKey():pgCore.uuid("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=b(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),l;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":l=sqliteCore.text(o);break;case "integer":l=sqliteCore.integer(o);break;case "decimal":case "numeric":l=sqliteCore.numeric(o);break;case "boolean":l=sqliteCore.integer(o,{mode:"boolean"});break;case "timestamp":l=sqliteCore.text(o);break;case "jsonb":l=sqliteCore.text(o);break;default:l=sqliteCore.text(o);}else switch(r){case "varchar":l=pgCore.varchar(o,{length:255});break;case "integer":l=pgCore.integer(o);break;case "decimal":l=pgCore.decimal(o);break;case "boolean":l=pgCore.boolean(o);break;case "timestamp":l=pgCore.timestamp(o);break;case "jsonb":l=pgCore.jsonb(o);break;default:l=pgCore.text(o);}n.required||(l=l.default(null)),s[a]=l;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?sqliteCore.text("created_at").default(new Date().toISOString()):pgCore.timestamp("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?sqliteCore.text("updated_at").default(new Date().toISOString()):pgCore.timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?sqliteCore.text("status").default("draft"):pgCore.varchar("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?sqliteCore.integer("hasDraft",{mode:"boolean"}).default(false):pgCore.boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteCore.sqliteTable(e,s):pgCore.pgTable(e,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),l=e.fields.some(u=>u.name==="status"),c=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
|
|
3
|
-
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
4
|
-
${u},
|
|
5
|
-
${r}
|
|
6
|
-
${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
7
|
-
${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
8
|
-
${l?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
|
|
9
|
-
${c?"":'"hasDraft" BOOLEAN DEFAULT false'}
|
|
10
|
-
)
|
|
11
|
-
`);}else i.push(`
|
|
12
|
-
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
13
|
-
"id" TEXT PRIMARY KEY,
|
|
14
|
-
${r}
|
|
15
|
-
${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
16
|
-
${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
17
|
-
${l?"":`"status" TEXT DEFAULT 'draft',`}
|
|
18
|
-
${c?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
19
|
-
)
|
|
20
|
-
`);}if(i.length>0)if(this.dialect==="postgres")await this.executeRaw(drizzleOrm.sql.raw(i.join(`;
|
|
21
|
-
`)));else for(let e of i)await this.executeRaw(drizzleOrm.sql.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=b(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),n=this.columnSqlType(e,i);return `"${s}" ${n} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(t){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(t,i){let e={},s=t.slug.startsWith("_globals_"),n=t.fields.some(l=>l.name==="createdAt"),r=t.fields.some(l=>l.name==="updatedAt"),a=t.fields.some(l=>l.name==="status"),o=t.fields.some(l=>l.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',n||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let l of t.fields){if(!l.name||l.name==="id")continue;let c=this.getColumnSqlDefinition(l,this.dialect),u=l.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=c;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(drizzleOrm.sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.executeRaw(drizzleOrm.sql`PRAGMA table_info("${drizzleOrm.sql.raw(i)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(r=>!e.has(r));if(n.length>0){let r=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(drizzleOrm.sql.raw(r.join(`;
|
|
22
|
-
`)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=b(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),l=e.get(o);!l||l.type!=="character varying"||(a==="text"?await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=b(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
|
|
23
|
-
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n=10,page:r=1,tenantId:a,select:o,draft:l}=t,c=this.getCollection(i),u=this.getTable(i),h={...e};this.tenantContext&&c.tenantScoped&&(h=chunkO4PPZOVI_cjs.c({where:h},i,this.tenantContext,chunkO4PPZOVI_cjs.b).where||{});let g=this.buildWhereClause(h,c,u,a),y=c.fields.find(p=>p.name==="status"),f=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(p=>p.value==="published");!l&&u.status&&f&&g.push(drizzleOrm.eq(u.status,"published"));let E=this.parseSort(s),T=!l&&u.status&&f?{...h,status:"published"}:h,Y=await this.count({collection:i,where:T,tenantId:a}),J=(r-1)*n,F=[];try{let p=u[E.field]||u.createdAt||u.id,R=E.direction==="asc"?p:drizzleOrm.desc(p),_=this.client.select().from(u);g.length>0&&(_=_.where(drizzleOrm.and(...g))),F=await _.orderBy(R).limit(n).offset(J);}catch(p){console.error("[DrizzleAdapter] Query error:",p);}let C=F.map(p=>this.processResult(p,c));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(p=>chunkO4PPZOVI_cjs.d(p,i,this.tenantContext,chunkO4PPZOVI_cjs.b))),l&&(C=await Promise.all(C.map(async p=>{let R=await this.executeRaw(drizzleOrm.sql`
|
|
24
|
-
SELECT * FROM kyro_versions
|
|
25
|
-
WHERE collection_slug = ${i}
|
|
26
|
-
AND document_id = ${p.id}
|
|
27
|
-
ORDER BY created_at DESC
|
|
28
|
-
LIMIT 1
|
|
29
|
-
`);if(R.length>0){let _=R[0],w=_.data;for(;typeof w=="string";)try{w=JSON.parse(w);}catch{break}return (!w||typeof w!="object"||Array.isArray(w))&&(w={}),{...p,...w,status:p.status,_hasUnpublishedChanges:_.status==="draft"}}return p}))),{docs:C,...this.calculatePagination(r,n,Y)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?N(e):e;if(this.tenantContext&&r.tenantScoped){let f={id:o,tenantId:this.tenantContext.tenantId};if(!chunkO4PPZOVI_cjs.d(f,i,this.tenantContext,chunkO4PPZOVI_cjs.b))return null}let l=[drizzleOrm.eq(a.id,o)];s&&a.tenantId&&l.push(drizzleOrm.eq(a.tenantId,s));let c=r.fields.find(f=>f.name==="status"),u=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(f=>f.value==="published");!n&&a.status&&u&&l.push(drizzleOrm.eq(a.status,"published"));let h=l.length>1?drizzleOrm.and(...l):l[0],g=await this.client.select().from(a).where(h);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n){let f=await this.executeRaw(drizzleOrm.sql`
|
|
30
|
-
SELECT * FROM kyro_versions
|
|
31
|
-
WHERE collection_slug = ${i}
|
|
32
|
-
AND document_id = ${y.id}
|
|
33
|
-
ORDER BY created_at DESC
|
|
34
|
-
LIMIT 1
|
|
35
|
-
`);if(f.length>0){let E=f[0],T=E.data;for(;typeof T=="string";)try{T=JSON.parse(T);}catch{break}(!T||typeof T!="object"||Array.isArray(T))&&(T={}),y={...y,...T,status:y.status,_hasUnpublishedChanges:E.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),l=this.dialect==="postgres"&&typeof e=="string"?N(e):e,c=[drizzleOrm.eq(a.id,l)];n&&a.tenantId&&c.push(drizzleOrm.eq(a.tenantId,n));let u=await this.client.update(a).set(o).where(drizzleOrm.and(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?N(e):e,o=[drizzleOrm.eq(r.id,a)];s&&r.tenantId&&o.push(drizzleOrm.eq(r.tenantId,s));let l=await this.client.delete(r).where(drizzleOrm.and(...o)).returning();if(l.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(l[0],n)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:drizzleOrm.sql`count(*)`}).from(r);a.length>0&&(o=o.where(drizzleOrm.and(...a)));let l=await o;return Number(l[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let l=this.getTable(i),c=this.client.select().from(l),u=o.fields.find(f=>f.name==="status"),h=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(f=>f.value==="published");!n&&l.status&&h&&(c=c.where(drizzleOrm.eq(l.status,"published")));let g=await c.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n){let f=await this.executeRaw(drizzleOrm.sql`
|
|
36
|
-
SELECT * FROM kyro_versions
|
|
37
|
-
WHERE collection_slug = ${i}
|
|
38
|
-
AND document_id = ${a}
|
|
39
|
-
ORDER BY created_at DESC
|
|
40
|
-
LIMIT 1
|
|
41
|
-
`);if(f.length>0){let E=f[0],T=typeof E.data=="string"?JSON.parse(E.data):E.data;y={...y,...T,status:y.status,_hasUnpublishedChanges:E.status==="draft"};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),l=await this.executeRaw(drizzleOrm.sql`
|
|
42
|
-
SELECT count(*) as count
|
|
43
|
-
FROM kyro_versions
|
|
44
|
-
WHERE collection_slug = ${i}
|
|
45
|
-
AND document_id = ${e}
|
|
46
|
-
AND autosave = 0
|
|
47
|
-
${r&&o.tenantScoped?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
|
|
48
|
-
`),c=parseInt(l[0]?.count||"0");return {docs:(await this.executeRaw(drizzleOrm.sql`
|
|
49
|
-
SELECT *
|
|
50
|
-
FROM kyro_versions
|
|
51
|
-
WHERE collection_slug = ${i}
|
|
52
|
-
AND document_id = ${e}
|
|
53
|
-
AND autosave = 0
|
|
54
|
-
${r&&o.tenantScoped?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
|
|
55
|
-
ORDER BY created_at DESC
|
|
56
|
-
LIMIT ${s}
|
|
57
|
-
OFFSET ${a}
|
|
58
|
-
`)).map(h=>({...h,data:typeof h.data=="string"?JSON.parse(h.data):h.data})),...this.calculatePagination(n,s,c)}}async findVersionByID(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=await this.executeRaw(drizzleOrm.sql`
|
|
59
|
-
SELECT * FROM kyro_versions
|
|
60
|
-
WHERE id = ${t.versionId}
|
|
61
|
-
AND collection_slug = ${t.collection}
|
|
62
|
-
${t.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${t.tenantId}`:drizzleOrm.sql``}
|
|
63
|
-
LIMIT 1
|
|
64
|
-
`);if(e.length===0)return null;let s=e[0];return {...s,data:typeof s.data=="string"?JSON.parse(s.data):s.data}}async createVersion(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=new Date().toISOString();if(t.autosave){let r=await this.executeRaw(drizzleOrm.sql`
|
|
65
|
-
SELECT * FROM kyro_versions
|
|
66
|
-
WHERE collection_slug = ${t.collection}
|
|
67
|
-
AND document_id = ${t.documentId}
|
|
68
|
-
AND autosave = 1
|
|
69
|
-
${t.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${t.tenantId}`:drizzleOrm.sql``}
|
|
70
|
-
LIMIT 1
|
|
71
|
-
`);if(r.length>0)return await this.executeRaw(drizzleOrm.sql`
|
|
72
|
-
UPDATE kyro_versions
|
|
73
|
-
SET data = ${JSON.stringify(t.data)},
|
|
74
|
-
status = ${t.status},
|
|
75
|
-
updated_at = ${e}
|
|
76
|
-
WHERE id = ${r[0].id}
|
|
77
|
-
`),this.findVersionByID({collection:t.collection,versionId:r[0].id,tenantId:t.tenantId})}let s=Math.random().toString(36).substring(2,15),n=typeof t.data=="string"?t.data:JSON.stringify(t.data);if(await this.executeRaw(drizzleOrm.sql`
|
|
78
|
-
INSERT INTO kyro_versions (
|
|
79
|
-
id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
|
|
80
|
-
) VALUES (
|
|
81
|
-
${s}, ${t.collection}, ${t.documentId}, ${t.tenantId&&i.tenantScoped?t.tenantId:null},
|
|
82
|
-
${n}, ${t.status}, ${t.autosave?1:0}, ${t.createdBy||null},
|
|
83
|
-
${t.changeDescription||null}, ${e}, ${e}
|
|
84
|
-
)
|
|
85
|
-
`),!t.autosave){let r=this.getCollection(t.collection);r.versions?.maxPerDoc&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:r.versions.maxPerDoc,tenantId:t.tenantId});}return this.findVersionByID({collection:t.collection,versionId:s,tenantId:t.tenantId})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection);if(t.keepLatest){let s=(await this.executeRaw(drizzleOrm.sql`
|
|
86
|
-
SELECT id FROM kyro_versions
|
|
87
|
-
WHERE collection_slug = ${t.collection}
|
|
88
|
-
AND document_id = ${t.documentId}
|
|
89
|
-
AND autosave = 0
|
|
90
|
-
${t.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${t.tenantId}`:drizzleOrm.sql``}
|
|
91
|
-
ORDER BY created_at DESC
|
|
92
|
-
LIMIT ${t.keepLatest}
|
|
93
|
-
`)).map(n=>n.id);s.length>0&&await this.executeRaw(drizzleOrm.sql`
|
|
94
|
-
DELETE FROM kyro_versions
|
|
95
|
-
WHERE collection_slug = ${t.collection}
|
|
96
|
-
AND document_id = ${t.documentId}
|
|
97
|
-
AND autosave = 0
|
|
98
|
-
AND id NOT IN (${drizzleOrm.sql.join(s.map(n=>drizzleOrm.sql`${n}`),drizzleOrm.sql`, `)})
|
|
99
|
-
`);}else await this.executeRaw(drizzleOrm.sql`
|
|
100
|
-
DELETE FROM kyro_versions
|
|
101
|
-
WHERE collection_slug = ${t.collection}
|
|
102
|
-
AND document_id = ${t.documentId}
|
|
103
|
-
${t.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${t.tenantId}`:drizzleOrm.sql``}
|
|
104
|
-
`);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t,i,e,s){let n=[];s&&i.tenantScoped&&e.tenantId&&n.push(drizzleOrm.eq(e.tenantId,s));for(let[r,a]of Object.entries(t)){let o=r,l=o.toUpperCase();if(o==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=N(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:N(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(c=>typeof c=="string"?N(c):c)}))),l==="AND"&&Array.isArray(a)){let c=a.map(u=>this.buildWhereClause(u,i,e)).flat().filter(Boolean);c.length>0&&n.push(drizzleOrm.and(...c));}else if(l==="OR"&&Array.isArray(a)){let c=a.map(u=>this.buildWhereClause(u,i,e)).flat().filter(Boolean);c.length>0&&n.push(drizzleOrm.or(...c));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=e[o]||e[o.replace(/-/g,"_")]||e[o.replace(/([A-Z])/g,"_$1").toLowerCase()]||(o==="created_at"?e.createdAt:void 0)||(o==="createdAt"?e.created_at:void 0)||(o==="updated_at"?e.updatedAt:void 0)||(o==="updatedAt"?e.updated_at:void 0);if(!c)continue;a.equals!==void 0&&n.push(drizzleOrm.eq(c,a.equals)),a.not_equals!==void 0&&n.push(drizzleOrm.ne(c,a.not_equals)),a.in&&Array.isArray(a.in)&&(a.in.length===0?n.push(drizzleOrm.sql`1 = 0`):n.push(drizzleOrm.inArray(c,a.in))),a.like!==void 0&&(this.dialect==="postgres"?n.push(drizzleOrm.ilike(c,a.like)):n.push(drizzleOrm.like(c,a.like))),a.contains!==void 0&&(this.dialect==="postgres"?n.push(drizzleOrm.ilike(c,`%${a.contains}%`)):n.push(drizzleOrm.like(c,`%${a.contains}%`))),a.greater_than!==void 0&&n.push(drizzleOrm.gt(c,a.greater_than)),a.greater_than_equal!==void 0&&n.push(drizzleOrm.gte(c,a.greater_than_equal)),a.less_than!==void 0&&n.push(drizzleOrm.lt(c,a.less_than)),a.less_than_equal!==void 0&&n.push(drizzleOrm.lte(c,a.less_than_equal));}else {let c=e[o]||e[o.replace(/-/g,"_")]||e[o.replace(/([A-Z])/g,"_$1").toLowerCase()];c&&n.push(drizzleOrm.eq(c,a));}}return n}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let n=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();n!==s.name&&e[n]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[n],delete e[n]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let n=s;if(e[n.name]&&typeof e[n.name]=="string")try{let r=JSON.parse(e[n.name]);e[n.name]=r;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let r=n.blocks||[];e[n.name]=chunkYOJOVQIH_cjs.d(e[n.name],r);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let r of s.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let o=e[s.name][a.name];if(typeof o=="string")try{let l=JSON.parse(o);e[s.name][a.name]=Array.isArray(l)?l.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof l.id=="string"?l.id:String(l.id||"");}catch{}else o&&typeof o=="object"&&(e[s.name][a.name]=Array.isArray(o)?o.map(l=>l&&typeof l=="object"&&typeof l.id=="string"?l.id:String(l||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[s.name]=="string")try{let r=JSON.parse(e[s.name]);if(typeof r=="object"&&r!==null){e[s.name]=r;continue}}catch{}let n={};for(let r of s.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let o=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(a.type==="upload"||a.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(l=>l&&typeof l=="object"&&typeof l.id=="string"?l.id:String(l||"")):typeof o.id=="string"?o.id:String(o.id||""));}n[a.name]=o,delete e[a.name];}e[s.name]=n;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),chunkOXEJCIOA_cjs.a(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
|
|
105
|
-
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
106
|
-
id text PRIMARY KEY,
|
|
107
|
-
collection_slug text NOT NULL,
|
|
108
|
-
document_id text NOT NULL,
|
|
109
|
-
tenant_id text,
|
|
110
|
-
data text NOT NULL,
|
|
111
|
-
status text NOT NULL DEFAULT 'draft',
|
|
112
|
-
autosave integer NOT NULL DEFAULT 0,
|
|
113
|
-
created_by text,
|
|
114
|
-
change_description text,
|
|
115
|
-
created_at text DEFAULT (datetime('now')),
|
|
116
|
-
updated_at text DEFAULT (datetime('now'))
|
|
117
|
-
)
|
|
118
|
-
`:t=`
|
|
119
|
-
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
120
|
-
id text PRIMARY KEY,
|
|
121
|
-
collection_slug text NOT NULL,
|
|
122
|
-
document_id text NOT NULL,
|
|
123
|
-
tenant_id text,
|
|
124
|
-
data text NOT NULL,
|
|
125
|
-
status text NOT NULL,
|
|
126
|
-
autosave integer NOT NULL DEFAULT 0,
|
|
127
|
-
created_by text,
|
|
128
|
-
change_description text,
|
|
129
|
-
created_at text NOT NULL,
|
|
130
|
-
updated_at text NOT NULL
|
|
131
|
-
)
|
|
132
|
-
`,await this.executeRaw(drizzleOrm.sql.raw(t));try{this.dialect==="postgres"?await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new pgCore.PgDialect().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new sqliteCore.SQLiteSyncDialect().sqlToQuery(t);i=n.sql,e=n.params;}else if(t&&typeof t.toSQL=="function"){let n=t.toSQL();i=n.sql,e=n.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let n=s.prepare(i);return (e.length>0?await n.bind(...e).all():await n.all()).results||[]}if(typeof this.client?.execute=="function"){let n=await this.client.execute(t);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}return []}};function fe(m){return new I(m)}exports.a=b;exports.b=j;exports.c=I;exports.d=fe;
|