@kyro-cms/core 0.12.1 → 0.12.3
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-HQND27DT.cjs → chunk-32GUKU7D.cjs} +2 -2
- package/dist/chunk-3YGGZ2VN.js +133 -0
- package/dist/{chunk-APQOYPRT.cjs → chunk-54B2Q567.cjs} +7 -7
- package/dist/{chunk-FKTZLM2C.cjs → chunk-7WQ4D7WW.cjs} +1 -1
- package/dist/{chunk-QMPMY2WI.js → chunk-B7V5KOIM.js} +7 -7
- package/dist/{chunk-WRSQOKRF.js → chunk-GDCTY6JO.js} +1 -1
- package/dist/{chunk-BRAWV32L.js → chunk-MAWFXNW4.js} +1 -1
- package/dist/chunk-Z7CNY2UV.cjs +133 -0
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5KGQOTLK.cjs +0 -133
- package/dist/chunk-76RLJA6S.js +0 -133
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk7WQ4D7WW_cjs=require('./chunk-7WQ4D7WW.cjs');require('./chunk-32GUKU7D.cjs'),require('./chunk-UJNSOOYZ.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ER2PUSHG.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-54B2Q567.cjs'),require('./chunk-AJAZ7D3W.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GFU7AOI3.cjs'),require('./chunk-ET6NN2V2.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-WE46GGL4.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-G3J2EU5D.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-Z7CNY2UV.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-UBHFUFD4.cjs'),require('./chunk-UCCFT5OO.cjs'),require('./chunk-ATLSIYRH.cjs'),require('./chunk-EJDIR56C.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 chunk7WQ4D7WW_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await chunk7WQ4D7WW_cjs.b(),!await o())return r();let t=await chunk7WQ4D7WW_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await chunk7WQ4D7WW_cjs.b(),!await o())return r();let t=await chunk7WQ4D7WW_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)};exports.GET=u;exports.POST=l;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b,a}from'./chunk-
|
|
1
|
+
import {b,a}from'./chunk-MAWFXNW4.js';import'./chunk-GDCTY6JO.js';import'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-5BPMMIAQ.js';import'./chunk-PP7W5UKL.js';import'./chunk-B7V5KOIM.js';import'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';import'./chunk-KG7V6O2Z.js';import'./chunk-HLSB2MCK.js';import'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';import'./chunk-3YGGZ2VN.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';import'./chunk-YPDRUVWG.js';import'./chunk-P7CESLDJ.js';import'./chunk-TQNM4C7H.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 chunk7WQ4D7WW_cjs=require('./chunk-7WQ4D7WW.cjs');require('./chunk-32GUKU7D.cjs'),require('./chunk-UJNSOOYZ.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ER2PUSHG.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-54B2Q567.cjs'),require('./chunk-AJAZ7D3W.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GFU7AOI3.cjs'),require('./chunk-ET6NN2V2.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-WE46GGL4.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-G3J2EU5D.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-Z7CNY2UV.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-UBHFUFD4.cjs'),require('./chunk-UCCFT5OO.cjs'),require('./chunk-ATLSIYRH.cjs'),require('./chunk-EJDIR56C.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 chunk7WQ4D7WW_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await chunk7WQ4D7WW_cjs.b(),await s()?chunk7WQ4D7WW_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-MAWFXNW4.js';import'./chunk-GDCTY6JO.js';import'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-5BPMMIAQ.js';import'./chunk-PP7W5UKL.js';import'./chunk-B7V5KOIM.js';import'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';import'./chunk-KG7V6O2Z.js';import'./chunk-HLSB2MCK.js';import'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';import'./chunk-3YGGZ2VN.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';import'./chunk-YPDRUVWG.js';import'./chunk-P7CESLDJ.js';import'./chunk-TQNM4C7H.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 chunk7WQ4D7WW_cjs=require('./chunk-7WQ4D7WW.cjs');require('./chunk-32GUKU7D.cjs'),require('./chunk-UJNSOOYZ.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ER2PUSHG.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-54B2Q567.cjs'),require('./chunk-AJAZ7D3W.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GFU7AOI3.cjs'),require('./chunk-ET6NN2V2.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-WE46GGL4.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-G3J2EU5D.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-Z7CNY2UV.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-UBHFUFD4.cjs'),require('./chunk-UCCFT5OO.cjs'),require('./chunk-ATLSIYRH.cjs'),require('./chunk-EJDIR56C.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');Object.defineProperty(exports,"ALL",{enumerable:true,get:function(){return chunk7WQ4D7WW_cjs.c}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunk7WQ4D7WW_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunk7WQ4D7WW_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-MAWFXNW4.js';import'./chunk-GDCTY6JO.js';import'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-5BPMMIAQ.js';import'./chunk-PP7W5UKL.js';import'./chunk-B7V5KOIM.js';import'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';import'./chunk-KG7V6O2Z.js';import'./chunk-HLSB2MCK.js';import'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';import'./chunk-3YGGZ2VN.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';import'./chunk-YPDRUVWG.js';import'./chunk-P7CESLDJ.js';import'./chunk-TQNM4C7H.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
'use strict';var chunk65G73T7Z_cjs=require('./chunk-65G73T7Z.cjs'),chunkKD7LUCFY_cjs=require('./chunk-KD7LUCFY.cjs'),chunkER2PUSHG_cjs=require('./chunk-ER2PUSHG.cjs'),chunkHS2KNFAB_cjs=require('./chunk-HS2KNFAB.cjs'),
|
|
1
|
+
'use strict';var chunk65G73T7Z_cjs=require('./chunk-65G73T7Z.cjs'),chunkKD7LUCFY_cjs=require('./chunk-KD7LUCFY.cjs'),chunkER2PUSHG_cjs=require('./chunk-ER2PUSHG.cjs'),chunkHS2KNFAB_cjs=require('./chunk-HS2KNFAB.cjs'),chunk54B2Q567_cjs=require('./chunk-54B2Q567.cjs'),chunkWE46GGL4_cjs=require('./chunk-WE46GGL4.cjs'),chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkG3J2EU5D_cjs=require('./chunk-G3J2EU5D.cjs'),chunkZ7CNY2UV_cjs=require('./chunk-Z7CNY2UV.cjs'),chunkMIOMMB23_cjs=require('./chunk-MIOMMB23.cjs'),chunkEJDIR56C_cjs=require('./chunk-EJDIR56C.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(s,e){for(let t of s){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let n of t.tabs)if(O(n.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(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Collection slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Collection "${s.slug}" has no fields defined`);else {let t=N(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,n]of Object.entries(s.access))typeof n!="boolean"&&typeof n!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(O(s.fields,s.admin.useAsTitle)||e.push(`Collection "${s.slug}" admin.useAsTitle references unknown field "${s.admin.useAsTitle}"`)),s.admin?.defaultColumns)for(let t of s.admin.defaultColumns)O(s.fields,t)||e.push(`Collection "${s.slug}" admin.defaultColumns references unknown field "${t}"`);if(s.upload&&s.upload.fileSize&&s.upload.fileSize<=0&&e.push(`Collection "${s.slug}" upload.fileSize must be positive`),s.versions&&s.versions.maxPerDoc&&s.versions.maxPerDoc<=0&&e.push(`Collection "${s.slug}" versions.maxPerDoc must be positive`),s.auth){let t=s.fields.some(a=>a.name==="email"),n=s.fields.some(a=>a.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),n||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function B(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Global slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Global "${s.slug}" has no fields defined`);else {let t=N(s.fields,`global:${s.slug}`);e.push(...t);}return e}function N(s,e){let t=[],n=new Set;for(let a=0;a<s.length;a++){let i=s[a];if(i.type==="row"||i.type==="collapsible"||i.type==="tabs"){if("fields"in i&&i.fields){let r=N(i.fields,e);t.push(...r);}else if("tabs"in i)for(let r of i.tabs){let c=N(r.fields,e);t.push(...c);}continue}let o=i.name;if(!o){t.push(`${e}: Field at index ${a} is missing a "name" property`);continue}if(n.has(o)&&t.push(`${e}: Duplicate field name "${o}"`),n.add(o),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(o)||t.push(`${e}: Field name "${o}" must be alphanumeric with underscores`),!i.type){t.push(`${e}: Field "${o}" is missing a "type" property`);continue}switch(i.type){case "relationship":i.relationTo||t.push(`${e}: Relationship field "${o}" is missing "relationTo"`);break;case "array":if(!i.fields||i.fields.length===0)t.push(`${e}: Array field "${o}" has no fields defined`);else {let r=N(i.fields,`${e}.${o}`);t.push(...r);}break;case "group":if(!i.fields||i.fields.length===0)t.push(`${e}: Group field "${o}" has no fields defined`);else {let r=N(i.fields,`${e}.${o}`);t.push(...r);}break;case "blocks":if(!i.blocks||i.blocks.length===0)t.push(`${e}: Blocks field "${o}" has no blocks defined`);else {let r=Ie(i.blocks,`${e}.${o}`);t.push(...r);}break;case "select":case "radio":if(typeof i.options=="function")break;if((!i.options||i.options.length===0)&&!i.dynamicOptions)t.push(`${e}: ${i.type} field "${o}" has no options defined`);else if(Array.isArray(i.options)){let r=i.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${i.type} field "${o}" has duplicate option values`);}break;case "upload":i.relationTo||t.push(`${e}: Upload field "${o}" is missing "relationTo"`);break}"min"in i&&"max"in i&&i.min>i.max&&t.push(`${e}: Field "${o}" has min greater than max`),"minLength"in i&&"maxLength"in i&&i.minLength>i.maxLength&&t.push(`${e}: Field "${o}" has minLength greater than maxLength`),"minRows"in i&&"maxRows"in i&&i.minRows>i.maxRows&&t.push(`${e}: Field "${o}" has minRows greater than maxRows`);}return t}function Ie(s,e){let t=[],n=new Set;for(let a of s){if(!a.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(a.slug)&&t.push(`${e}: Duplicate block slug "${a.slug}"`),n.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 i=N(a.fields,`${e}.${a.slug}`);t.push(...i);}}return t}function fe(s,e=[]){let t=[],n=new Set;for(let a of s)n.has(a.slug)&&t.push(`Duplicate collection slug "${a.slug}"`),n.add(a.slug);for(let a of e)n.has(a.slug)&&t.push(`Duplicate global slug "${a.slug}"`),n.add(a.slug);for(let a of s){let i=V(a);t.push(...i);}for(let a of e){let i=B(a);t.push(...i);}for(let a of s){let i=$(a.fields,s);t.push(...i);}if(t.length>0)throw new K(t)}function $(s,e){let t=[],n=new Set(e.map(a=>a.slug));for(let a of s){if(a.type==="relationship"){let i=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let o of i)n.has(o)||console.warn(`[Kyro Config Warning]: Relationship field "${a.name}" references unknown collection "${o}". Select options will not be available until this collection is registered.`);}if(a.type==="upload"){let i=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let o of i)n.has(o)||t.push(`Upload field "${a.name}" references unknown collection "${o}"`);}if("fields"in a&&a.fields){let i=$(a.fields,e);t.push(...i);}if("tabs"in a)for(let i of a.tabs){let o=$(i.fields,e);t.push(...o);}if("blocks"in a)for(let i of a.blocks){let o=$(i.fields,e);t.push(...o);}}return t}function C(s){switch(s.type){case "text":return $e(s);case "number":return Oe(s);case "checkbox":return Pe(s);case "date":return Le(s);case "email":return ke(s);case "password":return _e(s);case "textarea":return je(s);case "select":return Ze(s);case "radio":return qe(s);case "color":return Ue(s);case "richtext":return Ge(s);case "json":return Ke(s);case "code":return Ve(s);case "upload":return ye(s);case "image":return ye(s);case "markdown":return Be(s);case "relationship":return he(s);case "relationship-block":return he(s);case "array":return Me(s);case "list":return ze(s);case "group":return We(s);case "blocks":return Xe(s);case "row":return Je(s);case "collapsible":return He(s);case "tabs":return Ye(s);default:return zod.z.any()}}function $e(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.pattern&&(e=e.regex(new RegExp(s.pattern))),s.variant==="email"&&(e=e.email()),s.variant==="url"&&(e=e.url()),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Oe(s){let e=s.integer?zod.z.coerce.number().int():zod.z.coerce.number();return s.min!==void 0&&(e=e.min(s.min)),s.max!==void 0&&(e=e.max(s.max)),s.step&&(e=e.refine(t=>Number.isInteger(t/s.step),`Value must be divisible by ${s.step}`)),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Pe(s){let e=zod.z.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Le(s){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return s.minDate&&(e=e.refine(t=>new Date(t)>=new Date(s.minDate),`Date must be after ${s.minDate}`)),s.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(s.maxDate),`Date must be before ${s.maxDate}`)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ke(s){let e=zod.z.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function _e(s){let e=zod.z.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function je(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ze(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);s.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=s.hasMany?zod.z.array(zod.z.string()):zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function qe(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);e=zod.z.enum(t);}else e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ue(s){let e=zod.z.string();return s.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),s.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),s.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ge(s){let e=zod.z.array(zod.z.record(zod.z.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ke(s){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ve(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ye(s){let e;if(s.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Be(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function he(s){let e;return Array.isArray(s.relationTo)?e=zod.z.object({relationTo:zod.z.enum(s.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Me(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,C(n)]))).passthrough(),t=zod.z.array(e);return s.minRows&&(t=t.min(s.minRows)),s.maxRows&&(t=t.max(s.maxRows)),s.required||(t=t.optional().nullable()),s.validate&&(t=T(t,s.validate)),t}function ze(s){let e=zod.z.array(zod.z.string());return s.required||(e=e.optional().nullable()),e}function We(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])));return s.required?e:e.optional().nullable()}function Xe(s){let e=s.blocks||[];e.map(i=>zod.z.object({blockType:zod.z.literal(i.slug),...Object.fromEntries(i.fields.filter(o=>o.name).map(o=>[o.name,C(o)]))}));let n=e.map(i=>i.slug),a;if(n.length>0){let i=zod.z.object({blockType:zod.z.enum(n)}).catchall(zod.z.any()),o=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());a=zod.z.array(zod.z.union([i,o,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 s.minRows&&(a=a.min(s.minRows)),s.maxRows&&(a=a.max(s.maxRows)),s.required||(a=a.optional().nullable()),s.validate&&(a=T(a,s.validate)),a}function Je(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function He(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function Ye(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=C(n));return zod.z.object(e).passthrough().optional()}function T(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function R(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let i=R(a.fields);Object.assign(n,i);}e[t.name]=zod.z.object(n).passthrough().optional();}else if(t.type==="row"&&"fields"in t){let n=R(t.fields);Object.assign(e,n);}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(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let i=E(a.fields);Object.assign(n,i);}e[t.name]=zod.z.object(n).passthrough().optional().nullable();}else if(t.type==="row"&&"fields"in t){let n=E(t.fields);Object.assign(e,n);}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 ge(s){let e=R(s.fields);return s.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),s.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function me(s){let e=R(s.fields);return zod.z.object(e).passthrough()}function be(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let i of a.fields)i.name&&(n[i.name]=C(i).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let a of t.fields)a.name&&(n[a.name]=C(a).optional().nullable());Object.assign(e,n);}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 Te(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Ae(s){let e=R(s.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ce(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let i of a.fields)i.name&&(n[i.name]=C(i).optional().nullable());e[t.name]=zod.z.object(n).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 D=class{storageProviders=chunkAPQOYPRT_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));if(t.seo){let a=chunkKD7LUCFY_cjs.a(),i=t.fields.find(o=>o.type==="tabs"&&o.name==="tabs");i&&i.tabs?i.tabs.push({label:"SEO Settings",fields:a.fields}):t.fields.push(a);}t.fields=this.applyFieldDefaults(t);let n=V(t);if(n.length>0)throw new Error(`Invalid collection config: ${n.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=B(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let a of this.plugins)a.extendGlobal&&(n=a.extendGlobal(n.slug,n));this.globals.set(n.slug,n),this.clearSchemaCache(`global:${n.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let n=this.collections.get(e);if(n){let i=ge(n);return this.schemaCache.set(e,i),i}let a=this.globals.get(e);if(a){let i=Ae(a);return this.schemaCache.set(`global:${e}`,i),i}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let i=me(a);return this.schemaCache.set(t,i),i}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let o=be(a);return this.schemaCache.set(t,o),o}let i=this.globals.get(e);if(i){let o=Ce(i);return this.schemaCache.set(`global:${e}:update`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let i=Te(a);return this.schemaCache.set(t,i),i}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(n=>n.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(n=>n.name==="tenantId")&&t.push({name:"tenantId",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(n=>n.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(n=>n.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(n=>n.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let n=this.globals.get(e);if(n)return n.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),n=new Map,a=i=>{for(let o of i){if(o.name&&n.set(o.name,o),"fields"in o&&o.fields&&a(o.fields),"tabs"in o)for(let r of o.tabs)a(r.fields);if("blocks"in o)for(let r of o.blocks)a(r.fields);}};return a(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();fe(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 n=this.collections.get(e)?.admin?.useAsTitle;return n||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(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 Qe(){return v||(v=new D),v}function et(){v=null;}function M(){return v=new D,v}var tt={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 st(s,e){switch(s){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Se(s,e){return {provider:s,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:st(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function nt(s,e,t){let n=t[e.configKey]||{};return Se(s,n)}function at(s,e,t){let n=t?.[e.configKey]||t;return Se(s,n)}var Ee={name:"@kyro-cms/storage-s3",version:"1.0.0",description:"S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)",init:s=>{let e=s.registry?.storageProviders;if(!e)return;let t="@kyro-cms/storage-s3";for(let n of Object.values(tt))e.register({type:n.type,displayName:n.displayName,pluginName:t,configKey:n.configKey,configFields:n.configFields,extractConfig:a=>nt(n.type,n,a),extractRawConfig:a=>at(n.type,n,a),factory:a=>chunkAPQOYPRT_cjs.a(a)});}};var xe={name:"@kyro-cms/storage-cloudinary",version:"1.0.0",description:"Cloudinary image and video storage",init:s=>{let e=s.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 n=t?.cloudinary||t;return {cloudName:n?.cloudName||"",apiKey:n?.apiKey||"",apiSecret:n?.apiSecret||"",folder:n?.folder,uploadPreset:n?.uploadPreset}},factory:t=>chunkAPQOYPRT_cjs.b(t)});}};var Ne={name:"@kyro-cms/storage-ftp",version:"1.0.0",description:"FTP/SFTP storage provider",init:s=>{let e=s.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 n=t?.ftp||t;return {host:n?.host||"",port:n?.port||21,user:n?.user||"",password:n?.password||"",secure:n?.secure||false,baseUrl:n?.baseUrl||"",prefix:n?.prefix,type:"ftp"}},factory:t=>chunkAPQOYPRT_cjs.c(t)});}};var ot=[Ee,xe,Ne];function z(s,e,t){let n=e.split(".");if(n.length===0)return false;let a=n[0],i=n.slice(1).join(".");for(let o of s)if(o.name===a)return i?o.fields&&Array.isArray(o.fields)||o.type==="array"&&o.fields&&Array.isArray(o.fields)?z(o.fields,i,t):false:(Object.assign(o,t),true);return false}function rt(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:a,...i}=n;if(t.admin={...t.admin,...i},a&&t.fields&&Array.isArray(t.fields))for(let[o,r]of Object.entries(a))z(t.fields,o,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 chunkG3J2EU5D_cjs.b(this.registry),this.webhookService=chunkWE46GGL4_cjs.o(this.db);for(let t of ot)this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&rt(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"}]},n={slug:chunkWE46GGL4_cjs.f,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},a={slug:chunkWE46GGL4_cjs.g,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"}]},i=this.registry.getGlobals();if(this.db instanceof chunk5KGQOTLK_cjs.c&&this.db.dialect==="postgres"){let o=this.db,r=chunkNY47CFVP_cjs.d.replace(/-/g,"_");o.schema[r]||(o.schema[r]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,n,a],i),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),n={};try{let a=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});a&&a.states&&(n=a.states);}catch{}for(let a of t)n[a]!==void 0&&e.setPluginEnabled(a,n[a]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,a=t?.checkSession!==false;return chunkAPQOYPRT_cjs.s({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:a,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkHS2KNFAB_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:a})=>{let i=chunkNY47CFVP_cjs.f(a),o,r;if(i&&this.db){let d=await chunkNY47CFVP_cjs.e(i,this.db);d.user&&(o=d.user,r=chunkNY47CFVP_cjs.g(d));}let c=e?.tenantId;return {db:this.db,registry:this.registry,user:o,req:a,tenantId:c,apiKey:r,relationLoader:new chunkHS2KNFAB_cjs.a({db:this.db,tenantId:c,user:o})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let i=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[o,...r]=i.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!o||!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 chunkER2PUSHG_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),p=chunkER2PUSHG_cjs.i(d)[o];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${o}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let m=p[c];if(typeof m!="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 y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let A=new URL(t.url).searchParams.get("input");if(A)try{y=JSON.parse(decodeURIComponent(A));}catch{}}let h=y?.["0"]??y,f=await m({...h,collection:o});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let h=y.message||"Internal error",f=h.includes("not found")?404:h.includes("denied")||h.includes("authentication required")?403:h.includes("conflict")?409:500,A=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:h,code:A,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let n=async a=>{let i=await chunkNY47CFVP_cjs.e(a,this.db);if(!i.valid)throw new Error(i.error||"Invalid API key");if(!i.user)throw new Error("API key has no associated user");return i.user};return this.wsServer=chunkG3J2EU5D_cjs.d({pubsub:this.pubsub,port:e?.port||8080,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||n}),this.wsServer}async shutdown(){this.wsServer&&await this.wsServer.close(),await this.db.disconnect();}};function Ht(s){return new W(s)}var ct=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-HQND27DT.cjs', document.baseURI).href))),dt="node:sqlite",{DatabaseSync:ut}=ct(dt);function x(s){let e=[];for(let t of s)if(t.type==="tabs"&&"tabs"in t)for(let n of t.tabs)e.push(...x(n.fields));else t.type==="row"&&"fields"in t?e.push(...x(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...x(t.fields)):e.push(t);return e}function ft(s,e){let t=e,n=s[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{n=n?JSON.parse(n):null;}catch{n=null;}if(t.type==="checkbox"&&(n=!!n),t.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((t.type==="upload"||t.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(i=>typeof i=="object"&&i!==null?i:{id:i}):n=typeof a=="object"?a:{id:a};}catch{n={id:n};}if(t.type==="relationship"&&n)try{let a=JSON.parse(n);Array.isArray(a),n=a;}catch{n={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:n};}if(t.type==="list"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}if(t.type==="relationship-block"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}return n}function Re(s,e){return Array.isArray(s)?s.map(t=>{if(!t||typeof t!="object")return t;let n=t.data?{...t.data}:void 0;if(!n)return t;let a=e.find(i=>i.slug===t.type||i.slug===t.slug);if(!a||!Array.isArray(a.fields))return t;for(let i of a.fields){if(i.name&&(i.type==="upload"||i.type==="image")&&n[i.name]){let o=n[i.name];Array.isArray(o)?n[i.name]=o.map(r=>typeof r=="string"?{id:r}:r):typeof o=="string"&&(n[i.name]={id:o});}if(i.type==="blocks"&&i.name&&n[i.name]){let o=i.blocks||[];n[i.name]=Re(n[i.name],o);}}return {...t,data:n}}):s}function X(s,e){try{return s.prepare(`PRAGMA table_info(${e})`).all().map(n=>n.name)}catch{return []}}var J=class extends chunkEJDIR56C_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 ut(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=n=>{let a=e(n),i=o=>typeof o=="boolean"?o?1:0:o===void 0?null:o;return new Proxy(a,{get(o,r,c){if(r==="all")return (...u)=>o.all(...u.map(i));if(r==="get")return (...u)=>o.get(...u.map(i));if(r==="run")return (...u)=>o.run(...u.map(i));let d=Reflect.get(o,r,c);return typeof d=="function"?d.bind(o):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 n=t||this.getTableNameFor(e.slug),a=["id TEXT PRIMARY KEY"];for(let r of x(e.fields)){if(!r.name||r.name==="id")continue;let c=this.fieldToSQL(r);c&&a.push(c);}let i=x(e.fields);i.some(r=>r.name==="createdAt")||a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),i.some(r=>r.name==="updatedAt")||a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),i.some(r=>r.name==="status")||a.push("status TEXT DEFAULT 'draft'"),i.some(r=>r.name==="hasDraft")||a.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let o=X(this.db,n);if(o.length===0){let r=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(r),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let c of x(e.fields))c.name&&c.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${c.name} ON ${n}(${this.col(c.name)})`),c.name&&c.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${c.name}_unique ON ${n}(${this.col(c.name)})`);}else {let r=new Set(o);for(let c of a){let d=c.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!r.has(d)&&d!=="id")try{d==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} TEXT DEFAULT 'published'`):d==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
|
|
3
|
+
`)}`),this.name="ConfigValidationError",this.errors=e;}};function V(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Collection slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Collection "${s.slug}" has no fields defined`);else {let t=N(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,n]of Object.entries(s.access))typeof n!="boolean"&&typeof n!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(O(s.fields,s.admin.useAsTitle)||e.push(`Collection "${s.slug}" admin.useAsTitle references unknown field "${s.admin.useAsTitle}"`)),s.admin?.defaultColumns)for(let t of s.admin.defaultColumns)O(s.fields,t)||e.push(`Collection "${s.slug}" admin.defaultColumns references unknown field "${t}"`);if(s.upload&&s.upload.fileSize&&s.upload.fileSize<=0&&e.push(`Collection "${s.slug}" upload.fileSize must be positive`),s.versions&&s.versions.maxPerDoc&&s.versions.maxPerDoc<=0&&e.push(`Collection "${s.slug}" versions.maxPerDoc must be positive`),s.auth){let t=s.fields.some(a=>a.name==="email"),n=s.fields.some(a=>a.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),n||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function B(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Global slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Global "${s.slug}" has no fields defined`);else {let t=N(s.fields,`global:${s.slug}`);e.push(...t);}return e}function N(s,e){let t=[],n=new Set;for(let a=0;a<s.length;a++){let i=s[a];if(i.type==="row"||i.type==="collapsible"||i.type==="tabs"){if("fields"in i&&i.fields){let r=N(i.fields,e);t.push(...r);}else if("tabs"in i)for(let r of i.tabs){let c=N(r.fields,e);t.push(...c);}continue}let o=i.name;if(!o){t.push(`${e}: Field at index ${a} is missing a "name" property`);continue}if(n.has(o)&&t.push(`${e}: Duplicate field name "${o}"`),n.add(o),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(o)||t.push(`${e}: Field name "${o}" must be alphanumeric with underscores`),!i.type){t.push(`${e}: Field "${o}" is missing a "type" property`);continue}switch(i.type){case "relationship":i.relationTo||t.push(`${e}: Relationship field "${o}" is missing "relationTo"`);break;case "array":if(!i.fields||i.fields.length===0)t.push(`${e}: Array field "${o}" has no fields defined`);else {let r=N(i.fields,`${e}.${o}`);t.push(...r);}break;case "group":if(!i.fields||i.fields.length===0)t.push(`${e}: Group field "${o}" has no fields defined`);else {let r=N(i.fields,`${e}.${o}`);t.push(...r);}break;case "blocks":if(!i.blocks||i.blocks.length===0)t.push(`${e}: Blocks field "${o}" has no blocks defined`);else {let r=Ie(i.blocks,`${e}.${o}`);t.push(...r);}break;case "select":case "radio":if(typeof i.options=="function")break;if((!i.options||i.options.length===0)&&!i.dynamicOptions)t.push(`${e}: ${i.type} field "${o}" has no options defined`);else if(Array.isArray(i.options)){let r=i.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${i.type} field "${o}" has duplicate option values`);}break;case "upload":i.relationTo||t.push(`${e}: Upload field "${o}" is missing "relationTo"`);break}"min"in i&&"max"in i&&i.min>i.max&&t.push(`${e}: Field "${o}" has min greater than max`),"minLength"in i&&"maxLength"in i&&i.minLength>i.maxLength&&t.push(`${e}: Field "${o}" has minLength greater than maxLength`),"minRows"in i&&"maxRows"in i&&i.minRows>i.maxRows&&t.push(`${e}: Field "${o}" has minRows greater than maxRows`);}return t}function Ie(s,e){let t=[],n=new Set;for(let a of s){if(!a.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(a.slug)&&t.push(`${e}: Duplicate block slug "${a.slug}"`),n.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 i=N(a.fields,`${e}.${a.slug}`);t.push(...i);}}return t}function fe(s,e=[]){let t=[],n=new Set;for(let a of s)n.has(a.slug)&&t.push(`Duplicate collection slug "${a.slug}"`),n.add(a.slug);for(let a of e)n.has(a.slug)&&t.push(`Duplicate global slug "${a.slug}"`),n.add(a.slug);for(let a of s){let i=V(a);t.push(...i);}for(let a of e){let i=B(a);t.push(...i);}for(let a of s){let i=$(a.fields,s);t.push(...i);}if(t.length>0)throw new K(t)}function $(s,e){let t=[],n=new Set(e.map(a=>a.slug));for(let a of s){if(a.type==="relationship"){let i=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let o of i)n.has(o)||console.warn(`[Kyro Config Warning]: Relationship field "${a.name}" references unknown collection "${o}". Select options will not be available until this collection is registered.`);}if(a.type==="upload"){let i=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let o of i)n.has(o)||t.push(`Upload field "${a.name}" references unknown collection "${o}"`);}if("fields"in a&&a.fields){let i=$(a.fields,e);t.push(...i);}if("tabs"in a)for(let i of a.tabs){let o=$(i.fields,e);t.push(...o);}if("blocks"in a)for(let i of a.blocks){let o=$(i.fields,e);t.push(...o);}}return t}function C(s){switch(s.type){case "text":return $e(s);case "number":return Oe(s);case "checkbox":return Pe(s);case "date":return Le(s);case "email":return ke(s);case "password":return _e(s);case "textarea":return je(s);case "select":return Ze(s);case "radio":return qe(s);case "color":return Ue(s);case "richtext":return Ge(s);case "json":return Ke(s);case "code":return Ve(s);case "upload":return ye(s);case "image":return ye(s);case "markdown":return Be(s);case "relationship":return he(s);case "relationship-block":return he(s);case "array":return Me(s);case "list":return ze(s);case "group":return We(s);case "blocks":return Xe(s);case "row":return Je(s);case "collapsible":return He(s);case "tabs":return Ye(s);default:return zod.z.any()}}function $e(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.pattern&&(e=e.regex(new RegExp(s.pattern))),s.variant==="email"&&(e=e.email()),s.variant==="url"&&(e=e.url()),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Oe(s){let e=s.integer?zod.z.coerce.number().int():zod.z.coerce.number();return s.min!==void 0&&(e=e.min(s.min)),s.max!==void 0&&(e=e.max(s.max)),s.step&&(e=e.refine(t=>Number.isInteger(t/s.step),`Value must be divisible by ${s.step}`)),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Pe(s){let e=zod.z.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Le(s){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return s.minDate&&(e=e.refine(t=>new Date(t)>=new Date(s.minDate),`Date must be after ${s.minDate}`)),s.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(s.maxDate),`Date must be before ${s.maxDate}`)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ke(s){let e=zod.z.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function _e(s){let e=zod.z.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function je(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ze(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);s.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=s.hasMany?zod.z.array(zod.z.string()):zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function qe(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);e=zod.z.enum(t);}else e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ue(s){let e=zod.z.string();return s.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),s.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),s.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ge(s){let e=zod.z.array(zod.z.record(zod.z.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ke(s){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ve(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ye(s){let e;if(s.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Be(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function he(s){let e;return Array.isArray(s.relationTo)?e=zod.z.object({relationTo:zod.z.enum(s.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Me(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,C(n)]))).passthrough(),t=zod.z.array(e);return s.minRows&&(t=t.min(s.minRows)),s.maxRows&&(t=t.max(s.maxRows)),s.required||(t=t.optional().nullable()),s.validate&&(t=T(t,s.validate)),t}function ze(s){let e=zod.z.array(zod.z.string());return s.required||(e=e.optional().nullable()),e}function We(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])));return s.required?e:e.optional().nullable()}function Xe(s){let e=s.blocks||[];e.map(i=>zod.z.object({blockType:zod.z.literal(i.slug),...Object.fromEntries(i.fields.filter(o=>o.name).map(o=>[o.name,C(o)]))}));let n=e.map(i=>i.slug),a;if(n.length>0){let i=zod.z.object({blockType:zod.z.enum(n)}).catchall(zod.z.any()),o=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());a=zod.z.array(zod.z.union([i,o,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 s.minRows&&(a=a.min(s.minRows)),s.maxRows&&(a=a.max(s.maxRows)),s.required||(a=a.optional().nullable()),s.validate&&(a=T(a,s.validate)),a}function Je(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function He(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function Ye(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=C(n));return zod.z.object(e).passthrough().optional()}function T(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function R(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let i=R(a.fields);Object.assign(n,i);}e[t.name]=zod.z.object(n).passthrough().optional();}else if(t.type==="row"&&"fields"in t){let n=R(t.fields);Object.assign(e,n);}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(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let i=E(a.fields);Object.assign(n,i);}e[t.name]=zod.z.object(n).passthrough().optional().nullable();}else if(t.type==="row"&&"fields"in t){let n=E(t.fields);Object.assign(e,n);}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 ge(s){let e=R(s.fields);return s.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),s.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function me(s){let e=R(s.fields);return zod.z.object(e).passthrough()}function be(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let i of a.fields)i.name&&(n[i.name]=C(i).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let a of t.fields)a.name&&(n[a.name]=C(a).optional().nullable());Object.assign(e,n);}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 Te(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Ae(s){let e=R(s.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ce(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let i of a.fields)i.name&&(n[i.name]=C(i).optional().nullable());e[t.name]=zod.z.object(n).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 D=class{storageProviders=chunk54B2Q567_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));if(t.seo){let a=chunkKD7LUCFY_cjs.a(),i=t.fields.find(o=>o.type==="tabs"&&o.name==="tabs");i&&i.tabs?i.tabs.push({label:"SEO Settings",fields:a.fields}):t.fields.push(a);}t.fields=this.applyFieldDefaults(t);let n=V(t);if(n.length>0)throw new Error(`Invalid collection config: ${n.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=B(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let a of this.plugins)a.extendGlobal&&(n=a.extendGlobal(n.slug,n));this.globals.set(n.slug,n),this.clearSchemaCache(`global:${n.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let n=this.collections.get(e);if(n){let i=ge(n);return this.schemaCache.set(e,i),i}let a=this.globals.get(e);if(a){let i=Ae(a);return this.schemaCache.set(`global:${e}`,i),i}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let i=me(a);return this.schemaCache.set(t,i),i}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let o=be(a);return this.schemaCache.set(t,o),o}let i=this.globals.get(e);if(i){let o=Ce(i);return this.schemaCache.set(`global:${e}:update`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let i=Te(a);return this.schemaCache.set(t,i),i}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(n=>n.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(n=>n.name==="tenantId")&&t.push({name:"tenantId",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(n=>n.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(n=>n.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(n=>n.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let n=this.globals.get(e);if(n)return n.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),n=new Map,a=i=>{for(let o of i){if(o.name&&n.set(o.name,o),"fields"in o&&o.fields&&a(o.fields),"tabs"in o)for(let r of o.tabs)a(r.fields);if("blocks"in o)for(let r of o.blocks)a(r.fields);}};return a(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();fe(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 n=this.collections.get(e)?.admin?.useAsTitle;return n||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(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 Qe(){return v||(v=new D),v}function et(){v=null;}function M(){return v=new D,v}var tt={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 st(s,e){switch(s){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Se(s,e){return {provider:s,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:st(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function nt(s,e,t){let n=t[e.configKey]||{};return Se(s,n)}function at(s,e,t){let n=t?.[e.configKey]||t;return Se(s,n)}var Ee={name:"@kyro-cms/storage-s3",version:"1.0.0",description:"S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)",init:s=>{let e=s.registry?.storageProviders;if(!e)return;let t="@kyro-cms/storage-s3";for(let n of Object.values(tt))e.register({type:n.type,displayName:n.displayName,pluginName:t,configKey:n.configKey,configFields:n.configFields,extractConfig:a=>nt(n.type,n,a),extractRawConfig:a=>at(n.type,n,a),factory:a=>chunk54B2Q567_cjs.a(a)});}};var xe={name:"@kyro-cms/storage-cloudinary",version:"1.0.0",description:"Cloudinary image and video storage",init:s=>{let e=s.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 n=t?.cloudinary||t;return {cloudName:n?.cloudName||"",apiKey:n?.apiKey||"",apiSecret:n?.apiSecret||"",folder:n?.folder,uploadPreset:n?.uploadPreset}},factory:t=>chunk54B2Q567_cjs.b(t)});}};var Ne={name:"@kyro-cms/storage-ftp",version:"1.0.0",description:"FTP/SFTP storage provider",init:s=>{let e=s.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 n=t?.ftp||t;return {host:n?.host||"",port:n?.port||21,user:n?.user||"",password:n?.password||"",secure:n?.secure||false,baseUrl:n?.baseUrl||"",prefix:n?.prefix,type:"ftp"}},factory:t=>chunk54B2Q567_cjs.c(t)});}};var ot=[Ee,xe,Ne];function z(s,e,t){let n=e.split(".");if(n.length===0)return false;let a=n[0],i=n.slice(1).join(".");for(let o of s)if(o.name===a)return i?o.fields&&Array.isArray(o.fields)||o.type==="array"&&o.fields&&Array.isArray(o.fields)?z(o.fields,i,t):false:(Object.assign(o,t),true);return false}function rt(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:a,...i}=n;if(t.admin={...t.admin,...i},a&&t.fields&&Array.isArray(t.fields))for(let[o,r]of Object.entries(a))z(t.fields,o,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 chunkG3J2EU5D_cjs.b(this.registry),this.webhookService=chunkWE46GGL4_cjs.o(this.db);for(let t of ot)this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&rt(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"}]},n={slug:chunkWE46GGL4_cjs.f,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},a={slug:chunkWE46GGL4_cjs.g,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"}]},i=this.registry.getGlobals();if(this.db instanceof chunkZ7CNY2UV_cjs.c&&this.db.dialect==="postgres"){let o=this.db,r=chunkNY47CFVP_cjs.d.replace(/-/g,"_");o.schema[r]||(o.schema[r]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,n,a],i),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),n={};try{let a=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});a&&a.states&&(n=a.states);}catch{}for(let a of t)n[a]!==void 0&&e.setPluginEnabled(a,n[a]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,a=t?.checkSession!==false;return chunk54B2Q567_cjs.s({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:a,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkHS2KNFAB_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:a})=>{let i=chunkNY47CFVP_cjs.f(a),o,r;if(i&&this.db){let d=await chunkNY47CFVP_cjs.e(i,this.db);d.user&&(o=d.user,r=chunkNY47CFVP_cjs.g(d));}let c=e?.tenantId;return {db:this.db,registry:this.registry,user:o,req:a,tenantId:c,apiKey:r,relationLoader:new chunkHS2KNFAB_cjs.a({db:this.db,tenantId:c,user:o})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let i=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[o,...r]=i.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!o||!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 chunkER2PUSHG_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),p=chunkER2PUSHG_cjs.i(d)[o];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${o}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let m=p[c];if(typeof m!="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 y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let A=new URL(t.url).searchParams.get("input");if(A)try{y=JSON.parse(decodeURIComponent(A));}catch{}}let h=y?.["0"]??y,f=await m({...h,collection:o});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let h=y.message||"Internal error",f=h.includes("not found")?404:h.includes("denied")||h.includes("authentication required")?403:h.includes("conflict")?409:500,A=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:h,code:A,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let n=async a=>{let i=await chunkNY47CFVP_cjs.e(a,this.db);if(!i.valid)throw new Error(i.error||"Invalid API key");if(!i.user)throw new Error("API key has no associated user");return i.user};return this.wsServer=chunkG3J2EU5D_cjs.d({pubsub:this.pubsub,port:e?.port||8080,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||n}),this.wsServer}async shutdown(){this.wsServer&&await this.wsServer.close(),await this.db.disconnect();}};function Ht(s){return new W(s)}var ct=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-32GUKU7D.cjs', document.baseURI).href))),dt="node:sqlite",{DatabaseSync:ut}=ct(dt);function x(s){let e=[];for(let t of s)if(t.type==="tabs"&&"tabs"in t)for(let n of t.tabs)e.push(...x(n.fields));else t.type==="row"&&"fields"in t?e.push(...x(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...x(t.fields)):e.push(t);return e}function ft(s,e){let t=e,n=s[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{n=n?JSON.parse(n):null;}catch{n=null;}if(t.type==="checkbox"&&(n=!!n),t.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((t.type==="upload"||t.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(i=>typeof i=="object"&&i!==null?i:{id:i}):n=typeof a=="object"?a:{id:a};}catch{n={id:n};}if(t.type==="relationship"&&n)try{let a=JSON.parse(n);Array.isArray(a),n=a;}catch{n={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:n};}if(t.type==="list"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}if(t.type==="relationship-block"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}return n}function Re(s,e){return Array.isArray(s)?s.map(t=>{if(!t||typeof t!="object")return t;let n=t.data?{...t.data}:void 0;if(!n)return t;let a=e.find(i=>i.slug===t.type||i.slug===t.slug);if(!a||!Array.isArray(a.fields))return t;for(let i of a.fields){if(i.name&&(i.type==="upload"||i.type==="image")&&n[i.name]){let o=n[i.name];Array.isArray(o)?n[i.name]=o.map(r=>typeof r=="string"?{id:r}:r):typeof o=="string"&&(n[i.name]={id:o});}if(i.type==="blocks"&&i.name&&n[i.name]){let o=i.blocks||[];n[i.name]=Re(n[i.name],o);}}return {...t,data:n}}):s}function X(s,e){try{return s.prepare(`PRAGMA table_info(${e})`).all().map(n=>n.name)}catch{return []}}var J=class extends chunkEJDIR56C_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 ut(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=n=>{let a=e(n),i=o=>typeof o=="boolean"?o?1:0:o===void 0?null:o;return new Proxy(a,{get(o,r,c){if(r==="all")return (...u)=>o.all(...u.map(i));if(r==="get")return (...u)=>o.get(...u.map(i));if(r==="run")return (...u)=>o.run(...u.map(i));let d=Reflect.get(o,r,c);return typeof d=="function"?d.bind(o):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 n=t||this.getTableNameFor(e.slug),a=["id TEXT PRIMARY KEY"];for(let r of x(e.fields)){if(!r.name||r.name==="id")continue;let c=this.fieldToSQL(r);c&&a.push(c);}let i=x(e.fields);i.some(r=>r.name==="createdAt")||a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),i.some(r=>r.name==="updatedAt")||a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),i.some(r=>r.name==="status")||a.push("status TEXT DEFAULT 'draft'"),i.some(r=>r.name==="hasDraft")||a.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let o=X(this.db,n);if(o.length===0){let r=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(r),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let c of x(e.fields))c.name&&c.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${c.name} ON ${n}(${this.col(c.name)})`),c.name&&c.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${c.name}_unique ON ${n}(${this.col(c.name)})`);}else {let r=new Set(o);for(let c of a){let d=c.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!r.has(d)&&d!=="id")try{d==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} TEXT DEFAULT 'published'`):d==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} TEXT`);}catch{}}}this.migrations.set(n,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,
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import {a,c,b,d}from'./chunk-TQNM4C7H.js';import {sql,eq,desc,and,or,ne,inArray,like,gt,gte,lt,lte}from'drizzle-orm';import {text,uuid,jsonb,timestamp,boolean,decimal,integer as integer$1,varchar,pgTable}from'drizzle-orm/pg-core';import {text as text$1,integer,numeric,sqliteTable}from'drizzle-orm/sqlite-core';import {drizzle}from'drizzle-orm/postgres-js';import ce from'postgres';import {randomBytes}from'crypto';import {mkdir}from'fs/promises';import {resolve,dirname}from'path';import {createRequire}from'module';var P=false;function _(f){if(typeof f!="string")return f;let a=f.replace(/-/g,"").toLowerCase();return a.length===32?`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`:f}function L(f,a="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return a==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return a==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return a==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function De(f,a="postgres"){let n=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${n} = pgTable('${n}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let t of f.fields){if(t.name==="id")continue;let i=L(t,a),r=t.required,s=` ${t.name}: pg.${i}('${t.name}')`;t.unique&&(s+=".unique()"),r||(s+=".nullable()"),t.defaultValue!==void 0&&(typeof t.defaultValue=="string"?s+=`.default('${t.defaultValue}')`:typeof t.defaultValue=="boolean"?s+=`.default(${t.defaultValue})`:s+=`.default(sql\`${JSON.stringify(t.defaultValue)}\`)`),s+=",",e.push(s);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${a==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${a==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
|
|
2
|
+
`)}function j(f,a){return Array.isArray(f)?f.map(n=>{if(!n||typeof n!="object")return n;let e=n.data?{...n.data}:void 0;if(!e)return n;let t=a.find(i=>i.slug===n.type||i.slug===n.slug);if(!t||!Array.isArray(t.fields))return n;for(let i of t.fields){if(i.name&&(i.type==="upload"||i.type==="image")&&e[i.name]){let r=e[i.name];Array.isArray(r)?e[i.name]=r.map(s=>typeof s=="string"?{id:s}:s):typeof r=="string"&&(e[i.name]={id:r});}if(i.type==="blocks"&&i.name&&e[i.name]){let r=i.blocks||[];e[i.name]=j(e[i.name],r);}}return {...n,data:e}}):f}var x=class extends a{client;schema;dialect;connectionString;versionsTableReady=false;constructor(a){if(super(),this.schema=a.schema||{},a.connectionString){this.connectionString=a.connectionString;let n=a.connectionString.toLowerCase();n.startsWith("postgres://")||n.startsWith("postgresql://")?this.dialect="postgres":n.includes(".db")||n.includes("sqlite")||n.includes("file:")?this.dialect="sqlite":this.dialect=a.type||"postgres";}else this.client=a.client,this.dialect=a.type||"sqlite";}prepareData(a,n){let e=super.prepareData(a,n);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of n.fields)if(t.type==="date"&&t.name){let i=e[t.name];i&&typeof i=="string"&&(e[t.name]=new Date(i));}for(let t of n.fields){let r=L(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let s=a[t.name];if(s&&typeof s=="object"){let o={};for(let[c,u]of Object.entries(s)){let l=t.tabs.flatMap(y=>y.fields).find(y=>y.name===c);(l?.type==="upload"||l?.type==="image"||l?.type==="list"||l?.type==="relationship-block")&&u?o[c]=Array.isArray(u)||typeof u=="object"?JSON.stringify(u):u:o[c]=u;}e[t.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&t.name&&a[t.name]!==void 0&&a[t.name]!==null)e[t.name]=this.dialect==="sqlite"?JSON.stringify(a[t.name]):a[t.name];else if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let s=a[t.name];s!=null&&(e[t.name]=this.dialect==="sqlite"||!r?typeof s=="string"?s:JSON.stringify(s):s);}}for(let t of n.fields)if(t.name&&e[t.name]===""){let i=L(t,this.dialect);(i==="timestamp"||i==="jsonb"||i==="decimal"||i==="integer"||i==="numeric"||i==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let{default:a}=await import('postgres'),{drizzle:n}=await import('drizzle-orm/postgres-js'),e=a(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let{default:a}=await import('better-sqlite3'),{drizzle:n}=await import('drizzle-orm/better-sqlite3'),e=new a(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}this.connected=true;}async init(a,n=[]){if(await super.init(a,n),this.connectionString&&!this.client&&await this.connect(),this.client&&!P){for(let t of a){let i=this.getTableName(t.slug);this.schema[i]||(this.schema[i]=this.createTableFromConfig(t));}await this.ensureCollectionTables(a);let e=n.map(t=>({slug:`_globals_${t.slug}`,fields:t.fields,label:t.label}));for(let t of e){let i=this.getTableName(t.slug);this.schema[i]||(this.schema[i]=this.createTableFromConfig(t,true)),this.collections.has(t.slug)||this.collections.set(t.slug,t);}await this.ensureCollectionTables(e),P=true;}}createTableFromConfig(a,n=false){let e=this.getTableName(a.slug),t={id:n?text("id").primaryKey():uuid("id").primaryKey().defaultRandom()};for(let i of a.fields){if(!i.name||i.name==="id")continue;let r=L(i,this.dialect),s=i.name.replace(/-/g,"_"),o=s.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=text$1(o);break;case "integer":c=integer(o);break;case "decimal":case "numeric":c=numeric(o);break;case "boolean":c=integer(o,{mode:"boolean"});break;case "timestamp":c=text$1(o);break;case "jsonb":c=text$1(o);break;default:c=text$1(o);}else switch(r){case "varchar":c=varchar(o,{length:255});break;case "integer":c=integer$1(o);break;case "decimal":c=decimal(o);break;case "boolean":c=boolean(o);break;case "timestamp":c=timestamp(o);break;case "jsonb":c=jsonb(o);break;default:c=text(o);}i.required||(c=c.default(null)),t[s]=c;}return t.createdAt||(t.createdAt=this.dialect==="sqlite"?text$1("created_at").default(new Date().toISOString()):timestamp("created_at").defaultNow()),t.updatedAt||(t.updatedAt=this.dialect==="sqlite"?text$1("updated_at").default(new Date().toISOString()):timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(t.status||(t.status=this.dialect==="sqlite"?text$1("status").default("draft"):varchar("status",{length:20}).default("draft")),t.hasDraft||(t.hasDraft=this.dialect==="sqlite"?integer("hasDraft",{mode:"boolean"}).default(false):boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteTable(e,t):pgTable(e,t)}async ensureCollectionTables(a){let n=[];for(let e of a){let t=e.slug.startsWith("_globals_"),i=this.getTableName(e.slug),r=this.generateCreateColumns(e),s=e.fields.some(l=>l.name==="createdAt"),o=e.fields.some(l=>l.name==="updatedAt"),c=e.fields.some(l=>l.name==="status"),u=e.fields.some(l=>l.name==="hasDraft");if(this.dialect==="postgres"){let l=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS "${i}" (
|
|
4
|
+
${l},
|
|
5
|
+
${r}
|
|
6
|
+
${s?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
7
|
+
${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
8
|
+
${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
|
|
9
|
+
${u?"":'"hasDraft" BOOLEAN DEFAULT false'}
|
|
10
|
+
)
|
|
11
|
+
`);}else n.push(`
|
|
12
|
+
CREATE TABLE IF NOT EXISTS "${i}" (
|
|
13
|
+
"id" TEXT PRIMARY KEY,
|
|
14
|
+
${r}
|
|
15
|
+
${s?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
16
|
+
${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
17
|
+
${c?"":`"status" TEXT DEFAULT 'draft',`}
|
|
18
|
+
${u?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
19
|
+
)
|
|
20
|
+
`);}if(n.length>0)if(this.dialect==="postgres")await this.client.execute(sql.raw(n.join(`;
|
|
21
|
+
`)));else for(let e of n)await this.client.execute(sql.raw(e));for(let e of a){let t=this.getTableName(e.slug);t==="users"||t==="audit_logs"||await this.syncTableColumns(e,t);}}getColumnSqlDefinition(a,n){let e=L(a,n),t=a.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),i=this.columnSqlType(e,n);return `"${t}" ${i} DEFAULT NULL`}columnSqlType(a,n){if(n==="sqlite")switch(a){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(a){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(a,n){let e={},t=a.slug.startsWith("_globals_"),i=a.fields.some(c=>c.name==="createdAt"),r=a.fields.some(c=>c.name==="updatedAt"),s=a.fields.some(c=>c.name==="status"),o=a.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',i||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),s||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',i||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),s||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of a.fields){if(!c.name||c.name==="id")continue;let u=this.getColumnSqlDefinition(c,this.dialect),l=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[l]=u;}return e}async syncTableColumns(a,n){let e;try{if(this.dialect==="postgres"){let r=await this.client.execute(sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${n}`);e=new Map(r.map(s=>[s.column_name,{type:s.data_type,maxLen:s.character_maximum_length}]));}else {let r=await this.client.execute(sql`PRAGMA table_info("${sql.raw(n)}")`);e=new Map(r.map(s=>[s.name,{type:s.type,maxLen:null}]));}}catch{return}let t=this.getExpectedColumnDefs(a,n),i=Object.keys(t).filter(r=>!e.has(r));if(i.length>0){let r=i.map(s=>`ALTER TABLE "${n}" ADD COLUMN ${t[s]}`);await this.executeRaw(sql.raw(r.join(`;
|
|
22
|
+
`)));}if(this.dialect==="postgres")for(let r of a.fields){if(!r.name||r.name==="id")continue;let s=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(s==="text"?await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${o}" TYPE TEXT`)):s==="jsonb"&&(await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(a){let n=[];for(let e of a.fields){if(!e.name||e.name==="id")continue;let t=L(e,this.dialect),i=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",s;if(this.dialect==="sqlite")switch(t){case "varchar":case "text":s=`TEXT ${r}`;break;case "integer":s=`INTEGER ${r}`;break;case "decimal":case "numeric":s=`NUMERIC ${r}`;break;case "boolean":s=`INTEGER ${r}`;break;case "timestamp":s=`TEXT ${r}`;break;case "jsonb":s=`TEXT ${r}`;break;default:s=`TEXT ${r}`;}else switch(t){case "varchar":s=`VARCHAR(255) ${r}`;break;case "integer":s=`INTEGER ${r}`;break;case "decimal":s=`DECIMAL ${r}`;break;case "boolean":s=`BOOLEAN ${r}`;break;case "timestamp":s=`TIMESTAMP ${r}`;break;case "jsonb":s=`JSONB ${r}`;break;default:s=`TEXT ${r}`;}n.push(`"${i}" ${s}`);}return n.join(`,
|
|
23
|
+
`)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(a){let{collection:n,where:e={},sort:t,limit:i=10,page:r=1,tenantId:s,select:o,draft:c$1}=a,u=this.getCollection(n),l=this.getTable(n),T={...e};this.tenantContext&&u.tenantScoped&&(T=c({where:T},n,this.tenantContext,b).where||{});let y=this.buildWhereClause(T,u,l,s),h=u.fields.find(m=>m.name==="status"),p=h?.type==="select"&&Array.isArray(h.options)&&h.options.some(m=>m.value==="published");!c$1&&l.status&&p&&y.push(eq(l.status,"published"));let A=this.parseSort(t),N=!c$1&&l.status&&p?{...T,status:"published"}:T,X=await this.count({collection:n,where:N,tenantId:s}),W=(r-1)*i,v=[];try{let m=l[A.field]||l.createdAt||l.id,R=A.direction==="asc"?m:desc(m),E=this.client.select().from(l);y.length>0&&(E=E.where(and(...y))),v=await E.orderBy(R).limit(i).offset(W);}catch(m){console.error("[DrizzleAdapter] Query error:",m);}let w=v.map(m=>this.processResult(m,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(w=w.filter(m=>d(m,n,this.tenantContext,b))),c$1&&(w=await Promise.all(w.map(async m=>{let R=await this.executeRaw(sql`
|
|
24
|
+
SELECT * FROM kyro_versions
|
|
25
|
+
WHERE collection_slug = ${n}
|
|
26
|
+
AND document_id = ${m.id}
|
|
27
|
+
ORDER BY created_at DESC
|
|
28
|
+
LIMIT 1
|
|
29
|
+
`);if(R.length>0){let E=R[0],V=typeof E.data=="string"?JSON.parse(E.data):E.data;return {...m,...V,status:m.status}}return m}))),{docs:w,...this.calculatePagination(r,i,X)}}async findByID(a){let{collection:n,id:e,tenantId:t,draft:i}=a,r=this.getCollection(n),s=this.getTable(n),o=this.dialect==="postgres"&&typeof e=="string"?_(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!d(p,n,this.tenantContext,b))return null}let c=[eq(s.id,o)];t&&s.tenantId&&c.push(eq(s.tenantId,t));let u=r.fields.find(p=>p.name==="status"),l=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!i&&s.status&&l&&c.push(eq(s.status,"published"));let T=c.length>1?and(...c):c[0],y=await this.client.select().from(s).where(T);if(y.length===0)return null;let h=this.processResult(y[0],r);if(i){let p=await this.executeRaw(sql`
|
|
30
|
+
SELECT * FROM kyro_versions
|
|
31
|
+
WHERE collection_slug = ${n}
|
|
32
|
+
AND document_id = ${h.id}
|
|
33
|
+
ORDER BY created_at DESC
|
|
34
|
+
LIMIT 1
|
|
35
|
+
`);if(p.length>0){let A=p[0],N=typeof A.data=="string"?JSON.parse(A.data):A.data;h={...h,...N,status:h.status};}}return h}async create(a){let{collection:n,data:e,tenantId:t}=a,i=this.getCollection(n),r=this.getTable(n),s=this.prepareData(e,i);t&&(s.tenantId=t);let o=await this.client.insert(r).values(s).returning();return this.processResult(o[0],i)}async update(a){let{collection:n,id:e,data:t,tenantId:i}=a,r=this.getCollection(n),s=this.getTable(n),o=this.prepareData(t,r),c=this.dialect==="postgres"&&typeof e=="string"?_(e):e,u=[eq(s.id,c)];i&&s.tenantId&&u.push(eq(s.tenantId,i));let l=await this.client.update(s).set(o).where(and(...u)).returning();if(l.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(l[0],r)}async delete(a){let{collection:n,id:e,tenantId:t}=a,i=this.getCollection(n),r=this.getTable(n),s=this.dialect==="postgres"&&typeof e=="string"?_(e):e,o=[eq(r.id,s)];t&&r.tenantId&&o.push(eq(r.tenantId,t));let c=await this.client.delete(r).where(and(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(c[0],i)}async count(a){let{collection:n,where:e={},tenantId:t}=a,i=this.getCollection(n),r=this.getTable(n),s=this.buildWhereClause(e,i,r,t);try{let o=this.client.select({count:sql`count(*)`}).from(r);s.length>0&&(o=o.where(and(...s)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(a){let{collection:n,where:e={},tenantId:t,draft:i}=a;if(n.startsWith("_globals_")){let s=n.replace("_globals_",""),o=this.globals.get(s);if(!o)throw new Error(`Global "${s}" not found`);let c=this.getTable(n),u=this.client.select().from(c),l=o.fields.find(p=>p.name==="status"),T=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(p=>p.value==="published");!i&&c.status&&T&&(u=u.where(eq(c.status,"published")));let y=await u.limit(1);if(y.length===0)return null;let h=this.processResult(y[0],o);if(i){let p=await this.executeRaw(sql`
|
|
36
|
+
SELECT * FROM kyro_versions
|
|
37
|
+
WHERE collection_slug = ${n}
|
|
38
|
+
AND document_id = ${s}
|
|
39
|
+
ORDER BY created_at DESC
|
|
40
|
+
LIMIT 1
|
|
41
|
+
`);if(p.length>0){let A=p[0],N=typeof A.data=="string"?JSON.parse(A.data):A.data;h={...h,...N,status:h.status};}}return h}return (await this.find({...a,limit:1})).docs[0]||null}async findVersions(a){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:t=10,page:i=1,tenantId:r}=a,s=(i-1)*t,o=await this.executeRaw(sql`
|
|
42
|
+
SELECT count(*) as count
|
|
43
|
+
FROM kyro_versions
|
|
44
|
+
WHERE collection_slug = ${n}
|
|
45
|
+
AND document_id = ${e}
|
|
46
|
+
AND autosave = 0
|
|
47
|
+
${r?sql`AND tenant_id = ${r}`:sql``}
|
|
48
|
+
`),c=parseInt(o[0]?.count||"0");return {docs:(await this.executeRaw(sql`
|
|
49
|
+
SELECT *
|
|
50
|
+
FROM kyro_versions
|
|
51
|
+
WHERE collection_slug = ${n}
|
|
52
|
+
AND document_id = ${e}
|
|
53
|
+
AND autosave = 0
|
|
54
|
+
${r?sql`AND tenant_id = ${r}`:sql``}
|
|
55
|
+
ORDER BY created_at DESC
|
|
56
|
+
LIMIT ${t}
|
|
57
|
+
OFFSET ${s}
|
|
58
|
+
`)).map(l=>({...l,data:typeof l.data=="string"?JSON.parse(l.data):l.data})),...this.calculatePagination(i,t,c)}}async findVersionByID(a){await this.ensureVersionsTable();let n=await this.executeRaw(sql`
|
|
59
|
+
SELECT * FROM kyro_versions
|
|
60
|
+
WHERE id = ${a.versionId}
|
|
61
|
+
AND collection_slug = ${a.collection}
|
|
62
|
+
${a.tenantId?sql`AND tenant_id = ${a.tenantId}`:sql``}
|
|
63
|
+
LIMIT 1
|
|
64
|
+
`);if(n.length===0)return null;let e=n[0];return {...e,data:typeof e.data=="string"?JSON.parse(e.data):e.data}}async createVersion(a){await this.ensureVersionsTable();let n=new Date().toISOString();if(a.autosave){let t=await this.executeRaw(sql`
|
|
65
|
+
SELECT * FROM kyro_versions
|
|
66
|
+
WHERE collection_slug = ${a.collection}
|
|
67
|
+
AND document_id = ${a.documentId}
|
|
68
|
+
AND autosave = 1
|
|
69
|
+
${a.tenantId?sql`AND tenant_id = ${a.tenantId}`:sql``}
|
|
70
|
+
LIMIT 1
|
|
71
|
+
`);if(t.length>0)return await this.executeRaw(sql`
|
|
72
|
+
UPDATE kyro_versions
|
|
73
|
+
SET data = ${JSON.stringify(a.data)},
|
|
74
|
+
status = ${a.status},
|
|
75
|
+
updated_at = ${n}
|
|
76
|
+
WHERE id = ${t[0].id}
|
|
77
|
+
`),this.findVersionByID({collection:a.collection,versionId:t[0].id,tenantId:a.tenantId})}let e=Math.random().toString(36).substring(2,15);if(await this.executeRaw(sql`
|
|
78
|
+
INSERT INTO kyro_versions (
|
|
79
|
+
id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
|
|
80
|
+
) VALUES (
|
|
81
|
+
${e}, ${a.collection}, ${a.documentId}, ${a.tenantId||null},
|
|
82
|
+
${JSON.stringify(a.data)}, ${a.status}, ${a.autosave?1:0}, ${a.createdBy||null},
|
|
83
|
+
${a.changeDescription||null}, ${n}, ${n}
|
|
84
|
+
)
|
|
85
|
+
`),!a.autosave){let t=this.getCollection(a.collection);t.versions?.maxPerDoc&&await this.deleteVersions({collection:a.collection,documentId:a.documentId,keepLatest:t.versions.maxPerDoc,tenantId:a.tenantId});}return this.findVersionByID({collection:a.collection,versionId:e,tenantId:a.tenantId})}async updateLatestVersion(a){return this.createVersion({...a,autosave:true})}async deleteVersions(a){if(await this.ensureVersionsTable(),a.keepLatest){let e=(await this.executeRaw(sql`
|
|
86
|
+
SELECT id FROM kyro_versions
|
|
87
|
+
WHERE collection_slug = ${a.collection}
|
|
88
|
+
AND document_id = ${a.documentId}
|
|
89
|
+
AND autosave = 0
|
|
90
|
+
${a.tenantId?sql`AND tenant_id = ${a.tenantId}`:sql``}
|
|
91
|
+
ORDER BY created_at DESC
|
|
92
|
+
LIMIT ${a.keepLatest}
|
|
93
|
+
`)).map(t=>t.id);e.length>0&&await this.executeRaw(sql`
|
|
94
|
+
DELETE FROM kyro_versions
|
|
95
|
+
WHERE collection_slug = ${a.collection}
|
|
96
|
+
AND document_id = ${a.documentId}
|
|
97
|
+
AND autosave = 0
|
|
98
|
+
AND id NOT IN (${sql.join(e.map(t=>sql`${t}`),sql`, `)})
|
|
99
|
+
`);}else await this.executeRaw(sql`
|
|
100
|
+
DELETE FROM kyro_versions
|
|
101
|
+
WHERE collection_slug = ${a.collection}
|
|
102
|
+
AND document_id = ${a.documentId}
|
|
103
|
+
${a.tenantId?sql`AND tenant_id = ${a.tenantId}`:sql``}
|
|
104
|
+
`);}getTable(a){let n=this.getTableName(a),e=this.schema[n];if(!e)throw new Error(`Table "${n}" not found in schema`);return e}buildWhereClause(a,n,e,t){let i=[];t&&n.tenantScoped&&e.tenantId&&i.push(eq(e.tenantId,t));for(let[r,s]of Object.entries(a))if(r==="id"&&this.dialect==="postgres"&&(typeof s=="string"?s=_(s):s&&typeof s=="object"&&(s.equals!==void 0&&typeof s.equals=="string"&&(s={...s,equals:_(s.equals)}),s.in&&Array.isArray(s.in)&&(s={...s,in:s.in.map(o=>typeof o=="string"?_(o):o)}))),r==="AND"&&Array.isArray(s)){let o=s.map(c=>this.buildWhereClause(c,n,e)).flat().filter(Boolean);o.length>0&&i.push(and(...o));}else if(r==="OR"&&Array.isArray(s)){let o=s.map(c=>this.buildWhereClause(c,n,e)).flat().filter(Boolean);o.length>0&&i.push(or(...o));}else if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let o=e[r];if(!o)continue;s.equals!==void 0&&i.push(eq(o,s.equals)),s.not_equals!==void 0&&i.push(ne(o,s.not_equals)),s.in&&Array.isArray(s.in)&&i.push(inArray(o,s.in)),s.like!==void 0&&i.push(like(o,s.like)),s.contains!==void 0&&i.push(like(o,`%${s.contains}%`)),s.greater_than!==void 0&&i.push(gt(o,s.greater_than)),s.greater_than_equal!==void 0&&i.push(gte(o,s.greater_than_equal)),s.less_than!==void 0&&i.push(lt(o,s.less_than)),s.less_than_equal!==void 0&&i.push(lte(o,s.less_than_equal));}else {let o=e[r];o&&i.push(eq(o,s));}return i}processResult(a,n){if(!a)return null;let e={...a};a.id&&(e.id=String(a.id));for(let t of n.fields){if(!t.name)continue;let i=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();i!==t.name&&e[i]!==void 0&&e[t.name]===void 0&&(e[t.name]=e[i],delete e[i]);}for(let t of n.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(t.type)){let i=t;if(e[i.name]&&typeof e[i.name]=="string")try{let r=JSON.parse(e[i.name]);e[i.name]=r;}catch{}if(t.type==="blocks"&&e[i.name]&&Array.isArray(e[i.name])){let r=i.blocks||[];e[i.name]=j(e[i.name],r);}}if(t.type==="tabs"&&"tabs"in t&&t.name){if(typeof e[t.name]=="object"&&e[t.name]!==null&&!Array.isArray(e[t.name])){for(let r of t.tabs)for(let s of r.fields)if((s.type==="upload"||s.type==="image")&&s.name){let o=e[t.name][s.name];if(typeof o=="string")try{let c=JSON.parse(o);e[t.name][s.name]=Array.isArray(c)?c.map(u=>u&&typeof u=="object"&&typeof u.id=="string"?u.id:String(u||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else o&&typeof o=="object"&&(e[t.name][s.name]=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[t.name]=="string")try{let r=JSON.parse(e[t.name]);if(typeof r=="object"&&r!==null){e[t.name]=r;continue}}catch{}let i={};for(let r of t.tabs)for(let s of r.fields)if(s.name&&e[s.name]!==void 0){let o=e[s.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(s.type==="upload"||s.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}i[s.name]=o,delete e[s.name];}e[t.name]=i;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),e}async ensureVersionsTable(){if(this.versionsTableReady)return;let a;this.dialect==="sqlite"?a=`
|
|
105
|
+
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
106
|
+
id text PRIMARY KEY,
|
|
107
|
+
collection_slug text NOT NULL,
|
|
108
|
+
document_id text NOT NULL,
|
|
109
|
+
tenant_id text,
|
|
110
|
+
data text NOT NULL,
|
|
111
|
+
status text NOT NULL DEFAULT 'draft',
|
|
112
|
+
autosave integer NOT NULL DEFAULT 0,
|
|
113
|
+
created_by text,
|
|
114
|
+
change_description text,
|
|
115
|
+
created_at text DEFAULT (datetime('now')),
|
|
116
|
+
updated_at text DEFAULT (datetime('now'))
|
|
117
|
+
)
|
|
118
|
+
`:a=`
|
|
119
|
+
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
120
|
+
id text PRIMARY KEY,
|
|
121
|
+
collection_slug text NOT NULL,
|
|
122
|
+
document_id text NOT NULL,
|
|
123
|
+
tenant_id text,
|
|
124
|
+
data text NOT NULL,
|
|
125
|
+
status text NOT NULL,
|
|
126
|
+
autosave integer NOT NULL DEFAULT 0,
|
|
127
|
+
created_by text,
|
|
128
|
+
change_description text,
|
|
129
|
+
created_at text NOT NULL,
|
|
130
|
+
updated_at text NOT NULL
|
|
131
|
+
)
|
|
132
|
+
`,await this.executeRaw(sql.raw(a));try{this.dialect==="postgres"?await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(a){let n=await this.client.execute(a);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}};function _e(f){return new x(f)}var me=createRequire(import.meta.url),he="node:sqlite",{DatabaseSync:ye}=me(he);function ge(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function B(){return randomBytes(16).toString("hex")}async function xe(){let f=ge();if(f==="sqlite"){let r=resolve(process.cwd(),"data","kyro.db");await mkdir(dirname(r),{recursive:true});let s=new ye(r);return s.exec("PRAGMA journal_mode = WAL"),{db:s,dialect:f,genId:B}}let a=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",n=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",t=ce(a,{max:n,ssl:e?"require":false,onnotice:()=>{}});return {db:drizzle(t),dialect:f,genId:B}}async function ve(f,a){}async function Oe(f){let{roles:a}=await import('./schema-KFYUM674.js');await f.insert(a).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
|
|
133
|
+
export{L as a,De as b,x as c,_e as d,B as e,xe as f,ve as g,Oe as h};
|