@kyro-cms/core 0.13.6 → 0.13.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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-A4XM33WO.js → chunk-3RIGRHON.js} +1 -1
- package/dist/{chunk-TG5YQ4PB.cjs → chunk-MCK2QRAU.cjs} +2 -2
- package/dist/{chunk-HACW42ZZ.cjs → chunk-O2SA56P2.cjs} +2 -2
- package/dist/chunk-O6I26T6A.js +3 -0
- package/dist/{chunk-VQWOCGJ2.cjs → chunk-PPGZHOYR.cjs} +1 -1
- package/dist/{chunk-N25DOGLQ.js → chunk-SYE3OS5T.js} +1 -1
- package/dist/{chunk-YLP3EKTQ.js → chunk-TVWHTVLI.js} +1 -1
- package/dist/chunk-UE7DTBD7.cjs +1 -0
- package/dist/chunk-XL64URKD.cjs +2 -0
- package/dist/chunk-YNBJGPIU.js +2 -0
- package/dist/cli/index.cjs +17 -17
- package/dist/cli/index.js +13 -13
- package/dist/index-B_39z2jP.d.cts +217 -0
- package/dist/index-xqpVL2Zq.d.ts +217 -0
- package/dist/index.cjs +13 -13
- package/dist/index.d.cts +2 -31
- package/dist/index.d.ts +2 -31
- package/dist/index.js +14 -14
- package/dist/{mongo-auth-adapter-33M5ENM7.cjs → mongo-auth-adapter-22MV3TI3.cjs} +1 -1
- package/dist/{mongo-auth-adapter-4ITULS2P.js → mongo-auth-adapter-66PWVRZW.js} +1 -1
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.d.cts +3 -130
- package/dist/mongodb/index.d.ts +3 -130
- package/dist/mongodb/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/package.json +2 -1
- package/dist/chunk-CIWLQXB2.js +0 -2
- package/dist/chunk-GDLMPZKD.cjs +0 -2
- package/dist/chunk-NBBAMC2X.cjs +0 -1
- package/dist/chunk-VWXHW74B.js +0 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkPPGZHOYR_cjs=require('./chunk-PPGZHOYR.cjs');require('./chunk-MCK2QRAU.cjs'),require('./chunk-VPBGZW4P.cjs'),require('./chunk-N7CDHWQH.cjs'),require('./chunk-DCKJT247.cjs'),require('./chunk-7KTPBTH5.cjs'),require('./chunk-24W5I6SJ.cjs'),require('./chunk-O2SA56P2.cjs'),require('./chunk-H2IJDTA2.cjs'),require('./chunk-PW6Y5MQL.cjs'),require('./chunk-34LCWI5X.cjs'),require('./chunk-LXTVMP5F.cjs'),require('./chunk-2I2AXTKY.cjs'),require('./chunk-GS4CMYKS.cjs'),require('./chunk-OJBL4CXK.cjs'),require('./chunk-DCFOVCJX.cjs'),require('./chunk-FU76HURF.cjs'),require('./chunk-GWUHIIPO.cjs'),require('./chunk-EG4SRTYS.cjs'),require('./chunk-3A5UO6OQ.cjs'),require('./chunk-23RSKVJP.cjs'),require('./chunk-YOJOVQIH.cjs'),require('./chunk-XL64URKD.cjs'),require('./chunk-UE7DTBD7.cjs'),require('./chunk-O4PPZOVI.cjs'),require('./chunk-JJY2F6NL.cjs'),require('./chunk-OXEJCIOA.cjs'),require('./chunk-KOSR7235.cjs'),require('./chunk-JHFD3IAU.cjs');function r(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function n(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await chunkPPGZHOYR_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var u=async e=>{if(await chunkPPGZHOYR_cjs.b(e),!await o())return n();let s=await chunkPPGZHOYR_cjs.a.getGraphQL().fetch(e.request,e.locals);return r(s)},d=async e=>{if(await chunkPPGZHOYR_cjs.b(e),!await o())return n();let s=await chunkPPGZHOYR_cjs.a.getGraphQL().fetch(e.request,e.locals);return r(s)};exports.GET=d;exports.POST=u;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b,a}from'./chunk-
|
|
1
|
+
import {b,a}from'./chunk-TVWHTVLI.js';import'./chunk-SYE3OS5T.js';import'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.js';import'./chunk-GTAKGVUY.js';import'./chunk-5RBGM5N5.js';import'./chunk-3RIGRHON.js';import'./chunk-FAG2645P.js';import'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';import'./chunk-SBFVITY2.js';import'./chunk-5I3BM5TV.js';import'./chunk-W5GDZG64.js';import'./chunk-OPKZYQV7.js';import'./chunk-3N34WXBS.js';import'./chunk-OXH6CANN.js';import'./chunk-TJ6N5ZPZ.js';import'./chunk-JXJTFBHG.js';import'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';import'./chunk-O6I26T6A.js';import'./chunk-YNBJGPIU.js';import'./chunk-YNSKDTFG.js';import'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
function r(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function n(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var d=async e=>{if(await b(e),!await o())return n();let s=await a.getGraphQL().fetch(e.request,e.locals);return r(s)},f=async e=>{if(await b(e),!await o())return n();let s=await a.getGraphQL().fetch(e.request,e.locals);return r(s)};export{f as GET,d as POST};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkPPGZHOYR_cjs=require('./chunk-PPGZHOYR.cjs');require('./chunk-MCK2QRAU.cjs'),require('./chunk-VPBGZW4P.cjs'),require('./chunk-N7CDHWQH.cjs'),require('./chunk-DCKJT247.cjs'),require('./chunk-7KTPBTH5.cjs'),require('./chunk-24W5I6SJ.cjs'),require('./chunk-O2SA56P2.cjs'),require('./chunk-H2IJDTA2.cjs'),require('./chunk-PW6Y5MQL.cjs'),require('./chunk-34LCWI5X.cjs'),require('./chunk-LXTVMP5F.cjs'),require('./chunk-2I2AXTKY.cjs'),require('./chunk-GS4CMYKS.cjs'),require('./chunk-OJBL4CXK.cjs'),require('./chunk-DCFOVCJX.cjs'),require('./chunk-FU76HURF.cjs'),require('./chunk-GWUHIIPO.cjs'),require('./chunk-EG4SRTYS.cjs'),require('./chunk-3A5UO6OQ.cjs'),require('./chunk-23RSKVJP.cjs'),require('./chunk-YOJOVQIH.cjs'),require('./chunk-XL64URKD.cjs'),require('./chunk-UE7DTBD7.cjs'),require('./chunk-O4PPZOVI.cjs'),require('./chunk-JJY2F6NL.cjs'),require('./chunk-OXEJCIOA.cjs'),require('./chunk-KOSR7235.cjs'),require('./chunk-JHFD3IAU.cjs');function r(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var n={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await chunkPPGZHOYR_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??n.trpcEnabled}catch{return true}}var l=async e=>(await chunkPPGZHOYR_cjs.b(e),await s()?chunkPPGZHOYR_cjs.a.getTRPC().fetch(e.request,e.locals):r());exports.ALL=l;
|
package/dist/api-handler-trpc.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b,a}from'./chunk-
|
|
1
|
+
import {b,a}from'./chunk-TVWHTVLI.js';import'./chunk-SYE3OS5T.js';import'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.js';import'./chunk-GTAKGVUY.js';import'./chunk-5RBGM5N5.js';import'./chunk-3RIGRHON.js';import'./chunk-FAG2645P.js';import'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';import'./chunk-SBFVITY2.js';import'./chunk-5I3BM5TV.js';import'./chunk-W5GDZG64.js';import'./chunk-OPKZYQV7.js';import'./chunk-3N34WXBS.js';import'./chunk-OXH6CANN.js';import'./chunk-TJ6N5ZPZ.js';import'./chunk-JXJTFBHG.js';import'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';import'./chunk-O6I26T6A.js';import'./chunk-YNBJGPIU.js';import'./chunk-YNSKDTFG.js';import'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
function r(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var n={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??n.trpcEnabled}catch{return true}}var p=async e=>(await b(e),await s()?a.getTRPC().fetch(e.request,e.locals):r());export{p as ALL};
|
package/dist/api-handler.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkPPGZHOYR_cjs=require('./chunk-PPGZHOYR.cjs');require('./chunk-MCK2QRAU.cjs'),require('./chunk-VPBGZW4P.cjs'),require('./chunk-N7CDHWQH.cjs'),require('./chunk-DCKJT247.cjs'),require('./chunk-7KTPBTH5.cjs'),require('./chunk-24W5I6SJ.cjs'),require('./chunk-O2SA56P2.cjs'),require('./chunk-H2IJDTA2.cjs'),require('./chunk-PW6Y5MQL.cjs'),require('./chunk-34LCWI5X.cjs'),require('./chunk-LXTVMP5F.cjs'),require('./chunk-2I2AXTKY.cjs'),require('./chunk-GS4CMYKS.cjs'),require('./chunk-OJBL4CXK.cjs'),require('./chunk-DCFOVCJX.cjs'),require('./chunk-FU76HURF.cjs'),require('./chunk-GWUHIIPO.cjs'),require('./chunk-EG4SRTYS.cjs'),require('./chunk-3A5UO6OQ.cjs'),require('./chunk-23RSKVJP.cjs'),require('./chunk-YOJOVQIH.cjs'),require('./chunk-XL64URKD.cjs'),require('./chunk-UE7DTBD7.cjs'),require('./chunk-O4PPZOVI.cjs'),require('./chunk-JJY2F6NL.cjs'),require('./chunk-OXEJCIOA.cjs'),require('./chunk-KOSR7235.cjs'),require('./chunk-JHFD3IAU.cjs');Object.defineProperty(exports,"ALL",{enumerable:true,get:function(){return chunkPPGZHOYR_cjs.c}});Object.defineProperty(exports,"createKyroHandler",{enumerable:true,get:function(){return chunkPPGZHOYR_cjs.d}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunkPPGZHOYR_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunkPPGZHOYR_cjs.b}});
|
package/dist/api-handler.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{c as ALL,d as createKyroHandler,a as kyroInstance,b as warmKyroInstance}from'./chunk-
|
|
1
|
+
export{c as ALL,d as createKyroHandler,a as kyroInstance,b as warmKyroInstance}from'./chunk-TVWHTVLI.js';import'./chunk-SYE3OS5T.js';import'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.js';import'./chunk-GTAKGVUY.js';import'./chunk-5RBGM5N5.js';import'./chunk-3RIGRHON.js';import'./chunk-FAG2645P.js';import'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';import'./chunk-SBFVITY2.js';import'./chunk-5I3BM5TV.js';import'./chunk-W5GDZG64.js';import'./chunk-OPKZYQV7.js';import'./chunk-3N34WXBS.js';import'./chunk-OXH6CANN.js';import'./chunk-TJ6N5ZPZ.js';import'./chunk-JXJTFBHG.js';import'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';import'./chunk-O6I26T6A.js';import'./chunk-YNBJGPIU.js';import'./chunk-YNSKDTFG.js';import'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import'./chunk-RLW6AQF2.js';import {createStorage}from'unstorage';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
async function d(m={}){let{namespace:o="kyro",ttl:a}=m,{default:c}=await import('unstorage/drivers/indexedb'),e=createStorage({driver:c({dbName:"kyro-cms",storeName:o})}),i=o?`${o}:`:"";return {storage:{getItem:async t=>{let r=`${i}${t}`,s=await e.getItem(r);if(s==null)return null;try{let n=JSON.parse(s);return n.expiry&&Date.now()>n.expiry?(await e.removeItem(r),null):n.value}catch{return s}},setItem:async(t,r)=>{let s=`${i}${t}`,n=JSON.stringify(a?{value:r,expiry:Date.now()+a}:{value:r});await e.setItem(s,n);},removeItem:async t=>{await e.removeItem(`${i}${t}`);}},cleanup:async()=>{await e.dispose?.();}}}export{d as createBrowserStorage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';require('./chunk-JHFD3IAU.cjs');var unstorage=require('unstorage');async function y(m={}){let{namespace:o="kyro",ttl:a}=m,{default:c}=await import('unstorage/drivers/indexedb'),e=unstorage.createStorage({driver:c({dbName:"kyro-cms",storeName:o})}),i=o?`${o}:`:"";return {storage:{getItem:async t=>{let r=`${i}${t}`,s=await e.getItem(r);if(s==null)return null;try{let n=JSON.parse(s);return n.expiry&&Date.now()>n.expiry?(await e.removeItem(r),null):n.value}catch{return s}},setItem:async(t,r)=>{let s=`${i}${t}`,n=JSON.stringify(a?{value:r,expiry:Date.now()+a}:{value:r});await e.setItem(s,n);},removeItem:async t=>{await e.removeItem(`${i}${t}`);}},cleanup:async()=>{await e.dispose?.();}}}exports.createBrowserStorage=y;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a}from'./chunk-FAG2645P.js';import {a as a$8}from'./chunk-IIVBEZC2.js';import {a as a$3}from'./chunk-I22MSXGL.js';import {k,i,g,s,o,j,n,q,r,m}from'./chunk-SBFVITY2.js';import {p,q as q$1}from'./chunk-5I3BM5TV.js';import {c,a as a$9,o as o$1,b as b$1}from'./chunk-OPKZYQV7.js';import {a as a$5,f,g as g$1,c as c$1,b as b$2,d}from'./chunk-3N34WXBS.js';import {a as a$1}from'./chunk-JXJTFBHG.js';import {a as a$6}from'./chunk-IIPSXKNV.js';import {a as a$2,b}from'./chunk-WLSVS3NC.js';import {a as a$7}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-FAG2645P.js';import {a as a$8}from'./chunk-IIVBEZC2.js';import {a as a$3}from'./chunk-I22MSXGL.js';import {k,i,g,s,o,j,n,q,r,m}from'./chunk-SBFVITY2.js';import {p,q as q$1}from'./chunk-5I3BM5TV.js';import {c,a as a$9,o as o$1,b as b$1}from'./chunk-OPKZYQV7.js';import {a as a$5,f,g as g$1,c as c$1,b as b$2,d}from'./chunk-3N34WXBS.js';import {a as a$1}from'./chunk-JXJTFBHG.js';import {a as a$6}from'./chunk-IIPSXKNV.js';import {a as a$2,b}from'./chunk-WLSVS3NC.js';import {a as a$7}from'./chunk-YNBJGPIU.js';import {a as a$a}from'./chunk-NGNXOXI5.js';import {a as a$4}from'./chunk-O4RKZQYQ.js';import {Hono}from'hono';import Te,{join,resolve,basename,extname}from'path';import {randomBytes,createHmac,createHash}from'crypto';import {verify,sign}from'hono/jwt';import {existsSync,readFileSync}from'fs';import {mkdir,readdir,stat,rename,unlink,writeFile}from'fs/promises';import ar from'process';import {S3Client,ListObjectsV2Command,DeleteObjectsCommand,DeleteObjectCommand,PutObjectCommand,HeadObjectCommand,CopyObjectCommand}from'@aws-sdk/client-s3';import {NodeHttpHandler}from'@smithy/node-http-handler';import'stream';import {zodToJsonSchema}from'zod-to-json-schema';import Wt from'bcryptjs';import {sql}from'drizzle-orm';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
function wt(i){let{db:t,userLookup:s$1}=i;return async function(a){let n=c$1(a);if(n&&t){let p=await b$2(n,t,s$1);if(p.valid&&p.user)return {user:p.user,tenantContext:yt(p.user),apiKeyContext:d(p),status:200,authType:"apikey"};if(p.error)return {status:401,error:p.error}}let c=g(a);if(c)try{let p=await m(c);if(!p.valid)return {status:401,error:p.reason||"Session invalid"};let o=await s(a);if(o){let u=s$1?await s$1(o.userId):null;if(u)return {user:u,tenantContext:yt(u),status:200,authType:"session"}}}catch(p){console.error("Session validation error:",p);}return {status:401,error:"Authentication required"}}}function yt(i){return {tenantId:i.tenantId||"default",userId:i.id||"anonymous",role:i.role||"guest",roles:[i.role||"guest"],permissions:[],isSuperAdmin:i.role==="super_admin"}}var he=class{storage=new Map;userStorage=new Map;limits;userLimits;constructor(e,t){this.limits={...Vt,...e},this.userLimits=t||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${e}:${t}`}getUserKey(e,t,s){return `user:${e}:${t}:${s}`}cleanupOldEntries(e,t){let r=Date.now()-t;for(;e.length>0&&e[0].timestamp<r;)e.shift();}async check(e,t){let s=this.limits[e]||this.limits["api:general"],r=this.getKey(e,t),a=this.storage.get(r);a||(a=[],this.storage.set(r,a)),this.cleanupOldEntries(a,s.window);let n=Date.now(),c=a.reduce((p,o)=>p+o.count,0);if(a.push({timestamp:n,count:1}),c>=s.max){let o=a.reduce((u,d)=>u.timestamp<d.timestamp?u:d,a[0]).timestamp+s.window;return {allowed:false,remaining:0,resetAt:o,retryAfter:Math.ceil((o-n)/1e3)}}return {allowed:true,remaining:s.max-c-1,resetAt:n+s.window}}async checkUser(e,t,s){let r=this.userLimits[e]||this.userLimits["user:api"],a=this.userStorage.get(t),n=[];a?n=a.get(this.getKey(e,s))||[]:(this.userStorage.has(t)||this.userStorage.set(t,new Map),this.userStorage.get(t).set(this.getKey(e,s),n)),this.cleanupOldEntries(n,r.window);let c=Date.now(),p=n.reduce((o,u)=>o+u.count,0);if(n.push({timestamp:c,count:1}),p>=r.max){let u=n.reduce((d,m)=>d.timestamp<m.timestamp?d:m,n[0]).timestamp+r.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-c)/1e3)}}return {allowed:true,remaining:r.max-p-1,resetAt:c+r.window}}async reset(e,t){let s=this.getKey(e,t);this.storage.delete(s);}async resetUser(e,t,s){let r=this.userStorage.get(t);if(r){let a=this.getKey(e,s);r.delete(a);}}async getStatus(e,t){let s=this.limits[e]||this.limits["api:general"],r=this.getKey(e,t),a=this.storage.get(r);a||(a=[],this.storage.set(r,a)),this.cleanupOldEntries(a,s.window);let n=Date.now(),c=a.reduce((p,o)=>p+o.count,0);return {count:c,limit:s.max,remaining:Math.max(0,s.max-c),resetAt:n+s.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}},Vt={"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}};var ke={retentionDays:30};var bt=class{redis;prefix;retentionDays;constructor(e,t=30,s="kyro:audit:"){this.redis=e,this.prefix=s,this.retentionDays=t;}async log(e){let t=randomBytes(16).toString("hex"),s=new Date,r={...e,id:t,timestamp:s},a=this.getKeyForDate(s),n=`${this.prefix}log:${t}`;await this.redis.hset(n,this.serializeLog(r)),await this.redis.expire(n,this.retentionDays*24*60*60+3600),await this.redis.zadd(a,s.getTime(),t),await this.redis.expire(a,this.retentionDays*24*60*60+3600);let c=e.userId?`${this.prefix}user:${e.userId}`:null;return c&&(await this.redis.zadd(c,s.getTime(),t),await this.redis.expire(c,this.retentionDays*24*60*60+3600)),t}async get(e){let t=`${this.prefix}log:${e}`,s=await this.redis.hgetall(t);return !s||Object.keys(s).length===0?null:this.deserializeLog(s)}async query(e={}){let{limit:t=50,offset:s=0}=e,r=[];if(e.userId)r.push(`${this.prefix}user:${e.userId}`);else if(e.startDate||e.endDate)r=this.getKeysForDateRange(e.startDate,e.endDate);else {let p=new Date;r=this.getKeysForDateRange(new Date(p.getTime()-this.retentionDays*24*60*60*1e3),p);}let a=[];for(let p of r){let o=await this.redis.zrange(p,0,-1,"WITHSCORES");for(let u=0;u<o.length;u+=2)a.push([o[u],parseInt(o[u+1],10)]);}a.sort((p,o)=>o[1]-p[1]);let n=a.length;a=a.slice(s,s+t);let c=[];for(let[p]of a){let o=await this.get(p);o&&this.matchesFilter(o,e)&&c.push(o);}return {logs:c,total:n}}async getRecent(e=50){let t=[],s=new Date,r=this.getKeysForDateRange(new Date(s.getTime()-10080*60*1e3),s),a=[];for(let n of r){let c=await this.redis.zrange(n,0,-1,"WITHSCORES");for(let p=0;p<c.length;p+=2)a.push([c[p],parseInt(c[p+1],10)]);}a.sort((n,c)=>c[1]-n[1]);for(let[n]of a.slice(0,e)){let c=await this.get(n);c&&t.push(c);}return t}async getUserActivity(e,t=50){let s=`${this.prefix}user:${e}`,r=await this.redis.zrange(s,0,t-1),a=[];for(let n of r){let c=await this.get(n);c&&a.push(c);}return a}async getStats(e,t){let s=this.getKeysForDateRange(e||new Date(Date.now()-2592e6),t||new Date),r={},a=0,n=0,c=0,p=new Set;for(let o of s){let u=await this.redis.zrange(o,0,-1);for(let d of u){let m=await this.get(d);m&&(a++,r[m.action]=(r[m.action]||0)+1,m.success&&c++,m.action==="login_failed"&&n++,m.userId&&p.add(m.userId));}}return {totalEvents:a,byAction:r,successRate:a>0?c/a:1,failedLogins:n,uniqueUsers:p}}async cleanup(){let e=Date.now()-this.retentionDays*24*60*60*1e3,t=await this.redis.keys(`${this.prefix}date:*`),s=0;for(let r of t){let a=await this.redis.zrangebyscore(r,0,e);for(let n of a)await this.redis.del(`${this.prefix}log:${n}`),s++;await this.redis.zremrangebyscore(r,0,e);}return s}getKeyForDate(e){let t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return `${this.prefix}date:${t}-${s}-${r}`}getKeysForDateRange(e,t){let s=[],r=e||new Date(Date.now()-this.retentionDays*24*60*60*1e3),a=t||new Date,n=new Date(r);for(;n<=a;)s.push(this.getKeyForDate(n)),n.setDate(n.getDate()+1);return s}matchesFilter(e,t){return !(t.action&&!(Array.isArray(t.action)?t.action:[t.action]).includes(e.action)||t.resource&&e.resource!==t.resource||t.resourceId&&e.resourceId!==t.resourceId||t.success!==void 0&&e.success!==t.success)}serializeLog(e){let t={id:e.id,timestamp:new Date(e.timestamp).toISOString(),action:e.action,resource:e.resource,success:e.success?"1":"0"};return e.userId&&(t.userId=e.userId),e.userEmail&&(t.userEmail=e.userEmail),e.role&&(t.role=e.role),e.resourceId&&(t.resourceId=e.resourceId),e.ipAddress&&(t.ipAddress=e.ipAddress),e.userAgent&&(t.userAgent=e.userAgent),e.error&&(t.error=e.error),e.changes&&(t.changes=JSON.stringify(e.changes)),e.metadata&&(t.metadata=JSON.stringify(e.metadata)),t}deserializeLog(e){return {id:e.id,timestamp:new Date(e.timestamp),action:e.action,userId:e.userId,userEmail:e.userEmail,role:e.role,resource:e.resource,resourceId:e.resourceId,ipAddress:e.ipAddress,userAgent:e.userAgent,success:e.success==="1",error:e.error,changes:e.changes?JSON.parse(e.changes):void 0,metadata:e.metadata?JSON.parse(e.metadata):void 0}}};function $r(i){return {ipAddress:i.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||i.headers.get("x-real-ip")||"unknown",userAgent:i.headers.get("user-agent")||"unknown"}}function te(i){return {ipAddress:i.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||i.headers.get("x-real-ip")||"unknown",userAgent:i.headers.get("user-agent")||"unknown"}}var At=class{logs=[];retentionDays;constructor(e=ke.retentionDays){this.retentionDays=e;}async log(e){let t=randomBytes(16).toString("hex"),r={...e,id:t,timestamp:new Date};return this.logs.push(r),this.cleanupOldLogs(),t}async get(e){return this.logs.find(t=>t.id===e)||null}async query(e={}){let{limit:t=50,offset:s=0}=e,r=[...this.logs];if(e.userId&&(r=r.filter(o=>o.userId===e.userId)),e.action){let o=Array.isArray(e.action)?e.action:[e.action];r=r.filter(u=>o.includes(u.action));}e.resource&&(r=r.filter(o=>o.resource===e.resource)),e.resourceId&&(r=r.filter(o=>o.resourceId===e.resourceId)),e.success!==void 0&&(r=r.filter(o=>o.success===e.success));let a=e.startDate,n=e.endDate;a!==void 0&&(r=r.filter(o=>o.timestamp>=a)),n!==void 0&&(r=r.filter(o=>o.timestamp<=n)),r.sort((o,u)=>u.timestamp.getTime()-o.timestamp.getTime());let c=r.length;return {logs:r.slice(s,s+t),total:c}}async getRecent(e=50){let t=new Date(Date.now()-6048e5);return this.logs.filter(r=>r.timestamp>=t).sort((r,a)=>a.timestamp.getTime()-r.timestamp.getTime()).slice(0,e)}async getUserActivity(e,t=50){return this.logs.filter(r=>r.userId===e).sort((r,a)=>a.timestamp.getTime()-r.timestamp.getTime()).slice(0,t)}async getStats(e,t){let s=e||new Date(Date.now()-2592e6),r=t||new Date,a=this.logs.filter(d=>d.timestamp>=s&&d.timestamp<=r),n={},c=0,p=0,o=0,u=new Set;for(let d of a){c++;let m=d.action;n[m]=(n[m]||0)+1,d.success&&o++,d.action==="login_failed"&&p++,d.userId&&u.add(d.userId);}return {totalEvents:c,byAction:n,successRate:c>0?o/c:1,failedLogins:p,uniqueUsers:u}}async cleanup(){let e=new Date(Date.now()-this.retentionDays*24*60*60*1e3),t=this.logs.length;return this.logs=this.logs.filter(s=>s.timestamp>=e),t-this.logs.length}cleanupOldLogs(){let e=new Date(Date.now()-this.retentionDays*24*60*60*1e3);this.logs.length;this.logs=this.logs.filter(s=>s.timestamp>=e);}};var ye=class{authAdapter;email;passwordPolicy;lockout;rateLimiter;auditLogger;baseUrl;emailVerificationRequired;jwtSecret;constructor(e){this.authAdapter=e.redis,this.email=e.email,this.passwordPolicy=e.passwordPolicy||new a,this.lockout=e.lockout,this.rateLimiter=e.rateLimiter,this.auditLogger=e.auditLogger,this.baseUrl=e.baseUrl||"http://localhost:4321",this.emailVerificationRequired=e.emailVerificationRequired??true,this.jwtSecret=e.jwtSecret||"kyro-default-secret-key-change-me-in-production";}getBaseUrl(e){if(e)try{let t=e.headers.get("x-forwarded-proto")||(e.url.startsWith("https")?"https":"http"),s=e.headers.get("x-forwarded-host")||e.headers.get("host");return s?`${t}://${s}`:new URL(e.url).origin}catch{}return process.env.KYRO_BASE_URL||process.env.SERVER_URL||process.env.PUBLIC_URL||process.env.SITE_URL||this.baseUrl||"http://localhost:4321"}async register(e){let{ipAddress:t,userAgent:s}=te(e);if(this.rateLimiter){let r=await this.rateLimiter.check("auth:register",t);if(!r.allowed)return this.rateLimitResponse(r)}try{let r=await e.json();if(!r.email||!r.password)return this.errorResponse("Email and password are required",400);if(r.password!==r.confirmPassword)return this.errorResponse("Passwords do not match",400);let a=this.passwordPolicy.validate(r.password);if(!a.valid)return this.errorResponse(a.errors.join(". "),400);let n=await this.authAdapter.findUserByEmail(r.email);if(n){if(!n.emailVerified&&this.emailVerificationRequired&&this.email){let o=(await this.authAdapter.createEmailVerificationToken?.(n.id))?.token||randomBytes(32).toString("hex"),d=`${this.getBaseUrl(e)}/admin/auth/verify-email?token=${o}`,m=this.email.getTemplates().verifyEmail(d,r.email);return await this.email.send({to:r.email,...m}),this.jsonResponse({success:!0,message:"An unverified account already exists with this email. We have resent the confirmation link to your inbox.",requiresVerification:!0},200)}return this.errorResponse("Email already registered",400)}let c=await this.authAdapter.createUser({email:r.email,password:r.password,role:r.role||"customer",tenantId:r.tenantId});if(this.emailVerificationRequired&&this.email){let p=randomBytes(32).toString("hex"),u=`${this.getBaseUrl(e)}/admin/auth/verify-email?token=${p}`;await this.authAdapter.createSession(c.id,{ipAddress:t,userAgent:s});let d=this.email.getTemplates().verifyEmail(u,r.email);await this.email.send({to:r.email,...d});}return this.auditLogger&&await this.auditLogger.log({action:"register",userId:c.id,userEmail:c.email,resource:"auth",ipAddress:t,userAgent:s,success:!0}),this.jsonResponse({success:!0,message:"Registration successful",user:this.sanitizeUser(c),requiresVerification:this.emailVerificationRequired&&!!this.email},201)}catch(r){return console.error("[AuthRoutes.register] Registration error:",r),this.errorResponse("Registration failed",500)}}async login(e){let{ipAddress:t,userAgent:s}=te(e);if(this.rateLimiter){let r=await this.rateLimiter.check("auth:login",t);if(!r.allowed)return this.rateLimitResponse(r)}try{let r=await e.json();if(!r.email||!r.password)return this.errorResponse("Email and password are required",400);let a=await this.authAdapter.findUserByEmail(r.email);if(!a)return await this.recordFailedLogin(t,s),this.errorResponse("Invalid credentials",401);if(a.locked)return this.auditLogger&&await this.auditLogger.log({action:"login_failed",userId:a.id,userEmail:a.email,resource:"auth",ipAddress:t,userAgent:s,success:!1,error:"Account locked"}),this.errorResponse("Account locked. Contact an administrator.",403);if(this.lockout){let u=await this.lockout.checkLockout(a.id);if(u.locked)return this.auditLogger&&await this.auditLogger.log({action:"login_failed",userId:a.id,userEmail:a.email,resource:"auth",ipAddress:t,userAgent:s,success:!1,error:"Account locked"}),this.errorResponse(`Account locked. Try again in ${Math.ceil((u.lockedUntil.getTime()-Date.now())/6e4)} minutes`,423)}let n=await this.authAdapter.verifyPassword(r.email,r.password);if(!n)return await this.recordFailedLogin(t,s,a.id,a.email),this.errorResponse("Invalid credentials",401);if(this.emailVerificationRequired&&n.emailVerified===!1){if(this.email){let d=(await this.authAdapter.createEmailVerificationToken?.(n.id))?.token||randomBytes(32).toString("hex"),y=`${this.getBaseUrl(e)}/admin/auth/verify-email?token=${d}`,l=this.email.getTemplates().verifyEmail(y,n.email);await this.email.send({to:n.email,...l});}return this.errorResponse("Your email address is not verified yet. We have sent a new confirmation link to your email inbox.",403)}this.lockout&&await this.lockout.resetAttempts(a.id),this.auditLogger&&await this.auditLogger.log({action:"login",userId:a.id,userEmail:a.email,role:a.role,resource:"auth",ipAddress:t,userAgent:s,success:!0}),await this.authAdapter.updateUser(a.id,{lastLogin:new Date().toISOString()});let c=await k({id:a.id,email:a.email,role:a.role,tenantId:a.tenantId});if(this.email&&a.email){let u=new Date().toLocaleString(),d=this.email.getTemplates().newLogin(t,u,a.email,void 0,s);this.email.send({to:a.email,...d}).catch(m=>console.error("Failed to send newLogin email:",m));}let p={success:!0,user:this.sanitizeUser(a)},o=this.jsonResponse(p);return i(o,c)}catch(r){return console.error("[Auth] Login error:",r),this.errorResponse("Login failed",500)}}async logout(e){let t=g(e);if(!t)return this.errorResponse("No session to logout",401);let{ipAddress:s$1,userAgent:r}=te(e);try{let a=await s(e);a&&(await o(t),this.auditLogger&&await this.auditLogger.log({action:"logout",userId:a.userId,userEmail:a.email,resource:"auth",ipAddress:s$1,userAgent:r,success:!0}));let n=this.jsonResponse({success:!0,message:"Logged out successfully"});return j(n)}catch{return this.errorResponse("Logout failed",500)}}async refresh(e){try{let t=g(e);if(!t)return this.errorResponse("Not authenticated",401);let s=await n(t,e);return s?this.jsonResponse({success:!0,expiresAt:s.expiresAt}):this.errorResponse("Session not found",404)}catch(t){return console.error("[Auth] Session refresh error:",t),this.errorResponse("Session refresh failed",500)}}async me(e){let t=await s(e);return t?this.jsonResponse({success:true,user:{id:t.userId,email:t.email,role:t.role,tenantId:t.tenantId}}):this.errorResponse("Not authenticated",401)}async changePassword(e){let t=await s(e);if(!t)return this.errorResponse("Not authenticated",401);let{ipAddress:s$1,userAgent:r}=te(e);try{let a=await e.json(),{currentPassword:n,newPassword:c,confirmPassword:p}=a;if(!n||!c)return this.errorResponse("Current and new password required",400);if(c!==p)return this.errorResponse("Passwords do not match",400);let o=this.passwordPolicy.validate(c);if(!o.valid)return this.errorResponse(o.errors.join(". "),400);let u=await this.authAdapter.findUserById(t.userId);if(!u)return this.errorResponse("User not found",404);if(!(u.passwordHash?await this.authAdapter.verifyPassword(n,u.passwordHash):!1))return this.errorResponse("Current password is incorrect",401);let m=await this.authAdapter.getPasswordHistory?.(u.id,5);if(await this.authAdapter.isPasswordInHistory?.(c,u.id,5))return this.errorResponse("Password was recently used. Please choose a different password",400);let l=await this.authAdapter.hashPassword(c);if(u.passwordHash&&await this.authAdapter.addPasswordToHistory?.(u.id,u.passwordHash),await this.authAdapter.updateUser(u.id,{passwordHash:l}),await this.authAdapter.deleteUserSessions(u.id),this.email&&this.email.getTemplates){let g=this.email.getTemplates().passwordChanged(u.email,void 0,s$1,r);await this.email.send({to:u.email,...g});}return this.auditLogger&&await this.auditLogger.log({action:"password_change",userId:u.id,userEmail:u.email,resource:"auth",ipAddress:s$1,userAgent:r,success:!0}),this.jsonResponse({success:!0,message:"Password changed successfully"})}catch{return this.errorResponse("Password change failed",500)}}async forgotPassword(e){let{ipAddress:t,userAgent:s}=te(e);if(this.rateLimiter){let r=await this.rateLimiter.check("auth:forgot",t);if(!r.allowed)return this.rateLimitResponse(r)}try{let r=await e.json(),{email:a}=r;if(!a)return this.errorResponse("Email required",400);let n=await this.authAdapter.findUserByEmail(a);if(!n)return this.jsonResponse({success:!0,message:"If the email exists, a reset link has been sent"});if(this.email){let c=randomBytes(32).toString("hex");if(this.authAdapter.createPasswordResetToken){let d=await this.authAdapter.createPasswordResetToken(n.email);d.token&&(c=d.token);}let o=`${this.getBaseUrl(e)}/admin/auth/reset-password?token=${c}`,u=this.email.getTemplates().resetPassword(o,n.email);await this.email.send({to:n.email,...u});}return this.auditLogger&&await this.auditLogger.log({action:"password_reset",userId:n.id,userEmail:n.email,resource:"auth",ipAddress:t,userAgent:s,success:!0}),this.jsonResponse({success:!0,message:"If the email exists, a reset link has been sent"})}catch{return this.errorResponse("Password reset request failed",500)}}async resetPassword(e){let{ipAddress:t}=te(e);if(this.rateLimiter){let r=await this.rateLimiter.check("auth:reset",t);if(!r.allowed)return this.rateLimitResponse(r)}try{let r=await e.json(),{token:a,newPassword:n,confirmPassword:c}=r;if(!a||!n)return this.errorResponse("Reset token and new password are required",400);if(n!==c)return this.errorResponse("Passwords do not match",400);let p=this.passwordPolicy.validate(n);if(!p.valid)return this.errorResponse(p.errors.join(". "),400);if(this.authAdapter.resetPasswordWithToken){let o=await this.authAdapter.resetPasswordWithToken(a,n);if(!o.success)return this.errorResponse(o.error||"Password reset failed or token expired",400)}return this.jsonResponse({success:!0,message:"Password reset successful. You can now log in with your new password."})}catch(r){return console.error("[AuthRoutes.resetPassword] Error:",r),this.errorResponse("Password reset failed",500)}}async verifyEmail(e){let s=new URL(e.url).searchParams.get("token");if(!s)return this.errorResponse("Verification token required",400);try{if(this.authAdapter.verifyEmailToken){let r=await this.authAdapter.verifyEmailToken(s);if(!r.success)return this.errorResponse(r.error||"Invalid or expired verification token",400);if(r.userId&&this.email){let a=await this.authAdapter.findUserById(r.userId);if(a){let n=this.email.getTemplates().welcome(a.email);await this.email.send({to:a.email,...n});}}}return this.jsonResponse({success:!0,message:"Email address verified successfully"})}catch(r){return console.error("[AuthRoutes.verifyEmail] Error:",r),this.errorResponse("Email verification failed",500)}}async recordFailedLogin(e,t,s,r){if(this.lockout){let a=await this.lockout.recordFailedAttempt(s||e);if(a.locked&&a.totalAttempts===this.lockout.getConfig().maxAttempts&&this.email&&r){let n=Math.ceil(this.lockout.getConfig().lockDuration/6e4),c=this.email.getTemplates().accountLocked(a.totalAttempts,n,r,void 0,e,t);this.email.send({to:r,...c}).catch(p=>console.error("Failed to send accountLocked email:",p));}}this.auditLogger&&await this.auditLogger.log({action:"login_failed",userId:s,userEmail:r,resource:"auth",ipAddress:e,userAgent:t,success:false,error:"Invalid credentials"});}sanitizeUser(e){let{passwordHash:t,...s}=e;return s}jsonResponse(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Cache-Control":"no-store, no-cache, must-revalidate, max-age=0"}})}async listSessions(e){let t=await s(e);if(!t)return this.errorResponse("Not authenticated",401);try{let s=await q(t.userId,g(e)??void 0);return this.jsonResponse({sessions:s})}catch(s){return console.error("[AuthRoutes.listSessions] Error:",s),this.errorResponse("Failed to list sessions",500)}}async revokeSession(e,t){let s$1=await s(e);if(!s$1)return this.errorResponse("Not authenticated",401);try{let a=(await q(s$1.userId)).find(n=>n.id===t);return a?a.currentSession?this.errorResponse("Cannot revoke current session",400):(await o(t),this.jsonResponse({success:!0,message:"Session revoked"})):this.errorResponse("Session not found",404)}catch(r){return console.error("[AuthRoutes.revokeSession] Error:",r),this.errorResponse("Failed to revoke session",500)}}async revokeOtherSessions(e){let t=await s(e);if(!t)return this.errorResponse("Not authenticated",401);try{let s=await q(t.userId),r=g(e);for(let a of s)a.currentSession||await o(a.id);return this.jsonResponse({success:!0,message:"Other sessions revoked"})}catch(s){return console.error("[AuthRoutes.revokeOtherSessions] Error:",s),this.errorResponse("Failed to revoke sessions",500)}}async renameSession(e,t){let s$1=await s(e);if(!s$1)return this.errorResponse("Not authenticated",401);try{if(!(await q(s$1.userId)).find(p=>p.id===t))return this.errorResponse("Session not found",404);let n=await e.json(),{name:c}=n;return !c||typeof c!="string"||c.trim().length===0?this.errorResponse("Invalid session name",400):(await r(t,c.trim()),this.jsonResponse({success:!0,message:"Session renamed"}))}catch(r){return console.error("[AuthRoutes.renameSession] Error:",r),this.errorResponse("Failed to rename session",500)}}async refreshSession(e){let t=g(e);if(!t)return this.errorResponse("No session",401);try{let{refreshSession:s}=await import('./auth-session-4WJUKESW.js'),r=await s(t,e);return r?this.jsonResponse({success:!0,expiresAt:r.expiresAt}):this.errorResponse("Session not found",404)}catch(s){return console.error("[AuthRoutes.refreshSession] Error:",s),this.errorResponse("Failed to refresh session",500)}}errorResponse(e,t){return new Response(JSON.stringify({success:false,error:e}),{status:t,headers:{"Content-Type":"application/json"}})}async rateLimitResponse(e){return new Response(JSON.stringify({error:"Too many requests. Please try again later."}),{status:429,headers:{"Content-Type":"application/json",...e.retryAfter?{"Retry-After":e.retryAfter.toString()}:{}}})}async requestMagicLink(e){te(e);try{let r=await e.json();if(!r.email)return this.errorResponse("Email required",400);let a=await this.authAdapter.findUserByEmail(r.email);if(!a)return this.jsonResponse({success:!0,message:"If an account exists, a link was sent."});if(this.email){let n=Buffer.from(JSON.stringify({email:a.email,exp:Date.now()+6e5})).toString("base64url"),c=createHmac("sha256",this.jwtSecret).update(n).digest("hex"),p=`${n}.${c}`,u=`${this.getBaseUrl(e)}/admin/auth/magic-link?token=${p}`,d=this.email.getTemplates().magicLink(u,void 0,a.email);this.email.send({to:a.email,...d}).catch(m=>console.error("Magic link err:",m));}return this.jsonResponse({success:!0,message:"If an account exists, a link was sent."})}catch{return this.errorResponse("Failed to process request",500)}}async verifyMagicLink(e){let{ipAddress:t,userAgent:s}=te(e),a=new URL(e.url).searchParams.get("token");if(!a)return this.errorResponse("Token required",400);try{let[n,c]=a.split(".");if(!n||!c)return this.errorResponse("Invalid token",400);let p=createHmac("sha256",this.jwtSecret).update(n).digest("hex");if(c!==p)return this.errorResponse("Invalid token",400);let o=JSON.parse(Buffer.from(n,"base64url").toString());if(Date.now()>o.exp)return this.errorResponse("Token expired",400);let u=await this.authAdapter.findUserByEmail(o.email);if(!u)return this.errorResponse("User not found",404);if(u.locked)return this.errorResponse("Account locked",403);let d=await k({id:u.id,email:u.email,role:u.role,tenantId:u.tenantId});this.auditLogger&&await this.auditLogger.log({action:"login",userId:u.id,userEmail:u.email,resource:"auth",ipAddress:t,userAgent:s,success:!0});let m=this.jsonResponse({success:!0,user:this.sanitizeUser(u)});return i(m,d)}catch{return this.errorResponse("Invalid token",400)}}async inviteUser(e){try{let t=await e.json();if(!t.email||!t.role)return this.errorResponse("Email and role required",400);let s=await this.authAdapter.findUserByEmail(t.email);if(s)return this.errorResponse("User already exists",409);if(s=await this.authAdapter.createUser({email:t.email,password:randomBytes(16).toString("hex"),role:t.role}),this.email){let r=await this.authAdapter.createPasswordResetToken(s.email),n=`${this.getBaseUrl(e)}/admin/auth/reset-password?token=${r.token}`,c=this.email.getTemplates().userInvite(n,t.role,t.inviterName||"An administrator");this.email.send({to:s.email,...c}).catch(p=>console.error("Invite email err:",p));}return this.jsonResponse({success:!0,message:"User invited successfully"})}catch{return this.errorResponse("Failed to invite user",500)}}};var I=class extends Error{constructor(t,s,r){super(s);this.statusCode=t;this.message=s;this.metadata=r;this.name="ApiError";}statusCode;message;metadata};function vt(i,e){if(e instanceof I)return i.json({error:e.message},e.statusCode);let t=e instanceof Error?e.message:"Internal Server Error";return i.json({error:t},500)}({_media:{create:c.MEDIA_UPLOAD,update:c.MEDIA_UPLOAD,delete:c.MEDIA_DELETE}});var ce=new WeakMap;async function z(i,e,t,s,r,a,n=true,c="none"){let p=t&&typeof t=="object"?t:null,o=p?`col:${i.slug}:${e}:${s?.id||"anon"}:${r||""}:${a?.apiKeyId||""}`:null;if(p&&o){let d=ce.get(p);if(d&&d.has(o))return d.get(o)}let u=await a$9(i,e,{user:s,req:t,tenantId:r,apiKey:a},{enablePublicAccess:n,defaultAccess:c});if(p&&o){let d=ce.get(p);d||(d=new Map,ce.set(p,d)),d.set(o,u);}return u}async function we(i,e,t,s,r,a=true){let n=t&&typeof t=="object"?t:null,c=n?`gbl:${i.slug}:${e}:${s?.id||"anon"}:${r||""}`:null;if(n&&c){let o=ce.get(n);if(o&&o.has(c))return o.get(c)}let p=await b$1(i,e,{user:s,req:t,tenantId:r},{enablePublicAccess:a});if(n&&c){let o=ce.get(n);o||(o=new Map,ce.set(n,o)),o.set(c,p);}return p}async function ae(i,e,t,s,r,a=true){let n=await we(i,e,t,s,r,a);if(!n.allowed)throw new I(n.status||403,n.error||"Access denied");return n}async function $(i,e,t,s){if(t)return {user:t,tenantId:s,apiKeyContext:void 0,authType:"static"};if(e){let r=await e(i);if(r.status===200&&r.user)return {user:r.user,tenantId:r.tenantContext?.tenantId,apiKeyContext:r.apiKeyContext,authType:r.authType}}return {user:void 0,tenantId:void 0,apiKeyContext:void 0,authType:void 0}}var ne=class i{hooks=[];constructor(e=[]){this.hooks=[...e];}pipe(e){return this.hooks.push(e),this}async execute(e){let t=e.data;for(let s of this.hooks)try{let r=await s({...e,data:t});r!==void 0&&(t=r);}catch(r){throw new Error(`[Kyro CMS HookPipeline Error] Failed during ${e.operation} on collection "${e.collection||"global"}": ${r instanceof Error?r.message:String(r)}`)}return t}static async run(e,t){return !e||e.length===0?t.data:new i(e).execute(t)}};function Pe(i,e,t){let{registry:s,db:r,authSecret:a,user:n,tenantId:c,settings:p}=e,o=p?.access?.enablePublicAccess??true,u=p?.access?.defaultCollectionAccess??"none";for(let d of s.getCollections()){let m=d.slug,y=`/api/${m}`;i.post(`${y}/dynamic-options/:fieldName`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"read",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let w=l.req.param("fieldName"),A=d.fields.find(_=>_.name===w);if(!A||A.type!=="relationship"||!A.relationTo)throw new I(400,"Invalid field for dynamic options");let b=Array.isArray(A.relationTo)?A.relationTo[0]:A.relationTo,E=await l.req.json(),U=await r.find({collection:b,where:E.where,limit:20,tenantId:h}),O=s.getCollection(b)?.admin?.useAsTitle||"id",R=(U.docs||[]).map(_=>({label:_[O]||_.id,value:_.id}));return l.json({data:R})}),i.all(`${y}/semantic-search`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"read",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let w=[],A="",b$1=10,E=.4;if(l.req.method==="POST"){let P=await l.req.json().catch(()=>({}));w=P.vector||[],A=P.q||P.query||"",b$1=P.limit?parseInt(String(P.limit)):10,E=P.threshold?parseFloat(String(P.threshold)):.4;}else {let P=new URL(l.req.url);A=P.searchParams.get("q")||P.searchParams.get("query")||"",b$1=parseInt(P.searchParams.get("limit")||"10"),E=parseFloat(P.searchParams.get("threshold")||"0.4");}let v=(await r.find({collection:m,limit:200,tenantId:h})).docs||[],R=d.fields.filter(P=>P.type==="embedding")[0]?.name||"embedding",_=v.map(P=>{let W=P[R],H=0;if(Array.isArray(W)&&Array.isArray(w)&&w.length>0){let f=0,k=0,L=0;for(let q=0;q<Math.min(W.length,w.length);q++)f+=W[q]*w[q],k+=W[q]*W[q],L+=w[q]*w[q];H=k&&L?f/(Math.sqrt(k)*Math.sqrt(L)):0;}else if(A){let f=String(P.title||P.name||"").toLowerCase(),k=String(P.content||P.description||"").toLowerCase(),L=A.toLowerCase();f.includes(L)?H=.9:k.includes(L)?H=.7:H=.1;}return {doc:P,score:H}}),D=await Promise.all(_.filter(P=>P.score>=E).sort((P,W)=>W.score-P.score).slice(0,b$1).map(async P=>({...await b(P.doc,d.fields,g,l.req.raw,"read"),_similarity:Math.round(P.score*1e3)/1e3})));return l.json({docs:D,totalDocs:D.length,query:A||void 0})}),i.get(y,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=new URL(l.req.url),w=S.searchParams.get("draft"),A=S.searchParams.get("kyroToken"),b=false,E=a||process.env.KYRO_AUTH_SECRET||process.env.AUTH_SECRET||"kyro-preview-secret";if(w==="true"&&A&&E)try{let q=await verify(A,E,"HS256");q&&q.type==="preview"&&q.collection===d.slug&&(b=!0);}catch(q){console.warn("Invalid preview token",q);}if(!b){let q=await z(d,"read",l.req.raw,g,h,T,o,u);if(!q.allowed)throw new I(q.status||403,q.error||"Access denied")}let U=parseInt(S.searchParams.get("limit")||"10"),v=parseInt(S.searchParams.get("page")||"1"),O=S.searchParams.get("sort")||void 0,R=parseInt(S.searchParams.get("depth")||"0"),_=S.searchParams.get("select")?.split(",")||void 0,D=S.searchParams.get("where"),P;if(D)try{P=JSON.parse(decodeURIComponent(D));}catch{throw new I(400,"Invalid JSON in where clause")}let W=S.searchParams.get("search")||S.searchParams.get("q");if(W&&W.trim()){let q=W.trim(),C=(d.fields||[]).filter(x=>x.name&&x.name!=="id"&&(x.type==="text"||x.type==="email"||x.type==="textarea"||x.type==="select"||x.type==="radio"||x.indexed)&&!x.admin?.hidden).map(x=>x.name);if(C.length>0){let x=C.map(K=>({[K]:{contains:q}}));P?P={AND:[P,{OR:x}]}:P={OR:x};}}let H=w==="true"?true:w==="false"?false:!!g,f=await r.find({collection:m,where:P,limit:U,page:v,sort:O,tenantId:h,select:_,draft:H}),k=await r.count({collection:m,where:P,tenantId:h});await o$1(f.docs||[],d.fields,r,s,1,R);let L=(f.docs||[]).map(a$a);return l.json({docs:L,totalDocs:k,limit:U,page:v,totalPages:Math.ceil(k/U),data:L,meta:{total:k,page:v,limit:U,totalPages:Math.ceil(k/U)}})}),i.get(`${y}/:id/versions`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"read",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let w=l.req.param("id"),A=parseInt(l.req.query("page")||"1"),b=Math.min(parseInt(l.req.query("limit")||"30"),100),E=l.req.query("compareA"),U=l.req.query("compareB");if(E&&U&&typeof r.findVersionByID=="function")try{let R=await r.findVersionByID({collection:m,versionId:E,tenantId:h}),_=await r.findVersionByID({collection:m,versionId:U,tenantId:h});if(!R||!_)throw new I(404,"One or both comparison versions were not found");let D=typeof R.data=="string"?JSON.parse(R.data):R.data||{},P=typeof _.data=="string"?JSON.parse(_.data):_.data||{},W=[],H=new Set([...Object.keys(D),...Object.keys(P)]);for(let f of H)["id","createdAt","updatedAt","publishedAt"].includes(f)||JSON.stringify(D[f])!==JSON.stringify(P[f])&&W.push({field:f,oldValue:D[f]??null,newValue:P[f]??null});return l.json({diffs:W,versionA:R,versionB:_})}catch(R){if(R instanceof I)throw R;return console.warn(`[compareVersions] Error comparing versions for ${m}/${w}:`,R),l.json({diffs:[]})}let v=[],O=0;if(typeof r.findVersions=="function")try{let R=await r.findVersions({collection:m,documentId:w,page:A,limit:b,tenantId:h});v=R.docs||[],O=R.totalDocs||v.length;}catch(R){console.warn(`[findVersions] Error fetching versions for ${m}/${w}:`,R);}return l.json({docs:v,totalDocs:O,page:A,limit:b,totalPages:Math.ceil(O/b)||1,data:v,meta:{total:O,page:A,limit:b,totalPages:Math.ceil(O/b)||1}})}),i.post(`${y}/:id/versions`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"update",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let w=l.req.param("id"),A=await l.req.json().catch(()=>({})),b=A.versionId;if(A.action==="restore"&&b&&typeof r.findVersionByID=="function"){let E=await r.findVersionByID({collection:m,versionId:b,tenantId:h});if(!E)throw new I(404,`Version '${b}' not found`);let U=typeof E.data=="string"?JSON.parse(E.data):E.data,{id:v,createdAt:O,updatedAt:R,..._}=U;d.versions&&typeof r.createVersion=="function"&&await r.createVersion({collection:m,documentId:w,data:_,status:_.status||"published",autosave:false,createdBy:g?.id,changeDescription:`Restored from version ${E.version||b}`,tenantId:h});let D=await r.update({collection:m,id:w,data:_,tenantId:h}),P=a$a(D);return l.json({doc:P,data:P,message:"Version restored successfully"})}throw new I(400,"Invalid action for version management")}),i.get(`${y}/:id/versions/:versionId`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"read",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let w=l.req.param("versionId"),A=null;if(typeof r.findVersionByID=="function"&&(A=await r.findVersionByID({collection:m,versionId:w,tenantId:h})),!A)throw new I(404,`Version '${w}' not found`);return l.json({doc:A,data:A})}),i.post(`${y}/:id/versions/:versionId/restore`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"update",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let w=l.req.param("id"),A=l.req.param("versionId");if(typeof r.restoreVersion=="function")try{let b=await r.restoreVersion({collection:m,documentId:w,versionId:A,tenantId:h});return l.json({doc:b,data:b,message:"Version restored successfully"})}catch(b){console.warn("[restoreVersion] Adapter restore failed, falling back to manual restore:",b);}if(typeof r.findVersionByID=="function"){let b=await r.findVersionByID({collection:m,versionId:A,tenantId:h});if(!b)throw new I(404,`Version '${A}' not found`);let E=typeof b.data=="string"?JSON.parse(b.data):b.data,{id:U,createdAt:v,updatedAt:O,...R}=E;d.versions&&typeof r.createVersion=="function"&&await r.createVersion({collection:m,documentId:w,data:R,status:R.status||"published",autosave:false,createdBy:g?.id,changeDescription:`Restored from version ${b.version||A}`,tenantId:h});let _=await r.update({collection:m,id:w,data:R,tenantId:h}),D=a$a(_);return l.json({doc:D,data:D,message:"Version restored successfully"})}throw new I(501,"Version restoration not supported by database adapter")}),i.post(`${y}/preview-url`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"read",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let A=await l.req.json().catch(()=>({}))||{};if(A.id&&!A.slug)try{let v=await r.findByID({collection:d.slug,id:A.id,tenantId:h});v&&(A={...v,...A});}catch{}let b,E=a||process.env.KYRO_AUTH_SECRET||process.env.AUTH_SECRET||"kyro-preview-secret";try{b=await sign({type:"preview",collection:d.slug,id:A.id,exp:Math.floor(Date.now()/1e3)+3600},E,"HS256");}catch(v){console.warn("Failed to sign preview token:",v);}let U="";if(typeof d.admin?.preview=="function")try{U=await d.admin.preview(A,{req:l.req.raw,token:b});}catch(v){console.error(`[Kyro Preview] Error in custom preview function for ${d.slug}:`,v);}if(!U){let v=A.slug||A.id||"";if(U=v?`/${d.slug}/${v}`:`/${d.slug}`,b){let O=U.includes("?")?"&":"?";U+=`${O}draft=true&kyroToken=${b}`;}}return l.json({url:U})}),i.get(`${y}/:id`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=new URL(l.req.url),w=S.searchParams.get("draft"),A=S.searchParams.get("kyroToken"),b=false,E=a||process.env.KYRO_AUTH_SECRET||process.env.AUTH_SECRET||"kyro-preview-secret";if(w==="true"&&A&&E)try{let D=await verify(A,E,"HS256");D&&D.type==="preview"&&D.collection===d.slug&&(b=!0);}catch(D){console.warn("Invalid preview token",D);}if(!b){let D=await z(d,"read",l.req.raw,g,h,T,o,u);if(!D.allowed)throw new I(D.status||403,D.error||"Access denied")}let U=l.req.param("id"),v=parseInt(S.searchParams.get("depth")||"1"),O=w==="true"?true:w==="false"?false:!!g,R=await r.findByID({collection:m,id:U,tenantId:h,draft:O});if(!R)throw new I(404,`Document '${U}' not found in '${m}'`);await o$1([R],d.fields,r,s,1,v);let _=a$a(R);return l.json({doc:_,data:_})}),i.post(y,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"create",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let w=await l.req.json();d.hooks?.beforeChange&&d.hooks.beforeChange.length>0&&(w=await new ne(d.hooks.beforeChange).execute({data:w,collection:m,operation:"create",req:l.req.raw,user:g}));let A=await r.create({collection:m,data:w,tenantId:h});if(d.versions&&typeof r.createVersion=="function")try{await r.createVersion({collection:m,documentId:A?.id||w.id,data:A,status:w.status||"published",autosave:!1,createdBy:g?.id,changeDescription:w.changeDescription||"Initial version",tenantId:h});}catch(E){console.warn(`[createVersion] Failed creating initial version for ${m}:`,E);}d.hooks?.afterChange&&d.hooks.afterChange.length>0&&await new ne(d.hooks.afterChange).execute({data:A,collection:m,operation:"create",req:l.req.raw,user:g});let b=a$a(A);return l.json({doc:b,data:b,message:"Document created successfully"},201)}),i.patch(`${y}/:id`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"update",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let w=l.req.param("id"),A=await l.req.json(),b=new URL(l.req.url),E=b.searchParams.get("autosave")==="true"||l.req.header("x-autosave")==="true"||A.autosave===true,U=b.searchParams.get("draft")==="true"||l.req.header("x-draft")==="true"||A.draft===true,v=d.versions?.drafts===true;if(d.hooks?.beforeChange&&d.hooks.beforeChange.length>0){let _=await r.findByID({collection:m,id:w,tenantId:h});A=await new ne(d.hooks.beforeChange).execute({data:A,originalDoc:_||void 0,collection:m,operation:"update",req:l.req.raw,user:g});}let O;if(v&&U)typeof r.createVersion=="function"&&await r.createVersion({collection:m,documentId:w,data:A,status:"draft",autosave:E,createdBy:g?.id,changeDescription:A.changeDescription||(E?"Auto-saved draft":"Draft snapshot"),tenantId:h}),O=await r.findByID({collection:m,id:w,tenantId:h,draft:true});else {let _=await r.findByID({collection:m,id:w,tenantId:h,draft:true});if(!_)throw new I(404,`Document '${w}' not found in '${m}'`);let D={..._,...A};if(d.versions&&typeof r.createVersion=="function")try{await r.createVersion({collection:m,documentId:w,data:D,status:A.status||_.status||"published",autosave:E,createdBy:g?.id,changeDescription:A.changeDescription||(E?"Auto-saved":"Updated snapshot"),tenantId:h});}catch(P){console.warn(`[createVersion] Failed creating version for ${m}/${w}:`,P);}if(O=await r.update({collection:m,id:w,data:A,tenantId:h}),!O)throw new I(404,`Document '${w}' not found in '${m}'`)}d.hooks?.afterChange&&d.hooks.afterChange.length>0&&await new ne(d.hooks.afterChange).execute({data:O,collection:m,operation:"update",req:l.req.raw,user:g});let R=a$a(O);return l.json({doc:R,data:R,message:"Document updated successfully"})}),i.delete(`${y}/:id`,async l=>{let{user:g,tenantId:h,apiKeyContext:T}=await $(l.req.raw,t,n,c),S=await z(d,"delete",l.req.raw,g,h,T,o,u);if(!S.allowed)throw new I(S.status||403,S.error||"Access denied");let w=l.req.param("id");if(!await r.delete({collection:m,id:w,tenantId:h}))throw new I(404,`Document '${w}' not found in '${m}'`);return l.json({success:true,message:`Document '${w}' deleted successfully`})});}}function Le(i,e,t){let{registry:s,db:r,authSecret:a,user:n,tenantId:c,settings:p}=e,o=p?.access?.enablePublicAccess??true;for(let u of s.getGlobals()){let d=u.slug,m=`/api/globals/${d}`;i.get(m,async l=>{let{user:g,tenantId:h}=await $(l.req.raw,t,n,c),T=new URL(l.req.url),S=T.searchParams.get("draft"),w=T.searchParams.get("kyroToken"),A=false,b=a||process.env.KYRO_AUTH_SECRET||process.env.AUTH_SECRET||"kyro-preview-secret";if(S==="true"&&w&&b)try{let R=await verify(w,b,"HS256");R&&R.type==="preview"&&R.collection===`_globals_${u.slug}`&&(A=!0);}catch(R){console.warn("Invalid preview token",R);}A||await ae(u,"read",l.req.raw,g,h,o);let E=parseInt(T.searchParams.get("depth")||"0"),U=`_globals_${d}`,v=await r.findOne({collection:U,where:{},depth:E,tenantId:h,draft:S==="true"?true:S==="false"?false:!!g});v||(v={id:d}),await o$1([v],u.fields,r,s,1,E);let O=a$a(v);return l.json({doc:O,data:O})}),i.post(`${m}/preview-url`,async l=>{let{user:g,tenantId:h}=await $(l.req.raw,t,n,c);await ae(u,"read",l.req.raw,g,h,o);let S=await l.req.json().catch(()=>({}))||{},w,A=a||process.env.KYRO_AUTH_SECRET||process.env.AUTH_SECRET||"kyro-preview-secret";try{w=await sign({type:"preview",collection:`_globals_${u.slug}`,exp:Math.floor(Date.now()/1e3)+3600},A,"HS256");}catch(E){console.warn("Failed to sign global preview token:",E);}let b="";if(typeof u.admin?.preview=="function")try{b=await u.admin.preview(S,{req:l.req.raw,token:w});}catch(E){console.error(`[Kyro Preview] Error in custom preview function for global ${u.slug}:`,E);}if(!b&&(b=`/${u.slug}`,w)){let E=b.includes("?")?"&":"?";b+=`${E}draft=true&kyroToken=${w}`;}return l.json({url:b})}),i.get(`${m}/versions`,async l=>{let{user:g,tenantId:h}=await $(l.req.raw,t,n,c);await ae(u,"read",l.req.raw,g,h,o);let T=`_globals_${d}`,S=parseInt(l.req.query("page")||"1"),w=Math.min(parseInt(l.req.query("limit")||"30"),100),A=l.req.query("compareA"),b=l.req.query("compareB");if(A&&b&&typeof r.findVersionByID=="function")try{let v=await r.findVersionByID({collection:T,versionId:A,tenantId:h}),O=await r.findVersionByID({collection:T,versionId:b,tenantId:h});if(!v||!O)return l.json({error:"One or both comparison versions were not found"},404);let R=typeof v.data=="string"?JSON.parse(v.data):v.data||{},_=typeof O.data=="string"?JSON.parse(O.data):O.data||{},D=[],P=new Set([...Object.keys(R),...Object.keys(_)]);for(let W of P)["id","createdAt","updatedAt","publishedAt"].includes(W)||JSON.stringify(R[W])!==JSON.stringify(_[W])&&D.push({field:W,oldValue:R[W]??null,newValue:_[W]??null});return l.json({diffs:D,versionA:v,versionB:O})}catch(v){return console.warn(`[compareVersions] Error comparing global versions for ${d}:`,v),l.json({diffs:[]})}let E=[],U=0;if(typeof r.findVersions=="function")try{let v=await r.findVersions({collection:T,documentId:d,page:S,limit:w,tenantId:h});E=v.docs||[],U=v.totalDocs||E.length;}catch(v){console.warn(`[findVersions] Error fetching global versions for ${d}:`,v);}return l.json({docs:E,totalDocs:U,page:S,limit:w,totalPages:Math.ceil(U/w)||1,data:E,meta:{total:U,page:S,limit:w,totalPages:Math.ceil(U/w)||1}})}),i.get(`${m}/versions/:versionId`,async l=>{let{user:g,tenantId:h}=await $(l.req.raw,t,n,c);await ae(u,"read",l.req.raw,g,h,o);let T=`_globals_${d}`,S=l.req.param("versionId"),w=null;return typeof r.findVersionByID=="function"&&(w=await r.findVersionByID({collection:T,versionId:S,tenantId:h})),w?l.json({doc:w,data:w}):l.json({error:`Global version '${S}' not found`},404)}),i.post(`${m}/versions/:versionId/restore`,async l=>{let{user:g,tenantId:h}=await $(l.req.raw,t,n,c);await ae(u,"update",l.req.raw,g,h,o);let T=`_globals_${d}`,S=l.req.param("versionId");if(typeof r.findVersionByID=="function"){let w=await r.findVersionByID({collection:T,versionId:S,tenantId:h});if(!w)return l.json({error:`Global version '${S}' not found`},404);let A=typeof w.data=="string"?JSON.parse(w.data):w.data,{id:b,createdAt:E,updatedAt:U,...v}=A,O=await r.findOne({collection:T,where:{},tenantId:h}),R;O?R=await r.update({collection:T,id:O.id,data:v,tenantId:h}):R=await r.create({collection:T,data:{id:d,...v},tenantId:h}),u.versions&&typeof r.createVersion=="function"&&await r.createVersion({collection:T,documentId:d,data:R||v,status:"published",autosave:false,createdBy:g?.id,changeDescription:`Restored from version ${w.version||S}`,tenantId:h});let _=a$a(R);return l.json({doc:_,data:_,message:"Global version restored successfully"})}return l.json({error:"Version restoration not supported by database adapter"},501)});let y=async l=>{let{user:g,tenantId:h}=await $(l.req.raw,t,n,c);await ae(u,"update",l.req.raw,g,h,o);let T=await l.req.json(),S=new URL(l.req.url),w=S.searchParams.get("autosave")==="true"||l.req.header("x-autosave")==="true"||T.autosave===true,A=S.searchParams.get("draft")==="true"||l.req.header("x-draft")==="true"||T.draft===true,b=`_globals_${d}`,E=await r.findOne({collection:b,where:{},tenantId:h}),U;if(E?U=await r.update({collection:b,id:E.id,data:T,tenantId:h}):U=await r.create({collection:b,data:{id:d,...T},tenantId:h}),u.versions&&typeof r.createVersion=="function")try{await r.createVersion({collection:b,documentId:d,data:U||T,status:A?"draft":"published",autosave:w,createdBy:g?.id,changeDescription:T.changeDescription||(w?"Auto-saved":"Updated snapshot"),tenantId:h});}catch(O){console.warn(`[createVersion] Failed creating version for global ${d}:`,O);}let v=a$a(U);return l.json({doc:v,data:v,message:"Global updated successfully"})};i.post(m,y),i.patch(m,y),i.put(m,y);}}function oe(i){let{uploadDir:e=join(ar.cwd(),"public","uploads"),baseUrl:t="/uploads"}=i;async function s(n){existsSync(n)||await mkdir(n,{recursive:true});}function r(n){let c=extname(n).toLowerCase();return {".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".avi":"video/x-msvideo",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".rar":"application/vnd.rar",".7z":"application/x-7z-compressed"}[c]||"application/octet-stream"}async function a(n){try{let c=n.toString("hex",0,8);if(c.startsWith("89504e47")){let p=n.readUInt32BE(16),o=n.readUInt32BE(20);return {width:p,height:o}}if(c.startsWith("ffd8")){let p=2;for(;p<n.length&&n[p]===255;){let o=n[p+1];if(o===192||o===194){let u=n.readUInt16BE(p+5);return {width:n.readUInt16BE(p+7),height:u}}p+=2+n.readUInt16BE(p+2);}}}catch{}return {}}return re({name:"local",displayName:"Local Storage",supportsDynamicResize:true,async upload(n,c){await s(e);let p=Buffer.from(await n.arrayBuffer()),o=createHash("md5").update(p).digest("hex"),u=extname(n.name),d=c?.filename||`${o}${u}`,m=c?.folder||"",y=m?join(e,m):e;await s(y);let l=join(y,d);await writeFile(l,p);let g=n.type.startsWith("image/")?await a(p):{},h=t||"/uploads",T=m?`/${m}/${d}`:`/${d}`,S=h+T;return {id:o,filename:d,originalName:n.name,mimeType:n.type||r(n.name),size:p.length,url:S,thumbnailUrl:n.type.startsWith("image/")?S:void 0,folder:m||void 0,provider:"local",metadata:{...g,...c?.metadata},createdAt:new Date().toISOString()}},async uploadFromUrl(n,c){let p=await fetch(n);if(!p.ok)throw new Error(`Failed to fetch file: ${p.statusText}`);let o=await p.blob(),u=p.headers.get("content-disposition"),d=c?.filename;if(!d&&u){let y=u.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);y&&(d=y[1].replace(/['"]/g,""));}d||(d=basename(new URL(n).pathname));let m=new File([o],d,{type:o.type||r(d)});return this.upload(m,c)},async delete(n){let c=join(e,n.replace(t+"/",""));try{await unlink(c);}catch{}},async rename(n,c){let p=join(e,n.replace(t+"/","")),o=join(e,c);return await rename(p,o),`${t}/${c}`},async list(n){let c=n?join(e,n):e;if(!existsSync(c))return [];let p=[],o=await readdir(c,{withFileTypes:true});for(let u of o)if(u.isFile()){let d=join(c,u.name),m=await stat(d),y=`${t}${n?`/${n}`:""}/${u.name}`;p.push({id:createHash("md5").update(u.name).digest("hex"),filename:u.name,originalName:u.name,mimeType:r(u.name),size:m.size,url:y,provider:"local",createdAt:m.birthtime.toISOString()});}return p},async exists(n){let c=join(e,n.replace(t+"/",""));return existsSync(c)},async createFolder(n){let c=join(e,n);await mkdir(c,{recursive:true});},async deleteFolder(n){let c=join(e,n);if(existsSync(c)){let{rm:p}=await import('fs/promises');await p(c,{recursive:true,force:true});}}})}function qe(i){let e=(t,s)=>{if(!i.signKey)return t;let r=createHmac("sha256",i.signKey).update(t+s.toString()).digest("hex");return s.set("s",r),t};return {name:"imgix",displayName:"Imgix",supportsDynamicResize:true,async upload(t,s){throw new Error("Imgix is a transformation service. Use another provider for uploads.")},async uploadFromUrl(t,s){let r=s?.filename||t.split("/").pop()||"file",a=await fetch(t);if(!a.ok)throw new Error(`Failed to fetch: ${a.statusText}`);let n=await a.blob();new File([n],r,{type:n.type});return {id:Buffer.from(t).toString("base64").slice(0,20),filename:r,originalName:r,mimeType:n.type,size:n.size,url:this.getImageUrl(t),thumbnailUrl:this.getImageUrl(t,{width:200,height:200,fit:"crop"}),provider:"imgix",createdAt:new Date().toISOString()}},async delete(t){},async rename(t,s){return `https://${i.domain}/${s}`},getImageUrl(t,s){let r=new URL(t),a=new URLSearchParams(r.search);i.defaultParameters&&Object.entries(i.defaultParameters).forEach(([c,p])=>{a.has(c)||a.set(c,p);}),s&&(s.width&&a.set("w",String(s.width)),s.height&&a.set("h",String(s.height)),s.quality&&a.set("q",String(s.quality)),s.format&&a.set("fm",s.format),s.fit&&a.set("fit",s.fit),s.blur&&a.set("blur",String(s.blur)),s.sharpen&&a.set("sharp",String(s.sharpen))),a.set("auto","compress,format");r.pathname+"?"+a.toString();return i.signKey&&(e(r.pathname+a.toString(),a)),`https://${i.domain}${r.pathname}${a.toString()?"?"+a.toString():""}`},async generateThumbnail(t){return this.getImageUrl(t.url,{width:200,height:200,fit:"crop"})},async list(){return []},async exists(t){try{return (await fetch(t,{method:"HEAD"})).ok}catch{return false}},async createFolder(){},async deleteFolder(){}}}function Ae(i,e){return e.cdnUrl?`${e.cdnUrl.replace(/\/$/,"")}/${i}`:`https://${e.storageZone}.b-cdn.net/${i}`}function De(i){return i.cdnUrl?i.cdnUrl.replace(/\/$/,"")+"/":`https://${i.storageZone}.b-cdn.net/`}function Ce(i){let e=`https://storage.bunnycdn.com/${i.storageZone}`,t=s=>`${i.prefix?`${i.prefix}/`:""}${s}`.replace(/\/+/g,"/");return re({name:"bunny",displayName:"Bunny.net Storage",supportsDynamicResize:true,async upload(s,r){let a=t(`${r?.folder?`${r.folder}/`:""}${r?.filename||s.name}`),n=Buffer.from(await s.arrayBuffer()),c=await fetch(`${e}/${a}`,{method:"PUT",headers:{AccessKey:i.apiKey,"Content-Type":s.type},body:n});if(!c.ok){let p=await c.text();throw new Error(`Bunny.net upload failed: ${c.status} ${p}`)}return {id:Buffer.from(a).toString("base64url"),filename:r?.filename||s.name,originalName:s.name,mimeType:s.type,size:n.length,url:Ae(a,i),thumbnailUrl:s.type.startsWith("image/")?Ae(a,i):void 0,folder:r?.folder,provider:"bunny",metadata:r?.metadata,createdAt:new Date().toISOString()}},async delete(s){let r=s.replace(De(i),""),a=await fetch(`${e}/${r}`,{method:"DELETE",headers:{AccessKey:i.apiKey}});if(!a.ok&&a.status!==404){let n=await a.text();throw new Error(`Bunny.net delete failed: ${a.status} ${n}`)}},async rename(s,r){let a=s.replace(De(i),""),n=i.prefix?`${i.prefix}/${r}`:r,c=await fetch(`${e}/${a}`,{method:"GET",headers:{AccessKey:i.apiKey}});if(!c.ok)throw new Error("Bunny.net rename failed: could not read old file");let p=await c.arrayBuffer();return await fetch(`${e}/${n}`,{method:"PUT",headers:{AccessKey:i.apiKey,"Content-Type":c.headers.get("Content-Type")||"application/octet-stream"},body:p}),await this.delete(s),Ae(n,i)},async list(s){let r=t(s||""),a=await fetch(`${e}/${r}`,{method:"GET",headers:{AccessKey:i.apiKey}});if(!a.ok){let c=await a.text();throw new Error(`Bunny.net list failed: ${a.status} ${c}`)}return (await a.json()).map(c=>({id:Buffer.from(c.ObjectName||"").toString("base64url"),filename:c.ObjectName?.split("/").pop()||"",originalName:c.ObjectName?.split("/").pop()||"",mimeType:"application/octet-stream",size:c.Length||0,url:Ae(c.ObjectName||"",i),provider:"bunny",createdAt:c.LastChanged||new Date().toISOString()}))},async exists(s){let r=s.replace(De(i),"");return (await fetch(`${e}/${r}`,{method:"HEAD",headers:{AccessKey:i.apiKey}})).ok},async createFolder(s){let r=t(`${s}/`);await fetch(`${e}/${r}`,{method:"PUT",headers:{AccessKey:i.apiKey,"Content-Length":"0"},body:""});},async deleteFolder(s){let r=t(`${s}/`);await fetch(`${e}/${r}`,{method:"DELETE",headers:{AccessKey:i.apiKey}});}})}function $e(){let i=()=>{let s=globalThis.STORAGE_BUCKET;if(!s)throw new Error("Cloudflare R2 native binding 'STORAGE_BUCKET' not found in global scope.");return s},e=s=>`/api/media/file/${s}`,t=s=>s.replace(/\/+/g,"/").replace(/^\/+/,"");return re({name:"cloudflare_r2",displayName:"Cloudflare R2 (Native)",supportsDynamicResize:true,async upload(s,r){let a=i(),n=t(`${r?.folder?`${r.folder}/`:""}${r?.filename||s.name}`),c=await s.arrayBuffer(),p=await a.put(n,c,{httpMetadata:{contentType:s.type},customMetadata:r?.metadata||{}});return {id:Buffer.from(n).toString("base64url"),filename:r?.filename||s.name,originalName:s.name,mimeType:s.type,size:p.size,url:e(n),thumbnailUrl:s.type.startsWith("image/")?e(n):void 0,folder:r?.folder,provider:"cloudflare_r2",metadata:{...r?.metadata,etag:p.etag},createdAt:new Date().toISOString()}},async delete(s){let r=i(),a=s.replace(/^\/api\/media\/file\//,"");await r.delete(a);},async rename(s,r){let a=i(),n=s.replace(/^\/api\/media\/file\//,""),c=t(r),p=await a.get(n);if(!p)throw new Error("File not found");return await a.put(c,p.body,{httpMetadata:p.httpMetadata,customMetadata:p.customMetadata}),await a.delete(n),e(c)},async list(s){let r=i(),a=t(s||"");return (await r.list({prefix:a})).objects.map(c=>({id:Buffer.from(c.key).toString("base64url"),filename:c.key.split("/").pop()||"",originalName:c.key.split("/").pop()||"",mimeType:c.httpMetadata?.contentType||"application/octet-stream",size:c.size,url:e(c.key),provider:"cloudflare_r2",createdAt:c.uploaded.toISOString()}))},async exists(s){try{let r=i(),a=s.replace(/^\/api\/media\/file\//,"");return await r.head(a)!==null}catch{return false}}})}var Oe=class{providers=new Map;providerToPlugin=new Map;disabledPlugins=new Set;constructor(){this.registerLocal(),this.registerImgix(),this.registerBunny(),this.registerCloudflareR2(),this.registerCloudflareS3();}registerLocal(){this.register({type:"local",displayName:"Local Server",configKey:"local",configFields:[{name:"uploadDir",type:"text",label:"Upload Directory",defaultValue:"./public/uploads"},{name:"baseUrl",type:"text",label:"Base URL",defaultValue:"/uploads"}],extractConfig:(e,t)=>e[t]||{},extractRawConfig:e=>{let t=e?.local||e,s=(t?.uploadDir||"").trim(),r;s?Te.isAbsolute(s)?r=s:s.includes("/")||s.includes("\\")?r=Te.resolve(process.cwd(),s):r=Te.join(process.cwd(),"public",s):r=Te.join(process.cwd(),"public","uploads");let a=(t?.baseUrl||"").trim(),n;return a?n=a.startsWith("/")?a:`/${a}`:n="/uploads",{uploadDir:r,baseUrl:n}},factory:e=>oe(e)});}registerImgix(){this.register({type:"imgix",displayName:"Imgix",configKey:"imgix",configFields:[{name:"domain",type:"text",label:"Domain",required:true},{name:"signKey",type:"password",label:"Sign Key"}],extractConfig:(e,t)=>e[t]||{},extractRawConfig:e=>e?.imgix||e,factory:e=>qe(e)});}registerBunny(){this.register({type:"bunny",displayName:"Bunny.net",configKey:"bunny",configFields:[{name:"storageZone",type:"text",label:"Storage Zone",required:true},{name:"apiKey",type:"password",label:"API Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}],extractConfig:(e,t)=>e[t]||{},extractRawConfig:e=>e?.bunny||e,factory:e=>Ce(e)});}registerCloudflareR2(){this.register({type:"cloudflare_r2",displayName:"Cloudflare R2 (Native)",configKey:"cloudflareR2",configFields:[],extractConfig:()=>({}),extractRawConfig:()=>({}),factory:()=>$e()});}registerCloudflareS3(){this.register({type:"cloudflare_s3",displayName:"Cloudflare R2 (S3 Compat)",configKey:"cloudflareR2",configFields:[],extractConfig:()=>(console.warn('[StorageRegistry] "cloudflare_s3" is deprecated; use "cloudflare_r2" instead.'),{}),extractRawConfig:()=>({}),factory:()=>$e()});}register(e){if(this.providers.has(e.type)){console.warn(`[StorageRegistry] Provider "${e.type}" already registered, skipping`);return}e.pluginName&&this.providerToPlugin.set(e.type,e.pluginName),this.providers.set(e.type,e);}unregister(e){this.providers.delete(e),this.providerToPlugin.delete(e);}get(e){return this.providers.get(e)}getAll(){return Array.from(this.providers.values())}getAllAvailable(e){let t=this.getAll();return e?t.filter(s=>s.pluginName?e(s.pluginName):true):t}has(e){return this.providers.has(e)}async resolve(e,t){let s=this.providers.get(e);if(!s)throw new Error(`Unknown storage provider type: "${e}". Is the plugin that provides it enabled?`);if(s.pluginName&&this.disabledPlugins.has(s.pluginName))throw new Error(`Storage provider "${e}" is not available (plugin "${s.pluginName}" is disabled)`);let r=s.configKey||e,a=s.extractConfig(t,r);return s.factory(a)}async resolveWithConfig(e,t){let s=this.providers.get(e);if(!s)throw new Error(`Unknown storage provider type: "${e}". Is the plugin that provides it enabled?`);if(s.pluginName&&this.disabledPlugins.has(s.pluginName))throw new Error(`Storage provider "${e}" is not available (plugin "${s.pluginName}" is disabled)`);let r=s.extractRawConfig(t);return s.factory(r)}getProviderPluginName(e){return this.providerToPlugin.get(e)}getAllPluginNames(){return Array.from(new Set(this.providerToPlugin.values()))}setPluginEnabled(e,t){t?this.disabledPlugins.delete(e):this.disabledPlugins.add(e);}isPluginEnabled(e){return !this.disabledPlugins.has(e)}},_e=null;function Ne(){return _e||(_e=new Oe),_e}function Pt(i){if(!i)return "";if(i.startsWith("pub-"))return i;let e=i.match(/pub-[a-zA-Z0-9]+/i);return e?e[0]:""}function ur(i,e){let t=i.startsWith("/")?i.slice(1):i;if(e.cdnUrl)return `${e.cdnUrl.replace(/\/$/,"")}/${t}`;switch(e.provider){case "r2":{let s=Pt(e.publicDevUrl);return s?`https://${s}.r2.dev/${t}`:`https://${e.bucket}.${e.accountId}.r2.cloudflarestorage.com/${t}`}case "gcs":return `https://storage.googleapis.com/${e.bucket}/${t}`;case "digitalocean":return `https://${e.bucket}.${e.region}.cdn.digitaloceanspaces.com/${t}`;case "backblaze":return `https://${e.bucket}.s3.backblazeb2.com/${t}`;case "wasabi":return `https://${e.bucket}.s3.wasabisys.com/${t}`;default:return `https://${e.bucket}.s3.${e.region}.amazonaws.com/${t}`}}function je(i){if(i.cdnUrl)return i.cdnUrl.replace(/\/$/,"")+"/";switch(i.provider){case "r2":{let e=Pt(i.publicDevUrl);return e?`https://${e}.r2.dev/`:`https://${i.bucket}.${i.accountId}.r2.cloudflarestorage.com/`}case "gcs":return `https://storage.googleapis.com/${i.bucket}/`;case "digitalocean":return `https://${i.bucket}.${i.region}.cdn.digitaloceanspaces.com/`;case "backblaze":return `https://${i.bucket}.s3.backblazeb2.com/`;case "wasabi":return `https://${i.bucket}.s3.wasabisys.com/`;default:return `https://${i.bucket}.s3.${i.region}.amazonaws.com/`}}function pr(i){switch(i){case "r2":return "Cloudflare R2";case "gcs":return "Google Cloud Storage";case "digitalocean":return "DigitalOcean Spaces";case "backblaze":return "Backblaze B2";case "wasabi":return "Wasabi";default:return "AWS S3"}}function mr(i){let e=new S3Client({region:i.region||"auto",endpoint:i.endpoint,credentials:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey},forcePathStyle:true,tls:true,...i.provider==="r2"&&{requestHandler:new NodeHttpHandler}}),t=r=>`${i.prefix?`${i.prefix}/`:""}${r}`.replace(/\/+/g,"/"),s=r=>ur(r,i);return re({name:i.provider,displayName:pr(i.provider),supportsDynamicResize:true,async upload(r,a){let n=t(`${a?.folder?`${a.folder}/`:""}${a?.filename||r.name}`),c=Buffer.from(await r.arrayBuffer());await e.send(new PutObjectCommand({Bucket:i.bucket,Key:n,Body:c,ContentType:r.type,Metadata:a?.metadata}));let p=await e.send(new HeadObjectCommand({Bucket:i.bucket,Key:n}));return {id:Buffer.from(n).toString("base64url"),filename:a?.filename||r.name,originalName:r.name,mimeType:r.type,size:c.length,url:s(n),thumbnailUrl:r.type.startsWith("image/")?s(n):void 0,folder:a?.folder,provider:i.provider,metadata:{...a?.metadata,etag:p.ETag},createdAt:new Date().toISOString()}},async delete(r){let a=r.replace(je(i),"");await e.send(new DeleteObjectCommand({Bucket:i.bucket,Key:a}));},async rename(r,a){let n=r.replace(je(i),""),c=i.prefix?`${i.prefix}/${a}`:a;return await e.send(new CopyObjectCommand({Bucket:i.bucket,CopySource:`${i.bucket}/${n}`,Key:c})),await e.send(new DeleteObjectCommand({Bucket:i.bucket,Key:n})),s(c)},async list(r){let a=t(r||"");return ((await e.send(new ListObjectsV2Command({Bucket:i.bucket,Prefix:a}))).Contents||[]).map(c=>({id:Buffer.from(c.Key||"").toString("base64url"),filename:c.Key?.split("/").pop()||"",originalName:c.Key?.split("/").pop()||"",mimeType:"application/octet-stream",size:c.Size||0,url:s(c.Key||""),provider:i.provider,createdAt:c.LastModified?.toISOString()||new Date().toISOString()}))},async exists(r){try{let a=r.replace(je(i),"");return await e.send(new HeadObjectCommand({Bucket:i.bucket,Key:a})),!0}catch{return false}},async createFolder(r){let a=t(`${r}/`);await e.send(new PutObjectCommand({Bucket:i.bucket,Key:a,Body:""}));},async deleteFolder(r){let a=t(`${r}/`),n;do{let c=await e.send(new ListObjectsV2Command({Bucket:i.bucket,Prefix:a,ContinuationToken:n}));if(c.Contents?.length){let p=c.Contents.map(o=>({Key:o.Key}));await e.send(new DeleteObjectsCommand({Bucket:i.bucket,Delete:{Objects:p}}));}n=c.IsTruncated?c.NextContinuationToken:void 0;}while(n);await e.send(new DeleteObjectCommand({Bucket:i.bucket,Key:a}));}})}function gr(i){let e=()=>`https://api.cloudinary.com/v1_1/${i.cloudName}/upload`,t=async s=>{let r=await import('crypto'),a=Object.keys(s).sort().map(n=>`${n}=${s[n]}`).join("&");return r.createHash("sha256").update(a+i.apiSecret).digest("hex")};return {name:"cloudinary",displayName:"Cloudinary",supportsDynamicResize:true,async upload(s,r){let a=new FormData;if(a.append("file",s),i.uploadPreset)a.append("upload_preset",i.uploadPreset);else {let p=Math.round(Date.now()/1e3),o={timestamp:String(p)};(r?.folder||i.folder)&&(o.folder=r?.folder||i.folder||"");let u=await t(o);a.append("timestamp",String(p)),a.append("signature",u),a.append("api_key",i.apiKey);}(r?.folder||i.folder)&&a.append("folder",r?.folder||i.folder||"");let n=await fetch(e(),{method:"POST",body:a});if(!n.ok){let p=await n.json();throw new Error(`Cloudinary upload failed: ${p.error?.message||n.statusText}`)}let c=await n.json();return {id:c.public_id,filename:`${c.public_id}.${c.format}`,originalName:c.original_filename||s.name,mimeType:s.type||`image/${c.format}`,size:c.bytes,url:c.secure_url,thumbnailUrl:this.getImageUrl(c.secure_url,{width:200,height:200,fit:"crop"}),width:c.width,height:c.height,folder:r?.folder||i.folder,provider:"cloudinary",createdAt:new Date().toISOString()}},async uploadFromUrl(s,r){let a=new FormData;a.append("file",s),a.append("upload_preset","ml_default"),(r?.folder||i.folder)&&a.append("folder",r?.folder||i.folder||"");let n=await fetch(e(),{method:"POST",body:a});if(!n.ok)throw new Error("Cloudinary upload failed");let c=await n.json();return {id:c.public_id,filename:`${c.public_id}.${c.format}`,originalName:c.original_filename||s.split("/").pop()||"file",mimeType:`image/${c.format}`,size:c.bytes,url:c.secure_url,thumbnailUrl:this.getImageUrl(c.secure_url,{width:200,height:200,fit:"crop"}),width:c.width,height:c.height,provider:"cloudinary",createdAt:new Date().toISOString()}},async delete(s){try{let r=s.split("/image/upload/");if(r.length!==2){console.warn("[Cloudinary delete] Could not parse URL:",s);return}let a=r[1].replace(/^v\d+\//,"").replace(/\.[^.]+$/,""),n=Math.round(Date.now()/1e3),c={timestamp:String(n),public_id:a},p=Object.keys(c).sort().map(l=>`${l}=${c[l]}`).join("&"),u=(await import('crypto')).createHash("sha256").update(p+i.apiSecret).digest("hex"),d=`https://api.cloudinary.com/v1_1/${i.cloudName}/image/destroy`,m=new FormData;m.append("public_id",a),m.append("timestamp",String(n)),m.append("signature",u),m.append("api_key",i.apiKey);let y=await fetch(d,{method:"POST",body:m});if(!y.ok){let l=await y.json();console.warn("[Cloudinary delete] Failed:",l);}}catch(r){console.warn("[Cloudinary delete] Error:",r.message);}},async rename(s,r){let a="",n=r.replace(/\.[^.]+$/,""),c="";try{let p=s.split("/image/upload/");if(p.length!==2)return console.warn("[Cloudinary rename] Could not parse old URL:",s),s;let o=p[1],u=o.match(/^(v\d+)\//);a=u?u[1]:"";let d=o.replace(/^v\d+\//,"").replace(/\.[^.]+$/,""),m=d.split("/");c=m.length>1?m.slice(0,-1).join("/"):"";let y=r.replace(/\.[^.]+$/,"");n=c?`${c}/${y}`:y;let l=Math.round(Date.now()/1e3),g={from_public_id:d,to_public_id:n,timestamp:String(l)},h=Object.keys(g).sort().map(b=>`${b}=${g[b]}`).join("&"),S=(await import('crypto')).createHash("sha256").update(h+i.apiSecret).digest("hex"),w=new FormData;w.append("from_public_id",d),w.append("to_public_id",n),w.append("timestamp",String(l)),w.append("signature",S),w.append("api_key",i.apiKey);let A=await fetch(`https://api.cloudinary.com/v1_1/${i.cloudName}/image/rename`,{method:"POST",body:w});if(A.ok)return (await A.json()).secure_url;{let b=await A.json();console.warn("[Cloudinary rename] Failed:",b);let E=a?`/${a}/`:"/";return `https://res.cloudinary.com/${i.cloudName}/image/upload${E}${n}.${r.split(".").pop()}`}}catch(p){console.warn("[Cloudinary rename] Error:",p.message);let o=a?`/${a}/`:"/";return `https://res.cloudinary.com/${i.cloudName}/image/upload${o}${n}.${r.split(".").pop()}`}},getImageUrl(s,r){if(!r)return s;let a=s.split("/upload/");if(a.length!==2)return s;let n=[];if(r.width&&n.push(`w_${r.width}`),r.height&&n.push(`h_${r.height}`),r.fit){let p={crop:"c_fill",clip:"c_fit",scale:"c_scale",fill:"c_fill"};n.push(p[r.fit]||"c_limit");}r.quality&&n.push(`q_${r.quality}`),r.format&&n.push(`f_${r.format}`);let c=n.join(",");return `${a[0]}/upload/${c}/${a[1]}`},async generateThumbnail(s){return this.getImageUrl(s.url,{width:200,height:200,fit:"crop"})},async list(){return []},async exists(s){return (await fetch(s,{method:"HEAD"})).ok},async createFolder(){},async deleteFolder(){}}}async function Lt(i){let e=i.getStorageConfig(),t=Ne();try{return await t.resolve(e.type,e)}catch(s){return console.warn(`[resolveProvider] ${s.message} \u2014 falling back to local storage`),oe({uploadDir:Te.join(process.cwd(),"public","uploads"),baseUrl:"/uploads"})}}function re(i){return {async uploadFromUrl(e,t){let s=await fetch(e);if(!s.ok)throw new Error(`Failed to fetch: ${s.statusText}`);let r=await s.blob(),a=e.split("/").pop()||"file",n=new File([r],a,{type:r.type});return this.upload(n,t)},getImageUrl(e,t){if(!t||Object.keys(t).length===0)return e;let s=new URLSearchParams({url:e});return t.width&&s.set("w",String(t.width)),t.height&&s.set("h",String(t.height)),t.quality&&s.set("q",String(t.quality)),t.format&&s.set("f",t.format),t.cropWidth&&t.cropHeight&&(s.set("cx",String(t.cropX??0)),s.set("cy",String(t.cropY??0)),s.set("cw",String(t.cropWidth)),s.set("ch",String(t.cropHeight))),`/api/media/resize?${s.toString()}`},async generateThumbnail(e){return this.getImageUrl(e.url,{width:400,height:400})},...i}}async function qt(i){if(!i)return console.warn("[resolveProviderWithConfig] No config, using local"),oe({uploadDir:Te.join(process.cwd(),"public","uploads"),baseUrl:"/uploads"});let e=i.type||"local",t=Ne();try{return await t.resolveWithConfig(e,i)}catch(s){return console.warn(`[resolveProviderWithConfig] ${s.message} \u2014 falling back to local storage`),oe({uploadDir:Te.join(process.cwd(),"public","uploads"),baseUrl:"/uploads"})}}function Dt(){return typeof globalThis>"u"?false:typeof globalThis.EdgeRuntime=="string"||typeof globalThis.WebSocketPair<"u"||typeof globalThis.Deno<"u"||typeof process<"u"&&process.env?.NEXT_RUNTIME==="edge"}async function Ct(i,e){let t=e?.format||"webp",s=(t==="avif"?80:85);if(!Dt())try{let{default:r}=await import('sharp'),a=await r(i).metadata(),n=r(i),c=r(i).resize({width:500,withoutEnlargement:!0});return t==="avif"?(n=n.avif({quality:s}),c=c.avif({quality:Math.min(s,75)})):t==="png"?(n=n.png({compressionLevel:8}),c=c.png({compressionLevel:8})):t==="jpeg"||t==="jpg"?(n=n.jpeg({quality:s}),c=c.jpeg({quality:Math.min(s,80)})):(n=n.webp({quality:s}),c=c.webp({quality:Math.min(s,80)})),{buffer:await n.toBuffer(),thumbnailBuffer:await c.toBuffer(),width:a.width,height:a.height,format:t}}catch{}return {buffer:i,thumbnailBuffer:i,format:"passthrough"}}var $t=`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS media (
|
|
4
4
|
id TEXT PRIMARY KEY,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var chunkN7CDHWQH_cjs=require('./chunk-N7CDHWQH.cjs'),chunkDCKJT247_cjs=require('./chunk-DCKJT247.cjs'),chunk7KTPBTH5_cjs=require('./chunk-7KTPBTH5.cjs'),chunk24W5I6SJ_cjs=require('./chunk-24W5I6SJ.cjs'),
|
|
1
|
+
'use strict';var chunkN7CDHWQH_cjs=require('./chunk-N7CDHWQH.cjs'),chunkDCKJT247_cjs=require('./chunk-DCKJT247.cjs'),chunk7KTPBTH5_cjs=require('./chunk-7KTPBTH5.cjs'),chunk24W5I6SJ_cjs=require('./chunk-24W5I6SJ.cjs'),chunkO2SA56P2_cjs=require('./chunk-O2SA56P2.cjs'),chunkOJBL4CXK_cjs=require('./chunk-OJBL4CXK.cjs'),chunkDCFOVCJX_cjs=require('./chunk-DCFOVCJX.cjs'),chunkFU76HURF_cjs=require('./chunk-FU76HURF.cjs'),chunkGWUHIIPO_cjs=require('./chunk-GWUHIIPO.cjs'),chunk23RSKVJP_cjs=require('./chunk-23RSKVJP.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga');function P(s,e){for(let t of s){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let n of t.tabs)if(P(n.fields,e))return true}if("fields"in t&&t.fields&&P(t.fields,e))return true}return false}var G=class extends Error{errors;constructor(e){super(`Configuration validation failed:
|
|
2
2
|
${e.join(`
|
|
3
|
-
`)}`),this.name="ConfigValidationError",this.errors=e;}};function N(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Collection slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Collection "${s.slug}" has no fields defined`);else {let t=k(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,n]of Object.entries(s.access))typeof n!="boolean"&&typeof n!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(P(s.fields,s.admin.useAsTitle)||e.push(`Collection "${s.slug}" admin.useAsTitle references unknown field "${s.admin.useAsTitle}"`)),s.admin?.defaultColumns)for(let t of s.admin.defaultColumns)P(s.fields,t)||e.push(`Collection "${s.slug}" admin.defaultColumns references unknown field "${t}"`);if(s.upload&&s.upload.fileSize&&s.upload.fileSize<=0&&e.push(`Collection "${s.slug}" upload.fileSize must be positive`),s.versions&&s.versions.maxPerDoc&&s.versions.maxPerDoc<=0&&e.push(`Collection "${s.slug}" versions.maxPerDoc must be positive`),s.auth){let t=s.fields.some(i=>i.name==="email"),n=s.fields.some(i=>i.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),n||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function _(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Global slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Global "${s.slug}" has no fields defined`);else {let t=k(s.fields,`global:${s.slug}`);e.push(...t);}return e}function k(s,e){let t=[],n=new Set;for(let i=0;i<s.length;i++){let o=s[i];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let c=k(o.fields,e);t.push(...c);}else if("tabs"in o)for(let c of o.tabs){let l=k(c.fields,e);t.push(...l);}continue}let r=o.name;if(!r){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(n.has(r)&&t.push(`${e}: Duplicate field name "${r}"`),n.add(r),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r)||t.push(`${e}: Field name "${r}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${r}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${r}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${r}" has no blocks defined`);else {let c=Ie(o.blocks,`${e}.${r}`);t.push(...c);}break;case "select":case "radio":if(typeof o.options=="function")break;if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${r}" has no options defined`);else if(Array.isArray(o.options)){let c=o.options.map(u=>typeof u=="object"&&u!==null&&"value"in u?u.value:u),l=new Set(c);c.length!==l.size&&t.push(`${e}: ${o.type} field "${r}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${r}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${r}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${r}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${r}" has minRows greater than maxRows`);}return t}function Ie(s,e){let t=[],n=new Set;for(let i of s){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),n.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let o=k(i.fields,`${e}.${i.slug}`);t.push(...o);}}return t}function be(s,e=[]){let t=[],n=new Set;for(let i of s)n.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),n.add(i.slug);for(let i of e)n.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),n.add(i.slug);for(let i of s){let o=N(i);t.push(...o);}for(let i of e){let o=_(i);t.push(...o);}for(let i of s){let o=F(i.fields,s);t.push(...o);}if(t.length>0)throw new G(t)}function F(s,e){let t=[],n=new Set(e.map(i=>i.slug));for(let i of s){if(i.type==="relationship"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)r!=="*"&&!n.has(r)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${r}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)n.has(r)||t.push(`Upload field "${i.name}" references unknown collection "${r}"`);}if("fields"in i&&i.fields){let o=F(i.fields,e);t.push(...o);}if("tabs"in i)for(let o of i.tabs){let r=F(o.fields,e);t.push(...r);}if("blocks"in i)for(let o of i.blocks){let r=F(o.fields,e);t.push(...r);}}return t}function y(s){switch(s.type){case "text":return qe(s);case "number":return Le(s);case "checkbox":return De(s);case "date":return Ge(s);case "email":return Ne(s);case "password":return _e(s);case "textarea":return Ue(s);case "select":return ze(s);case "radio":return He(s);case "color":return Me(s);case "richtext":return Be(s);case "json":return Ve(s);case "code":return We(s);case "upload":return ve(s);case "image":return ve(s);case "markdown":return Ye(s);case "relationship":return Ce(s);case "relationship-block":return Ce(s);case "array":return Je(s);case "list":return Qe(s);case "group":return Xe(s);case "blocks":return et(s);case "row":return tt(s);case "collapsible":return st(s);case "tabs":return it(s);default:return zod.z.any()}}function qe(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.pattern&&(e=e.regex(new RegExp(s.pattern))),s.variant==="email"&&(e=e.email()),s.variant==="url"&&(e=e.url()),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Le(s){let e=s.integer?zod.z.coerce.number().int():zod.z.coerce.number();return s.min!==void 0&&(e=e.min(s.min)),s.max!==void 0&&(e=e.max(s.max)),s.step&&(e=e.refine(t=>Number.isInteger(t/s.step),`Value must be divisible by ${s.step}`)),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function De(s){let e=zod.z.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ge(s){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return s.minDate&&(e=e.refine(t=>new Date(t)>=new Date(s.minDate),`Date must be after ${s.minDate}`)),s.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(s.maxDate),`Date must be before ${s.maxDate}`)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ne(s){let e=zod.z.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function _e(s){let e=zod.z.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ue(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function ze(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);s.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=s.hasMany?zod.z.array(zod.z.string()):zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function He(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);e=zod.z.enum(t);}else e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Me(s){let e=zod.z.string();return s.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),s.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),s.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Be(s){let e=zod.z.array(zod.z.record(zod.z.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ve(s){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function We(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function ve(s){let e;if(s.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ye(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ce(s){let e;return Array.isArray(s.relationTo)?e=zod.z.object({relationTo:zod.z.enum(s.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Je(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,y(n)]))).passthrough(),t=zod.z.array(e);return s.minRows&&(t=t.min(s.minRows)),s.maxRows&&(t=t.max(s.maxRows)),s.required||(t=t.optional().nullable()),s.validate&&(t=f(t,s.validate)),t}function Qe(s){let e=zod.z.array(zod.z.string());return s.required||(e=e.optional().nullable()),e}function Xe(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])));return s.required?e:e.optional().nullable()}function et(s){let e=s.blocks||[];e.map(o=>zod.z.object({blockType:zod.z.literal(o.slug),...Object.fromEntries(o.fields.filter(r=>r.name).map(r=>[r.name,y(r)]))}));let n=e.map(o=>o.slug),i;if(n.length>0){let o=zod.z.object({blockType:zod.z.enum(n)}).catchall(zod.z.any()),r=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());i=zod.z.array(zod.z.union([o,r,zod.z.record(zod.z.any())]));}else i=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return s.minRows&&(i=i.min(s.minRows)),s.maxRows&&(i=i.max(s.maxRows)),s.required||(i=i.optional().nullable()),s.validate&&(i=f(i,s.validate)),i}function tt(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function st(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function it(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=y(n));return zod.z.object(e).passthrough().optional()}function f(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function S(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=S(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else {if(!t.name)continue;e[t.name]=y(t);}return e}function A(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=A(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=zod.z.object(A(t.fields)).passthrough().optional().nullable():Object.assign(e,A(t.fields));else {if(!t.name)continue;e[t.name]=y(t).optional().nullable();}return e}function xe(s){let e=S(s.fields);return s.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),s.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ae(s){let e=S(s.fields);return zod.z.object(e).passthrough()}function we(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let i of t.fields)i.name&&(n[i.name]=y(i).optional().nullable());Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}function ke(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Se(s){let e=S(s.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Te(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}var R=class{storageProviders=chunkHACW42ZZ_cjs.e();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e,fields:[...e.fields]};for(let i of this.plugins){let o=i.extensions?.collections?.find(r=>r.slug===t.slug);o&&(t={...t,...o.config,fields:[...t.fields,...o.config.fields||[]]});}if(t.seo){let i=chunkDCKJT247_cjs.a(),o=t.fields.findIndex(r=>r.type==="tabs");if(o!==-1){let r=t.fields[o];t.fields[o]={...r,tabs:[...r.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let n=N(t);if(n.length>0)throw new Error(`Invalid collection config: ${n.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=_(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let i of this.plugins){let o=i.extensions?.globals?.find(r=>r.slug===n.slug);o&&(n={...n,...o.config,fields:[...n.fields||[],...o.config.fields||[]]});}this.globals.set(n.slug,n),this.clearSchemaCache(`global:${n.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let n=this.collections.get(e);if(n){let o=xe(n);return this.schemaCache.set(e,o),o}let i=this.globals.get(e);if(i){let o=Se(i);return this.schemaCache.set(`global:${e}`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let o=Ae(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let r=we(i);return this.schemaCache.set(t,r),r}let o=this.globals.get(e);if(o){let r=Te(o);return this.schemaCache.set(`global:${e}:update`,r),r}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let o=ke(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return y(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(n=>n.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(n=>n.name==="tenantId")&&t.push({name:"tenantId",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(n=>n.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(n=>n.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(n=>n.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let n=this.globals.get(e);if(n)return n.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),n=new Map,i=o=>{for(let r of o){if(r.name&&n.set(r.name,r),"fields"in r&&r.fields&&i(r.fields),"tabs"in r)for(let c of r.tabs)i(c.fields);if("blocks"in r)for(let c of r.blocks)i(c.fields);}};return i(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();be(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let n=t.collections||[];for(let o of n)o.slug&&!this.hasCollection(o.slug)&&this.addCollection(o);let i=t.globals||[];for(let o of i)o.slug&&!this.hasGlobal(o.slug)&&this.addGlobal(o);}this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let n=this.collections.get(e)?.admin?.useAsTitle;return n||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(i=>i.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},T=null;function ot(){return T||(T=new R),T}function nt(){T=null;}function U(){return T=new R,T}var C=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},O=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[n,i]of Object.entries(t))if(Array.isArray(i))for(let o of i)this.registerHook(n,o);}unregister(e){let t=this.plugins.get(e);if(!t)return;let n=t.getHooks?.()||{};for(let[i,o]of Object.entries(n))if(Array.isArray(o))for(let r of o)this.unregisterHook(i,r);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let n=this.hooks.get(e);if(n){let i=n.indexOf(t);i>-1&&n.splice(i,1);}}async executeHook(e,t){let n=this.hooks.get(e)||[],i=t;for(let o of n)try{let r=await o({...t,data:i});r!==void 0&&(i=r);}catch(r){console.error(`[PluginManager] Error in hook "${e}":`,r);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let n=t.getCollections?.()||[];e.push(...n);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let n=t.getGlobals?.()||[];e.push(...n);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},z=class extends C{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},H=class extends C{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},M=class extends C{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},B=class extends C{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},V=class extends C{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},kt={SEO:z,Analytics:H,Comments:M,Reviews:B,Wishlist:V};var Re=new Set(["type","admin","label","singularLabel","labelPlural","relationTo","required","hasMany","defaultValue","validate","options","dynamicOptions","filterOptions","hooks","min","max","minLength","maxLength","minRows","maxRows","minDate","maxDate","step","integer","variant","pattern","format","fields","tabs","blocks"]);function Fe(s){return typeof s!="object"||s===null||Array.isArray(s)?false:Object.keys(s).some(e=>Re.has(e))}function Z(s,e=""){let t={};for(let[n,i]of Object.entries(s)){let o=e?`${e}.${n}`:n;i&&typeof i=="object"&&!Array.isArray(i)&&!Fe(i)?Object.assign(t,Z(i,o)):t[o]=i;}return t}function v(s,e,t,n=true){let i=e.split(".");if(i.length===0)return false;let o=i[0],r=i.slice(1).join("."),c=o.match(/^(?:tab|tabs)\[(.+?)\]$/i);if(c){let l=c[1].toLowerCase();for(let u of s)if(u.type==="tabs"&&u.tabs&&Array.isArray(u.tabs)){for(let d of u.tabs)if((d.label||d.name||"").toLowerCase()===l&&d.fields&&Array.isArray(d.fields))return v(d.fields,r,t,n)}return false}for(let l of s){if(l.name===o)if(r){if(l.fields&&Array.isArray(l.fields))return v(l.fields,r,t,true);if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true;return false}if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");if(!g)return false;for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields))return v(p.fields,g,t,true);return false}return l.type==="array"&&l.fields&&Array.isArray(l.fields)?v(l.fields,r,t,true):false}else return Object.assign(l,t),true;if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){if(o==="blocks"&&r){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields)&&v(p.fields,g,t,true))return true}for(let d of l.blocks)if(d.slug===o&&d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true}if(!l.name||l.type==="tabs"||l.type==="row"||l.type==="collapsible"){if(l.fields&&Array.isArray(l.fields)&&v(l.fields,e,t,false))return true;if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,e,t,false))return true}}}return n&&!r&&t&&t.type?(s.push({name:o,...t}),true):false}function W(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({slug:o?.slug||i,...o}));function n(i){for(let o of i){if(o.type==="blocks"){Array.isArray(o.blocks)||(o.blocks=[]);for(let r of t){let c=o.blocks.findIndex(l=>l.slug===r.slug);c>=0?o.blocks[c]={...o.blocks[c],...r}:o.blocks.push(r);}return true}if(o.fields&&Array.isArray(o.fields)&&n(o.fields))return true;if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let r of o.tabs)if(r.fields&&Array.isArray(r.fields)&&n(r.fields))return true}}return false}n(s);}function Y(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({label:o?.label||i,...Array.isArray(o)?{fields:o}:o})),n=s.find(i=>i.type==="tabs");if(n&&Array.isArray(n.tabs))for(let i of t){let o=n.tabs.find(r=>(r.label||r.name||"").toLowerCase()===(i.label||i.name||"").toLowerCase());o?(i.fields&&Array.isArray(i.fields)&&(Array.isArray(o.fields)||(o.fields=[]),o.fields.push(...i.fields)),Object.assign(o,i)):n.tabs.push(i);}else {let i=[...s];s.length=0,s.push({type:"tabs",tabs:[{label:"General",fields:i},...t]});}}function J(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,labels:c,label:l,singularLabel:u,labelPlural:d,hidden:g,timestamps:p,versions:h,seo:m,access:b,hooks:x,admin:ie,...oe}=n;if(l&&(t.label=l),u&&(t.singularLabel=u),d&&(t.labelPlural=d),c&&(c.singular&&(t.singularLabel=c.singular),c.plural&&(t.labelPlural=c.plural)),p!==void 0&&(t.timestamps=p),h!==void 0&&(t.versions={...t.versions,...h}),m!==void 0&&(t.seo=m),b&&(t.access={...t.access,...b}),x&&(t.hooks={...t.hooks,...x}),(ie||oe)&&(t.admin={...t.admin,...ie,...oe}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let Ee=Z(i);for(let[Ke,$e]of Object.entries(Ee))v(t.fields,Ke,$e);}}}}function Q(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,label:c,hidden:l,versions:u,access:d,hooks:g,admin:p,...h}=n;if(c&&(t.label=c),u!==void 0&&(t.versions={...t.versions,...u}),d&&(t.access={...t.access,...d}),g&&(t.hooks={...t.hooks,...g}),(p||h)&&(t.admin={...t.admin,...p,...h}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let m=Z(i);for(let[b,x]of Object.entries(m))v(t.fields,b,x);}}}}var at={aws:{type:"aws",configKey:"s3",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1",admin:{placeholder:"us-east-1"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"endpoint",type:"text",label:"Endpoint URL",admin:{placeholder:"https://s3.custom.com"}},{name:"cdnUrl",type:"text",label:"CDN URL",admin:{placeholder:"https://cdn.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}]},r2:{type:"r2",configKey:"r2",displayName:"Cloudflare R2",configFields:[{name:"accountId",type:"text",label:"Account ID",required:true,admin:{placeholder:"Your Cloudflare Account ID"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"publicDevUrl",type:"text",label:"Public Dev URL ID",admin:{placeholder:"pub-xxxxxxxxxxxxxxxx",description:"Enter ONLY the ID (e.g., pub-b8d8c4cc8bcf4d868ddd95efc1b305aa). Do NOT include https:// or the full URL. Found in R2 Dashboard \u2192 Public Dev URL."}},{name:"cdnUrl",type:"text",label:"Custom CDN URL",admin:{placeholder:"https://assets.example.com (optional)"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads (optional)",description:"Optional prefix for all object keys. Do not use '/' as prefix."}}]},gcs:{type:"gcs",configKey:"gcs",displayName:"Google Cloud Storage",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"projectId",type:"text",label:"Project ID"},{name:"clientEmail",type:"text",label:"Client Email"},{name:"privateKey",type:"password",label:"Private Key"},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},digitalocean:{type:"digitalocean",configKey:"digitalocean",displayName:"DigitalOcean Spaces",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"nyc3"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},backblaze:{type:"backblaze",configKey:"backblaze",displayName:"Backblaze B2",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"accountId",type:"text",label:"Account ID"},{name:"applicationKeyId",type:"text",label:"Application Key ID",required:true},{name:"applicationKey",type:"password",label:"Application Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},wasabi:{type:"wasabi",configKey:"wasabi",displayName:"Wasabi",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]}};function rt(s,e){switch(s){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Pe(s,e){return {provider:s,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:rt(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function lt(s,e,t){let n=t[e.configKey]||{};return Pe(s,n)}function ct(s,e,t){let n=t?.[e.configKey]||t;return Pe(s,n)}var X=class extends C{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let n=this.name;for(let i of Object.values(at))t.register({type:i.type,displayName:i.displayName,pluginName:n,configKey:i.configKey,configFields:i.configFields,extractConfig:o=>lt(i.type,i,o),extractRawConfig:o=>ct(i.type,i,o),factory:o=>chunkHACW42ZZ_cjs.a(o)});}},Oe=new X;var ee=class extends C{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:n=>({cloudName:n.cloudinary?.cloudName||"",apiKey:n.cloudinary?.apiKey||"",apiSecret:n.cloudinary?.apiSecret||"",folder:n.cloudinary?.folder,uploadPreset:n.cloudinary?.uploadPreset}),extractRawConfig:n=>{let i=n?.cloudinary||n;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:n=>chunkHACW42ZZ_cjs.b(n)});}},Ze=new ee;var ut=[Oe,Ze],te=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=U(),this.db=e.adapter||e.db,this.pubsub=new chunkFU76HURF_cjs.b(this.registry),this.webhookService=chunkOJBL4CXK_cjs.n(this.db),this.pluginManager=new O;for(let t of ut)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&J(e.collections,e.admin.collectionOverrides),e.globals&&e.admin?.globalOverrides&&Q(e.globals,e.admin.globalOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(chunkN7CDHWQH_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkDCFOVCJX_cjs.a,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},n={slug:chunkOJBL4CXK_cjs.e,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:chunkOJBL4CXK_cjs.f,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},o=this.registry.getGlobals();if(this.db instanceof chunkGWUHIIPO_cjs.c&&this.db.dialect==="postgres"){let r=this.db,c=chunkDCFOVCJX_cjs.a.replace(/-/g,"_");r.schema&&!r.schema[c]&&(r.schema[c]=chunk23RSKVJP_cjs.g);}await this.db.init([...this.registry.getCollections(),t,n,i],o),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),n={};try{let i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(n=i.states);}catch{}for(let i of t)n[i]!==void 0&&e.setPluginEnabled(i,n[i]);}async getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,i=t?.checkSession!==false;return chunkHACW42ZZ_cjs.n({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunk24W5I6SJ_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:i})=>{let o=chunkDCFOVCJX_cjs.c(i),r,c;if(o&&this.db){let u=await chunkDCFOVCJX_cjs.b(o,this.db);u.user&&(r=u.user,c=chunkDCFOVCJX_cjs.d(u));}let l=e?.tenantId;return {db:this.db,registry:this.registry,user:r,req:i,tenantId:l,apiKey:c,relationLoader:new chunk24W5I6SJ_cjs.a({db:this.db,tenantId:l,user:r})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[r,...c]=o.split("."),l=c.join(".");if(l=l.replace(/\.(query|mutate|subscribe)$/,""),!r||!l)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let u=await chunk7KTPBTH5_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),g=chunk7KTPBTH5_cjs.i(u)[r];if(!g)return new Response(JSON.stringify({error:{message:`Collection '${r}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let p=g[l];if(typeof p!="function")return new Response(JSON.stringify({error:{message:`Procedure '${l}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let h={};if(t.method==="POST"||t.method==="PATCH")h=await t.json().catch(()=>({}));else {let x=new URL(t.url).searchParams.get("input");if(x)try{h=JSON.parse(decodeURIComponent(x));}catch{}}let m=h?.["0"]??h,b=await p({...m,collection:r});return new Response(JSON.stringify({result:{data:b}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(h){let m=h.message||"Internal error",b=m.includes("not found")?404:m.includes("denied")||m.includes("authentication required")?403:m.includes("conflict")?409:500,x=b===404?-32601:b===403?-32001:b===409?-32002:-32603;return new Response(JSON.stringify({error:{message:m,code:x,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:b}}}),{status:b,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let n=async r=>{let c=await chunkDCFOVCJX_cjs.b(r,this.db);if(!c.valid)throw new Error(c.error||"Invalid API key");if(!c.user)throw new Error("API key has no associated user");return c.user},i=e?.port||8080,o=globalThis;if(o.__KYRO_WS_SERVER__)try{await o.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=chunkFU76HURF_cjs.e({pubsub:this.pubsub,port:i,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||n}),o.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function pt(s){return new te(s)}function ns(s){let e=pt(s),t=null;return async function(i,o){return t||(t=e.init()),await t,(await e.getREST()).fetch(i,o)}}var je={debug:0,info:1,warn:2,error:3,none:4},se=class{level;constructor(){let e=typeof process<"u"?process.env?.KYRO_LOG_LEVEL:void 0;this.level=e||"info";}setLevel(e){this.level=e;}getLevel(){return this.level}shouldLog(e){return je[e]>=je[this.level]}debug(...e){this.shouldLog("debug")&&console.debug("[Kyro DEBUG]",...e);}info(...e){this.shouldLog("info")&&console.log("[Kyro]",...e);}warn(...e){this.shouldLog("warn")&&console.warn("[Kyro WARN]",...e);}error(...e){this.shouldLog("error")&&console.error("[Kyro ERROR]",...e);}},bs=new se;
|
|
3
|
+
`)}`),this.name="ConfigValidationError",this.errors=e;}};function N(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Collection slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Collection "${s.slug}" has no fields defined`);else {let t=k(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,n]of Object.entries(s.access))typeof n!="boolean"&&typeof n!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(P(s.fields,s.admin.useAsTitle)||e.push(`Collection "${s.slug}" admin.useAsTitle references unknown field "${s.admin.useAsTitle}"`)),s.admin?.defaultColumns)for(let t of s.admin.defaultColumns)P(s.fields,t)||e.push(`Collection "${s.slug}" admin.defaultColumns references unknown field "${t}"`);if(s.upload&&s.upload.fileSize&&s.upload.fileSize<=0&&e.push(`Collection "${s.slug}" upload.fileSize must be positive`),s.versions&&s.versions.maxPerDoc&&s.versions.maxPerDoc<=0&&e.push(`Collection "${s.slug}" versions.maxPerDoc must be positive`),s.auth){let t=s.fields.some(i=>i.name==="email"),n=s.fields.some(i=>i.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),n||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function _(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Global slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Global "${s.slug}" has no fields defined`);else {let t=k(s.fields,`global:${s.slug}`);e.push(...t);}return e}function k(s,e){let t=[],n=new Set;for(let i=0;i<s.length;i++){let o=s[i];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let c=k(o.fields,e);t.push(...c);}else if("tabs"in o)for(let c of o.tabs){let l=k(c.fields,e);t.push(...l);}continue}let r=o.name;if(!r){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(n.has(r)&&t.push(`${e}: Duplicate field name "${r}"`),n.add(r),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r)||t.push(`${e}: Field name "${r}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${r}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${r}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${r}" has no blocks defined`);else {let c=Ie(o.blocks,`${e}.${r}`);t.push(...c);}break;case "select":case "radio":if(typeof o.options=="function")break;if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${r}" has no options defined`);else if(Array.isArray(o.options)){let c=o.options.map(u=>typeof u=="object"&&u!==null&&"value"in u?u.value:u),l=new Set(c);c.length!==l.size&&t.push(`${e}: ${o.type} field "${r}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${r}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${r}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${r}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${r}" has minRows greater than maxRows`);}return t}function Ie(s,e){let t=[],n=new Set;for(let i of s){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),n.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let o=k(i.fields,`${e}.${i.slug}`);t.push(...o);}}return t}function be(s,e=[]){let t=[],n=new Set;for(let i of s)n.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),n.add(i.slug);for(let i of e)n.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),n.add(i.slug);for(let i of s){let o=N(i);t.push(...o);}for(let i of e){let o=_(i);t.push(...o);}for(let i of s){let o=F(i.fields,s);t.push(...o);}if(t.length>0)throw new G(t)}function F(s,e){let t=[],n=new Set(e.map(i=>i.slug));for(let i of s){if(i.type==="relationship"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)r!=="*"&&!n.has(r)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${r}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)n.has(r)||t.push(`Upload field "${i.name}" references unknown collection "${r}"`);}if("fields"in i&&i.fields){let o=F(i.fields,e);t.push(...o);}if("tabs"in i)for(let o of i.tabs){let r=F(o.fields,e);t.push(...r);}if("blocks"in i)for(let o of i.blocks){let r=F(o.fields,e);t.push(...r);}}return t}function y(s){switch(s.type){case "text":return qe(s);case "number":return Le(s);case "checkbox":return De(s);case "date":return Ge(s);case "email":return Ne(s);case "password":return _e(s);case "textarea":return Ue(s);case "select":return ze(s);case "radio":return He(s);case "color":return Me(s);case "richtext":return Be(s);case "json":return Ve(s);case "code":return We(s);case "upload":return ve(s);case "image":return ve(s);case "markdown":return Ye(s);case "relationship":return Ce(s);case "relationship-block":return Ce(s);case "array":return Je(s);case "list":return Qe(s);case "group":return Xe(s);case "blocks":return et(s);case "row":return tt(s);case "collapsible":return st(s);case "tabs":return it(s);default:return zod.z.any()}}function qe(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.pattern&&(e=e.regex(new RegExp(s.pattern))),s.variant==="email"&&(e=e.email()),s.variant==="url"&&(e=e.url()),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Le(s){let e=s.integer?zod.z.coerce.number().int():zod.z.coerce.number();return s.min!==void 0&&(e=e.min(s.min)),s.max!==void 0&&(e=e.max(s.max)),s.step&&(e=e.refine(t=>Number.isInteger(t/s.step),`Value must be divisible by ${s.step}`)),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function De(s){let e=zod.z.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ge(s){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return s.minDate&&(e=e.refine(t=>new Date(t)>=new Date(s.minDate),`Date must be after ${s.minDate}`)),s.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(s.maxDate),`Date must be before ${s.maxDate}`)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ne(s){let e=zod.z.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function _e(s){let e=zod.z.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ue(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function ze(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);s.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=s.hasMany?zod.z.array(zod.z.string()):zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function He(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);e=zod.z.enum(t);}else e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Me(s){let e=zod.z.string();return s.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),s.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),s.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Be(s){let e=zod.z.array(zod.z.record(zod.z.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ve(s){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function We(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function ve(s){let e;if(s.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ye(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ce(s){let e;return Array.isArray(s.relationTo)?e=zod.z.object({relationTo:zod.z.enum(s.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Je(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,y(n)]))).passthrough(),t=zod.z.array(e);return s.minRows&&(t=t.min(s.minRows)),s.maxRows&&(t=t.max(s.maxRows)),s.required||(t=t.optional().nullable()),s.validate&&(t=f(t,s.validate)),t}function Qe(s){let e=zod.z.array(zod.z.string());return s.required||(e=e.optional().nullable()),e}function Xe(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])));return s.required?e:e.optional().nullable()}function et(s){let e=s.blocks||[];e.map(o=>zod.z.object({blockType:zod.z.literal(o.slug),...Object.fromEntries(o.fields.filter(r=>r.name).map(r=>[r.name,y(r)]))}));let n=e.map(o=>o.slug),i;if(n.length>0){let o=zod.z.object({blockType:zod.z.enum(n)}).catchall(zod.z.any()),r=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());i=zod.z.array(zod.z.union([o,r,zod.z.record(zod.z.any())]));}else i=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return s.minRows&&(i=i.min(s.minRows)),s.maxRows&&(i=i.max(s.maxRows)),s.required||(i=i.optional().nullable()),s.validate&&(i=f(i,s.validate)),i}function tt(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function st(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function it(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=y(n));return zod.z.object(e).passthrough().optional()}function f(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function S(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=S(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else {if(!t.name)continue;e[t.name]=y(t);}return e}function A(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=A(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=zod.z.object(A(t.fields)).passthrough().optional().nullable():Object.assign(e,A(t.fields));else {if(!t.name)continue;e[t.name]=y(t).optional().nullable();}return e}function xe(s){let e=S(s.fields);return s.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),s.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ae(s){let e=S(s.fields);return zod.z.object(e).passthrough()}function we(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let i of t.fields)i.name&&(n[i.name]=y(i).optional().nullable());Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}function ke(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Se(s){let e=S(s.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Te(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}var R=class{storageProviders=chunkO2SA56P2_cjs.e();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e,fields:[...e.fields]};for(let i of this.plugins){let o=i.extensions?.collections?.find(r=>r.slug===t.slug);o&&(t={...t,...o.config,fields:[...t.fields,...o.config.fields||[]]});}if(t.seo){let i=chunkDCKJT247_cjs.a(),o=t.fields.findIndex(r=>r.type==="tabs");if(o!==-1){let r=t.fields[o];t.fields[o]={...r,tabs:[...r.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let n=N(t);if(n.length>0)throw new Error(`Invalid collection config: ${n.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=_(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let i of this.plugins){let o=i.extensions?.globals?.find(r=>r.slug===n.slug);o&&(n={...n,...o.config,fields:[...n.fields||[],...o.config.fields||[]]});}this.globals.set(n.slug,n),this.clearSchemaCache(`global:${n.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let n=this.collections.get(e);if(n){let o=xe(n);return this.schemaCache.set(e,o),o}let i=this.globals.get(e);if(i){let o=Se(i);return this.schemaCache.set(`global:${e}`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let o=Ae(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let r=we(i);return this.schemaCache.set(t,r),r}let o=this.globals.get(e);if(o){let r=Te(o);return this.schemaCache.set(`global:${e}:update`,r),r}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let o=ke(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return y(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(n=>n.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(n=>n.name==="tenantId")&&t.push({name:"tenantId",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(n=>n.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(n=>n.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(n=>n.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let n=this.globals.get(e);if(n)return n.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),n=new Map,i=o=>{for(let r of o){if(r.name&&n.set(r.name,r),"fields"in r&&r.fields&&i(r.fields),"tabs"in r)for(let c of r.tabs)i(c.fields);if("blocks"in r)for(let c of r.blocks)i(c.fields);}};return i(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();be(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let n=t.collections||[];for(let o of n)o.slug&&!this.hasCollection(o.slug)&&this.addCollection(o);let i=t.globals||[];for(let o of i)o.slug&&!this.hasGlobal(o.slug)&&this.addGlobal(o);}this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let n=this.collections.get(e)?.admin?.useAsTitle;return n||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(i=>i.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},T=null;function ot(){return T||(T=new R),T}function nt(){T=null;}function U(){return T=new R,T}var C=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},O=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[n,i]of Object.entries(t))if(Array.isArray(i))for(let o of i)this.registerHook(n,o);}unregister(e){let t=this.plugins.get(e);if(!t)return;let n=t.getHooks?.()||{};for(let[i,o]of Object.entries(n))if(Array.isArray(o))for(let r of o)this.unregisterHook(i,r);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let n=this.hooks.get(e);if(n){let i=n.indexOf(t);i>-1&&n.splice(i,1);}}async executeHook(e,t){let n=this.hooks.get(e)||[],i=t;for(let o of n)try{let r=await o({...t,data:i});r!==void 0&&(i=r);}catch(r){console.error(`[PluginManager] Error in hook "${e}":`,r);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let n=t.getCollections?.()||[];e.push(...n);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let n=t.getGlobals?.()||[];e.push(...n);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},z=class extends C{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},H=class extends C{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},M=class extends C{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},B=class extends C{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},V=class extends C{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},kt={SEO:z,Analytics:H,Comments:M,Reviews:B,Wishlist:V};var Re=new Set(["type","admin","label","singularLabel","labelPlural","relationTo","required","hasMany","defaultValue","validate","options","dynamicOptions","filterOptions","hooks","min","max","minLength","maxLength","minRows","maxRows","minDate","maxDate","step","integer","variant","pattern","format","fields","tabs","blocks"]);function Fe(s){return typeof s!="object"||s===null||Array.isArray(s)?false:Object.keys(s).some(e=>Re.has(e))}function Z(s,e=""){let t={};for(let[n,i]of Object.entries(s)){let o=e?`${e}.${n}`:n;i&&typeof i=="object"&&!Array.isArray(i)&&!Fe(i)?Object.assign(t,Z(i,o)):t[o]=i;}return t}function v(s,e,t,n=true){let i=e.split(".");if(i.length===0)return false;let o=i[0],r=i.slice(1).join("."),c=o.match(/^(?:tab|tabs)\[(.+?)\]$/i);if(c){let l=c[1].toLowerCase();for(let u of s)if(u.type==="tabs"&&u.tabs&&Array.isArray(u.tabs)){for(let d of u.tabs)if((d.label||d.name||"").toLowerCase()===l&&d.fields&&Array.isArray(d.fields))return v(d.fields,r,t,n)}return false}for(let l of s){if(l.name===o)if(r){if(l.fields&&Array.isArray(l.fields))return v(l.fields,r,t,true);if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true;return false}if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");if(!g)return false;for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields))return v(p.fields,g,t,true);return false}return l.type==="array"&&l.fields&&Array.isArray(l.fields)?v(l.fields,r,t,true):false}else return Object.assign(l,t),true;if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){if(o==="blocks"&&r){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields)&&v(p.fields,g,t,true))return true}for(let d of l.blocks)if(d.slug===o&&d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true}if(!l.name||l.type==="tabs"||l.type==="row"||l.type==="collapsible"){if(l.fields&&Array.isArray(l.fields)&&v(l.fields,e,t,false))return true;if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,e,t,false))return true}}}return n&&!r&&t&&t.type?(s.push({name:o,...t}),true):false}function W(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({slug:o?.slug||i,...o}));function n(i){for(let o of i){if(o.type==="blocks"){Array.isArray(o.blocks)||(o.blocks=[]);for(let r of t){let c=o.blocks.findIndex(l=>l.slug===r.slug);c>=0?o.blocks[c]={...o.blocks[c],...r}:o.blocks.push(r);}return true}if(o.fields&&Array.isArray(o.fields)&&n(o.fields))return true;if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let r of o.tabs)if(r.fields&&Array.isArray(r.fields)&&n(r.fields))return true}}return false}n(s);}function Y(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({label:o?.label||i,...Array.isArray(o)?{fields:o}:o})),n=s.find(i=>i.type==="tabs");if(n&&Array.isArray(n.tabs))for(let i of t){let o=n.tabs.find(r=>(r.label||r.name||"").toLowerCase()===(i.label||i.name||"").toLowerCase());o?(i.fields&&Array.isArray(i.fields)&&(Array.isArray(o.fields)||(o.fields=[]),o.fields.push(...i.fields)),Object.assign(o,i)):n.tabs.push(i);}else {let i=[...s];s.length=0,s.push({type:"tabs",tabs:[{label:"General",fields:i},...t]});}}function J(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,labels:c,label:l,singularLabel:u,labelPlural:d,hidden:g,timestamps:p,versions:h,seo:m,access:b,hooks:x,admin:ie,...oe}=n;if(l&&(t.label=l),u&&(t.singularLabel=u),d&&(t.labelPlural=d),c&&(c.singular&&(t.singularLabel=c.singular),c.plural&&(t.labelPlural=c.plural)),p!==void 0&&(t.timestamps=p),h!==void 0&&(t.versions={...t.versions,...h}),m!==void 0&&(t.seo=m),b&&(t.access={...t.access,...b}),x&&(t.hooks={...t.hooks,...x}),(ie||oe)&&(t.admin={...t.admin,...ie,...oe}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let Ee=Z(i);for(let[Ke,$e]of Object.entries(Ee))v(t.fields,Ke,$e);}}}}function Q(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,label:c,hidden:l,versions:u,access:d,hooks:g,admin:p,...h}=n;if(c&&(t.label=c),u!==void 0&&(t.versions={...t.versions,...u}),d&&(t.access={...t.access,...d}),g&&(t.hooks={...t.hooks,...g}),(p||h)&&(t.admin={...t.admin,...p,...h}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let m=Z(i);for(let[b,x]of Object.entries(m))v(t.fields,b,x);}}}}var at={aws:{type:"aws",configKey:"s3",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1",admin:{placeholder:"us-east-1"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"endpoint",type:"text",label:"Endpoint URL",admin:{placeholder:"https://s3.custom.com"}},{name:"cdnUrl",type:"text",label:"CDN URL",admin:{placeholder:"https://cdn.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}]},r2:{type:"r2",configKey:"r2",displayName:"Cloudflare R2",configFields:[{name:"accountId",type:"text",label:"Account ID",required:true,admin:{placeholder:"Your Cloudflare Account ID"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"publicDevUrl",type:"text",label:"Public Dev URL ID",admin:{placeholder:"pub-xxxxxxxxxxxxxxxx",description:"Enter ONLY the ID (e.g., pub-b8d8c4cc8bcf4d868ddd95efc1b305aa). Do NOT include https:// or the full URL. Found in R2 Dashboard \u2192 Public Dev URL."}},{name:"cdnUrl",type:"text",label:"Custom CDN URL",admin:{placeholder:"https://assets.example.com (optional)"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads (optional)",description:"Optional prefix for all object keys. Do not use '/' as prefix."}}]},gcs:{type:"gcs",configKey:"gcs",displayName:"Google Cloud Storage",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"projectId",type:"text",label:"Project ID"},{name:"clientEmail",type:"text",label:"Client Email"},{name:"privateKey",type:"password",label:"Private Key"},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},digitalocean:{type:"digitalocean",configKey:"digitalocean",displayName:"DigitalOcean Spaces",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"nyc3"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},backblaze:{type:"backblaze",configKey:"backblaze",displayName:"Backblaze B2",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"accountId",type:"text",label:"Account ID"},{name:"applicationKeyId",type:"text",label:"Application Key ID",required:true},{name:"applicationKey",type:"password",label:"Application Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},wasabi:{type:"wasabi",configKey:"wasabi",displayName:"Wasabi",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]}};function rt(s,e){switch(s){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Pe(s,e){return {provider:s,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:rt(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function lt(s,e,t){let n=t[e.configKey]||{};return Pe(s,n)}function ct(s,e,t){let n=t?.[e.configKey]||t;return Pe(s,n)}var X=class extends C{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let n=this.name;for(let i of Object.values(at))t.register({type:i.type,displayName:i.displayName,pluginName:n,configKey:i.configKey,configFields:i.configFields,extractConfig:o=>lt(i.type,i,o),extractRawConfig:o=>ct(i.type,i,o),factory:o=>chunkO2SA56P2_cjs.a(o)});}},Oe=new X;var ee=class extends C{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:n=>({cloudName:n.cloudinary?.cloudName||"",apiKey:n.cloudinary?.apiKey||"",apiSecret:n.cloudinary?.apiSecret||"",folder:n.cloudinary?.folder,uploadPreset:n.cloudinary?.uploadPreset}),extractRawConfig:n=>{let i=n?.cloudinary||n;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:n=>chunkO2SA56P2_cjs.b(n)});}},Ze=new ee;var ut=[Oe,Ze],te=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=U(),this.db=e.adapter||e.db,this.pubsub=new chunkFU76HURF_cjs.b(this.registry),this.webhookService=chunkOJBL4CXK_cjs.n(this.db),this.pluginManager=new O;for(let t of ut)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&J(e.collections,e.admin.collectionOverrides),e.globals&&e.admin?.globalOverrides&&Q(e.globals,e.admin.globalOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(chunkN7CDHWQH_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkDCFOVCJX_cjs.a,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},n={slug:chunkOJBL4CXK_cjs.e,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:chunkOJBL4CXK_cjs.f,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},o=this.registry.getGlobals();if(this.db instanceof chunkGWUHIIPO_cjs.c&&this.db.dialect==="postgres"){let r=this.db,c=chunkDCFOVCJX_cjs.a.replace(/-/g,"_");r.schema&&!r.schema[c]&&(r.schema[c]=chunk23RSKVJP_cjs.g);}await this.db.init([...this.registry.getCollections(),t,n,i],o),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),n={};try{let i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(n=i.states);}catch{}for(let i of t)n[i]!==void 0&&e.setPluginEnabled(i,n[i]);}async getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,i=t?.checkSession!==false;return chunkO2SA56P2_cjs.n({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunk24W5I6SJ_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:i})=>{let o=chunkDCFOVCJX_cjs.c(i),r,c;if(o&&this.db){let u=await chunkDCFOVCJX_cjs.b(o,this.db);u.user&&(r=u.user,c=chunkDCFOVCJX_cjs.d(u));}let l=e?.tenantId;return {db:this.db,registry:this.registry,user:r,req:i,tenantId:l,apiKey:c,relationLoader:new chunk24W5I6SJ_cjs.a({db:this.db,tenantId:l,user:r})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[r,...c]=o.split("."),l=c.join(".");if(l=l.replace(/\.(query|mutate|subscribe)$/,""),!r||!l)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let u=await chunk7KTPBTH5_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),g=chunk7KTPBTH5_cjs.i(u)[r];if(!g)return new Response(JSON.stringify({error:{message:`Collection '${r}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let p=g[l];if(typeof p!="function")return new Response(JSON.stringify({error:{message:`Procedure '${l}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let h={};if(t.method==="POST"||t.method==="PATCH")h=await t.json().catch(()=>({}));else {let x=new URL(t.url).searchParams.get("input");if(x)try{h=JSON.parse(decodeURIComponent(x));}catch{}}let m=h?.["0"]??h,b=await p({...m,collection:r});return new Response(JSON.stringify({result:{data:b}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(h){let m=h.message||"Internal error",b=m.includes("not found")?404:m.includes("denied")||m.includes("authentication required")?403:m.includes("conflict")?409:500,x=b===404?-32601:b===403?-32001:b===409?-32002:-32603;return new Response(JSON.stringify({error:{message:m,code:x,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:b}}}),{status:b,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let n=async r=>{let c=await chunkDCFOVCJX_cjs.b(r,this.db);if(!c.valid)throw new Error(c.error||"Invalid API key");if(!c.user)throw new Error("API key has no associated user");return c.user},i=e?.port||8080,o=globalThis;if(o.__KYRO_WS_SERVER__)try{await o.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=chunkFU76HURF_cjs.e({pubsub:this.pubsub,port:i,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||n}),o.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function pt(s){return new te(s)}function ns(s){let e=pt(s),t=null;return async function(i,o){return t||(t=e.init()),await t,(await e.getREST()).fetch(i,o)}}var je={debug:0,info:1,warn:2,error:3,none:4},se=class{level;constructor(){let e=typeof process<"u"?process.env?.KYRO_LOG_LEVEL:void 0;this.level=e||"info";}setLevel(e){this.level=e;}getLevel(){return this.level}shouldLog(e){return je[e]>=je[this.level]}debug(...e){this.shouldLog("debug")&&console.debug("[Kyro DEBUG]",...e);}info(...e){this.shouldLog("info")&&console.log("[Kyro]",...e);}warn(...e){this.shouldLog("warn")&&console.warn("[Kyro WARN]",...e);}error(...e){this.shouldLog("error")&&console.error("[Kyro ERROR]",...e);}},bs=new se;
|
|
4
4
|
exports.A=v;exports.B=W;exports.C=Y;exports.D=J;exports.E=Q;exports.F=te;exports.G=pt;exports.H=ns;exports.I=se;exports.J=bs;exports.a=G;exports.b=N;exports.c=_;exports.d=k;exports.e=be;exports.f=y;exports.g=xe;exports.h=Ae;exports.i=we;exports.j=ke;exports.k=Se;exports.l=R;exports.m=ot;exports.n=nt;exports.o=U;exports.p=C;exports.q=O;exports.r=z;exports.s=H;exports.t=M;exports.u=B;exports.v=V;exports.w=kt;exports.x=Re;exports.y=Fe;exports.z=Z;
|