@kyro-cms/core 0.13.8 → 0.13.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +1 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +1 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/chunk-7QZYK4MT.cjs +132 -0
- package/dist/{chunk-PPGZHOYR.cjs → chunk-CXQ2AC27.cjs} +1 -1
- package/dist/{chunk-SYE3OS5T.js → chunk-FKJ7AX37.js} +1 -1
- package/dist/{chunk-MCK2QRAU.cjs → chunk-HUZ3P5OC.cjs} +2 -2
- package/dist/chunk-PMO2O77B.js +133 -0
- package/dist/{chunk-TVWHTVLI.js → chunk-VBSM5DZ5.js} +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-GWUHIIPO.cjs +0 -132
- package/dist/chunk-TJ6N5ZPZ.js +0 -133
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var chunkN7CDHWQH_cjs=require('./chunk-N7CDHWQH.cjs'),chunkDCKJT247_cjs=require('./chunk-DCKJT247.cjs'),chunk7KTPBTH5_cjs=require('./chunk-7KTPBTH5.cjs'),chunk24W5I6SJ_cjs=require('./chunk-24W5I6SJ.cjs'),chunkO2SA56P2_cjs=require('./chunk-O2SA56P2.cjs'),chunkOJBL4CXK_cjs=require('./chunk-OJBL4CXK.cjs'),chunkDCFOVCJX_cjs=require('./chunk-DCFOVCJX.cjs'),chunkFU76HURF_cjs=require('./chunk-FU76HURF.cjs'),
|
|
1
|
+
'use strict';var chunkN7CDHWQH_cjs=require('./chunk-N7CDHWQH.cjs'),chunkDCKJT247_cjs=require('./chunk-DCKJT247.cjs'),chunk7KTPBTH5_cjs=require('./chunk-7KTPBTH5.cjs'),chunk24W5I6SJ_cjs=require('./chunk-24W5I6SJ.cjs'),chunkO2SA56P2_cjs=require('./chunk-O2SA56P2.cjs'),chunkOJBL4CXK_cjs=require('./chunk-OJBL4CXK.cjs'),chunkDCFOVCJX_cjs=require('./chunk-DCFOVCJX.cjs'),chunkFU76HURF_cjs=require('./chunk-FU76HURF.cjs'),chunk7QZYK4MT_cjs=require('./chunk-7QZYK4MT.cjs'),chunk23RSKVJP_cjs=require('./chunk-23RSKVJP.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga');function P(s,e){for(let t of s){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let n of t.tabs)if(P(n.fields,e))return true}if("fields"in t&&t.fields&&P(t.fields,e))return true}return false}var G=class extends Error{errors;constructor(e){super(`Configuration validation failed:
|
|
2
2
|
${e.join(`
|
|
3
|
-
`)}`),this.name="ConfigValidationError",this.errors=e;}};function N(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Collection slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Collection "${s.slug}" has no fields defined`);else {let t=k(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,n]of Object.entries(s.access))typeof n!="boolean"&&typeof n!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(P(s.fields,s.admin.useAsTitle)||e.push(`Collection "${s.slug}" admin.useAsTitle references unknown field "${s.admin.useAsTitle}"`)),s.admin?.defaultColumns)for(let t of s.admin.defaultColumns)P(s.fields,t)||e.push(`Collection "${s.slug}" admin.defaultColumns references unknown field "${t}"`);if(s.upload&&s.upload.fileSize&&s.upload.fileSize<=0&&e.push(`Collection "${s.slug}" upload.fileSize must be positive`),s.versions&&s.versions.maxPerDoc&&s.versions.maxPerDoc<=0&&e.push(`Collection "${s.slug}" versions.maxPerDoc must be positive`),s.auth){let t=s.fields.some(i=>i.name==="email"),n=s.fields.some(i=>i.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),n||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function _(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Global slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Global "${s.slug}" has no fields defined`);else {let t=k(s.fields,`global:${s.slug}`);e.push(...t);}return e}function k(s,e){let t=[],n=new Set;for(let i=0;i<s.length;i++){let o=s[i];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let c=k(o.fields,e);t.push(...c);}else if("tabs"in o)for(let c of o.tabs){let l=k(c.fields,e);t.push(...l);}continue}let r=o.name;if(!r){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(n.has(r)&&t.push(`${e}: Duplicate field name "${r}"`),n.add(r),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r)||t.push(`${e}: Field name "${r}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${r}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${r}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${r}" has no blocks defined`);else {let c=Ie(o.blocks,`${e}.${r}`);t.push(...c);}break;case "select":case "radio":if(typeof o.options=="function")break;if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${r}" has no options defined`);else if(Array.isArray(o.options)){let c=o.options.map(u=>typeof u=="object"&&u!==null&&"value"in u?u.value:u),l=new Set(c);c.length!==l.size&&t.push(`${e}: ${o.type} field "${r}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${r}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${r}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${r}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${r}" has minRows greater than maxRows`);}return t}function Ie(s,e){let t=[],n=new Set;for(let i of s){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),n.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let o=k(i.fields,`${e}.${i.slug}`);t.push(...o);}}return t}function be(s,e=[]){let t=[],n=new Set;for(let i of s)n.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),n.add(i.slug);for(let i of e)n.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),n.add(i.slug);for(let i of s){let o=N(i);t.push(...o);}for(let i of e){let o=_(i);t.push(...o);}for(let i of s){let o=F(i.fields,s);t.push(...o);}if(t.length>0)throw new G(t)}function F(s,e){let t=[],n=new Set(e.map(i=>i.slug));for(let i of s){if(i.type==="relationship"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)r!=="*"&&!n.has(r)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${r}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)n.has(r)||t.push(`Upload field "${i.name}" references unknown collection "${r}"`);}if("fields"in i&&i.fields){let o=F(i.fields,e);t.push(...o);}if("tabs"in i)for(let o of i.tabs){let r=F(o.fields,e);t.push(...r);}if("blocks"in i)for(let o of i.blocks){let r=F(o.fields,e);t.push(...r);}}return t}function y(s){switch(s.type){case "text":return qe(s);case "number":return Le(s);case "checkbox":return De(s);case "date":return Ge(s);case "email":return Ne(s);case "password":return _e(s);case "textarea":return Ue(s);case "select":return ze(s);case "radio":return He(s);case "color":return Me(s);case "richtext":return Be(s);case "json":return Ve(s);case "code":return We(s);case "upload":return ve(s);case "image":return ve(s);case "markdown":return Ye(s);case "relationship":return Ce(s);case "relationship-block":return Ce(s);case "array":return Je(s);case "list":return Qe(s);case "group":return Xe(s);case "blocks":return et(s);case "row":return tt(s);case "collapsible":return st(s);case "tabs":return it(s);default:return zod.z.any()}}function qe(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.pattern&&(e=e.regex(new RegExp(s.pattern))),s.variant==="email"&&(e=e.email()),s.variant==="url"&&(e=e.url()),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Le(s){let e=s.integer?zod.z.coerce.number().int():zod.z.coerce.number();return s.min!==void 0&&(e=e.min(s.min)),s.max!==void 0&&(e=e.max(s.max)),s.step&&(e=e.refine(t=>Number.isInteger(t/s.step),`Value must be divisible by ${s.step}`)),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function De(s){let e=zod.z.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ge(s){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return s.minDate&&(e=e.refine(t=>new Date(t)>=new Date(s.minDate),`Date must be after ${s.minDate}`)),s.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(s.maxDate),`Date must be before ${s.maxDate}`)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ne(s){let e=zod.z.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function _e(s){let e=zod.z.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ue(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function ze(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);s.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=s.hasMany?zod.z.array(zod.z.string()):zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function He(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);e=zod.z.enum(t);}else e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Me(s){let e=zod.z.string();return s.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),s.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),s.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Be(s){let e=zod.z.array(zod.z.record(zod.z.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ve(s){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function We(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function ve(s){let e;if(s.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ye(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ce(s){let e;return Array.isArray(s.relationTo)?e=zod.z.object({relationTo:zod.z.enum(s.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Je(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,y(n)]))).passthrough(),t=zod.z.array(e);return s.minRows&&(t=t.min(s.minRows)),s.maxRows&&(t=t.max(s.maxRows)),s.required||(t=t.optional().nullable()),s.validate&&(t=f(t,s.validate)),t}function Qe(s){let e=zod.z.array(zod.z.string());return s.required||(e=e.optional().nullable()),e}function Xe(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])));return s.required?e:e.optional().nullable()}function et(s){let e=s.blocks||[];e.map(o=>zod.z.object({blockType:zod.z.literal(o.slug),...Object.fromEntries(o.fields.filter(r=>r.name).map(r=>[r.name,y(r)]))}));let n=e.map(o=>o.slug),i;if(n.length>0){let o=zod.z.object({blockType:zod.z.enum(n)}).catchall(zod.z.any()),r=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());i=zod.z.array(zod.z.union([o,r,zod.z.record(zod.z.any())]));}else i=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return s.minRows&&(i=i.min(s.minRows)),s.maxRows&&(i=i.max(s.maxRows)),s.required||(i=i.optional().nullable()),s.validate&&(i=f(i,s.validate)),i}function tt(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function st(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function it(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=y(n));return zod.z.object(e).passthrough().optional()}function f(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function S(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=S(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else {if(!t.name)continue;e[t.name]=y(t);}return e}function A(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=A(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=zod.z.object(A(t.fields)).passthrough().optional().nullable():Object.assign(e,A(t.fields));else {if(!t.name)continue;e[t.name]=y(t).optional().nullable();}return e}function xe(s){let e=S(s.fields);return s.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),s.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ae(s){let e=S(s.fields);return zod.z.object(e).passthrough()}function we(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let i of t.fields)i.name&&(n[i.name]=y(i).optional().nullable());Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}function ke(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Se(s){let e=S(s.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Te(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}var R=class{storageProviders=chunkO2SA56P2_cjs.e();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e,fields:[...e.fields]};for(let i of this.plugins){let o=i.extensions?.collections?.find(r=>r.slug===t.slug);o&&(t={...t,...o.config,fields:[...t.fields,...o.config.fields||[]]});}if(t.seo){let i=chunkDCKJT247_cjs.a(),o=t.fields.findIndex(r=>r.type==="tabs");if(o!==-1){let r=t.fields[o];t.fields[o]={...r,tabs:[...r.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let n=N(t);if(n.length>0)throw new Error(`Invalid collection config: ${n.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=_(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let i of this.plugins){let o=i.extensions?.globals?.find(r=>r.slug===n.slug);o&&(n={...n,...o.config,fields:[...n.fields||[],...o.config.fields||[]]});}this.globals.set(n.slug,n),this.clearSchemaCache(`global:${n.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let n=this.collections.get(e);if(n){let o=xe(n);return this.schemaCache.set(e,o),o}let i=this.globals.get(e);if(i){let o=Se(i);return this.schemaCache.set(`global:${e}`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let o=Ae(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let r=we(i);return this.schemaCache.set(t,r),r}let o=this.globals.get(e);if(o){let r=Te(o);return this.schemaCache.set(`global:${e}:update`,r),r}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let o=ke(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return y(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(n=>n.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(n=>n.name==="tenantId")&&t.push({name:"tenantId",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(n=>n.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(n=>n.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(n=>n.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let n=this.globals.get(e);if(n)return n.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),n=new Map,i=o=>{for(let r of o){if(r.name&&n.set(r.name,r),"fields"in r&&r.fields&&i(r.fields),"tabs"in r)for(let c of r.tabs)i(c.fields);if("blocks"in r)for(let c of r.blocks)i(c.fields);}};return i(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();be(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let n=t.collections||[];for(let o of n)o.slug&&!this.hasCollection(o.slug)&&this.addCollection(o);let i=t.globals||[];for(let o of i)o.slug&&!this.hasGlobal(o.slug)&&this.addGlobal(o);}this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let n=this.collections.get(e)?.admin?.useAsTitle;return n||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(i=>i.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},T=null;function ot(){return T||(T=new R),T}function nt(){T=null;}function U(){return T=new R,T}var C=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},O=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[n,i]of Object.entries(t))if(Array.isArray(i))for(let o of i)this.registerHook(n,o);}unregister(e){let t=this.plugins.get(e);if(!t)return;let n=t.getHooks?.()||{};for(let[i,o]of Object.entries(n))if(Array.isArray(o))for(let r of o)this.unregisterHook(i,r);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let n=this.hooks.get(e);if(n){let i=n.indexOf(t);i>-1&&n.splice(i,1);}}async executeHook(e,t){let n=this.hooks.get(e)||[],i=t;for(let o of n)try{let r=await o({...t,data:i});r!==void 0&&(i=r);}catch(r){console.error(`[PluginManager] Error in hook "${e}":`,r);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let n=t.getCollections?.()||[];e.push(...n);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let n=t.getGlobals?.()||[];e.push(...n);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},z=class extends C{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},H=class extends C{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},M=class extends C{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},B=class extends C{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},V=class extends C{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},kt={SEO:z,Analytics:H,Comments:M,Reviews:B,Wishlist:V};var Re=new Set(["type","admin","label","singularLabel","labelPlural","relationTo","required","hasMany","defaultValue","validate","options","dynamicOptions","filterOptions","hooks","min","max","minLength","maxLength","minRows","maxRows","minDate","maxDate","step","integer","variant","pattern","format","fields","tabs","blocks"]);function Fe(s){return typeof s!="object"||s===null||Array.isArray(s)?false:Object.keys(s).some(e=>Re.has(e))}function Z(s,e=""){let t={};for(let[n,i]of Object.entries(s)){let o=e?`${e}.${n}`:n;i&&typeof i=="object"&&!Array.isArray(i)&&!Fe(i)?Object.assign(t,Z(i,o)):t[o]=i;}return t}function v(s,e,t,n=true){let i=e.split(".");if(i.length===0)return false;let o=i[0],r=i.slice(1).join("."),c=o.match(/^(?:tab|tabs)\[(.+?)\]$/i);if(c){let l=c[1].toLowerCase();for(let u of s)if(u.type==="tabs"&&u.tabs&&Array.isArray(u.tabs)){for(let d of u.tabs)if((d.label||d.name||"").toLowerCase()===l&&d.fields&&Array.isArray(d.fields))return v(d.fields,r,t,n)}return false}for(let l of s){if(l.name===o)if(r){if(l.fields&&Array.isArray(l.fields))return v(l.fields,r,t,true);if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true;return false}if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");if(!g)return false;for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields))return v(p.fields,g,t,true);return false}return l.type==="array"&&l.fields&&Array.isArray(l.fields)?v(l.fields,r,t,true):false}else return Object.assign(l,t),true;if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){if(o==="blocks"&&r){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields)&&v(p.fields,g,t,true))return true}for(let d of l.blocks)if(d.slug===o&&d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true}if(!l.name||l.type==="tabs"||l.type==="row"||l.type==="collapsible"){if(l.fields&&Array.isArray(l.fields)&&v(l.fields,e,t,false))return true;if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,e,t,false))return true}}}return n&&!r&&t&&t.type?(s.push({name:o,...t}),true):false}function W(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({slug:o?.slug||i,...o}));function n(i){for(let o of i){if(o.type==="blocks"){Array.isArray(o.blocks)||(o.blocks=[]);for(let r of t){let c=o.blocks.findIndex(l=>l.slug===r.slug);c>=0?o.blocks[c]={...o.blocks[c],...r}:o.blocks.push(r);}return true}if(o.fields&&Array.isArray(o.fields)&&n(o.fields))return true;if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let r of o.tabs)if(r.fields&&Array.isArray(r.fields)&&n(r.fields))return true}}return false}n(s);}function Y(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({label:o?.label||i,...Array.isArray(o)?{fields:o}:o})),n=s.find(i=>i.type==="tabs");if(n&&Array.isArray(n.tabs))for(let i of t){let o=n.tabs.find(r=>(r.label||r.name||"").toLowerCase()===(i.label||i.name||"").toLowerCase());o?(i.fields&&Array.isArray(i.fields)&&(Array.isArray(o.fields)||(o.fields=[]),o.fields.push(...i.fields)),Object.assign(o,i)):n.tabs.push(i);}else {let i=[...s];s.length=0,s.push({type:"tabs",tabs:[{label:"General",fields:i},...t]});}}function J(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,labels:c,label:l,singularLabel:u,labelPlural:d,hidden:g,timestamps:p,versions:h,seo:m,access:b,hooks:x,admin:ie,...oe}=n;if(l&&(t.label=l),u&&(t.singularLabel=u),d&&(t.labelPlural=d),c&&(c.singular&&(t.singularLabel=c.singular),c.plural&&(t.labelPlural=c.plural)),p!==void 0&&(t.timestamps=p),h!==void 0&&(t.versions={...t.versions,...h}),m!==void 0&&(t.seo=m),b&&(t.access={...t.access,...b}),x&&(t.hooks={...t.hooks,...x}),(ie||oe)&&(t.admin={...t.admin,...ie,...oe}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let Ee=Z(i);for(let[Ke,$e]of Object.entries(Ee))v(t.fields,Ke,$e);}}}}function Q(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,label:c,hidden:l,versions:u,access:d,hooks:g,admin:p,...h}=n;if(c&&(t.label=c),u!==void 0&&(t.versions={...t.versions,...u}),d&&(t.access={...t.access,...d}),g&&(t.hooks={...t.hooks,...g}),(p||h)&&(t.admin={...t.admin,...p,...h}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let m=Z(i);for(let[b,x]of Object.entries(m))v(t.fields,b,x);}}}}var at={aws:{type:"aws",configKey:"s3",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1",admin:{placeholder:"us-east-1"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"endpoint",type:"text",label:"Endpoint URL",admin:{placeholder:"https://s3.custom.com"}},{name:"cdnUrl",type:"text",label:"CDN URL",admin:{placeholder:"https://cdn.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}]},r2:{type:"r2",configKey:"r2",displayName:"Cloudflare R2",configFields:[{name:"accountId",type:"text",label:"Account ID",required:true,admin:{placeholder:"Your Cloudflare Account ID"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"publicDevUrl",type:"text",label:"Public Dev URL ID",admin:{placeholder:"pub-xxxxxxxxxxxxxxxx",description:"Enter ONLY the ID (e.g., pub-b8d8c4cc8bcf4d868ddd95efc1b305aa). Do NOT include https:// or the full URL. Found in R2 Dashboard \u2192 Public Dev URL."}},{name:"cdnUrl",type:"text",label:"Custom CDN URL",admin:{placeholder:"https://assets.example.com (optional)"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads (optional)",description:"Optional prefix for all object keys. Do not use '/' as prefix."}}]},gcs:{type:"gcs",configKey:"gcs",displayName:"Google Cloud Storage",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"projectId",type:"text",label:"Project ID"},{name:"clientEmail",type:"text",label:"Client Email"},{name:"privateKey",type:"password",label:"Private Key"},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},digitalocean:{type:"digitalocean",configKey:"digitalocean",displayName:"DigitalOcean Spaces",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"nyc3"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},backblaze:{type:"backblaze",configKey:"backblaze",displayName:"Backblaze B2",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"accountId",type:"text",label:"Account ID"},{name:"applicationKeyId",type:"text",label:"Application Key ID",required:true},{name:"applicationKey",type:"password",label:"Application Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},wasabi:{type:"wasabi",configKey:"wasabi",displayName:"Wasabi",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]}};function rt(s,e){switch(s){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Pe(s,e){return {provider:s,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:rt(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function lt(s,e,t){let n=t[e.configKey]||{};return Pe(s,n)}function ct(s,e,t){let n=t?.[e.configKey]||t;return Pe(s,n)}var X=class extends C{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let n=this.name;for(let i of Object.values(at))t.register({type:i.type,displayName:i.displayName,pluginName:n,configKey:i.configKey,configFields:i.configFields,extractConfig:o=>lt(i.type,i,o),extractRawConfig:o=>ct(i.type,i,o),factory:o=>chunkO2SA56P2_cjs.a(o)});}},Oe=new X;var ee=class extends C{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:n=>({cloudName:n.cloudinary?.cloudName||"",apiKey:n.cloudinary?.apiKey||"",apiSecret:n.cloudinary?.apiSecret||"",folder:n.cloudinary?.folder,uploadPreset:n.cloudinary?.uploadPreset}),extractRawConfig:n=>{let i=n?.cloudinary||n;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:n=>chunkO2SA56P2_cjs.b(n)});}},Ze=new ee;var ut=[Oe,Ze],te=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=U(),this.db=e.adapter||e.db,this.pubsub=new chunkFU76HURF_cjs.b(this.registry),this.webhookService=chunkOJBL4CXK_cjs.n(this.db),this.pluginManager=new O;for(let t of ut)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&J(e.collections,e.admin.collectionOverrides),e.globals&&e.admin?.globalOverrides&&Q(e.globals,e.admin.globalOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(chunkN7CDHWQH_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkDCFOVCJX_cjs.a,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},n={slug:chunkOJBL4CXK_cjs.e,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:chunkOJBL4CXK_cjs.f,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},o=this.registry.getGlobals();if(this.db instanceof chunkGWUHIIPO_cjs.c&&this.db.dialect==="postgres"){let r=this.db,c=chunkDCFOVCJX_cjs.a.replace(/-/g,"_");r.schema&&!r.schema[c]&&(r.schema[c]=chunk23RSKVJP_cjs.g);}await this.db.init([...this.registry.getCollections(),t,n,i],o),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),n={};try{let i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(n=i.states);}catch{}for(let i of t)n[i]!==void 0&&e.setPluginEnabled(i,n[i]);}async getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,i=t?.checkSession!==false;return chunkO2SA56P2_cjs.n({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunk24W5I6SJ_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:i})=>{let o=chunkDCFOVCJX_cjs.c(i),r,c;if(o&&this.db){let u=await chunkDCFOVCJX_cjs.b(o,this.db);u.user&&(r=u.user,c=chunkDCFOVCJX_cjs.d(u));}let l=e?.tenantId;return {db:this.db,registry:this.registry,user:r,req:i,tenantId:l,apiKey:c,relationLoader:new chunk24W5I6SJ_cjs.a({db:this.db,tenantId:l,user:r})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[r,...c]=o.split("."),l=c.join(".");if(l=l.replace(/\.(query|mutate|subscribe)$/,""),!r||!l)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let u=await chunk7KTPBTH5_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),g=chunk7KTPBTH5_cjs.i(u)[r];if(!g)return new Response(JSON.stringify({error:{message:`Collection '${r}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let p=g[l];if(typeof p!="function")return new Response(JSON.stringify({error:{message:`Procedure '${l}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let h={};if(t.method==="POST"||t.method==="PATCH")h=await t.json().catch(()=>({}));else {let x=new URL(t.url).searchParams.get("input");if(x)try{h=JSON.parse(decodeURIComponent(x));}catch{}}let m=h?.["0"]??h,b=await p({...m,collection:r});return new Response(JSON.stringify({result:{data:b}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(h){let m=h.message||"Internal error",b=m.includes("not found")?404:m.includes("denied")||m.includes("authentication required")?403:m.includes("conflict")?409:500,x=b===404?-32601:b===403?-32001:b===409?-32002:-32603;return new Response(JSON.stringify({error:{message:m,code:x,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:b}}}),{status:b,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let n=async r=>{let c=await chunkDCFOVCJX_cjs.b(r,this.db);if(!c.valid)throw new Error(c.error||"Invalid API key");if(!c.user)throw new Error("API key has no associated user");return c.user},i=e?.port||8080,o=globalThis;if(o.__KYRO_WS_SERVER__)try{await o.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=chunkFU76HURF_cjs.e({pubsub:this.pubsub,port:i,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||n}),o.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function pt(s){return new te(s)}function ns(s){let e=pt(s),t=null;return async function(i,o){return t||(t=e.init()),await t,(await e.getREST()).fetch(i,o)}}var je={debug:0,info:1,warn:2,error:3,none:4},se=class{level;constructor(){let e=typeof process<"u"?process.env?.KYRO_LOG_LEVEL:void 0;this.level=e||"info";}setLevel(e){this.level=e;}getLevel(){return this.level}shouldLog(e){return je[e]>=je[this.level]}debug(...e){this.shouldLog("debug")&&console.debug("[Kyro DEBUG]",...e);}info(...e){this.shouldLog("info")&&console.log("[Kyro]",...e);}warn(...e){this.shouldLog("warn")&&console.warn("[Kyro WARN]",...e);}error(...e){this.shouldLog("error")&&console.error("[Kyro ERROR]",...e);}},bs=new se;
|
|
3
|
+
`)}`),this.name="ConfigValidationError",this.errors=e;}};function N(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Collection slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Collection "${s.slug}" has no fields defined`);else {let t=k(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,n]of Object.entries(s.access))typeof n!="boolean"&&typeof n!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(P(s.fields,s.admin.useAsTitle)||e.push(`Collection "${s.slug}" admin.useAsTitle references unknown field "${s.admin.useAsTitle}"`)),s.admin?.defaultColumns)for(let t of s.admin.defaultColumns)P(s.fields,t)||e.push(`Collection "${s.slug}" admin.defaultColumns references unknown field "${t}"`);if(s.upload&&s.upload.fileSize&&s.upload.fileSize<=0&&e.push(`Collection "${s.slug}" upload.fileSize must be positive`),s.versions&&s.versions.maxPerDoc&&s.versions.maxPerDoc<=0&&e.push(`Collection "${s.slug}" versions.maxPerDoc must be positive`),s.auth){let t=s.fields.some(i=>i.name==="email"),n=s.fields.some(i=>i.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),n||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function _(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Global slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Global "${s.slug}" has no fields defined`);else {let t=k(s.fields,`global:${s.slug}`);e.push(...t);}return e}function k(s,e){let t=[],n=new Set;for(let i=0;i<s.length;i++){let o=s[i];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let c=k(o.fields,e);t.push(...c);}else if("tabs"in o)for(let c of o.tabs){let l=k(c.fields,e);t.push(...l);}continue}let r=o.name;if(!r){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(n.has(r)&&t.push(`${e}: Duplicate field name "${r}"`),n.add(r),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r)||t.push(`${e}: Field name "${r}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${r}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${r}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${r}" has no blocks defined`);else {let c=Ie(o.blocks,`${e}.${r}`);t.push(...c);}break;case "select":case "radio":if(typeof o.options=="function")break;if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${r}" has no options defined`);else if(Array.isArray(o.options)){let c=o.options.map(u=>typeof u=="object"&&u!==null&&"value"in u?u.value:u),l=new Set(c);c.length!==l.size&&t.push(`${e}: ${o.type} field "${r}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${r}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${r}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${r}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${r}" has minRows greater than maxRows`);}return t}function Ie(s,e){let t=[],n=new Set;for(let i of s){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),n.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let o=k(i.fields,`${e}.${i.slug}`);t.push(...o);}}return t}function be(s,e=[]){let t=[],n=new Set;for(let i of s)n.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),n.add(i.slug);for(let i of e)n.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),n.add(i.slug);for(let i of s){let o=N(i);t.push(...o);}for(let i of e){let o=_(i);t.push(...o);}for(let i of s){let o=F(i.fields,s);t.push(...o);}if(t.length>0)throw new G(t)}function F(s,e){let t=[],n=new Set(e.map(i=>i.slug));for(let i of s){if(i.type==="relationship"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)r!=="*"&&!n.has(r)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${r}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)n.has(r)||t.push(`Upload field "${i.name}" references unknown collection "${r}"`);}if("fields"in i&&i.fields){let o=F(i.fields,e);t.push(...o);}if("tabs"in i)for(let o of i.tabs){let r=F(o.fields,e);t.push(...r);}if("blocks"in i)for(let o of i.blocks){let r=F(o.fields,e);t.push(...r);}}return t}function y(s){switch(s.type){case "text":return qe(s);case "number":return Le(s);case "checkbox":return De(s);case "date":return Ge(s);case "email":return Ne(s);case "password":return _e(s);case "textarea":return Ue(s);case "select":return ze(s);case "radio":return He(s);case "color":return Me(s);case "richtext":return Be(s);case "json":return Ve(s);case "code":return We(s);case "upload":return ve(s);case "image":return ve(s);case "markdown":return Ye(s);case "relationship":return Ce(s);case "relationship-block":return Ce(s);case "array":return Je(s);case "list":return Qe(s);case "group":return Xe(s);case "blocks":return et(s);case "row":return tt(s);case "collapsible":return st(s);case "tabs":return it(s);default:return zod.z.any()}}function qe(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.pattern&&(e=e.regex(new RegExp(s.pattern))),s.variant==="email"&&(e=e.email()),s.variant==="url"&&(e=e.url()),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Le(s){let e=s.integer?zod.z.coerce.number().int():zod.z.coerce.number();return s.min!==void 0&&(e=e.min(s.min)),s.max!==void 0&&(e=e.max(s.max)),s.step&&(e=e.refine(t=>Number.isInteger(t/s.step),`Value must be divisible by ${s.step}`)),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function De(s){let e=zod.z.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ge(s){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return s.minDate&&(e=e.refine(t=>new Date(t)>=new Date(s.minDate),`Date must be after ${s.minDate}`)),s.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(s.maxDate),`Date must be before ${s.maxDate}`)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ne(s){let e=zod.z.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function _e(s){let e=zod.z.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ue(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function ze(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);s.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=s.hasMany?zod.z.array(zod.z.string()):zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function He(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);e=zod.z.enum(t);}else e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Me(s){let e=zod.z.string();return s.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),s.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),s.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Be(s){let e=zod.z.array(zod.z.record(zod.z.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ve(s){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function We(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function ve(s){let e;if(s.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ye(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ce(s){let e;return Array.isArray(s.relationTo)?e=zod.z.object({relationTo:zod.z.enum(s.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Je(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,y(n)]))).passthrough(),t=zod.z.array(e);return s.minRows&&(t=t.min(s.minRows)),s.maxRows&&(t=t.max(s.maxRows)),s.required||(t=t.optional().nullable()),s.validate&&(t=f(t,s.validate)),t}function Qe(s){let e=zod.z.array(zod.z.string());return s.required||(e=e.optional().nullable()),e}function Xe(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])));return s.required?e:e.optional().nullable()}function et(s){let e=s.blocks||[];e.map(o=>zod.z.object({blockType:zod.z.literal(o.slug),...Object.fromEntries(o.fields.filter(r=>r.name).map(r=>[r.name,y(r)]))}));let n=e.map(o=>o.slug),i;if(n.length>0){let o=zod.z.object({blockType:zod.z.enum(n)}).catchall(zod.z.any()),r=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());i=zod.z.array(zod.z.union([o,r,zod.z.record(zod.z.any())]));}else i=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return s.minRows&&(i=i.min(s.minRows)),s.maxRows&&(i=i.max(s.maxRows)),s.required||(i=i.optional().nullable()),s.validate&&(i=f(i,s.validate)),i}function tt(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function st(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function it(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=y(n));return zod.z.object(e).passthrough().optional()}function f(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function S(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=S(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else {if(!t.name)continue;e[t.name]=y(t);}return e}function A(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=A(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=zod.z.object(A(t.fields)).passthrough().optional().nullable():Object.assign(e,A(t.fields));else {if(!t.name)continue;e[t.name]=y(t).optional().nullable();}return e}function xe(s){let e=S(s.fields);return s.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),s.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ae(s){let e=S(s.fields);return zod.z.object(e).passthrough()}function we(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let i of t.fields)i.name&&(n[i.name]=y(i).optional().nullable());Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}function ke(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Se(s){let e=S(s.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Te(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}var R=class{storageProviders=chunkO2SA56P2_cjs.e();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e,fields:[...e.fields]};for(let i of this.plugins){let o=i.extensions?.collections?.find(r=>r.slug===t.slug);o&&(t={...t,...o.config,fields:[...t.fields,...o.config.fields||[]]});}if(t.seo){let i=chunkDCKJT247_cjs.a(),o=t.fields.findIndex(r=>r.type==="tabs");if(o!==-1){let r=t.fields[o];t.fields[o]={...r,tabs:[...r.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let n=N(t);if(n.length>0)throw new Error(`Invalid collection config: ${n.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=_(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let i of this.plugins){let o=i.extensions?.globals?.find(r=>r.slug===n.slug);o&&(n={...n,...o.config,fields:[...n.fields||[],...o.config.fields||[]]});}this.globals.set(n.slug,n),this.clearSchemaCache(`global:${n.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let n=this.collections.get(e);if(n){let o=xe(n);return this.schemaCache.set(e,o),o}let i=this.globals.get(e);if(i){let o=Se(i);return this.schemaCache.set(`global:${e}`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let o=Ae(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let r=we(i);return this.schemaCache.set(t,r),r}let o=this.globals.get(e);if(o){let r=Te(o);return this.schemaCache.set(`global:${e}:update`,r),r}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,n=this.schemaCache.get(t);if(n)return n;let i=this.collections.get(e);if(i){let o=ke(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return y(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(n=>n.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(n=>n.name==="tenantId")&&t.push({name:"tenantId",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(n=>n.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(n=>n.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(n=>n.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let n=this.globals.get(e);if(n)return n.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),n=new Map,i=o=>{for(let r of o){if(r.name&&n.set(r.name,r),"fields"in r&&r.fields&&i(r.fields),"tabs"in r)for(let c of r.tabs)i(c.fields);if("blocks"in r)for(let c of r.blocks)i(c.fields);}};return i(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();be(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let n=t.collections||[];for(let o of n)o.slug&&!this.hasCollection(o.slug)&&this.addCollection(o);let i=t.globals||[];for(let o of i)o.slug&&!this.hasGlobal(o.slug)&&this.addGlobal(o);}this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let n=this.collections.get(e)?.admin?.useAsTitle;return n||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(i=>i.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},T=null;function ot(){return T||(T=new R),T}function nt(){T=null;}function U(){return T=new R,T}var C=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},O=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[n,i]of Object.entries(t))if(Array.isArray(i))for(let o of i)this.registerHook(n,o);}unregister(e){let t=this.plugins.get(e);if(!t)return;let n=t.getHooks?.()||{};for(let[i,o]of Object.entries(n))if(Array.isArray(o))for(let r of o)this.unregisterHook(i,r);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let n=this.hooks.get(e);if(n){let i=n.indexOf(t);i>-1&&n.splice(i,1);}}async executeHook(e,t){let n=this.hooks.get(e)||[],i=t;for(let o of n)try{let r=await o({...t,data:i});r!==void 0&&(i=r);}catch(r){console.error(`[PluginManager] Error in hook "${e}":`,r);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let n=t.getCollections?.()||[];e.push(...n);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let n=t.getGlobals?.()||[];e.push(...n);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},z=class extends C{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},H=class extends C{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},M=class extends C{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},B=class extends C{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},V=class extends C{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},kt={SEO:z,Analytics:H,Comments:M,Reviews:B,Wishlist:V};var Re=new Set(["type","admin","label","singularLabel","labelPlural","relationTo","required","hasMany","defaultValue","validate","options","dynamicOptions","filterOptions","hooks","min","max","minLength","maxLength","minRows","maxRows","minDate","maxDate","step","integer","variant","pattern","format","fields","tabs","blocks"]);function Fe(s){return typeof s!="object"||s===null||Array.isArray(s)?false:Object.keys(s).some(e=>Re.has(e))}function Z(s,e=""){let t={};for(let[n,i]of Object.entries(s)){let o=e?`${e}.${n}`:n;i&&typeof i=="object"&&!Array.isArray(i)&&!Fe(i)?Object.assign(t,Z(i,o)):t[o]=i;}return t}function v(s,e,t,n=true){let i=e.split(".");if(i.length===0)return false;let o=i[0],r=i.slice(1).join("."),c=o.match(/^(?:tab|tabs)\[(.+?)\]$/i);if(c){let l=c[1].toLowerCase();for(let u of s)if(u.type==="tabs"&&u.tabs&&Array.isArray(u.tabs)){for(let d of u.tabs)if((d.label||d.name||"").toLowerCase()===l&&d.fields&&Array.isArray(d.fields))return v(d.fields,r,t,n)}return false}for(let l of s){if(l.name===o)if(r){if(l.fields&&Array.isArray(l.fields))return v(l.fields,r,t,true);if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true;return false}if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");if(!g)return false;for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields))return v(p.fields,g,t,true);return false}return l.type==="array"&&l.fields&&Array.isArray(l.fields)?v(l.fields,r,t,true):false}else return Object.assign(l,t),true;if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){if(o==="blocks"&&r){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields)&&v(p.fields,g,t,true))return true}for(let d of l.blocks)if(d.slug===o&&d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true}if(!l.name||l.type==="tabs"||l.type==="row"||l.type==="collapsible"){if(l.fields&&Array.isArray(l.fields)&&v(l.fields,e,t,false))return true;if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,e,t,false))return true}}}return n&&!r&&t&&t.type?(s.push({name:o,...t}),true):false}function W(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({slug:o?.slug||i,...o}));function n(i){for(let o of i){if(o.type==="blocks"){Array.isArray(o.blocks)||(o.blocks=[]);for(let r of t){let c=o.blocks.findIndex(l=>l.slug===r.slug);c>=0?o.blocks[c]={...o.blocks[c],...r}:o.blocks.push(r);}return true}if(o.fields&&Array.isArray(o.fields)&&n(o.fields))return true;if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let r of o.tabs)if(r.fields&&Array.isArray(r.fields)&&n(r.fields))return true}}return false}n(s);}function Y(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({label:o?.label||i,...Array.isArray(o)?{fields:o}:o})),n=s.find(i=>i.type==="tabs");if(n&&Array.isArray(n.tabs))for(let i of t){let o=n.tabs.find(r=>(r.label||r.name||"").toLowerCase()===(i.label||i.name||"").toLowerCase());o?(i.fields&&Array.isArray(i.fields)&&(Array.isArray(o.fields)||(o.fields=[]),o.fields.push(...i.fields)),Object.assign(o,i)):n.tabs.push(i);}else {let i=[...s];s.length=0,s.push({type:"tabs",tabs:[{label:"General",fields:i},...t]});}}function J(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,labels:c,label:l,singularLabel:u,labelPlural:d,hidden:g,timestamps:p,versions:h,seo:m,access:b,hooks:x,admin:ie,...oe}=n;if(l&&(t.label=l),u&&(t.singularLabel=u),d&&(t.labelPlural=d),c&&(c.singular&&(t.singularLabel=c.singular),c.plural&&(t.labelPlural=c.plural)),p!==void 0&&(t.timestamps=p),h!==void 0&&(t.versions={...t.versions,...h}),m!==void 0&&(t.seo=m),b&&(t.access={...t.access,...b}),x&&(t.hooks={...t.hooks,...x}),(ie||oe)&&(t.admin={...t.admin,...ie,...oe}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let Ee=Z(i);for(let[Ke,$e]of Object.entries(Ee))v(t.fields,Ke,$e);}}}}function Q(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,label:c,hidden:l,versions:u,access:d,hooks:g,admin:p,...h}=n;if(c&&(t.label=c),u!==void 0&&(t.versions={...t.versions,...u}),d&&(t.access={...t.access,...d}),g&&(t.hooks={...t.hooks,...g}),(p||h)&&(t.admin={...t.admin,...p,...h}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let m=Z(i);for(let[b,x]of Object.entries(m))v(t.fields,b,x);}}}}var at={aws:{type:"aws",configKey:"s3",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1",admin:{placeholder:"us-east-1"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"endpoint",type:"text",label:"Endpoint URL",admin:{placeholder:"https://s3.custom.com"}},{name:"cdnUrl",type:"text",label:"CDN URL",admin:{placeholder:"https://cdn.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}]},r2:{type:"r2",configKey:"r2",displayName:"Cloudflare R2",configFields:[{name:"accountId",type:"text",label:"Account ID",required:true,admin:{placeholder:"Your Cloudflare Account ID"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"publicDevUrl",type:"text",label:"Public Dev URL ID",admin:{placeholder:"pub-xxxxxxxxxxxxxxxx",description:"Enter ONLY the ID (e.g., pub-b8d8c4cc8bcf4d868ddd95efc1b305aa). Do NOT include https:// or the full URL. Found in R2 Dashboard \u2192 Public Dev URL."}},{name:"cdnUrl",type:"text",label:"Custom CDN URL",admin:{placeholder:"https://assets.example.com (optional)"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads (optional)",description:"Optional prefix for all object keys. Do not use '/' as prefix."}}]},gcs:{type:"gcs",configKey:"gcs",displayName:"Google Cloud Storage",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"projectId",type:"text",label:"Project ID"},{name:"clientEmail",type:"text",label:"Client Email"},{name:"privateKey",type:"password",label:"Private Key"},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},digitalocean:{type:"digitalocean",configKey:"digitalocean",displayName:"DigitalOcean Spaces",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"nyc3"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},backblaze:{type:"backblaze",configKey:"backblaze",displayName:"Backblaze B2",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"accountId",type:"text",label:"Account ID"},{name:"applicationKeyId",type:"text",label:"Application Key ID",required:true},{name:"applicationKey",type:"password",label:"Application Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},wasabi:{type:"wasabi",configKey:"wasabi",displayName:"Wasabi",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]}};function rt(s,e){switch(s){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Pe(s,e){return {provider:s,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:rt(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function lt(s,e,t){let n=t[e.configKey]||{};return Pe(s,n)}function ct(s,e,t){let n=t?.[e.configKey]||t;return Pe(s,n)}var X=class extends C{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let n=this.name;for(let i of Object.values(at))t.register({type:i.type,displayName:i.displayName,pluginName:n,configKey:i.configKey,configFields:i.configFields,extractConfig:o=>lt(i.type,i,o),extractRawConfig:o=>ct(i.type,i,o),factory:o=>chunkO2SA56P2_cjs.a(o)});}},Oe=new X;var ee=class extends C{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:n=>({cloudName:n.cloudinary?.cloudName||"",apiKey:n.cloudinary?.apiKey||"",apiSecret:n.cloudinary?.apiSecret||"",folder:n.cloudinary?.folder,uploadPreset:n.cloudinary?.uploadPreset}),extractRawConfig:n=>{let i=n?.cloudinary||n;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:n=>chunkO2SA56P2_cjs.b(n)});}},Ze=new ee;var ut=[Oe,Ze],te=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=U(),this.db=e.adapter||e.db,this.pubsub=new chunkFU76HURF_cjs.b(this.registry),this.webhookService=chunkOJBL4CXK_cjs.n(this.db),this.pluginManager=new O;for(let t of ut)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&J(e.collections,e.admin.collectionOverrides),e.globals&&e.admin?.globalOverrides&&Q(e.globals,e.admin.globalOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(chunkN7CDHWQH_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkDCFOVCJX_cjs.a,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},n={slug:chunkOJBL4CXK_cjs.e,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:chunkOJBL4CXK_cjs.f,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},o=this.registry.getGlobals();if(this.db instanceof chunk7QZYK4MT_cjs.c&&this.db.dialect==="postgres"){let r=this.db,c=chunkDCFOVCJX_cjs.a.replace(/-/g,"_");r.schema&&!r.schema[c]&&(r.schema[c]=chunk23RSKVJP_cjs.g);}await this.db.init([...this.registry.getCollections(),t,n,i],o),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),n={};try{let i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(n=i.states);}catch{}for(let i of t)n[i]!==void 0&&e.setPluginEnabled(i,n[i]);}async getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,i=t?.checkSession!==false;return chunkO2SA56P2_cjs.n({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunk24W5I6SJ_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:i})=>{let o=chunkDCFOVCJX_cjs.c(i),r,c;if(o&&this.db){let u=await chunkDCFOVCJX_cjs.b(o,this.db);u.user&&(r=u.user,c=chunkDCFOVCJX_cjs.d(u));}let l=e?.tenantId;return {db:this.db,registry:this.registry,user:r,req:i,tenantId:l,apiKey:c,relationLoader:new chunk24W5I6SJ_cjs.a({db:this.db,tenantId:l,user:r})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[r,...c]=o.split("."),l=c.join(".");if(l=l.replace(/\.(query|mutate|subscribe)$/,""),!r||!l)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let u=await chunk7KTPBTH5_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),g=chunk7KTPBTH5_cjs.i(u)[r];if(!g)return new Response(JSON.stringify({error:{message:`Collection '${r}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let p=g[l];if(typeof p!="function")return new Response(JSON.stringify({error:{message:`Procedure '${l}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let h={};if(t.method==="POST"||t.method==="PATCH")h=await t.json().catch(()=>({}));else {let x=new URL(t.url).searchParams.get("input");if(x)try{h=JSON.parse(decodeURIComponent(x));}catch{}}let m=h?.["0"]??h,b=await p({...m,collection:r});return new Response(JSON.stringify({result:{data:b}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(h){let m=h.message||"Internal error",b=m.includes("not found")?404:m.includes("denied")||m.includes("authentication required")?403:m.includes("conflict")?409:500,x=b===404?-32601:b===403?-32001:b===409?-32002:-32603;return new Response(JSON.stringify({error:{message:m,code:x,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:b}}}),{status:b,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let n=async r=>{let c=await chunkDCFOVCJX_cjs.b(r,this.db);if(!c.valid)throw new Error(c.error||"Invalid API key");if(!c.user)throw new Error("API key has no associated user");return c.user},i=e?.port||8080,o=globalThis;if(o.__KYRO_WS_SERVER__)try{await o.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=chunkFU76HURF_cjs.e({pubsub:this.pubsub,port:i,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||n}),o.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function pt(s){return new te(s)}function ns(s){let e=pt(s),t=null;return async function(i,o){return t||(t=e.init()),await t,(await e.getREST()).fetch(i,o)}}var je={debug:0,info:1,warn:2,error:3,none:4},se=class{level;constructor(){let e=typeof process<"u"?process.env?.KYRO_LOG_LEVEL:void 0;this.level=e||"info";}setLevel(e){this.level=e;}getLevel(){return this.level}shouldLog(e){return je[e]>=je[this.level]}debug(...e){this.shouldLog("debug")&&console.debug("[Kyro DEBUG]",...e);}info(...e){this.shouldLog("info")&&console.log("[Kyro]",...e);}warn(...e){this.shouldLog("warn")&&console.warn("[Kyro WARN]",...e);}error(...e){this.shouldLog("error")&&console.error("[Kyro ERROR]",...e);}},bs=new se;
|
|
4
4
|
exports.A=v;exports.B=W;exports.C=Y;exports.D=J;exports.E=Q;exports.F=te;exports.G=pt;exports.H=ns;exports.I=se;exports.J=bs;exports.a=G;exports.b=N;exports.c=_;exports.d=k;exports.e=be;exports.f=y;exports.g=xe;exports.h=Ae;exports.i=we;exports.j=ke;exports.k=Se;exports.l=R;exports.m=ot;exports.n=nt;exports.o=U;exports.p=C;exports.q=O;exports.r=z;exports.s=H;exports.t=M;exports.u=B;exports.v=V;exports.w=kt;exports.x=Re;exports.y=Fe;exports.z=Z;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import {c,d as d$1}from'./chunk-WLSVS3NC.js';import {a,c as c$1,b,d}from'./chunk-YNSKDTFG.js';import {a as a$1}from'./chunk-VLFM66BZ.js';import {a as a$2}from'./chunk-NGNXOXI5.js';import {sql,eq,desc,and,or,ne,inArray,ilike,like,gt,gte,lt,lte}from'drizzle-orm';import {text,uuid,jsonb,timestamp,boolean,decimal,integer as integer$1,varchar,pgTable,PgDialect}from'drizzle-orm/pg-core';import {text as text$1,integer,numeric,sqliteTable,SQLiteSyncDialect}from'drizzle-orm/sqlite-core';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
function w(m,s="postgres"){switch(m.type){case "text":case "email":case "password":case "color":case "icon":return s==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return m.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return s==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return s==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function X(m,s="postgres"){let n=m.slug.replace(/-/g,"_"),e=[];e.push(`export const ${n} = pgTable('${n}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");let r=c(m.fields);for(let t of r){if(t.name==="id"||t.type==="password")continue;let l=w(t,s),a=t.required,o=` ${t.name}: pg.${l}('${t.name}')`;t.unique&&(o+=".unique()"),a||(o+=".nullable()"),t.defaultValue!==void 0&&(typeof t.defaultValue=="string"?o+=`.default('${t.defaultValue}')`:typeof t.defaultValue=="boolean"?o+=`.default(${t.defaultValue})`:o+=`.default(sql\`${JSON.stringify(t.defaultValue)}\`)`),o+=",",e.push(o);}return m.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${s==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${s==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
|
|
3
|
+
`)}function R(m){if(typeof m!="string")return m;let s=m.replace(/-/g,"").toLowerCase();return s.length===32?`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`:m}var x=class extends a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let n=s.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=s.type||"postgres";}else this.rawClient=s.client,this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,n){let e=super.prepareData(s,n),r=c(n.fields);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 r)if(t.type==="date"&&t.name){let l=e[t.name];l&&typeof l=="string"&&(e[t.name]=new Date(l));}for(let t of r){let a=w(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let o=s[t.name];if(o&&typeof o=="object"){let c={};for(let[i,u]of Object.entries(o)){let f=t.tabs.flatMap(E=>E.fields).find(E=>E.name===i);(f?.type==="upload"||f?.type==="image"||f?.type==="list"||f?.type==="relationship-block")&&u?c[i]=Array.isArray(u)||typeof u=="object"?JSON.stringify(u):u:c[i]=u;}e[t.name]=this.dialect==="sqlite"||!a?JSON.stringify(c):c;}}else if(a&&t.name&&s[t.name]!==void 0&&s[t.name]!==null)e[t.name]=this.dialect==="sqlite"?JSON.stringify(s[t.name]):s[t.name];else if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let o=s[t.name];o!=null&&(e[t.name]=this.dialect==="sqlite"||!a?typeof o=="string"?o:JSON.stringify(o):o);}}for(let t of r)if(t.name&&e[t.name]===""){let l=w(t,this.dialect);(l==="timestamp"||l==="jsonb"||l==="decimal"||l==="integer"||l==="numeric"||l==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let s,n;try{s=(await import('postgres')).default,n=(await import('drizzle-orm/postgres-js')).drizzle;}catch{a$1(["postgres","drizzle-orm"]),s=(await import('postgres')).default,n=(await import('drizzle-orm/postgres-js')).drizzle;}let e=s(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let s,n;try{s=(await import('better-sqlite3')).default,n=(await import('drizzle-orm/better-sqlite3')).drizzle;}catch{a$1(["better-sqlite3","drizzle-orm"]),s=(await import('better-sqlite3')).default,n=(await import('drizzle-orm/better-sqlite3')).drizzle;}let e=new s(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:s}=await import('drizzle-orm/d1');this.client=s(this.rawClient,{schema:this.schema});}this.connected=true;}async init(s,n=[]){if(await super.init(s,n),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let r of s){let t=this.getTableName(r.slug);this.schema[t]||(this.schema[t]=this.createTableFromConfig(r));}await this.ensureCollectionTables(s);let e=n.map(r=>({slug:`_globals_${r.slug}`,fields:r.fields,label:r.label}));for(let r of e){let t=this.getTableName(r.slug);this.schema[t]||(this.schema[t]=this.createTableFromConfig(r,true)),this.collections.has(r.slug)||this.collections.set(r.slug,r);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(s,n=false){let e=this.getTableName(s.slug),r={id:n?text("id").primaryKey():uuid("id").primaryKey().defaultRandom()},t=c(s.fields);for(let l of t){if(!l.name||l.name==="id"||l.type==="password")continue;let a=w(l,this.dialect),o=l.name.replace(/-/g,"_"),c=o.replace(/([A-Z])/g,"_$1").toLowerCase(),i;if(this.dialect==="sqlite")switch(a){case "varchar":case "text":i=text$1(c);break;case "integer":i=integer(c);break;case "decimal":case "numeric":i=numeric(c);break;case "boolean":i=integer(c,{mode:"boolean"});break;case "timestamp":i=text$1(c);break;case "jsonb":i=text$1(c);break;default:i=text$1(c);}else switch(a){case "varchar":i=varchar(c,{length:255});break;case "integer":i=integer$1(c);break;case "decimal":i=decimal(c);break;case "boolean":i=boolean(c);break;case "timestamp":i=timestamp(c);break;case "jsonb":i=jsonb(c);break;default:i=text(c);}l.required||(i=i.default(null)),r[o]=i;}return r.createdAt||(r.createdAt=this.dialect==="sqlite"?text$1("created_at").default(new Date().toISOString()):timestamp("created_at").defaultNow()),r.updatedAt||(r.updatedAt=this.dialect==="sqlite"?text$1("updated_at").default(new Date().toISOString()):timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(r.status||(r.status=this.dialect==="sqlite"?text$1("status").default("draft"):varchar("status",{length:20}).default("draft")),r.hasDraft||(r.hasDraft=this.dialect==="sqlite"?integer("hasDraft",{mode:"boolean"}).default(false):boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteTable(e,r):pgTable(e,r)}async ensureCollectionTables(s){let n=[];for(let e of s){let r=e.slug.startsWith("_globals_"),t=this.getTableName(e.slug),l=this.generateCreateColumns(e),a=c(e.fields),o=a.some(f=>f.name==="createdAt"),c$1=a.some(f=>f.name==="updatedAt"),i=a.some(f=>f.name==="status"),u=a.some(f=>f.name==="hasDraft");if(this.dialect==="postgres"){let f=r?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS "${t}" (
|
|
5
|
+
${f},
|
|
6
|
+
${l}
|
|
7
|
+
${o?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
8
|
+
${c$1?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
9
|
+
${i?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
|
|
10
|
+
${u?"":'"hasDraft" BOOLEAN DEFAULT false'}
|
|
11
|
+
)
|
|
12
|
+
`);}else n.push(`
|
|
13
|
+
CREATE TABLE IF NOT EXISTS "${t}" (
|
|
14
|
+
"id" TEXT PRIMARY KEY,
|
|
15
|
+
${l}
|
|
16
|
+
${o?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
17
|
+
${c$1?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
18
|
+
${i?"":`"status" TEXT DEFAULT 'draft',`}
|
|
19
|
+
${u?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
20
|
+
)
|
|
21
|
+
`);}if(n.length>0)if(this.dialect==="postgres")await this.executeRaw(sql.raw(n.join(`;
|
|
22
|
+
`)));else for(let e of n)await this.executeRaw(sql.raw(e));for(let e of s){let r=this.getTableName(e.slug);r==="users"||r==="audit_logs"||await this.syncTableColumns(e,r);}}getColumnSqlDefinition(s,n){let e=w(s,n),r=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),t=this.columnSqlType(e,n);return `"${r}" ${t} DEFAULT NULL`}columnSqlType(s,n){if(n==="sqlite")switch(s){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(s){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(s,n){let e={},r=s.slug.startsWith("_globals_"),t=c(s.fields),l=t.some(i=>i.name==="createdAt"),a=t.some(i=>i.name==="updatedAt"),o=t.some(i=>i.name==="status"),c$1=t.some(i=>i.name==="hasDraft");this.dialect==="postgres"?(e.id=r?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',l||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),a||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),o||(e.status='"status" VARCHAR(20) DEFAULT NULL'),c$1||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',l||(e.created_at='"created_at" TEXT DEFAULT NULL'),a||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),o||(e.status='"status" TEXT DEFAULT NULL'),c$1||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let i of t){if(!i.name||i.name==="id")continue;let u=this.getColumnSqlDefinition(i,this.dialect),f=i.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[f]=u;}return e}async syncTableColumns(s,n){let e;try{if(this.dialect==="postgres"){let l=await this.executeRaw(sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${n}`);e=new Map(l.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let l=await this.executeRaw(sql`PRAGMA table_info("${sql.raw(n)}")`);e=new Map(l.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let r=this.getExpectedColumnDefs(s,n),t=Object.keys(r).filter(l=>!e.has(l));if(t.length>0){let l=t.map(a=>`ALTER TABLE "${n}" ADD COLUMN ${r[a]}`);await this.executeRaw(sql.raw(l.join(`;
|
|
23
|
+
`)));}if(this.dialect==="postgres"){let l=c(s.fields);for(let a of l){if(!a.name||a.name==="id")continue;let o=w(a,this.dialect),c=a.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),i=e.get(c);!i||i.type!=="character varying"||(o==="text"?await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${c}" TYPE TEXT`)):o==="jsonb"&&(await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${c}" DROP DEFAULT`)),await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${c}" TYPE JSONB USING (CASE WHEN "${c}" IS NULL THEN NULL WHEN "${c}"::text ~ '^\\s*\\{' THEN "${c}"::jsonb ELSE jsonb_build_object('id', "${c}"::text) END)`))));}}}generateCreateColumns(s){let n=[],e=c(s.fields);for(let r of e){if(!r.name||r.name==="id")continue;let t=w(r,this.dialect),l=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),a=r.required?"NOT NULL":"DEFAULT NULL",o;if(this.dialect==="sqlite")switch(t){case "varchar":case "text":o=`TEXT ${a}`;break;case "integer":o=`INTEGER ${a}`;break;case "decimal":case "numeric":o=`NUMERIC ${a}`;break;case "boolean":o=`INTEGER ${a}`;break;case "timestamp":o=`TEXT ${a}`;break;case "jsonb":o=`TEXT ${a}`;break;default:o=`TEXT ${a}`;}else switch(t){case "varchar":o=`VARCHAR(255) ${a}`;break;case "integer":o=`INTEGER ${a}`;break;case "decimal":o=`DECIMAL ${a}`;break;case "boolean":o=`BOOLEAN ${a}`;break;case "timestamp":o=`TIMESTAMP ${a}`;break;case "jsonb":o=`JSONB ${a}`;break;default:o=`TEXT ${a}`;}n.push(`"${l}" ${o}`);}return n.join(`,
|
|
24
|
+
`)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:r,limit:t=10,page:l=1,tenantId:a,select:o,draft:c$2}=s,i=this.getCollection(n),u=this.getTable(n),f={...e};this.tenantContext&&i.tenantScoped&&(f=c$1({where:f},n,this.tenantContext,b).where||{});let L=this.buildWhereClause(f,i,u,a),y=c(i.fields).find(h=>h.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c$2&&u.status&&p&&L.push(eq(u.status,"published"));let b$1=this.parseSort(r),T=!c$2&&u.status&&p?{...f,status:"published"}:f,K=await this.count({collection:n,where:T,tenantId:a}),G=(l-1)*t,q=[];try{let h=u[b$1.field]||u.createdAt||u.id,I=b$1.direction==="asc"?h:desc(h),N=this.client.select().from(u);L.length>0&&(N=N.where(and(...L))),q=await N.orderBy(I).limit(t).offset(G);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let $=q.map(h=>this.processResult(h,i));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&($=$.filter(h=>d(h,n,this.tenantContext,b))),c$2&&($=await Promise.all($.map(async h=>{let I=await this.executeRaw(sql`
|
|
25
|
+
SELECT * FROM kyro_versions
|
|
26
|
+
WHERE collection_slug = ${n}
|
|
27
|
+
AND document_id = ${h.id}
|
|
28
|
+
ORDER BY created_at DESC
|
|
29
|
+
LIMIT 1
|
|
30
|
+
`);if(I.length>0){let N=I[0],_=N.data;for(;typeof _=="string";)try{_=JSON.parse(_);}catch{break}return (!_||typeof _!="object"||Array.isArray(_))&&(_={}),{...h,..._,status:h.status,_hasUnpublishedChanges:N.status==="draft"}}return h}))),{docs:$,...this.calculatePagination(l,t,K)}}async findByID(s){let{collection:n,id:e,tenantId:r,draft:t}=s,l=this.getCollection(n),a=this.getTable(n),o=this.dialect==="postgres"&&typeof e=="string"?R(e):e;if(this.tenantContext&&l.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!d(p,n,this.tenantContext,b))return null}let c$1=[eq(a.id,o)];r&&a.tenantId&&c$1.push(eq(a.tenantId,r));let u=c(l.fields).find(p=>p.name==="status"),f=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!t&&a.status&&f&&c$1.push(eq(a.status,"published"));let L=c$1.length>1?and(...c$1):c$1[0],E=await this.client.select().from(a).where(L);if(E.length===0)return null;let y=this.processResult(E[0],l);if(t){let p=await this.executeRaw(sql`
|
|
31
|
+
SELECT * FROM kyro_versions
|
|
32
|
+
WHERE collection_slug = ${n}
|
|
33
|
+
AND document_id = ${y.id}
|
|
34
|
+
ORDER BY created_at DESC
|
|
35
|
+
LIMIT 1
|
|
36
|
+
`);if(p.length>0){let b=p[0],T=b.data;for(;typeof T=="string";)try{T=JSON.parse(T);}catch{break}(!T||typeof T!="object"||Array.isArray(T))&&(T={}),y={...y,...T,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}async create(s){let{collection:n,data:e,tenantId:r}=s,t=this.getCollection(n),l=this.getTable(n),a=this.prepareData(e,t);r&&t.tenantScoped&&(a.tenantId=r);let o=await this.client.insert(l).values(a).returning();return this.processResult(o[0],t)}async update(s){let{collection:n,id:e,data:r,tenantId:t}=s,l=this.getCollection(n),a=this.getTable(n),o=this.prepareData(r,l),c=this.dialect==="postgres"&&typeof e=="string"?R(e):e,i=[eq(a.id,c)];t&&a.tenantId&&i.push(eq(a.tenantId,t));let u=await this.client.update(a).set(o).where(and(...i)).returning();if(u.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(u[0],l)}async delete(s){let{collection:n,id:e,tenantId:r}=s,t=this.getCollection(n),l=this.getTable(n),a=this.dialect==="postgres"&&typeof e=="string"?R(e):e,o=[eq(l.id,a)];r&&l.tenantId&&o.push(eq(l.tenantId,r));let c=await this.client.delete(l).where(and(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(c[0],t)}async count(s){let{collection:n,where:e={},tenantId:r}=s,t=this.getCollection(n),l=this.getTable(n),a=this.buildWhereClause(e,t,l,r);try{let o=this.client.select({count:sql`count(*)`}).from(l);a.length>0&&(o=o.where(and(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:n,where:e={},tenantId:r,draft:t}=s;if(n.startsWith("_globals_")){let a=n.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c$1=this.getTable(n),i=this.client.select().from(c$1),f=c(o.fields).find(p=>p.name==="status"),L=f?.type==="select"&&Array.isArray(f.options)&&f.options.some(p=>p.value==="published");!t&&c$1.status&&L&&(i=i.where(eq(c$1.status,"published")));let E=await i.limit(1);if(E.length===0)return null;let y=this.processResult(E[0],o);if(t){let p=await this.executeRaw(sql`
|
|
37
|
+
SELECT * FROM kyro_versions
|
|
38
|
+
WHERE collection_slug = ${n}
|
|
39
|
+
AND document_id = ${a}
|
|
40
|
+
ORDER BY created_at DESC
|
|
41
|
+
LIMIT 1
|
|
42
|
+
`);if(p.length>0){let b=p[0],T=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,...T,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:r=10,page:t=1,tenantId:l}=s,a=(t-1)*r,o=this.getCollection(n),c=await this.executeRaw(sql`
|
|
43
|
+
SELECT count(*) as count
|
|
44
|
+
FROM kyro_versions
|
|
45
|
+
WHERE collection_slug = ${n}
|
|
46
|
+
AND document_id = ${e}
|
|
47
|
+
AND autosave = 0
|
|
48
|
+
${l&&o.tenantScoped?sql`AND tenant_id = ${l}`:sql``}
|
|
49
|
+
`),i=parseInt(c[0]?.count||"0");return {docs:(await this.executeRaw(sql`
|
|
50
|
+
SELECT *
|
|
51
|
+
FROM kyro_versions
|
|
52
|
+
WHERE collection_slug = ${n}
|
|
53
|
+
AND document_id = ${e}
|
|
54
|
+
AND autosave = 0
|
|
55
|
+
${l&&o.tenantScoped?sql`AND tenant_id = ${l}`:sql``}
|
|
56
|
+
ORDER BY created_at DESC
|
|
57
|
+
LIMIT ${r}
|
|
58
|
+
OFFSET ${a}
|
|
59
|
+
`)).map(f=>({...f,data:typeof f.data=="string"?JSON.parse(f.data):f.data})),...this.calculatePagination(t,r,i)}}async findVersionByID(s){await this.ensureVersionsTable();let n=this.getCollection(s.collection),e=await this.executeRaw(sql`
|
|
60
|
+
SELECT * FROM kyro_versions
|
|
61
|
+
WHERE id = ${s.versionId}
|
|
62
|
+
AND collection_slug = ${s.collection}
|
|
63
|
+
${s.tenantId&&n.tenantScoped?sql`AND tenant_id = ${s.tenantId}`:sql``}
|
|
64
|
+
LIMIT 1
|
|
65
|
+
`);if(e.length===0)return null;let r=e[0];return {...r,data:typeof r.data=="string"?JSON.parse(r.data):r.data}}async createVersion(s){await this.ensureVersionsTable();let n=this.getCollection(s.collection),e=new Date().toISOString();if(s.autosave){let l=await this.executeRaw(sql`
|
|
66
|
+
SELECT * FROM kyro_versions
|
|
67
|
+
WHERE collection_slug = ${s.collection}
|
|
68
|
+
AND document_id = ${s.documentId}
|
|
69
|
+
AND autosave = 1
|
|
70
|
+
${s.tenantId&&n.tenantScoped?sql`AND tenant_id = ${s.tenantId}`:sql``}
|
|
71
|
+
LIMIT 1
|
|
72
|
+
`);if(l.length>0)return await this.executeRaw(sql`
|
|
73
|
+
UPDATE kyro_versions
|
|
74
|
+
SET data = ${JSON.stringify(s.data)},
|
|
75
|
+
status = ${s.status},
|
|
76
|
+
updated_at = ${e}
|
|
77
|
+
WHERE id = ${l[0].id}
|
|
78
|
+
`),this.findVersionByID({collection:s.collection,versionId:l[0].id,tenantId:s.tenantId})}let r=Math.random().toString(36).substring(2,15),t=typeof s.data=="string"?s.data:JSON.stringify(s.data);if(await this.executeRaw(sql`
|
|
79
|
+
INSERT INTO kyro_versions (
|
|
80
|
+
id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
|
|
81
|
+
) VALUES (
|
|
82
|
+
${r}, ${s.collection}, ${s.documentId}, ${s.tenantId&&n.tenantScoped?s.tenantId:null},
|
|
83
|
+
${t}, ${s.status}, ${s.autosave?1:0}, ${s.createdBy||null},
|
|
84
|
+
${s.changeDescription||null}, ${e}, ${e}
|
|
85
|
+
)
|
|
86
|
+
`),!s.autosave){let l=this.getCollection(s.collection);l.versions?.maxPerDoc&&await this.deleteVersions({collection:s.collection,documentId:s.documentId,keepLatest:l.versions.maxPerDoc,tenantId:s.tenantId});}return this.findVersionByID({collection:s.collection,versionId:r,tenantId:s.tenantId})}async updateLatestVersion(s){return this.createVersion({...s,autosave:true})}async deleteVersions(s){await this.ensureVersionsTable();let n=this.getCollection(s.collection);if(s.keepLatest){let r=(await this.executeRaw(sql`
|
|
87
|
+
SELECT id FROM kyro_versions
|
|
88
|
+
WHERE collection_slug = ${s.collection}
|
|
89
|
+
AND document_id = ${s.documentId}
|
|
90
|
+
AND autosave = 0
|
|
91
|
+
${s.tenantId&&n.tenantScoped?sql`AND tenant_id = ${s.tenantId}`:sql``}
|
|
92
|
+
ORDER BY created_at DESC
|
|
93
|
+
LIMIT ${s.keepLatest}
|
|
94
|
+
`)).map(t=>t.id);r.length>0&&await this.executeRaw(sql`
|
|
95
|
+
DELETE FROM kyro_versions
|
|
96
|
+
WHERE collection_slug = ${s.collection}
|
|
97
|
+
AND document_id = ${s.documentId}
|
|
98
|
+
AND autosave = 0
|
|
99
|
+
AND id NOT IN (${sql.join(r.map(t=>sql`${t}`),sql`, `)})
|
|
100
|
+
`);}else await this.executeRaw(sql`
|
|
101
|
+
DELETE FROM kyro_versions
|
|
102
|
+
WHERE collection_slug = ${s.collection}
|
|
103
|
+
AND document_id = ${s.documentId}
|
|
104
|
+
${s.tenantId&&n.tenantScoped?sql`AND tenant_id = ${s.tenantId}`:sql``}
|
|
105
|
+
`);}getTable(s){let n=this.getTableName(s),e=this.schema[n];if(!e)throw new Error(`Table "${n}" not found in schema`);return e}buildWhereClause(s,n,e,r){let t=[];r&&n.tenantScoped&&e.tenantId&&t.push(eq(e.tenantId,r));for(let[l,a]of Object.entries(s)){let o=l,c=o.toUpperCase();if(o==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=R(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:R(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(i=>typeof i=="string"?R(i):i)}))),c==="AND"&&Array.isArray(a)){let i=a.map(u=>this.buildWhereClause(u,n,e)).flat().filter(Boolean);i.length>0&&t.push(and(...i));}else if(c==="OR"&&Array.isArray(a)){let i=a.map(u=>this.buildWhereClause(u,n,e)).flat().filter(Boolean);i.length>0&&t.push(or(...i));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=e[o]||e[o.replace(/-/g,"_")]||e[o.replace(/([A-Z])/g,"_$1").toLowerCase()]||(o==="created_at"?e.createdAt:void 0)||(o==="createdAt"?e.created_at:void 0)||(o==="updated_at"?e.updatedAt:void 0)||(o==="updatedAt"?e.updated_at:void 0);if(!i)continue;a.equals!==void 0&&t.push(eq(i,a.equals)),a.not_equals!==void 0&&t.push(ne(i,a.not_equals)),a.in&&Array.isArray(a.in)&&(a.in.length===0?t.push(sql`1 = 0`):t.push(inArray(i,a.in))),a.like!==void 0&&(this.dialect==="postgres"?t.push(ilike(i,a.like)):t.push(like(i,a.like))),a.contains!==void 0&&(this.dialect==="postgres"?t.push(ilike(i,`%${a.contains}%`)):t.push(like(i,`%${a.contains}%`))),a.greater_than!==void 0&&t.push(gt(i,a.greater_than)),a.greater_than_equal!==void 0&&t.push(gte(i,a.greater_than_equal)),a.less_than!==void 0&&t.push(lt(i,a.less_than)),a.less_than_equal!==void 0&&t.push(lte(i,a.less_than_equal));}else {let i=e[o]||e[o.replace(/-/g,"_")]||e[o.replace(/([A-Z])/g,"_$1").toLowerCase()];i&&t.push(eq(i,a));}}return t}processResult(s,n){if(!s)return null;let e={...s};for(let t of Object.keys(e))/^\d+$/.test(t)&&delete e[t];s.id&&(e.id=String(s.id));let r=c(n.fields);for(let t of r){if(!t.name)continue;let l=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();l!==t.name&&e[l]!==void 0&&e[t.name]===void 0&&(e[t.name]=e[l],delete e[l]);}for(let t of r){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(t.type)){let l=t;if(e[l.name]&&typeof e[l.name]=="string")try{let a=JSON.parse(e[l.name]);e[l.name]=a;}catch{}if(t.type==="blocks"&&e[l.name]&&Array.isArray(e[l.name])){let a=l.blocks||[];e[l.name]=d$1(e[l.name],a);}}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 a of t.tabs)for(let o of a.fields)if((o.type==="upload"||o.type==="image")&&o.name){let c=e[t.name][o.name];if(typeof c=="string")try{let i=JSON.parse(c);e[t.name][o.name]=Array.isArray(i)?i.map(u=>u&&typeof u=="object"&&typeof u.id=="string"?u.id:String(u||"")):typeof i.id=="string"?i.id:String(i.id||"");}catch{}else c&&typeof c=="object"&&(e[t.name][o.name]=Array.isArray(c)?c.map(i=>i&&typeof i=="object"&&typeof i.id=="string"?i.id:String(i||"")):typeof c.id=="string"?c.id:String(c.id||""));}continue}if(typeof e[t.name]=="string")try{let a=JSON.parse(e[t.name]);if(typeof a=="object"&&a!==null){e[t.name]=a;continue}}catch{}let l={};for(let a of t.tabs)for(let o of a.fields)if(o.name&&e[o.name]!==void 0){let c=e[o.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(o.type)){if(c&&typeof c=="string")try{c=JSON.parse(c);}catch{}(o.type==="upload"||o.type==="image")&&c&&typeof c=="object"&&(c=Array.isArray(c)?c.map(i=>i&&typeof i=="object"&&typeof i.id=="string"?i.id:String(i||"")):typeof c.id=="string"?c.id:String(c.id||""));}l[o.name]=c,delete e[o.name];}e[t.name]=l;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),a$2(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let s;this.dialect==="sqlite"?s=`
|
|
106
|
+
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
107
|
+
id text PRIMARY KEY,
|
|
108
|
+
collection_slug text NOT NULL,
|
|
109
|
+
document_id text NOT NULL,
|
|
110
|
+
tenant_id text,
|
|
111
|
+
data text NOT NULL,
|
|
112
|
+
status text NOT NULL DEFAULT 'draft',
|
|
113
|
+
autosave integer NOT NULL DEFAULT 0,
|
|
114
|
+
created_by text,
|
|
115
|
+
change_description text,
|
|
116
|
+
created_at text DEFAULT (datetime('now')),
|
|
117
|
+
updated_at text DEFAULT (datetime('now'))
|
|
118
|
+
)
|
|
119
|
+
`:s=`
|
|
120
|
+
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
121
|
+
id text PRIMARY KEY,
|
|
122
|
+
collection_slug text NOT NULL,
|
|
123
|
+
document_id text NOT NULL,
|
|
124
|
+
tenant_id text,
|
|
125
|
+
data text NOT NULL,
|
|
126
|
+
status text NOT NULL,
|
|
127
|
+
autosave integer NOT NULL DEFAULT 0,
|
|
128
|
+
created_by text,
|
|
129
|
+
change_description text,
|
|
130
|
+
created_at text NOT NULL,
|
|
131
|
+
updated_at text NOT NULL
|
|
132
|
+
)
|
|
133
|
+
`,await this.executeRaw(sql.raw(s));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 execute(s){return this.executeRaw(s)}async executeRaw(s){let n="",e=[];if(typeof s=="string")n=s;else if(s&&(s.queryChunks||s.decoder))if(this.dialect==="postgres"){let t=new PgDialect().sqlToQuery(s);n=t.sql,e=t.params;}else {let t=new SQLiteSyncDialect().sqlToQuery(s);n=t.sql,e=t.params;}else if(s&&typeof s.toSQL=="function"){let t=s.toSQL();n=t.sql,e=t.params||[];}else n=String(s);let r=this.rawClient||this.client;if(r?.prepare&&typeof r.prepare=="function"){let t=r.prepare(n);return (e.length>0?await t.bind(...e).all():await t.all()).results||[]}if(typeof this.client?.execute=="function"){let t=await this.client.execute(s);return Array.isArray(t)?t:Array.isArray(t?.rows)?t.rows:Array.isArray(t?.[0])?t[0]:[]}return []}};function me(m){return new x(m)}export{w as a,X as b,x as c,me as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {J,G}from'./chunk-
|
|
1
|
+
import {J,G}from'./chunk-FKJ7AX37.js';import {e}from'./chunk-KUY4QDAL.js';import {m as m$1}from'./chunk-3RIGRHON.js';import {a as a$1}from'./chunk-IIVBEZC2.js';import {c as c$1}from'./chunk-PMO2O77B.js';import {a}from'./chunk-IIPSXKNV.js';import {a as a$2}from'./chunk-YNBJGPIU.js';import m from'kyro:config';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
var n=null,c=null;async function T(){if(!n){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e$1=m.default||m,t=e$1.adapter,r=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||r)){let s=globalThis.DB;e$1.adapter=new c$1({type:"sqlite",client:s}),J.info("Hot-swapped to D1 DrizzleAdapter");}n=G(e$1),await n.init();let a$3=e$1.adapter,p=a$3&&a$3.dialect&&(a$3.dialect==="postgres"||a$3.dialect==="sqlite"),l=a$3&&a$3.dialect==="mongodb",o;if(p)a$3.dialect==="postgres"?o=new a({db:a$3.client}):a$3.dialect==="sqlite"&&(o=new m$1({db:a$3.rawClient||a$3.client}));else if(r&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a$1({path:s});}else l&&(o=new a$2({adapter:a$3}));if(o?.connect)try{await o.connect();}catch(s){J.warn("Auth connect warning:",s);}try{await n.loadSettings();}catch(s){J.warn("loadSettings warning:",s);}try{await e(o);}catch(s){J.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=n;}catch(e){throw n=null,c=null,J.error("Init failed, will retry:",e),e}}}async function b(e){let t=globalThis.DB?globalThis:null;try{let{env:r}=await import('cloudflare:workers');r&&(t=r);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),c||(c=T()),await c;}var w={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function _(e){return n?n.settings?.access?.apiAccess?.[e]??w[e]??true:w[e]??true}var E=async e=>{if(!n)try{await Promise.race([b(e),new Promise((t,r)=>setTimeout(()=>r(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let r=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(r===`${a}/graphql`&&typeof n.getGraphQL=="function"){if(!_("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await n.getGraphQL().fetch(e.request,e.locals);return new Response(o.body,o)}if(r.startsWith(`${a}/trpc/`)&&typeof n.getTRPC=="function"){if(!_("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await n.getTRPC().fetch(e.request,e.locals);return new Response(o.body,o)}return await(await n.getREST()).fetch(e.request,e.locals)}catch(t){let r=process.env.NODE_ENV==="production";return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:r?"An unexpected error occurred":t?.message||String(t),...r?{}:{stack:t?.stack}}),{status:500,headers:{"Content-Type":"application/json"}})}},q=E;export{n as a,b,E as c,q as d};
|
package/dist/drizzle/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk7QZYK4MT_cjs=require('../chunk-7QZYK4MT.cjs'),chunkEG4SRTYS_cjs=require('../chunk-EG4SRTYS.cjs'),chunk3A5UO6OQ_cjs=require('../chunk-3A5UO6OQ.cjs');require('../chunk-23RSKVJP.cjs'),require('../chunk-YOJOVQIH.cjs'),require('../chunk-O4PPZOVI.cjs'),require('../chunk-JJY2F6NL.cjs'),require('../chunk-OXEJCIOA.cjs'),require('../chunk-KOSR7235.cjs'),require('../chunk-JHFD3IAU.cjs');Object.defineProperty(exports,"DrizzleAdapter",{enumerable:true,get:function(){return chunk7QZYK4MT_cjs.c}});Object.defineProperty(exports,"collectionToDrizzleSchema",{enumerable:true,get:function(){return chunk7QZYK4MT_cjs.b}});Object.defineProperty(exports,"createDrizzleAdapter",{enumerable:true,get:function(){return chunk7QZYK4MT_cjs.d}});Object.defineProperty(exports,"fieldToDrizzleType",{enumerable:true,get:function(){return chunk7QZYK4MT_cjs.a}});Object.defineProperty(exports,"createDatabase",{enumerable:true,get:function(){return chunkEG4SRTYS_cjs.b}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkEG4SRTYS_cjs.c}});Object.defineProperty(exports,"seedDefaultRoles",{enumerable:true,get:function(){return chunkEG4SRTYS_cjs.d}});Object.defineProperty(exports,"PostgresAuthAdapter",{enumerable:true,get:function(){return chunk3A5UO6OQ_cjs.a}});
|
package/dist/drizzle/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{c as DrizzleAdapter,b as collectionToDrizzleSchema,d as createDrizzleAdapter,a as fieldToDrizzleType}from'../chunk-
|
|
1
|
+
export{c as DrizzleAdapter,b as collectionToDrizzleSchema,d as createDrizzleAdapter,a as fieldToDrizzleType}from'../chunk-PMO2O77B.js';export{b as createDatabase,c as runMigrations,d as seedDefaultRoles}from'../chunk-JXJTFBHG.js';export{a as PostgresAuthAdapter}from'../chunk-IIPSXKNV.js';import'../chunk-7EY3GXRA.js';import'../chunk-WLSVS3NC.js';import'../chunk-YNSKDTFG.js';import'../chunk-VLFM66BZ.js';import'../chunk-NGNXOXI5.js';import'../chunk-O4RKZQYQ.js';import'../chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|