@kyro-cms/core 0.12.60 → 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.
Files changed (77) hide show
  1. package/dist/api-handler-graphql.cjs +1 -1
  2. package/dist/api-handler-graphql.js +1 -1
  3. package/dist/api-handler-trpc.cjs +1 -1
  4. package/dist/api-handler-trpc.js +1 -1
  5. package/dist/api-handler.cjs +1 -1
  6. package/dist/api-handler.js +1 -1
  7. package/dist/{bootstrap-VUWX45QN.js → bootstrap-WB6FDH2T.js} +1 -1
  8. package/dist/bootstrap-XDT4MRML.cjs +1 -0
  9. package/dist/{chunk-33E4YN62.js → chunk-26MOA3HJ.js} +10 -10
  10. package/dist/{chunk-M56F4LQ5.cjs → chunk-3XLXKGEU.cjs} +1 -1
  11. package/dist/{chunk-WQCLLM4S.cjs → chunk-4FHWIGHO.cjs} +10 -10
  12. package/dist/chunk-4ZWLNGLS.js +2 -0
  13. package/dist/{chunk-VOQUO2EZ.cjs → chunk-5DWQGEM2.cjs} +22 -22
  14. package/dist/{chunk-OXGJOYEO.js → chunk-637PTUHF.js} +1 -1
  15. package/dist/chunk-6QWX3DEB.cjs +120 -0
  16. package/dist/{chunk-ZMG7Z3KF.js → chunk-75BFTYBS.js} +23 -23
  17. package/dist/{chunk-YZEMLLD2.js → chunk-AWQGDMOE.js} +3 -3
  18. package/dist/chunk-D6SDGHY6.js +2 -0
  19. package/dist/{chunk-MP5VC5ER.cjs → chunk-FP5UK272.cjs} +1 -1
  20. package/dist/{chunk-AK754S3T.cjs → chunk-FSL3NLRT.cjs} +2 -2
  21. package/dist/{chunk-RTHJ6SS5.js → chunk-GQGFNTDZ.js} +1 -1
  22. package/dist/chunk-HKYBQYAJ.cjs +19 -0
  23. package/dist/{chunk-TDGSIF5H.cjs → chunk-JU3UAZRY.cjs} +10 -11
  24. package/dist/chunk-KMFLHGD5.cjs +1 -0
  25. package/dist/{chunk-NTKIONEC.cjs → chunk-LOP464VR.cjs} +1 -1
  26. package/dist/{chunk-R25WLKX4.js → chunk-N6MNQIQU.js} +101 -101
  27. package/dist/{chunk-BHR7OAU4.cjs → chunk-OPTVCCQQ.cjs} +101 -101
  28. package/dist/chunk-RDFGJHEG.js +2 -0
  29. package/dist/chunk-RILJCH6H.js +121 -0
  30. package/dist/{chunk-KCHPADCH.cjs → chunk-SOCBJPYB.cjs} +1 -1
  31. package/dist/chunk-T4JJVUGT.js +20 -0
  32. package/dist/{chunk-7N6TW4JB.js → chunk-TBTQXIHP.js} +1 -1
  33. package/dist/{chunk-KNOFTUQV.js → chunk-VJODUKKM.js} +11 -12
  34. package/dist/{chunk-DUO523BH.cjs → chunk-ZHA446FA.cjs} +1 -1
  35. package/dist/cli/index.cjs +1 -1
  36. package/dist/cli/index.js +1 -1
  37. package/dist/client.cjs +1 -1
  38. package/dist/client.js +1 -1
  39. package/dist/drizzle/index.cjs +1 -1
  40. package/dist/drizzle/index.d.cts +2 -1
  41. package/dist/drizzle/index.d.ts +2 -1
  42. package/dist/drizzle/index.js +1 -1
  43. package/dist/fields/index.cjs +1 -1
  44. package/dist/fields/index.js +1 -1
  45. package/dist/graphql/index.cjs +1 -1
  46. package/dist/graphql/index.d.cts +2 -0
  47. package/dist/graphql/index.d.ts +2 -0
  48. package/dist/graphql/index.js +1 -1
  49. package/dist/index.cjs +3 -3
  50. package/dist/index.d.cts +1 -1
  51. package/dist/index.d.ts +1 -1
  52. package/dist/index.js +5 -5
  53. package/dist/{local-2IFOTHAA.js → local-4MZ7KOL3.js} +1 -1
  54. package/dist/{local-UESCNPQP.cjs → local-NDTKWJQ6.cjs} +1 -1
  55. package/dist/postgres-auth-adapter-SK3N3OSS.js +1 -1
  56. package/dist/postgres-auth-adapter-ZO6HK5AK.cjs +1 -1
  57. package/dist/postgres-js-GXZX3AGZ.cjs +1 -0
  58. package/dist/{postgres-js-4CI7FMYS.js → postgres-js-WE3NBRFO.js} +1 -1
  59. package/dist/rest/index.cjs +1 -1
  60. package/dist/rest/index.d.cts +3 -3
  61. package/dist/rest/index.d.ts +3 -3
  62. package/dist/rest/index.js +1 -1
  63. package/dist/{sqlite-adapter-4TPNROJK.js → sqlite-adapter-52PL52VU.js} +1 -1
  64. package/dist/{sqlite-adapter-ZTABLT2X.cjs → sqlite-adapter-MNNZZXGX.cjs} +1 -1
  65. package/dist/trpc/index.cjs +1 -1
  66. package/dist/trpc/index.js +1 -1
  67. package/package.json +2 -2
  68. package/dist/bootstrap-JF6Q4L6P.cjs +0 -1
  69. package/dist/chunk-5LPNEYK5.cjs +0 -1
  70. package/dist/chunk-72VOOMJI.js +0 -20
  71. package/dist/chunk-AO2IXWV4.js +0 -2
  72. package/dist/chunk-OUMUIICN.cjs +0 -264
  73. package/dist/chunk-PA4ZZREG.js +0 -2
  74. package/dist/chunk-PCVQNVSU.cjs +0 -19
  75. package/dist/chunk-SQBTIMWF.js +0 -2
  76. package/dist/chunk-T4TSELDS.js +0 -265
  77. package/dist/postgres-js-3Y54EXVQ.cjs +0 -1
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkLY7N3UHH_cjs=require('./chunk-LY7N3UHH.cjs'),chunkGNOSG3PK_cjs=require('./chunk-GNOSG3PK.cjs'),chunkBCEE4NBZ_cjs=require('./chunk-BCEE4NBZ.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`
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-KWGB3YNI.js';import {a}from'./chunk-R25WLKX4.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); }
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$4,f}from'./chunk-OXGJOYEO.js';import {a as a$5}from'./chunk-2HA6EKXX.js';import {c,a as a$2,b,e,h}from'./chunk-JV4HJBXW.js';import {n,M as M$1,p,q,o,w,E,s,t,u,v}from'./chunk-HRAY65XH.js';import {ia,oa,fa,ma,$,ha,ca,pa,ra,J}from'./chunk-3NSZZCOJ.js';import {a,c as c$1,b as b$1,d}from'./chunk-SLMIYECU.js';import {a as a$1}from'./chunk-P6JITOFF.js';import {a as a$3}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();function D(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}function L(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 Ie(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=L(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 le(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]=le(e[n.name],r);}}return {...i,data:e}}):f}var M=class extends 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 r=L(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=L(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-4CI7FMYS.js')).drizzle;}catch{a$1(["postgres","drizzle-orm"]),t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-4CI7FMYS.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$1(["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=L(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$2(o);break;case "decimal":case "numeric":c$1=b(o);break;case "boolean":c$1=a$2(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$2("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(`
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=L(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=L(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=L(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),_=!c&&u.status&&p$1?{...m,status:"published"}:m,ue=await this.count({collection:i,where:_,tenantId:a}),fe=(r-1)*n$1,P=[];try{let h=u[b.field]||u.createdAt||u.id,R=b.direction==="asc"?h:M$1(h),A=this.client.select().from(u);g.length>0&&(A=A.where(p(...g))),P=await A.orderBy(R).limit(n$1).offset(fe);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let N=P.map(h=>this.processResult(h,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(h=>d(h,i,this.tenantContext,b$1))),c&&(N=await Promise.all(N.map(async h=>{let R=await this.executeRaw(J`
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(R.length>0){let A=R[0],pe=typeof A.data=="string"?JSON.parse(A.data):A.data;return {...h,...pe,status:h.status,_hasUnpublishedChanges:A.status==="draft"}}return h}))),{docs:N,...this.calculatePagination(r,n$1,ue)}}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"?D(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`
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],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,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"?D(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"?D(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`
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],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,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`
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=D(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:D(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(o=>typeof o=="string"?D(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(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]=le(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$3(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
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$4().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 $e(f){return new M(f)}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 Pe(){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$5(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:f(s),dialect:f$1,genId:de}}async function je(f,t){}async function Be(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();}
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};
@@ -1 +1 @@
1
- 'use strict';var chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();async function f(e,r){return typeof e=="boolean"?e:typeof e=="function"?await e(r):true}function y(...e){let r={};for(let t of e)t&&typeof t=="object"&&Object.assign(r,t);return r}function h(e,r){return f(e,r).then(t=>{if(t!==true)return t===false?{_id:{$eq:null}}:t})}chunkBUNLC3II_cjs.h();var u="api_keys";function A(e){return e.substring(0,8)}function g(e,r){if(e.length!==r.length)return false;try{return crypto.timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}async function C(e,r,t){if(!e||typeof e!="string")return {valid:false,error:"No API key provided"};if(!e.startsWith("kyro_"))return {valid:false,error:"Invalid API key format"};let l=A(e);try{let s=await r.find({collection:u,where:{keyPrefix:{equals:l}},limit:100,page:1});if(!s.docs||s.docs.length===0)return {valid:!1,error:"Invalid API key"};let n=null;for(let i of s.docs){let c=i;if(g(c.key,e)){n=c;break}}if(!n)return {valid:!1,error:"Invalid API key"};if(n.expiresAt&&new Date(n.expiresAt)<new Date)return {valid:!1,error:"API key has expired"};try{await r.update({collection:u,id:n.id,data:{lastUsedAt:new Date().toISOString()}});}catch{}let o={id:n.userId,role:n.role||"author",tenantId:n.tenantId};if(t){let i=await t(n.userId);i&&Object.assign(o,i);}return {valid:!0,userId:n.userId,user:o,permissions:n.permissions||[],apiKeyId:n.id,tenantId:o.tenantId,role:o.role}}catch(s){return console.error("[ApiKey] Validation error:",s),{valid:false,error:"Failed to validate API key"}}}function P(e){let r=e.headers.get("Authorization");if(r){if(r.startsWith("ApiKey "))return r.slice(7).trim();if(r.startsWith("Bearer "))return null}let t=e.headers.get("X-API-Key");return t?t.trim():null}function K(e){return !e.valid||!e.userId?null:{userId:e.userId,user:e.user||{},permissions:e.permissions||[],apiKeyId:e.apiKeyId||"",tenantId:e.tenantId,role:e.role}}function k(e,r){if(e.length===0)return false;if(e.includes("*")||e.includes(r))return true;let[t,l]=r.split(":");return !!e.includes(`${t}:*`)}function v(){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";for(let t=0;t<32;t++)r+=e[Math.floor(Math.random()*e.length)];return `kyro_${r}`}function b(e){return e.substring(0,8)}exports.a=f;exports.b=y;exports.c=h;exports.d=u;exports.e=C;exports.f=P;exports.g=K;exports.h=k;exports.i=v;exports.j=b;
1
+ 'use strict';var chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();async function f(e,r){return typeof e=="boolean"?e:typeof e=="function"?await e(r):true}function y(...e){let r={};for(let t of e)t&&typeof t=="object"&&Object.assign(r,t);return r}function h(e,r){return f(e,r).then(t=>{if(t!==true)return t===false?{_id:{$eq:null}}:t})}chunkBUNLC3II_cjs.h();var u="api_keys";function A(e){return e.substring(0,8)}function g(e,r){if(e.length!==r.length)return false;try{return crypto.timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}async function C(e,r,t){if(!e||typeof e!="string")return {valid:false,error:"No API key provided"};if(!e.startsWith("kyro_"))return {valid:false,error:"Invalid API key format"};let l=A(e);try{let s=await r.find({collection:u,where:{keyPrefix:{equals:l}},limit:100,page:1});if(!s.docs||s.docs.length===0)return {valid:!1,error:"Invalid API key"};let n=null;for(let i of s.docs){let c=i;if(g(c.key,e)){n=c;break}}if(!n)return {valid:!1,error:"Invalid API key"};if(n.expiresAt&&new Date(n.expiresAt)<new Date)return {valid:!1,error:"API key has expired"};try{await r.update({collection:u,id:n.id,data:{lastUsedAt:new Date().toISOString()}});}catch{}let o={id:n.userId,role:n.role||"author",tenantId:n.tenantId};if(t){let i=await t(n.userId);i&&Object.assign(o,i);}return {valid:!0,userId:n.userId,user:o,permissions:n.permissions||[],apiKeyId:n.id,tenantId:o.tenantId,role:o.role}}catch(s){return console.error("[ApiKey] Validation error:",s),{valid:false,error:"Failed to validate API key"}}}function P(e){let r=e.headers.get("Authorization");if(r){if(r.startsWith("ApiKey "))return r.slice(7).trim();if(r.startsWith("Bearer "))return null}let t=e.headers.get("X-API-Key");return t?t.trim():null}function K(e){return !e.valid||!e.userId?null:{userId:e.userId,user:e.user||{},permissions:e.permissions||[],apiKeyId:e.apiKeyId||"",tenantId:e.tenantId,role:e.role}}function k(e,r){if(e.length===0)return false;if(e.includes("*")||e.includes(r))return true;let[t,l]=r.split(":");return !!e.includes(`${t}:*`)}function v(){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";for(let t=0;t<32;t++)r+=e[Math.floor(Math.random()*e.length)];return `kyro_${r}`}function b(e){return e.substring(0,8)}exports.a=u;exports.b=C;exports.c=P;exports.d=K;exports.e=k;exports.f=v;exports.g=b;exports.h=f;exports.i=y;exports.j=h;
@@ -390,4 +390,4 @@ bucket_name = "${u}"
390
390
  `);}catch(x){let _=x?.stdout?.toString?.()||"",L=x?.stderr?.toString?.()||"";ee.fail("Deployment failed"),_&&process.stdout.write(_),L&&process.stdout.write(L),console.log(`
391
391
  ${C.red.bold("\u2716 Deployment Failed!")}`),console.log(` ${C.dim("See the Wrangler error above.")}
392
392
  `),f&&process.stdout.write(JSON.stringify({ok:false,error:"Deployment failed"})+`
393
- `),process.exit(1);}}),i}var ng=url.fileURLToPath(chunkBUNLC3II_cjs.g),og=Gt.dirname(ng),Gl="0.1.0";try{Gl=JSON.parse(et.readFileSync(Gt.join(og,"../../package.json"),"utf-8")).version;}catch{}var jt=new ie;jt.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(Gl);jt.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async i=>{let{exec:t}=await import('child_process'),e=t(`astro dev --port ${i.port} --host ${i.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});e.stdout?.on("data",s=>process.stdout.write(s)),e.stderr?.on("data",s=>process.stderr.write(s)),process.on("SIGINT",()=>{e.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{e.kill("SIGTERM"),process.exit(0);});});jt.addCommand(Bo());jt.addCommand(Vl());var ts=jt.command("db").description("Database management commands");ts.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit generate",(t,e,s)=>{t&&(console.error("\u274C Generation failed:",t.message),process.exit(1));});});ts.command("migrate").description("Run database migrations").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit migrate",(t,e,s)=>{t&&(console.error("\u274C Migration failed:",t.message),process.exit(1));});});ts.command("push").description("Push schema to database (development)").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit push",(t,e,s)=>{t&&(console.error("\u274C Push failed:",t.message),process.exit(1));});});ts.command("seed").description("Seed database with initial data").action(async()=>{let{exec:i}=await import('child_process');i("npx tsx src/database/drizzle/seed.ts",(t,e,s)=>{t&&(console.error("\u274C Seeding failed:",t.message),process.exit(1));});});ts.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit studio",(t,e,s)=>{t&&(console.error("\u274C Studio failed:",t.message),process.exit(1));});});var ug=jt.command("auth").description("Authentication management commands");ug.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async i=>{(!i.email||!i.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:t}=await import('../bootstrap-JF6Q4L6P.cjs'),e=process.env.DATABASE_URL||"",s=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),r=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),n=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:"),o;if(s){let{PostgresAuthAdapter:a}=await import('../postgres-auth-adapter-ZO6HK5AK.cjs'),{drizzle:h}=await import('../postgres-js-3Y54EXVQ.cjs'),{default:d}=await import('../src-6LAUXXDM.cjs'),c=d(e,{max:1,onnotice:()=>{}}),f=h(c);o=new a({db:f});}else if(r){let{MongoDBAuthAdapter:a}=await import('../mongo-auth-adapter-EUHAYWJ6.cjs'),h=await import('../lib-5QYYN6ML.cjs'),d=h.MongoClient??h.default?.MongoClient,c=new d(e);await c.connect();let f=c.db();o=new a({db:f});}else {let{SQLiteAuthAdapter:a}=await import('../sqlite-adapter-ZTABLT2X.cjs'),h=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a({path:h});}o.connect&&await o.connect();let u=await t({authAdapter:o,adminEmail:i.email,adminPassword:i.password,adminRole:i.role});o.disconnect&&await o.disconnect(),u.success||(console.error("\u274C Failed to create admin:",u.error),process.exit(1));}catch(t){console.error("\u274C Bootstrap failed:",t),process.exit(1);}});jt.command("health").description("Check system health").action(async()=>{let i=process.env.DATABASE_URL||"",t=i.toLowerCase().startsWith("postgres://")||i.toLowerCase().startsWith("postgresql://"),e=i.toLowerCase().startsWith("mongodb://")||i.toLowerCase().startsWith("mongodb+srv://"),s=!i||i.includes(".db")||i.includes("sqlite")||i.includes("file:");if(t)try{let{default:r}=await import('../src-6LAUXXDM.cjs'),n=r(i,{max:1,onnotice:()=>{}});await n.unsafe("SELECT 1"),await n.end();}catch{}else if(e)try{let r=await import('../lib-5QYYN6ML.cjs'),n=r.MongoClient??r.default?.MongoClient,o=new n(i);await o.connect(),await o.db().admin().ping(),await o.close();}catch{}else if(s)try{let r=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:n}=await import('fs');n(r);}catch{}});jt.parse();process.argv.slice(2).length||jt.outputHelp();
393
+ `),process.exit(1);}}),i}var ng=url.fileURLToPath(chunkBUNLC3II_cjs.g),og=Gt.dirname(ng),Gl="0.1.0";try{Gl=JSON.parse(et.readFileSync(Gt.join(og,"../../package.json"),"utf-8")).version;}catch{}var jt=new ie;jt.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(Gl);jt.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async i=>{let{exec:t}=await import('child_process'),e=t(`astro dev --port ${i.port} --host ${i.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});e.stdout?.on("data",s=>process.stdout.write(s)),e.stderr?.on("data",s=>process.stderr.write(s)),process.on("SIGINT",()=>{e.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{e.kill("SIGTERM"),process.exit(0);});});jt.addCommand(Bo());jt.addCommand(Vl());var ts=jt.command("db").description("Database management commands");ts.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit generate",(t,e,s)=>{t&&(console.error("\u274C Generation failed:",t.message),process.exit(1));});});ts.command("migrate").description("Run database migrations").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit migrate",(t,e,s)=>{t&&(console.error("\u274C Migration failed:",t.message),process.exit(1));});});ts.command("push").description("Push schema to database (development)").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit push",(t,e,s)=>{t&&(console.error("\u274C Push failed:",t.message),process.exit(1));});});ts.command("seed").description("Seed database with initial data").action(async()=>{let{exec:i}=await import('child_process');i("npx tsx src/database/drizzle/seed.ts",(t,e,s)=>{t&&(console.error("\u274C Seeding failed:",t.message),process.exit(1));});});ts.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit studio",(t,e,s)=>{t&&(console.error("\u274C Studio failed:",t.message),process.exit(1));});});var ug=jt.command("auth").description("Authentication management commands");ug.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async i=>{(!i.email||!i.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:t}=await import('../bootstrap-XDT4MRML.cjs'),e=process.env.DATABASE_URL||"",s=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),r=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),n=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:"),o;if(s){let{PostgresAuthAdapter:a}=await import('../postgres-auth-adapter-ZO6HK5AK.cjs'),{drizzle:h}=await import('../postgres-js-GXZX3AGZ.cjs'),{default:d}=await import('../src-6LAUXXDM.cjs'),c=d(e,{max:1,onnotice:()=>{}}),f=h(c);o=new a({db:f});}else if(r){let{MongoDBAuthAdapter:a}=await import('../mongo-auth-adapter-EUHAYWJ6.cjs'),h=await import('../lib-5QYYN6ML.cjs'),d=h.MongoClient??h.default?.MongoClient,c=new d(e);await c.connect();let f=c.db();o=new a({db:f});}else {let{SQLiteAuthAdapter:a}=await import('../sqlite-adapter-MNNZZXGX.cjs'),h=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a({path:h});}o.connect&&await o.connect();let u=await t({authAdapter:o,adminEmail:i.email,adminPassword:i.password,adminRole:i.role});o.disconnect&&await o.disconnect(),u.success||(console.error("\u274C Failed to create admin:",u.error),process.exit(1));}catch(t){console.error("\u274C Bootstrap failed:",t),process.exit(1);}});jt.command("health").description("Check system health").action(async()=>{let i=process.env.DATABASE_URL||"",t=i.toLowerCase().startsWith("postgres://")||i.toLowerCase().startsWith("postgresql://"),e=i.toLowerCase().startsWith("mongodb://")||i.toLowerCase().startsWith("mongodb+srv://"),s=!i||i.includes(".db")||i.includes("sqlite")||i.includes("file:");if(t)try{let{default:r}=await import('../src-6LAUXXDM.cjs'),n=r(i,{max:1,onnotice:()=>{}});await n.unsafe("SELECT 1"),await n.end();}catch{}else if(e)try{let r=await import('../lib-5QYYN6ML.cjs'),n=r.MongoClient??r.default?.MongoClient,o=new n(i);await o.connect(),await o.db().admin().ping(),await o.close();}catch{}else if(s)try{let r=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:n}=await import('fs');n(r);}catch{}});jt.parse();process.argv.slice(2).length||jt.outputHelp();
package/dist/cli/index.js CHANGED
@@ -391,4 +391,4 @@ bucket_name = "${u}"
391
391
  `);}catch(v){let S=v?.stdout?.toString?.()||"",W=v?.stderr?.toString?.()||"";se.fail("Deployment failed"),S&&process.stdout.write(S),W&&process.stdout.write(W),console.log(`
392
392
  ${E.red.bold("\u2716 Deployment Failed!")}`),console.log(` ${E.dim("See the Wrangler error above.")}
393
393
  `),f&&process.stdout.write(JSON.stringify({ok:false,error:"Deployment failed"})+`
394
- `),process.exit(1);}}),i}var og=fileURLToPath(import.meta.url),ug=dirname(og),zl="0.1.0";try{zl=JSON.parse(readFileSync(join(ug,"../../package.json"),"utf-8")).version;}catch{}var Nt=new re;Nt.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(zl);Nt.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async i=>{let{exec:t}=await import('child_process'),e=t(`astro dev --port ${i.port} --host ${i.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});e.stdout?.on("data",s=>process.stdout.write(s)),e.stderr?.on("data",s=>process.stderr.write(s)),process.on("SIGINT",()=>{e.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{e.kill("SIGTERM"),process.exit(0);});});Nt.addCommand(Mo());Nt.addCommand(Gl());var es=Nt.command("db").description("Database management commands");es.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit generate",(t,e,s)=>{t&&(console.error("\u274C Generation failed:",t.message),process.exit(1));});});es.command("migrate").description("Run database migrations").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit migrate",(t,e,s)=>{t&&(console.error("\u274C Migration failed:",t.message),process.exit(1));});});es.command("push").description("Push schema to database (development)").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit push",(t,e,s)=>{t&&(console.error("\u274C Push failed:",t.message),process.exit(1));});});es.command("seed").description("Seed database with initial data").action(async()=>{let{exec:i}=await import('child_process');i("npx tsx src/database/drizzle/seed.ts",(t,e,s)=>{t&&(console.error("\u274C Seeding failed:",t.message),process.exit(1));});});es.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit studio",(t,e,s)=>{t&&(console.error("\u274C Studio failed:",t.message),process.exit(1));});});var ag=Nt.command("auth").description("Authentication management commands");ag.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async i=>{(!i.email||!i.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:t}=await import('../bootstrap-VUWX45QN.js'),e=process.env.DATABASE_URL||"",s=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),r=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),n=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:"),o;if(s){let{PostgresAuthAdapter:a}=await import('../postgres-auth-adapter-SK3N3OSS.js'),{drizzle:h}=await import('../postgres-js-4CI7FMYS.js'),{default:d}=await import('../src-QBADSZV4.js'),c=d(e,{max:1,onnotice:()=>{}}),f=h(c);o=new a({db:f});}else if(r){let{MongoDBAuthAdapter:a}=await import('../mongo-auth-adapter-FW7ATYQ6.js'),h=await import('../lib-XXYYUPMW.js'),d=h.MongoClient??h.default?.MongoClient,c=new d(e);await c.connect();let f=c.db();o=new a({db:f});}else {let{SQLiteAuthAdapter:a}=await import('../sqlite-adapter-4TPNROJK.js'),h=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a({path:h});}o.connect&&await o.connect();let u=await t({authAdapter:o,adminEmail:i.email,adminPassword:i.password,adminRole:i.role});o.disconnect&&await o.disconnect(),u.success||(console.error("\u274C Failed to create admin:",u.error),process.exit(1));}catch(t){console.error("\u274C Bootstrap failed:",t),process.exit(1);}});Nt.command("health").description("Check system health").action(async()=>{let i=process.env.DATABASE_URL||"",t=i.toLowerCase().startsWith("postgres://")||i.toLowerCase().startsWith("postgresql://"),e=i.toLowerCase().startsWith("mongodb://")||i.toLowerCase().startsWith("mongodb+srv://"),s=!i||i.includes(".db")||i.includes("sqlite")||i.includes("file:");if(t)try{let{default:r}=await import('../src-QBADSZV4.js'),n=r(i,{max:1,onnotice:()=>{}});await n.unsafe("SELECT 1"),await n.end();}catch{}else if(e)try{let r=await import('../lib-XXYYUPMW.js'),n=r.MongoClient??r.default?.MongoClient,o=new n(i);await o.connect(),await o.db().admin().ping(),await o.close();}catch{}else if(s)try{let r=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:n}=await import('fs');n(r);}catch{}});Nt.parse();process.argv.slice(2).length||Nt.outputHelp();
394
+ `),process.exit(1);}}),i}var og=fileURLToPath(import.meta.url),ug=dirname(og),zl="0.1.0";try{zl=JSON.parse(readFileSync(join(ug,"../../package.json"),"utf-8")).version;}catch{}var Nt=new re;Nt.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(zl);Nt.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async i=>{let{exec:t}=await import('child_process'),e=t(`astro dev --port ${i.port} --host ${i.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});e.stdout?.on("data",s=>process.stdout.write(s)),e.stderr?.on("data",s=>process.stderr.write(s)),process.on("SIGINT",()=>{e.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{e.kill("SIGTERM"),process.exit(0);});});Nt.addCommand(Mo());Nt.addCommand(Gl());var es=Nt.command("db").description("Database management commands");es.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit generate",(t,e,s)=>{t&&(console.error("\u274C Generation failed:",t.message),process.exit(1));});});es.command("migrate").description("Run database migrations").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit migrate",(t,e,s)=>{t&&(console.error("\u274C Migration failed:",t.message),process.exit(1));});});es.command("push").description("Push schema to database (development)").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit push",(t,e,s)=>{t&&(console.error("\u274C Push failed:",t.message),process.exit(1));});});es.command("seed").description("Seed database with initial data").action(async()=>{let{exec:i}=await import('child_process');i("npx tsx src/database/drizzle/seed.ts",(t,e,s)=>{t&&(console.error("\u274C Seeding failed:",t.message),process.exit(1));});});es.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit studio",(t,e,s)=>{t&&(console.error("\u274C Studio failed:",t.message),process.exit(1));});});var ag=Nt.command("auth").description("Authentication management commands");ag.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async i=>{(!i.email||!i.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:t}=await import('../bootstrap-WB6FDH2T.js'),e=process.env.DATABASE_URL||"",s=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),r=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),n=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:"),o;if(s){let{PostgresAuthAdapter:a}=await import('../postgres-auth-adapter-SK3N3OSS.js'),{drizzle:h}=await import('../postgres-js-WE3NBRFO.js'),{default:d}=await import('../src-QBADSZV4.js'),c=d(e,{max:1,onnotice:()=>{}}),f=h(c);o=new a({db:f});}else if(r){let{MongoDBAuthAdapter:a}=await import('../mongo-auth-adapter-FW7ATYQ6.js'),h=await import('../lib-XXYYUPMW.js'),d=h.MongoClient??h.default?.MongoClient,c=new d(e);await c.connect();let f=c.db();o=new a({db:f});}else {let{SQLiteAuthAdapter:a}=await import('../sqlite-adapter-52PL52VU.js'),h=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a({path:h});}o.connect&&await o.connect();let u=await t({authAdapter:o,adminEmail:i.email,adminPassword:i.password,adminRole:i.role});o.disconnect&&await o.disconnect(),u.success||(console.error("\u274C Failed to create admin:",u.error),process.exit(1));}catch(t){console.error("\u274C Bootstrap failed:",t),process.exit(1);}});Nt.command("health").description("Check system health").action(async()=>{let i=process.env.DATABASE_URL||"",t=i.toLowerCase().startsWith("postgres://")||i.toLowerCase().startsWith("postgresql://"),e=i.toLowerCase().startsWith("mongodb://")||i.toLowerCase().startsWith("mongodb+srv://"),s=!i||i.includes(".db")||i.includes("sqlite")||i.includes("file:");if(t)try{let{default:r}=await import('../src-QBADSZV4.js'),n=r(i,{max:1,onnotice:()=>{}});await n.unsafe("SELECT 1"),await n.end();}catch{}else if(e)try{let r=await import('../lib-XXYYUPMW.js'),n=r.MongoClient??r.default?.MongoClient,o=new n(i);await o.connect(),await o.db().admin().ping(),await o.close();}catch{}else if(s)try{let r=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:n}=await import('fs');n(r);}catch{}});Nt.parse();process.argv.slice(2).length||Nt.outputHelp();
package/dist/client.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunkJT36FTHY_cjs=require('./chunk-JT36FTHY.cjs'),chunkQC4YXUBT_cjs=require('./chunk-QC4YXUBT.cjs');require('./chunk-5LPNEYK5.cjs');var chunkMVX2PYJJ_cjs=require('./chunk-MVX2PYJJ.cjs');require('./chunk-73D2PNHD.cjs');var chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');chunkBUNLC3II_cjs.h();Object.defineProperty(exports,"CSSGenerator",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.a}});Object.defineProperty(exports,"createAdminStyling",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.g}});Object.defineProperty(exports,"defaultDarkTheme",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.d}});Object.defineProperty(exports,"defaultFieldStyling",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.h}});Object.defineProperty(exports,"defaultLightTheme",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.c}});Object.defineProperty(exports,"ecommerce2026Theme",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.e}});Object.defineProperty(exports,"generateCSSVariables",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.f}});Object.defineProperty(exports,"generateTailwindConfig",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.b}});Object.defineProperty(exports,"ALL_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.q}});Object.defineProperty(exports,"renderRichText",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.u}});Object.defineProperty(exports,"richTextStyles",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.s}});Object.defineProperty(exports,"createAuditContext",{enumerable:true,get:function(){return chunkMVX2PYJJ_cjs.a}});
1
+ 'use strict';var chunkJT36FTHY_cjs=require('./chunk-JT36FTHY.cjs'),chunkQC4YXUBT_cjs=require('./chunk-QC4YXUBT.cjs');require('./chunk-KMFLHGD5.cjs');var chunkMVX2PYJJ_cjs=require('./chunk-MVX2PYJJ.cjs');require('./chunk-73D2PNHD.cjs');var chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');chunkBUNLC3II_cjs.h();Object.defineProperty(exports,"CSSGenerator",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.a}});Object.defineProperty(exports,"createAdminStyling",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.g}});Object.defineProperty(exports,"defaultDarkTheme",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.d}});Object.defineProperty(exports,"defaultFieldStyling",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.h}});Object.defineProperty(exports,"defaultLightTheme",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.c}});Object.defineProperty(exports,"ecommerce2026Theme",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.e}});Object.defineProperty(exports,"generateCSSVariables",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.f}});Object.defineProperty(exports,"generateTailwindConfig",{enumerable:true,get:function(){return chunkJT36FTHY_cjs.b}});Object.defineProperty(exports,"ALL_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.q}});Object.defineProperty(exports,"renderRichText",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.u}});Object.defineProperty(exports,"richTextStyles",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.s}});Object.defineProperty(exports,"createAuditContext",{enumerable:true,get:function(){return chunkMVX2PYJJ_cjs.a}});
package/dist/client.js CHANGED
@@ -1,2 +1,2 @@
1
- export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-7FXEXHK6.js';export{q as ALL_FIELD_TYPES,u as renderRichText,s as richTextStyles}from'./chunk-ZRIBWDYJ.js';import'./chunk-SQBTIMWF.js';export{a as createAuditContext}from'./chunk-L2QXP26Q.js';import'./chunk-7MNDQU6K.js';import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-7FXEXHK6.js';export{q as ALL_FIELD_TYPES,u as renderRichText,s as richTextStyles}from'./chunk-ZRIBWDYJ.js';import'./chunk-D6SDGHY6.js';export{a as createAuditContext}from'./chunk-L2QXP26Q.js';import'./chunk-7MNDQU6K.js';import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
2
  g();
@@ -1 +1 @@
1
- 'use strict';require('../chunk-AMGJ5AFH.cjs');var chunkTDGSIF5H_cjs=require('../chunk-TDGSIF5H.cjs'),chunkXBQ6HV3T_cjs=require('../chunk-XBQ6HV3T.cjs');require('../chunk-7JWQ2PZP.cjs'),require('../chunk-NGNJSUGL.cjs'),require('../chunk-KCHPADCH.cjs'),require('../chunk-BAVN7VDR.cjs'),require('../chunk-LY7N3UHH.cjs'),require('../chunk-7ACHOBWY.cjs'),require('../chunk-GNOSG3PK.cjs'),require('../chunk-BCEE4NBZ.cjs'),require('../chunk-VRZC4TTF.cjs'),require('../chunk-VQ53TFYA.cjs'),require('../chunk-F4ITQ6XQ.cjs'),require('../chunk-HTYVI2HK.cjs'),require('../chunk-ZOVH6QT5.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"DrizzleAdapter",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.c}});Object.defineProperty(exports,"collectionToDrizzleSchema",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.b}});Object.defineProperty(exports,"createDatabase",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.f}});Object.defineProperty(exports,"createDrizzleAdapter",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.d}});Object.defineProperty(exports,"fieldToDrizzleType",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.a}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.g}});Object.defineProperty(exports,"seedDefaultRoles",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.h}});Object.defineProperty(exports,"PostgresAuthAdapter",{enumerable:true,get:function(){return chunkXBQ6HV3T_cjs.a}});
1
+ 'use strict';require('../chunk-AMGJ5AFH.cjs');var chunkJU3UAZRY_cjs=require('../chunk-JU3UAZRY.cjs');require('../chunk-7ACHOBWY.cjs');var chunkXBQ6HV3T_cjs=require('../chunk-XBQ6HV3T.cjs');require('../chunk-7JWQ2PZP.cjs'),require('../chunk-NGNJSUGL.cjs'),require('../chunk-SOCBJPYB.cjs'),require('../chunk-GNOSG3PK.cjs'),require('../chunk-BCEE4NBZ.cjs'),require('../chunk-LY7N3UHH.cjs'),require('../chunk-BAVN7VDR.cjs'),require('../chunk-VRZC4TTF.cjs'),require('../chunk-VQ53TFYA.cjs'),require('../chunk-F4ITQ6XQ.cjs'),require('../chunk-HTYVI2HK.cjs'),require('../chunk-ZOVH6QT5.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"DrizzleAdapter",{enumerable:true,get:function(){return chunkJU3UAZRY_cjs.g}});Object.defineProperty(exports,"collectionToDrizzleSchema",{enumerable:true,get:function(){return chunkJU3UAZRY_cjs.f}});Object.defineProperty(exports,"createDatabase",{enumerable:true,get:function(){return chunkJU3UAZRY_cjs.b}});Object.defineProperty(exports,"createDrizzleAdapter",{enumerable:true,get:function(){return chunkJU3UAZRY_cjs.h}});Object.defineProperty(exports,"fieldToDrizzleType",{enumerable:true,get:function(){return chunkJU3UAZRY_cjs.e}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkJU3UAZRY_cjs.c}});Object.defineProperty(exports,"seedDefaultRoles",{enumerable:true,get:function(){return chunkJU3UAZRY_cjs.d}});Object.defineProperty(exports,"PostgresAuthAdapter",{enumerable:true,get:function(){return chunkXBQ6HV3T_cjs.a}});
@@ -1,11 +1,12 @@
1
1
  import { A as AbstractBaseAdapter } from '../base-DDEmdRqV.cjs';
2
2
  import { C as CollectionConfig, G as GlobalConfig, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindOneArgs } from '../types-DOKMyC3y.cjs';
3
- import { F as Field } from '../types-euTszc-1.cjs';
4
3
  import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
5
4
  import { A as AuthAdapter, U as UserRole, c as AuthUser, S as Session, e as AuditLogFilter, d as AuditLog } from '../types-CpjuXbe7.cjs';
5
+ import { F as Field } from '../types-euTszc-1.cjs';
6
6
 
7
7
  declare function fieldToDrizzleType(field: Field, dialect?: 'postgres' | 'sqlite'): string;
8
8
  declare function collectionToDrizzleSchema(collection: CollectionConfig, dialect?: 'postgres' | 'sqlite'): string;
9
+
9
10
  declare class DrizzleAdapter extends AbstractBaseAdapter {
10
11
  client: any;
11
12
  private schema;
@@ -1,11 +1,12 @@
1
1
  import { A as AbstractBaseAdapter } from '../base-7vJMzr4V.js';
2
2
  import { C as CollectionConfig, G as GlobalConfig, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindOneArgs } from '../types-CYGXsNcJ.js';
3
- import { F as Field } from '../types-euTszc-1.js';
4
3
  import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
5
4
  import { A as AuthAdapter, U as UserRole, c as AuthUser, S as Session, e as AuditLogFilter, d as AuditLog } from '../types-CpjuXbe7.js';
5
+ import { F as Field } from '../types-euTszc-1.js';
6
6
 
7
7
  declare function fieldToDrizzleType(field: Field, dialect?: 'postgres' | 'sqlite'): string;
8
8
  declare function collectionToDrizzleSchema(collection: CollectionConfig, dialect?: 'postgres' | 'sqlite'): string;
9
+
9
10
  declare class DrizzleAdapter extends AbstractBaseAdapter {
10
11
  client: any;
11
12
  private schema;
@@ -1 +1 @@
1
- import'../chunk-QDBGBDCT.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'../chunk-KNOFTUQV.js';export{a as PostgresAuthAdapter}from'../chunk-ZWDBPEXL.js';import'../chunk-47CXBWMA.js';import'../chunk-EML5FDUU.js';import'../chunk-OXGJOYEO.js';import'../chunk-FLMUMPDE.js';import'../chunk-2HA6EKXX.js';import'../chunk-JV4HJBXW.js';import'../chunk-N5POANYV.js';import'../chunk-HRAY65XH.js';import'../chunk-3NSZZCOJ.js';import'../chunk-SLMIYECU.js';import'../chunk-P6JITOFF.js';import'../chunk-7NH7H3WA.js';import'../chunk-VVVCCB6R.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ import'../chunk-QDBGBDCT.js';export{g as DrizzleAdapter,f as collectionToDrizzleSchema,b as createDatabase,h as createDrizzleAdapter,e as fieldToDrizzleType,c as runMigrations,d as seedDefaultRoles}from'../chunk-VJODUKKM.js';import'../chunk-JV4HJBXW.js';export{a as PostgresAuthAdapter}from'../chunk-ZWDBPEXL.js';import'../chunk-47CXBWMA.js';import'../chunk-EML5FDUU.js';import'../chunk-637PTUHF.js';import'../chunk-N5POANYV.js';import'../chunk-HRAY65XH.js';import'../chunk-2HA6EKXX.js';import'../chunk-FLMUMPDE.js';import'../chunk-3NSZZCOJ.js';import'../chunk-SLMIYECU.js';import'../chunk-P6JITOFF.js';import'../chunk-7NH7H3WA.js';import'../chunk-VVVCCB6R.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
@@ -1 +1 @@
1
- 'use strict';var chunkQC4YXUBT_cjs=require('../chunk-QC4YXUBT.cjs'),chunk5LPNEYK5_cjs=require('../chunk-5LPNEYK5.cjs');require('../chunk-73D2PNHD.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"ALL_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.q}});Object.defineProperty(exports,"COMPLEX_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.n}});Object.defineProperty(exports,"LAYOUT_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.p}});Object.defineProperty(exports,"PRIMITIVE_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.m}});Object.defineProperty(exports,"RELATIONAL_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.o}});Object.defineProperty(exports,"createRelationshipFieldConfig",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.r}});Object.defineProperty(exports,"isArrayField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.d}});Object.defineProperty(exports,"isBlocksField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.f}});Object.defineProperty(exports,"isGroupField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.e}});Object.defineProperty(exports,"isIconField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.l}});Object.defineProperty(exports,"isImageField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.h}});Object.defineProperty(exports,"isLayoutField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.k}});Object.defineProperty(exports,"isNumberField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.b}});Object.defineProperty(exports,"isRelationshipField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.c}});Object.defineProperty(exports,"isRichTextField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.i}});Object.defineProperty(exports,"isSelectField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.j}});Object.defineProperty(exports,"isTextField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.a}});Object.defineProperty(exports,"isUploadField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.g}});Object.defineProperty(exports,"normalizeRichTextValue",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.t}});Object.defineProperty(exports,"renderRichText",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.u}});Object.defineProperty(exports,"richTextStyles",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.s}});Object.defineProperty(exports,"generateSEOFields",{enumerable:true,get:function(){return chunk5LPNEYK5_cjs.a}});
1
+ 'use strict';var chunkQC4YXUBT_cjs=require('../chunk-QC4YXUBT.cjs'),chunkKMFLHGD5_cjs=require('../chunk-KMFLHGD5.cjs');require('../chunk-73D2PNHD.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"ALL_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.q}});Object.defineProperty(exports,"COMPLEX_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.n}});Object.defineProperty(exports,"LAYOUT_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.p}});Object.defineProperty(exports,"PRIMITIVE_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.m}});Object.defineProperty(exports,"RELATIONAL_FIELD_TYPES",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.o}});Object.defineProperty(exports,"createRelationshipFieldConfig",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.r}});Object.defineProperty(exports,"isArrayField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.d}});Object.defineProperty(exports,"isBlocksField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.f}});Object.defineProperty(exports,"isGroupField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.e}});Object.defineProperty(exports,"isIconField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.l}});Object.defineProperty(exports,"isImageField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.h}});Object.defineProperty(exports,"isLayoutField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.k}});Object.defineProperty(exports,"isNumberField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.b}});Object.defineProperty(exports,"isRelationshipField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.c}});Object.defineProperty(exports,"isRichTextField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.i}});Object.defineProperty(exports,"isSelectField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.j}});Object.defineProperty(exports,"isTextField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.a}});Object.defineProperty(exports,"isUploadField",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.g}});Object.defineProperty(exports,"normalizeRichTextValue",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.t}});Object.defineProperty(exports,"renderRichText",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.u}});Object.defineProperty(exports,"richTextStyles",{enumerable:true,get:function(){return chunkQC4YXUBT_cjs.s}});Object.defineProperty(exports,"generateSEOFields",{enumerable:true,get:function(){return chunkKMFLHGD5_cjs.a}});
@@ -1 +1 @@
1
- export{q as ALL_FIELD_TYPES,n as COMPLEX_FIELD_TYPES,p as LAYOUT_FIELD_TYPES,m as PRIMITIVE_FIELD_TYPES,o as RELATIONAL_FIELD_TYPES,r as createRelationshipFieldConfig,d as isArrayField,f as isBlocksField,e as isGroupField,l as isIconField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,t as normalizeRichTextValue,u as renderRichText,s as richTextStyles}from'../chunk-ZRIBWDYJ.js';export{a as generateSEOFields}from'../chunk-SQBTIMWF.js';import'../chunk-7MNDQU6K.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ export{q as ALL_FIELD_TYPES,n as COMPLEX_FIELD_TYPES,p as LAYOUT_FIELD_TYPES,m as PRIMITIVE_FIELD_TYPES,o as RELATIONAL_FIELD_TYPES,r as createRelationshipFieldConfig,d as isArrayField,f as isBlocksField,e as isGroupField,l as isIconField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,t as normalizeRichTextValue,u as renderRichText,s as richTextStyles}from'../chunk-ZRIBWDYJ.js';export{a as generateSEOFields}from'../chunk-D6SDGHY6.js';import'../chunk-7MNDQU6K.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
@@ -1 +1 @@
1
- 'use strict';var chunkVOQUO2EZ_cjs=require('../chunk-VOQUO2EZ.cjs');require('../chunk-DUO523BH.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"RelationLoader",{enumerable:true,get:function(){return chunkVOQUO2EZ_cjs.H}});Object.defineProperty(exports,"buildGraphQLSchema",{enumerable:true,get:function(){return chunkVOQUO2EZ_cjs.J}});Object.defineProperty(exports,"createGraphQLSchema",{enumerable:true,get:function(){return chunkVOQUO2EZ_cjs.K}});Object.defineProperty(exports,"depthLimit",{enumerable:true,get:function(){return chunkVOQUO2EZ_cjs.I}});Object.defineProperty(exports,"printSchema",{enumerable:true,get:function(){return chunkVOQUO2EZ_cjs.G}});
1
+ 'use strict';var chunk5DWQGEM2_cjs=require('../chunk-5DWQGEM2.cjs');require('../chunk-ZHA446FA.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"RelationLoader",{enumerable:true,get:function(){return chunk5DWQGEM2_cjs.H}});Object.defineProperty(exports,"buildGraphQLSchema",{enumerable:true,get:function(){return chunk5DWQGEM2_cjs.J}});Object.defineProperty(exports,"createGraphQLSchema",{enumerable:true,get:function(){return chunk5DWQGEM2_cjs.K}});Object.defineProperty(exports,"depthLimit",{enumerable:true,get:function(){return chunk5DWQGEM2_cjs.I}});Object.defineProperty(exports,"printSchema",{enumerable:true,get:function(){return chunk5DWQGEM2_cjs.G}});
@@ -22,8 +22,10 @@ declare class RelationLoader {
22
22
  private getCacheKey;
23
23
  load(collection: string, id: string): Promise<any | undefined>;
24
24
  flushAll(): Promise<void>;
25
+ loadMany(collection: string, ids: string[]): Promise<(any | undefined)[]>;
25
26
  resolveOne(collection: string, id: string): any | undefined;
26
27
  }
28
+
27
29
  interface GraphQLContext {
28
30
  db: BaseAdapter;
29
31
  registry: Registry;
@@ -22,8 +22,10 @@ declare class RelationLoader {
22
22
  private getCacheKey;
23
23
  load(collection: string, id: string): Promise<any | undefined>;
24
24
  flushAll(): Promise<void>;
25
+ loadMany(collection: string, ids: string[]): Promise<(any | undefined)[]>;
25
26
  resolveOne(collection: string, id: string): any | undefined;
26
27
  }
28
+
27
29
  interface GraphQLContext {
28
30
  db: BaseAdapter;
29
31
  registry: Registry;
@@ -1 +1 @@
1
- export{H as RelationLoader,J as buildGraphQLSchema,K as createGraphQLSchema,I as depthLimit,G as printSchema}from'../chunk-ZMG7Z3KF.js';import'../chunk-RTHJ6SS5.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ export{H as RelationLoader,J as buildGraphQLSchema,K as createGraphQLSchema,I as depthLimit,G as printSchema}from'../chunk-75BFTYBS.js';import'../chunk-GQGFNTDZ.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }