@kyro-cms/core 0.12.16 → 0.12.18
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/README.md +5 -2
- package/dist/{WebhookService-i-Kl3dvf.d.cts → WebhookService-BBcCHBo8.d.cts} +1 -1
- package/dist/{WebhookService-ByrpAI4d.d.ts → WebhookService-C19xR8qE.d.ts} +1 -1
- 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/{base-iyJTfH-3.d.cts → base-C2iwjdJQ.d.cts} +2 -7
- package/dist/{base-oUSURe4_.d.ts → base-yXdYZxFK.d.ts} +2 -7
- package/dist/chunk-3Q2WUG63.cjs +2 -0
- package/dist/chunk-4RMFCTWH.js +1 -0
- package/dist/{chunk-TQNM4C7H.js → chunk-5KOQYQEE.js} +1 -1
- package/dist/{chunk-ZZIGN5PZ.js → chunk-7USZ4YRI.js} +1 -1
- package/dist/chunk-BVG6VSAJ.cjs +1 -0
- package/dist/chunk-CPGTIDGM.js +3 -0
- package/dist/chunk-DKESD4HI.js +133 -0
- package/dist/chunk-EQIAXBR4.cjs +86 -0
- package/dist/{chunk-EJDIR56C.cjs → chunk-FHJJKFAU.cjs} +1 -1
- package/dist/chunk-FVZ5RFLO.js +2 -0
- package/dist/chunk-G7SSHELM.cjs +1 -0
- package/dist/chunk-GXVCCKOL.js +1 -0
- package/dist/chunk-HRNAHWDS.js +21 -0
- package/dist/chunk-ILEZ3NYX.cjs +2 -0
- package/dist/{chunk-RY3BG3AN.cjs → chunk-JAJ6ZWAQ.cjs} +1 -1
- package/dist/chunk-LHW4R367.js +1 -0
- package/dist/chunk-ODPUHZUA.js +86 -0
- package/dist/chunk-RDKCMKBE.cjs +21 -0
- package/dist/chunk-RNCVLIKD.cjs +3 -0
- package/dist/chunk-VGQ4VUG6.js +2 -0
- package/dist/chunk-WG3UQEV7.cjs +133 -0
- package/dist/chunk-ZUVP4UK7.cjs +1 -0
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +3 -8
- package/dist/drizzle/index.d.ts +3 -8
- package/dist/drizzle/index.js +1 -1
- package/dist/graphql/index.d.cts +2 -2
- package/dist/graphql/index.d.ts +2 -2
- package/dist/{index-DVDMEql7.d.ts → index-CqR97Q2L.d.ts} +1 -1
- package/dist/{index-DNy8jbA2.d.cts → index-DRNSjOte.d.cts} +1 -1
- package/dist/index.cjs +26 -19
- package/dist/index.d.cts +200 -15
- package/dist/index.d.ts +200 -15
- package/dist/index.js +26 -19
- package/dist/mongo-auth-adapter-AIMZTNG6.js +1 -0
- package/dist/{mongo-auth-adapter-6726C5KF.cjs → mongo-auth-adapter-C62QYCYV.cjs} +1 -1
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.d.cts +6 -9
- package/dist/mongodb/index.d.ts +6 -9
- package/dist/mongodb/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.d.cts +3 -3
- package/dist/rest/index.d.ts +3 -3
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.d.cts +1 -1
- package/dist/templates/index.d.ts +1 -1
- package/dist/templates/index.js +1 -1
- package/dist/trpc/index.cjs +1 -1
- package/dist/trpc/index.d.cts +2 -2
- package/dist/trpc/index.d.ts +2 -2
- package/dist/trpc/index.js +1 -1
- package/dist/{types-BcZiluXL.d.cts → types-BjivdGbU.d.cts} +10 -7
- package/dist/{types-Dc8VAPhF.d.ts → types-CaXXmV9h.d.ts} +10 -7
- package/package.json +6 -3
- package/dist/chunk-2NJR2B4W.cjs +0 -3
- package/dist/chunk-3RR6IV5I.js +0 -133
- package/dist/chunk-3ZFRP5M2.cjs +0 -133
- package/dist/chunk-DTSYK7KK.js +0 -21
- package/dist/chunk-FGSIHWQJ.js +0 -3
- package/dist/chunk-HHH4XNNS.cjs +0 -1
- package/dist/chunk-I67R6MR5.js +0 -2
- package/dist/chunk-IQYP3DDJ.cjs +0 -21
- package/dist/chunk-ISCIUG37.js +0 -1
- package/dist/chunk-IZCTG4RG.js +0 -1
- package/dist/chunk-M5JUPA7G.cjs +0 -86
- package/dist/chunk-NI7S5JMH.js +0 -86
- package/dist/chunk-RYIEE2TH.cjs +0 -2
- package/dist/chunk-W6P4N3Z7.js +0 -2
- package/dist/chunk-WMZEULS2.cjs +0 -1
- package/dist/chunk-XUONID6O.cjs +0 -2
- package/dist/mongo-auth-adapter-U6SH4OWA.js +0 -1
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
'use strict';var chunkFHJJKFAU_cjs=require('./chunk-FHJJKFAU.cjs'),chunkD5P2IPGX_cjs=require('./chunk-D5P2IPGX.cjs'),chunkG7SSHELM_cjs=require('./chunk-G7SSHELM.cjs'),drizzleOrm=require('drizzle-orm'),pgCore=require('drizzle-orm/pg-core'),sqliteCore=require('drizzle-orm/sqlite-core'),postgresJs=require('drizzle-orm/postgres-js'),le=require('postgres'),crypto=require('crypto'),promises=require('fs/promises'),path=require('path'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var le__default=/*#__PURE__*/_interopDefault(le);function _(f){if(typeof f!="string")return f;let s=f.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)}`:f}function L(f,s="postgres"){switch(f.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 f.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 Ne(f,s="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let t of f.fields){if(t.name==="id"||t.type==="password")continue;let a=L(t,s),r=t.required,n=` ${t.name}: pg.${a}('${t.name}')`;t.unique&&(n+=".unique()"),r||(n+=".nullable()"),t.defaultValue!==void 0&&(typeof t.defaultValue=="string"?n+=`.default('${t.defaultValue}')`:typeof t.defaultValue=="boolean"?n+=`.default(${t.defaultValue})`:n+=`.default(sql\`${JSON.stringify(t.defaultValue)}\`)`),n+=",",e.push(n);}return f.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(`
|
|
2
|
+
`)}function B(f,s){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let t=s.find(a=>a.slug===i.type||a.slug===i.slug);if(!t||!Array.isArray(t.fields))return i;for(let a of t.fields){if(a.name&&(a.type==="upload"||a.type==="image")&&e[a.name]){let r=e[a.name];Array.isArray(r)?e[a.name]=r.map(n=>typeof n=="string"?{id:n}:n):typeof r=="string"&&(e[a.name]={id:r});}if(a.type==="blocks"&&a.name&&e[a.name]){let r=a.blocks||[];e[a.name]=B(e[a.name],r);}}return {...i,data:e}}):f}var x=class extends chunkFHJJKFAU_cjs.a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let i=s.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=s.type||"postgres";}else this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,i){let e=super.prepareData(s,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of i.fields)if(t.type==="date"&&t.name){let a=e[t.name];a&&typeof a=="string"&&(e[t.name]=new Date(a));}for(let t of i.fields){let r=L(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let n=s[t.name];if(n&&typeof n=="object"){let o={};for(let[c,d]of Object.entries(n)){let u=t.tabs.flatMap(g=>g.fields).find(g=>g.name===c);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&d?o[c]=Array.isArray(d)||typeof d=="object"?JSON.stringify(d):d:o[c]=d;}e[t.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&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 n=s[t.name];n!=null&&(e[t.name]=this.dialect==="sqlite"||!r?typeof n=="string"?n:JSON.stringify(n):n);}}for(let t of i.fields)if(t.name&&e[t.name]===""){let a=L(t,this.dialect);(a==="timestamp"||a==="jsonb"||a==="decimal"||a==="integer"||a==="numeric"||a==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let s,i;try{s=(await import('postgres')).default,i=(await import('drizzle-orm/postgres-js')).drizzle;}catch{chunkD5P2IPGX_cjs.a(["postgres","drizzle-orm"]),s=(await import('postgres')).default,i=(await import('drizzle-orm/postgres-js')).drizzle;}let e=s(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let s,i;try{s=(await import('better-sqlite3')).default,i=(await import('drizzle-orm/better-sqlite3')).drizzle;}catch{chunkD5P2IPGX_cjs.a(["better-sqlite3","drizzle-orm"]),s=(await import('better-sqlite3')).default,i=(await import('drizzle-orm/better-sqlite3')).drizzle;}let e=new s(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}this.connected=true;}async init(s,i=[]){if(await super.init(s,i),this.connectionString&&!this.client&&await this.connect(),this.client&&!this._schemaEnsured){for(let t of s){let a=this.getTableName(t.slug);this.schema[a]||(this.schema[a]=this.createTableFromConfig(t));}await this.ensureCollectionTables(s);let e=i.map(t=>({slug:`_globals_${t.slug}`,fields:t.fields,label:t.label}));for(let t of e){let a=this.getTableName(t.slug);this.schema[a]||(this.schema[a]=this.createTableFromConfig(t,true)),this.collections.has(t.slug)||this.collections.set(t.slug,t);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(s,i=false){let e=this.getTableName(s.slug),t={id:i?pgCore.text("id").primaryKey():pgCore.uuid("id").primaryKey().defaultRandom()};for(let a of s.fields){if(!a.name||a.name==="id"||a.type==="password")continue;let r=L(a,this.dialect),n=a.name.replace(/-/g,"_"),o=n.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=sqliteCore.text(o);break;case "integer":c=sqliteCore.integer(o);break;case "decimal":case "numeric":c=sqliteCore.numeric(o);break;case "boolean":c=sqliteCore.integer(o,{mode:"boolean"});break;case "timestamp":c=sqliteCore.text(o);break;case "jsonb":c=sqliteCore.text(o);break;default:c=sqliteCore.text(o);}else switch(r){case "varchar":c=pgCore.varchar(o,{length:255});break;case "integer":c=pgCore.integer(o);break;case "decimal":c=pgCore.decimal(o);break;case "boolean":c=pgCore.boolean(o);break;case "timestamp":c=pgCore.timestamp(o);break;case "jsonb":c=pgCore.jsonb(o);break;default:c=pgCore.text(o);}a.required||(c=c.default(null)),t[n]=c;}return t.createdAt||(t.createdAt=this.dialect==="sqlite"?sqliteCore.text("created_at").default(new Date().toISOString()):pgCore.timestamp("created_at").defaultNow()),t.updatedAt||(t.updatedAt=this.dialect==="sqlite"?sqliteCore.text("updated_at").default(new Date().toISOString()):pgCore.timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(t.status||(t.status=this.dialect==="sqlite"?sqliteCore.text("status").default("draft"):pgCore.varchar("status",{length:20}).default("draft")),t.hasDraft||(t.hasDraft=this.dialect==="sqlite"?sqliteCore.integer("hasDraft",{mode:"boolean"}).default(false):pgCore.boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteCore.sqliteTable(e,t):pgCore.pgTable(e,t)}async ensureCollectionTables(s){let i=[];for(let e of s){let t=e.slug.startsWith("_globals_"),a=this.getTableName(e.slug),r=this.generateCreateColumns(e),n=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),c=e.fields.some(u=>u.name==="status"),d=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS "${a}" (
|
|
4
|
+
${u},
|
|
5
|
+
${r}
|
|
6
|
+
${n?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
7
|
+
${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
8
|
+
${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
|
|
9
|
+
${d?"":'"hasDraft" BOOLEAN DEFAULT false'}
|
|
10
|
+
)
|
|
11
|
+
`);}else i.push(`
|
|
12
|
+
CREATE TABLE IF NOT EXISTS "${a}" (
|
|
13
|
+
"id" TEXT PRIMARY KEY,
|
|
14
|
+
${r}
|
|
15
|
+
${n?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
16
|
+
${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
17
|
+
${c?"":`"status" TEXT DEFAULT 'draft',`}
|
|
18
|
+
${d?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
19
|
+
)
|
|
20
|
+
`);}if(i.length>0)if(this.dialect==="postgres")await this.client.execute(drizzleOrm.sql.raw(i.join(`;
|
|
21
|
+
`)));else for(let e of i)await this.client.execute(drizzleOrm.sql.raw(e));for(let e of s){let t=this.getTableName(e.slug);t==="users"||t==="audit_logs"||await this.syncTableColumns(e,t);}}getColumnSqlDefinition(s,i){let e=L(s,i),t=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),a=this.columnSqlType(e,i);return `"${t}" ${a} DEFAULT NULL`}columnSqlType(s,i){if(i==="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,i){let e={},t=s.slug.startsWith("_globals_"),a=s.fields.some(c=>c.name==="createdAt"),r=s.fields.some(c=>c.name==="updatedAt"),n=s.fields.some(c=>c.name==="status"),o=s.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',a||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),n||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',a||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),n||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of s.fields){if(!c.name||c.name==="id")continue;let d=this.getColumnSqlDefinition(c,this.dialect),u=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=d;}return e}async syncTableColumns(s,i){let e;try{if(this.dialect==="postgres"){let r=await this.client.execute(drizzleOrm.sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(n=>[n.column_name,{type:n.data_type,maxLen:n.character_maximum_length}]));}else {let r=await this.client.execute(drizzleOrm.sql`PRAGMA table_info("${drizzleOrm.sql.raw(i)}")`);e=new Map(r.map(n=>[n.name,{type:n.type,maxLen:null}]));}}catch{return}let t=this.getExpectedColumnDefs(s,i),a=Object.keys(t).filter(r=>!e.has(r));if(a.length>0){let r=a.map(n=>`ALTER TABLE "${i}" ADD COLUMN ${t[n]}`);await this.executeRaw(drizzleOrm.sql.raw(r.join(`;
|
|
22
|
+
`)));}if(this.dialect==="postgres")for(let r of s.fields){if(!r.name||r.name==="id")continue;let n=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(n==="text"?await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):n==="jsonb"&&(await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(s){let i=[];for(let e of s.fields){if(!e.name||e.name==="id")continue;let t=L(e,this.dialect),a=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",n;if(this.dialect==="sqlite")switch(t){case "varchar":case "text":n=`TEXT ${r}`;break;case "integer":n=`INTEGER ${r}`;break;case "decimal":case "numeric":n=`NUMERIC ${r}`;break;case "boolean":n=`INTEGER ${r}`;break;case "timestamp":n=`TEXT ${r}`;break;case "jsonb":n=`TEXT ${r}`;break;default:n=`TEXT ${r}`;}else switch(t){case "varchar":n=`VARCHAR(255) ${r}`;break;case "integer":n=`INTEGER ${r}`;break;case "decimal":n=`DECIMAL ${r}`;break;case "boolean":n=`BOOLEAN ${r}`;break;case "timestamp":n=`TIMESTAMP ${r}`;break;case "jsonb":n=`JSONB ${r}`;break;default:n=`TEXT ${r}`;}i.push(`"${a}" ${n}`);}return i.join(`,
|
|
23
|
+
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:i,where:e={},sort:t,limit:a=10,page:r=1,tenantId:n,select:o,draft:c}=s,d=this.getCollection(i),u=this.getTable(i),h={...e};this.tenantContext&&d.tenantScoped&&(h=chunkFHJJKFAU_cjs.c({where:h},i,this.tenantContext,chunkFHJJKFAU_cjs.b).where||{});let g=this.buildWhereClause(h,d,u,n),y=d.fields.find(m=>m.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(m=>m.value==="published");!c&&u.status&&p&&g.push(drizzleOrm.eq(u.status,"published"));let A=this.parseSort(t),w=!c&&u.status&&p?{...h,status:"published"}:h,W=await this.count({collection:i,where:w,tenantId:n}),z=(r-1)*a,O=[];try{let m=u[A.field]||u.createdAt||u.id,R=A.direction==="asc"?m:drizzleOrm.desc(m),E=this.client.select().from(u);g.length>0&&(E=E.where(drizzleOrm.and(...g))),O=await E.orderBy(R).limit(a).offset(z);}catch(m){console.error("[DrizzleAdapter] Query error:",m);}let N=O.map(m=>this.processResult(m,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(m=>chunkFHJJKFAU_cjs.d(m,i,this.tenantContext,chunkFHJJKFAU_cjs.b))),c&&(N=await Promise.all(N.map(async m=>{let R=await this.executeRaw(drizzleOrm.sql`
|
|
24
|
+
SELECT * FROM kyro_versions
|
|
25
|
+
WHERE collection_slug = ${i}
|
|
26
|
+
AND document_id = ${m.id}
|
|
27
|
+
ORDER BY created_at DESC
|
|
28
|
+
LIMIT 1
|
|
29
|
+
`);if(R.length>0){let E=R[0],V=typeof E.data=="string"?JSON.parse(E.data):E.data;return {...m,...V,status:m.status}}return m}))),{docs:N,...this.calculatePagination(r,a,W)}}async findByID(s){let{collection:i,id:e,tenantId:t,draft:a}=s,r=this.getCollection(i),n=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?_(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!chunkFHJJKFAU_cjs.d(p,i,this.tenantContext,chunkFHJJKFAU_cjs.b))return null}let c=[drizzleOrm.eq(n.id,o)];t&&n.tenantId&&c.push(drizzleOrm.eq(n.tenantId,t));let d=r.fields.find(p=>p.name==="status"),u=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(p=>p.value==="published");!a&&n.status&&u&&c.push(drizzleOrm.eq(n.status,"published"));let h=c.length>1?drizzleOrm.and(...c):c[0],g=await this.client.select().from(n).where(h);if(g.length===0)return null;let y=this.processResult(g[0],r);if(a){let p=await this.executeRaw(drizzleOrm.sql`
|
|
30
|
+
SELECT * FROM kyro_versions
|
|
31
|
+
WHERE collection_slug = ${i}
|
|
32
|
+
AND document_id = ${y.id}
|
|
33
|
+
ORDER BY created_at DESC
|
|
34
|
+
LIMIT 1
|
|
35
|
+
`);if(p.length>0){let A=p[0],w=typeof A.data=="string"?JSON.parse(A.data):A.data;y={...y,...w,status:y.status};}}return y}async create(s){let{collection:i,data:e,tenantId:t}=s,a=this.getCollection(i),r=this.getTable(i),n=this.prepareData(e,a);t&&a.tenantScoped&&(n.tenantId=t);let o=await this.client.insert(r).values(n).returning();return this.processResult(o[0],a)}async update(s){let{collection:i,id:e,data:t,tenantId:a}=s,r=this.getCollection(i),n=this.getTable(i),o=this.prepareData(t,r),c=this.dialect==="postgres"&&typeof e=="string"?_(e):e,d=[drizzleOrm.eq(n.id,c)];a&&n.tenantId&&d.push(drizzleOrm.eq(n.tenantId,a));let u=await this.client.update(n).set(o).where(drizzleOrm.and(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(s){let{collection:i,id:e,tenantId:t}=s,a=this.getCollection(i),r=this.getTable(i),n=this.dialect==="postgres"&&typeof e=="string"?_(e):e,o=[drizzleOrm.eq(r.id,n)];t&&r.tenantId&&o.push(drizzleOrm.eq(r.tenantId,t));let c=await this.client.delete(r).where(drizzleOrm.and(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],a)}async count(s){let{collection:i,where:e={},tenantId:t}=s,a=this.getCollection(i),r=this.getTable(i),n=this.buildWhereClause(e,a,r,t);try{let o=this.client.select({count:drizzleOrm.sql`count(*)`}).from(r);n.length>0&&(o=o.where(drizzleOrm.and(...n)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:i,where:e={},tenantId:t,draft:a}=s;if(i.startsWith("_globals_")){let n=i.replace("_globals_",""),o=this.globals.get(n);if(!o)throw new Error(`Global "${n}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),h=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!a&&c.status&&h&&(d=d.where(drizzleOrm.eq(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(a){let p=await this.executeRaw(drizzleOrm.sql`
|
|
36
|
+
SELECT * FROM kyro_versions
|
|
37
|
+
WHERE collection_slug = ${i}
|
|
38
|
+
AND document_id = ${n}
|
|
39
|
+
ORDER BY created_at DESC
|
|
40
|
+
LIMIT 1
|
|
41
|
+
`);if(p.length>0){let A=p[0],w=typeof A.data=="string"?JSON.parse(A.data):A.data;y={...y,...w,status:y.status};}}return y}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:t=10,page:a=1,tenantId:r}=s,n=(a-1)*t,o=this.getCollection(i),c=await this.executeRaw(drizzleOrm.sql`
|
|
42
|
+
SELECT count(*) as count
|
|
43
|
+
FROM kyro_versions
|
|
44
|
+
WHERE collection_slug = ${i}
|
|
45
|
+
AND document_id = ${e}
|
|
46
|
+
AND autosave = 0
|
|
47
|
+
${r&&o.tenantScoped?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
|
|
48
|
+
`),d=parseInt(c[0]?.count||"0");return {docs:(await this.executeRaw(drizzleOrm.sql`
|
|
49
|
+
SELECT *
|
|
50
|
+
FROM kyro_versions
|
|
51
|
+
WHERE collection_slug = ${i}
|
|
52
|
+
AND document_id = ${e}
|
|
53
|
+
AND autosave = 0
|
|
54
|
+
${r&&o.tenantScoped?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
|
|
55
|
+
ORDER BY created_at DESC
|
|
56
|
+
LIMIT ${t}
|
|
57
|
+
OFFSET ${n}
|
|
58
|
+
`)).map(h=>({...h,data:typeof h.data=="string"?JSON.parse(h.data):h.data})),...this.calculatePagination(a,t,d)}}async findVersionByID(s){await this.ensureVersionsTable();let i=this.getCollection(s.collection),e=await this.executeRaw(drizzleOrm.sql`
|
|
59
|
+
SELECT * FROM kyro_versions
|
|
60
|
+
WHERE id = ${s.versionId}
|
|
61
|
+
AND collection_slug = ${s.collection}
|
|
62
|
+
${s.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
|
|
63
|
+
LIMIT 1
|
|
64
|
+
`);if(e.length===0)return null;let t=e[0];return {...t,data:typeof t.data=="string"?JSON.parse(t.data):t.data}}async createVersion(s){await this.ensureVersionsTable();let i=this.getCollection(s.collection),e=new Date().toISOString();if(s.autosave){let a=await this.executeRaw(drizzleOrm.sql`
|
|
65
|
+
SELECT * FROM kyro_versions
|
|
66
|
+
WHERE collection_slug = ${s.collection}
|
|
67
|
+
AND document_id = ${s.documentId}
|
|
68
|
+
AND autosave = 1
|
|
69
|
+
${s.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
|
|
70
|
+
LIMIT 1
|
|
71
|
+
`);if(a.length>0)return await this.executeRaw(drizzleOrm.sql`
|
|
72
|
+
UPDATE kyro_versions
|
|
73
|
+
SET data = ${JSON.stringify(s.data)},
|
|
74
|
+
status = ${s.status},
|
|
75
|
+
updated_at = ${e}
|
|
76
|
+
WHERE id = ${a[0].id}
|
|
77
|
+
`),this.findVersionByID({collection:s.collection,versionId:a[0].id,tenantId:s.tenantId})}let t=Math.random().toString(36).substring(2,15);if(await this.executeRaw(drizzleOrm.sql`
|
|
78
|
+
INSERT INTO kyro_versions (
|
|
79
|
+
id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
|
|
80
|
+
) VALUES (
|
|
81
|
+
${t}, ${s.collection}, ${s.documentId}, ${s.tenantId&&i.tenantScoped?s.tenantId:null},
|
|
82
|
+
${JSON.stringify(s.data)}, ${s.status}, ${s.autosave?1:0}, ${s.createdBy||null},
|
|
83
|
+
${s.changeDescription||null}, ${e}, ${e}
|
|
84
|
+
)
|
|
85
|
+
`),!s.autosave){let a=this.getCollection(s.collection);a.versions?.maxPerDoc&&await this.deleteVersions({collection:s.collection,documentId:s.documentId,keepLatest:a.versions.maxPerDoc,tenantId:s.tenantId});}return this.findVersionByID({collection:s.collection,versionId:t,tenantId:s.tenantId})}async updateLatestVersion(s){return this.createVersion({...s,autosave:true})}async deleteVersions(s){await this.ensureVersionsTable();let i=this.getCollection(s.collection);if(s.keepLatest){let t=(await this.executeRaw(drizzleOrm.sql`
|
|
86
|
+
SELECT id FROM kyro_versions
|
|
87
|
+
WHERE collection_slug = ${s.collection}
|
|
88
|
+
AND document_id = ${s.documentId}
|
|
89
|
+
AND autosave = 0
|
|
90
|
+
${s.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
|
|
91
|
+
ORDER BY created_at DESC
|
|
92
|
+
LIMIT ${s.keepLatest}
|
|
93
|
+
`)).map(a=>a.id);t.length>0&&await this.executeRaw(drizzleOrm.sql`
|
|
94
|
+
DELETE FROM kyro_versions
|
|
95
|
+
WHERE collection_slug = ${s.collection}
|
|
96
|
+
AND document_id = ${s.documentId}
|
|
97
|
+
AND autosave = 0
|
|
98
|
+
AND id NOT IN (${drizzleOrm.sql.join(t.map(a=>drizzleOrm.sql`${a}`),drizzleOrm.sql`, `)})
|
|
99
|
+
`);}else await this.executeRaw(drizzleOrm.sql`
|
|
100
|
+
DELETE FROM kyro_versions
|
|
101
|
+
WHERE collection_slug = ${s.collection}
|
|
102
|
+
AND document_id = ${s.documentId}
|
|
103
|
+
${s.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
|
|
104
|
+
`);}getTable(s){let i=this.getTableName(s),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(s,i,e,t){let a=[];t&&i.tenantScoped&&e.tenantId&&a.push(drizzleOrm.eq(e.tenantId,t));for(let[r,n]of Object.entries(s))if(r==="id"&&this.dialect==="postgres"&&(typeof n=="string"?n=_(n):n&&typeof n=="object"&&(n.equals!==void 0&&typeof n.equals=="string"&&(n={...n,equals:_(n.equals)}),n.in&&Array.isArray(n.in)&&(n={...n,in:n.in.map(o=>typeof o=="string"?_(o):o)}))),r==="AND"&&Array.isArray(n)){let o=n.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&a.push(drizzleOrm.and(...o));}else if(r==="OR"&&Array.isArray(n)){let o=n.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&a.push(drizzleOrm.or(...o));}else if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let o=e[r];if(!o)continue;n.equals!==void 0&&a.push(drizzleOrm.eq(o,n.equals)),n.not_equals!==void 0&&a.push(drizzleOrm.ne(o,n.not_equals)),n.in&&Array.isArray(n.in)&&a.push(drizzleOrm.inArray(o,n.in)),n.like!==void 0&&a.push(drizzleOrm.like(o,n.like)),n.contains!==void 0&&a.push(drizzleOrm.like(o,`%${n.contains}%`)),n.greater_than!==void 0&&a.push(drizzleOrm.gt(o,n.greater_than)),n.greater_than_equal!==void 0&&a.push(drizzleOrm.gte(o,n.greater_than_equal)),n.less_than!==void 0&&a.push(drizzleOrm.lt(o,n.less_than)),n.less_than_equal!==void 0&&a.push(drizzleOrm.lte(o,n.less_than_equal));}else {let o=e[r];o&&a.push(drizzleOrm.eq(o,n));}return a}processResult(s,i){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));for(let t of i.fields){if(!t.name)continue;let a=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();a!==t.name&&e[a]!==void 0&&e[t.name]===void 0&&(e[t.name]=e[a],delete e[a]);}for(let t of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(t.type)){let a=t;if(e[a.name]&&typeof e[a.name]=="string")try{let r=JSON.parse(e[a.name]);e[a.name]=r;}catch{}if(t.type==="blocks"&&e[a.name]&&Array.isArray(e[a.name])){let r=a.blocks||[];e[a.name]=B(e[a.name],r);}}if(t.type==="tabs"&&"tabs"in t&&t.name){if(typeof e[t.name]=="object"&&e[t.name]!==null&&!Array.isArray(e[t.name])){for(let r of t.tabs)for(let n of r.fields)if((n.type==="upload"||n.type==="image")&&n.name){let o=e[t.name][n.name];if(typeof o=="string")try{let c=JSON.parse(o);e[t.name][n.name]=Array.isArray(c)?c.map(d=>d&&typeof d=="object"&&typeof d.id=="string"?d.id:String(d||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else o&&typeof o=="object"&&(e[t.name][n.name]=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[t.name]=="string")try{let r=JSON.parse(e[t.name]);if(typeof r=="object"&&r!==null){e[t.name]=r;continue}}catch{}let a={};for(let r of t.tabs)for(let n of r.fields)if(n.name&&e[n.name]!==void 0){let o=e[n.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(n.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(n.type==="upload"||n.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}a[n.name]=o,delete e[n.name];}e[t.name]=a;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),chunkG7SSHELM_cjs.a(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let s;this.dialect==="sqlite"?s=`
|
|
105
|
+
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
106
|
+
id text PRIMARY KEY,
|
|
107
|
+
collection_slug text NOT NULL,
|
|
108
|
+
document_id text NOT NULL,
|
|
109
|
+
tenant_id text,
|
|
110
|
+
data text NOT NULL,
|
|
111
|
+
status text NOT NULL DEFAULT 'draft',
|
|
112
|
+
autosave integer NOT NULL DEFAULT 0,
|
|
113
|
+
created_by text,
|
|
114
|
+
change_description text,
|
|
115
|
+
created_at text DEFAULT (datetime('now')),
|
|
116
|
+
updated_at text DEFAULT (datetime('now'))
|
|
117
|
+
)
|
|
118
|
+
`:s=`
|
|
119
|
+
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
120
|
+
id text PRIMARY KEY,
|
|
121
|
+
collection_slug text NOT NULL,
|
|
122
|
+
document_id text NOT NULL,
|
|
123
|
+
tenant_id text,
|
|
124
|
+
data text NOT NULL,
|
|
125
|
+
status text NOT NULL,
|
|
126
|
+
autosave integer NOT NULL DEFAULT 0,
|
|
127
|
+
created_by text,
|
|
128
|
+
change_description text,
|
|
129
|
+
created_at text NOT NULL,
|
|
130
|
+
updated_at text NOT NULL
|
|
131
|
+
)
|
|
132
|
+
`,await this.executeRaw(drizzleOrm.sql.raw(s));try{this.dialect==="postgres"?await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(s){let i=await this.client.execute(s);return Array.isArray(i)?i:Array.isArray(i?.rows)?i.rows:Array.isArray(i?.[0])?i[0]:[]}};function Re(f){return new x(f)}var he=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-WG3UQEV7.cjs', document.baseURI).href))),ye="node:sqlite",{DatabaseSync:ge}=he(ye);function Te(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function X(){return crypto.randomBytes(16).toString("hex")}async function Ue(){let f=Te();if(f==="sqlite"){let r=path.resolve(process.cwd(),"data","kyro.db");await promises.mkdir(path.dirname(r),{recursive:true});let n=new ge(r);return n.exec("PRAGMA journal_mode = WAL"),{db:n,dialect:f,genId:X}}let s=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",i=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",t=le__default.default(s,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:postgresJs.drizzle(t),dialect:f,genId:X}}async function qe(f,s){}async function Fe(f){let{roles:s}=await import('./schema-HIUSHSUI.cjs');await f.insert(s).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
|
|
133
|
+
exports.a=L;exports.b=Ne;exports.c=x;exports.d=Re;exports.e=X;exports.f=Ue;exports.g=qe;exports.h=Fe;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkILEZ3NYX_cjs=require('./chunk-ILEZ3NYX.cjs'),chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkG7SSHELM_cjs=require('./chunk-G7SSHELM.cjs');async function W(e){let a=chunkILEZ3NYX_cjs.o(e.db),t={db:e.db,registry:e.registry,req:e.req,user:e.user,tenantId:e.tenantId,webhookService:a,settings:e.settings},n=chunkNY47CFVP_cjs.f(e.req);if(n){let r=await chunkNY47CFVP_cjs.e(n,e.db,async o=>{try{return await e.db.findByID({collection:"users",id:o})||null}catch{return null}});r.valid&&(t.user=r.user||e.user,t.tenantId=r.tenantId||e.tenantId,t.apiKey=chunkNY47CFVP_cjs.g(r));}return t}var O={_media:{create:chunkILEZ3NYX_cjs.d.MEDIA_UPLOAD,update:chunkILEZ3NYX_cjs.d.MEDIA_UPLOAD,delete:chunkILEZ3NYX_cjs.d.MEDIA_DELETE}};function C(e,a){let t=O[e];return t?t[a]:`collection.${a}`}async function D(e,a,t){if(e.webhookService)try{await e.webhookService.trigger(a,{collection:t.collection,operation:t.operation,data:t.data,previousData:t.previousData,user:e.user?{id:e.user.id,email:e.user.email,role:e.user.role}:void 0,tenantId:e.tenantId});}catch(n){console.error(`[Webhook] Failed to trigger ${a}:`,n);}}function m(e,a){if(!(!e||typeof e!="object"))for(let t of a){if(t.type==="tabs"&&Array.isArray(t.tabs)){let r=t.name?e[t.name]:e;if(r&&typeof r=="object")for(let o of t.tabs)Array.isArray(o.fields)&&m(r,o.fields);continue}if(!t.name||!(t.name in e))continue;if(e[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||t.type==="email"||t.type==="password"||t.type==="color"||(e[t.name]=null)),(t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")m(e[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let r of e[t.name])r&&typeof r=="object"&&m(r,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let r of e[t.name]){if(!r||typeof r!="object")continue;let o=r.type||r.blockType;if(!o)continue;let s=t.blocks.find(i=>i.slug===o);if(!s||!Array.isArray(s.fields))continue;let u=r.data&&typeof r.data=="object"?r.data:r;m(u,s.fields);}}}async function g(e,a,t){let n=await chunkILEZ3NYX_cjs.b(e,a,{user:t.user,req:t.req,tenantId:t.tenantId,apiKey:t.apiKey});if(!n.allowed)throw new Error(n.error||"Access denied");t.tenantId&&t.db.setTenantContext({tenantId:t.tenantId,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});}function R(e){return async a=>{let{collection:t,where:n,sort:r,limit:o,page:s,depth:u,select:i,draft:d}=a,l=e.registry.getCollection(t);if(await g(l,"read",e),l.hooks?.beforeRead)for(let y of l.hooks.beforeRead)await y({collection:t,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read",where:n});let c=d??!!e.user,b=await e.db.find({collection:t,where:n||{},sort:r,limit:o||10,page:s||1,depth:u||0,tenantId:e.tenantId,select:i,draft:c});if(l.hooks?.afterRead)for(let y of b.docs)for(let w of l.hooks.afterRead)await w({collection:t,doc:y,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read"});return await chunkILEZ3NYX_cjs.a(b.docs,l.fields,e.db,e.registry,1,u||0),chunkG7SSHELM_cjs.a(b)}}function q(e){return async a=>{let{collection:t,id:n,depth:r,select:o,draft:s}=a,u=e.registry.getCollection(t);await g(u,"read",e);let i=s??!!e.user,d=await e.db.findByID({collection:t,id:n,depth:r||0,tenantId:e.tenantId,select:o,draft:i});if(!d)throw new Error(`Document not found: ${t}/${n}`);if(u.hooks?.afterRead)for(let l of u.hooks.afterRead)await l({collection:t,doc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read",id:n});return await chunkILEZ3NYX_cjs.a([d],u.fields,e.db,e.registry,1,r||0),chunkG7SSHELM_cjs.a(d)}}function P(e){return async a=>{let{collection:t,data:n,depth:r,select:o}=a,s=e.registry.getCollection(t);await g(s,"create",e);let i=e.registry.getCreateZodSchema(t).parse(n);if(s.tenantScoped&&e.tenantId&&(i.tenantId=e.tenantId),s.hooks?.beforeValidate)for(let l of s.hooks.beforeValidate){let c=await l({collection:t,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});c&&typeof c=="object"&&!Array.isArray(c)&&Object.assign(i,c);}if(s.hooks?.beforeChange)for(let l of s.hooks.beforeChange){let c=await l({collection:t,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});c&&typeof c=="object"&&!Array.isArray(c)&&Object.assign(i,c);}let d=await e.db.create({collection:t,data:i,depth:r||0,tenantId:e.tenantId,select:o});if(s.hooks?.afterChange)for(let l of s.hooks.afterChange)await l({collection:t,doc:d,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});return await D(e,C(t,"create"),{collection:t,data:d,operation:"create"}),{doc:d}}}function v(e){return async a=>{let{collection:t,id:n,data:r,depth:o,select:s,baseUpdatedAt:u}=a,i=e.registry.getCollection(t);await g(i,"update",e);let d=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true});if(!d)throw new Error(`Document not found: ${t}/${n}`);if(u&&d.updatedAt&&u!==d.updatedAt)throw new Error(`Revision conflict: document has changed since ${u}. Current updatedAt: ${d.updatedAt}`);m(r,i.fields);let c=e.registry.getUpdateZodSchema(t).parse(r);if(i.tenantScoped&&e.tenantId&&(c.tenantId=e.tenantId),i.hooks?.beforeValidate)for(let h of i.hooks.beforeValidate){let f=await h({collection:t,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});f&&typeof f=="object"&&!Array.isArray(f)&&Object.assign(c,f);}if(i.hooks?.beforeChange)for(let h of i.hooks.beforeChange){let f=await h({collection:t,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});f&&typeof f=="object"&&!Array.isArray(f)&&Object.assign(c,f);}let b=e.req&&typeof e.req.headers?.get=="function"&&e.req.headers.get("x-draft")==="true"||a.draft===true,y=i.versions?.drafts===true,w=e.req?.query?.autosave==="true"||e.req?.url?.includes("autosave=true")||a.autosave===true,p;if(y&&b?(await e.db.createVersion({collection:t,documentId:n,data:c,status:"draft",autosave:w,createdBy:e.user?.id,tenantId:e.tenantId}),p=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true})):y?(p=await e.db.update({collection:t,id:n,data:{...c,status:"published"},depth:o||0,tenantId:e.tenantId,select:s}),await e.db.createVersion({collection:t,documentId:n,data:c,status:"published",createdBy:e.user?.id,tenantId:e.tenantId})):p=await e.db.update({collection:t,id:n,data:c,depth:o||0,tenantId:e.tenantId,select:s}),i.hooks?.afterChange)for(let h of i.hooks.afterChange)await h({collection:t,doc:p,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});return await D(e,C(t,"update"),{collection:t,data:p,previousData:d,operation:"update"}),{doc:p}}}function K(e){return async a=>{let{collection:t,id:n}=a,r=e.registry.getCollection(t);await g(r,"delete",e);let o=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true});if(!o)throw new Error(`Document not found: ${t}/${n}`);if(r.hooks?.beforeDelete)for(let u of r.hooks.beforeDelete)await u({collection:t,doc:o,req:e.req,user:e.user,tenantId:e.tenantId,operation:"delete",id:n});let s=await e.db.delete({collection:t,id:n,tenantId:e.tenantId});if(r.hooks?.afterDelete)for(let u of r.hooks.afterDelete)await u({collection:t,doc:s,req:e.req,user:e.user,tenantId:e.tenantId,operation:"delete",id:n});return await D(e,C(t,"delete"),{collection:t,data:s,previousData:o,operation:"delete"}),{doc:s,message:"Deleted successfully"}}}function E(e){return async a=>{let{collection:t,where:n}=a,r=e.registry.getCollection(t);return await g(r,"read",e),{totalDocs:await e.db.count({collection:t,where:n||{},tenantId:e.tenantId})}}}async function $(e,a,t){let n=await chunkILEZ3NYX_cjs.c(e,a,{user:t.user,req:t.req,tenantId:t.tenantId});if(!n.allowed)throw new Error(n.error||"Access denied");t.tenantId&&t.db.setTenantContext({tenantId:t.tenantId,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});}function T(e){let a={},t=e.registry.getCollections();for(let r of t){let o=r.slug;a[o]={find:R(e),findByID:q(e),create:P(e),update:v(e),delete:K(e),count:E(e)};}let n=e.registry.getGlobals();for(let r of n){let o=r.slug;a[`_globals_${o}`]={get:async s=>(await $(r,"read",e),await e.db.findOne({collection:`_globals_${o}`,where:{},tenantId:e.tenantId,depth:s?.depth,draft:s?.draft,select:s?.select})),update:async s=>{await $(r,"update",e);let i=e.registry.getZodSchema(o).parse(s.data),d=await e.db.findOne({collection:`_globals_${o}`,where:{},tenantId:e.tenantId,draft:true}),l;return d?l=await e.db.update({collection:`_globals_${o}`,id:d.id,data:i,tenantId:e.tenantId}):l=await e.db.create({collection:`_globals_${o}`,data:{...i,id:o},tenantId:e.tenantId}),l}};}return a}function V(e){if(e.settings?.access?.apiAccess?.trpcEnabled===false)throw new Error("tRPC API is disabled");return T(e)}exports.a=W;exports.b=R;exports.c=q;exports.d=P;exports.e=v;exports.f=K;exports.g=E;exports.h=T;exports.i=V;
|
package/dist/cli/index.cjs
CHANGED
|
@@ -208,4 +208,4 @@ ${e.map(t=>{let r=m(t.slug);return ` ${C(t.slug)}: {
|
|
|
208
208
|
`)}
|
|
209
209
|
};
|
|
210
210
|
}
|
|
211
|
-
`,n}function K(){return new commander.Command("generate").description("Generate TypeScript types from collection configs").option("-c, --config <path>","Path to config file or directory","./src/kyro").option("-o, --output <path>","Output file path","./src/types/kyro.d.ts").option("-w, --watch","Watch for changes and regenerate").option("--url <url>","URL of a running Kyro CMS instance (enables remote mode)").option("--api-key <key>","API key for authentication (required with --url)").action(async n=>{if(n.url){n.url||(console.error("\u274C --url is required when using --api"),process.exit(1)),n.apiKey||(console.error("\u274C --api-key is required when using --api"),process.exit(1));let o=path.resolve(n.output);try{let s=await q(n.url,n.apiKey),a=D(s),d=path.join(o,"..");fs.existsSync(d)||fs.mkdirSync(d,{recursive:!0}),fs.writeFileSync(o,a);}catch(s){console.error("\u274C Error:",s.message),process.exit(1);}return}let t=path.resolve(n.config),r=path.resolve(n.output);try{let o=await glob.glob(`${t}/**/*.{ts,js}`);o.length===0&&(console.error("\u274C No config files found at:",t),process.exit(1));let s=[];for(let i of o)try{let l=await import(i),u=Object.values(l).filter(c=>c&&c.slug&&c.fields);s.push(...u);}catch{console.warn(`\u26A0\uFE0F Could not parse: ${i}`);}s.length===0&&(console.error("\u274C No valid collection configs found"),process.exit(1));let a=T(s),d=path.join(r,"..");if(fs.existsSync(d)||fs.mkdirSync(d,{recursive:!0}),fs.writeFileSync(r,a),n.watch){let{watch:i}=await import('fs');i(t,{recursive:!0},async(l,u)=>{let c=[];for(let S of o)try{let k=await import(S+`?t=${Date.now()}`),v=Object.values(k).filter(h=>h&&h.slug&&h.fields);c.push(...v);}catch{}let f=T(c);fs.writeFileSync(r,f);});}}catch(o){console.error("\u274C Error:",o.message),process.exit(1);}})}var L=url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))),N=path.dirname(L),P="0.1.0";try{P=JSON.parse(fs.readFileSync(path.join(N,"../../package.json"),"utf-8")).version;}catch{}var p=new commander.Command;p.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(P);p.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async e=>{let{exec:n}=await import('child_process'),t=n(`astro dev --port ${e.port} --host ${e.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});t.stdout?.on("data",r=>process.stdout.write(r)),t.stderr?.on("data",r=>process.stderr.write(r)),process.on("SIGINT",()=>{t.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{t.kill("SIGTERM"),process.exit(0);});});p.addCommand(K());var g=p.command("db").description("Database management commands");g.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit generate",(n,t,r)=>{n&&(console.error("\u274C Generation failed:",n.message),process.exit(1));});});g.command("migrate").description("Run database migrations").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit migrate",(n,t,r)=>{n&&(console.error("\u274C Migration failed:",n.message),process.exit(1));});});g.command("push").description("Push schema to database (development)").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit push",(n,t,r)=>{n&&(console.error("\u274C Push failed:",n.message),process.exit(1));});});g.command("seed").description("Seed database with initial data").action(async()=>{let{exec:e}=await import('child_process');e("npx tsx src/database/drizzle/seed.ts",(n,t,r)=>{n&&(console.error("\u274C Seeding failed:",n.message),process.exit(1));});});g.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit studio",(n,t,r)=>{n&&(console.error("\u274C Studio failed:",n.message),process.exit(1));});});var F=p.command("auth").description("Authentication management commands");F.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async e=>{(!e.email||!e.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:n}=await import('../bootstrap-YLGVKTQS.cjs'),t=process.env.DATABASE_URL||"",r=t.toLowerCase().startsWith("postgres://")||t.toLowerCase().startsWith("postgresql://"),o=t.toLowerCase().startsWith("mongodb://")||t.toLowerCase().startsWith("mongodb+srv://"),s=!t||t.includes(".db")||t.includes("sqlite")||t.includes("file:"),a;if(r){let{PostgresAuthAdapter:i}=await import('../postgres-auth-adapter-JKDYYULH.cjs'),{drizzle:l}=await import('drizzle-orm/postgres-js'),{default:u}=await import('postgres'),c=u(t,{max:1,onnotice:()=>{}}),f=l(c);a=new i({db:f});}else if(o){let{MongoDBAuthAdapter:i}=await import('../mongo-auth-adapter-
|
|
211
|
+
`,n}function K(){return new commander.Command("generate").description("Generate TypeScript types from collection configs").option("-c, --config <path>","Path to config file or directory","./src/kyro").option("-o, --output <path>","Output file path","./src/types/kyro.d.ts").option("-w, --watch","Watch for changes and regenerate").option("--url <url>","URL of a running Kyro CMS instance (enables remote mode)").option("--api-key <key>","API key for authentication (required with --url)").action(async n=>{if(n.url){n.url||(console.error("\u274C --url is required when using --api"),process.exit(1)),n.apiKey||(console.error("\u274C --api-key is required when using --api"),process.exit(1));let o=path.resolve(n.output);try{let s=await q(n.url,n.apiKey),a=D(s),d=path.join(o,"..");fs.existsSync(d)||fs.mkdirSync(d,{recursive:!0}),fs.writeFileSync(o,a);}catch(s){console.error("\u274C Error:",s.message),process.exit(1);}return}let t=path.resolve(n.config),r=path.resolve(n.output);try{let o=await glob.glob(`${t}/**/*.{ts,js}`);o.length===0&&(console.error("\u274C No config files found at:",t),process.exit(1));let s=[];for(let i of o)try{let l=await import(i),u=Object.values(l).filter(c=>c&&c.slug&&c.fields);s.push(...u);}catch{console.warn(`\u26A0\uFE0F Could not parse: ${i}`);}s.length===0&&(console.error("\u274C No valid collection configs found"),process.exit(1));let a=T(s),d=path.join(r,"..");if(fs.existsSync(d)||fs.mkdirSync(d,{recursive:!0}),fs.writeFileSync(r,a),n.watch){let{watch:i}=await import('fs');i(t,{recursive:!0},async(l,u)=>{let c=[];for(let S of o)try{let k=await import(S+`?t=${Date.now()}`),v=Object.values(k).filter(h=>h&&h.slug&&h.fields);c.push(...v);}catch{}let f=T(c);fs.writeFileSync(r,f);});}}catch(o){console.error("\u274C Error:",o.message),process.exit(1);}})}var L=url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))),N=path.dirname(L),P="0.1.0";try{P=JSON.parse(fs.readFileSync(path.join(N,"../../package.json"),"utf-8")).version;}catch{}var p=new commander.Command;p.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(P);p.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async e=>{let{exec:n}=await import('child_process'),t=n(`astro dev --port ${e.port} --host ${e.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});t.stdout?.on("data",r=>process.stdout.write(r)),t.stderr?.on("data",r=>process.stderr.write(r)),process.on("SIGINT",()=>{t.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{t.kill("SIGTERM"),process.exit(0);});});p.addCommand(K());var g=p.command("db").description("Database management commands");g.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit generate",(n,t,r)=>{n&&(console.error("\u274C Generation failed:",n.message),process.exit(1));});});g.command("migrate").description("Run database migrations").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit migrate",(n,t,r)=>{n&&(console.error("\u274C Migration failed:",n.message),process.exit(1));});});g.command("push").description("Push schema to database (development)").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit push",(n,t,r)=>{n&&(console.error("\u274C Push failed:",n.message),process.exit(1));});});g.command("seed").description("Seed database with initial data").action(async()=>{let{exec:e}=await import('child_process');e("npx tsx src/database/drizzle/seed.ts",(n,t,r)=>{n&&(console.error("\u274C Seeding failed:",n.message),process.exit(1));});});g.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit studio",(n,t,r)=>{n&&(console.error("\u274C Studio failed:",n.message),process.exit(1));});});var F=p.command("auth").description("Authentication management commands");F.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async e=>{(!e.email||!e.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:n}=await import('../bootstrap-YLGVKTQS.cjs'),t=process.env.DATABASE_URL||"",r=t.toLowerCase().startsWith("postgres://")||t.toLowerCase().startsWith("postgresql://"),o=t.toLowerCase().startsWith("mongodb://")||t.toLowerCase().startsWith("mongodb+srv://"),s=!t||t.includes(".db")||t.includes("sqlite")||t.includes("file:"),a;if(r){let{PostgresAuthAdapter:i}=await import('../postgres-auth-adapter-JKDYYULH.cjs'),{drizzle:l}=await import('drizzle-orm/postgres-js'),{default:u}=await import('postgres'),c=u(t,{max:1,onnotice:()=>{}}),f=l(c);a=new i({db:f});}else if(o){let{MongoDBAuthAdapter:i}=await import('../mongo-auth-adapter-C62QYCYV.cjs'),{MongoClient:l}=await import('mongodb'),u=new l(t);await u.connect();let c=u.db();a=new i({db:c});}else {let{SQLiteAuthAdapter:i}=await import('../sqlite-adapter-PLD57WOH.cjs'),l=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";a=new i({path:l});}a.connect&&await a.connect();let d=await n({authAdapter:a,adminEmail:e.email,adminPassword:e.password,adminRole:e.role});a.disconnect&&await a.disconnect(),d.success||(console.error("\u274C Failed to create admin:",d.error),process.exit(1));}catch(n){console.error("\u274C Bootstrap failed:",n),process.exit(1);}});p.command("health").description("Check system health").action(async()=>{let e=process.env.DATABASE_URL||"",n=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),t=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),r=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:");if(n)try{let{default:o}=await import('postgres'),s=o(e,{max:1,onnotice:()=>{}});await s.unsafe("SELECT 1"),await s.end();}catch{}else if(t)try{let{MongoClient:o}=await import('mongodb'),s=new o(e);await s.connect(),await s.db().admin().ping(),await s.close();}catch{}else if(r)try{let o=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:s}=await import('fs');s(o);}catch{}});p.parse();process.argv.slice(2).length||p.outputHelp();
|
package/dist/cli/index.js
CHANGED
|
@@ -208,4 +208,4 @@ ${e.map(t=>{let r=m(t.slug);return ` ${C(t.slug)}: {
|
|
|
208
208
|
`)}
|
|
209
209
|
};
|
|
210
210
|
}
|
|
211
|
-
`,n}function K(){return new Command("generate").description("Generate TypeScript types from collection configs").option("-c, --config <path>","Path to config file or directory","./src/kyro").option("-o, --output <path>","Output file path","./src/types/kyro.d.ts").option("-w, --watch","Watch for changes and regenerate").option("--url <url>","URL of a running Kyro CMS instance (enables remote mode)").option("--api-key <key>","API key for authentication (required with --url)").action(async n=>{if(n.url){n.url||(console.error("\u274C --url is required when using --api"),process.exit(1)),n.apiKey||(console.error("\u274C --api-key is required when using --api"),process.exit(1));let o=resolve(n.output);try{let s=await q(n.url,n.apiKey),a=D(s),d=join(o,"..");existsSync(d)||mkdirSync(d,{recursive:!0}),writeFileSync(o,a);}catch(s){console.error("\u274C Error:",s.message),process.exit(1);}return}let t=resolve(n.config),r=resolve(n.output);try{let o=await glob(`${t}/**/*.{ts,js}`);o.length===0&&(console.error("\u274C No config files found at:",t),process.exit(1));let s=[];for(let i of o)try{let l=await import(i),u=Object.values(l).filter(c=>c&&c.slug&&c.fields);s.push(...u);}catch{console.warn(`\u26A0\uFE0F Could not parse: ${i}`);}s.length===0&&(console.error("\u274C No valid collection configs found"),process.exit(1));let a=T(s),d=join(r,"..");if(existsSync(d)||mkdirSync(d,{recursive:!0}),writeFileSync(r,a),n.watch){let{watch:i}=await import('fs');i(t,{recursive:!0},async(l,u)=>{let c=[];for(let S of o)try{let k=await import(S+`?t=${Date.now()}`),v=Object.values(k).filter(h=>h&&h.slug&&h.fields);c.push(...v);}catch{}let f=T(c);writeFileSync(r,f);});}}catch(o){console.error("\u274C Error:",o.message),process.exit(1);}})}var L=fileURLToPath(import.meta.url),N=dirname(L),P="0.1.0";try{P=JSON.parse(readFileSync(join(N,"../../package.json"),"utf-8")).version;}catch{}var p=new Command;p.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(P);p.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async e=>{let{exec:n}=await import('child_process'),t=n(`astro dev --port ${e.port} --host ${e.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});t.stdout?.on("data",r=>process.stdout.write(r)),t.stderr?.on("data",r=>process.stderr.write(r)),process.on("SIGINT",()=>{t.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{t.kill("SIGTERM"),process.exit(0);});});p.addCommand(K());var g=p.command("db").description("Database management commands");g.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit generate",(n,t,r)=>{n&&(console.error("\u274C Generation failed:",n.message),process.exit(1));});});g.command("migrate").description("Run database migrations").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit migrate",(n,t,r)=>{n&&(console.error("\u274C Migration failed:",n.message),process.exit(1));});});g.command("push").description("Push schema to database (development)").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit push",(n,t,r)=>{n&&(console.error("\u274C Push failed:",n.message),process.exit(1));});});g.command("seed").description("Seed database with initial data").action(async()=>{let{exec:e}=await import('child_process');e("npx tsx src/database/drizzle/seed.ts",(n,t,r)=>{n&&(console.error("\u274C Seeding failed:",n.message),process.exit(1));});});g.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit studio",(n,t,r)=>{n&&(console.error("\u274C Studio failed:",n.message),process.exit(1));});});var F=p.command("auth").description("Authentication management commands");F.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async e=>{(!e.email||!e.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:n}=await import('../bootstrap-A3OBR3YI.js'),t=process.env.DATABASE_URL||"",r=t.toLowerCase().startsWith("postgres://")||t.toLowerCase().startsWith("postgresql://"),o=t.toLowerCase().startsWith("mongodb://")||t.toLowerCase().startsWith("mongodb+srv://"),s=!t||t.includes(".db")||t.includes("sqlite")||t.includes("file:"),a;if(r){let{PostgresAuthAdapter:i}=await import('../postgres-auth-adapter-33QOIRXT.js'),{drizzle:l}=await import('drizzle-orm/postgres-js'),{default:u}=await import('postgres'),c=u(t,{max:1,onnotice:()=>{}}),f=l(c);a=new i({db:f});}else if(o){let{MongoDBAuthAdapter:i}=await import('../mongo-auth-adapter-
|
|
211
|
+
`,n}function K(){return new Command("generate").description("Generate TypeScript types from collection configs").option("-c, --config <path>","Path to config file or directory","./src/kyro").option("-o, --output <path>","Output file path","./src/types/kyro.d.ts").option("-w, --watch","Watch for changes and regenerate").option("--url <url>","URL of a running Kyro CMS instance (enables remote mode)").option("--api-key <key>","API key for authentication (required with --url)").action(async n=>{if(n.url){n.url||(console.error("\u274C --url is required when using --api"),process.exit(1)),n.apiKey||(console.error("\u274C --api-key is required when using --api"),process.exit(1));let o=resolve(n.output);try{let s=await q(n.url,n.apiKey),a=D(s),d=join(o,"..");existsSync(d)||mkdirSync(d,{recursive:!0}),writeFileSync(o,a);}catch(s){console.error("\u274C Error:",s.message),process.exit(1);}return}let t=resolve(n.config),r=resolve(n.output);try{let o=await glob(`${t}/**/*.{ts,js}`);o.length===0&&(console.error("\u274C No config files found at:",t),process.exit(1));let s=[];for(let i of o)try{let l=await import(i),u=Object.values(l).filter(c=>c&&c.slug&&c.fields);s.push(...u);}catch{console.warn(`\u26A0\uFE0F Could not parse: ${i}`);}s.length===0&&(console.error("\u274C No valid collection configs found"),process.exit(1));let a=T(s),d=join(r,"..");if(existsSync(d)||mkdirSync(d,{recursive:!0}),writeFileSync(r,a),n.watch){let{watch:i}=await import('fs');i(t,{recursive:!0},async(l,u)=>{let c=[];for(let S of o)try{let k=await import(S+`?t=${Date.now()}`),v=Object.values(k).filter(h=>h&&h.slug&&h.fields);c.push(...v);}catch{}let f=T(c);writeFileSync(r,f);});}}catch(o){console.error("\u274C Error:",o.message),process.exit(1);}})}var L=fileURLToPath(import.meta.url),N=dirname(L),P="0.1.0";try{P=JSON.parse(readFileSync(join(N,"../../package.json"),"utf-8")).version;}catch{}var p=new Command;p.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(P);p.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async e=>{let{exec:n}=await import('child_process'),t=n(`astro dev --port ${e.port} --host ${e.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});t.stdout?.on("data",r=>process.stdout.write(r)),t.stderr?.on("data",r=>process.stderr.write(r)),process.on("SIGINT",()=>{t.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{t.kill("SIGTERM"),process.exit(0);});});p.addCommand(K());var g=p.command("db").description("Database management commands");g.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit generate",(n,t,r)=>{n&&(console.error("\u274C Generation failed:",n.message),process.exit(1));});});g.command("migrate").description("Run database migrations").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit migrate",(n,t,r)=>{n&&(console.error("\u274C Migration failed:",n.message),process.exit(1));});});g.command("push").description("Push schema to database (development)").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit push",(n,t,r)=>{n&&(console.error("\u274C Push failed:",n.message),process.exit(1));});});g.command("seed").description("Seed database with initial data").action(async()=>{let{exec:e}=await import('child_process');e("npx tsx src/database/drizzle/seed.ts",(n,t,r)=>{n&&(console.error("\u274C Seeding failed:",n.message),process.exit(1));});});g.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:e}=await import('child_process');e("npx drizzle-kit studio",(n,t,r)=>{n&&(console.error("\u274C Studio failed:",n.message),process.exit(1));});});var F=p.command("auth").description("Authentication management commands");F.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async e=>{(!e.email||!e.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:n}=await import('../bootstrap-A3OBR3YI.js'),t=process.env.DATABASE_URL||"",r=t.toLowerCase().startsWith("postgres://")||t.toLowerCase().startsWith("postgresql://"),o=t.toLowerCase().startsWith("mongodb://")||t.toLowerCase().startsWith("mongodb+srv://"),s=!t||t.includes(".db")||t.includes("sqlite")||t.includes("file:"),a;if(r){let{PostgresAuthAdapter:i}=await import('../postgres-auth-adapter-33QOIRXT.js'),{drizzle:l}=await import('drizzle-orm/postgres-js'),{default:u}=await import('postgres'),c=u(t,{max:1,onnotice:()=>{}}),f=l(c);a=new i({db:f});}else if(o){let{MongoDBAuthAdapter:i}=await import('../mongo-auth-adapter-AIMZTNG6.js'),{MongoClient:l}=await import('mongodb'),u=new l(t);await u.connect();let c=u.db();a=new i({db:c});}else {let{SQLiteAuthAdapter:i}=await import('../sqlite-adapter-EXYRYZEV.js'),l=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";a=new i({path:l});}a.connect&&await a.connect();let d=await n({authAdapter:a,adminEmail:e.email,adminPassword:e.password,adminRole:e.role});a.disconnect&&await a.disconnect(),d.success||(console.error("\u274C Failed to create admin:",d.error),process.exit(1));}catch(n){console.error("\u274C Bootstrap failed:",n),process.exit(1);}});p.command("health").description("Check system health").action(async()=>{let e=process.env.DATABASE_URL||"",n=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),t=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),r=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:");if(n)try{let{default:o}=await import('postgres'),s=o(e,{max:1,onnotice:()=>{}});await s.unsafe("SELECT 1"),await s.end();}catch{}else if(t)try{let{MongoClient:o}=await import('mongodb'),s=new o(e);await s.connect(),await s.db().admin().ping(),await s.close();}catch{}else if(r)try{let o=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:s}=await import('fs');s(o);}catch{}});p.parse();process.argv.slice(2).length||p.outputHelp();
|
package/dist/client.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as AdminConfig, a as AuthConfig, C as CollectionConfig, G as GlobalConfig, I as ImageSize, K as KyroConfig, U as UploadConfig, V as VersionConfig } from './types-
|
|
1
|
+
export { A as AdminConfig, a as AuthConfig, C as CollectionConfig, G as GlobalConfig, I as ImageSize, K as KyroConfig, U as UploadConfig, V as VersionConfig } from './types-BjivdGbU.cjs';
|
|
2
2
|
export { A as ALL_FIELD_TYPES, a as ArrayField, B as BaseField, b as Block, c as BlockAdmin, d as BlockImage, e as BlocksField, C as CheckboxField, f as CodeField, g as CollapsibleField, h as ColorField, D as DateField, i as DeclarativeCondition, E as EmailField, F as Field, j as FieldAdmin, k as FieldType, G as GroupField, I as IconField, l as ImageField, J as JSONField, M as MarkdownField, N as NumberField, P as PasswordField, R as RadioField, m as RelationshipField, n as RichTextBlock, o as RichTextField, p as RowField, S as SecretField, q as SelectField, T as TabsField, r as TextField, s as TextareaField, U as UploadField } from './types-euTszc-1.cjs';
|
|
3
3
|
export { r as renderRichText, a as richTextStyles } from './richtext-DrhORshE.cjs';
|
|
4
4
|
export { A as AuthAdapter, a as AuthResult, S as AuthSession, b as AuthTokenConfig, c as AuthUser, J as JWTPayload, L as LoginCredentials, R as RegisterData, S as Session, U as UserRole } from './types-CpjuXbe7.cjs';
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as AdminConfig, a as AuthConfig, C as CollectionConfig, G as GlobalConfig, I as ImageSize, K as KyroConfig, U as UploadConfig, V as VersionConfig } from './types-
|
|
1
|
+
export { A as AdminConfig, a as AuthConfig, C as CollectionConfig, G as GlobalConfig, I as ImageSize, K as KyroConfig, U as UploadConfig, V as VersionConfig } from './types-CaXXmV9h.js';
|
|
2
2
|
export { A as ALL_FIELD_TYPES, a as ArrayField, B as BaseField, b as Block, c as BlockAdmin, d as BlockImage, e as BlocksField, C as CheckboxField, f as CodeField, g as CollapsibleField, h as ColorField, D as DateField, i as DeclarativeCondition, E as EmailField, F as Field, j as FieldAdmin, k as FieldType, G as GroupField, I as IconField, l as ImageField, J as JSONField, M as MarkdownField, N as NumberField, P as PasswordField, R as RadioField, m as RelationshipField, n as RichTextBlock, o as RichTextField, p as RowField, S as SecretField, q as SelectField, T as TabsField, r as TextField, s as TextareaField, U as UploadField } from './types-euTszc-1.js';
|
|
3
3
|
export { r as renderRichText, a as richTextStyles } from './richtext-DrhORshE.js';
|
|
4
4
|
export { A as AuthAdapter, a as AuthResult, S as AuthSession, b as AuthTokenConfig, c as AuthUser, J as JWTPayload, L as LoginCredentials, R as RegisterData, S as Session, U as UserRole } from './types-CpjuXbe7.js';
|
package/dist/drizzle/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';require('../chunk-4ORJMSJU.cjs');var
|
|
1
|
+
'use strict';require('../chunk-4ORJMSJU.cjs');var chunkWG3UQEV7_cjs=require('../chunk-WG3UQEV7.cjs'),chunkGYQMNXXW_cjs=require('../chunk-GYQMNXXW.cjs');require('../chunk-MIOMMB23.cjs'),require('../chunk-FHJJKFAU.cjs'),require('../chunk-D5P2IPGX.cjs'),require('../chunk-G7SSHELM.cjs'),require('../chunk-Q3Q7BJVQ.cjs'),require('../chunk-AHSFSERC.cjs');Object.defineProperty(exports,"DrizzleAdapter",{enumerable:true,get:function(){return chunkWG3UQEV7_cjs.c}});Object.defineProperty(exports,"collectionToDrizzleSchema",{enumerable:true,get:function(){return chunkWG3UQEV7_cjs.b}});Object.defineProperty(exports,"createDatabase",{enumerable:true,get:function(){return chunkWG3UQEV7_cjs.f}});Object.defineProperty(exports,"createDrizzleAdapter",{enumerable:true,get:function(){return chunkWG3UQEV7_cjs.d}});Object.defineProperty(exports,"fieldToDrizzleType",{enumerable:true,get:function(){return chunkWG3UQEV7_cjs.a}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkWG3UQEV7_cjs.g}});Object.defineProperty(exports,"seedDefaultRoles",{enumerable:true,get:function(){return chunkWG3UQEV7_cjs.h}});Object.defineProperty(exports,"PostgresAuthAdapter",{enumerable:true,get:function(){return chunkGYQMNXXW_cjs.a}});
|
package/dist/drizzle/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AbstractBaseAdapter } from '../base-
|
|
2
|
-
import { C as CollectionConfig, G as GlobalConfig, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs } from '../types-
|
|
1
|
+
import { A as AbstractBaseAdapter } from '../base-C2iwjdJQ.cjs';
|
|
2
|
+
import { C as CollectionConfig, G as GlobalConfig, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindOneArgs } from '../types-BjivdGbU.cjs';
|
|
3
3
|
import { F as Field } from '../types-euTszc-1.cjs';
|
|
4
4
|
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
5
5
|
import { A as AuthAdapter, U as UserRole, c as AuthUser, S as Session, e as AuditLogFilter, d as AuditLog } from '../types-CpjuXbe7.cjs';
|
|
@@ -40,12 +40,7 @@ declare class DrizzleAdapter extends AbstractBaseAdapter {
|
|
|
40
40
|
where?: Record<string, any>;
|
|
41
41
|
tenantId?: string;
|
|
42
42
|
}): Promise<number>;
|
|
43
|
-
findOne(args:
|
|
44
|
-
collection: string;
|
|
45
|
-
where: Record<string, any>;
|
|
46
|
-
tenantId?: string;
|
|
47
|
-
draft?: boolean;
|
|
48
|
-
}): Promise<any>;
|
|
43
|
+
findOne(args: FindOneArgs): Promise<any>;
|
|
49
44
|
findVersions(args: any): Promise<FindResult<any>>;
|
|
50
45
|
findVersionByID(args: {
|
|
51
46
|
collection: string;
|
package/dist/drizzle/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AbstractBaseAdapter } from '../base-
|
|
2
|
-
import { C as CollectionConfig, G as GlobalConfig, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs } from '../types-
|
|
1
|
+
import { A as AbstractBaseAdapter } from '../base-yXdYZxFK.js';
|
|
2
|
+
import { C as CollectionConfig, G as GlobalConfig, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindOneArgs } from '../types-CaXXmV9h.js';
|
|
3
3
|
import { F as Field } from '../types-euTszc-1.js';
|
|
4
4
|
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
5
5
|
import { A as AuthAdapter, U as UserRole, c as AuthUser, S as Session, e as AuditLogFilter, d as AuditLog } from '../types-CpjuXbe7.js';
|
|
@@ -40,12 +40,7 @@ declare class DrizzleAdapter extends AbstractBaseAdapter {
|
|
|
40
40
|
where?: Record<string, any>;
|
|
41
41
|
tenantId?: string;
|
|
42
42
|
}): Promise<number>;
|
|
43
|
-
findOne(args:
|
|
44
|
-
collection: string;
|
|
45
|
-
where: Record<string, any>;
|
|
46
|
-
tenantId?: string;
|
|
47
|
-
draft?: boolean;
|
|
48
|
-
}): Promise<any>;
|
|
43
|
+
findOne(args: FindOneArgs): Promise<any>;
|
|
49
44
|
findVersions(args: any): Promise<FindResult<any>>;
|
|
50
45
|
findVersionByID(args: {
|
|
51
46
|
collection: string;
|
package/dist/drizzle/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import'../chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'../chunk-
|
|
1
|
+
import'../chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'../chunk-DKESD4HI.js';export{a as PostgresAuthAdapter}from'../chunk-RHCWCG3O.js';import'../chunk-OG7CNQGU.js';import'../chunk-5KOQYQEE.js';import'../chunk-6SPPR5JZ.js';import'../chunk-4RMFCTWH.js';import'../chunk-KDNYHLD2.js';import'../chunk-5J6HXUF6.js';
|
package/dist/graphql/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { GraphQLSchema } from 'graphql';
|
|
2
2
|
export { printSchema } from 'graphql';
|
|
3
|
-
import { B as BaseAdapter,
|
|
4
|
-
import { R as Registry } from '../index-
|
|
3
|
+
import { B as BaseAdapter, k as User, R as Request } from '../types-BjivdGbU.cjs';
|
|
4
|
+
import { R as Registry } from '../index-DRNSjOte.cjs';
|
|
5
5
|
import '../types-euTszc-1.cjs';
|
|
6
6
|
import 'zod';
|
|
7
7
|
|
package/dist/graphql/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { GraphQLSchema } from 'graphql';
|
|
2
2
|
export { printSchema } from 'graphql';
|
|
3
|
-
import { B as BaseAdapter,
|
|
4
|
-
import { R as Registry } from '../index-
|
|
3
|
+
import { B as BaseAdapter, k as User, R as Request } from '../types-CaXXmV9h.js';
|
|
4
|
+
import { R as Registry } from '../index-CqR97Q2L.js';
|
|
5
5
|
import '../types-euTszc-1.js';
|
|
6
6
|
import 'zod';
|
|
7
7
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CollectionConfig, G as GlobalConfig,
|
|
1
|
+
import { C as CollectionConfig, G as GlobalConfig, j as KyroPlugin } from './types-CaXXmV9h.js';
|
|
2
2
|
import { F as Field } from './types-euTszc-1.js';
|
|
3
3
|
import { ZodTypeAny } from 'zod';
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CollectionConfig, G as GlobalConfig,
|
|
1
|
+
import { C as CollectionConfig, G as GlobalConfig, j as KyroPlugin } from './types-BjivdGbU.cjs';
|
|
2
2
|
import { F as Field } from './types-euTszc-1.cjs';
|
|
3
3
|
import { ZodTypeAny } from 'zod';
|
|
4
4
|
|