@kyro-cms/core 0.12.66 → 0.12.67
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 +1 -1
- package/dist/{WebhookService-Bue85CZq.d.ts → WebhookService-CGNSlclW.d.ts} +1 -1
- package/dist/{WebhookService-B-jb55_P.d.cts → WebhookService-CIQPD1We.d.cts} +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-CU2tjpsX.d.cts → base-Ds06wMo9.d.cts} +2 -2
- package/dist/{base-CTeNj4rw.d.ts → base-DxDXLyWe.d.ts} +2 -2
- package/dist/chunk-2XUD2OPJ.js +121 -0
- package/dist/{chunk-LVHWORV4.js → chunk-4YCI3HBD.js} +3 -3
- package/dist/chunk-7LLCXY5O.cjs +19 -0
- package/dist/{chunk-N4HVIKNF.cjs → chunk-B3BSVEFC.cjs} +1 -1
- package/dist/{chunk-EQDO2U65.cjs → chunk-CTIQQ3ZX.cjs} +17 -17
- package/dist/{chunk-EUOOUY3K.js → chunk-EJN3FJWB.js} +2 -2
- package/dist/{chunk-6VMTMVGV.cjs → chunk-GH4OVDIL.cjs} +1 -1
- package/dist/{chunk-YLJYAAXH.js → chunk-HEGM2QMX.js} +18 -18
- package/dist/{chunk-YFUH3SST.cjs → chunk-IL2TMAHB.cjs} +25 -25
- package/dist/chunk-JCEJ4VTN.js +20 -0
- package/dist/chunk-JSTDCK3Z.js +2 -0
- package/dist/chunk-MSC4G2HF.cjs +2 -0
- package/dist/{chunk-AXT3QPVM.js → chunk-MVZSSTCV.js} +26 -26
- package/dist/chunk-MYGHZQMO.cjs +1 -0
- package/dist/{chunk-KCQBV3MA.js → chunk-VTOL3URF.js} +1 -1
- package/dist/chunk-ZED7JS6I.cjs +120 -0
- package/dist/client.cjs +1 -1
- package/dist/client.d.cts +3 -3
- package/dist/client.d.ts +3 -3
- package/dist/client.js +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +3 -3
- package/dist/drizzle/index.d.ts +3 -3
- package/dist/drizzle/index.js +1 -1
- package/dist/fields/index.d.cts +2 -2
- package/dist/fields/index.d.ts +2 -2
- package/dist/graphql/index.d.cts +3 -3
- package/dist/graphql/index.d.ts +3 -3
- package/dist/{index-HNBjfQpn.d.cts → index-BHYGO3yF.d.cts} +2 -2
- package/dist/{index-Bz9JqRGI.d.cts → index-D7kt5jT_.d.ts} +12 -1
- package/dist/{index-Bz9JqRGI.d.ts → index-DPtCjn94.d.cts} +12 -1
- package/dist/{index-DowyndWK.d.ts → index-DTy4k1oU.d.ts} +2 -2
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +12 -12
- package/dist/index.d.ts +12 -12
- package/dist/index.js +6 -6
- package/dist/{local-4MZ7KOL3.js → local-DPLKZQA3.js} +1 -1
- package/dist/{local-NDTKWJQ6.cjs → local-S5VA7IXE.cjs} +1 -1
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.d.cts +3 -3
- package/dist/mongodb/index.d.ts +3 -3
- package/dist/mongodb/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.d.cts +4 -4
- package/dist/rest/index.d.ts +4 -4
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.d.cts +2 -2
- package/dist/templates/index.d.ts +2 -2
- package/dist/templates/index.js +1 -1
- package/dist/trpc/index.d.cts +3 -3
- package/dist/trpc/index.d.ts +3 -3
- package/dist/{types-euTszc-1.d.cts → types-BKPEavuy.d.cts} +3 -0
- package/dist/{types-euTszc-1.d.ts → types-BKPEavuy.d.ts} +3 -0
- package/dist/{types-ComJeXGL.d.cts → types-BWJx6zzm.d.ts} +38 -14
- package/dist/{types-COokblgr.d.ts → types-CeAQSR87.d.cts} +38 -14
- package/package.json +2 -2
- package/dist/chunk-6KERPHAL.cjs +0 -2
- package/dist/chunk-FX3Y3ZT5.cjs +0 -120
- package/dist/chunk-HKYBQYAJ.cjs +0 -19
- package/dist/chunk-RVWHGHST.js +0 -121
- package/dist/chunk-T4JJVUGT.js +0 -20
|
@@ -1,80 +1,80 @@
|
|
|
1
|
-
'use strict';var chunk7ACHOBWY_cjs=require('./chunk-7ACHOBWY.cjs'),chunkSOCBJPYB_cjs=require('./chunk-SOCBJPYB.cjs'),chunkBCEE4NBZ_cjs=require('./chunk-BCEE4NBZ.cjs'),chunkVRZC4TTF_cjs=require('./chunk-VRZC4TTF.cjs'),chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();function b(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
|
|
2
|
-
`)}function
|
|
1
|
+
'use strict';var chunk7ACHOBWY_cjs=require('./chunk-7ACHOBWY.cjs'),chunkSOCBJPYB_cjs=require('./chunk-SOCBJPYB.cjs'),chunkBCEE4NBZ_cjs=require('./chunk-BCEE4NBZ.cjs'),chunkVRZC4TTF_cjs=require('./chunk-VRZC4TTF.cjs'),chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();function b(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=b(s,t),o=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),o||(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(`
|
|
2
|
+
`)}function j(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 o=e[n.name];Array.isArray(o)?e[n.name]=o.map(a=>typeof a=="string"?{id:a}:a):typeof o=="string"&&(e[n.name]={id:o});}if(n.type==="blocks"&&n.name&&e[n.name]){let o=n.blocks||[];e[n.name]=j(e[n.name],o);}}return {...i,data:e}}):f}function C(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 O=class extends chunkVQ53TFYA_cjs.a{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 o=b(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let r={};for(let[l,c]of Object.entries(a)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===l);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&c?r[l]=Array.isArray(c)||typeof c=="object"?JSON.stringify(c):c:r[l]=c;}e[s.name]=this.dialect==="sqlite"||!o?JSON.stringify(r):r;}}else if(o&&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"||!o?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=b(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-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-GXZX3AGZ.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["postgres","drizzle-orm"]),t=(await import('./src-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-GXZX3AGZ.cjs')).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-5IISPX34.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-5IISPX34.cjs')).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-5ZQJOFDX.cjs');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=this.getTableName(t.slug),s={id:i?chunkVRZC4TTF_cjs.ia("id").primaryKey():chunkVRZC4TTF_cjs.oa("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let o=b(n,this.dialect),a=n.name.replace(/-/g,"_"),r=a.replace(/([A-Z])/g,"_$1").toLowerCase(),l;if(this.dialect==="sqlite")switch(o){case "varchar":case "text":l=chunk7ACHOBWY_cjs.c(r);break;case "integer":l=chunk7ACHOBWY_cjs.a(r);break;case "decimal":case "numeric":l=chunk7ACHOBWY_cjs.b(r);break;case "boolean":l=chunk7ACHOBWY_cjs.a(r,{mode:"boolean"});break;case "timestamp":l=chunk7ACHOBWY_cjs.c(r);break;case "jsonb":l=chunk7ACHOBWY_cjs.c(r);break;default:l=chunk7ACHOBWY_cjs.c(r);}else switch(o){case "varchar":l=chunkVRZC4TTF_cjs.pa(r,{length:255});break;case "integer":l=chunkVRZC4TTF_cjs.ca(r);break;case "decimal":l=chunkVRZC4TTF_cjs.ha(r);break;case "boolean":l=chunkVRZC4TTF_cjs.$(r);break;case "timestamp":l=chunkVRZC4TTF_cjs.ma(r);break;case "jsonb":l=chunkVRZC4TTF_cjs.fa(r);break;default:l=chunkVRZC4TTF_cjs.ia(r);}n.required||(l=l.default(null)),s[a]=l;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("created_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("updated_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("status").default("draft"):chunkVRZC4TTF_cjs.pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.a("hasDraft",{mode:"boolean"}).default(false):chunkVRZC4TTF_cjs.$("hasDraft").default(false))),this.dialect==="sqlite"?chunk7ACHOBWY_cjs.e(e,s):chunkVRZC4TTF_cjs.ra(e,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),o=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),r=e.fields.some(u=>u.name==="updatedAt"),l=e.fields.some(u=>u.name==="status"),c=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(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
4
4
|
${u},
|
|
5
|
-
${
|
|
5
|
+
${o}
|
|
6
6
|
${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
7
|
-
${
|
|
7
|
+
${r?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
8
8
|
${l?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
|
|
9
|
-
${
|
|
9
|
+
${c?"":'"hasDraft" BOOLEAN DEFAULT false'}
|
|
10
10
|
)
|
|
11
11
|
`);}else i.push(`
|
|
12
12
|
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
13
13
|
"id" TEXT PRIMARY KEY,
|
|
14
|
-
${
|
|
14
|
+
${o}
|
|
15
15
|
${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
16
|
-
${
|
|
16
|
+
${r?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
17
17
|
${l?"":`"status" TEXT DEFAULT 'draft',`}
|
|
18
|
-
${
|
|
18
|
+
${c?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
19
19
|
)
|
|
20
20
|
`);}if(i.length>0)if(this.dialect==="postgres")await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(i.join(`;
|
|
21
|
-
`)));else for(let e of i)await this.executeRaw(chunkVRZC4TTF_cjs.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=b(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(l=>l.name==="createdAt"),
|
|
22
|
-
`)));}if(this.dialect==="postgres")for(let
|
|
23
|
-
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n=10,page:
|
|
21
|
+
`)));else for(let e of i)await this.executeRaw(chunkVRZC4TTF_cjs.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=b(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(l=>l.name==="createdAt"),o=t.fields.some(l=>l.name==="updatedAt"),a=t.fields.some(l=>l.name==="status"),r=t.fields.some(l=>l.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'),o||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),r||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),o||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),r||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let l of t.fields){if(!l.name||l.name==="id")continue;let c=this.getColumnSqlDefinition(l,this.dialect),u=l.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=c;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let o=await this.executeRaw(chunkVRZC4TTF_cjs.J`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(o.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let o=await this.executeRaw(chunkVRZC4TTF_cjs.J`PRAGMA table_info("${chunkVRZC4TTF_cjs.J.raw(i)}")`);e=new Map(o.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(o=>!e.has(o));if(n.length>0){let o=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(o.join(`;
|
|
22
|
+
`)));}if(this.dialect==="postgres")for(let o of t.fields){if(!o.name||o.name==="id")continue;let a=b(o,this.dialect),r=o.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),l=e.get(r);!l||l.type!=="character varying"||(a==="text"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${r}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${r}" DROP DEFAULT`)),await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${r}" TYPE JSONB USING (CASE WHEN "${r}" IS NULL THEN NULL WHEN "${r}"::text ~ '^\\s*\\{' THEN "${r}"::jsonb ELSE jsonb_build_object('id', "${r}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=b(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),o=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${o}`;break;case "integer":a=`INTEGER ${o}`;break;case "decimal":case "numeric":a=`NUMERIC ${o}`;break;case "boolean":a=`INTEGER ${o}`;break;case "timestamp":a=`TEXT ${o}`;break;case "jsonb":a=`TEXT ${o}`;break;default:a=`TEXT ${o}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${o}`;break;case "integer":a=`INTEGER ${o}`;break;case "decimal":a=`DECIMAL ${o}`;break;case "boolean":a=`BOOLEAN ${o}`;break;case "timestamp":a=`TIMESTAMP ${o}`;break;case "jsonb":a=`JSONB ${o}`;break;default:a=`TEXT ${o}`;}i.push(`"${n}" ${a}`);}return i.join(`,
|
|
23
|
+
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n=10,page:o=1,tenantId:a,select:r,draft:l}=t,c=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&c.tenantScoped&&(m=chunkVQ53TFYA_cjs.c({where:m},i,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let g=this.buildWhereClause(m,c,u,a),y=c.fields.find(h=>h.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!l&&u.status&&p&&g.push(chunkBCEE4NBZ_cjs.n(u.status,"published"));let E=this.parseSort(s),A=!l&&u.status&&p?{...m,status:"published"}:m,ue=await this.count({collection:i,where:A,tenantId:a}),fe=(o-1)*n,z=[];try{let h=u[E.field]||u.createdAt||u.id,$=E.direction==="asc"?h:chunkBCEE4NBZ_cjs.M(h),D=this.client.select().from(u);g.length>0&&(D=D.where(chunkBCEE4NBZ_cjs.p(...g))),z=await D.orderBy($).limit(n).offset(fe);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let R=z.map(h=>this.processResult(h,c));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(R=R.filter(h=>chunkVQ53TFYA_cjs.d(h,i,this.tenantContext,chunkVQ53TFYA_cjs.b))),l&&(R=await Promise.all(R.map(async h=>{let $=await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
24
24
|
SELECT * FROM kyro_versions
|
|
25
25
|
WHERE collection_slug = ${i}
|
|
26
26
|
AND document_id = ${h.id}
|
|
27
27
|
ORDER BY created_at DESC
|
|
28
28
|
LIMIT 1
|
|
29
|
-
`);if($.length>0){let
|
|
29
|
+
`);if($.length>0){let D=$[0],w=D.data;for(;typeof w=="string";)try{w=JSON.parse(w);}catch{break}return (!w||typeof w!="object"||Array.isArray(w))&&(w={}),{...h,...w,status:h.status,_hasUnpublishedChanges:D.status==="draft"}}return h}))),{docs:R,...this.calculatePagination(o,n,ue)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n}=t,o=this.getCollection(i),a=this.getTable(i),r=this.dialect==="postgres"&&typeof e=="string"?C(e):e;if(this.tenantContext&&o.tenantScoped){let p={id:r,tenantId:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(p,i,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let l=[chunkBCEE4NBZ_cjs.n(a.id,r)];s&&a.tenantId&&l.push(chunkBCEE4NBZ_cjs.n(a.tenantId,s));let c=o.fields.find(p=>p.name==="status"),u=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(p=>p.value==="published");!n&&a.status&&u&&l.push(chunkBCEE4NBZ_cjs.n(a.status,"published"));let m=l.length>1?chunkBCEE4NBZ_cjs.p(...l):l[0],g=await this.client.select().from(a).where(m);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
30
30
|
SELECT * FROM kyro_versions
|
|
31
31
|
WHERE collection_slug = ${i}
|
|
32
32
|
AND document_id = ${y.id}
|
|
33
33
|
ORDER BY created_at DESC
|
|
34
34
|
LIMIT 1
|
|
35
|
-
`);if(p.length>0){let E=p[0],A=E.data;for(;typeof A=="string";)try{A=JSON.parse(A);}catch{break}(!A||typeof A!="object"||Array.isArray(A))&&(A={}),y={...y,...A,status:y.status,_hasUnpublishedChanges:E.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),
|
|
35
|
+
`);if(p.length>0){let E=p[0],A=E.data;for(;typeof A=="string";)try{A=JSON.parse(A);}catch{break}(!A||typeof A!="object"||Array.isArray(A))&&(A={}),y={...y,...A,status:y.status,_hasUnpublishedChanges:E.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),o=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let r=await this.client.insert(o).values(a).returning();return this.processResult(r[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n}=t,o=this.getCollection(i),a=this.getTable(i),r=this.prepareData(s,o),l=this.dialect==="postgres"&&typeof e=="string"?C(e):e,c=[chunkBCEE4NBZ_cjs.n(a.id,l)];n&&a.tenantId&&c.push(chunkBCEE4NBZ_cjs.n(a.tenantId,n));let u=await this.client.update(a).set(r).where(chunkBCEE4NBZ_cjs.p(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],o)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n=this.getCollection(i),o=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?C(e):e,r=[chunkBCEE4NBZ_cjs.n(o.id,a)];s&&o.tenantId&&r.push(chunkBCEE4NBZ_cjs.n(o.tenantId,s));let l=await this.client.delete(o).where(chunkBCEE4NBZ_cjs.p(...r)).returning();if(l.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(l[0],n)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),o=this.getTable(i),a=this.buildWhereClause(e,n,o,s);try{let r=this.client.select({count:chunkVRZC4TTF_cjs.J`count(*)`}).from(o);a.length>0&&(r=r.where(chunkBCEE4NBZ_cjs.p(...a)));let l=await r;return Number(l[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),r=this.globals.get(a);if(!r)throw new Error(`Global "${a}" not found`);let l=this.getTable(i),c=this.client.select().from(l),u=r.fields.find(p=>p.name==="status"),m=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n&&l.status&&m&&(c=c.where(chunkBCEE4NBZ_cjs.n(l.status,"published")));let g=await c.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
36
36
|
SELECT * FROM kyro_versions
|
|
37
37
|
WHERE collection_slug = ${i}
|
|
38
38
|
AND document_id = ${a}
|
|
39
39
|
ORDER BY created_at DESC
|
|
40
40
|
LIMIT 1
|
|
41
|
-
`);if(p.length>0){let E=p[0],A=typeof E.data=="string"?JSON.parse(E.data):E.data;y={...y,...A,status:y.status,_hasUnpublishedChanges:E.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:
|
|
41
|
+
`);if(p.length>0){let E=p[0],A=typeof E.data=="string"?JSON.parse(E.data):E.data;y={...y,...A,status:y.status,_hasUnpublishedChanges:E.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:o}=t,a=(n-1)*s,r=this.getCollection(i),l=await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
42
42
|
SELECT count(*) as count
|
|
43
43
|
FROM kyro_versions
|
|
44
44
|
WHERE collection_slug = ${i}
|
|
45
45
|
AND document_id = ${e}
|
|
46
46
|
AND autosave = 0
|
|
47
|
-
${r
|
|
48
|
-
`),
|
|
47
|
+
${o&&r.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${o}`:chunkVRZC4TTF_cjs.J``}
|
|
48
|
+
`),c=parseInt(l[0]?.count||"0");return {docs:(await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
49
49
|
SELECT *
|
|
50
50
|
FROM kyro_versions
|
|
51
51
|
WHERE collection_slug = ${i}
|
|
52
52
|
AND document_id = ${e}
|
|
53
53
|
AND autosave = 0
|
|
54
|
-
${r
|
|
54
|
+
${o&&r.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${o}`:chunkVRZC4TTF_cjs.J``}
|
|
55
55
|
ORDER BY created_at DESC
|
|
56
56
|
LIMIT ${s}
|
|
57
57
|
OFFSET ${a}
|
|
58
|
-
`)).map(m=>({...m,data:typeof m.data=="string"?JSON.parse(m.data):m.data})),...this.calculatePagination(n,s,
|
|
58
|
+
`)).map(m=>({...m,data:typeof m.data=="string"?JSON.parse(m.data):m.data})),...this.calculatePagination(n,s,c)}}async findVersionByID(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
59
59
|
SELECT * FROM kyro_versions
|
|
60
60
|
WHERE id = ${t.versionId}
|
|
61
61
|
AND collection_slug = ${t.collection}
|
|
62
62
|
${t.tenantId&&i.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${t.tenantId}`:chunkVRZC4TTF_cjs.J``}
|
|
63
63
|
LIMIT 1
|
|
64
|
-
`);if(e.length===0)return null;let s=e[0];return {...s,data:typeof s.data=="string"?JSON.parse(s.data):s.data}}async createVersion(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=new Date().toISOString();if(t.autosave){let
|
|
64
|
+
`);if(e.length===0)return null;let s=e[0];return {...s,data:typeof s.data=="string"?JSON.parse(s.data):s.data}}async createVersion(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=new Date().toISOString();if(t.autosave){let o=await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
65
65
|
SELECT * FROM kyro_versions
|
|
66
66
|
WHERE collection_slug = ${t.collection}
|
|
67
67
|
AND document_id = ${t.documentId}
|
|
68
68
|
AND autosave = 1
|
|
69
69
|
${t.tenantId&&i.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${t.tenantId}`:chunkVRZC4TTF_cjs.J``}
|
|
70
70
|
LIMIT 1
|
|
71
|
-
`);if(
|
|
71
|
+
`);if(o.length>0)return await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
72
72
|
UPDATE kyro_versions
|
|
73
73
|
SET data = ${JSON.stringify(t.data)},
|
|
74
74
|
status = ${t.status},
|
|
75
75
|
updated_at = ${e}
|
|
76
|
-
WHERE id = ${
|
|
77
|
-
`),this.findVersionByID({collection:t.collection,versionId:
|
|
76
|
+
WHERE id = ${o[0].id}
|
|
77
|
+
`),this.findVersionByID({collection:t.collection,versionId:o[0].id,tenantId:t.tenantId})}let s=Math.random().toString(36).substring(2,15),n=typeof t.data=="string"?t.data:JSON.stringify(t.data);if(await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
78
78
|
INSERT INTO kyro_versions (
|
|
79
79
|
id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
|
|
80
80
|
) VALUES (
|
|
@@ -82,7 +82,7 @@
|
|
|
82
82
|
${n}, ${t.status}, ${t.autosave?1:0}, ${t.createdBy||null},
|
|
83
83
|
${t.changeDescription||null}, ${e}, ${e}
|
|
84
84
|
)
|
|
85
|
-
`),!t.autosave){let
|
|
85
|
+
`),!t.autosave){let o=this.getCollection(t.collection);o.versions?.maxPerDoc&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:o.versions.maxPerDoc,tenantId:t.tenantId});}return this.findVersionByID({collection:t.collection,versionId:s,tenantId:t.tenantId})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection);if(t.keepLatest){let s=(await this.executeRaw(chunkVRZC4TTF_cjs.J`
|
|
86
86
|
SELECT id FROM kyro_versions
|
|
87
87
|
WHERE collection_slug = ${t.collection}
|
|
88
88
|
AND document_id = ${t.documentId}
|
|
@@ -101,7 +101,7 @@
|
|
|
101
101
|
WHERE collection_slug = ${t.collection}
|
|
102
102
|
AND document_id = ${t.documentId}
|
|
103
103
|
${t.tenantId&&i.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${t.tenantId}`:chunkVRZC4TTF_cjs.J``}
|
|
104
|
-
`);}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,i,e,s){let n=[];s&&i.tenantScoped&&e.tenantId&&n.push(chunkBCEE4NBZ_cjs.n(e.tenantId,s));for(let[
|
|
104
|
+
`);}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,i,e,s){let n=[];s&&i.tenantScoped&&e.tenantId&&n.push(chunkBCEE4NBZ_cjs.n(e.tenantId,s));for(let[o,a]of Object.entries(t)){let r=o,l=r.toUpperCase();if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=C(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:C(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(c=>typeof c=="string"?C(c):c)}))),l==="AND"&&Array.isArray(a)){let c=a.map(u=>this.buildWhereClause(u,i,e)).flat().filter(Boolean);c.length>0&&n.push(chunkBCEE4NBZ_cjs.p(...c));}else if(l==="OR"&&Array.isArray(a)){let c=a.map(u=>this.buildWhereClause(u,i,e)).flat().filter(Boolean);c.length>0&&n.push(chunkBCEE4NBZ_cjs.q(...c));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=e[r]||e[r.replace(/-/g,"_")]||e[r.replace(/([A-Z])/g,"_$1").toLowerCase()]||(r==="created_at"?e.createdAt:void 0)||(r==="createdAt"?e.created_at:void 0)||(r==="updated_at"?e.updatedAt:void 0)||(r==="updatedAt"?e.updated_at:void 0);if(!c)continue;a.equals!==void 0&&n.push(chunkBCEE4NBZ_cjs.n(c,a.equals)),a.not_equals!==void 0&&n.push(chunkBCEE4NBZ_cjs.o(c,a.not_equals)),a.in&&Array.isArray(a.in)&&(a.in.length===0?n.push(chunkVRZC4TTF_cjs.J`1 = 0`):n.push(chunkBCEE4NBZ_cjs.w(c,a.in))),a.like!==void 0&&(this.dialect==="postgres"?n.push(chunkBCEE4NBZ_cjs.G(c,a.like)):n.push(chunkBCEE4NBZ_cjs.E(c,a.like))),a.contains!==void 0&&(this.dialect==="postgres"?n.push(chunkBCEE4NBZ_cjs.G(c,`%${a.contains}%`)):n.push(chunkBCEE4NBZ_cjs.E(c,`%${a.contains}%`))),a.greater_than!==void 0&&n.push(chunkBCEE4NBZ_cjs.s(c,a.greater_than)),a.greater_than_equal!==void 0&&n.push(chunkBCEE4NBZ_cjs.t(c,a.greater_than_equal)),a.less_than!==void 0&&n.push(chunkBCEE4NBZ_cjs.u(c,a.less_than)),a.less_than_equal!==void 0&&n.push(chunkBCEE4NBZ_cjs.v(c,a.less_than_equal));}else {let c=e[r]||e[r.replace(/-/g,"_")]||e[r.replace(/([A-Z])/g,"_$1").toLowerCase()];c&&n.push(chunkBCEE4NBZ_cjs.n(c,a));}}return n}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 o=JSON.parse(e[n.name]);e[n.name]=o;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let o=n.blocks||[];e[n.name]=j(e[n.name],o);}}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 o of s.tabs)for(let a of o.fields)if((a.type==="upload"||a.type==="image")&&a.name){let r=e[s.name][a.name];if(typeof r=="string")try{let l=JSON.parse(r);e[s.name][a.name]=Array.isArray(l)?l.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof l.id=="string"?l.id:String(l.id||"");}catch{}else r&&typeof r=="object"&&(e[s.name][a.name]=Array.isArray(r)?r.map(l=>l&&typeof l=="object"&&typeof l.id=="string"?l.id:String(l||"")):typeof r.id=="string"?r.id:String(r.id||""));}continue}if(typeof e[s.name]=="string")try{let o=JSON.parse(e[s.name]);if(typeof o=="object"&&o!==null){e[s.name]=o;continue}}catch{}let n={};for(let o of s.tabs)for(let a of o.fields)if(a.name&&e[a.name]!==void 0){let r=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(r&&typeof r=="string")try{r=JSON.parse(r);}catch{}(a.type==="upload"||a.type==="image")&&r&&typeof r=="object"&&(r=Array.isArray(r)?r.map(l=>l&&typeof l=="object"&&typeof l.id=="string"?l.id:String(l||"")):typeof r.id=="string"?r.id:String(r.id||""));}n[a.name]=r,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()),chunkZOVH6QT5_cjs.a(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
|
|
105
105
|
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
106
106
|
id text PRIMARY KEY,
|
|
107
107
|
collection_slug text NOT NULL,
|
|
@@ -129,4 +129,4 @@
|
|
|
129
129
|
created_at text NOT NULL,
|
|
130
130
|
updated_at text NOT NULL
|
|
131
131
|
)
|
|
132
|
-
`,await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(chunkVRZC4TTF_cjs.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 chunkSOCBJPYB_cjs.a().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new chunk7ACHOBWY_cjs.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
|
|
132
|
+
`,await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(chunkVRZC4TTF_cjs.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 chunkSOCBJPYB_cjs.a().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new chunk7ACHOBWY_cjs.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 pe(f){return new O(f)}exports.a=b;exports.b=de;exports.c=O;exports.d=pe;
|
|
@@ -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 E(m){let t=[];for(let a of m)if(a.type==="tabs"&&"tabs"in a)for(let n of a.tabs)t.push(...E(n.fields));else a.type==="row"&&"fields"in a?t.push(...E(a.fields)):a.type==="collapsible"&&"fields"in a?t.push(...E(a.fields)):t.push(a);return t}function P(m,t){let a=t,n=m[a.name];if(a.type==="json"||a.type==="richtext"||a.type==="array"||a.type==="group"||a.type==="blocks"||a.type==="list"||a.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(a.type==="checkbox"&&(n=!!n),a.type==="date"&&n)try{let i=new Date(n);isNaN(i.getTime())?n=null:n=i.toISOString();}catch{n=null;}if((a.type==="upload"||a.type==="image")&&n)try{let i=JSON.parse(n);Array.isArray(i)?n=i.map(o=>typeof o=="object"&&o!==null?o:{id:o}):n=typeof i=="object"?i:{id:i};}catch{n=typeof n=="string"?{id:n}:n;}return n}var R;function U(){return R||(R=createRequire("file:///")("node:sqlite").DatabaseSync,R)}function j(m,t){return Array.isArray(m)?m.map(a=>{if(!a||typeof a!="object")return a;let n=a.data?{...a.data}:void 0;if(!n)return a;let i=t.find(o=>o.slug===a.type||o.slug===a.slug);if(!i||!Array.isArray(i.fields))return a;for(let o of i.fields){if(o.name&&(o.type==="upload"||o.type==="image")&&n[o.name]){let e=n[o.name];Array.isArray(e)?n[o.name]=e.map(s=>typeof s=="string"?{id:s}:s):typeof e=="string"&&(n[o.name]={id:e});}if(o.type==="blocks"&&o.name&&n[o.name]){let e=o.blocks||[];n[o.name]=j(n[o.name],e);}}return {...a,data:n}}):m}function I(m,t){try{return m.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}catch{return []}}var L=class extends a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(t){super(),this.path=t.path,t.db?this.db=t.db:this.db=null;}async connect(){if(!this.db)this.db=new(U())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(U())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let t=this.db.prepare.bind(this.db),a=n=>{let i=t(n),o=e=>typeof e=="boolean"?e?1:0:e===void 0?null:e;return new Proxy(i,{get(e,s,r){if(s==="all")return (...c)=>e.all(...c.map(o));if(s==="get")return (...c)=>e.get(...c.map(o));if(s==="run")return (...c)=>e.run(...c.map(o));let l=Reflect.get(e,s,r);return typeof l=="function"?l.bind(e):l}})};a.__wrapped=true,this.db.prepare=a;}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(t,a){let n=a||this.getTableNameFor(t.slug),i=["id TEXT PRIMARY KEY"];for(let s of E(t.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&i.push(r);}let o=E(t.fields);o.some(s=>s.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="status")||i.push("status TEXT DEFAULT 'draft'"),o.some(s=>s.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),t.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let e=I(this.db,n);if(e.length===0){let s=`CREATE TABLE IF NOT EXISTS ${n} (${i.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let r of E(t.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${r.name} ON ${n}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${r.name}_unique ON ${n}(${this.col(r.name)})`);}else {let s=new Set(e);for(let r of i){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!s.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(n,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(t,a){let n=a.replace(/^-/,""),i=I(this.db,t);if(!i.includes(n)){if(n==="created_at"&&i.includes("createdAt"))return '"createdAt"';if(n==="createdAt"&&i.includes("created_at"))return '"created_at"';if(n==="updated_at"&&i.includes("updatedAt"))return '"updatedAt"';if(n==="updatedAt"&&i.includes("updated_at"))return '"updated_at"'}return this.col(n)}col(t){return `"${t}"`}fieldToSQL(t){switch(t.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(t.name)+" TEXT";case "number":return this.col(t.name)+" REAL";case "checkbox":return this.col(t.name)+" INTEGER DEFAULT 0";case "date":return this.col(t.name)+" TEXT";case "select":case "radio":return this.col(t.name)+" TEXT";case "relationship":case "upload":return this.col(t.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(t.name)+" TEXT";default:return null}}parseGlobalsSlug(t){if(t.startsWith("_globals_")){let a=t.replace("_globals_","");return {isGlobal:true,globalSlug:a,tableName:`global_${a.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(t)}}buildWhere(t,a){let n=[],i=[];for(let[o,e]of Object.entries(t)){let s=o.toUpperCase();if((s==="AND"||s==="OR")&&Array.isArray(e)){let l=[];for(let c of e)if(typeof c=="object"&&c!==null){let d=this.buildWhere(c,a);d.clause&&(l.push(`(${d.clause})`),i.push(...d.params));}l.length>0&&n.push(`(${l.join(` ${s} `)})`);continue}let r=this.resolveCol(a,o);typeof e=="object"&&e!==null&&!Array.isArray(e)?(e.equals!==void 0&&(n.push(`${r} = ?`),i.push(e.equals)),e.not_equals!==void 0&&(n.push(`${r} != ?`),i.push(e.not_equals)),e.in!==void 0&&Array.isArray(e.in)&&(e.in.length===0?n.push("1 = 0"):(n.push(`${r} IN (${e.in.map(()=>"?").join(", ")})`),i.push(...e.in))),e.contains!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),i.push(`%${e.contains}%`)),e.like!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),i.push(e.like)),e.greater_than!==void 0&&(n.push(`${r} > ?`),i.push(e.greater_than)),e.greater_than_equal!==void 0&&(n.push(`${r} >= ?`),i.push(e.greater_than_equal)),e.less_than!==void 0&&(n.push(`${r} < ?`),i.push(e.less_than)),e.less_than_equal!==void 0&&(n.push(`${r} <= ?`),i.push(e.less_than_equal))):e!==void 0&&(n.push(`${r} = ?`),i.push(e));}return {clause:n.join(" AND "),params:i}}async find(t){let{collection:a,where:n={},sort:i,limit:o=10,page:e=1,tenantId:s,select:r,draft:l=false}=t,c$1=this.parseGlobalsSlug(a),d$1=c$1.isGlobal?this.globals.get(c$1.globalSlug):this.getCollection(a);this.ensureTable(d$1,c$1.tableName);let y=c$1.tableName,h=`SELECT * FROM ${y}`,f=[],u=[],g={...n};this.tenantContext&&d$1.tenantScoped&&(g=c({where:g},a,this.tenantContext,b).where||{});let b$1=d$1.fields.find(p=>p.name==="status"),T=b$1?.type==="select"&&Array.isArray(b$1.options)&&b$1.options.some(p=>p.value==="published");if(!l&&T&&(u.push("status = ?"),f.push("published")),s&&d$1.tenantScoped&&(u.push("tenant_id = ?"),f.push(s)),g&&Object.keys(g).length>0){let p=this.buildWhere(g,y);p.clause&&(u.push(`(${p.clause})`),f.push(...p.params));}u.length>0&&(h+=` WHERE ${u.join(" AND ")}`);let $=i||"-createdAt",M=this.resolveCol(y,$),V=$.startsWith("-")?"DESC":"ASC";h+=` ORDER BY ${M} ${V}`;let X=h.replace("SELECT *","SELECT COUNT(*) as count"),S=this.db.prepare(X).get(...f)?.count||0;h+=" LIMIT ? OFFSET ?",f.push(o,(e-1)*o);let N=this.db.prepare(h).all(...f).map(p=>this.rowToDoc(p,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(p=>d(p,a,this.tenantContext,b))),l&&(N=await Promise.all(N.map(async p=>{let D=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(a,p.id);if(D){let G=D.data?JSON.parse(D.data):{};return a$1({...p,...G,status:p.status,_hasUnpublishedChanges:D.status==="draft"})}return p}))),N=N.map(p=>a$1(p)),{docs:N,totalDocs:S,limit:o,totalPages:Math.ceil(S/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(S/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(S/o)?e+1:null}}async findByID(t){let{collection:a,id:n,tenantId:i,draft:o=false}=t,e=this.parseGlobalsSlug(a),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(a);this.ensureTable(s,e.tableName);let l=`SELECT * FROM ${e.tableName} WHERE id = ?`,c=[n];if(this.tenantContext&&s.tenantScoped){let u={id:n,tenant_id:this.tenantContext.tenantId};if(!d(u,a,this.tenantContext,b))return null}let d$1=s.fields.find(u=>u.name==="status"),y=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(u=>u.value==="published");!o&&y&&(l+=" AND status = ?",c.push("published")),i&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i));let h=this.db.prepare(l).get(...c);if(!h)return null;let f=this.rowToDoc(h,s);if(o){let u=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(a,f.id);if(u){let g=u.data?JSON.parse(u.data):{};f={...f,...g,status:f.status,_hasUnpublishedChanges:u.status==="draft"};}}return a$1(f)}async create(t){let{collection:a,data:n,tenantId:i}=t,o=this.parseGlobalsSlug(a),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(e,o.tableName);let s=o.tableName,r=o.isGlobal?o.globalSlug:n.id||this.generateId(),l=this.prepareData(n,e);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,i&&e.tenantScoped&&(l.tenant_id=i);let d=Object.keys(l),y=I(this.db,s),h={};for(let T of d)y.includes(T)&&(h[T]=l[T]);let f=Object.keys(h),u=f.map(T=>this.col(T)),g=f.map(()=>"?").join(", "),b=Object.values(h).map(T=>T!==null&&typeof T=="object"?JSON.stringify(T):T);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${u.join(", ")}) VALUES (${g})`).run(...b),this.ensureVersionsTable(),this.findByID({collection:a,id:r,tenantId:i,draft:true})}async update(t){let{collection:a,id:n,data:i,tenantId:o}=t,e=this.parseGlobalsSlug(a),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(a);this.ensureTable(s,e.tableName);let r=e.tableName,l=this.prepareData(i,s);l.updated_at=new Date().toISOString();let c=I(this.db,r),d={};for(let b of Object.keys(l))c.includes(b)&&(d[b]=l[b]);let h=Object.keys(d).map(b=>`${this.col(b)} = ?`).join(", "),f=Object.values(d).map(b=>b!==null&&typeof b=="object"?JSON.stringify(b):b),u=`UPDATE ${r} SET ${h} WHERE id = ?`,g=[...f,n];return o&&s.tenantScoped&&(u+=" AND tenant_id = ?",g.push(o)),this.db.prepare(u).run(...g),this.ensureVersionsTable(),this.findByID({collection:a,id:n,tenantId:o,draft:true})}async delete(t){let{collection:a,id:n,tenantId:i}=t,o=this.parseGlobalsSlug(a),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(e,o.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:a,id:n,tenantId:i,draft:true});if(!s)throw new Error(`Document not found: ${a}/${n}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[n];return i&&e.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i)),this.db.prepare(l).run(...c),s}async count(t){let{collection:a,tenantId:n}=t,i=this.parseGlobalsSlug(a),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(a);this.ensureTable(o,i.tableName);let e=i.tableName,s=`SELECT COUNT(*) as count FROM ${e}`,r=[],l=[];if(n&&o.tenantScoped&&(r.push("tenant_id = ?"),l.push(n)),t.where&&Object.keys(t.where).length>0){let d=this.buildWhere(t.where,e);d.clause&&(r.push(`(${d.clause})`),l.push(...d.params));}return r.length>0&&(s+=` WHERE ${r.join(" AND ")}`),this.db.prepare(s).get(...l)?.count||0}async findOne(t){let a=this.parseGlobalsSlug(t.collection);if(a.isGlobal){let i=this.globals.get(a.globalSlug);if(!i)throw new Error(`Global "${a.globalSlug}" not found in adapter`);this.ensureTable(i,a.tableName);let o=`SELECT * FROM ${a.tableName}`,e=[],s=[],r=i.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!t.draft&&i.versions&&l&&e.push("status = 'published'"),e.length>0&&(o+=` WHERE ${e.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...s);if(c){let d=this.rowToDoc(c,i);if(t.draft){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(t.collection,a.globalSlug);if(y){let h=y.data?JSON.parse(y.data):{};d={...d,...h,status:d.status,_hasUnpublishedChanges:y.status==="draft"};}}return d}return null}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){this.ensureVersionsTable();let{collection:a,documentId:n,tenantId:i,limit:o=20,page:e=1}=t,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[a,n];i?(s.push("tenant_id = ?"),r.push(i)):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,y=(e-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,y).map(u=>this.rowToVersion(u)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(d/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(d/o)?e+1:null}}async findVersionByID(t){this.ensureVersionsTable();let a=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(t.versionId,t.collection);return a?this.rowToVersion(a):null}async createVersion(t){this.ensureVersionsTable();let a=new Date().toISOString();if(t.autosave){let s=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[t.collection,t.documentId];t.tenantId?(s+=" AND tenant_id = ?",r.push(t.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(t.data),t.status,a,l.id);let c=await this.findVersionByID({collection:t.collection,versionId:l.id});if(c)return c}}let n=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(t.collection,t.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(n,t.collection,t.documentId,t.tenantId??null,o,t.status,t.autosave?1:0,JSON.stringify(t.data),t.createdBy??null,t.changeDescription??null,t.status==="published"?a:null,a,a),!t.autosave){let r=this.collections.get(t.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:r,tenantId:t.tenantId});}return await this.findVersionByID({collection:t.collection,versionId:n})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){this.ensureVersionsTable();let{collection:a,documentId:n,keepLatest:i,tenantId:o}=t;if(i&&i>0){let e=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(a,n),s=0,r=[];for(let l of e)l.status==="published"||l.autosave===1||(s++,s>i&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let e=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,s=[a,n];o&&(e+=" AND tenant_id = ?",s.push(o)),this.db.prepare(e).run(...s);}}rowToVersion(t){return {id:String(t.id),collection:t.collection_slug,documentId:t.document_id,version:t.version,status:t.status,data:t.data?JSON.parse(t.data):{},createdBy:t.created_by??void 0,changeDescription:t.change_description??void 0,publishedAt:t.published_at??null,createdAt:t.created_at,updatedAt:t.updated_at}}prepareData(t,a){let n={},i=E(a.fields),o=(e,s)=>{let r=e;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(e.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:e.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify({relationTo:e.relationTo,value:s.id||s}):String(s)}return s};for(let e of i){if(!e.name||e.name==="id"||a.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===e.name))))continue;let r=t[e.name];r!==void 0&&(n[e.name]=o(e,r));}for(let e of a.fields)if(e.type==="tabs"&&"tabs"in e&&e.name){let s=t[e.name];if(s&&typeof s=="object"){for(let r of e.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=s[l.name];c!==void 0&&(n[l.name]=o(l,c));}}}return n}rowToDoc(t,a){let n={id:t.id};for(let i of E(a.fields)){if(!i.name||i.name==="id")continue;let o=i,e=t[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{e=e?JSON.parse(e):null;}catch{e=null;}if(o.type==="blocks"&&e&&Array.isArray(e)){let s=o.blocks||[];e=j(e,s);}if(i.type==="checkbox"&&(e=!!e),i.type==="date"&&e)try{let s=new Date(e);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${i.name}":`,e),e=null):e=s.toISOString();}catch{e=null;}if((i.type==="upload"||i.type==="image")&&e)try{let s=JSON.parse(e);Array.isArray(s)?e=s.map(r=>typeof r=="object"&&r!==null?r:{id:r}):e=typeof s=="object"?s:{id:s};}catch{e={id:e};}if(i.type==="relationship"&&e)try{let s=JSON.parse(e);Array.isArray(s),e=s;}catch{e={relationTo:Array.isArray(i.relationTo)?i.relationTo[0]:i.relationTo,value:e};}n[i.name]=e;}for(let i of a.fields)if(!(!i.name||i.name==="id"||i.name==="row"||i.name==="collapsible")&&i.type==="tabs"&&"tabs"in i){let o={};for(let e of i.tabs)for(let s of e.fields)s.name&&s.name!=="id"&&(o[s.name]=P(t,s));n[i.name]=o;}if(a.timestamps){let i=t.createdAt||t.created_at,o=t.updatedAt||t.updated_at;if(i)try{let e=new Date(i);isNaN(e.getTime())||(n.createdAt=e.toISOString());}catch{}if(o)try{let e=new Date(o);isNaN(e.getTime())||(n.updatedAt=e.toISOString());}catch{}}a.tenantScoped&&(n.tenantId=t.tenant_id),n.status=t.status??"published",n.hasDraft=t.hasDraft?!!t.hasDraft:false;for(let i of Object.keys(n))/^\d+$/.test(i)&&delete n[i];return n}generateId(){let t=Date.now().toString(16).padStart(12,"0"),a=randomBytes(6).toString("hex");return t+a}getMediaById(t){try{let a=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${a} WHERE id = ?`).get(t);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.url}}catch{}return null}getTableNameFor(t){return t.replace(/-/g,"_")}async migrate(){for(let t of this.collections.values())this.ensureTable(t);}async rollback(){}async transaction(t){return new Promise((a,n)=>{let i=this.db.transaction(async()=>t({db:this.db}));try{let o=i();a(o);}catch(o){n(o);}})}getDatabase(){return this.db}exec(t){this.db.exec(t);}prepare(t){return this.db.prepare(t)}};function W(m){return new L(m||{})}export{L as a,W as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g();var R=new Set(["type","admin","label","singularLabel","labelPlural","relationTo","required","hasMany","defaultValue","validate","options","dynamicOptions","filterOptions","hooks","min","max","minLength","maxLength","minRows","maxRows","minDate","maxDate","step","integer","variant","pattern","format","fields","tabs","blocks"]);function P(o){return typeof o!="object"||o===null||Array.isArray(o)?false:Object.keys(o).some(l=>R.has(l))}function m(o,l=""){let e={};for(let[n,i]of Object.entries(o)){let r=l?`${l}.${n}`:n;i&&typeof i=="object"&&!Array.isArray(i)&&!P(i)?Object.assign(e,m(i,r)):e[r]=i;}return e}function y(o,l,e,n=true){let i=l.split(".");if(i.length===0)return false;let r=i[0],t=i.slice(1).join("."),f=r.match(/^(?:tab|tabs)\[(.+?)\]$/i);if(f){let s=f[1].toLowerCase();for(let c of o)if(c.type==="tabs"&&c.tabs&&Array.isArray(c.tabs)){for(let a of c.tabs)if((a.label||a.name||"").toLowerCase()===s&&a.fields&&Array.isArray(a.fields))return y(a.fields,t,e,n)}return false}for(let s of o){if(s.name===r)if(t){if(s.fields&&Array.isArray(s.fields))return y(s.fields,t,e,n);if(s.type==="tabs"&&s.tabs&&Array.isArray(s.tabs)){for(let a of s.tabs)if(a.fields&&Array.isArray(a.fields)&&y(a.fields,t,e,n))return true;return false}if(s.type==="blocks"&&s.blocks&&Array.isArray(s.blocks)){let a=t.split(".")[0],b=t.split(".").slice(1).join(".");if(!b)return false;for(let d of s.blocks)if(d.slug===a&&d.fields&&Array.isArray(d.fields))return y(d.fields,b,e,n);return false}return s.type==="array"&&s.fields&&Array.isArray(s.fields)?y(s.fields,t,e,n):false}else return Object.assign(s,e),true;if(s.type==="blocks"&&s.blocks&&Array.isArray(s.blocks)){for(let a of s.blocks)if(a.slug===r&&a.fields&&Array.isArray(a.fields)&&y(a.fields,t,e,n))return true}if(!s.name||s.type==="tabs"||s.type==="row"||s.type==="collapsible"){if(s.fields&&Array.isArray(s.fields)&&y(s.fields,l,e,false))return true;if(s.type==="tabs"&&s.tabs&&Array.isArray(s.tabs)){for(let a of s.tabs)if(a.fields&&Array.isArray(a.fields)&&y(a.fields,l,e,false))return true}}}return n&&!t&&e&&e.type?(o.push({name:r,...e}),true):false}function h(o,l){if(!l)return;let e=Array.isArray(l)?l:Object.entries(l).map(([i,r])=>({slug:r?.slug||i,...r}));function n(i){for(let r of i){if(r.type==="blocks"){Array.isArray(r.blocks)||(r.blocks=[]);for(let t of e){let f=r.blocks.findIndex(s=>s.slug===t.slug);f>=0?r.blocks[f]={...r.blocks[f],...t}:r.blocks.push(t);}return true}if(r.fields&&Array.isArray(r.fields)&&n(r.fields))return true;if(r.type==="tabs"&&r.tabs&&Array.isArray(r.tabs)){for(let t of r.tabs)if(t.fields&&Array.isArray(t.fields)&&n(t.fields))return true}}return false}n(o);}function x(o,l){if(!l)return;let e=Array.isArray(l)?l:Object.entries(l).map(([i,r])=>({label:r?.label||i,...Array.isArray(r)?{fields:r}:r})),n=o.find(i=>i.type==="tabs");if(n&&Array.isArray(n.tabs))for(let i of e){let r=n.tabs.find(t=>(t.label||t.name||"").toLowerCase()===(i.label||i.name||"").toLowerCase());r?(i.fields&&Array.isArray(i.fields)&&(Array.isArray(r.fields)||(r.fields=[]),r.fields.push(...i.fields)),Object.assign(r,i)):n.tabs.push(i);}else {let i=[...o];o.length=0,o.push({type:"tabs",tabs:[{label:"General",fields:i},...e]});}}function T(o,l){if(l)for(let e of o){let n=l[e.slug];if(n){let{fields:i,blocks:r,tabs:t,labels:f,label:s,singularLabel:c,labelPlural:a,hidden:b,timestamps:d,versions:u,seo:A,access:g,hooks:p,admin:k,...v}=n;if(s&&(e.label=s),c&&(e.singularLabel=c),a&&(e.labelPlural=a),f&&(f.singular&&(e.singularLabel=f.singular),f.plural&&(e.labelPlural=f.plural)),d!==void 0&&(e.timestamps=d),u!==void 0&&(e.versions={...e.versions,...u}),A!==void 0&&(e.seo=A),g&&(e.access={...e.access,...g}),p&&(e.hooks={...e.hooks,...p}),(k||v)&&(e.admin={...e.admin,...k,...v}),r&&h(e.fields,r),t&&x(e.fields,t),i){let F=m(i);for(let[L,j]of Object.entries(F))y(e.fields,L,j);}}}}function S(o,l){if(l)for(let e of o){let n=l[e.slug];if(n){let{fields:i,blocks:r,tabs:t,label:f,hidden:s,versions:c,access:a,hooks:b,admin:d,...u}=n;if(f&&(e.label=f),c!==void 0&&(e.versions={...e.versions,...c}),a&&(e.access={...e.access,...a}),b&&(e.hooks={...e.hooks,...b}),(d||u)&&(e.admin={...e.admin,...d,...u}),r&&h(e.fields,r),t&&x(e.fields,t),i){let A=m(i);for(let[g,p]of Object.entries(A))y(e.fields,g,p);}}}}export{R as a,P as b,m as c,y as d,h as e,x as f,T as g,S as h};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();var A=class extends chunkVQ53TFYA_cjs.a{dialect="mongodb";client;db;database;connectionString;constructor(o){if(super(),o.connectionString){this.connectionString=o.connectionString;try{let e=new URL(o.connectionString);this.database=e.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database="kyro_cms";}}else this.client=o.client,this.database=o.database;}async connect(){if(this.connectionString&&!this.client){let o;try{let e=await import('./lib-5QYYN6ML.cjs');o=e.MongoClient??e.default?.MongoClient;}catch{chunkF4ITQ6XQ_cjs.a(["mongodb"]);let n=await import('./lib-5QYYN6ML.cjs');o=n.MongoClient??n.default?.MongoClient;}this.client=new o(this.connectionString),await this.client.connect();}else if(this.client&&typeof this.client.connect=="function")try{await this.client.connect();}catch{}this.client&&(this.db=this.client.db(this.database),this.connected=true);}async disconnect(){this.client&&(await this.client.close(),this.connected=false);}getMongoCollection(o){if(!this.db&&this.client&&(this.db=this.client.db(this.database),this.connected=true),!this.db)throw new Error("MongoDB not connected");return this.db.collection(o)}async find(o){let{collection:e,where:n={},sort:s,limit:t=10,page:i=1,tenantId:r,select:a,draft:l}=o,d=this.getCollectionConfig(e),f=this.getMongoCollection(e),g={...n};this.tenantContext&&d.tenantScoped&&(g=chunkVQ53TFYA_cjs.c({where:g},e,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let u=this.buildFilter(g,d.tenantScoped?r:void 0),c=d.fields.find(p=>p.name==="status"),h=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(p=>p.value==="published");!l&&h&&(u.status="published");let y=this.parseSort(s),O={[y.field]:y.direction==="asc"?1:-1},$=(i-1)*t,[x,M]=await Promise.all([f.find(u).sort(O).skip($).limit(t).project(this.buildProjection(a)).toArray(),f.countDocuments(u)]),C=x.map(p=>this.processResult(p,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(p=>chunkVQ53TFYA_cjs.d(p,e,this.tenantContext,chunkVQ53TFYA_cjs.b))),l&&(C=await Promise.all(C.map(async p=>{let m=await this.getMongoCollection(`${e}_versions`).findOne({document_id:p.id},{sort:{createdAt:-1}});if(m){let P=typeof m.data=="string"?JSON.parse(m.data):m.data&&typeof m.data=="object"?m.data:{};return {...p,...P,status:p.status,_hasUnpublishedChanges:m.status==="draft"}}return p}))),{docs:C,...this.calculatePagination(i,t,M)}}async findByID(o){let{collection:e,id:n,tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e);if(this.tenantContext&&i.tenantScoped){let u={_id:n,tenantId:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(u,e,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let a={_id:n};s&&i.tenantScoped&&(a.tenantId=s);let l=i.fields.find(u=>u.name==="status"),d=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(u=>u.value==="published");!t&&d&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status,_hasUnpublishedChanges:c.status==="draft"};}}return g}async create(o){let{collection:e,data:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.prepareData(n,t),a=r.id||this.generateId();delete r.id;let l={...r,_id:a};return s&&t.tenantScoped&&(l.tenantId=s),await i.insertOne(l),this.processResult(l,t)}async update(o){let{collection:e,id:n,data:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a={_id:n};t&&i.tenantScoped&&(a.tenantId=t);let l=this.prepareData(s,i),d=await r.findOneAndUpdate(a,{$set:l},{returnDocument:"after"});if(!d)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(d,i)}async delete(o){let{collection:e,id:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r={_id:n};s&&t.tenantScoped&&(r.tenantId=s);let a=await i.findOneAndDelete(r);if(!a)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(a,t)}async count(o){let{collection:e,where:n={},tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.buildFilter(n,t.tenantScoped?s:void 0);return i.countDocuments(r)}async findOne(o){let{collection:e,where:n={},tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildFilter(n,i.tenantScoped?s:void 0),l=i.fields.find(u=>u.name==="status"),d=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(u=>u.value==="published");!t&&d&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status};}}return g}async findVersions(o){let{collection:e,documentId:n,sort:s,limit:t=10,page:i=1,tenantId:r}=o,a=this.getCollectionConfig(e),l=this.getMongoCollection(`${e}_versions`),d={document_id:n,autosave:{$ne:true}};r&&a.tenantScoped&&(d.tenant_id=r);let f=(i-1)*t,g=this.parseSort(s),u={[g.field]:g.direction==="asc"?1:-1},[c,h]=await Promise.all([l.find(d).sort(u).skip(f).limit(t).toArray(),l.countDocuments(d)]);return {docs:c.map(y=>this.processResult(y,{})),...this.calculatePagination(i,t,h)}}async findVersionByID(o){let{collection:e,versionId:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(`${e}_versions`),r={_id:n};s&&t.tenantScoped&&(r.tenant_id=s);let a=await i.findOne(r);return a?this.processResult(a,{}):null}async createVersion(o){let{collection:e,documentId:n,data:s,status:t,createdBy:i,changeDescription:r,tenantId:a,autosave:l}=o,d=this.getCollectionConfig(e),f=this.getMongoCollection(`${e}_versions`);if(l){let c={document_id:n,collection_slug:e,autosave:true};a&&d.tenantScoped&&(c.tenant_id=a);let h=await f.findOne(c);if(h){let y=new Date().toISOString();return await f.updateOne({_id:h._id},{$set:{data:s,status:t,updatedAt:y}}),this.processResult({...h,data:s,status:t,updatedAt:y},{})}}let g=new Date().toISOString(),u={_id:this.generateId(),document_id:n,collection_slug:e,data:s,status:t,autosave:l===true,created_by:i,change_description:r,createdAt:g,updatedAt:g};if(a&&d.tenantScoped&&(u.tenant_id=a),await f.insertOne(u),!l){let c=this.getCollectionConfig(e);c.versions?.maxPerDoc&&await this.deleteVersions({collection:e,documentId:n,keepLatest:c.versions.maxPerDoc,tenantId:a});}return this.processResult(u,{})}async updateLatestVersion(o){return this.createVersion({...o,autosave:true})}async deleteVersions(o){let{collection:e,documentId:n,keepLatest:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(`${e}_versions`);if(s){let a={document_id:n,autosave:{$ne:true}};t&&i.tenantScoped&&(a.tenant_id=t);let d=(await r.find(a).sort({createdAt:-1}).limit(s).project({_id:1}).toArray()).map(f=>f._id);d.length>0&&await r.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:d},...t&&i.tenantScoped?{tenant_id:t}:{}});}else {let a={document_id:n};t&&i.tenantScoped&&(a.tenant_id=t),await r.deleteMany(a);}}async migrate(){for(let o of this.collections.values()){let e=this.getMongoCollection(o.slug);await e.createIndex({_id:1}),o.tenantScoped&&await e.createIndex({tenantId:1}),o.timestamps&&await e.createIndex({createdAt:-1});for(let n of o.fields)n.unique&&n.name&&await e.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await e.createIndex({[n.name]:1});}}getCollectionConfig(o){if(o.startsWith("_globals_")){let n=o.replace("_globals_",""),s=this.globals.get(n);if(!s)throw new Error(`Global "${n}" not found`);return s}let e=this.collections.get(o);if(!e)throw new Error(`Collection "${o}" not found`);return e}buildFilter(o={},e){let n={};e&&(n.tenantId=e);for(let[s,t]of Object.entries(o))if(s==="AND"&&Array.isArray(t)){let i=t.map(r=>this.buildFilter(r));Object.assign(n,...i);}else if(s==="OR"&&Array.isArray(t))n.$or=t.map(i=>this.buildFilter(i));else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let i={};if(t.equals!==void 0){n[s==="id"?"_id":s]=t.equals;continue}t.not_equals!==void 0&&(i.$ne=t.not_equals),t.in!==void 0&&(i.$in=t.in),t.not_in!==void 0&&(i.$nin=t.not_in),t.greater_than!==void 0&&(i.$gt=t.greater_than),t.greater_than_equal!==void 0&&(i.$gte=t.greater_than_equal),t.less_than!==void 0&&(i.$lt=t.less_than),t.less_than_equal!==void 0&&(i.$lte=t.less_than_equal),t.like!==void 0&&(i.$regex=new RegExp(t.like.replace(/%/g,".*"),"i")),t.not_like!==void 0&&(i.$not=new RegExp(t.not_like.replace(/%/g,".*"),"i")),t.contains!==void 0&&(i.$regex=new RegExp(`.*${t.contains}.*`,"i")),t.exists!==void 0&&(i.$exists=t.exists),Object.keys(i).length>0&&(n[s==="id"?"_id":s]=i);}else n[s==="id"?"_id":s]=t;return n}buildProjection(o){if(!o||o.length===0)return;let e={_id:1};for(let n of o)e[n]=1;return e}processResult(o,e){if(!o)return null;let n={...o};for(let s of Object.keys(n))/^\d+$/.test(s)&&delete n[s];return o._id&&(n.id=o._id,delete n._id),delete n.__v,n.createdAt&&(n.createdAt=new Date(n.createdAt).toISOString()),n.updatedAt&&(n.updatedAt=new Date(n.updatedAt).toISOString()),chunkZOVH6QT5_cjs.a(n)}generateId(){let o=Date.now().toString(16).padStart(12,"0"),e=crypto.randomBytes(6).toString("hex");return o+e}};function V(v){return new A(v)}
|
|
2
|
+
exports.a=A;exports.b=V;
|