@kyro-cms/core 0.12.58 → 0.12.61
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/{bootstrap-IGHJFNYG.js → bootstrap-WB6FDH2T.js} +1 -1
- package/dist/bootstrap-XDT4MRML.cjs +1 -0
- package/dist/{chunk-YZNFCSCE.js → chunk-26MOA3HJ.js} +10 -10
- package/dist/{chunk-ECFZEY5B.cjs → chunk-3XLXKGEU.cjs} +1 -1
- package/dist/{chunk-QLUMJS5W.cjs → chunk-4FHWIGHO.cjs} +10 -10
- package/dist/chunk-4ZWLNGLS.js +2 -0
- package/dist/{chunk-VOQUO2EZ.cjs → chunk-5DWQGEM2.cjs} +22 -22
- package/dist/{chunk-OXGJOYEO.js → chunk-637PTUHF.js} +1 -1
- package/dist/chunk-6QWX3DEB.cjs +120 -0
- package/dist/{chunk-ZMG7Z3KF.js → chunk-75BFTYBS.js} +23 -23
- package/dist/{chunk-YZEMLLD2.js → chunk-AWQGDMOE.js} +3 -3
- package/dist/chunk-D6SDGHY6.js +2 -0
- package/dist/{chunk-MP5VC5ER.cjs → chunk-FP5UK272.cjs} +1 -1
- package/dist/{chunk-AK754S3T.cjs → chunk-FSL3NLRT.cjs} +2 -2
- package/dist/{chunk-RTHJ6SS5.js → chunk-GQGFNTDZ.js} +1 -1
- package/dist/chunk-HKYBQYAJ.cjs +19 -0
- package/dist/{chunk-TDGSIF5H.cjs → chunk-JU3UAZRY.cjs} +10 -11
- package/dist/chunk-KMFLHGD5.cjs +1 -0
- package/dist/{chunk-XP56DE7A.js → chunk-KWGB3YNI.js} +90 -78
- package/dist/{chunk-KBJ4XZWF.cjs → chunk-LOP464VR.cjs} +1 -1
- package/dist/{chunk-R25WLKX4.js → chunk-N6MNQIQU.js} +101 -101
- package/dist/{chunk-BHR7OAU4.cjs → chunk-OPTVCCQQ.cjs} +101 -101
- package/dist/chunk-RDFGJHEG.js +2 -0
- package/dist/chunk-RILJCH6H.js +121 -0
- package/dist/{chunk-KCHPADCH.cjs → chunk-SOCBJPYB.cjs} +1 -1
- package/dist/chunk-T4JJVUGT.js +20 -0
- package/dist/{chunk-BAXBE4JD.js → chunk-TBTQXIHP.js} +1 -1
- package/dist/{chunk-KNOFTUQV.js → chunk-VJODUKKM.js} +11 -12
- package/dist/{chunk-VKXWJOWI.cjs → chunk-XTTGHN3D.cjs} +90 -78
- package/dist/{chunk-DUO523BH.cjs → chunk-ZHA446FA.cjs} +1 -1
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.js +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +2 -1
- package/dist/drizzle/index.d.ts +2 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/fields/index.cjs +1 -1
- package/dist/fields/index.js +1 -1
- package/dist/graphql/index.cjs +1 -1
- package/dist/graphql/index.d.cts +2 -0
- package/dist/graphql/index.d.ts +2 -0
- package/dist/graphql/index.js +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +7 -9
- package/dist/index.d.ts +7 -9
- package/dist/index.js +5 -5
- package/dist/{local-2IFOTHAA.js → local-4MZ7KOL3.js} +1 -1
- package/dist/{local-UESCNPQP.cjs → local-NDTKWJQ6.cjs} +1 -1
- package/dist/postgres-auth-adapter-SK3N3OSS.js +1 -1
- package/dist/postgres-auth-adapter-ZO6HK5AK.cjs +1 -1
- package/dist/postgres-js-GXZX3AGZ.cjs +1 -0
- package/dist/{postgres-js-4CI7FMYS.js → postgres-js-WE3NBRFO.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/{sqlite-adapter-4TPNROJK.js → sqlite-adapter-52PL52VU.js} +1 -1
- package/dist/{sqlite-adapter-ZTABLT2X.cjs → sqlite-adapter-MNNZZXGX.cjs} +1 -1
- package/dist/trpc/index.cjs +1 -1
- package/dist/trpc/index.js +1 -1
- package/package.json +2 -2
- package/dist/bootstrap-FTVBJ47D.cjs +0 -1
- package/dist/chunk-5LPNEYK5.cjs +0 -1
- package/dist/chunk-72VOOMJI.js +0 -20
- package/dist/chunk-KFEJPRC4.js +0 -265
- package/dist/chunk-PA4ZZREG.js +0 -2
- package/dist/chunk-PCVQNVSU.cjs +0 -19
- package/dist/chunk-SQBTIMWF.js +0 -2
- package/dist/chunk-X4RTM5AQ.js +0 -2
- package/dist/chunk-Z2XEW5RL.cjs +0 -264
- package/dist/postgres-js-3Y54EXVQ.cjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkGNOSG3PK_cjs=require('./chunk-GNOSG3PK.cjs'),chunkBCEE4NBZ_cjs=require('./chunk-BCEE4NBZ.cjs'),chunkLY7N3UHH_cjs=require('./chunk-LY7N3UHH.cjs'),chunkVRZC4TTF_cjs=require('./chunk-VRZC4TTF.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();var Z=class extends chunkVRZC4TTF_cjs.N{static[chunkVRZC4TTF_cjs.a]="PgViewBase"};var U=class{static[chunkVRZC4TTF_cjs.a]="PgDialect";casing;constructor(e){this.casing=new chunkGNOSG3PK_cjs.b(e?.casing);}async migrate(e,t,i){let s=typeof i=="string"?"__drizzle_migrations":i.migrationsTable??"__drizzle_migrations",n=typeof i=="string"?"drizzle":i.migrationsSchema??"drizzle",o=chunkVRZC4TTF_cjs.J`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS ${chunkVRZC4TTF_cjs.J.identifier(n)}.${chunkVRZC4TTF_cjs.J.identifier(s)} (
|
|
3
3
|
id SERIAL PRIMARY KEY,
|
|
4
4
|
hash text NOT NULL,
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {a,c,b,d}from'./chunk-SLMIYECU.js';import {a as a$1}from'./chunk-VVVCCB6R.js';import {g}from'./chunk-Y2YAKDEQ.js';import {createRequire}from'module';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g();g();g();function N(T){let e=[];for(let n of T)if(n.type==="tabs"&&"tabs"in n)for(let a of n.tabs)e.push(...N(a.fields));else n.type==="row"&&"fields"in n?e.push(...N(n.fields)):n.type==="collapsible"&&"fields"in n?e.push(...N(n.fields)):e.push(n);return e}function U(T,e){let n=e,a=T[n.name];if(n.type==="json"||n.type==="richtext"||n.type==="array"||n.type==="group"||n.type==="blocks"||n.type==="list"||n.type==="relationship-block")try{a=a?JSON.parse(a):null;}catch{a=null;}if(n.type==="checkbox"&&(a=!!a),n.type==="date"&&a)try{let o=new Date(a);isNaN(o.getTime())?a=null:a=o.toISOString();}catch{a=null;}if((n.type==="upload"||n.type==="image")&&a)try{let o=JSON.parse(a);Array.isArray(o)?a=o.map(i=>typeof i=="object"&&i!==null?i:{id:i}):a=typeof o=="object"?o:{id:o};}catch{a=typeof a=="string"?{id:a}:a;}return a}var R;function w(){return R||(R=createRequire("file:///")("node:sqlite").DatabaseSync,R)}function M(T,e){return Array.isArray(T)?T.map(n=>{if(!n||typeof n!="object")return n;let a=n.data?{...n.data}:void 0;if(!a)return n;let o=e.find(i=>i.slug===n.type||i.slug===n.slug);if(!o||!Array.isArray(o.fields))return n;for(let i of o.fields){if(i.name&&(i.type==="upload"||i.type==="image")&&a[i.name]){let t=a[i.name];Array.isArray(t)?a[i.name]=t.map(s=>typeof s=="string"?{id:s}:s):typeof t=="string"&&(a[i.name]={id:t});}if(i.type==="blocks"&&i.name&&a[i.name]){let t=i.blocks||[];a[i.name]=M(a[i.name],t);}}return {...n,data:a}}):T}function L(T,e){try{return T.prepare(`PRAGMA table_info(${e})`).all().map(a=>a.name)}catch{return []}}var O=class extends a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(!this.db)this.db=new(w())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(w())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),n=a=>{let o=e(a),i=t=>typeof t=="boolean"?t?1:0:t===void 0?null:t;return new Proxy(o,{get(t,s,r){if(s==="all")return (...c)=>t.all(...c.map(i));if(s==="get")return (...c)=>t.get(...c.map(i));if(s==="run")return (...c)=>t.run(...c.map(i));let l=Reflect.get(t,s,r);return typeof l=="function"?l.bind(t):l}})};n.__wrapped=true,this.db.prepare=n;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(e,n){let a=n||this.getTableNameFor(e.slug),o=["id TEXT PRIMARY KEY"];for(let s of N(e.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&o.push(r);}let i=N(e.fields);i.some(s=>s.name==="createdAt")||o.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),i.some(s=>s.name==="updatedAt")||o.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),i.some(s=>s.name==="status")||o.push("status TEXT DEFAULT 'draft'"),i.some(s=>s.name==="hasDraft")||o.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&o.push("tenant_id TEXT NOT NULL");let t=L(this.db,a);if(t.length===0){let s=`CREATE TABLE IF NOT EXISTS ${a} (${o.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${a}_status ON ${a}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${a}_${r.name} ON ${a}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${a}_${r.name}_unique ON ${a}(${this.col(r.name)})`);}else {let s=new Set(t);for(let r of o){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!s.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${a} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${a} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${a} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(a,true);}ensureVersionsTable(){this.db.exec(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
|
|
4
|
+
id TEXT PRIMARY KEY,
|
|
5
|
+
collection_slug TEXT NOT NULL,
|
|
6
|
+
document_id TEXT NOT NULL,
|
|
7
|
+
tenant_id TEXT,
|
|
8
|
+
version INTEGER NOT NULL,
|
|
9
|
+
status TEXT NOT NULL DEFAULT 'draft',
|
|
10
|
+
autosave INTEGER NOT NULL DEFAULT 0,
|
|
11
|
+
data TEXT NOT NULL,
|
|
12
|
+
created_by TEXT,
|
|
13
|
+
change_description TEXT,
|
|
14
|
+
published_at TEXT,
|
|
15
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
16
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
17
|
+
)
|
|
18
|
+
`);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(e,n){let a=n.replace(/^-/,""),o=L(this.db,e);if(!o.includes(a)){if(a==="created_at"&&o.includes("createdAt"))return '"createdAt"';if(a==="createdAt"&&o.includes("created_at"))return '"created_at"';if(a==="updated_at"&&o.includes("updatedAt"))return '"updatedAt"';if(a==="updatedAt"&&o.includes("updated_at"))return '"updated_at"'}return this.col(a)}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let n=e.replace("_globals_","");return {isGlobal:true,globalSlug:n,tableName:`global_${n.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:n,where:a={},sort:o,limit:i=10,page:t=1,tenantId:s,draft:r=false}=e,l=this.parseGlobalsSlug(n),c$1=l.isGlobal?this.globals.get(l.globalSlug):this.getCollection(n);this.ensureTable(c$1,l.tableName);let d$1=l.tableName,b$1=`SELECT * FROM ${d$1}`,u=[],f=[],p={...a};this.tenantContext&&c$1.tenantScoped&&(p=c({where:p},n,this.tenantContext,b).where||{});let E=c$1.fields.find(h=>h.name==="status"),m=E?.type==="select"&&Array.isArray(E.options)&&E.options.some(h=>h.value==="published");!r&&m&&(f.push("status = ?"),u.push("published")),s&&c$1.tenantScoped&&(f.push("tenant_id = ?"),u.push(s));for(let[h,y]of Object.entries(p)){if(h==="AND"||h==="OR")continue;let S=this.resolveCol(d$1,h);typeof y=="object"&&y!==null?(y.equals!==void 0&&(f.push(`${S} = ?`),u.push(y.equals)),y.in!==void 0&&(f.push(`${S} IN (${y.in.map(()=>"?").join(", ")})`),u.push(...y.in)),y.not_equals!==void 0&&(f.push(`${S} != ?`),u.push(y.not_equals))):(f.push(`${S} = ?`),u.push(y));}f.length>0&&(b$1+=` WHERE ${f.join(" AND ")}`);let g=o||"-createdAt",j=this.resolveCol(d$1,g),V=g.startsWith("-")?"DESC":"ASC";b$1+=` ORDER BY ${j} ${V}`;let X=b$1.replace("SELECT *","SELECT COUNT(*) as count"),C=this.db.prepare(X).get(...u)?.count||0;b$1+=" LIMIT ? OFFSET ?",u.push(i,(t-1)*i);let A=this.db.prepare(b$1).all(...u).map(h=>this.rowToDoc(h,c$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(A=A.filter(h=>d(h,n,this.tenantContext,b))),r&&(A=await Promise.all(A.map(async h=>{let y=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(n,h.id);if(y){let S=y.data?JSON.parse(y.data):{};return a$1({...h,...S,status:h.status,_hasUnpublishedChanges:y.status==="draft"})}return h}))),A=A.map(h=>a$1(h)),{docs:A,totalDocs:C,limit:i,totalPages:Math.ceil(C/i),page:t,pagingCounter:(t-1)*i+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(C/i),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(C/i)?t+1:null}}async findByID(e){let{collection:n,id:a,tenantId:o,draft:i=false}=e,t=this.parseGlobalsSlug(n),s=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(n);this.ensureTable(s,t.tableName);let l=`SELECT * FROM ${t.tableName} WHERE id = ?`,c=[a];if(this.tenantContext&&s.tenantScoped){let p={id:a,tenant_id:this.tenantContext.tenantId};if(!d(p,n,this.tenantContext,b))return null}let d$1=s.fields.find(p=>p.name==="status"),b$1=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(p=>p.value==="published");!i&&b$1&&(l+=" AND status = ?",c.push("published")),o&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(o));let u=this.db.prepare(l).get(...c);if(!u)return null;let f=this.rowToDoc(u,s);if(i){let p=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(n,f.id);if(p){let E=p.data?JSON.parse(p.data):{};f={...f,...E,status:f.status,_hasUnpublishedChanges:p.status==="draft"};}}return a$1(f)}async create(e){let{collection:n,data:a,tenantId:o}=e,i=this.parseGlobalsSlug(n),t=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(n);this.ensureTable(t,i.tableName);let s=i.tableName,r=i.isGlobal?i.globalSlug:a.id||this.generateId(),l=this.prepareData(a,t);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,o&&t.tenantScoped&&(l.tenant_id=o);let d=Object.keys(l),b=L(this.db,s),u={};for(let g of d)b.includes(g)&&(u[g]=l[g]);let f=Object.keys(u),p=f.map(g=>this.col(g)),E=f.map(()=>"?").join(", "),m=Object.values(u).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${p.join(", ")}) VALUES (${E})`).run(...m),this.ensureVersionsTable(),this.findByID({collection:n,id:r,tenantId:o,draft:true})}async update(e){let{collection:n,id:a,data:o,tenantId:i}=e,t=this.parseGlobalsSlug(n),s=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(n);this.ensureTable(s,t.tableName);let r=t.tableName,l=this.prepareData(o,s);l.updated_at=new Date().toISOString();let c=L(this.db,r),d={};for(let m of Object.keys(l))c.includes(m)&&(d[m]=l[m]);let u=Object.keys(d).map(m=>`${this.col(m)} = ?`).join(", "),f=Object.values(d).map(m=>m!==null&&typeof m=="object"?JSON.stringify(m):m),p=`UPDATE ${r} SET ${u} WHERE id = ?`,E=[...f,a];return i&&s.tenantScoped&&(p+=" AND tenant_id = ?",E.push(i)),this.db.prepare(p).run(...E),this.ensureVersionsTable(),this.findByID({collection:n,id:a,tenantId:i,draft:true})}async delete(e){let{collection:n,id:a,tenantId:o}=e,i=this.parseGlobalsSlug(n),t=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(n);this.ensureTable(t,i.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:n,id:a,tenantId:o,draft:true});if(!s)throw new Error(`Document not found: ${n}/${a}`);let l=`DELETE FROM ${i.tableName} WHERE id = ?`,c=[a];return o&&t.tenantScoped&&(l+=" AND tenant_id = ?",c.push(o)),this.db.prepare(l).run(...c),s}async count(e){let{collection:n,tenantId:a}=e,o=this.parseGlobalsSlug(n),i=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(n);this.ensureTable(i,o.tableName);let s=`SELECT COUNT(*) as count FROM ${o.tableName}`,r=[];return a&&i.tenantScoped&&(s+=" WHERE tenant_id = ?",r.push(a)),this.db.prepare(s).get(...r)?.count||0}async findOne(e){let n=this.parseGlobalsSlug(e.collection);if(n.isGlobal){let o=this.globals.get(n.globalSlug);if(!o)throw new Error(`Global "${n.globalSlug}" not found in adapter`);this.ensureTable(o,n.tableName);let i=`SELECT * FROM ${n.tableName}`,t=[],s=[],r=o.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!e.draft&&o.versions&&l&&t.push("status = 'published'"),t.length>0&&(i+=` WHERE ${t.join(" AND ")}`),i+=" LIMIT 1";let c=this.db.prepare(i).get(...s);if(c){let d=this.rowToDoc(c,o);if(e.draft){let b=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,n.globalSlug);if(b){let u=b.data?JSON.parse(b.data):{};d={...d,...u,status:d.status,_hasUnpublishedChanges:b.status==="draft"};}}return d}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:n,documentId:a,tenantId:o,limit:i=20,page:t=1}=e,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[n,a];o?(s.push("tenant_id = ?"),r.push(o)):s.push("tenant_id IS NULL");let l=`WHERE ${s.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,b=(t-1)*i;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,i,b).map(p=>this.rowToVersion(p)),totalDocs:d,limit:i,totalPages:Math.ceil(d/i),page:t,pagingCounter:(t-1)*i+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(d/i),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(d/i)?t+1:null}}async findVersionByID(e){this.ensureVersionsTable();let n=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return n?this.rowToVersion(n):null}async createVersion(e){this.ensureVersionsTable();let n=new Date().toISOString();if(e.autosave){let s=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[e.collection,e.documentId];e.tenantId?(s+=" AND tenant_id = ?",r.push(e.tenantId)):s+=" AND tenant_id IS NULL",s+=" LIMIT 1";let l=this.db.prepare(s).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,n,l.id);let c=await this.findVersionByID({collection:e.collection,versionId:l.id});if(c)return c}}let a=this.generateId(),i=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
|
|
19
|
+
id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
|
|
20
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(a,e.collection,e.documentId,e.tenantId??null,i,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?n:null,n,n),!e.autosave){let r=this.collections.get(e.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:r,tenantId:e.tenantId});}return await this.findVersionByID({collection:e.collection,versionId:a})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:n,documentId:a,keepLatest:o,tenantId:i}=e;if(o&&o>0){let t=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(n,a),s=0,r=[];for(let l of t)l.status==="published"||l.autosave===1||(s++,s>o&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let t=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,s=[n,a];i&&(t+=" AND tenant_id = ?",s.push(i)),this.db.prepare(t).run(...s);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,n){let a={},o=N(n.fields),i=(t,s)=>{let r=t;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return s!=null?JSON.stringify(s):null;if(r.type==="checkbox")return s?1:0;if(r.type==="number")return s!==null&&s!==""?Number(s):null;if(r.type==="upload"||r.type==="image"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify(s):String(s)}else if(t.type==="relationship"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:t.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify({relationTo:t.relationTo,value:s.id||s}):String(s)}return s};for(let t of o){if(!t.name||t.name==="id"||n.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===t.name))))continue;let r=e[t.name];r!==void 0&&(a[t.name]=i(t,r));}for(let t of n.fields)if(t.type==="tabs"&&"tabs"in t&&t.name){let s=e[t.name];if(s&&typeof s=="object"){for(let r of t.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=s[l.name];c!==void 0&&(a[l.name]=i(l,c));}}}return a}rowToDoc(e,n){let a={id:e.id};for(let o of N(n.fields)){if(!o.name||o.name==="id")continue;let i=o,t=e[i.name];if(i.type==="json"||i.type==="richtext"||i.type==="array"||i.type==="group"||i.type==="blocks"||i.type==="list"||i.type==="relationship-block")try{t=t?JSON.parse(t):null;}catch{t=null;}if(i.type==="blocks"&&t&&Array.isArray(t)){let s=i.blocks||[];t=M(t,s);}if(o.type==="checkbox"&&(t=!!t),o.type==="date"&&t)try{let s=new Date(t);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${o.name}":`,t),t=null):t=s.toISOString();}catch{t=null;}if((o.type==="upload"||o.type==="image")&&t)try{let s=JSON.parse(t);Array.isArray(s)?t=s.map(r=>typeof r=="object"&&r!==null?r:{id:r}):t=typeof s=="object"?s:{id:s};}catch{t={id:t};}if(o.type==="relationship"&&t)try{let s=JSON.parse(t);Array.isArray(s),t=s;}catch{t={relationTo:Array.isArray(o.relationTo)?o.relationTo[0]:o.relationTo,value:t};}a[o.name]=t;}for(let o of n.fields)if(!(!o.name||o.name==="id"||o.name==="row"||o.name==="collapsible")&&o.type==="tabs"&&"tabs"in o){let i={};for(let t of o.tabs)for(let s of t.fields)s.name&&s.name!=="id"&&(i[s.name]=U(e,s));a[o.name]=i;}if(n.timestamps){let o=e.createdAt||e.created_at,i=e.updatedAt||e.updated_at;if(o)try{let t=new Date(o);isNaN(t.getTime())||(a.createdAt=t.toISOString());}catch{}if(i)try{let t=new Date(i);isNaN(t.getTime())||(a.updatedAt=t.toISOString());}catch{}}n.tenantScoped&&(a.tenantId=e.tenant_id),a.status=e.status??"published",a.hasDraft=e.hasDraft?!!e.hasDraft:false;for(let o of Object.keys(a))/^\d+$/.test(o)&&delete a[o];return a}generateId(){let e=Date.now().toString(16).padStart(12,"0"),n=randomBytes(6).toString("hex");return e+n}getMediaById(e){try{let n=this.getTableNameFor("media"),a=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${n} WHERE id = ?`).get(e);if(a)return {id:a.id,url:a.url,thumbnailUrl:a.thumbnail_url||a.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((n,a)=>{let o=this.db.transaction(async()=>e({db:this.db}));try{let i=o();n(i);}catch(i){a(i);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function k(T){return new O(T||{})}export{O as a,k as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {r,q}from'./chunk-
|
|
1
|
+
import {r,q}from'./chunk-KWGB3YNI.js';import {a}from'./chunk-N6MNQIQU.js';import {g as g$1}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g$1();async function g(t){let{adminEmail:e,adminPassword:r$1,adminRole:a$1="super_admin",tenantId:n,emailConfig:o,sendWelcomeEmail:c=false}=t,s=t.authAdapter||new a({path:t.authDbPath||"./data/auth.db"});try{await s.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let u=new r().validate(r$1);if(!u.valid)return await s.disconnect?.(),{success:false,error:`Invalid password: ${u.errors.join(", ")}`};if(await s.findUserByEmail(e))return await s.disconnect?.(),{success:false,error:"Admin user already exists"};try{let i=await s.createUser({name:"Super Admin",email:e,password:r$1,role:a$1||"admin",tenantId:n});if(await s.updateUser?.(i.id,{emailVerified:!0}),c&&o){let l=new q(o),A=l.getTemplates().welcome(e.split("@")[0]);await l.send({to:e,...A});}return await s.disconnect?.(),{success:!0,user:i}}catch(i){return await s.disconnect?.(),{success:false,error:i instanceof Error?i.message:"Failed to create admin user"}}}async function M(t,e){return !await t.findUserByEmail(e)}function w(t){let e=t.KYRO_ADMIN_EMAIL,r=t.KYRO_ADMIN_PASSWORD;return !e||!r?null:{authDbPath:t.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:e,adminPassword:r,adminRole:t.KYRO_ADMIN_ROLE||"super_admin",tenantId:t.KYRO_ADMIN_TENANT_ID,emailConfig:t.SMTP_HOST?{provider:"smtp",smtp:{host:t.SMTP_HOST,port:parseInt(t.SMTP_PORT||"587",10),secure:t.SMTP_SECURE==="true",auth:{user:t.SMTP_USER||"",pass:t.SMTP_PASS||""}},from:t.SMTP_FROM||"noreply@example.com",fromName:t.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:t.KYRO_ADMIN_SEND_WELCOME==="true"}}function h(){return w(process.env)}async function E(){try{let{env:t}=await import('cloudflare:workers');if(t){let e=w(t);if(e)return e}}catch{}return null}async function x(t){let e=h()||await E();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await g(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function C(t,e=3,r=2e3){let a="";for(let n=0;n<e;n++){let o=await g(t);if(o.success||(a=o.error||"Unknown error",a.includes("already exists")))return o;n<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${a}`}}export{g as a,M as b,w as c,h as d,x as e,C as f};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {a as a$
|
|
2
|
-
g();function
|
|
3
|
-
`)}function
|
|
1
|
+
import {c,a as a$3,b,e,h}from'./chunk-JV4HJBXW.js';import {f,a as a$5}from'./chunk-637PTUHF.js';import {n,M as M$1,p,q,o,w as w$1,E,s,t,u,v}from'./chunk-HRAY65XH.js';import {a}from'./chunk-2HA6EKXX.js';import {ia,oa,fa,ma,$,ha,ca,pa,ra,J}from'./chunk-3NSZZCOJ.js';import {a as a$1,c as c$1,b as b$1,d}from'./chunk-SLMIYECU.js';import {a as a$2}from'./chunk-P6JITOFF.js';import {a as a$4}from'./chunk-VVVCCB6R.js';import {g}from'./chunk-Y2YAKDEQ.js';import {randomBytes}from'crypto';import {mkdir}from'fs/promises';import {resolve,dirname}from'path';import {createRequire}from'module';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g();var x;function Ee(){return x||(x=createRequire("file:///")("node:sqlite").DatabaseSync,x)}function we(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function de(){return randomBytes(16).toString("hex")}async function Ie(){let f$1=we();if(f$1==="sqlite"){let r=resolve(process.cwd(),"data","kyro.db");await mkdir(dirname(r),{recursive:true});let a=new(Ee())(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f$1,genId:de}}let t=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",s=a(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:f(s),dialect:f$1,genId:de}}async function $e(f,t){}async function xe(f){let{roles:t}=await import('./schema-YFMSJK2P.js');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}g();function w(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="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 t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function De(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let n=w(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
|
|
3
|
+
`)}function M(f,t){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 s=t.find(n=>n.slug===i.type||n.slug===i.slug);if(!s||!Array.isArray(s.fields))return i;for(let n of s.fields){if(n.name&&(n.type==="upload"||n.type==="image")&&e[n.name]){let r=e[n.name];Array.isArray(r)?e[n.name]=r.map(a=>typeof a=="string"?{id:a}:a):typeof r=="string"&&(e[n.name]={id:r});}if(n.type==="blocks"&&n.name&&e[n.name]){let r=n.blocks||[];e[n.name]=M(e[n.name],r);}}return {...i,data:e}}):f}g();function _(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}var P=class extends a$1{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.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=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,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 s of i.fields)if(s.type==="date"&&s.name){let n=e[s.name];n&&typeof n=="string"&&(e[s.name]=new Date(n));}for(let s of i.fields){let r=w(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let o={};for(let[c,d]of Object.entries(a)){let u=s.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[s.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let a=t[s.name];a!=null&&(e[s.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=w(s,this.dialect);(n==="timestamp"||n==="jsonb"||n==="decimal"||n==="integer"||n==="numeric"||n==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-WE3NBRFO.js')).drizzle;}catch{a$2(["postgres","drizzle-orm"]),t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-WE3NBRFO.js')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}catch{a$2(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('./d1-HPB6B253.js');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e$1=this.getTableName(t.slug),s={id:i?ia("id").primaryKey():oa("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=w(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c$1;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c$1=c(o);break;case "integer":c$1=a$3(o);break;case "decimal":case "numeric":c$1=b(o);break;case "boolean":c$1=a$3(o,{mode:"boolean"});break;case "timestamp":c$1=c(o);break;case "jsonb":c$1=c(o);break;default:c$1=c(o);}else switch(r){case "varchar":c$1=pa(o,{length:255});break;case "integer":c$1=ca(o);break;case "decimal":c$1=ha(o);break;case "boolean":c$1=$(o);break;case "timestamp":c$1=ma(o);break;case "jsonb":c$1=fa(o);break;default:c$1=ia(o);}n.required||(c$1=c$1.default(null)),s[a]=c$1;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?c("created_at").default(new Date().toISOString()):ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?c("updated_at").default(new Date().toISOString()):ma("updated_at").defaultNow()),e$1!=="users"&&e$1!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?c("status").default("draft"):pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?a$3("hasDraft",{mode:"boolean"}).default(false):$("hasDraft").default(false))),this.dialect==="sqlite"?e(e$1,s):ra(e$1,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=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=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
|
|
4
4
|
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
5
5
|
${u},
|
|
6
6
|
${r}
|
|
@@ -19,27 +19,27 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
|
|
|
19
19
|
${d?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
20
20
|
)
|
|
21
21
|
`);}if(i.length>0)if(this.dialect==="postgres")await this.executeRaw(J.raw(i.join(`;
|
|
22
|
-
`)));else for(let e of i)await this.executeRaw(J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=
|
|
23
|
-
`)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=
|
|
24
|
-
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n$1=10,page:r=1,tenantId:a,select:o,draft:c}=t,d$1=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&d$1.tenantScoped&&(m=c$1({where:m},i,this.tenantContext,b$1).where||{});let g=this.buildWhereClause(m,d$1,u,a),y=d$1.fields.find(h=>h.name==="status"),p$1=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c&&u.status&&p$1&&g.push(n(u.status,"published"));let b=this.parseSort(s),
|
|
22
|
+
`)));else for(let e of i)await this.executeRaw(J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=w(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),n=this.columnSqlType(e,i);return `"${s}" ${n} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){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(t){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(t,i){let e={},s=t.slug.startsWith("_globals_"),n=t.fields.some(c=>c.name==="createdAt"),r=t.fields.some(c=>c.name==="updatedAt"),a=t.fields.some(c=>c.name==="status"),o=t.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',n||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of t.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(t,i){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(J`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.executeRaw(J`PRAGMA table_info("${J.raw(i)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(r=>!e.has(r));if(n.length>0){let r=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(J.raw(r.join(`;
|
|
23
|
+
`)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=w(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(J.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(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=w(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
|
|
24
|
+
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n$1=10,page:r=1,tenantId:a,select:o,draft:c}=t,d$1=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&d$1.tenantScoped&&(m=c$1({where:m},i,this.tenantContext,b$1).where||{});let g=this.buildWhereClause(m,d$1,u,a),y=d$1.fields.find(h=>h.name==="status"),p$1=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c&&u.status&&p$1&&g.push(n(u.status,"published"));let b=this.parseSort(s),N=!c&&u.status&&p$1?{...m,status:"published"}:m,pe=await this.count({collection:i,where:N,tenantId:a}),he=(r-1)*n$1,j=[];try{let h=u[b.field]||u.createdAt||u.id,C=b.direction==="asc"?h:M$1(h),A=this.client.select().from(u);g.length>0&&(A=A.where(p(...g))),j=await A.orderBy(C).limit(n$1).offset(he);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let R=j.map(h=>this.processResult(h,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(R=R.filter(h=>d(h,i,this.tenantContext,b$1))),c&&(R=await Promise.all(R.map(async h=>{let C=await this.executeRaw(J`
|
|
25
25
|
SELECT * FROM kyro_versions
|
|
26
26
|
WHERE collection_slug = ${i}
|
|
27
27
|
AND document_id = ${h.id}
|
|
28
28
|
ORDER BY created_at DESC
|
|
29
29
|
LIMIT 1
|
|
30
|
-
`);if(
|
|
30
|
+
`);if(C.length>0){let A=C[0],me=typeof A.data=="string"?JSON.parse(A.data):A.data;return {...h,...me,status:h.status,_hasUnpublishedChanges:A.status==="draft"}}return h}))),{docs:R,...this.calculatePagination(r,n$1,pe)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n$1}=t,r=this.getCollection(i),a=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(!d(p,i,this.tenantContext,b$1))return null}let c=[n(a.id,o)];s&&a.tenantId&&c.push(n(a.tenantId,s));let d$1=r.fields.find(p=>p.name==="status"),u=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(p=>p.value==="published");!n$1&&a.status&&u&&c.push(n(a.status,"published"));let m=c.length>1?p(...c):c[0],g=await this.client.select().from(a).where(m);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n$1){let p=await this.executeRaw(J`
|
|
31
31
|
SELECT * FROM kyro_versions
|
|
32
32
|
WHERE collection_slug = ${i}
|
|
33
33
|
AND document_id = ${y.id}
|
|
34
34
|
ORDER BY created_at DESC
|
|
35
35
|
LIMIT 1
|
|
36
|
-
`);if(p.length>0){let b=p[0],
|
|
36
|
+
`);if(p.length>0){let b=p[0],N=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,...N,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n$1}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?_(e):e,d=[n(a.id,c)];n$1&&a.tenantId&&d.push(n(a.tenantId,n$1));let u=await this.client.update(a).set(o).where(p(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n$1=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?_(e):e,o=[n(r.id,a)];s&&r.tenantId&&o.push(n(r.tenantId,s));let c=await this.client.delete(r).where(p(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],n$1)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:J`count(*)`}).from(r);a.length>0&&(o=o.where(p(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n$1}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),m=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n$1&&c.status&&m&&(d=d.where(n(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n$1){let p=await this.executeRaw(J`
|
|
37
37
|
SELECT * FROM kyro_versions
|
|
38
38
|
WHERE collection_slug = ${i}
|
|
39
39
|
AND document_id = ${a}
|
|
40
40
|
ORDER BY created_at DESC
|
|
41
41
|
LIMIT 1
|
|
42
|
-
`);if(p.length>0){let b=p[0],
|
|
42
|
+
`);if(p.length>0){let b=p[0],N=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,...N,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),c=await this.executeRaw(J`
|
|
43
43
|
SELECT count(*) as count
|
|
44
44
|
FROM kyro_versions
|
|
45
45
|
WHERE collection_slug = ${i}
|
|
@@ -102,7 +102,7 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
|
|
|
102
102
|
WHERE collection_slug = ${t.collection}
|
|
103
103
|
AND document_id = ${t.documentId}
|
|
104
104
|
${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
|
|
105
|
-
`);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t$1,i,e,s$1){let n$1=[];s$1&&i.tenantScoped&&e.tenantId&&n$1.push(n(e.tenantId,s$1));for(let[r,a]of Object.entries(t$1))if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=
|
|
105
|
+
`);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t$1,i,e,s$1){let n$1=[];s$1&&i.tenantScoped&&e.tenantId&&n$1.push(n(e.tenantId,s$1));for(let[r,a]of Object.entries(t$1))if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=_(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:_(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(o=>typeof o=="string"?_(o):o)}))),r==="AND"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n$1.push(p(...o));}else if(r==="OR"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n$1.push(q(...o));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let o$1=e[r];if(!o$1)continue;a.equals!==void 0&&n$1.push(n(o$1,a.equals)),a.not_equals!==void 0&&n$1.push(o(o$1,a.not_equals)),a.in&&Array.isArray(a.in)&&n$1.push(w$1(o$1,a.in)),a.like!==void 0&&n$1.push(E(o$1,a.like)),a.contains!==void 0&&n$1.push(E(o$1,`%${a.contains}%`)),a.greater_than!==void 0&&n$1.push(s(o$1,a.greater_than)),a.greater_than_equal!==void 0&&n$1.push(t(o$1,a.greater_than_equal)),a.less_than!==void 0&&n$1.push(u(o$1,a.less_than)),a.less_than_equal!==void 0&&n$1.push(v(o$1,a.less_than_equal));}else {let o=e[r];o&&n$1.push(n(o,a));}return n$1}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let n=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();n!==s.name&&e[n]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[n],delete e[n]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let n=s;if(e[n.name]&&typeof e[n.name]=="string")try{let r=JSON.parse(e[n.name]);e[n.name]=r;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let r=n.blocks||[];e[n.name]=M(e[n.name],r);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let r of s.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let o=e[s.name][a.name];if(typeof o=="string")try{let c=JSON.parse(o);e[s.name][a.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[s.name][a.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[s.name]=="string")try{let r=JSON.parse(e[s.name]);if(typeof r=="object"&&r!==null){e[s.name]=r;continue}}catch{}let n={};for(let r of s.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let o=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(a.type==="upload"||a.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||""));}n[a.name]=o,delete e[a.name];}e[s.name]=n;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),a$4(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
|
|
106
106
|
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
107
107
|
id text PRIMARY KEY,
|
|
108
108
|
collection_slug text NOT NULL,
|
|
@@ -130,5 +130,4 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
|
|
|
130
130
|
created_at text NOT NULL,
|
|
131
131
|
updated_at text NOT NULL
|
|
132
132
|
)
|
|
133
|
-
`,await this.executeRaw(J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new a$
|
|
134
|
-
export{L as a,Ie as b,M as c,$e as d,de as e,Pe as f,je as g,Be as h};
|
|
133
|
+
`,await this.executeRaw(J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new a$5().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new h().sqlToQuery(t);i=n.sql,e=n.params;}else if(t&&typeof t.toSQL=="function"){let n=t.toSQL();i=n.sql,e=n.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let n=s.prepare(i);return (e.length>0?await n.bind(...e).all():await n.all()).results||[]}if(typeof this.client?.execute=="function"){let n=await this.client.execute(t);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}return []}};function We(f){return new P(f)}export{de as a,Ie as b,$e as c,xe as d,w as e,De as f,P as g,We as h};
|