@kyro-cms/core 0.10.8 → 0.10.11
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/{chunk-F3Z67QWS.cjs → chunk-3HVN4CBK.cjs} +1 -1
- package/dist/{chunk-TD6RULJU.cjs → chunk-6OXKGEY7.cjs} +2 -2
- package/dist/{chunk-ZELCS7IC.js → chunk-J66TVKOB.js} +3 -3
- package/dist/chunk-JAOX6WGD.cjs +1 -0
- package/dist/{chunk-POWTSLKC.js → chunk-KSWGDCZE.js} +2 -2
- package/dist/{chunk-ELICKLFM.cjs → chunk-OGS3MZXN.cjs} +3 -3
- package/dist/{chunk-PWGS2GPI.js → chunk-SW7WHMNI.js} +1 -1
- package/dist/chunk-TQW43BLR.js +1 -0
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.d.cts +0 -1
- package/dist/rest/index.d.ts +0 -1
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-MSSRVZH6.js +0 -1
- package/dist/chunk-Y7K26TBA.cjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkJAOX6WGD_cjs=require('./chunk-JAOX6WGD.cjs');require('./chunk-6OXKGEY7.cjs'),require('./chunk-UJNSOOYZ.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-CVVW4LXZ.cjs'),require('./chunk-CIE3XMLH.cjs'),require('./chunk-3HVN4CBK.cjs'),require('./chunk-AJAZ7D3W.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GFU7AOI3.cjs'),require('./chunk-ET6NN2V2.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ISWMETHJ.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-F7SR5IDT.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-6CLRVJPP.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-UBHFUFD4.cjs'),require('./chunk-UDSJGML2.cjs'),require('./chunk-ATLSIYRH.cjs'),require('./chunk-DV4LFLPL.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');function n(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function r(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await chunkJAOX6WGD_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await chunkJAOX6WGD_cjs.b(),!await o())return r();let t=await chunkJAOX6WGD_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await chunkJAOX6WGD_cjs.b(),!await o())return r();let t=await chunkJAOX6WGD_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)};exports.GET=u;exports.POST=l;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b,a
|
|
1
|
+
import {b,a}from'./chunk-TQW43BLR.js';import'./chunk-KSWGDCZE.js';import'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';import'./chunk-7N6NKCRT.js';import'./chunk-R6UUTH3T.js';import'./chunk-SW7WHMNI.js';import'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';import'./chunk-UVTS2IWM.js';import'./chunk-HLSB2MCK.js';import'./chunk-SL3LZQCF.js';import'./chunk-PP5S2UBV.js';import'./chunk-VKXQUYYV.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';import'./chunk-G6A7OSIG.js';import'./chunk-P7CESLDJ.js';import'./chunk-ZAQOSRP6.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';function n(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function r(){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 l=async e=>{if(await b(),!await o())return r();let t=await a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await b(),!await o())return r();let t=await a.getGraphQL().fetch(e.request,e.locals);return n(t)};export{u as GET,l as POST};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkJAOX6WGD_cjs=require('./chunk-JAOX6WGD.cjs');require('./chunk-6OXKGEY7.cjs'),require('./chunk-UJNSOOYZ.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-CVVW4LXZ.cjs'),require('./chunk-CIE3XMLH.cjs'),require('./chunk-3HVN4CBK.cjs'),require('./chunk-AJAZ7D3W.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GFU7AOI3.cjs'),require('./chunk-ET6NN2V2.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ISWMETHJ.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-F7SR5IDT.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-6CLRVJPP.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-UBHFUFD4.cjs'),require('./chunk-UDSJGML2.cjs'),require('./chunk-ATLSIYRH.cjs'),require('./chunk-DV4LFLPL.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');function n(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var r={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await chunkJAOX6WGD_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await chunkJAOX6WGD_cjs.b(),await s()?chunkJAOX6WGD_cjs.a.getTRPC().fetch(e.request,e.locals):n());exports.ALL=i;
|
package/dist/api-handler-trpc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b,a}from'./chunk-
|
|
1
|
+
import {b,a}from'./chunk-TQW43BLR.js';import'./chunk-KSWGDCZE.js';import'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';import'./chunk-7N6NKCRT.js';import'./chunk-R6UUTH3T.js';import'./chunk-SW7WHMNI.js';import'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';import'./chunk-UVTS2IWM.js';import'./chunk-HLSB2MCK.js';import'./chunk-SL3LZQCF.js';import'./chunk-PP5S2UBV.js';import'./chunk-VKXQUYYV.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';import'./chunk-G6A7OSIG.js';import'./chunk-P7CESLDJ.js';import'./chunk-ZAQOSRP6.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';function n(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var r={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??r.trpcEnabled}catch{return true}}var i=async e=>(await b(),await s()?a.getTRPC().fetch(e.request,e.locals):n());export{i as ALL};
|
package/dist/api-handler.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkJAOX6WGD_cjs=require('./chunk-JAOX6WGD.cjs');require('./chunk-6OXKGEY7.cjs'),require('./chunk-UJNSOOYZ.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-CVVW4LXZ.cjs'),require('./chunk-CIE3XMLH.cjs'),require('./chunk-3HVN4CBK.cjs'),require('./chunk-AJAZ7D3W.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GFU7AOI3.cjs'),require('./chunk-ET6NN2V2.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ISWMETHJ.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-F7SR5IDT.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-6CLRVJPP.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-UBHFUFD4.cjs'),require('./chunk-UDSJGML2.cjs'),require('./chunk-ATLSIYRH.cjs'),require('./chunk-DV4LFLPL.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');Object.defineProperty(exports,"ALL",{enumerable:true,get:function(){return chunkJAOX6WGD_cjs.c}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunkJAOX6WGD_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunkJAOX6WGD_cjs.b}});
|
package/dist/api-handler.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{c as ALL,a as kyroInstance,b as warmKyroInstance}from'./chunk-
|
|
1
|
+
export{c as ALL,a as kyroInstance,b as warmKyroInstance}from'./chunk-TQW43BLR.js';import'./chunk-KSWGDCZE.js';import'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';import'./chunk-7N6NKCRT.js';import'./chunk-R6UUTH3T.js';import'./chunk-SW7WHMNI.js';import'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';import'./chunk-UVTS2IWM.js';import'./chunk-HLSB2MCK.js';import'./chunk-SL3LZQCF.js';import'./chunk-PP5S2UBV.js';import'./chunk-VKXQUYYV.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';import'./chunk-G6A7OSIG.js';import'./chunk-P7CESLDJ.js';import'./chunk-ZAQOSRP6.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
`),await this.db.execute(e`CREATE INDEX IF NOT EXISTS "idx_media_folders_path" ON "media_folders" ("path")`),Ht=true;}}now(){return new Date().toISOString()}buildFindConditions(e){let t=[],a=[],i=e.sortBy==="name"?"title":e.sortBy==="createdAt"?"created_at":e.sortBy==="updatedAt"?"updated_at":e.sortBy||"created_at",c=e.sortDir==="asc"?"ASC":"DESC";if(e.search){t.push("(title LIKE ? OR filename LIKE ? OR original_name LIKE ? OR alt LIKE ?)");let u=`%${e.search}%`;a.push(u,u,u,u);}return e.type&&e.type!=="all"&&(t.push("mime_type LIKE ?"),a.push(`${e.type}/%`)),e.folder&&(t.push("(folder = ? OR folder LIKE ?)"),a.push(e.folder,`${e.folder}/%`)),{where:t.length>0?`WHERE ${t.join(" AND ")}`:"",params:a,orderBy:c,sortCol:i}}rowToMedia(e,t){return {id:e.id,filename:e.filename,title:e.title??null,originalName:e.original_name??e.originalName,mimeType:e.mime_type??e.mimeType,fileSize:e.file_size??e.fileSize,width:e.width??null,height:e.height??null,url:d.resolveMediaUrl(e.url,t),thumbnailUrl:d.resolveMediaUrl(e.thumbnail_url??e.thumbnailUrl??null,t),folder:e.folder??null,provider:e.provider,alt:e.alt??null,caption:e.caption??null,metadata:e.metadata??null,createdAt:e.created_at??e.createdAt,updatedAt:e.updated_at??e.updatedAt}}static resolveMediaUrl(e,t){return e?e.startsWith("http://")||e.startsWith("https://")||e.startsWith("blob:")||e.startsWith("data:")?e:`${(process.env.KYRO_BASE_URL||t||"http://localhost:4321").replace(/\/+$/,"")}${e.startsWith("/")?"":"/"}${e}`:null}async sqliteRun(e,t=[]){let a=this.db.prepare(e),i=e.trim().toLowerCase();return i.startsWith("insert")||i.startsWith("update")||i.startsWith("delete")?a.run(...t):a.all(...t)}sqliteGet(e,t=[]){return this.db.prepare(e).get(...t)}async upload(e,t=""){let a=e.type.startsWith("image/"),i,c=e,l=e.name,u=null,g=null;if(a&&!e.type.includes("svg")){let T=Buffer.from(await e.arrayBuffer());i=await Vt(T),l=`${e.name.replace(/\.[^/.]+$/,"").toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").substring(0,50)}.webp`,u=i.width??null,g=i.height??null,c=new File([i.buffer],l,{type:"image/webp"});}let f=await this.storage.upload(c,{folder:t,filename:l}),A=await this.storage.generateThumbnail({...f,id:"",provider:this.storage.name,createdAt:this.now()},{width:400,height:400}),w=this.genId(),U=this.now();if(this.dialect==="sqlite")await this.sqliteRun(`INSERT INTO ${this.mediaTable}
|
|
62
62
|
(id, filename, title, original_name, mime_type, file_size, width, height, url, thumbnail_url, folder, provider, alt, caption, metadata, created_at, updated_at)
|
|
63
63
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[w,f.filename,e.name.replace(/\.[^/.]+$/,""),e.name,f.mimeType,f.size,u,g,f.url,A,t||null,this.storage.name,null,null,null,U,U]);else {let{media:T}=await import('./media-OUBQTIQP.cjs'),k=f.mimeType,N=k.startsWith("image/")?"image":k.startsWith("video/")?"video":k.startsWith("audio/")?"audio":k.startsWith("application/pdf")?"document":["application/zip","application/x-zip","application/x-tar","application/gzip","application/x-7z"].includes(k)?"archive":"other";await this.db.insert(T).values({id:w,filename:f.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:k,fileSize:f.size,width:u,height:g,url:f.url,thumbnailUrl:A,folder:t||"",provider:this.storage.name,type:N,status:"active",alt:null,caption:null,createdAt:new Date,updatedAt:new Date}).returning();}return {id:w,filename:f.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:f.mimeType,fileSize:f.size,width:u,height:g,url:f.url,thumbnailUrl:A,folder:t||null,provider:this.storage.name,alt:null,caption:null,metadata:null,createdAt:U,updatedAt:U}}async uploadFromUrl(e,t=""){let a=await fetch(e);if(!a.ok)throw new Error(`Failed to fetch URL: ${a.status}`);let i=await a.blob(),c=e.split("/").pop()||"url-image",l=a.headers.get("content-type")||i.type||"application/octet-stream",u=new File([i],c,{type:l});return this.upload(u,t)}async delete(e,t){let a=await this.findById(e,t);if(a){if(await this.deleteFile(a.url),a.thumbnailUrl&&a.thumbnailUrl!==a.url&&a.thumbnailUrl!==a.url+"?thumb")try{await this.deleteFile(a.thumbnailUrl);}catch{}if(this.dialect==="sqlite")await this.sqliteRun(`DELETE FROM ${this.mediaTable} WHERE id = ?`,[e]);else {let{media:i}=await import('./media-OUBQTIQP.cjs'),{eq:c}=await import('drizzle-orm');await this.db.delete(i).where(c(i.id,e));}}}async deleteFile(e){await this.storage.delete(e);}async rename(e,t,a){let i=await this.findById(e,a);if(!i)return null;let c=await this.storage.rename(i.url,t),l;if(i.thumbnailUrl||this.storage.name==="cloudinary"){let A=c.match(/\/upload\/(v\d+)\//),w=A?A[1]+"/":"",U=c.match(/(.+?)\/upload\//);l=`${U?U[1]:"https://res.cloudinary.com/"+this.storage.config?.cloudName||"unknown"}/upload/w_200,h_200,c_fill/${w}${t}`;}let u=i.filename.split(".").pop(),g=t.includes(".")?t:`${t}.${u}`,f={url:c,filename:g,thumbnailUrl:l};if(this.dialect==="sqlite"){let A={...f};"thumbnailUrl"in A&&(A.thumbnail_url=A.thumbnailUrl,delete A.thumbnailUrl);let w=Object.keys(A).map(T=>`${T} = ?`).join(", "),U=Object.values(A);await this.sqliteRun(`UPDATE ${this.mediaTable} SET ${w}, updated_at = ? WHERE id = ?`,[...U,this.now(),e]);}else {let{media:A}=await import('./media-OUBQTIQP.cjs'),{eq:w}=await import('drizzle-orm');await this.db.update(A).set({...f,updatedAt:this.now()}).where(w(A.id,e));}return {...i,...f,updatedAt:this.now(),thumbnailUrl:f.thumbnailUrl??null}}async findById(e,t){if(this.dialect==="sqlite"){let l=this.sqliteGet(`SELECT * FROM ${this.mediaTable} WHERE id = ?`,[e]);return l?this.rowToMedia(l,t):null}let{media:a}=await import('./media-OUBQTIQP.cjs'),{eq:i}=await import('drizzle-orm'),[c]=await this.db.select().from(a).where(i(a.id,e));return c?this.rowToMedia(c,t):null}async find(e={},t){let{page:a=1,limit:i=30,search:c="",type:l="",folder:u="",sortBy:g="createdAt",sortDir:f="desc"}=e,{where:A,params:w,orderBy:U,sortCol:T}=this.buildFindConditions({page:a,limit:i,search:c,type:l,folder:u,sortBy:g,sortDir:f}),k=(a-1)*i;if(this.dialect==="sqlite"){let le=this.sqliteGet(`SELECT COUNT(*) as cnt FROM ${this.mediaTable} ${A}`,w)?.cnt??0;return {docs:(await this.sqliteRun(`SELECT * FROM ${this.mediaTable} ${A} ORDER BY ${T} ${U} LIMIT ? OFFSET ?`,[...w,i,k])).map(de=>this.rowToMedia(de,t)),totalDocs:le,page:a,limit:i,totalPages:Math.ceil(le/i)}}let{media:N}=await import('./media-OUBQTIQP.cjs'),{like:M,or:ae,and:C,asc:X,desc:J,eq:D,sql:Z}=await import('drizzle-orm'),ne=[];c&&ne.push(ae(M(N.title,`%${c}%`),M(N.filename,`%${c}%`),M(N.originalName,`%${c}%`),M(N.alt,`%${c}%`))),l&&l!=="all"&&ne.push(M(N.mimeType,`${l}/%`)),u&&ne.push(ae(D(N.folder,u),M(N.folder,`${u}/%`)));let we=ne.length>0?C(...ne):void 0,Oe=N[{created_at:"createdAt",updated_at:"updatedAt",title:"title",filename:"filename",file_size:"fileSize",mime_type:"mimeType",original_name:"originalName"}[T]||"createdAt"],Ie=f==="asc"?X(Oe):J(Oe),fe=await this.db.select().from(N).where(we).orderBy(Ie).limit(i).offset(k),[{count:K}]=await this.db.select({count:Z`count(*)`}).from(N).where(we),ie=Number(K);return {docs:fe.map(oe=>this.rowToMedia(oe,t)),totalDocs:ie,page:a,limit:i,totalPages:Math.ceil(ie/i)}}async update(e,t,a){let i=this.now();if(this.dialect==="sqlite"){let g=["updated_at = ?"],f=[i];t.title!==void 0&&(g.push("title = ?"),f.push(t.title)),t.alt!==void 0&&(g.push("alt = ?"),f.push(t.alt)),t.caption!==void 0&&(g.push("caption = ?"),f.push(t.caption)),t.folder!==void 0&&(g.push("folder = ?"),f.push(t.folder)),f.push(e),await this.sqliteRun(`UPDATE ${this.mediaTable} SET ${g.join(", ")} WHERE id = ?`,f);let A=this.sqliteGet(`SELECT * FROM ${this.mediaTable} WHERE id = ?`,[e]);return A?this.rowToMedia(A,a):null}let{media:c}=await import('./media-OUBQTIQP.cjs'),{eq:l}=await import('drizzle-orm'),[u]=await this.db.update(c).set({...t,updatedAt:new Date}).where(l(c.id,e)).returning();return u?this.rowToMedia(u,a):null}async updateMany(e,t){let a=this.now();if(this.dialect==="sqlite")for(let i of e){let c=["updated_at = ?"],l=[a];t.folder!==void 0&&(c.push("folder = ?"),l.push(t.folder||null)),l.push(i),await this.sqliteRun(`UPDATE ${this.mediaTable} SET ${c.join(", ")} WHERE id = ?`,l);}else {let{media:i}=await import('./media-OUBQTIQP.cjs'),{eq:c}=await import('drizzle-orm');for(let l of e)await this.db.update(i).set({...t,updatedAt:new Date}).where(c(i.id,l));}}async listFolders(){if(this.dialect==="sqlite")return (await this.sqliteRun(`SELECT path FROM ${this.foldersTable} UNION
|
|
64
|
-
SELECT folder as path FROM ${this.mediaTable} WHERE folder IS NOT NULL AND folder != ''`)).map(f=>f.path).filter(f=>f&&f!=="").sort();let{media:e,mediaFolders:t}=await import('./media-OUBQTIQP.cjs'),{eq:a,sql:i}=await import('drizzle-orm'),c=await this.db.select({folder:e.folder}).from(e).groupBy(e.folder),l=await this.db.select({path:t.path}).from(t),u=new Set([...c.map(g=>g.folder),...l.map(g=>g.path)]);return Array.from(u).filter(g=>g&&g!=="").sort()}async createFolder(e,t=""){let a=t?`${t}/${e}`:e;await this.storage.createFolder?.(a);let i=this.now();if(this.dialect==="sqlite")await this.sqliteRun(`INSERT OR IGNORE INTO ${this.foldersTable} (path, name, parent_path, created_at) VALUES (?, ?, ?, ?)`,[a,e,t||null,i]);else {let{mediaFolders:c}=await import('./media-OUBQTIQP.cjs');await this.db.insert(c).values({path:a,name:e,parentPath:t||null,createdAt:new Date}).onConflictDoNothing();}}async deleteFolder(e){let t=await this.find({folder:e,limit:1e4});for(let a of t.docs)await this.delete(a.id);if(await this.storage.deleteFolder?.(e),this.dialect==="sqlite")await this.sqliteRun(`DELETE FROM ${this.foldersTable} WHERE path = ? OR path LIKE ?`,[e,`${e}/%`]);else {let{mediaFolders:a}=await import('./media-OUBQTIQP.cjs'),{like:i,or:c,eq:l}=await import('drizzle-orm');await this.db.delete(a).where(c(l(a.path,e),i(a.path,`${e}/%`)));}}};function _e(d){return d.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ")}function me(d,e){if(!(!d||typeof d!="object"))for(let t of e){if(!t.name||!(t.name in d))continue;if(d[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||t.type==="email"||t.type==="password"||t.type==="color"||(d[t.name]=null)),t.type==="tabs"&&t.name&&Array.isArray(t.tabs)&&d[t.name]&&typeof d[t.name]=="object")for(let i of t.tabs)Array.isArray(i.fields)&&me(d[t.name],i.fields);else if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&d[t.name]&&typeof d[t.name]=="object")me(d[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(d[t.name]))for(let i of d[t.name])i&&typeof i=="object"&&me(i,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(d[t.name]))for(let i of d[t.name]){if(!i||typeof i!="object")continue;let c=i.type||i.blockType;if(!c)continue;let l=t.blocks.find(g=>g.slug===c);if(!l||!Array.isArray(l.fields))continue;let u=i.data&&typeof i.data=="object"?i.data:i;me(u,l.fields);}}}function ge(d,e){if(!(!e||typeof e!="object"))for(let t of d){if(t.type==="richtext"&&t.name){let a=e[t.name];typeof a=="string"?e[t.name]=[{type:"paragraph",children:[{text:a}]}]:a&&typeof a=="object"&&!Array.isArray(a)&&a.type==="doc"&&Array.isArray(a.content)&&(e[t.name]=a.content);}if(t.type==="tabs"&&t.name&&Array.isArray(t.tabs)&&e[t.name]&&typeof e[t.name]=="object")for(let a of t.tabs)Array.isArray(a.fields)&&ge(a.fields,e[t.name]);else if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")ge(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let a of e[t.name])a&&typeof a=="object"&&ge(t.fields,a);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let a of e[t.name]){if(!a||typeof a!="object")continue;let i=a.type||a.blockType;if(!i)continue;let c=t.blocks.find(u=>u.slug===i);if(!c||!Array.isArray(c.fields))continue;let l=a.data&&typeof a.data=="object"?a.data:a;ge(c.fields,l);}}}var _r={_media:{create:chunkISWMETHJ_cjs.c.MEDIA_UPLOAD,update:chunkISWMETHJ_cjs.c.MEDIA_UPLOAD,delete:chunkISWMETHJ_cjs.c.MEDIA_DELETE}};function Ae(d,e){let t=_r[d];return t?t[e]:`collection.${e}`}function Fr(d){let e=d.headers.get("x-forwarded-for");return e?e.split(",")[0].trim():d.headers.get("x-real-ip")||"unknown"}function Fe(d,e,t,a,i){e?.apiKeyId&&d&&d.createAuditLog({action:"api_request",userId:e.userId||"",resource:"api_key",resourceId:e.apiKeyId,success:true,metadata:{endpoint:t,method:a,ip:Fr(i)}});}function ut(d){return d.baseUpdatedAt??d._baseUpdatedAt}function pt(d){let{baseUpdatedAt:e,_baseUpdatedAt:t,...a}=d;return a}function Yt(d,e){return {error:"Document has changed since you started editing",code:"REVISION_CONFLICT",conflict:{expectedUpdatedAt:d??null,actualUpdatedAt:e.updatedAt??null,current:e}}}async function _(d,e,t,a,i,c,l=true,u="none"){return await chunkISWMETHJ_cjs.a(d,e,{user:a,req:t,tenantID:i,apiKey:c},{enablePublicAccess:l,defaultAccess:u})}async function Y(d,e,t,a,i,c=true){return await chunkISWMETHJ_cjs.b(d,e,{user:a,req:t,tenantID:i},{enablePublicAccess:c})}async function P(d,e,t,a){if(t)return {user:t,tenantID:a,apiKeyContext:void 0,authType:"static"};if(e){let i=await e(d);if(i.status===200&&i.user)return {user:i.user,tenantID:i.tenantContext?.tenantId,apiKeyContext:i.apiKeyContext,authType:i.authType}}return {user:void 0,tenantID:void 0,apiKeyContext:void 0,authType:void 0}}function Or(d,e){if(d instanceof chunk6CLRVJPP_cjs.c&&d.dialect==="postgres")return new chunkGYQMNXXW_cjs.a({db:d.client});if(d instanceof chunkUDSJGML2_cjs.a)return new chunkATLSIYRH_cjs.a({db:d.db});let t=Ce.resolve(e,"data","kyro.db");return new chunkET6NN2V2_cjs.a({path:process.env.KYRO_AUTH_DB_PATH||t})}function Zt(d){let{registry:e,db:t,authSecret:a,authAdapter:i,checkSession:c,user:l,tenantID:u,cors:g,webhookService:f,settings:A}=d,w=new hono.Hono,U=A?.access?.apiAccess
|
|
64
|
+
SELECT folder as path FROM ${this.mediaTable} WHERE folder IS NOT NULL AND folder != ''`)).map(f=>f.path).filter(f=>f&&f!=="").sort();let{media:e,mediaFolders:t}=await import('./media-OUBQTIQP.cjs'),{eq:a,sql:i}=await import('drizzle-orm'),c=await this.db.select({folder:e.folder}).from(e).groupBy(e.folder),l=await this.db.select({path:t.path}).from(t),u=new Set([...c.map(g=>g.folder),...l.map(g=>g.path)]);return Array.from(u).filter(g=>g&&g!=="").sort()}async createFolder(e,t=""){let a=t?`${t}/${e}`:e;await this.storage.createFolder?.(a);let i=this.now();if(this.dialect==="sqlite")await this.sqliteRun(`INSERT OR IGNORE INTO ${this.foldersTable} (path, name, parent_path, created_at) VALUES (?, ?, ?, ?)`,[a,e,t||null,i]);else {let{mediaFolders:c}=await import('./media-OUBQTIQP.cjs');await this.db.insert(c).values({path:a,name:e,parentPath:t||null,createdAt:new Date}).onConflictDoNothing();}}async deleteFolder(e){let t=await this.find({folder:e,limit:1e4});for(let a of t.docs)await this.delete(a.id);if(await this.storage.deleteFolder?.(e),this.dialect==="sqlite")await this.sqliteRun(`DELETE FROM ${this.foldersTable} WHERE path = ? OR path LIKE ?`,[e,`${e}/%`]);else {let{mediaFolders:a}=await import('./media-OUBQTIQP.cjs'),{like:i,or:c,eq:l}=await import('drizzle-orm');await this.db.delete(a).where(c(l(a.path,e),i(a.path,`${e}/%`)));}}};function _e(d){return d.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ")}function me(d,e){if(!(!d||typeof d!="object"))for(let t of e){if(!t.name||!(t.name in d))continue;if(d[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||t.type==="email"||t.type==="password"||t.type==="color"||(d[t.name]=null)),t.type==="tabs"&&t.name&&Array.isArray(t.tabs)&&d[t.name]&&typeof d[t.name]=="object")for(let i of t.tabs)Array.isArray(i.fields)&&me(d[t.name],i.fields);else if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&d[t.name]&&typeof d[t.name]=="object")me(d[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(d[t.name]))for(let i of d[t.name])i&&typeof i=="object"&&me(i,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(d[t.name]))for(let i of d[t.name]){if(!i||typeof i!="object")continue;let c=i.type||i.blockType;if(!c)continue;let l=t.blocks.find(g=>g.slug===c);if(!l||!Array.isArray(l.fields))continue;let u=i.data&&typeof i.data=="object"?i.data:i;me(u,l.fields);}}}function ge(d,e){if(!(!e||typeof e!="object"))for(let t of d){if(t.type==="richtext"&&t.name){let a=e[t.name];typeof a=="string"?e[t.name]=[{type:"paragraph",children:[{text:a}]}]:a&&typeof a=="object"&&!Array.isArray(a)&&a.type==="doc"&&Array.isArray(a.content)&&(e[t.name]=a.content);}if(t.type==="tabs"&&t.name&&Array.isArray(t.tabs)&&e[t.name]&&typeof e[t.name]=="object")for(let a of t.tabs)Array.isArray(a.fields)&&ge(a.fields,e[t.name]);else if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")ge(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let a of e[t.name])a&&typeof a=="object"&&ge(t.fields,a);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let a of e[t.name]){if(!a||typeof a!="object")continue;let i=a.type||a.blockType;if(!i)continue;let c=t.blocks.find(u=>u.slug===i);if(!c||!Array.isArray(c.fields))continue;let l=a.data&&typeof a.data=="object"?a.data:a;ge(c.fields,l);}}}var _r={_media:{create:chunkISWMETHJ_cjs.c.MEDIA_UPLOAD,update:chunkISWMETHJ_cjs.c.MEDIA_UPLOAD,delete:chunkISWMETHJ_cjs.c.MEDIA_DELETE}};function Ae(d,e){let t=_r[d];return t?t[e]:`collection.${e}`}function Fr(d){let e=d.headers.get("x-forwarded-for");return e?e.split(",")[0].trim():d.headers.get("x-real-ip")||"unknown"}function Fe(d,e,t,a,i){e?.apiKeyId&&d&&d.createAuditLog({action:"api_request",userId:e.userId||"",resource:"api_key",resourceId:e.apiKeyId,success:true,metadata:{endpoint:t,method:a,ip:Fr(i)}});}function ut(d){return d.baseUpdatedAt??d._baseUpdatedAt}function pt(d){let{baseUpdatedAt:e,_baseUpdatedAt:t,...a}=d;return a}function Yt(d,e){return {error:"Document has changed since you started editing",code:"REVISION_CONFLICT",conflict:{expectedUpdatedAt:d??null,actualUpdatedAt:e.updatedAt??null,current:e}}}async function _(d,e,t,a,i,c,l=true,u="none"){return await chunkISWMETHJ_cjs.a(d,e,{user:a,req:t,tenantID:i,apiKey:c},{enablePublicAccess:l,defaultAccess:u})}async function Y(d,e,t,a,i,c=true){return await chunkISWMETHJ_cjs.b(d,e,{user:a,req:t,tenantID:i},{enablePublicAccess:c})}async function P(d,e,t,a){if(t)return {user:t,tenantID:a,apiKeyContext:void 0,authType:"static"};if(e){let i=await e(d);if(i.status===200&&i.user)return {user:i.user,tenantID:i.tenantContext?.tenantId,apiKeyContext:i.apiKeyContext,authType:i.authType}}return {user:void 0,tenantID:void 0,apiKeyContext:void 0,authType:void 0}}function Or(d,e){if(d instanceof chunk6CLRVJPP_cjs.c&&d.dialect==="postgres")return new chunkGYQMNXXW_cjs.a({db:d.client});if(d instanceof chunkUDSJGML2_cjs.a)return new chunkATLSIYRH_cjs.a({db:d.db});let t=Ce.resolve(e,"data","kyro.db");return new chunkET6NN2V2_cjs.a({path:process.env.KYRO_AUTH_DB_PATH||t})}function Zt(d){let {registry:e,db:t,authSecret:a,authAdapter:i,checkSession:c,user:l,tenantID:u,cors:g,webhookService:f,settings:A}=d,w=new hono.Hono,U=A?.access?.apiAccess,T=A?.access?.enablePublicAccess??false,k=A?.access?.defaultCollectionAccess??"none";U?.requireAuth;let M=process.cwd(),ae=M.endsWith("admin")?Ce.resolve(M,".."):M,C=i||Or(t,ae),D=a?Et({db:t,userLookup:async r=>await C.findUserById(r)||null}):null,Z=U?.cors?.allowedOrigins,ne=g?.origins,we=Array.isArray(Z)?Z:typeof Z=="string"&&Z?Z.split(`
|
|
65
65
|
`).map(r=>r.trim()).filter(Boolean):[],be=we.length>0?we:ne||[];(be.length>0||g)&&w.use("*",async(r,n)=>{let m=r.req.header("Origin")||"*";if(be.length>0&&!be.includes(m))return r.json({error:"Origin not allowed"},403);let y=be.length>0?m:"*";if(r.header("Access-Control-Allow-Origin",y),r.header("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),r.header("Access-Control-Allow-Headers","Content-Type, Authorization, X-API-Key"),g?.credentials&&r.header("Access-Control-Allow-Credentials","true"),r.req.method==="OPTIONS")return r.text("");await n();});let Ie=A?.access?.rateLimiting,fe;if(Ie?.enabled){let r=Ie.maxRequests||100,n=Ie.windowMs||6e4;fe=new je({"api:general":{window:n,max:r}}),w.use("/api/*",async(m,y)=>{if(!fe)return y();let o=m.req.header("CF-Connecting-IP")||m.req.header("X-Forwarded-For")?.split(",")[0]?.trim()||m.req.header("X-Real-IP")||"unknown",s=await fe.check("api:general",o);if(m.header("X-RateLimit-Limit",String(r)),m.header("X-RateLimit-Remaining",String(s.remaining)),m.header("X-RateLimit-Reset",String(s.resetAt)),!s.allowed)return m.json({error:"Too many requests",retryAfter:s.retryAfter},429);await y();});}let K=new ke({redis:C,jwtSecret:a||"change-me",baseUrl:process.env.KYRO_BASE_URL||"http://localhost:4321",rateLimiter:fe});chunkAJAZ7D3W_cjs.b.fromConfig(t).then(r=>{r&&(K.email=r);}).catch(r=>{console.error("[Email] Failed to initialize transport from config:",r);}),w.post("/api/auth/login",async r=>K.login(r.req.raw)),w.post("/api/auth/register",async r=>K.register(r.req.raw)),w.post("/api/auth/logout",async r=>K.logout(r.req.raw)),w.post("/api/auth/refresh",async r=>K.refresh(r.req.raw)),w.get("/api/auth/me",async r=>K.me(r.req.raw)),w.get("/api/auth/sessions",async r=>K.listSessions(r.req.raw)),w.post("/api/auth/sessions/refresh",async r=>K.refreshSession(r.req.raw)),w.delete("/api/auth/sessions",async r=>K.revokeOtherSessions(r.req.raw)),w.delete("/api/auth/sessions/:id",async r=>K.revokeSession(r.req.raw,r.req.param("id"))),w.put("/api/auth/sessions/:id/name",async r=>K.renameSession(r.req.raw,r.req.param("id"))),w.get("/api/auth/access",async r=>{try{let{user:n,tenantID:m}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Not authenticated"},401);let y={},o={};for(let s of e.getCollections()){let p={read:(await _(s,"read",r.req.raw,n,m,void 0,T,k)).allowed,create:(await _(s,"create",r.req.raw,n,m,void 0,T,k)).allowed,update:(await _(s,"update",r.req.raw,n,m,void 0,T,k)).allowed,delete:(await _(s,"delete",r.req.raw,n,m,void 0,T,k)).allowed};y[s.slug]=p;}for(let s of e.getGlobals()){let p={read:(await Y(s,"read",r.req.raw,n,m,T)).allowed,update:(await Y(s,"update",r.req.raw,n,m,T)).allowed};o[s.slug]=p;}return r.json({collections:y,globals:o})}catch(n){return r.json({error:n.message},500)}});let ie=typeof e.hasCollection=="function"&&e.hasCollection("users")?e.getCollection("users"):(()=>{try{return e.getCollection("users")}catch{return chunkGFU7AOI3_cjs.a}})();w.get("/api/users",async r=>{try{let{user:n,tenantID:m}=await P(r.req.raw,D,l,u),y=await _(ie,"read",r.req.raw,n,m,void 0,T,k);if(!y.allowed)return r.json({error:y.error},y.status||403);let o=parseInt(r.req.query("page")||"1"),s=Math.min(parseInt(r.req.query("limit")||"10"),100),p=r.req.query("search")||void 0,b=await C.findUsers({page:o,limit:s,search:p});return r.json({docs:b.users,totalDocs:b.total,limit:s,totalPages:Math.ceil(b.total/s),page:o,pagingCounter:(o-1)*s+1,hasPrevPage:o>1,hasNextPage:o<Math.ceil(b.total/s),prevPage:o>1?o-1:null,nextPage:o<Math.ceil(b.total/s)?o+1:null})}catch(n){return console.error("[API] Error listing users:",n),r.json({error:n.message},500)}}),w.get("/api/users/:id",async r=>{try{let{user:n,tenantID:m}=await P(r.req.raw,D,l,u),y=r.req.param("id"),o=await C.findUserById(y);return o?r.json({data:o}):r.json({error:"User not found"},404)}catch(n){return r.json({error:n.message},500)}}),w.post("/api/users",async r=>{try{let{user:n,tenantID:m}=await P(r.req.raw,D,l,u),y=await _(ie,"create",r.req.raw,n,m,void 0,T,k);if(!y.allowed)return r.json({error:y.error},y.status||403);let o=await r.req.json();if(!o.email||!o.password)return r.json({error:"Email and password are required"},400);if(await C.findUserByEmail(o.email))return r.json({error:"Email already in use"},400);let p=await C.createUser({email:o.email,password:o.password,name:o.name,role:o.role||"customer",avatar:o.avatar,tenantId:o.tenantId});return n&&C?.createAuditLog({action:"user_create",userId:n.id,resource:"users",resourceId:p.id,success:!0}),r.json({data:p,message:"User created successfully"},201)}catch(n){return r.json({error:n.message},500)}}),w.patch("/api/users/:id",async r=>{try{let{user:n,tenantID:m}=await P(r.req.raw,D,l,u),y=await _(ie,"update",r.req.raw,n,m,void 0,T,k);if(!y.allowed)return r.json({error:y.error},y.status||403);let o=r.req.param("id"),s=await r.req.json(),p=await C.findUserById(o);if(!p)return r.json({error:"User not found"},404);let b={};s.name!==void 0&&(b.name=s.name),s.email!==void 0&&(b.email=s.email),s.role!==void 0&&(b.role=s.role),s.avatar!==void 0&&(b.avatar=typeof s.avatar=="object"&&s.avatar!==null?s.avatar.id||String(s.avatar):s.avatar),s.tenantId!==void 0&&(b.tenantId=s.tenantId),s.emailVerified!==void 0&&(b.emailVerified=s.emailVerified),s.locked!==void 0&&(b.locked=s.locked),s.failedLoginAttempts!==void 0&&(b.failedLoginAttempts=s.failedLoginAttempts),s.lastLogin!==void 0&&(b.lastLogin=s.lastLogin);let h=await C.updateUser(o,b);return h?(n&&(C?.createAuditLog({action:"user_update",userId:n.id,resource:"users",resourceId:o,success:!0}),s.role&&p.role!==s.role&&C?.createAuditLog({action:"role_change",userId:n.id,resource:"users",resourceId:o,success:!0,metadata:{oldRole:p.role,newRole:s.role}})),r.json({data:h,message:"User updated successfully"})):r.json({error:"User update failed"},500)}catch(n){return r.json({error:n.message},500)}}),w.delete("/api/users/:id",async r=>{try{let{user:n,tenantID:m}=await P(r.req.raw,D,l,u),y=await _(ie,"delete",r.req.raw,n,m,void 0,T,k);if(!y.allowed)return r.json({error:y.error},y.status||403);let o=r.req.param("id");if(n&&n.id===o)return r.json({error:"You cannot delete your own account"},403);let s=await C.findUserById(o);return s?await C.deleteUser(o)?(n&&C?.createAuditLog({action:"user_delete",userId:n.id,resource:"users",resourceId:o,success:!0}),r.json({data:s,message:"User deleted successfully"})):r.json({error:"User deletion failed"},500):r.json({error:"User not found"},404)}catch(n){return r.json({error:n.message},500)}}),w.get("/api/auth/audit-logs",async r=>{try{let{user:n,tenantID:m}=await P(r.req.raw,D,l,u),y=e.getCollection("audit_logs");if(y){let S=await _(y,"read",r.req.raw,n,m,void 0,T,k);if(!S.allowed)return r.json({error:S.error},S.status||403)}else if(!n)return r.json({error:"Authentication required"},401);let o=parseInt(r.req.query("page")||"1"),s=Math.min(parseInt(r.req.query("limit")||"50"),100),p=r.req.query("action")||void 0,b=r.req.query("userId")||void 0,h=r.req.query("resource")||void 0,I=await C.findAuditLogs({action:p,userId:b,resource:h,limit:s,offset:(o-1)*s});return r.json({docs:I.logs,totalDocs:I.total,limit:s,totalPages:Math.ceil(I.total/s),page:o,pagingCounter:(o-1)*s+1,hasPrevPage:o>1,hasNextPage:o<Math.ceil(I.total/s),prevPage:o>1?o-1:null,nextPage:o<Math.ceil(I.total/s)?o+1:null})}catch(n){return console.error("[API] Error listing audit logs:",n),r.json({error:n.message},500)}});let oe=null,le=null,W=async()=>{if(le)throw le;if(!oe)try{let r=t instanceof chunk6CLRVJPP_cjs.c?t.dialect:"sqlite",n=r==="postgres"&&t instanceof chunk6CLRVJPP_cjs.c?t.client:t;oe=await $e.init(n,{dialect:r});}catch(r){throw console.error("[getMedia] Init error:",r),le=r,r}return oe};w.get("/api/media",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=await W(),y=new URL(r.req.url).origin,o=parseInt(r.req.query("page")||"1"),s=parseInt(r.req.query("limit")||"30"),p=r.req.query("search")||"",b=r.req.query("type")||"",h=r.req.query("folder")||"",I=await m.find({page:o,limit:s,search:p,type:b,folder:h},y);return r.json(I)}catch(n){return console.error("[Media] find error:",n),r.json({error:n.message},500)}}),w.post("/api/media/upload",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=await W();if((r.req.header("content-type")||"").includes("multipart/form-data")){let p=await r.req.formData(),b=p.get("file"),h=p.get("folder")||"";if(!b)return r.json({error:"No file uploaded"},400);let I=await m.upload(b,h);return r.json(I)}let{url:o}=await r.req.json();if(!o)return r.json({error:"No URL provided"},400);let s=await m.uploadFromUrl(o);return r.json(s)}catch(n){return console.error("[Media] upload error:",n),r.json({error:n.message},500)}}),w.get("/api/media/folders",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let y=await(await W()).listFolders();return r.json(y)}catch(n){return console.error("[Media] folders error:",n),r.json({error:n.message},500)}}),w.post("/api/media/folders",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=await W(),y=await r.req.json(),{name:o,parentPath:s}=y;return o?(await m.createFolder(o,s||""),r.json({message:"Folder created",path:s?`${s}/${o}`:o})):r.json({error:"Folder name is required"},400)}catch(n){return console.error("[Media] create folder error:",n),r.json({error:n.message},500)}}),w.delete("/api/media/folders",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=await W(),y=r.req.query("path");return y?(await m.deleteFolder(y),r.json({message:"Folder deleted"})):r.json({error:"Path is required"},400)}catch(n){return console.error("[Media] delete folder error:",n),r.json({error:n.message},500)}}),w.delete("/api/media/:id",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=await W(),y=r.req.param("id"),o=new URL(r.req.url).origin;return await m.delete(y,o),r.json({success:!0})}catch(n){return console.error("[Media] delete error:",n),r.json({error:n.message},500)}}),w.get("/api/media/resize",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=r.req.query("url"),y=parseInt(r.req.query("w")||"0"),o=parseInt(r.req.query("h")||"0"),s=r.req.query("fit")||"cover";if(!m)return r.json({error:"URL is required"},400);let b=(await W()).storage;if(b.name!=="local")return r.redirect(m);let h=b.config?.uploadDir||Ce.join(process.cwd(),"public","uploads"),I=b.config?.baseUrl||"/uploads";if(!m.startsWith(I))return r.redirect(m);let S=m.replace(I,""),v=Ce.join(h,S);if(!fs.existsSync(v))return r.json({error:"File not found"},404);let x=fs.readFileSync(v),R=ct__default.default(x);(y>0||o>0)&&(R=R.resize({width:y>0?y:void 0,height:o>0?o:void 0,fit:s}));let q=await R.toBuffer(),j=await ct__default.default(x).metadata();return r.header("Content-Type",`image/${j.format||"webp"}`),r.header("Cache-Control","public, max-age=31536000, immutable"),r.body(q)}catch(n){return console.error("[Media] resize error:",n),r.json({error:n.message},500)}}),w.get("/api/media/:id",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=await W(),y=r.req.param("id"),o=new URL(r.req.url).origin,s=await m.findById(y,o);return s?r.json(s):r.json({error:"Media not found"},404)}catch(n){return console.error("[Media] get error:",n),r.json({error:n.message},500)}}),w.patch("/api/media/:id",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=await W(),y=r.req.param("id"),o=await r.req.json(),s=new URL(r.req.url).origin;if(o.folder!==void 0){let p=await m.update(y,{folder:o.folder},s);return r.json({doc:p})}return r.json({error:"No valid fields to update"},400)}catch(n){return console.error("[Media] update error:",n),r.json({error:n.message},500)}}),w.get("/api/media/test",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=await W();return r.json({status:m?"initialized":"failed",serviceType:m?.constructor?.name})}catch(n){return console.error("[test] Error:",n),r.json({error:n.message,type:n.constructor?.name,stack:n.stack},500)}}),w.get("/api/storage-status",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=!1,y="local";if(t)try{let o=t.prepare('SELECT provider FROM "_globals_storage-settings" LIMIT 1').get();o&&o.provider&&(m=!0,y=o.provider==="aws"?"s3":o.provider);}catch{try{let o=await t.findOne({collection:"_globals_storage-settings",where:{},draft:!0});o&&o.provider&&(m=!0,y=o.provider==="aws"?"s3":o.provider);}catch{}}return r.json({provider:y,configured:m,usage:0,limit:"unlimited"})}catch(n){return console.error("[Storage] status error:",n),r.json({error:n.message},500)}}),w.get("/api/plugins",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=e.getPlugins(),y=e.storageProviders,o=await Promise.all(m.map(async s=>{let p=!0,b=s.name,h={};try{let I=await t.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});I&&I.states&&(h=I.states);}catch{}return h[b]!==void 0&&(p=h[b]),y.setPluginEnabled(b,p),{id:b,name:b,version:s.version||"1.0.0",description:s.description||"",enabled:p,status:p?"active":"disabled"}}));return r.json(o)}catch(n){return console.error("[Plugins] list error:",n),r.json({error:n.message},500)}}),w.put("/api/plugins/:name/toggle",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=r.req.param("name"),y=e.storageProviders,s=!y.isPluginEnabled(m),p=[];if(!s)for(let h of y.getAll())h.pluginName===m&&p.push(h.type);if(!(r.req.query("force")==="1")&&!s&&p.length>0){let h="local";try{let I=t?.prepare?.('SELECT provider FROM "_globals_storage-settings" LIMIT 1')?.get();I?.provider&&(h=I.provider);}catch{try{let I=await t?.findOne?.({collection:"_globals_storage-settings",where:{},draft:!0});I?.provider&&(h=I.provider);}catch{}}if(p.includes(h))return r.json({error:`Cannot disable "${m}" \u2014 storage provider "${h}" is currently active. Switch to Local storage first.`,requiresAction:!0,activeProvider:h},409)}try{let h={},I="global",S=await t.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});S&&(h=S.states||{},I=S.id),h[m]=s,S?await t.update({collection:"_globals_plugin-settings",id:I,data:{states:h}}):await t.create({collection:"_globals_plugin-settings",data:{states:h,id:"global"}});}catch(h){console.warn(`[Plugins] Could not persist state for "${m}":`,h);}return y.setPluginEnabled(m,s),r.json({name:m,enabled:s})}catch(n){return console.error("[Plugins] toggle error:",n),r.json({error:n.message},500)}}),w.get("/api/health",r=>r.json({status:"ok",version:"0.1.0",collections:e.getCollectionSlugs(),timestamp:new Date().toISOString()})),w.get("/api/kyro/schema",async r=>{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=o=>o.map(s=>{let p={name:s.name,type:s.type,label:s.label,required:s.required??false,unique:s.unique??false,indexed:s.indexed??false,defaultValue:s.defaultValue,admin:s.admin?{...s.admin}:void 0};return s.minLength!==void 0&&(p.minLength=s.minLength),s.maxLength!==void 0&&(p.maxLength=s.maxLength),s.pattern!==void 0&&(p.pattern=s.pattern),s.variant!==void 0&&(p.variant=s.variant),s.hasMany!==void 0&&(p.hasMany=s.hasMany),s.min!==void 0&&(p.min=s.min),s.max!==void 0&&(p.max=s.max),s.step!==void 0&&(p.step=s.step),s.integer!==void 0&&(p.integer=s.integer),s.options&&(p.options=s.options),s.relationTo&&(p.relationTo=s.relationTo),s.maxDepth!==void 0&&(p.maxDepth=s.maxDepth),s.minRows!==void 0&&(p.minRows=s.minRows),s.maxRows!==void 0&&(p.maxRows=s.maxRows),s.localized!==void 0&&(p.localized=s.localized),s.language&&(p.language=s.language),s.format&&(p.format=s.format),s.allowedTypes&&(p.allowedTypes=s.allowedTypes),s.maxSize&&(p.maxSize=s.maxSize),(s.type==="group"||s.type==="row"||s.type==="collapsible"&&s.fields)&&(p.fields=m(s.fields)),s.type==="array"&&s.fields&&(p.fields=m(s.fields)),s.type==="blocks"&&s.blocks&&(p.blocks=s.blocks.map(b=>({slug:b.slug,label:b.label,fields:m(b.fields)}))),s.type==="tabs"&&s.tabs&&(p.tabs=s.tabs.map(b=>({label:b.label,name:b.name,fields:m(b.fields)}))),p}),y={collections:{},globals:{}};for(let o of e.getCollections()){let s=o.slug;try{y.collections[s]={slug:s,label:o.label||s,fields:m(o.fields),jsonSchema:zodToJsonSchema.zodToJsonSchema(e.getZodSchema(s),{target:"openApi3"}),createSchema:zodToJsonSchema.zodToJsonSchema(e.getCreateZodSchema(s),{target:"openApi3"}),updateSchema:zodToJsonSchema.zodToJsonSchema(e.getUpdateZodSchema(s),{target:"openApi3"}),procedures:{find:{collection:s,where:"Record<string,any>",sort:"string",limit:"number",page:"number",depth:"number",select:"string[]",draft:"boolean"},findByID:{collection:s,id:"string",depth:"number",select:"string[]",draft:"boolean"},create:{collection:s,data:"Record<string,any>",depth:"number",select:"string[]"},update:{collection:s,id:"string",data:"Record<string,any>",depth:"number",select:"string[]",baseUpdatedAt:"string"},delete:{collection:s,id:"string"},count:{collection:s,where:"Record<string,any>"}}};}catch{}}for(let o of e.getGlobals()){let s=o.slug,p=o.fields;if(s==="storage-settings"){let b=e.storageProviders,h=b.getAll(),I=new Set(b.getAllAvailable(v=>b.isPluginEnabled(v)).map(v=>v.type));I.add("local");let S=new Set(h.map(v=>v.type));p=p.filter(v=>v.type==="group"&&v.name&&S.has(v.name)?I.has(v.name):true).map(v=>v.name==="provider"&&v.type==="select"?{...v,options:v.options.filter(x=>I.has(x.value))}:v);}try{y.globals[s]={slug:s,label:o.label||s,fields:m(p),jsonSchema:zodToJsonSchema.zodToJsonSchema(e.getZodSchema(s),{target:"openApi3"}),procedures:{get:{},update:{data:"Record<string,any>"}}};}catch{}}return r.json(y)}),w.get("/api/collections",async r=>{let{user:n}=await P(r.req.raw,D,l,u);if(!n)return r.json({error:"Authentication required"},401);let m=e.getCollections().map(y=>({slug:y.slug,label:y.label||y.slug,fields:y.fields.filter(o=>o.name).map(o=>({name:o.name,type:o.type,required:o.required,label:o.label}))}));return r.json(m)});function de(r,n,m){if(m in n)return n[m];for(let y of r)if(y.name){if(y.type==="tabs"&&y.tabs){let o=n[y.name];if(o&&typeof o=="object"&&m in o)return o[m]}if((y.type==="group"||y.type==="collapsible")&&y.fields){let o=n[y.name];if(o&&typeof o=="object"){if(m in o)return o[m];let s=de(y.fields,o,m);if(s!==void 0)return s}}}}function Ne(r){let n=[];for(let m of r)if(m.type==="relationship")n.push(m);else if(m.type==="tabs"&&m.tabs)for(let y of m.tabs)n.push(...Ne(y.fields||[]));else (m.type==="group"||m.type==="collapsible")&&m.fields&&n.push(...Ne(m.fields||[]));return n}function Qt(r){if(!r)return [];if(typeof r=="string")return [r];if(Array.isArray(r))return r.map(n=>typeof n=="object"?n.value??n:n);if(typeof r=="object"){let n=r.value??r;return typeof n=="string"?[n]:Array.isArray(n)?n:[]}return []}async function Be(r,n,m,y){if(r.length===0)return;let o=Ne(n.fields);if(o.length!==0)for(let s of o){let p=Array.isArray(s.relationTo)?s.relationTo:[s.relationTo],b={};for(let h of p)b[h]=new Set;for(let h of r){let I=de(n.fields,h,s.name),S=Qt(I);for(let v of S)if(v)if(p.length===1)b[p[0]].add(v);else for(let x of p)b[x].add(v);}for(let[h,I]of Object.entries(b)){if(I.size===0)continue;let S=y.getCollection(h);if(!S)continue;let v=S.admin?.useAsTitle||"title",x=Array.from(I),R=[];for(let j of x)try{let E=await m.findByID({collection:h,id:j,draft:!0});if(E){let $=de(S.fields,E,v)??j;R.push({id:j,title:String($)});}}catch{R.push({id:j,title:j});}let q=new Map(R.map(j=>[j.id,j.title]));for(let j of r){let E=de(n.fields,j,s.name);if(!E)continue;let $=F=>{if(s.name in j)j[s.name]=F;else for(let L of n.fields)if(L.type==="tabs"&&L.tabs){for(let O of L.tabs)if(O.fields?.some(B=>B.name===s.name)){let B=j[L.name];B&&typeof B=="object"&&(B[s.name]=F);}}};if(typeof E=="string")$({id:E,title:q.get(E)||E});else if(Array.isArray(E))$(E.map(F=>{let L=typeof F=="object"?F.value??F.id:F;return {id:L,title:q.get(L)||L}}));else if(typeof E=="object"){let F=E.value??E.id;$({id:F,title:q.get(F)||F});}}}}}w.get("/api/search",async r=>{try{let n=r.req.query("q")||"",m=r.req.query("collections")||"",y=Math.min(parseInt(r.req.query("limit")||"10"),50);if(!n||n.length<2)return r.json({results:[],message:"Query too short"});let{user:o,tenantID:s}=await P(r.req.raw,D,l,u),p=m?m.split(",").filter(Boolean):e.getCollectionSlugs(),b=[],h=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i");for(let I of e.getCollections()){if(!p.includes(I.slug)||!(await _(I,"read",r.req.raw,o,s,void 0,T,k)).allowed)continue;let v=I.fields.filter(x=>x.name&&x.name!=="id"&&(x.type==="text"||x.type==="email"||x.type==="textarea"||x.type==="richtext"||x.indexed)&&!x.admin?.hidden).map(x=>x.name);if(v.length!==0)try{let x=v.map(q=>{let j={};return j[q]={like:`%${n}%`},j}),R=await t.find({collection:I.slug,where:{OR:x},limit:y,tenantID:s});await Be(R.docs,I,t,e);for(let q of R.docs){let j=I.admin?.useAsTitle||v.find($=>$==="title"||$==="name"||$==="heading"||$==="slug"),E=j?de(I.fields,q,j)??q.id:q.id;b.push({collection:I.slug,label:I.label||I.slug,id:q.id,title:String(E||"Untitled"),doc:q});}}catch(x){console.error(`Search error for ${I.slug}:`,x);}}return b.sort((I,S)=>I.label.localeCompare(S.label)),r.json({results:b})}catch(n){return r.json({error:n.message,results:[]},500)}}),w.get("/api/keys",async r=>{try{let{user:n,tenantID:m}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:read"))return r.json({error:"Forbidden"},403);let y=parseInt(r.req.query("page")||"1"),o=Math.min(parseInt(r.req.query("limit")||"50"),100),s=await t.find({collection:chunkNY47CFVP_cjs.d,where:{},page:y,limit:o,tenantID:m}),p=(s.docs||[]).map(b=>({id:b.id,name:b.name,keyPrefix:b.keyPrefix,permissions:b.permissions||[],lastUsed:b.lastUsedAt,createdAt:b.createdAt}));return r.json({docs:p,totalDocs:s.totalDocs||p.length,totalPages:s.totalPages||1})}catch(n){return console.error("[ApiKeys] GET error:",n),r.json({error:n.message},500)}}),w.post("/api/keys",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:admin"))return r.json({error:"Forbidden"},403);let m=await r.req.json();if(!m.name||typeof m.name!="string")return r.json({error:"name is required"},400);let y=chunkNY47CFVP_cjs.i(),o=await t.create({collection:chunkNY47CFVP_cjs.d,data:{userId:n.id,name:m.name,key:y,keyPrefix:chunkNY47CFVP_cjs.j(y),permissions:Array.isArray(m.permissions)?m.permissions:["*"],expiresAt:m.expiresAt||null,createdAt:new Date().toISOString()}});return await C?.createAuditLog({action:"api_key_create",userId:n.id,resource:"api_key",resourceId:o.id,success:!0,metadata:{keyName:m.name}}),r.json({...o,key:y,permissions:Array.isArray(m.permissions)?m.permissions:["*"]},201)}catch(n){return console.error("[ApiKeys] POST error:",n),r.json({error:n.message},500)}}),w.delete("/api/keys/:id",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:admin"))return r.json({error:"Forbidden"},403);let m=r.req.param("id"),y=await t.findByID({collection:chunkNY47CFVP_cjs.d,id:m});return y?(await t.delete({collection:chunkNY47CFVP_cjs.d,id:m}),await C?.createAuditLog({action:"api_key_delete",userId:n.id,resource:"api_key",resourceId:m,success:!0,metadata:{keyName:y.name}}),r.json({message:"API key deleted"})):r.json({error:"API key not found"},404)}catch(n){return console.error("[ApiKeys] DELETE error:",n),r.json({error:n.message},500)}}),w.patch("/api/keys/:id",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:admin"))return r.json({error:"Forbidden"},403);let m=r.req.param("id"),y=await r.req.json(),o=await t.findByID({collection:chunkNY47CFVP_cjs.d,id:m});if(!o)return r.json({error:"API key not found"},404);let s={};if(typeof y.name=="string"&&y.name.trim()&&(s.name=y.name.trim()),Array.isArray(y.permissions)&&(s.permissions=y.permissions),y.expiresAt!==void 0&&(s.expiresAt=y.expiresAt||null),Object.keys(s).length===0)return r.json({error:"Nothing to update"},400);let p=await t.update({collection:chunkNY47CFVP_cjs.d,id:m,data:s});return r.json({...p,keyPrefix:o.keyPrefix})}catch(n){return console.error("[ApiKeys] PATCH error:",n),r.json({error:n.message},500)}}),w.post("/api/keys/:id/rotate",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:admin"))return r.json({error:"Forbidden"},403);let m=r.req.param("id"),y=await t.findByID({collection:chunkNY47CFVP_cjs.d,id:m});if(!y)return r.json({error:"API key not found"},404);let o=chunkNY47CFVP_cjs.i(),s=await t.update({collection:chunkNY47CFVP_cjs.d,id:m,data:{key:o,keyPrefix:chunkNY47CFVP_cjs.j(o),lastUsedAt:null}});return await C?.createAuditLog({action:"api_key_rotate",userId:n.id,resource:"api_key",resourceId:m,success:!0,metadata:{keyName:y.name}}),r.json({...s,key:o,permissions:y.permissions,expiresAt:y.expiresAt})}catch(n){return console.error("[ApiKeys] rotate error:",n),r.json({error:n.message},500)}}),w.get("/api/webhooks",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:read"))return r.json({error:"Forbidden"},403);if(!f)return r.json({error:"Webhook service not available"},503);let m=await f.getWebhooks();return r.json({docs:m})}catch(n){return console.error("[Webhooks] GET error:",n),r.json({error:n.message},500)}}),w.post("/api/webhooks",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:admin"))return r.json({error:"Forbidden"},403);if(!f)return r.json({error:"Webhook service not available"},503);let m=await r.req.json(),y=await f.createWebhook(m);return await C?.createAuditLog({action:"webhook_create",userId:n.id,resource:"webhook",resourceId:y.id,success:!0,metadata:{name:y.name,url:y.url}}),r.json(y,201)}catch(n){return console.error("[Webhooks] POST error:",n),r.json({error:n.message},500)}}),w.get("/api/webhooks/:id",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:read"))return r.json({error:"Forbidden"},403);if(!f)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),y=await f.getWebhookById(m);return y?r.json(y):r.json({error:"Webhook not found"},404)}catch(n){return console.error("[Webhooks] GET :id error:",n),r.json({error:n.message},500)}}),w.patch("/api/webhooks/:id",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:admin"))return r.json({error:"Forbidden"},403);if(!f)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),y=await r.req.json(),o=await f.updateWebhook(m,y);return o?(await C?.createAuditLog({action:"webhook_update",userId:n.id,resource:"webhook",resourceId:m,success:!0,metadata:{name:o.name}}),r.json(o)):r.json({error:"Webhook not found"},404)}catch(n){return console.error("[Webhooks] PATCH error:",n),r.json({error:n.message},500)}}),w.delete("/api/webhooks/:id",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:admin"))return r.json({error:"Forbidden"},403);if(!f)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),y=await f.getWebhookById(m);return y?(await f.deleteWebhook(m),await C?.createAuditLog({action:"webhook_delete",userId:n.id,resource:"webhook",resourceId:m,success:!0,metadata:{name:y.name}}),r.json({message:"Webhook deleted"})):r.json({error:"Webhook not found"},404)}catch(n){return console.error("[Webhooks] DELETE error:",n),r.json({error:n.message},500)}}),w.post("/api/webhooks/:id/test",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:admin"))return r.json({error:"Forbidden"},403);if(!f)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),y=await f.testWebhook(m);return y?r.json(y):r.json({error:"Webhook not found"},404)}catch(n){return console.error("[Webhooks] test error:",n),r.json({error:n.message},500)}}),w.get("/api/webhooks/:id/history",async r=>{try{let{user:n}=await P(r.req.raw,D,l,u);if(!n||!chunkQ3Q7BJVQ_cjs.a(n,"users:read"))return r.json({error:"Forbidden"},403);if(!f)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),y=Math.min(parseInt(r.req.query("limit")||"50"),100),o=await f.getDeliveryHistory(m,y);return r.json({docs:o})}catch(n){return console.error("[Webhooks] history error:",n),r.json({error:n.message},500)}});function Me(r){let n={},m=["name","type","required","hasMany","relationTo","options","min","max","minLength","maxLength","defaultValue","label","localized","admin","unique","index","hidden","readOnly","deprecated"];for(let y of m)y in r&&(n[y]=r[y]);return r.fields&&(n.fields=r.fields.map(Me)),r.tabs&&(n.tabs=r.tabs.map(y=>({label:y.label,name:y.name,fields:y.fields.map(Me)}))),n}w.get("/api/__schema",async r=>{try{let{user:n,apiKeyContext:m}=await P(r.req.raw,D,l,u);if(!n&&!m)return r.json({error:"Unauthorized"},401);let o=e.getCollections().filter(s=>s.slug!=="users"&&s.slug!=="audit_logs").map(s=>({slug:s.slug,label:s.label,labelPlural:s.labelPlural,singularLabel:s.singularLabel,timestamps:s.timestamps,auth:!!s.auth,tenantScoped:!!s.tenantScoped,upload:s.upload?{staticDir:s.upload.staticDir,imageSizes:s.upload.imageSizes,mimeTypes:s.upload.mimeTypes}:void 0,fields:s.fields.map(Me)}));return r.json(o)}catch(n){return console.error("[Schema] error:",n),r.json({error:n.message},500)}});let er=e.getCollections();for(let r of er){let y=function(o,s){let p=[],b=new Set([...Object.keys(o),...Object.keys(s)]);for(let h of b)h==="id"||h==="createdAt"||h==="updatedAt"||JSON.stringify(o[h])!==JSON.stringify(s[h])&&p.push({field:h,oldValue:h in o?o[h]:void 0,newValue:h in s?s[h]:void 0});return p};let n=r.slug;if(n==="users"||n==="audit_logs")continue;let m=`/api/${n}`;w.get(m,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"read",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);p&&t.setTenantContext({tenantId:p,userId:s?.id??"",role:s?.role,isSuperAdmin:s?.role==="super_admin"});let I=new URL(o.req.url),S=parseInt(I.searchParams.get("page")||"1"),v=Math.min(parseInt(I.searchParams.get("limit")||"10"),100),x=I.searchParams.get("sort")||void 0,R=parseInt(I.searchParams.get("depth")||"0"),q=I.searchParams.get("select")?.split(",")||void 0,j=I.searchParams.get("draft"),E=j==="true"?!0:j==="false"?!1:!!s,$={},F=I.searchParams.get("where");if(F)try{$=JSON.parse(F);}catch{return o.json({error:"Invalid JSON in where parameter"},400)}let L=await t.find({collection:n,where:$,sort:x,limit:v,page:S,depth:R,tenantID:p,select:q,draft:E});return await Be(L.docs,r,t,e),o.json(L)}catch(s){return console.error("[API] list error:",s),o.json({error:s.message},500)}}),w.get(`${m}/:id/versions`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"read",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);let I=o.req.param("id");if(!I)return o.json({error:"Missing document ID"},400);let S=new URL(o.req.url),v=S.searchParams.get("compareA"),x=S.searchParams.get("compareB");if(Fe(C,b,`${m}/${I}/versions`,"GET",o.req.raw),v&&x){let[E,$]=await Promise.all([t.findVersionByID({collection:n,versionId:v,tenantID:p}),t.findVersionByID({collection:n,versionId:x,tenantID:p})]);if(!E||!$)return o.json({error:"Version not found"},404);let F=y(E.data,$.data);return o.json({diffs:F})}let R=parseInt(S.searchParams.get("page")||"1"),q=Math.min(parseInt(S.searchParams.get("limit")||"10"),100),j=await t.findVersions({collection:n,documentId:I,page:R,limit:q,tenantID:p});return o.json(j)}catch(s){return console.error("[API] versions error:",s),o.json({error:s.message},500)}}),w.put(`${m}/:id/draft`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"update",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);let I=o.req.param("id"),S=await o.req.json(),v=ut(S),x=await t.findByID({collection:n,id:I,tenantID:p,draft:!0});if(!x)return o.json({error:"Document not found"},404);let R;S.delta?R={...x,...S.delta}:R=S.data??pt(S);let q=await t.updateLatestVersion({collection:n,documentId:I,data:R,status:"draft",tenantID:p});return s&&C?.createAuditLog({action:"document_update",userId:s.id,resource:n,resourceId:I,success:!0,metadata:{type:"draft_save"}}),o.json({data:q,message:"Draft saved successfully"})}catch(s){return o.json({error:s.message},500)}}),w.delete(`${m}/:id/draft`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"update",o.req.raw,s,p,b,T,k);return h.allowed?(s&&C?.createAuditLog({action:"document_update",userId:s.id,resource:n,resourceId:o.req.param("id"),success:!0,metadata:{type:"draft_discard"}}),o.json({message:"Draft discarded successfully"})):o.json({error:h.error},h.status||403)}catch(s){return o.json({error:s.message},500)}}),w.get(`${m}/:id`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"read",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);let I=o.req.param("id"),S=new URL(o.req.url),v=parseInt(S.searchParams.get("depth")||"0"),x=S.searchParams.get("select")?.split(",")||void 0,R=S.searchParams.get("draft"),q=R==="true"?!0:R==="false"?!1:!!s,j=await t.findByID({collection:n,id:I,depth:v,tenantID:p,select:x,draft:q});return !j&&r.fields.some(E=>E.name==="slug")&&(j=await t.findOne({collection:n,where:{slug:I},tenantID:p,draft:q})),j?(await Be([j],r,t,e),o.json({data:j})):o.json({error:"Document not found"},404)}catch(s){return o.json({error:s.message},500)}}),w.post(m,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"create",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);p&&t.setTenantContext({tenantId:p,userId:s?.id??"",role:s?.role,isSuperAdmin:s?.role==="super_admin"}),Fe(C,b,m,"POST",o.req.raw);let S=await o.req.json();me(S,r.fields),ge(r.fields,S);let v=o.req.raw;if(r.hooks?.beforeValidate)for(let j of r.hooks.beforeValidate){let E=await j({collection:n,data:S,req:v,user:s,tenantID:p,operation:"create"});E&&Object.assign(S,E);}let x=e.getCreateZodSchema(n);try{S=x.parse(S);}catch(j){return o.json({error:`Validation failed: ${_e(j.errors)}`,details:j.errors},400)}r.tenantScoped&&p&&(S.tenantID=p);let R=r.versions?.drafts===!0;if(S.status=R?"draft":"published",r.hooks?.beforeChange)for(let j of r.hooks.beforeChange){let E=await j({collection:n,data:S,req:v,user:s,tenantID:p,operation:"create"});E&&Object.assign(S,E);}let q=await t.create({collection:n,data:S,tenantID:p});if(R&&await t.createVersion({collection:n,documentId:q.id,data:S,status:"draft",createdBy:s?.id,changeDescription:"Created",tenantID:p}),r.hooks?.afterChange)for(let j of r.hooks.afterChange)await j({collection:n,doc:q,data:S,req:v,user:s,tenantID:p,operation:"create"});return f&&f.trigger(Ae(n,"create"),{collection:n,operation:"create",data:q,user:s?{id:s.id,email:s.email,role:s.role}:void 0,tenantId:p}).catch(j=>console.error("[Webhook] Failed to trigger:",j)),s&&C?.createAuditLog({action:"document_create",userId:s.id,resource:n,resourceId:q.id,success:!0}),o.json({data:q,message:"Created successfully"},201)}catch(s){return s.name==="ZodError"?o.json({error:`Validation failed: ${_e(s.errors)}`,details:s.errors},400):o.json({error:s.message},500)}}),w.patch(`${m}/:id`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"update",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);let I=o.req.param("id"),S=await o.req.json(),v=ut(S),x=await t.findByID({collection:n,id:I,tenantID:p,draft:!0});if(!x)return o.json({error:"Document not found"},404);if(v&&x.updatedAt&&v!==x.updatedAt)return o.json(Yt(v,x),409);let R=Object.fromEntries(Object.entries(pt(S)).filter(([O,B])=>B!=="null"&&B!==void 0));me(R,r.fields),ge(r.fields,R);let q=o.req.raw;if(r.hooks?.beforeValidate)for(let O of r.hooks.beforeValidate){let B=await O({collection:n,data:R,originalDoc:x,req:q,user:s,tenantID:p,operation:"update"});B&&Object.assign(R,B);}if(R=e.getUpdateZodSchema(n).parse(R),r.hooks?.beforeChange)for(let O of r.hooks.beforeChange){let B=await O({collection:n,data:R,originalDoc:x,req:q,user:s,tenantID:p,operation:"update"});B&&Object.assign(R,B);}let E=o.req.header("X-Draft")==="true",$=r.versions?.drafts===!0,F=o.req.query("autosave")==="true",L;if($&&E?await t.createVersion({collection:n,documentId:I,data:R,status:"draft",autosave:F,createdBy:s?.id,changeDescription:F?"Autosave":"Draft saved",tenantID:p}):$?(await t.update({collection:n,id:I,data:{...R,status:"published"},tenantID:p}),await t.createVersion({collection:n,documentId:I,data:R,status:"published",createdBy:s?.id,changeDescription:"Published",tenantID:p})):await t.update({collection:n,id:I,data:R,tenantID:p}),L=await t.findByID({collection:n,id:I,tenantID:p,draft:!0}),r.hooks?.afterChange)for(let O of r.hooks.afterChange)await O({collection:n,doc:L,data:R,originalDoc:x,req:q,user:s,tenantID:p,operation:"update"});return f&&f.trigger(Ae(n,"update"),{collection:n,operation:"update",data:L,previousData:x,user:s?{id:s.id,email:s.email,role:s.role}:void 0,tenantId:p}).catch(O=>console.error("[Webhook] Failed to trigger:",O)),Fe(C,b,`${m}/${I}`,"PATCH",o.req.raw),s&&C?.createAuditLog({action:"document_update",userId:s.id,resource:n,resourceId:I,success:!0}),o.json({data:L,message:$?"Draft saved":"Updated successfully"})}catch(s){return s.name==="ZodError"?(console.error(`[PATCH ${m}/:id] Validation failed:`,s.errors),o.json({error:`Validation failed: ${_e(s.errors)}`,details:s.errors},400)):(console.error(`[PATCH ${m}/:id] ERROR:`,s.message,"CAUSE:",s.cause?.message||s.cause,"QUERY:",s.query),o.json({error:s.message},500))}}),w.delete(`${m}/:id`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"delete",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);p&&t.setTenantContext({tenantId:p,userId:s?.id??"",role:s?.role,isSuperAdmin:s?.role==="super_admin"});let I=o.req.param("id"),S=o.req.raw,v=await t.findByID({collection:n,id:I,tenantID:p,draft:!0});if(!v)return o.json({error:"Document not found"},404);if(r.hooks?.beforeDelete)for(let R of r.hooks.beforeDelete)await R({collection:n,doc:v,req:S,user:s,tenantID:p,operation:"delete"});let x=await t.delete({collection:n,id:I,tenantID:p});if(r.hooks?.afterDelete)for(let R of r.hooks.afterDelete)await R({collection:n,doc:x,originalDoc:v,req:S,user:s,tenantID:p,operation:"delete"});return f&&f.trigger(Ae(n,"delete"),{collection:n,operation:"delete",data:x,previousData:v,user:s?{id:s.id,email:s.email,role:s.role}:void 0,tenantId:p}).catch(R=>console.error("[Webhook] Failed to trigger:",R)),Fe(C,b,`${m}/${I}`,"DELETE",o.req.raw),s&&C?.createAuditLog({action:"document_delete",userId:s.id,resource:n,resourceId:I,success:!0}),o.json({data:x,message:"Deleted successfully"})}catch(s){return console.error(`[DELETE] Error deleting ${n}:`,s),o.json({error:s.message||String(s)},500)}}),w.post(`${m}/:id/duplicate`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"create",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);let I=o.req.param("id"),S=await t.findByID({collection:n,id:I,tenantID:p,draft:!0});if(!S)return o.json({error:"Document not found"},404);let{id:v,createdAt:x,updatedAt:R,...q}=S,j=Date.now().toString(36),E=`${S.slug||"document"}-copy-${j}`,$=await t.create({collection:n,data:{...q,slug:E,status:"draft"},tenantID:p});return o.json({data:$,message:"Document duplicated successfully"})}catch(s){return console.error("[Duplicate] Error:",s),o.json({error:s.message||String(s)},500)}}),w.post(`${m}/:id/versions/:versionId/restore`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"update",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);let I=o.req.param("id"),S=o.req.param("versionId"),v=await t.findVersionByID({collection:n,versionId:S,tenantID:p});if(!v)return o.json({error:"Version not found"},404);let x=await t.update({collection:n,id:I,data:{...v.data,status:"draft"},tenantID:p});return o.json({data:x,message:"Version restored successfully"})}catch(s){return o.json({error:s.message},500)}}),w.post(`${m}/:id/versions`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"update",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);let I=await o.req.json(),{versionId:S,action:v}=I;if(v==="restore"&&S){let x=await t.findVersionByID({collection:n,versionId:S,tenantID:p});if(!x)return o.json({error:"Version not found"},404);let R=await t.update({collection:n,id:o.req.param("id"),data:{...x.data,status:"draft"},tenantID:p});return o.json({data:R,message:"Version restored successfully"})}return o.json({error:"Invalid action"},400)}catch(s){return o.json({error:s.message},500)}}),w.post(`${m}/:id/publish`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"update",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);p&&t.setTenantContext({tenantId:p,userId:s?.id??"",role:s?.role,isSuperAdmin:s?.role==="super_admin"});let I=o.req.param("id"),S=await o.req.json().catch(()=>({})),v=ut(S),x=await t.findByID({collection:n,id:I,tenantID:p,draft:!0});if(!x)return o.json({error:"Document not found"},404);if(v&&x.updatedAt&&v!==x.updatedAt)return o.json(Yt(v,x),409);let R={status:"published"},q=x;if(r.versions?.drafts){let E=await t.findVersions({collection:n,documentId:I,limit:1,sort:"-createdAt",tenantID:p});if(E.docs.length>0){let $=E.docs[0];q={...x,...$.data},R={...$.data,...R};}}let j=await t.update({collection:n,id:I,data:R,tenantID:p});return r.versions?.drafts&&await t.createVersion({collection:n,documentId:I,data:{...q,status:"published"},status:"published",createdBy:s?.id,changeDescription:"Published",tenantID:p}),f&&f.trigger(Ae(n,"update"),{collection:n,operation:"update",data:j,user:s?{id:s.id,email:s.email,role:s.role}:void 0,tenantId:p}).catch(E=>console.error("[Webhook] Failed to trigger:",E)),o.json({data:j,message:"Published successfully"})}catch(s){return o.json({error:s.message},500)}}),w.post(`${m}/:id/unpublish`,async o=>{try{let{user:s,tenantID:p,apiKeyContext:b}=await P(o.req.raw,D,l,u),h=await _(r,"update",o.req.raw,s,p,b,T,k);if(!h.allowed)return o.json({error:h.error},h.status||403);let I=o.req.param("id");if(!await t.findByID({collection:n,id:I,tenantID:p,draft:!0}))return o.json({error:"Document not found"},404);let v=await t.update({collection:n,id:I,data:{status:"draft"},tenantID:p});return f&&f.trigger(Ae(n,"update"),{collection:n,operation:"update",data:v,user:s?{id:s.id,email:s.email,role:s.role}:void 0,tenantId:p}).catch(x=>console.error("[Webhook] Failed to trigger:",x)),o.json({data:v,message:"Unpublished successfully"})}catch(s){return o.json({error:s.message},500)}});}for(let r of e.getGlobals()){let n=r.slug,m=`/api/globals/${n}`;w.get(m,async o=>{try{let{user:s,tenantID:p}=await P(o.req.raw,D,l,u),b=await Y(r,"read",o.req.raw,s,p,T);if(!b.allowed)return o.json({error:b.error},b.status||403);let h=!!s,I=await t.findOne({collection:`_globals_${n}`,where:{},tenantID:p,draft:h});if(n==="system"){let S=sr__default.default.randomBytes(32).toString("hex");I?I.appSecret||(await t.update({collection:`_globals_${n}`,id:n,data:{appSecret:S},tenantID:p}),I.appSecret=S):I=await t.create({collection:`_globals_${n}`,data:{id:n,appSecret:S},tenantID:p});}return o.json({data:I||{}})}catch(s){return o.json({error:s.message},500)}});let y=async o=>{try{let{user:s,tenantID:p}=await P(o.req.raw,D,l,u),b=await Y(r,"update",o.req.raw,s,p,T);if(!b.allowed)return o.json({error:b.error},b.status||403);let h=pt(await o.req.json()),I=Object.fromEntries(Object.entries(h).filter(([O,B])=>B!==null&&B!=="null"&&B!==void 0));me(I,r.fields),ge(r.fields,I);let S=e.getUpdateZodSchema(n),v;try{v=S.parse(I);}catch(O){return o.json({error:`Validation failed: ${_e(O.errors)}`,details:O.errors},400)}let x=new Set(["id","createdAt","updatedAt","status","baseUpdatedAt","_baseUpdatedAt"]),R=Object.fromEntries(Object.entries(v).filter(([O])=>!x.has(O))),q=`_globals_${n}`,j=await t.findOne({collection:q,where:{},tenantID:p,draft:!0}),E=o.req.header("X-Draft")==="true",$=r.versions?.drafts===!0,F=o.req.query("autosave")==="true",L;if($&&E)await t.createVersion({collection:q,documentId:n,data:R,status:"draft",autosave:F,createdBy:s?.id,changeDescription:F?"Autosave":"Manual save",tenantID:p}),j?L=j:L=await t.create({collection:q,data:{...R,id:n,status:"draft"},tenantID:p});else if($&&!E){let O="published";j?L=await t.update({collection:q,id:n,data:{...R,status:O},tenantID:p}):L=await t.create({collection:q,data:{...R,id:n,status:O},tenantID:p}),await t.createVersion({collection:q,documentId:n,data:R,status:O,autosave:!1,createdBy:s?.id,changeDescription:"Published",tenantID:p});}else j?L=await t.update({collection:q,id:n,data:R,tenantID:p}):L=await t.create({collection:q,data:{...R,id:n},tenantID:p});if(n==="storage-settings"&&(oe=null,le=null),n==="email-settings"){let O=await chunkAJAZ7D3W_cjs.b.fromConfig(t);K.email=O||void 0;}return n==="system"&&await Tt(),s&&C?.createAuditLog({action:"settings_change",userId:s.id,resource:`global:${n}`,resourceId:n,success:!0}),o.json({data:L,message:"Updated successfully"})}catch(s){return console.error(`[API] Save global "${n}" failed:`,s),o.json({error:s.message||"Save failed",stack:process.env.NODE_ENV==="development"?s.stack:void 0},500)}};w.post(m,y),w.patch(m,y),w.post(`${m}/publish`,async o=>{try{let{user:s,tenantID:p}=await P(o.req.raw,D,l,u),b=await Y(r,"update",o.req.raw,s,p,T);if(!b.allowed)return o.json({error:b.error},403);let h=`_globals_${n}`,I=await t.findOne({collection:h,where:{},tenantID:p,draft:!0});if(!I)return o.json({error:"Global not found"},404);let S={status:"published"},v=I;if(r.versions?.drafts){let R=await t.findVersions({collection:h,documentId:n,limit:1,sort:"-createdAt",tenantID:p});R.docs.length>0&&(v={...I,...R.docs[0].data},S={...R.docs[0].data,...S});}let x=await t.update({collection:h,id:n,data:S,tenantID:p});return r.versions?.drafts&&await t.createVersion({collection:h,documentId:n,data:{...v,status:"published"},status:"published",createdBy:s?.id,changeDescription:"Published",tenantID:p}),o.json({data:x,message:"Published successfully"})}catch(s){return o.json({error:s.message},500)}}),w.post(`${m}/unpublish`,async o=>{try{let{user:s,tenantID:p}=await P(o.req.raw,D,l,u),b=await Y(r,"update",o.req.raw,s,p,T);if(!b.allowed)return o.json({error:b.error},403);let h=await t.update({collection:`_globals_${n}`,id:n,data:{status:"draft"},tenantID:p});return o.json({data:h,message:"Unpublished successfully"})}catch(s){return o.json({error:s.message},500)}}),w.get(`${m}/versions`,async o=>{try{let{user:s,tenantID:p}=await P(o.req.raw,D,l,u),b=await Y(r,"read",o.req.raw,s,p,T);if(!b.allowed)return o.json({error:b.error},403);let h=parseInt(o.req.query("limit")||"10"),I=parseInt(o.req.query("page")||"1"),S=await t.findVersions({collection:`_globals_${n}`,documentId:n,limit:h,page:I,tenantID:p});return o.json(S)}catch(s){return o.json({error:s.message},500)}}),w.get(`${m}/versions/:versionId`,async o=>{try{let s=o.req.param("versionId"),{user:p,tenantID:b}=await P(o.req.raw,D,l,u),h=await Y(r,"read",o.req.raw,p,b,T);if(!h.allowed)return o.json({error:h.error},403);let I=await t.findVersionByID({collection:`_globals_${n}`,versionId:s,tenantID:b});return I?o.json({data:I}):o.json({error:"Version not found"},404)}catch(s){return o.json({error:s.message},500)}}),w.post(`${m}/versions/:versionId/restore`,async o=>{try{let s=o.req.param("versionId"),{user:p,tenantID:b}=await P(o.req.raw,D,l,u),h=await Y(r,"update",o.req.raw,p,b,T);if(!h.allowed)return o.json({error:h.error},403);let I=`_globals_${n}`,S=await t.findVersionByID({collection:I,versionId:s,tenantID:b});if(!S)return o.json({error:"Version not found"},404);let v=await t.update({collection:I,id:n,data:{...S.data,status:"draft"},tenantID:b});return o.json({data:v,message:"Version restored successfully"})}catch(s){return o.json({error:s.message},500)}}),n==="email-settings"&&w.post(`${m}/test`,async o=>{try{let{user:s,tenantID:p}=await P(o.req.raw,D,l,u),b=await Y(r,"update",o.req.raw,s,p,T);if(!b.allowed)return o.json({error:b.error},b.status||403);let h=await o.req.json(),I={provider:h.provider,from:h.fromEmail||h.from,fromName:h.fromName,replyTo:h.replyTo,smtp:h.smtp?{host:h.smtp.host,port:h.smtp.port,secure:h.smtp.secure,auth:{user:h.smtp.username||h.smtp.user,pass:h.smtp.password||h.smtp.pass}}:void 0,resend:h.resend,sendgrid:h.sendgrid,mailgun:h.mailgun,ses:h.ses},S=new chunkAJAZ7D3W_cjs.b(I),v=h.testEmail||h.testEmailSection&&h.testEmailSection.testEmail;return v?(await S.send({to:v,subject:"Kyro CMS - Test Email",html:`
|
|
66
66
|
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;">
|
|
67
67
|
<h1 style="color: #0b1222; margin-bottom: 16px;">Success! \u{1F680}</h1>
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
'use strict';var chunk65G73T7Z_cjs=require('./chunk-65G73T7Z.cjs'),chunkCVVW4LXZ_cjs=require('./chunk-CVVW4LXZ.cjs'),chunkCIE3XMLH_cjs=require('./chunk-CIE3XMLH.cjs'),
|
|
1
|
+
'use strict';var chunk65G73T7Z_cjs=require('./chunk-65G73T7Z.cjs'),chunkCVVW4LXZ_cjs=require('./chunk-CVVW4LXZ.cjs'),chunkCIE3XMLH_cjs=require('./chunk-CIE3XMLH.cjs'),chunk3HVN4CBK_cjs=require('./chunk-3HVN4CBK.cjs'),chunkISWMETHJ_cjs=require('./chunk-ISWMETHJ.cjs'),chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkF7SR5IDT_cjs=require('./chunk-F7SR5IDT.cjs'),chunk6CLRVJPP_cjs=require('./chunk-6CLRVJPP.cjs'),chunkMIOMMB23_cjs=require('./chunk-MIOMMB23.cjs'),chunkDV4LFLPL_cjs=require('./chunk-DV4LFLPL.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga'),module$1=require('module'),crypto=require('crypto');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function O(n,e){for(let t of n){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let s of t.tabs)if(O(s.fields,e))return true}if("fields"in t&&t.fields&&O(t.fields,e))return true}return false}var K=class extends Error{errors;constructor(e){super(`Configuration validation failed:
|
|
2
2
|
${e.join(`
|
|
3
|
-
`)}`),this.name="ConfigValidationError",this.errors=e;}};function V(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Collection slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Collection "${n.slug}" has no fields defined`);else {let t=x(n.fields,n.slug);e.push(...t);}if(n.access)for(let[t,s]of Object.entries(n.access))typeof s!="boolean"&&typeof s!="function"&&e.push(`Collection "${n.slug}" has invalid access.${t} (must be boolean or function)`);if(n.admin?.useAsTitle&&(O(n.fields,n.admin.useAsTitle)||e.push(`Collection "${n.slug}" admin.useAsTitle references unknown field "${n.admin.useAsTitle}"`)),n.admin?.defaultColumns)for(let t of n.admin.defaultColumns)O(n.fields,t)||e.push(`Collection "${n.slug}" admin.defaultColumns references unknown field "${t}"`);if(n.upload&&n.upload.fileSize&&n.upload.fileSize<=0&&e.push(`Collection "${n.slug}" upload.fileSize must be positive`),n.versions&&n.versions.maxPerDoc&&n.versions.maxPerDoc<=0&&e.push(`Collection "${n.slug}" versions.maxPerDoc must be positive`),n.auth){let t=n.fields.some(a=>a.name==="email"),s=n.fields.some(a=>a.name==="password");t||e.push(`Collection "${n.slug}" with auth enabled requires an "email" field`),s||e.push(`Collection "${n.slug}" with auth enabled requires a "password" field`);}return e}function B(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Global slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Global "${n.slug}" has no fields defined`);else {let t=x(n.fields,`global:${n.slug}`);e.push(...t);}return e}function x(n,e){let t=[],s=new Set;for(let a=0;a<n.length;a++){let o=n[a];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let r=x(o.fields,e);t.push(...r);}else if("tabs"in o)for(let r of o.tabs){let c=x(r.fields,e);t.push(...c);}continue}let i=o.name;if(!i){t.push(`${e}: Field at index ${a} is missing a "name" property`);continue}if(s.has(i)&&t.push(`${e}: Duplicate field name "${i}"`),s.add(i),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(i)||t.push(`${e}: Field name "${i}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${i}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${i}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${i}" has no fields defined`);else {let r=x(o.fields,`${e}.${i}`);t.push(...r);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${i}" has no fields defined`);else {let r=x(o.fields,`${e}.${i}`);t.push(...r);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${i}" has no blocks defined`);else {let r=ve(o.blocks,`${e}.${i}`);t.push(...r);}break;case "select":case "radio":if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${i}" has no options defined`);else if(o.options){let r=o.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${o.type} field "${i}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${i}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${i}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${i}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${i}" has minRows greater than maxRows`);}return t}function ve(n,e){let t=[],s=new Set;for(let a of n){if(!a.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(s.has(a.slug)&&t.push(`${e}: Duplicate block slug "${a.slug}"`),s.add(a.slug),a.label||t.push(`${e}: Block "${a.slug}" is missing a "label" property`),!a.fields||a.fields.length===0)t.push(`${e}: Block "${a.slug}" has no fields defined`);else {let o=x(a.fields,`${e}.${a.slug}`);t.push(...o);}}return t}function pe(n,e=[]){let t=[],s=new Set;for(let a of n)s.has(a.slug)&&t.push(`Duplicate collection slug "${a.slug}"`),s.add(a.slug);for(let a of e)s.has(a.slug)&&t.push(`Duplicate global slug "${a.slug}"`),s.add(a.slug);for(let a of n){let o=V(a);t.push(...o);}for(let a of e){let o=B(a);t.push(...o);}for(let a of n){let o=$(a.fields,n);t.push(...o);}if(t.length>0)throw new K(t)}function $(n,e){let t=[],s=new Set(e.map(a=>a.slug));for(let a of n){if(a.type==="relationship"){let o=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let i of o)s.has(i)||console.warn(`[Kyro Config Warning]: Relationship field "${a.name}" references unknown collection "${i}". Select options will not be available until this collection is registered.`);}if(a.type==="upload"){let o=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let i of o)s.has(i)||t.push(`Upload field "${a.name}" references unknown collection "${i}"`);}if("fields"in a&&a.fields){let o=$(a.fields,e);t.push(...o);}if("tabs"in a)for(let o of a.tabs){let i=$(o.fields,e);t.push(...i);}if("blocks"in a)for(let o of a.blocks){let i=$(o.fields,e);t.push(...i);}}return t}function C(n){switch(n.type){case "text":return De(n);case "number":return we(n);case "checkbox":return Fe(n);case "date":return Ie(n);case "email":return $e(n);case "password":return Oe(n);case "textarea":return Pe(n);case "select":return Le(n);case "radio":return ke(n);case "color":return _e(n);case "richtext":return je(n);case "json":return Ze(n);case "code":return qe(n);case "upload":return fe(n);case "image":return fe(n);case "markdown":return Ue(n);case "relationship":return ye(n);case "relationship-block":return ye(n);case "array":return Ge(n);case "list":return Ke(n);case "group":return Ve(n);case "blocks":return Be(n);case "row":return Me(n);case "collapsible":return ze(n);case "tabs":return We(n);default:return zod.z.any()}}function De(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.pattern&&(e=e.regex(new RegExp(n.pattern))),n.variant==="email"&&(e=e.email()),n.variant==="url"&&(e=e.url()),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function we(n){let e=n.integer?zod.z.coerce.number().int():zod.z.coerce.number();return n.min!==void 0&&(e=e.min(n.min)),n.max!==void 0&&(e=e.max(n.max)),n.step&&(e=e.refine(t=>Number.isInteger(t/n.step),`Value must be divisible by ${n.step}`)),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Fe(n){let e=zod.z.boolean();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ie(n){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return n.minDate&&(e=e.refine(t=>new Date(t)>=new Date(n.minDate),`Date must be after ${n.minDate}`)),n.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(n.maxDate),`Date must be before ${n.maxDate}`)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function $e(n){let e=zod.z.string().email("Invalid email");return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Oe(n){let e=zod.z.string().min(6,"Password must be at least 6 characters");return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Pe(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Le(n){let e;if(n.options&&n.options.length>0){let t=n.options.map(s=>s.value);n.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=n.hasMany?zod.z.array(zod.z.string()):zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function ke(n){let e=n.options.map(s=>s.value),t=zod.z.enum(e);return n.required||(t=t.optional().nullable()),n.validate&&(t=b(t,n.validate)),t}function _e(n){let e=zod.z.string();return n.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),n.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),n.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function je(n){let e=zod.z.array(zod.z.record(zod.z.any()));return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ze(n){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function qe(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function fe(n){let e;if(n.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 n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ue(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function ye(n){let e;return Array.isArray(n.relationTo)?e=zod.z.object({relationTo:zod.z.enum(n.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ge(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(s=>s.name).map(s=>[s.name,C(s)]))),t=zod.z.array(e);return n.minRows&&(t=t.min(n.minRows)),n.maxRows&&(t=t.max(n.maxRows)),n.required||(t=t.optional().nullable()),n.validate&&(t=b(t,n.validate)),t}function Ke(n){let e=zod.z.array(zod.z.string());return n.required||(e=e.optional().nullable()),e}function Ve(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])));return n.required?e:e.optional().nullable()}function Be(n){let e=n.blocks||[];e.map(o=>zod.z.object({blockType:zod.z.literal(o.slug),...Object.fromEntries(o.fields.filter(i=>i.name).map(i=>[i.name,C(i)]))}));let s=e.map(o=>o.slug),a;if(s.length>0){let o=zod.z.object({blockType:zod.z.enum(s)}).catchall(zod.z.any()),i=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());a=zod.z.array(zod.z.union([o,i,zod.z.record(zod.z.any())]));}else a=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return n.minRows&&(a=a.min(n.minRows)),n.maxRows&&(a=a.max(n.maxRows)),n.required||(a=a.optional().nullable()),n.validate&&(a=b(a,n.validate)),a}function Me(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function ze(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function We(n){let e={};for(let t of n.tabs)for(let s of t.fields)s.name&&(e[s.name]=C(s));return zod.z.object(e).passthrough().optional()}function b(n,e){return n.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function R(n){let e={};for(let t of n)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs){let o=R(a.fields);Object.assign(s,o);}e[t.name]=zod.z.object(s).passthrough().optional();}else if(t.type==="row"&&"fields"in t){let s=R(t.fields);Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(R(t.fields)).passthrough().optional():e[t.name]=C(t);return e}function E(n){let e={};for(let t of n)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs){let o=E(a.fields);Object.assign(s,o);}e[t.name]=zod.z.object(s).passthrough().optional().nullable();}else if(t.type==="row"&&"fields"in t){let s=E(t.fields);Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).passthrough().optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).passthrough().optional().nullable():e[t.name]=C(t).optional().nullable();return e}function he(n){let e=R(n.fields);return n.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),n.tenantScoped&&(e.tenantID=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function ge(n){let e=R(n.fields);return zod.z.object(e).passthrough()}function me(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs)for(let o of a.fields)o.name&&(s[o.name]=C(o).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else if(t.type==="row"&&"fields"in t){let s={};for(let a of t.fields)a.name&&(s[a.name]=C(a).optional().nullable());Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return zod.z.object(e).passthrough()}function be(n){let e={};for(let t of n.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 Te(n){let e=R(n.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ce(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs)for(let o of a.fields)o.name&&(s[o.name]=C(o).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return zod.z.object(e).passthrough()}var w=class{storageProviders=chunkF3Z67QWS_cjs.f();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};for(let a of this.plugins)a.extendCollection&&(t=a.extendCollection(t.slug,t));t.fields=this.applyFieldDefaults(t);let s=V(t);if(s.length>0)throw new Error(`Invalid collection config: ${s.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=B(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let s={...e};for(let a of this.plugins)a.extendGlobal&&(s=a.extendGlobal(s.slug,s));this.globals.set(s.slug,s),this.clearSchemaCache(`global:${s.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 s=this.collections.get(e);if(s){let o=he(s);return this.schemaCache.set(e,o),o}let a=this.globals.get(e);if(a){let o=Te(a);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`,s=this.schemaCache.get(t);if(s)return s;let a=this.collections.get(e);if(a){let o=ge(a);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,s=this.schemaCache.get(t);if(s)return s;let a=this.collections.get(e);if(a){let i=me(a);return this.schemaCache.set(t,i),i}let o=this.globals.get(e);if(o){let i=Ce(o);return this.schemaCache.set(`global:${e}:update`,i),i}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,s=this.schemaCache.get(t);if(s)return s;let a=this.collections.get(e);if(a){let o=be(a);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return C(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(s=>s.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(s=>s.name==="tenantID")&&t.push({name:"tenantID",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(s=>s.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(s=>s.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(s=>s.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 s=this.globals.get(e);if(s)return s.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),s=new Map,a=o=>{for(let i of o){if(i.name&&s.set(i.name,i),"fields"in i&&i.fields&&a(i.fields),"tabs"in i)for(let r of i.tabs)a(r.fields);if("blocks"in i)for(let r of i.blocks)a(r.fields);}};return a(t),s}getVisibleFields(e){return this.getFields(e).filter(s=>!s.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();pe(e,t);}async init(e){this.validate();for(let t of this.plugins)t.init&&await t.init(e||this);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 s=this.collections.get(e)?.admin?.useAsTitle;return s||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(a=>a.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()}}},v=null;function Xe(){return v||(v=new w),v}function Je(){v=null;}function M(){return v=new w,v}var He={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 Ye(n,e){switch(n){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 Ae(n,e){return {provider:n,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:Ye(n,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function Qe(n,e,t){let s=t[e.configKey]||{};return Ae(n,s)}function et(n,e,t){let s=t?.[e.configKey]||t;return Ae(n,s)}var Se={name:"@kyro-cms/storage-s3",version:"1.0.0",description:"S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)",init:n=>{let e=n.registry?.storageProviders;if(!e)return;let t="@kyro-cms/storage-s3";for(let s of Object.values(He))e.register({type:s.type,displayName:s.displayName,pluginName:t,configKey:s.configKey,configFields:s.configFields,extractConfig:a=>Qe(s.type,s,a),extractRawConfig:a=>et(s.type,s,a),factory:a=>chunkF3Z67QWS_cjs.a(a)});}};var Ee={name:"@kyro-cms/storage-cloudinary",version:"1.0.0",description:"Cloudinary image and video storage",init:n=>{let e=n.registry?.storageProviders;e&&e.register({type:"cloudinary",displayName:"Cloudinary",pluginName:"@kyro-cms/storage-cloudinary",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:t=>({cloudName:t.cloudinary?.cloudName||"",apiKey:t.cloudinary?.apiKey||"",apiSecret:t.cloudinary?.apiSecret||"",folder:t.cloudinary?.folder,uploadPreset:t.cloudinary?.uploadPreset}),extractRawConfig:t=>{let s=t?.cloudinary||t;return {cloudName:s?.cloudName||"",apiKey:s?.apiKey||"",apiSecret:s?.apiSecret||"",folder:s?.folder,uploadPreset:s?.uploadPreset}},factory:t=>chunkF3Z67QWS_cjs.b(t)});}};var xe={name:"@kyro-cms/storage-ftp",version:"1.0.0",description:"FTP/SFTP storage provider",init:n=>{let e=n.registry?.storageProviders;e&&e.register({type:"ftp",displayName:"FTP",pluginName:"@kyro-cms/storage-ftp",configKey:"ftp",configFields:[{name:"host",type:"text",label:"Host",required:true,admin:{placeholder:"ftp.example.com"}},{name:"port",type:"number",label:"Port",defaultValue:21,admin:{placeholder:"21 for FTP"}},{name:"user",type:"text",label:"Username",required:true},{name:"password",type:"password",label:"Password",required:true},{name:"secure",type:"checkbox",label:"Use TLS/SSL",defaultValue:false,admin:{description:"Enable TLS/SSL for secure connections (FTP only)"}},{name:"baseUrl",type:"text",label:"Base URL",required:true,admin:{placeholder:"https://files.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}],extractConfig:t=>({host:t.ftp?.host||"",port:t.ftp?.port||21,user:t.ftp?.user||"",password:t.ftp?.password||"",secure:t.ftp?.secure||false,baseUrl:t.ftp?.baseUrl||"",prefix:t.ftp?.prefix,type:"ftp"}),extractRawConfig:t=>{let s=t?.ftp||t;return {host:s?.host||"",port:s?.port||21,user:s?.user||"",password:s?.password||"",secure:s?.secure||false,baseUrl:s?.baseUrl||"",prefix:s?.prefix,type:"ftp"}},factory:t=>chunkF3Z67QWS_cjs.c(t)});}};var nt=[Se,Ee,xe];function z(n,e,t){let s=e.split(".");if(s.length===0)return false;let a=s[0],o=s.slice(1).join(".");for(let i of n)if(i.name===a)return o?i.fields&&Array.isArray(i.fields)||i.type==="array"&&i.fields&&Array.isArray(i.fields)?z(i.fields,o,t):false:(Object.assign(i,t),true);return false}function st(n,e){if(e)for(let t of n){let s=e[t.slug];if(s){let{fields:a,...o}=s;if(t.admin={...t.admin,...o},a&&t.fields&&Array.isArray(t.fields))for(let[i,r]of Object.entries(a))z(t.fields,i,r);}}}var W=class{registry;db;pubsub;webhookService;settings;wsServer;config;constructor(e){this.config=e,this.registry=M(),this.db=e.adapter,this.pubsub=new chunkF7SR5IDT_cjs.b(this.registry),this.webhookService=chunkISWMETHJ_cjs.n(this.db);for(let t of nt)this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&st(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.registry.init(this),this.registry.addGlobalPostInit(chunk65G73T7Z_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:chunkNY47CFVP_cjs.d,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"}]},s={slug:chunkISWMETHJ_cjs.e,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},a={slug:chunkISWMETHJ_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 chunk6CLRVJPP_cjs.c&&this.db.dialect==="postgres"){let i=this.db,r=chunkNY47CFVP_cjs.d.replace(/-/g,"_");i.schema[r]||(i.schema[r]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,s,a],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(),s={};try{let a=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});a&&a.states&&(s=a.states);}catch{}for(let a of t)s[a]!==void 0&&e.setPluginEnabled(a,s[a]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,s=t?.secret,a=t?.checkSession!==false;return chunkF3Z67QWS_cjs.s({registry:this.registry,db:this.db,authSecret:s,authAdapter:this.config.authAdapter,checkSession:a,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkCIE3XMLH_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:a})=>{let o=chunkNY47CFVP_cjs.f(a),i,r;if(o&&this.db){let d=await chunkNY47CFVP_cjs.e(o,this.db);d.user&&(i=d.user,r=chunkNY47CFVP_cjs.g(d));}let c=e?.tenantID;return {db:this.db,registry:this.registry,user:i,req:a,tenantID:c,apiKey:r,relationLoader:new chunkCIE3XMLH_cjs.a({db:this.db,tenantID:c,user:i})}},graphiql:false,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,s)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[i,...r]=o.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!i||!c)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 d=await chunkCVVW4LXZ_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantID:e?.tenantID,settings:this.settings}),h=chunkCVVW4LXZ_cjs.i(d)[i];if(!h)return new Response(JSON.stringify({error:{message:`Collection '${i}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let g=h[c];if(typeof g!="function")return new Response(JSON.stringify({error:{message:`Procedure '${c}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let p={};if(t.method==="POST"||t.method==="PATCH")p=await t.json().catch(()=>({}));else {let S=new URL(t.url).searchParams.get("input");if(S)try{p=JSON.parse(decodeURIComponent(S));}catch{}}let f=p?.["0"]??p,m=await g({...f,collection:i});return new Response(JSON.stringify({result:{data:m}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(p){let f=p.message||"Internal error",m=f.includes("not found")?404:f.includes("denied")||f.includes("authentication required")?403:f.includes("conflict")?409:500,S=m===404?-32601:m===403?-32001:m===409?-32002:-32603;return new Response(JSON.stringify({error:{message:f,code:S,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:m}}}),{status:m,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 s=async a=>{let o=await chunkNY47CFVP_cjs.e(a,this.db);if(!o.valid)throw new Error(o.error||"Invalid API key");if(!o.user)throw new Error("API key has no associated user");return o.user};return this.wsServer=chunkF7SR5IDT_cjs.d({pubsub:this.pubsub,port:e?.port||8080,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||s}),this.wsServer}async shutdown(){this.wsServer&&await this.wsServer.close(),await this.db.disconnect();}};function Mt(n){return new W(n)}var it=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-TD6RULJU.cjs', document.baseURI).href))),ot="node:sqlite",{DatabaseSync:rt}=it(ot);function N(n){let e=[];for(let t of n)if(t.type==="tabs"&&"tabs"in t)for(let s of t.tabs)e.push(...N(s.fields));else t.type==="row"&&"fields"in t?e.push(...N(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...N(t.fields)):e.push(t);return e}function ct(n,e){let t=e,s=n[t.name];if(t.type==="json"||t.type==="richtext"||t.type==="array"||t.type==="group"||t.type==="blocks"||t.type==="list"||t.type==="relationship-block")try{s=s?JSON.parse(s):null;}catch{s=null;}if(t.type==="checkbox"&&(s=!!s),t.type==="date"&&s)try{let a=new Date(s);isNaN(a.getTime())?s=null:s=a.toISOString();}catch{s=null;}if((t.type==="upload"||t.type==="image")&&s)try{let a=JSON.parse(s);Array.isArray(a)?s=a.map(o=>typeof o=="object"&&o!==null?o:{id:o}):s=typeof a=="object"?a:{id:a};}catch{s={id:s};}if(t.type==="relationship"&&s)try{let a=JSON.parse(s);Array.isArray(a),s=a;}catch{s={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:s};}if(t.type==="list"&&s)try{let a=JSON.parse(s);s=Array.isArray(a)?a:[];}catch{s=[];}if(t.type==="relationship-block"&&s)try{let a=JSON.parse(s);s=Array.isArray(a)?a:[];}catch{s=[];}return s}function X(n,e){try{return n.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var J=class extends chunkDV4LFLPL_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(this.db||(this.db=new rt(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=s=>{let a=e(s),o=i=>typeof i=="boolean"?i?1:0:i===void 0?null:i;return new Proxy(a,{get(i,r,c){if(r==="all")return (...u)=>i.all(...u.map(o));if(r==="get")return (...u)=>i.get(...u.map(o));if(r==="run")return (...u)=>i.run(...u.map(o));let d=Reflect.get(i,r,c);return typeof d=="function"?d.bind(i):d}})};t.__wrapped=true,this.db.prepare=t;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){this.db&&this.db.close(),this.connected=false;}ensureTable(e,t){let s=t||this.getTableNameFor(e.slug),a=["id TEXT PRIMARY KEY"];for(let i of N(e.fields)){if(!i.name||i.name==="id")continue;let r=this.fieldToSQL(i);r&&a.push(r);}a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),a.push("status TEXT DEFAULT 'draft'"),a.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let o=X(this.db,s);if(o.length===0){let i=`CREATE TABLE IF NOT EXISTS ${s} (${a.join(", ")})`;this.db.exec(i),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${r.name} ON ${s}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${r.name}_unique ON ${s}(${this.col(r.name)})`);}else {let i=new Set(o);for(let r of a){let c=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!i.has(c)&&c!=="id")try{c==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(c)} TEXT DEFAULT 'published'`):c==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(c)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(c)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
|
|
3
|
+
`)}`),this.name="ConfigValidationError",this.errors=e;}};function V(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Collection slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Collection "${n.slug}" has no fields defined`);else {let t=x(n.fields,n.slug);e.push(...t);}if(n.access)for(let[t,s]of Object.entries(n.access))typeof s!="boolean"&&typeof s!="function"&&e.push(`Collection "${n.slug}" has invalid access.${t} (must be boolean or function)`);if(n.admin?.useAsTitle&&(O(n.fields,n.admin.useAsTitle)||e.push(`Collection "${n.slug}" admin.useAsTitle references unknown field "${n.admin.useAsTitle}"`)),n.admin?.defaultColumns)for(let t of n.admin.defaultColumns)O(n.fields,t)||e.push(`Collection "${n.slug}" admin.defaultColumns references unknown field "${t}"`);if(n.upload&&n.upload.fileSize&&n.upload.fileSize<=0&&e.push(`Collection "${n.slug}" upload.fileSize must be positive`),n.versions&&n.versions.maxPerDoc&&n.versions.maxPerDoc<=0&&e.push(`Collection "${n.slug}" versions.maxPerDoc must be positive`),n.auth){let t=n.fields.some(a=>a.name==="email"),s=n.fields.some(a=>a.name==="password");t||e.push(`Collection "${n.slug}" with auth enabled requires an "email" field`),s||e.push(`Collection "${n.slug}" with auth enabled requires a "password" field`);}return e}function B(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Global slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Global "${n.slug}" has no fields defined`);else {let t=x(n.fields,`global:${n.slug}`);e.push(...t);}return e}function x(n,e){let t=[],s=new Set;for(let a=0;a<n.length;a++){let o=n[a];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let r=x(o.fields,e);t.push(...r);}else if("tabs"in o)for(let r of o.tabs){let c=x(r.fields,e);t.push(...c);}continue}let i=o.name;if(!i){t.push(`${e}: Field at index ${a} is missing a "name" property`);continue}if(s.has(i)&&t.push(`${e}: Duplicate field name "${i}"`),s.add(i),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(i)||t.push(`${e}: Field name "${i}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${i}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${i}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${i}" has no fields defined`);else {let r=x(o.fields,`${e}.${i}`);t.push(...r);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${i}" has no fields defined`);else {let r=x(o.fields,`${e}.${i}`);t.push(...r);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${i}" has no blocks defined`);else {let r=ve(o.blocks,`${e}.${i}`);t.push(...r);}break;case "select":case "radio":if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${i}" has no options defined`);else if(o.options){let r=o.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${o.type} field "${i}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${i}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${i}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${i}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${i}" has minRows greater than maxRows`);}return t}function ve(n,e){let t=[],s=new Set;for(let a of n){if(!a.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(s.has(a.slug)&&t.push(`${e}: Duplicate block slug "${a.slug}"`),s.add(a.slug),a.label||t.push(`${e}: Block "${a.slug}" is missing a "label" property`),!a.fields||a.fields.length===0)t.push(`${e}: Block "${a.slug}" has no fields defined`);else {let o=x(a.fields,`${e}.${a.slug}`);t.push(...o);}}return t}function pe(n,e=[]){let t=[],s=new Set;for(let a of n)s.has(a.slug)&&t.push(`Duplicate collection slug "${a.slug}"`),s.add(a.slug);for(let a of e)s.has(a.slug)&&t.push(`Duplicate global slug "${a.slug}"`),s.add(a.slug);for(let a of n){let o=V(a);t.push(...o);}for(let a of e){let o=B(a);t.push(...o);}for(let a of n){let o=$(a.fields,n);t.push(...o);}if(t.length>0)throw new K(t)}function $(n,e){let t=[],s=new Set(e.map(a=>a.slug));for(let a of n){if(a.type==="relationship"){let o=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let i of o)s.has(i)||console.warn(`[Kyro Config Warning]: Relationship field "${a.name}" references unknown collection "${i}". Select options will not be available until this collection is registered.`);}if(a.type==="upload"){let o=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let i of o)s.has(i)||t.push(`Upload field "${a.name}" references unknown collection "${i}"`);}if("fields"in a&&a.fields){let o=$(a.fields,e);t.push(...o);}if("tabs"in a)for(let o of a.tabs){let i=$(o.fields,e);t.push(...i);}if("blocks"in a)for(let o of a.blocks){let i=$(o.fields,e);t.push(...i);}}return t}function C(n){switch(n.type){case "text":return De(n);case "number":return we(n);case "checkbox":return Fe(n);case "date":return Ie(n);case "email":return $e(n);case "password":return Oe(n);case "textarea":return Pe(n);case "select":return Le(n);case "radio":return ke(n);case "color":return _e(n);case "richtext":return je(n);case "json":return Ze(n);case "code":return qe(n);case "upload":return fe(n);case "image":return fe(n);case "markdown":return Ue(n);case "relationship":return ye(n);case "relationship-block":return ye(n);case "array":return Ge(n);case "list":return Ke(n);case "group":return Ve(n);case "blocks":return Be(n);case "row":return Me(n);case "collapsible":return ze(n);case "tabs":return We(n);default:return zod.z.any()}}function De(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.pattern&&(e=e.regex(new RegExp(n.pattern))),n.variant==="email"&&(e=e.email()),n.variant==="url"&&(e=e.url()),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function we(n){let e=n.integer?zod.z.coerce.number().int():zod.z.coerce.number();return n.min!==void 0&&(e=e.min(n.min)),n.max!==void 0&&(e=e.max(n.max)),n.step&&(e=e.refine(t=>Number.isInteger(t/n.step),`Value must be divisible by ${n.step}`)),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Fe(n){let e=zod.z.boolean();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ie(n){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return n.minDate&&(e=e.refine(t=>new Date(t)>=new Date(n.minDate),`Date must be after ${n.minDate}`)),n.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(n.maxDate),`Date must be before ${n.maxDate}`)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function $e(n){let e=zod.z.string().email("Invalid email");return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Oe(n){let e=zod.z.string().min(6,"Password must be at least 6 characters");return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Pe(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Le(n){let e;if(n.options&&n.options.length>0){let t=n.options.map(s=>s.value);n.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=n.hasMany?zod.z.array(zod.z.string()):zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function ke(n){let e=n.options.map(s=>s.value),t=zod.z.enum(e);return n.required||(t=t.optional().nullable()),n.validate&&(t=b(t,n.validate)),t}function _e(n){let e=zod.z.string();return n.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),n.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),n.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function je(n){let e=zod.z.array(zod.z.record(zod.z.any()));return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ze(n){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function qe(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function fe(n){let e;if(n.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 n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ue(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function ye(n){let e;return Array.isArray(n.relationTo)?e=zod.z.object({relationTo:zod.z.enum(n.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ge(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(s=>s.name).map(s=>[s.name,C(s)]))),t=zod.z.array(e);return n.minRows&&(t=t.min(n.minRows)),n.maxRows&&(t=t.max(n.maxRows)),n.required||(t=t.optional().nullable()),n.validate&&(t=b(t,n.validate)),t}function Ke(n){let e=zod.z.array(zod.z.string());return n.required||(e=e.optional().nullable()),e}function Ve(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])));return n.required?e:e.optional().nullable()}function Be(n){let e=n.blocks||[];e.map(o=>zod.z.object({blockType:zod.z.literal(o.slug),...Object.fromEntries(o.fields.filter(i=>i.name).map(i=>[i.name,C(i)]))}));let s=e.map(o=>o.slug),a;if(s.length>0){let o=zod.z.object({blockType:zod.z.enum(s)}).catchall(zod.z.any()),i=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());a=zod.z.array(zod.z.union([o,i,zod.z.record(zod.z.any())]));}else a=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return n.minRows&&(a=a.min(n.minRows)),n.maxRows&&(a=a.max(n.maxRows)),n.required||(a=a.optional().nullable()),n.validate&&(a=b(a,n.validate)),a}function Me(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function ze(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function We(n){let e={};for(let t of n.tabs)for(let s of t.fields)s.name&&(e[s.name]=C(s));return zod.z.object(e).passthrough().optional()}function b(n,e){return n.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function R(n){let e={};for(let t of n)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs){let o=R(a.fields);Object.assign(s,o);}e[t.name]=zod.z.object(s).passthrough().optional();}else if(t.type==="row"&&"fields"in t){let s=R(t.fields);Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(R(t.fields)).passthrough().optional():e[t.name]=C(t);return e}function E(n){let e={};for(let t of n)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs){let o=E(a.fields);Object.assign(s,o);}e[t.name]=zod.z.object(s).passthrough().optional().nullable();}else if(t.type==="row"&&"fields"in t){let s=E(t.fields);Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).passthrough().optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).passthrough().optional().nullable():e[t.name]=C(t).optional().nullable();return e}function he(n){let e=R(n.fields);return n.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),n.tenantScoped&&(e.tenantID=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function ge(n){let e=R(n.fields);return zod.z.object(e).passthrough()}function me(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs)for(let o of a.fields)o.name&&(s[o.name]=C(o).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else if(t.type==="row"&&"fields"in t){let s={};for(let a of t.fields)a.name&&(s[a.name]=C(a).optional().nullable());Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return zod.z.object(e).passthrough()}function be(n){let e={};for(let t of n.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 Te(n){let e=R(n.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ce(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs)for(let o of a.fields)o.name&&(s[o.name]=C(o).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return zod.z.object(e).passthrough()}var w=class{storageProviders=chunk3HVN4CBK_cjs.f();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};for(let a of this.plugins)a.extendCollection&&(t=a.extendCollection(t.slug,t));t.fields=this.applyFieldDefaults(t);let s=V(t);if(s.length>0)throw new Error(`Invalid collection config: ${s.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=B(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let s={...e};for(let a of this.plugins)a.extendGlobal&&(s=a.extendGlobal(s.slug,s));this.globals.set(s.slug,s),this.clearSchemaCache(`global:${s.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 s=this.collections.get(e);if(s){let o=he(s);return this.schemaCache.set(e,o),o}let a=this.globals.get(e);if(a){let o=Te(a);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`,s=this.schemaCache.get(t);if(s)return s;let a=this.collections.get(e);if(a){let o=ge(a);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,s=this.schemaCache.get(t);if(s)return s;let a=this.collections.get(e);if(a){let i=me(a);return this.schemaCache.set(t,i),i}let o=this.globals.get(e);if(o){let i=Ce(o);return this.schemaCache.set(`global:${e}:update`,i),i}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,s=this.schemaCache.get(t);if(s)return s;let a=this.collections.get(e);if(a){let o=be(a);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return C(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(s=>s.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(s=>s.name==="tenantID")&&t.push({name:"tenantID",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(s=>s.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(s=>s.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(s=>s.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 s=this.globals.get(e);if(s)return s.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),s=new Map,a=o=>{for(let i of o){if(i.name&&s.set(i.name,i),"fields"in i&&i.fields&&a(i.fields),"tabs"in i)for(let r of i.tabs)a(r.fields);if("blocks"in i)for(let r of i.blocks)a(r.fields);}};return a(t),s}getVisibleFields(e){return this.getFields(e).filter(s=>!s.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();pe(e,t);}async init(e){this.validate();for(let t of this.plugins)t.init&&await t.init(e||this);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 s=this.collections.get(e)?.admin?.useAsTitle;return s||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(a=>a.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()}}},v=null;function Xe(){return v||(v=new w),v}function Je(){v=null;}function M(){return v=new w,v}var He={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 Ye(n,e){switch(n){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 Ae(n,e){return {provider:n,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:Ye(n,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function Qe(n,e,t){let s=t[e.configKey]||{};return Ae(n,s)}function et(n,e,t){let s=t?.[e.configKey]||t;return Ae(n,s)}var Se={name:"@kyro-cms/storage-s3",version:"1.0.0",description:"S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)",init:n=>{let e=n.registry?.storageProviders;if(!e)return;let t="@kyro-cms/storage-s3";for(let s of Object.values(He))e.register({type:s.type,displayName:s.displayName,pluginName:t,configKey:s.configKey,configFields:s.configFields,extractConfig:a=>Qe(s.type,s,a),extractRawConfig:a=>et(s.type,s,a),factory:a=>chunk3HVN4CBK_cjs.a(a)});}};var Ee={name:"@kyro-cms/storage-cloudinary",version:"1.0.0",description:"Cloudinary image and video storage",init:n=>{let e=n.registry?.storageProviders;e&&e.register({type:"cloudinary",displayName:"Cloudinary",pluginName:"@kyro-cms/storage-cloudinary",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:t=>({cloudName:t.cloudinary?.cloudName||"",apiKey:t.cloudinary?.apiKey||"",apiSecret:t.cloudinary?.apiSecret||"",folder:t.cloudinary?.folder,uploadPreset:t.cloudinary?.uploadPreset}),extractRawConfig:t=>{let s=t?.cloudinary||t;return {cloudName:s?.cloudName||"",apiKey:s?.apiKey||"",apiSecret:s?.apiSecret||"",folder:s?.folder,uploadPreset:s?.uploadPreset}},factory:t=>chunk3HVN4CBK_cjs.b(t)});}};var xe={name:"@kyro-cms/storage-ftp",version:"1.0.0",description:"FTP/SFTP storage provider",init:n=>{let e=n.registry?.storageProviders;e&&e.register({type:"ftp",displayName:"FTP",pluginName:"@kyro-cms/storage-ftp",configKey:"ftp",configFields:[{name:"host",type:"text",label:"Host",required:true,admin:{placeholder:"ftp.example.com"}},{name:"port",type:"number",label:"Port",defaultValue:21,admin:{placeholder:"21 for FTP"}},{name:"user",type:"text",label:"Username",required:true},{name:"password",type:"password",label:"Password",required:true},{name:"secure",type:"checkbox",label:"Use TLS/SSL",defaultValue:false,admin:{description:"Enable TLS/SSL for secure connections (FTP only)"}},{name:"baseUrl",type:"text",label:"Base URL",required:true,admin:{placeholder:"https://files.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}],extractConfig:t=>({host:t.ftp?.host||"",port:t.ftp?.port||21,user:t.ftp?.user||"",password:t.ftp?.password||"",secure:t.ftp?.secure||false,baseUrl:t.ftp?.baseUrl||"",prefix:t.ftp?.prefix,type:"ftp"}),extractRawConfig:t=>{let s=t?.ftp||t;return {host:s?.host||"",port:s?.port||21,user:s?.user||"",password:s?.password||"",secure:s?.secure||false,baseUrl:s?.baseUrl||"",prefix:s?.prefix,type:"ftp"}},factory:t=>chunk3HVN4CBK_cjs.c(t)});}};var nt=[Se,Ee,xe];function z(n,e,t){let s=e.split(".");if(s.length===0)return false;let a=s[0],o=s.slice(1).join(".");for(let i of n)if(i.name===a)return o?i.fields&&Array.isArray(i.fields)||i.type==="array"&&i.fields&&Array.isArray(i.fields)?z(i.fields,o,t):false:(Object.assign(i,t),true);return false}function st(n,e){if(e)for(let t of n){let s=e[t.slug];if(s){let{fields:a,...o}=s;if(t.admin={...t.admin,...o},a&&t.fields&&Array.isArray(t.fields))for(let[i,r]of Object.entries(a))z(t.fields,i,r);}}}var W=class{registry;db;pubsub;webhookService;settings;wsServer;config;constructor(e){this.config=e,this.registry=M(),this.db=e.adapter,this.pubsub=new chunkF7SR5IDT_cjs.b(this.registry),this.webhookService=chunkISWMETHJ_cjs.n(this.db);for(let t of nt)this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&st(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.registry.init(this),this.registry.addGlobalPostInit(chunk65G73T7Z_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:chunkNY47CFVP_cjs.d,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"}]},s={slug:chunkISWMETHJ_cjs.e,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},a={slug:chunkISWMETHJ_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 chunk6CLRVJPP_cjs.c&&this.db.dialect==="postgres"){let i=this.db,r=chunkNY47CFVP_cjs.d.replace(/-/g,"_");i.schema[r]||(i.schema[r]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,s,a],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(),s={};try{let a=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});a&&a.states&&(s=a.states);}catch{}for(let a of t)s[a]!==void 0&&e.setPluginEnabled(a,s[a]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,s=t?.secret,a=t?.checkSession!==false;return chunk3HVN4CBK_cjs.s({registry:this.registry,db:this.db,authSecret:s,authAdapter:this.config.authAdapter,checkSession:a,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkCIE3XMLH_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:a})=>{let o=chunkNY47CFVP_cjs.f(a),i,r;if(o&&this.db){let d=await chunkNY47CFVP_cjs.e(o,this.db);d.user&&(i=d.user,r=chunkNY47CFVP_cjs.g(d));}let c=e?.tenantID;return {db:this.db,registry:this.registry,user:i,req:a,tenantID:c,apiKey:r,relationLoader:new chunkCIE3XMLH_cjs.a({db:this.db,tenantID:c,user:i})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,s)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[i,...r]=o.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!i||!c)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 d=await chunkCVVW4LXZ_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantID:e?.tenantID,settings:this.settings}),h=chunkCVVW4LXZ_cjs.i(d)[i];if(!h)return new Response(JSON.stringify({error:{message:`Collection '${i}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let g=h[c];if(typeof g!="function")return new Response(JSON.stringify({error:{message:`Procedure '${c}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let p={};if(t.method==="POST"||t.method==="PATCH")p=await t.json().catch(()=>({}));else {let S=new URL(t.url).searchParams.get("input");if(S)try{p=JSON.parse(decodeURIComponent(S));}catch{}}let f=p?.["0"]??p,m=await g({...f,collection:i});return new Response(JSON.stringify({result:{data:m}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(p){let f=p.message||"Internal error",m=f.includes("not found")?404:f.includes("denied")||f.includes("authentication required")?403:f.includes("conflict")?409:500,S=m===404?-32601:m===403?-32001:m===409?-32002:-32603;return new Response(JSON.stringify({error:{message:f,code:S,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:m}}}),{status:m,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 s=async a=>{let o=await chunkNY47CFVP_cjs.e(a,this.db);if(!o.valid)throw new Error(o.error||"Invalid API key");if(!o.user)throw new Error("API key has no associated user");return o.user};return this.wsServer=chunkF7SR5IDT_cjs.d({pubsub:this.pubsub,port:e?.port||8080,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||s}),this.wsServer}async shutdown(){this.wsServer&&await this.wsServer.close(),await this.db.disconnect();}};function Mt(n){return new W(n)}var it=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-6OXKGEY7.cjs', document.baseURI).href))),ot="node:sqlite",{DatabaseSync:rt}=it(ot);function N(n){let e=[];for(let t of n)if(t.type==="tabs"&&"tabs"in t)for(let s of t.tabs)e.push(...N(s.fields));else t.type==="row"&&"fields"in t?e.push(...N(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...N(t.fields)):e.push(t);return e}function ct(n,e){let t=e,s=n[t.name];if(t.type==="json"||t.type==="richtext"||t.type==="array"||t.type==="group"||t.type==="blocks"||t.type==="list"||t.type==="relationship-block")try{s=s?JSON.parse(s):null;}catch{s=null;}if(t.type==="checkbox"&&(s=!!s),t.type==="date"&&s)try{let a=new Date(s);isNaN(a.getTime())?s=null:s=a.toISOString();}catch{s=null;}if((t.type==="upload"||t.type==="image")&&s)try{let a=JSON.parse(s);Array.isArray(a)?s=a.map(o=>typeof o=="object"&&o!==null?o:{id:o}):s=typeof a=="object"?a:{id:a};}catch{s={id:s};}if(t.type==="relationship"&&s)try{let a=JSON.parse(s);Array.isArray(a),s=a;}catch{s={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:s};}if(t.type==="list"&&s)try{let a=JSON.parse(s);s=Array.isArray(a)?a:[];}catch{s=[];}if(t.type==="relationship-block"&&s)try{let a=JSON.parse(s);s=Array.isArray(a)?a:[];}catch{s=[];}return s}function X(n,e){try{return n.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var J=class extends chunkDV4LFLPL_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(this.db||(this.db=new rt(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=s=>{let a=e(s),o=i=>typeof i=="boolean"?i?1:0:i===void 0?null:i;return new Proxy(a,{get(i,r,c){if(r==="all")return (...u)=>i.all(...u.map(o));if(r==="get")return (...u)=>i.get(...u.map(o));if(r==="run")return (...u)=>i.run(...u.map(o));let d=Reflect.get(i,r,c);return typeof d=="function"?d.bind(i):d}})};t.__wrapped=true,this.db.prepare=t;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){this.db&&this.db.close(),this.connected=false;}ensureTable(e,t){let s=t||this.getTableNameFor(e.slug),a=["id TEXT PRIMARY KEY"];for(let i of N(e.fields)){if(!i.name||i.name==="id")continue;let r=this.fieldToSQL(i);r&&a.push(r);}a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),a.push("status TEXT DEFAULT 'draft'"),a.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let o=X(this.db,s);if(o.length===0){let i=`CREATE TABLE IF NOT EXISTS ${s} (${a.join(", ")})`;this.db.exec(i),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${r.name} ON ${s}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${r.name}_unique ON ${s}(${this.col(r.name)})`);}else {let i=new Set(o);for(let r of a){let c=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!i.has(c)&&c!=="id")try{c==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(c)} TEXT DEFAULT 'published'`):c==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(c)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(c)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
|
|
4
4
|
CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
6
6
|
collection_slug TEXT NOT NULL,
|