@kyro-cms/core 0.11.3 → 0.11.5

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 (81) hide show
  1. package/dist/{WebhookService-neHWRdFM.d.ts → WebhookService-0D8rBDOw.d.ts} +1 -1
  2. package/dist/{WebhookService-DvP8e4Gb.d.cts → WebhookService-BoHm8roq.d.cts} +1 -1
  3. package/dist/api-handler-graphql.cjs +1 -1
  4. package/dist/api-handler-graphql.js +1 -1
  5. package/dist/api-handler-trpc.cjs +1 -1
  6. package/dist/api-handler-trpc.js +1 -1
  7. package/dist/api-handler.cjs +1 -1
  8. package/dist/api-handler.js +1 -1
  9. package/dist/{base-DRK_7V46.d.ts → base-D_gWzhL1.d.ts} +2 -2
  10. package/dist/{base-CH7d01Yw.d.cts → base-m1Y9PVG6.d.cts} +2 -2
  11. package/dist/chunk-43U2NBVS.cjs +86 -0
  12. package/dist/chunk-5SEHX7ON.js +1 -0
  13. package/dist/{chunk-Q4CSLXCO.cjs → chunk-6CF7WF64.cjs} +2 -2
  14. package/dist/chunk-7ORSLR3S.js +2 -0
  15. package/dist/{chunk-E33PFGHA.js → chunk-CAD6VWL5.js} +1 -1
  16. package/dist/chunk-DNLO7PK6.cjs +2 -0
  17. package/dist/chunk-FCPFEHTM.cjs +3 -0
  18. package/dist/chunk-FU5JJVYA.js +3 -0
  19. package/dist/chunk-HM2Y4R77.js +21 -0
  20. package/dist/chunk-KD7LUCFY.cjs +1 -0
  21. package/dist/{chunk-62Y4NYMH.cjs → chunk-MOMALAYX.cjs} +1 -1
  22. package/dist/{chunk-GDMLWVJO.js → chunk-MTFJDAPX.js} +6 -6
  23. package/dist/chunk-O7FYIPJW.cjs +2 -0
  24. package/dist/{chunk-NGBJKZMT.js → chunk-PFT4OMNK.js} +2 -2
  25. package/dist/{chunk-RLDAQ7IH.cjs → chunk-QAJS4EXW.cjs} +7 -7
  26. package/dist/chunk-QEKTGNUJ.cjs +21 -0
  27. package/dist/chunk-V465K673.js +86 -0
  28. package/dist/chunk-XQPYBNIT.js +2 -0
  29. package/dist/client.cjs +1 -1
  30. package/dist/client.d.cts +3 -3
  31. package/dist/client.d.ts +3 -3
  32. package/dist/client.js +1 -1
  33. package/dist/drizzle/index.cjs +1 -1
  34. package/dist/drizzle/index.d.cts +3 -3
  35. package/dist/drizzle/index.d.ts +3 -3
  36. package/dist/drizzle/index.js +1 -1
  37. package/dist/fields/index.cjs +1 -1
  38. package/dist/fields/index.d.cts +5 -5
  39. package/dist/fields/index.d.ts +5 -5
  40. package/dist/fields/index.js +1 -1
  41. package/dist/graphql/index.cjs +1 -1
  42. package/dist/graphql/index.d.cts +3 -3
  43. package/dist/graphql/index.d.ts +3 -3
  44. package/dist/graphql/index.js +1 -1
  45. package/dist/{index-B52AAXcJ.d.cts → index-DpuTMOei.d.cts} +2 -2
  46. package/dist/{index-BTFBhepB.d.ts → index-wsdh-ul-.d.ts} +2 -2
  47. package/dist/index.cjs +2 -2
  48. package/dist/index.d.cts +12 -10
  49. package/dist/index.d.ts +12 -10
  50. package/dist/index.js +1 -1
  51. package/dist/mongodb/index.cjs +1 -1
  52. package/dist/mongodb/index.d.cts +3 -3
  53. package/dist/mongodb/index.d.ts +3 -3
  54. package/dist/mongodb/index.js +1 -1
  55. package/dist/rest/index.cjs +1 -1
  56. package/dist/rest/index.d.cts +4 -4
  57. package/dist/rest/index.d.ts +4 -4
  58. package/dist/rest/index.js +1 -1
  59. package/dist/richtext-DrhORshE.d.cts +5 -0
  60. package/dist/richtext-DrhORshE.d.ts +5 -0
  61. package/dist/templates/index.cjs +1 -1
  62. package/dist/templates/index.d.cts +4 -8
  63. package/dist/templates/index.d.ts +4 -8
  64. package/dist/templates/index.js +1 -1
  65. package/dist/trpc/index.d.cts +3 -3
  66. package/dist/trpc/index.d.ts +3 -3
  67. package/dist/{types-BH7tjlpR.d.ts → types-CGQSckv0.d.cts} +2 -1
  68. package/dist/{types-C9izrwhZ.d.cts → types-CIJsFuvf.d.cts} +15 -3
  69. package/dist/{types-C9izrwhZ.d.ts → types-CIJsFuvf.d.ts} +15 -3
  70. package/dist/{types-BMu-234T.d.cts → types-Cxb3Ukwl.d.ts} +2 -1
  71. package/package.json +1 -1
  72. package/dist/chunk-6JHNHMGB.cjs +0 -2
  73. package/dist/chunk-GT5P64DV.js +0 -21
  74. package/dist/chunk-ODCLVIIT.js +0 -3
  75. package/dist/chunk-PY45XUEJ.cjs +0 -21
  76. package/dist/chunk-RNY7W36D.cjs +0 -86
  77. package/dist/chunk-TDM56PFL.cjs +0 -3
  78. package/dist/chunk-TYOVXKQP.js +0 -2
  79. package/dist/chunk-WMY7BDPK.cjs +0 -2
  80. package/dist/chunk-WQKF57FY.js +0 -86
  81. package/dist/chunk-YLEVWUTV.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import {a,c,b,d}from'./chunk-4YYBWCDJ.js';import {sql,eq,desc,and,or,ne,inArray,like,gt,gte,lt,lte}from'drizzle-orm';import {text,uuid,jsonb,timestamp,boolean,decimal,integer as integer$1,varchar,pgTable}from'drizzle-orm/pg-core';import {text as text$1,integer,numeric,sqliteTable}from'drizzle-orm/sqlite-core';import {drizzle}from'drizzle-orm/postgres-js';import oe from'postgres';import {randomBytes}from'crypto';import {mkdir}from'fs/promises';import {resolve,dirname}from'path';import {createRequire}from'module';var M=false;function D(p,s="postgres"){switch(p.type){case "text":case "email":case "password":case "color":return s==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return p.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return s==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return s==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Ae(p,s="postgres"){let n=p.slug.replace(/-/g,"_"),e=[];e.push(`export const ${n} = pgTable('${n}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let t of p.fields){if(t.name==="id")continue;let o=D(t,s),r=t.required,a=` ${t.name}: pg.${o}('${t.name}')`;t.unique&&(a+=".unique()"),r||(a+=".nullable()"),t.defaultValue!==void 0&&(typeof t.defaultValue=="string"?a+=`.default('${t.defaultValue}')`:typeof t.defaultValue=="boolean"?a+=`.default(${t.defaultValue})`:a+=`.default(sql\`${JSON.stringify(t.defaultValue)}\`)`),a+=",",e.push(a);}return p.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${s==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${s==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
2
- `)}var S=class extends a{client;schema;dialect;connectionString;versionsTableReady=false;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let n=s.connectionString.toLowerCase();n.startsWith("postgres://")||n.startsWith("postgresql://")?this.dialect="postgres":n.includes(".db")||n.includes("sqlite")||n.includes("file:")?this.dialect="sqlite":this.dialect=s.type||"postgres";}else this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,n){let e=super.prepareData(s,n);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of n.fields)if(t.type==="date"&&t.name){let o=e[t.name];o&&typeof o=="string"&&(e[t.name]=new Date(o));}for(let t of n.fields){let r=D(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let a=s[t.name];if(a&&typeof a=="object"){let i={};for(let[c,u]of Object.entries(a)){let d=t.tabs.flatMap(h=>h.fields).find(h=>h.name===c);(d?.type==="upload"||d?.type==="image"||d?.type==="list"||d?.type==="relationship-block")&&u?i[c]=Array.isArray(u)||typeof u=="object"?JSON.stringify(u):u:i[c]=u;}e[t.name]=this.dialect==="sqlite"||!r?JSON.stringify(i):i;}}else if(r&&t.name&&s[t.name]!==void 0&&s[t.name]!==null)e[t.name]=this.dialect==="sqlite"?JSON.stringify(s[t.name]):s[t.name];else if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let a=s[t.name];a!=null&&(e[t.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let t of n.fields)if(t.name&&e[t.name]===""){let o=D(t,this.dialect);(o==="timestamp"||o==="jsonb"||o==="decimal"||o==="integer"||o==="numeric"||o==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let{default:s}=await import('postgres'),{drizzle:n}=await import('drizzle-orm/postgres-js'),e=s(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let{default:s}=await import('better-sqlite3'),{drizzle:n}=await import('drizzle-orm/better-sqlite3'),e=new s(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}this.connected=true;}async init(s,n=[]){if(await super.init(s,n),this.connectionString&&!this.client&&await this.connect(),this.client&&!M){for(let t of s){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t));}await this.ensureCollectionTables(s);let e=n.map(t=>({slug:`_globals_${t.slug}`,fields:t.fields,label:t.label}));for(let t of e){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t,true)),this.collections.has(t.slug)||this.collections.set(t.slug,t);}await this.ensureCollectionTables(e),M=true;}}createTableFromConfig(s,n=false){let e=this.getTableName(s.slug),t={id:n?text("id").primaryKey():uuid("id").primaryKey().defaultRandom()};for(let o of s.fields){if(!o.name||o.name==="id")continue;let r=D(o,this.dialect),a=o.name.replace(/-/g,"_"),i=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=text$1(i);break;case "integer":c=integer(i);break;case "decimal":case "numeric":c=numeric(i);break;case "boolean":c=integer(i,{mode:"boolean"});break;case "timestamp":c=text$1(i);break;case "jsonb":c=text$1(i);break;default:c=text$1(i);}else switch(r){case "varchar":c=varchar(i,{length:255});break;case "integer":c=integer$1(i);break;case "decimal":c=decimal(i);break;case "boolean":c=boolean(i);break;case "timestamp":c=timestamp(i);break;case "jsonb":c=jsonb(i);break;default:c=text(i);}o.required||(c=c.default(null)),t[a]=c;}return t.createdAt||(t.createdAt=this.dialect==="sqlite"?text$1("created_at").default(new Date().toISOString()):timestamp("created_at").defaultNow()),t.updatedAt||(t.updatedAt=this.dialect==="sqlite"?text$1("updated_at").default(new Date().toISOString()):timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(t.status||(t.status=this.dialect==="sqlite"?text$1("status").default("draft"):varchar("status",{length:20}).default("draft")),t.hasDraft||(t.hasDraft=this.dialect==="sqlite"?integer("hasDraft",{mode:"boolean"}).default(false):boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteTable(e,t):pgTable(e,t)}async ensureCollectionTables(s){let n=[];for(let e of s){let t=e.slug.startsWith("_globals_"),o=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(d=>d.name==="createdAt"),i=e.fields.some(d=>d.name==="updatedAt"),c=e.fields.some(d=>d.name==="status"),u=e.fields.some(d=>d.name==="hasDraft");if(this.dialect==="postgres"){let d=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
2
+ `)}var S=class extends a{client;schema;dialect;connectionString;versionsTableReady=false;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let n=s.connectionString.toLowerCase();n.startsWith("postgres://")||n.startsWith("postgresql://")?this.dialect="postgres":n.includes(".db")||n.includes("sqlite")||n.includes("file:")?this.dialect="sqlite":this.dialect=s.type||"postgres";}else this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,n){let e=super.prepareData(s,n);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of n.fields)if(t.type==="date"&&t.name){let o=e[t.name];o&&typeof o=="string"&&(e[t.name]=new Date(o));}for(let t of n.fields){let r=D(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let a=s[t.name];if(a&&typeof a=="object"){let i={};for(let[c,u]of Object.entries(a)){let d=t.tabs.flatMap(m=>m.fields).find(m=>m.name===c);(d?.type==="upload"||d?.type==="image"||d?.type==="list"||d?.type==="relationship-block")&&u?i[c]=Array.isArray(u)||typeof u=="object"?JSON.stringify(u):u:i[c]=u;}e[t.name]=this.dialect==="sqlite"||!r?JSON.stringify(i):i;}}else if(r&&t.name&&s[t.name]!==void 0&&s[t.name]!==null)e[t.name]=this.dialect==="sqlite"?JSON.stringify(s[t.name]):s[t.name];else if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let a=s[t.name];a!=null&&(e[t.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let t of n.fields)if(t.name&&e[t.name]===""){let o=D(t,this.dialect);(o==="timestamp"||o==="jsonb"||o==="decimal"||o==="integer"||o==="numeric"||o==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let{default:s}=await import('postgres'),{drizzle:n}=await import('drizzle-orm/postgres-js'),e=s(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let{default:s}=await import('better-sqlite3'),{drizzle:n}=await import('drizzle-orm/better-sqlite3'),e=new s(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}this.connected=true;}async init(s,n=[]){if(await super.init(s,n),this.connectionString&&!this.client&&await this.connect(),this.client&&!M){for(let t of s){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t));}await this.ensureCollectionTables(s);let e=n.map(t=>({slug:`_globals_${t.slug}`,fields:t.fields,label:t.label}));for(let t of e){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t,true)),this.collections.has(t.slug)||this.collections.set(t.slug,t);}await this.ensureCollectionTables(e),M=true;}}createTableFromConfig(s,n=false){let e=this.getTableName(s.slug),t={id:n?text("id").primaryKey():uuid("id").primaryKey().defaultRandom()};for(let o of s.fields){if(!o.name||o.name==="id")continue;let r=D(o,this.dialect),a=o.name.replace(/-/g,"_"),i=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=text$1(i);break;case "integer":c=integer(i);break;case "decimal":case "numeric":c=numeric(i);break;case "boolean":c=integer(i,{mode:"boolean"});break;case "timestamp":c=text$1(i);break;case "jsonb":c=text$1(i);break;default:c=text$1(i);}else switch(r){case "varchar":c=varchar(i,{length:255});break;case "integer":c=integer$1(i);break;case "decimal":c=decimal(i);break;case "boolean":c=boolean(i);break;case "timestamp":c=timestamp(i);break;case "jsonb":c=jsonb(i);break;default:c=text(i);}o.required||(c=c.default(null)),t[a]=c;}return t.createdAt||(t.createdAt=this.dialect==="sqlite"?text$1("created_at").default(new Date().toISOString()):timestamp("created_at").defaultNow()),t.updatedAt||(t.updatedAt=this.dialect==="sqlite"?text$1("updated_at").default(new Date().toISOString()):timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(t.status||(t.status=this.dialect==="sqlite"?text$1("status").default("draft"):varchar("status",{length:20}).default("draft")),t.hasDraft||(t.hasDraft=this.dialect==="sqlite"?integer("hasDraft",{mode:"boolean"}).default(false):boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteTable(e,t):pgTable(e,t)}async ensureCollectionTables(s){let n=[];for(let e of s){let t=e.slug.startsWith("_globals_"),o=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(d=>d.name==="createdAt"),i=e.fields.some(d=>d.name==="updatedAt"),c=e.fields.some(d=>d.name==="status"),u=e.fields.some(d=>d.name==="hasDraft");if(this.dialect==="postgres"){let d=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
3
3
  CREATE TABLE IF NOT EXISTS "${o}" (
4
4
  ${d},
5
5
  ${r}
@@ -20,25 +20,25 @@ import {a,c,b,d}from'./chunk-4YYBWCDJ.js';import {sql,eq,desc,and,or,ne,inArray,
20
20
  `);}if(n.length>0)if(this.dialect==="postgres")await this.client.execute(sql.raw(n.join(`;
21
21
  `)));else for(let e of n)await this.client.execute(sql.raw(e));for(let e of s){let t=this.getTableName(e.slug);t==="users"||t==="audit_logs"||await this.syncTableColumns(e,t);}}getColumnSqlDefinition(s,n){let e=D(s,n),t=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),o=this.columnSqlType(e,n);return `"${t}" ${o} DEFAULT NULL`}columnSqlType(s,n){if(n==="sqlite")switch(s){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(s){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(s,n){let e={},t=s.slug.startsWith("_globals_"),o=s.fields.some(c=>c.name==="createdAt"),r=s.fields.some(c=>c.name==="updatedAt"),a=s.fields.some(c=>c.name==="status"),i=s.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',o||(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'),i||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',o||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),i||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of s.fields){if(!c.name||c.name==="id")continue;let u=this.getColumnSqlDefinition(c,this.dialect),d=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[d]=u;}return e}async syncTableColumns(s,n){let e;try{if(this.dialect==="postgres"){let r=await this.client.execute(sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${n}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.client.execute(sql`PRAGMA table_info("${sql.raw(n)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let t=this.getExpectedColumnDefs(s,n),o=Object.keys(t).filter(r=>!e.has(r));if(o.length>0){let r=o.map(a=>`ALTER TABLE "${n}" ADD COLUMN ${t[a]}`);await this.executeRaw(sql.raw(r.join(`;
22
22
  `)));}if(this.dialect==="postgres")for(let r of s.fields){if(!r.name||r.name==="id")continue;let a=D(r,this.dialect),i=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(i);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" DROP DEFAULT`)),await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE JSONB USING (CASE WHEN "${i}" IS NULL THEN NULL WHEN "${i}"::text ~ '^\\s*\\{' THEN "${i}"::jsonb ELSE jsonb_build_object('id', "${i}"::text) END)`))));}}generateCreateColumns(s){let n=[];for(let e of s.fields){if(!e.name||e.name==="id")continue;let t=D(e,this.dialect),o=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(t){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(t){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}`;}n.push(`"${o}" ${a}`);}return n.join(`,
23
- `)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:t,limit:o=10,page:r=1,tenantID:a,select:i,draft:c$1}=s,u=this.getCollection(n),d$1=this.getTable(n),T={...e};this.tenantContext&&u.tenantScoped&&(T=c({where:T},n,this.tenantContext,b).where||{});let h=this.buildWhereClause(T,u,d$1,a),m=u.fields.find(f=>f.name==="status"),g=m?.type==="select"&&m.options?.some(f=>f.value==="published");!c$1&&d$1.status&&g&&h.push(eq(d$1.status,"published"));let E=this.parseSort(t),R=!c$1&&d$1.status&&g?{...T,status:"published"}:T,j=await this.count({collection:n,where:R,tenantID:a}),B=(r-1)*o,v=[];try{let f=d$1[E.field]||d$1.createdAt||d$1.id,N=E.direction==="asc"?f:desc(f),b=this.client.select().from(d$1);h.length>0&&(b=b.where(and(...h))),v=await b.orderBy(N).limit(o).offset(B);}catch(f){console.error("[DrizzleAdapter] Query error:",f);}let _=v.map(f=>this.processResult(f,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(_=_.filter(f=>d(f,n,this.tenantContext,b))),c$1&&(_=await Promise.all(_.map(async f=>{let N=await this.executeRaw(sql`
23
+ `)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:t,limit:o=10,page:r=1,tenantID:a,select:i,draft:c$1}=s,u=this.getCollection(n),d$1=this.getTable(n),T={...e};this.tenantContext&&u.tenantScoped&&(T=c({where:T},n,this.tenantContext,b).where||{});let m=this.buildWhereClause(T,u,d$1,a),h=u.fields.find(f=>f.name==="status"),y=h?.type==="select"&&Array.isArray(h.options)&&h.options.some(f=>f.value==="published");!c$1&&d$1.status&&y&&m.push(eq(d$1.status,"published"));let E=this.parseSort(t),R=!c$1&&d$1.status&&y?{...T,status:"published"}:T,j=await this.count({collection:n,where:R,tenantID:a}),B=(r-1)*o,v=[];try{let f=d$1[E.field]||d$1.createdAt||d$1.id,N=E.direction==="asc"?f:desc(f),b=this.client.select().from(d$1);m.length>0&&(b=b.where(and(...m))),v=await b.orderBy(N).limit(o).offset(B);}catch(f){console.error("[DrizzleAdapter] Query error:",f);}let _=v.map(f=>this.processResult(f,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(_=_.filter(f=>d(f,n,this.tenantContext,b))),c$1&&(_=await Promise.all(_.map(async f=>{let N=await this.executeRaw(sql`
24
24
  SELECT * FROM kyro_versions
25
25
  WHERE collection_slug = ${n}
26
26
  AND document_id = ${f.id}
27
27
  ORDER BY created_at DESC
28
28
  LIMIT 1
29
- `);if(N.length>0){let b=N[0],X=typeof b.data=="string"?JSON.parse(b.data):b.data;return {...f,...X,status:f.status}}return f}))),{docs:_,...this.calculatePagination(r,o,j)}}async findByID(s){let{collection:n,id:e,tenantID:t,draft:o}=s,r=this.getCollection(n),a=this.getTable(n);if(this.tenantContext&&r.tenantScoped){let m={id:e,tenantId:this.tenantContext.tenantId};if(!d(m,n,this.tenantContext,b))return null}let i=[eq(a.id,e)];t&&a.tenantId&&i.push(eq(a.tenantId,t));let c=r.fields.find(m=>m.name==="status"),u=c?.type==="select"&&c.options?.some(m=>m.value==="published");!o&&a.status&&u&&i.push(eq(a.status,"published"));let d$1=i.length>1?and(...i):i[0],T=await this.client.select().from(a).where(d$1);if(T.length===0)return null;let h=this.processResult(T[0],r);if(o){let m=await this.executeRaw(sql`
29
+ `);if(N.length>0){let b=N[0],X=typeof b.data=="string"?JSON.parse(b.data):b.data;return {...f,...X,status:f.status}}return f}))),{docs:_,...this.calculatePagination(r,o,j)}}async findByID(s){let{collection:n,id:e,tenantID:t,draft:o}=s,r=this.getCollection(n),a=this.getTable(n);if(this.tenantContext&&r.tenantScoped){let h={id:e,tenantId:this.tenantContext.tenantId};if(!d(h,n,this.tenantContext,b))return null}let i=[eq(a.id,e)];t&&a.tenantId&&i.push(eq(a.tenantId,t));let c=r.fields.find(h=>h.name==="status"),u=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(h=>h.value==="published");!o&&a.status&&u&&i.push(eq(a.status,"published"));let d$1=i.length>1?and(...i):i[0],T=await this.client.select().from(a).where(d$1);if(T.length===0)return null;let m=this.processResult(T[0],r);if(o){let h=await this.executeRaw(sql`
30
30
  SELECT * FROM kyro_versions
31
31
  WHERE collection_slug = ${n}
32
- AND document_id = ${h.id}
32
+ AND document_id = ${m.id}
33
33
  ORDER BY created_at DESC
34
34
  LIMIT 1
35
- `);if(m.length>0){let g=m[0],E=typeof g.data=="string"?JSON.parse(g.data):g.data;h={...h,...E,status:h.status};}}return h}async create(s){let{collection:n,data:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.prepareData(e,o);t&&(a.tenantId=t);let i=await this.client.insert(r).values(a).returning();return this.processResult(i[0],o)}async update(s){let{collection:n,id:e,data:t,tenantID:o}=s,r=this.getCollection(n),a=this.getTable(n),i=this.prepareData(t,r);delete i.id;let c=[eq(a.id,e)];o&&a.tenantId&&c.push(eq(a.tenantId,o));let u=await this.client.update(a).set(i).where(and(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(u[0],r)}async delete(s){let{collection:n,id:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=[eq(r.id,e)];t&&r.tenantId&&a.push(eq(r.tenantId,t));let i=await this.client.delete(r).where(and(...a)).returning();if(i.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(i[0],o)}async count(s){let{collection:n,where:e={},tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.buildWhereClause(e,o,r,t);try{let i=this.client.select({count:sql`count(*)`}).from(r);a.length>0&&(i=i.where(and(...a)));let c=await i;return Number(c[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:n,where:e={},tenantID:t,draft:o}=s;if(n.startsWith("_globals_")){let a=n.replace("_globals_",""),i=this.globals.get(a);if(!i)throw new Error(`Global "${a}" not found`);let c=this.getTable(n),u=this.client.select().from(c),d=i.fields.find(g=>g.name==="status"),T=d?.type==="select"&&d.options?.some(g=>g.value==="published");!o&&c.status&&T&&(u=u.where(eq(c.status,"published")));let h=await u.limit(1);if(h.length===0)return null;let m=this.processResult(h[0],i);if(o){let g=await this.executeRaw(sql`
35
+ `);if(h.length>0){let y=h[0],E=typeof y.data=="string"?JSON.parse(y.data):y.data;m={...m,...E,status:m.status};}}return m}async create(s){let{collection:n,data:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.prepareData(e,o);t&&(a.tenantId=t);let i=await this.client.insert(r).values(a).returning();return this.processResult(i[0],o)}async update(s){let{collection:n,id:e,data:t,tenantID:o}=s,r=this.getCollection(n),a=this.getTable(n),i=this.prepareData(t,r);delete i.id;let c=[eq(a.id,e)];o&&a.tenantId&&c.push(eq(a.tenantId,o));let u=await this.client.update(a).set(i).where(and(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(u[0],r)}async delete(s){let{collection:n,id:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=[eq(r.id,e)];t&&r.tenantId&&a.push(eq(r.tenantId,t));let i=await this.client.delete(r).where(and(...a)).returning();if(i.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(i[0],o)}async count(s){let{collection:n,where:e={},tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.buildWhereClause(e,o,r,t);try{let i=this.client.select({count:sql`count(*)`}).from(r);a.length>0&&(i=i.where(and(...a)));let c=await i;return Number(c[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:n,where:e={},tenantID:t,draft:o}=s;if(n.startsWith("_globals_")){let a=n.replace("_globals_",""),i=this.globals.get(a);if(!i)throw new Error(`Global "${a}" not found`);let c=this.getTable(n),u=this.client.select().from(c),d=i.fields.find(y=>y.name==="status"),T=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(y=>y.value==="published");!o&&c.status&&T&&(u=u.where(eq(c.status,"published")));let m=await u.limit(1);if(m.length===0)return null;let h=this.processResult(m[0],i);if(o){let y=await this.executeRaw(sql`
36
36
  SELECT * FROM kyro_versions
37
37
  WHERE collection_slug = ${n}
38
38
  AND document_id = ${a}
39
39
  ORDER BY created_at DESC
40
40
  LIMIT 1
41
- `);if(g.length>0){let E=g[0],R=typeof E.data=="string"?JSON.parse(E.data):E.data;m={...m,...R,status:m.status};}}return m}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:t=10,page:o=1,tenantID:r}=s,a=(o-1)*t,i=await this.executeRaw(sql`
41
+ `);if(y.length>0){let E=y[0],R=typeof E.data=="string"?JSON.parse(E.data):E.data;h={...h,...R,status:h.status};}}return h}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:t=10,page:o=1,tenantID:r}=s,a=(o-1)*t,i=await this.executeRaw(sql`
42
42
  SELECT count(*) as count
43
43
  FROM kyro_versions
44
44
  WHERE collection_slug = ${n}
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkQ3Q7BJVQ_cjs=require('./chunk-Q3Q7BJVQ.cjs'),graphql=require('graphql');var Z=class{db;tenantID;user;caches=new Map;pending=new Map;waiting=new Map;flushScheduled=false;constructor(r){this.db=r.db,this.tenantID=r.tenantID,this.user=r.user;}getCacheKey(r){return r}async load(r,n){let l=this.getCacheKey(r),f=this.caches.get(l);if(f||(f=new Map,this.caches.set(l,f)),f.has(n))return f.get(n);let a=this.pending.get(l);return a||(a=new Set,this.pending.set(l,a)),a.add(n),f.set(n,void 0),this.flushScheduled||(this.flushScheduled=true,queueMicrotask(()=>{this.flushScheduled=false,this.flushAll();})),new Promise(i=>{let o=this.waiting.get(`${l}:${n}`);o||(o=[],this.waiting.set(`${l}:${n}`,o)),o.push(i);})}async flushAll(){for(let[r,n]of this.pending){if(n.size===0)continue;let l=this.caches.get(r),f=await this.db.find({collection:r,where:{id:{in:Array.from(n)}},limit:n.size,tenantID:this.tenantID,draft:!!this.user});for(let a of f.docs||[])if(a&&a.id){l.set(a.id,a);let i=this.waiting.get(`${r}:${a.id}`);i&&(i.forEach(o=>o(a)),this.waiting.delete(`${r}:${a.id}`));}}for(let[r,n]of this.waiting)n.forEach(l=>l(void 0));this.waiting.clear(),this.pending.clear();}resolveOne(r,n){return this.caches.get(this.getCacheKey(r))?.get(n)}},q=new graphql.GraphQLScalarType({name:"JSON",description:"Arbitrary JSON value",serialize(e){return e},parseValue(e){return e},parseLiteral(e){switch(e.kind){case graphql.Kind.STRING:return e.value;case graphql.Kind.INT:case graphql.Kind.FLOAT:return parseFloat(e.value);case graphql.Kind.BOOLEAN:return e.value;case graphql.Kind.OBJECT:{let r={};for(let n of e.fields)r[n.name.value]=q.parseLiteral(n.value);return r}case graphql.Kind.LIST:return e.values.map(r=>q.parseLiteral(r));case graphql.Kind.NULL:return null;default:return null}}});function se(e){return r=>{let n=0;return {Field(){n++,n>e&&r.reportError(new Error(`Query exceeds max depth of ${e}`));},leaveField(){n--;}}}}function I(e){return e.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function H(e){let r=I(e);return r.charAt(0).toLowerCase()+r.slice(1)}function v(e){return e.endsWith("s")&&e.length>1?e.slice(0,-1):e}async function E(e,r,n){let l=e.access?.[r];if(n.apiKey){if(n.apiKey.permissions?.length>0){let a=e.slug,o=`${a}:${r==="read"?"read":r==="create"?"create":"update"}`;return !chunkNY47CFVP_cjs.h(n.apiKey.permissions,o)&&!chunkNY47CFVP_cjs.h(n.apiKey.permissions,`${a}:admin`)?{allowed:false}:{allowed:true}}if(l){let a=await chunkNY47CFVP_cjs.a(l,{req:n.req,user:n.user,tenantID:n.tenantID});return typeof a=="boolean"?{allowed:a}:{allowed:true,extraWhere:a}}return {allowed:true}}if(n.user){let a=e.slug,o=`${a}:${r==="read"?"read":r==="create"?"create":r==="update"?"update":"delete"}`;if(!chunkQ3Q7BJVQ_cjs.a({id:n.user.id,email:n.user.email,role:n.user.role},o)&&!chunkQ3Q7BJVQ_cjs.a({id:n.user.id,email:n.user.email,role:n.user.role},`${a}:admin`)&&!l)return {allowed:false}}if(!l)return n.user?{allowed:true}:{allowed:false};let f=await chunkNY47CFVP_cjs.a(l,{req:n.req,user:n.user,tenantID:n.tenantID});return typeof f=="boolean"?{allowed:f}:{allowed:true,extraWhere:f}}async function X(e,r,n){let l=e.access?.[r];if(n.apiKey){if(n.apiKey.permissions?.length>0){let a=e.slug,i=`${a}:${r}`;return !chunkNY47CFVP_cjs.h(n.apiKey.permissions,i)&&!chunkNY47CFVP_cjs.h(n.apiKey.permissions,`${a}:admin`)&&!chunkNY47CFVP_cjs.h(n.apiKey.permissions,`${a}:*`)?{allowed:false}:{allowed:true}}if(l){let a=await chunkNY47CFVP_cjs.a(l,{req:n.req,user:n.user,tenantID:n.tenantID});return {allowed:typeof a=="boolean"?a:true}}return {allowed:true}}if(!l){if(!n.user)return {allowed:false};let a=n.user.role;return a==="super_admin"||a==="admin"?{allowed:true}:{allowed:false}}let f=await chunkNY47CFVP_cjs.a(l,{req:n.req,user:n.user,tenantID:n.tenantID});return typeof f=="boolean"?{allowed:f}:{allowed:true}}function x(e,r){return e?e.startsWith("http://")||e.startsWith("https://")||e.startsWith("blob:")||e.startsWith("data:")?e:`${(process.env.KYRO_BASE_URL||r||"http://localhost:4321").replace(/\/+$/,"")}${e.startsWith("/")?"":"/"}${e}`:null}function K(e,r){return e&&(e.url&&(e.url=x(e.url,r)),e.thumbnailUrl&&(e.thumbnailUrl=x(e.thumbnailUrl,r)),e)}function k(e,r,n,l=false,f="Root",a=new Map){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "code":case "markdown":case "date":case "select":case "radio":return e.hasMany?new graphql.GraphQLList(graphql.GraphQLString):graphql.GraphQLString;case "list":return new graphql.GraphQLList(graphql.GraphQLString);case "upload":{let i=e;if(l)return i.hasMany?new graphql.GraphQLList(graphql.GraphQLString):graphql.GraphQLString;if(i.relationTo&&n?.[i.relationTo]){let o=n[i.relationTo];return i.hasMany?new graphql.GraphQLList(o):o}return q}case "image":{if(l)return graphql.GraphQLString;let i=e;return i.relationTo&&n?.[i.relationTo]?n[i.relationTo]:q}case "number":{let i=e.integer?graphql.GraphQLInt:graphql.GraphQLFloat;return e.hasMany?new graphql.GraphQLList(i):i}case "checkbox":return graphql.GraphQLBoolean;case "json":case "richtext":return q;case "blocks":{if(l)return q;let i=e,o=(i.blocks||[]).map(D=>{let m=`Block_${I(D.slug)}`,d=a.get(m);return d||(d=new graphql.GraphQLObjectType({name:m,fields:()=>{let y=j(D.fields||[],r,n,m,a);return y.blockType={type:graphql.GraphQLString},y.name={type:graphql.GraphQLString},y}}),a.set(m,d)),d});if(o.length===0)return q;let u=`${f}_${I(i.name)}_Blocks`,b=a.get(u);return b||(b=new graphql.GraphQLUnionType({name:u,types:o,resolveType:D=>`Block_${I(D.blockType||D.type)}`}),a.set(u,b)),new graphql.GraphQLList(b)}case "tabs":{if(l)return q;let i=e,o=`${f}_${I(i.name)}_Tabs`,u=a.get(o);return u||(u=new graphql.GraphQLObjectType({name:o,fields:()=>j(i.tabs?.flatMap(b=>b.fields||[])||[],r,n,o,a)}),a.set(o,u)),u}case "relationship":{let i=e.relationTo;if((i==="*"||Array.isArray(i)&&i.includes("*"))&&(i=r.getCollections().map(o=>o.slug)),typeof i=="string"){if(l)return e.hasMany?new graphql.GraphQLList(graphql.GraphQLString):graphql.GraphQLString;if(n?.[i])return e.hasMany?new graphql.GraphQLList(n[i]):n[i];let o=r.getCollection(i);if(o)return new graphql.GraphQLObjectType({name:`${I(i)}Ref`,fields:()=>({id:{type:graphql.GraphQLString},...N(o,r,n,a)})})}else if(Array.isArray(i)){if(l)return e.hasMany?new graphql.GraphQLList(q):q;let o=i.map(d=>{if(n?.[d])return n[d];let y=r.getCollection(d);if(y){let c=a.get(`${I(d)}Ref`);return c||(c=new graphql.GraphQLObjectType({name:`${I(d)}Ref`,fields:()=>({id:{type:graphql.GraphQLString},...N(y,r,n,a)})}),a.set(`${I(d)}Ref`,c)),c}return null}).filter(Boolean);if(o.length===0)return q;let u=`${f}_${I(e.name||"Ref")}_PolyUnion`,b=a.get(u);b||(b=new graphql.GraphQLUnionType({name:u,types:o,resolveType:d=>{if(d.__collection&&d.__collection!=="*")return n?.[d.__collection]?n[d.__collection].name:`${I(d.__collection)}Ref`}}),a.set(u,b));let D=`${f}_${I(e.name||"Ref")}_PolyWrapper`,m=a.get(D);return m||(m=new graphql.GraphQLObjectType({name:D,fields:{relationTo:{type:graphql.GraphQLString},value:{type:b}}}),a.set(D,m)),e.hasMany?new graphql.GraphQLList(m):m}return q}case "array":{if(l)return new graphql.GraphQLList(q);let i=e,o=`${f}_${I(i.name)}_ArrayItem`,u=a.get(o);return u||(u=new graphql.GraphQLObjectType({name:o,fields:()=>{let b=j(i.fields||[],r,n,o,a);return b.id={type:graphql.GraphQLString},b}}),a.set(o,u)),new graphql.GraphQLList(u)}case "group":{if(l)return q;let i=e,o=`${f}_${I(i.name)}_Group`,u=a.get(o);return u||(u=new graphql.GraphQLObjectType({name:o,fields:()=>j(i.fields||[],r,n,o,a)}),a.set(o,u)),u}default:return graphql.GraphQLString}}function j(e,r,n,l,f=new Map){let a={};for(let i of e){if(i.type==="tabs"&&!i.name){for(let o of i.tabs||[]){let u=j(o.fields||[],r,n,l,f);Object.assign(a,u);}continue}if(i.type==="row"||i.type==="collapsible"){let o=j(i.fields||[],r,n,l,f);Object.assign(a,o);continue}if(i.name&&i.admin?.hidden!==true){let o=ie(i,r,n,l,f);o&&(a[i.name]=o);}}return a}function N(e,r,n,l=new Map){return j(e.fields,r,n,I(v(e.slug)),l)}function ie(e,r,n,l,f=new Map){if(!e.name)return null;let a=e.deprecated||void 0;if(e.type==="upload"){let o=k(e,r,n,false,l,f),u=e;return {type:e.required?new graphql.GraphQLNonNull(o):o,description:e.admin?.description||e.label,deprecationReason:a,resolve:async(b,D,m)=>{let d=m?.relationLoader,y=b?.[u.name],c=m?.req?.url?new URL(m.req.url).origin:void 0;if(!y)return null;if(u.hasMany){let L=Array.isArray(y)?y:[];return Promise.all(L.map(async g=>{let G=typeof g=="string"?g:g?.id;if(!G||typeof g=="object"&&g?.url)return K(g,c);if(d){let F=d.resolveOne(u.relationTo,G);if(F)return K(F,c);let t=await d.load(u.relationTo,G);return t?K(t,c):null}return {id:G}}))}let w=typeof y=="string"?y:y?.id;if(!w||typeof y=="object"&&y?.url)return K(y,c);if(d){let L=d.resolveOne(u.relationTo,w);if(L)return K(L,c);let g=await d.load(u.relationTo,w);return g?K(g,c):null}return {id:w}}}}if(e.type==="relationship"&&!e.hasMany){let o=k(e,r,n,false,l,f);return {type:e.required?new graphql.GraphQLNonNull(o):o,description:e.admin?.description||e.label,deprecationReason:a,resolve:async(u,b,D)=>{let m=D?.relationLoader,d=e,y=u?.[d.name];if(!y)return null;let c=Array.isArray(d.relationTo)||d.relationTo==="*",w=c?y?.relationTo:d.relationTo,L=c?y?.value:y;if(c&&typeof y=="string"&&(w=d.relationTo[0],L=y),c&&w==="*")return null;if(m&&typeof L=="string"&&typeof w=="string"&&w!=="*"){let g=m.resolveOne(w,L);if(g)return c?{relationTo:w,value:{...g,__collection:w}}:g;let G=await m.load(w,L);return G?c?{relationTo:w,value:{...G,__collection:w}}:G:null}return c?{relationTo:w,value:{id:L,__collection:w}}:{id:L}}}}if(e.type==="relationship"&&e.hasMany)return {type:k(e,r,n,false,l,f),description:e.admin?.description||e.label,deprecationReason:a,resolve:async(u,b,D)=>{let m=D?.relationLoader,d=e,y=u?.[d.name]||[];if(typeof y=="string")try{y=JSON.parse(y);}catch{}if(Array.isArray(y)||(y=[]),!y.length)return [];let c=Array.isArray(d.relationTo)||d.relationTo==="*";if(m){let w=[];for(let L of y){let g=c?L?.relationTo:d.relationTo,G=c?L?.value:L;if(c&&typeof L=="string"&&(g=d.relationTo[0],G=L),!(c&&g==="*")){if(typeof G=="string"&&typeof g=="string"&&g!=="*"){let F=m.resolveOne(g,G);if(F){w.push(c?{relationTo:g,value:{...F,__collection:g}}:F);continue}let t=await m.load(g,G);if(t){w.push(c?{relationTo:g,value:{...t,__collection:g}}:t);continue}continue}w.push(c?{relationTo:g,value:{id:G,__collection:g}}:{id:G});}}return w}return y.map(w=>{let L=c?w?.relationTo:d.relationTo,g=c?w?.value:w;return c&&typeof w=="string"&&(L=d.relationTo[0],g=w),c?{relationTo:L,value:{id:g}}:{id:g}})}};if(e.type==="blocks"){let o=k(e,r,n,false,l,f);return {type:e.required?new graphql.GraphQLNonNull(o):o,description:e.admin?.description||e.label,deprecationReason:a,resolve:u=>{let b=u?.[e.name];if(typeof b=="string")try{b=JSON.parse(b);}catch{}return Array.isArray(b)?b.map(D=>D&&D.data&&D.type?{...D.data,id:D.id,type:D.type,blockType:D.type,name:D.name}:D):b}}}let i=k(e,r,n,false,l,f);return {type:e.required?new graphql.GraphQLNonNull(i):i,description:e.admin?.description||e.label,deprecationReason:a,resolve:o=>{let u=o?.[e.name];if(typeof u=="string"&&["array","group","tabs","blocks","json","richtext","list"].includes(e.type))try{u=JSON.parse(u);}catch{}return u}}}function ee(e){let{registry:r,db:n,user:l,req:f,tenantID:a,apiKey:i,settings:o}=e;if(o?.access?.apiAccess?.graphqlEnabled===false)throw new Error("GraphQL API is disabled");let b=r.getCollections(),D=r.getGlobals(),m={},d={},y=new Map;for(let t of b){m[t.slug]=new graphql.GraphQLObjectType({name:I(v(t.slug)),fields:()=>({id:{type:graphql.GraphQLString},...N(t,r,m,y),...t.timestamps?{createdAt:{type:graphql.GraphQLString},updatedAt:{type:graphql.GraphQLString}}:{},...t.tenantScoped?{tenantID:{type:graphql.GraphQLString}}:{}})});let Q={};for(let _ of t.fields)_.name&&_.name!=="id"&&(Q[_.name]={type:k(_,r,m,true)});d[t.slug]=new graphql.GraphQLInputObjectType({name:`${I(v(t.slug))}Input`,fields:()=>Q});}let c={},w={};for(let t of D)c[t.slug]=new graphql.GraphQLObjectType({name:`${I(t.slug)}Global`,fields:()=>({id:{type:graphql.GraphQLString},...N({slug:t.slug,fields:t.fields},r,m)})}),w[t.slug]=new graphql.GraphQLInputObjectType({name:`${I(t.slug)}GlobalInput`,fields:()=>{let Q={};for(let _ of t.fields)_.name&&_.name!=="id"&&(Q[_.name]={type:k(_,r,m,true)});return Q}});let L={};for(let t of b){let Q=m[t.slug];Q&&(L[H(t.slug)]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}FindResult`,fields:{docs:{type:new graphql.GraphQLList(Q)},totalDocs:{type:graphql.GraphQLInt},page:{type:graphql.GraphQLInt},totalPages:{type:graphql.GraphQLInt},hasNextPage:{type:graphql.GraphQLBoolean},hasPrevPage:{type:graphql.GraphQLBoolean}}}),args:{where:{type:graphql.GraphQLString},sort:{type:graphql.GraphQLString},limit:{type:graphql.GraphQLInt},page:{type:graphql.GraphQLInt},draft:{type:graphql.GraphQLBoolean}},resolve:async(_,T,s)=>{let p=await E(t,"read",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey});if(!p.allowed)throw new Error("Access denied");s.tenantID&&n.setTenantContext({tenantId:s.tenantID,userId:s.user?.id??"",role:s.user?.role,isSuperAdmin:s.user?.role==="super_admin"});let $={};if(T.where)try{$=JSON.parse(T.where);}catch{}p.extraWhere&&($={...$,...p.extraWhere});let O=T.draft??!!s.user;return n.find({collection:t.slug,where:$,sort:T.sort,limit:T.limit||10,page:T.page||1,tenantID:s.tenantID,draft:O})}},L[H(v(t.slug))]={type:Q,args:{id:{type:graphql.GraphQLString},slug:{type:graphql.GraphQLString},draft:{type:graphql.GraphQLBoolean}},resolve:async(_,T,s)=>{if(!T.id&&!T.slug)throw new Error("Either id or slug is required");if(!(await E(t,"read",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey})).allowed)throw new Error("Access denied");s.tenantID&&n.setTenantContext({tenantId:s.tenantID,userId:s.user?.id??"",role:s.user?.role,isSuperAdmin:s.user?.role==="super_admin"});let $=T.draft??!!s.user;return T.id?n.findByID({collection:t.slug,id:T.id,tenantID:s.tenantID,draft:$}):(await n.find({collection:t.slug,where:{slug:{equals:T.slug}},limit:1,page:1,tenantID:s.tenantID,draft:$})).docs?.[0]||null}},L[`count${I(t.slug)}`]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}Count`,fields:{totalDocs:{type:graphql.GraphQLInt}}}),args:{where:{type:graphql.GraphQLString}},resolve:async(_,T,s)=>{if(!(await E(t,"read",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey})).allowed)return {totalDocs:0};let $={};if(T.where)try{$=JSON.parse(T.where);}catch{}return {totalDocs:await n.count({collection:t.slug,where:$,tenantID:s.tenantID})}}});}for(let t of D){let Q=c[t.slug];Q&&(L[H(v(t.slug))]={type:Q,resolve:async(_,T,s)=>{if(!(await X(t,"read",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey})).allowed)throw new Error("Access denied: cannot read global");return s.tenantID&&n.setTenantContext({tenantId:s.tenantID,userId:s.user?.id??"",role:s.user?.role,isSuperAdmin:s.user?.role==="super_admin"}),n.findOne({collection:`_globals_${t.slug}`,where:{},tenantID:s.tenantID})}});}let g=new graphql.GraphQLObjectType({name:"Query",fields:L}),G={};for(let t of b){let Q=m[t.slug],_=d[t.slug];!Q||!_||(G[`create${I(v(t.slug))}`]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}CreateResult`,fields:{doc:{type:Q},message:{type:graphql.GraphQLString}}}),args:{data:{type:new graphql.GraphQLNonNull(_)}},resolve:async(T,s,p)=>{if(!(await E(t,"create",{user:p.user,req:p.req,tenantID:p.tenantID,apiKey:p.apiKey})).allowed)throw new Error("Access denied: cannot create");p.tenantID&&n.setTenantContext({tenantId:p.tenantID,userId:p.user?.id??"",role:p.user?.role,isSuperAdmin:p.user?.role==="super_admin"});let J=r.getCreateZodSchema(t.slug).parse(s.data);return {doc:await n.create({collection:t.slug,data:J,tenantID:p.tenantID}),message:"Created successfully"}}},G[`update${I(v(t.slug))}`]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}UpdateResult`,fields:{doc:{type:Q},message:{type:graphql.GraphQLString}}}),args:{id:{type:new graphql.GraphQLNonNull(graphql.GraphQLString)},data:{type:new graphql.GraphQLNonNull(_)},baseUpdatedAt:{type:graphql.GraphQLString}},resolve:async(T,s,p)=>{if(!(await E(t,"update",{user:p.user,req:p.req,tenantID:p.tenantID,apiKey:p.apiKey})).allowed)throw new Error("Access denied: cannot update");if(p.tenantID&&n.setTenantContext({tenantId:p.tenantID,userId:p.user?.id??"",role:p.user?.role,isSuperAdmin:p.user?.role==="super_admin"}),s.baseUpdatedAt){let W=await n.findByID({collection:t.slug,id:s.id,tenantID:p.tenantID,draft:true});if(W&&W.updatedAt&&s.baseUpdatedAt!==W.updatedAt)throw new Error(`Revision conflict: document has changed since ${s.baseUpdatedAt}. Current updatedAt: ${W.updatedAt}`)}let J=r.getUpdateZodSchema(t.slug).parse(s.data);return {doc:await n.update({collection:t.slug,id:s.id,data:J,tenantID:p.tenantID}),message:"Updated successfully"}}},G[`delete${I(v(t.slug))}`]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}DeleteResult`,fields:{doc:{type:Q},message:{type:graphql.GraphQLString}}}),args:{id:{type:new graphql.GraphQLNonNull(graphql.GraphQLString)}},resolve:async(T,s,p)=>{if(!(await E(t,"delete",{user:p.user,req:p.req,tenantID:p.tenantID,apiKey:p.apiKey})).allowed)throw new Error("Access denied: cannot delete");return p.tenantID&&n.setTenantContext({tenantId:p.tenantID,userId:p.user?.id??"",role:p.user?.role,isSuperAdmin:p.user?.role==="super_admin"}),{doc:await n.delete({collection:t.slug,id:s.id,tenantID:p.tenantID}),message:"Deleted successfully"}}});}for(let t of D){let Q=w[t.slug];Q&&(G[`update${I(t.slug)}`]={type:new graphql.GraphQLObjectType({name:`${I(t.slug)}UpdateResult`,fields:{doc:{type:c[t.slug]||graphql.GraphQLString},message:{type:graphql.GraphQLString}}}),args:{data:{type:new graphql.GraphQLNonNull(Q)}},resolve:async(_,T,s)=>{if(!(await X(t,"update",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey})).allowed)throw new Error("Access denied: cannot update global");s.tenantID&&n.setTenantContext({tenantId:s.tenantID,userId:s.user?.id??"",role:s.user?.role,isSuperAdmin:s.user?.role==="super_admin"});let $=await n.findOne({collection:`_globals_${t.slug}`,where:{},tenantID:s.tenantID}),O;return $?O=await n.update({collection:`_globals_${t.slug}`,id:$.id,data:T.data,tenantID:s.tenantID}):O=await n.create({collection:`_globals_${t.slug}`,data:T.data,tenantID:s.tenantID}),{doc:O,message:"Updated successfully"}}});}let F=new graphql.GraphQLObjectType({name:"Mutation",fields:G});return new graphql.GraphQLSchema({query:g,mutation:F})}function oe(e,r,n){return ee({registry:e,db:r,user:n?.user,req:n?.req,tenantID:n?.tenantID,apiKey:n?.apiKey})}
2
+ Object.defineProperty(exports,"e",{enumerable:true,get:function(){return graphql.printSchema}});exports.a=Z;exports.b=se;exports.c=ee;exports.d=oe;
@@ -1,4 +1,4 @@
1
- import {generateHTML}from'@tiptap/html';import d from'@tiptap/starter-kit';import s from'@tiptap/extension-link';import p from'@tiptap/extension-image';import c from'@tiptap/extension-text-align';import x from'@tiptap/extension-underline';import u from'@tiptap/extension-highlight';import m from'@tiptap/extension-task-list';import g from'@tiptap/extension-task-item';import {TextStyle}from'@tiptap/extension-text-style';import y from'@tiptap/extension-color';function b(e){return e.type==="text"}function h(e){return e.type==="number"}function k(e){return e.type==="relationship"}function R(e){return e.type==="array"}function B(e){return e.type==="group"}function T(e){return e.type==="blocks"}function w(e){return e.type==="upload"}function L(e){return e.type==="image"}function I(e){return e.type==="richtext"}function V(e){return e.type==="select"}function A(e){return e.type==="row"||e.type==="collapsible"||e.type==="tabs"}var r=["text","number","checkbox","date","email","password","textarea","select","radio","color"],n=["richtext","json","code","upload","image","markdown"],o=["relationship","array","group","blocks"],a=["row","collapsible","tabs"],C=[...r,...n,...o,...a];function S(e,t,i){return {name:e,type:"relationship",relationTo:t,...i,required:i?.required??false}}var Y=`
1
+ import {generateHTML}from'@tiptap/html';import s from'@tiptap/starter-kit';import d from'@tiptap/extension-link';import p from'@tiptap/extension-image';import c from'@tiptap/extension-text-align';import x from'@tiptap/extension-underline';import g from'@tiptap/extension-highlight';import u from'@tiptap/extension-task-list';import m from'@tiptap/extension-task-item';import {TextStyle}from'@tiptap/extension-text-style';import y from'@tiptap/extension-color';function b(e){return e.type==="text"}function h(e){return e.type==="number"}function k(e){return e.type==="relationship"}function R(e){return e.type==="array"}function B(e){return e.type==="group"}function T(e){return e.type==="blocks"}function w(e){return e.type==="upload"}function L(e){return e.type==="image"}function A(e){return e.type==="richtext"}function I(e){return e.type==="select"}function V(e){return e.type==="row"||e.type==="collapsible"||e.type==="tabs"}var r=["text","number","checkbox","date","email","password","textarea","select","radio","color"],n=["richtext","json","code","upload","image","markdown"],o=["relationship","array","group","blocks"],a=["row","collapsible","tabs"],C=[...r,...n,...o,...a];function D(e,t,i){return {name:e,type:"relationship",relationTo:t,...i,required:i?.required??false}}var Y=`
2
2
  .kyro-richtext {
3
3
  color: inherit;
4
4
  line-height: 1.7;
@@ -87,4 +87,4 @@ import {generateHTML}from'@tiptap/html';import d from'@tiptap/starter-kit';impor
87
87
  border-radius: 0.25rem;
88
88
  padding: 0.125rem 0.25rem;
89
89
  }
90
- `.trim(),f=[d,s.configure({openOnClick:false}),p,c.configure({types:["heading","paragraph"]}),x,u.configure({multicolor:true}),m,g.configure({nested:true}),TextStyle,y];function G(e){return typeof e=="object"&&e!==null?e:{}}function j(e){if(typeof e!="object"||e===null)return "";try{return `<div class="kyro-richtext">${generateHTML(e,f)}</div>`}catch(t){return console.error("Failed to render rich text:",t),""}}export{b as a,h as b,k as c,R as d,B as e,T as f,w as g,L as h,I as i,V as j,A as k,r as l,n as m,o as n,a as o,C as p,S as q,Y as r,G as s,j as t};
90
+ `.trim(),f=[s,d.configure({openOnClick:false}),p,c.configure({types:["heading","paragraph"]}),x,g.configure({multicolor:true}),u,m.configure({nested:true}),TextStyle,y];function G(e){return typeof e=="object"&&e!==null?e:{}}function j(e){if(typeof e!="object"||e===null)return "";try{return `<div class="kyro-richtext">${generateHTML(e,f)}</div>`}catch(t){return console.error("Failed to render rich text:",t),""}}export{b as a,h as b,k as c,R as d,B as e,T as f,w as g,L as h,A as i,I as j,V as k,r as l,n as m,o as n,a as o,C as p,D as q,Y as r,G as s,j as t};
@@ -1,5 +1,5 @@
1
1
  'use strict';var chunkW4ZDETHA_cjs=require('./chunk-W4ZDETHA.cjs'),drizzleOrm=require('drizzle-orm'),pgCore=require('drizzle-orm/pg-core'),sqliteCore=require('drizzle-orm/sqlite-core'),postgresJs=require('drizzle-orm/postgres-js'),oe=require('postgres'),crypto=require('crypto'),promises=require('fs/promises'),path=require('path'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var oe__default=/*#__PURE__*/_interopDefault(oe);var M=false;function D(p,s="postgres"){switch(p.type){case "text":case "email":case "password":case "color":return s==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return p.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return s==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return s==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Ae(p,s="postgres"){let n=p.slug.replace(/-/g,"_"),e=[];e.push(`export const ${n} = pgTable('${n}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let t of p.fields){if(t.name==="id")continue;let o=D(t,s),r=t.required,a=` ${t.name}: pg.${o}('${t.name}')`;t.unique&&(a+=".unique()"),r||(a+=".nullable()"),t.defaultValue!==void 0&&(typeof t.defaultValue=="string"?a+=`.default('${t.defaultValue}')`:typeof t.defaultValue=="boolean"?a+=`.default(${t.defaultValue})`:a+=`.default(sql\`${JSON.stringify(t.defaultValue)}\`)`),a+=",",e.push(a);}return p.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${s==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${s==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
2
- `)}var S=class extends chunkW4ZDETHA_cjs.a{client;schema;dialect;connectionString;versionsTableReady=false;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let n=s.connectionString.toLowerCase();n.startsWith("postgres://")||n.startsWith("postgresql://")?this.dialect="postgres":n.includes(".db")||n.includes("sqlite")||n.includes("file:")?this.dialect="sqlite":this.dialect=s.type||"postgres";}else this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,n){let e=super.prepareData(s,n);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of n.fields)if(t.type==="date"&&t.name){let o=e[t.name];o&&typeof o=="string"&&(e[t.name]=new Date(o));}for(let t of n.fields){let r=D(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let a=s[t.name];if(a&&typeof a=="object"){let i={};for(let[c,u]of Object.entries(a)){let d=t.tabs.flatMap(h=>h.fields).find(h=>h.name===c);(d?.type==="upload"||d?.type==="image"||d?.type==="list"||d?.type==="relationship-block")&&u?i[c]=Array.isArray(u)||typeof u=="object"?JSON.stringify(u):u:i[c]=u;}e[t.name]=this.dialect==="sqlite"||!r?JSON.stringify(i):i;}}else if(r&&t.name&&s[t.name]!==void 0&&s[t.name]!==null)e[t.name]=this.dialect==="sqlite"?JSON.stringify(s[t.name]):s[t.name];else if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let a=s[t.name];a!=null&&(e[t.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let t of n.fields)if(t.name&&e[t.name]===""){let o=D(t,this.dialect);(o==="timestamp"||o==="jsonb"||o==="decimal"||o==="integer"||o==="numeric"||o==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let{default:s}=await import('postgres'),{drizzle:n}=await import('drizzle-orm/postgres-js'),e=s(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let{default:s}=await import('better-sqlite3'),{drizzle:n}=await import('drizzle-orm/better-sqlite3'),e=new s(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}this.connected=true;}async init(s,n=[]){if(await super.init(s,n),this.connectionString&&!this.client&&await this.connect(),this.client&&!M){for(let t of s){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t));}await this.ensureCollectionTables(s);let e=n.map(t=>({slug:`_globals_${t.slug}`,fields:t.fields,label:t.label}));for(let t of e){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t,true)),this.collections.has(t.slug)||this.collections.set(t.slug,t);}await this.ensureCollectionTables(e),M=true;}}createTableFromConfig(s,n=false){let e=this.getTableName(s.slug),t={id:n?pgCore.text("id").primaryKey():pgCore.uuid("id").primaryKey().defaultRandom()};for(let o of s.fields){if(!o.name||o.name==="id")continue;let r=D(o,this.dialect),a=o.name.replace(/-/g,"_"),i=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=sqliteCore.text(i);break;case "integer":c=sqliteCore.integer(i);break;case "decimal":case "numeric":c=sqliteCore.numeric(i);break;case "boolean":c=sqliteCore.integer(i,{mode:"boolean"});break;case "timestamp":c=sqliteCore.text(i);break;case "jsonb":c=sqliteCore.text(i);break;default:c=sqliteCore.text(i);}else switch(r){case "varchar":c=pgCore.varchar(i,{length:255});break;case "integer":c=pgCore.integer(i);break;case "decimal":c=pgCore.decimal(i);break;case "boolean":c=pgCore.boolean(i);break;case "timestamp":c=pgCore.timestamp(i);break;case "jsonb":c=pgCore.jsonb(i);break;default:c=pgCore.text(i);}o.required||(c=c.default(null)),t[a]=c;}return t.createdAt||(t.createdAt=this.dialect==="sqlite"?sqliteCore.text("created_at").default(new Date().toISOString()):pgCore.timestamp("created_at").defaultNow()),t.updatedAt||(t.updatedAt=this.dialect==="sqlite"?sqliteCore.text("updated_at").default(new Date().toISOString()):pgCore.timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(t.status||(t.status=this.dialect==="sqlite"?sqliteCore.text("status").default("draft"):pgCore.varchar("status",{length:20}).default("draft")),t.hasDraft||(t.hasDraft=this.dialect==="sqlite"?sqliteCore.integer("hasDraft",{mode:"boolean"}).default(false):pgCore.boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteCore.sqliteTable(e,t):pgCore.pgTable(e,t)}async ensureCollectionTables(s){let n=[];for(let e of s){let t=e.slug.startsWith("_globals_"),o=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(d=>d.name==="createdAt"),i=e.fields.some(d=>d.name==="updatedAt"),c=e.fields.some(d=>d.name==="status"),u=e.fields.some(d=>d.name==="hasDraft");if(this.dialect==="postgres"){let d=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
2
+ `)}var S=class extends chunkW4ZDETHA_cjs.a{client;schema;dialect;connectionString;versionsTableReady=false;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let n=s.connectionString.toLowerCase();n.startsWith("postgres://")||n.startsWith("postgresql://")?this.dialect="postgres":n.includes(".db")||n.includes("sqlite")||n.includes("file:")?this.dialect="sqlite":this.dialect=s.type||"postgres";}else this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,n){let e=super.prepareData(s,n);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of n.fields)if(t.type==="date"&&t.name){let o=e[t.name];o&&typeof o=="string"&&(e[t.name]=new Date(o));}for(let t of n.fields){let r=D(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let a=s[t.name];if(a&&typeof a=="object"){let i={};for(let[c,u]of Object.entries(a)){let d=t.tabs.flatMap(m=>m.fields).find(m=>m.name===c);(d?.type==="upload"||d?.type==="image"||d?.type==="list"||d?.type==="relationship-block")&&u?i[c]=Array.isArray(u)||typeof u=="object"?JSON.stringify(u):u:i[c]=u;}e[t.name]=this.dialect==="sqlite"||!r?JSON.stringify(i):i;}}else if(r&&t.name&&s[t.name]!==void 0&&s[t.name]!==null)e[t.name]=this.dialect==="sqlite"?JSON.stringify(s[t.name]):s[t.name];else if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let a=s[t.name];a!=null&&(e[t.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let t of n.fields)if(t.name&&e[t.name]===""){let o=D(t,this.dialect);(o==="timestamp"||o==="jsonb"||o==="decimal"||o==="integer"||o==="numeric"||o==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let{default:s}=await import('postgres'),{drizzle:n}=await import('drizzle-orm/postgres-js'),e=s(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let{default:s}=await import('better-sqlite3'),{drizzle:n}=await import('drizzle-orm/better-sqlite3'),e=new s(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}this.connected=true;}async init(s,n=[]){if(await super.init(s,n),this.connectionString&&!this.client&&await this.connect(),this.client&&!M){for(let t of s){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t));}await this.ensureCollectionTables(s);let e=n.map(t=>({slug:`_globals_${t.slug}`,fields:t.fields,label:t.label}));for(let t of e){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t,true)),this.collections.has(t.slug)||this.collections.set(t.slug,t);}await this.ensureCollectionTables(e),M=true;}}createTableFromConfig(s,n=false){let e=this.getTableName(s.slug),t={id:n?pgCore.text("id").primaryKey():pgCore.uuid("id").primaryKey().defaultRandom()};for(let o of s.fields){if(!o.name||o.name==="id")continue;let r=D(o,this.dialect),a=o.name.replace(/-/g,"_"),i=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=sqliteCore.text(i);break;case "integer":c=sqliteCore.integer(i);break;case "decimal":case "numeric":c=sqliteCore.numeric(i);break;case "boolean":c=sqliteCore.integer(i,{mode:"boolean"});break;case "timestamp":c=sqliteCore.text(i);break;case "jsonb":c=sqliteCore.text(i);break;default:c=sqliteCore.text(i);}else switch(r){case "varchar":c=pgCore.varchar(i,{length:255});break;case "integer":c=pgCore.integer(i);break;case "decimal":c=pgCore.decimal(i);break;case "boolean":c=pgCore.boolean(i);break;case "timestamp":c=pgCore.timestamp(i);break;case "jsonb":c=pgCore.jsonb(i);break;default:c=pgCore.text(i);}o.required||(c=c.default(null)),t[a]=c;}return t.createdAt||(t.createdAt=this.dialect==="sqlite"?sqliteCore.text("created_at").default(new Date().toISOString()):pgCore.timestamp("created_at").defaultNow()),t.updatedAt||(t.updatedAt=this.dialect==="sqlite"?sqliteCore.text("updated_at").default(new Date().toISOString()):pgCore.timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(t.status||(t.status=this.dialect==="sqlite"?sqliteCore.text("status").default("draft"):pgCore.varchar("status",{length:20}).default("draft")),t.hasDraft||(t.hasDraft=this.dialect==="sqlite"?sqliteCore.integer("hasDraft",{mode:"boolean"}).default(false):pgCore.boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteCore.sqliteTable(e,t):pgCore.pgTable(e,t)}async ensureCollectionTables(s){let n=[];for(let e of s){let t=e.slug.startsWith("_globals_"),o=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(d=>d.name==="createdAt"),i=e.fields.some(d=>d.name==="updatedAt"),c=e.fields.some(d=>d.name==="status"),u=e.fields.some(d=>d.name==="hasDraft");if(this.dialect==="postgres"){let d=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
3
3
  CREATE TABLE IF NOT EXISTS "${o}" (
4
4
  ${d},
5
5
  ${r}
@@ -20,25 +20,25 @@
20
20
  `);}if(n.length>0)if(this.dialect==="postgres")await this.client.execute(drizzleOrm.sql.raw(n.join(`;
21
21
  `)));else for(let e of n)await this.client.execute(drizzleOrm.sql.raw(e));for(let e of s){let t=this.getTableName(e.slug);t==="users"||t==="audit_logs"||await this.syncTableColumns(e,t);}}getColumnSqlDefinition(s,n){let e=D(s,n),t=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),o=this.columnSqlType(e,n);return `"${t}" ${o} DEFAULT NULL`}columnSqlType(s,n){if(n==="sqlite")switch(s){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(s){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(s,n){let e={},t=s.slug.startsWith("_globals_"),o=s.fields.some(c=>c.name==="createdAt"),r=s.fields.some(c=>c.name==="updatedAt"),a=s.fields.some(c=>c.name==="status"),i=s.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',o||(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'),i||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',o||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),i||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of s.fields){if(!c.name||c.name==="id")continue;let u=this.getColumnSqlDefinition(c,this.dialect),d=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[d]=u;}return e}async syncTableColumns(s,n){let e;try{if(this.dialect==="postgres"){let r=await this.client.execute(drizzleOrm.sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${n}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.client.execute(drizzleOrm.sql`PRAGMA table_info("${drizzleOrm.sql.raw(n)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let t=this.getExpectedColumnDefs(s,n),o=Object.keys(t).filter(r=>!e.has(r));if(o.length>0){let r=o.map(a=>`ALTER TABLE "${n}" ADD COLUMN ${t[a]}`);await this.executeRaw(drizzleOrm.sql.raw(r.join(`;
22
22
  `)));}if(this.dialect==="postgres")for(let r of s.fields){if(!r.name||r.name==="id")continue;let a=D(r,this.dialect),i=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(i);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" DROP DEFAULT`)),await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE JSONB USING (CASE WHEN "${i}" IS NULL THEN NULL WHEN "${i}"::text ~ '^\\s*\\{' THEN "${i}"::jsonb ELSE jsonb_build_object('id', "${i}"::text) END)`))));}}generateCreateColumns(s){let n=[];for(let e of s.fields){if(!e.name||e.name==="id")continue;let t=D(e,this.dialect),o=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(t){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(t){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}`;}n.push(`"${o}" ${a}`);}return n.join(`,
23
- `)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:t,limit:o=10,page:r=1,tenantID:a,select:i,draft:c}=s,u=this.getCollection(n),d=this.getTable(n),T={...e};this.tenantContext&&u.tenantScoped&&(T=chunkW4ZDETHA_cjs.c({where:T},n,this.tenantContext,chunkW4ZDETHA_cjs.b).where||{});let h=this.buildWhereClause(T,u,d,a),m=u.fields.find(f=>f.name==="status"),g=m?.type==="select"&&m.options?.some(f=>f.value==="published");!c&&d.status&&g&&h.push(drizzleOrm.eq(d.status,"published"));let E=this.parseSort(t),R=!c&&d.status&&g?{...T,status:"published"}:T,j=await this.count({collection:n,where:R,tenantID:a}),B=(r-1)*o,v=[];try{let f=d[E.field]||d.createdAt||d.id,N=E.direction==="asc"?f:drizzleOrm.desc(f),b=this.client.select().from(d);h.length>0&&(b=b.where(drizzleOrm.and(...h))),v=await b.orderBy(N).limit(o).offset(B);}catch(f){console.error("[DrizzleAdapter] Query error:",f);}let _=v.map(f=>this.processResult(f,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(_=_.filter(f=>chunkW4ZDETHA_cjs.d(f,n,this.tenantContext,chunkW4ZDETHA_cjs.b))),c&&(_=await Promise.all(_.map(async f=>{let N=await this.executeRaw(drizzleOrm.sql`
23
+ `)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:t,limit:o=10,page:r=1,tenantID:a,select:i,draft:c}=s,u=this.getCollection(n),d=this.getTable(n),T={...e};this.tenantContext&&u.tenantScoped&&(T=chunkW4ZDETHA_cjs.c({where:T},n,this.tenantContext,chunkW4ZDETHA_cjs.b).where||{});let m=this.buildWhereClause(T,u,d,a),h=u.fields.find(f=>f.name==="status"),y=h?.type==="select"&&Array.isArray(h.options)&&h.options.some(f=>f.value==="published");!c&&d.status&&y&&m.push(drizzleOrm.eq(d.status,"published"));let E=this.parseSort(t),R=!c&&d.status&&y?{...T,status:"published"}:T,j=await this.count({collection:n,where:R,tenantID:a}),B=(r-1)*o,v=[];try{let f=d[E.field]||d.createdAt||d.id,N=E.direction==="asc"?f:drizzleOrm.desc(f),b=this.client.select().from(d);m.length>0&&(b=b.where(drizzleOrm.and(...m))),v=await b.orderBy(N).limit(o).offset(B);}catch(f){console.error("[DrizzleAdapter] Query error:",f);}let _=v.map(f=>this.processResult(f,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(_=_.filter(f=>chunkW4ZDETHA_cjs.d(f,n,this.tenantContext,chunkW4ZDETHA_cjs.b))),c&&(_=await Promise.all(_.map(async f=>{let N=await this.executeRaw(drizzleOrm.sql`
24
24
  SELECT * FROM kyro_versions
25
25
  WHERE collection_slug = ${n}
26
26
  AND document_id = ${f.id}
27
27
  ORDER BY created_at DESC
28
28
  LIMIT 1
29
- `);if(N.length>0){let b=N[0],X=typeof b.data=="string"?JSON.parse(b.data):b.data;return {...f,...X,status:f.status}}return f}))),{docs:_,...this.calculatePagination(r,o,j)}}async findByID(s){let{collection:n,id:e,tenantID:t,draft:o}=s,r=this.getCollection(n),a=this.getTable(n);if(this.tenantContext&&r.tenantScoped){let m={id:e,tenantId:this.tenantContext.tenantId};if(!chunkW4ZDETHA_cjs.d(m,n,this.tenantContext,chunkW4ZDETHA_cjs.b))return null}let i=[drizzleOrm.eq(a.id,e)];t&&a.tenantId&&i.push(drizzleOrm.eq(a.tenantId,t));let c=r.fields.find(m=>m.name==="status"),u=c?.type==="select"&&c.options?.some(m=>m.value==="published");!o&&a.status&&u&&i.push(drizzleOrm.eq(a.status,"published"));let d=i.length>1?drizzleOrm.and(...i):i[0],T=await this.client.select().from(a).where(d);if(T.length===0)return null;let h=this.processResult(T[0],r);if(o){let m=await this.executeRaw(drizzleOrm.sql`
29
+ `);if(N.length>0){let b=N[0],X=typeof b.data=="string"?JSON.parse(b.data):b.data;return {...f,...X,status:f.status}}return f}))),{docs:_,...this.calculatePagination(r,o,j)}}async findByID(s){let{collection:n,id:e,tenantID:t,draft:o}=s,r=this.getCollection(n),a=this.getTable(n);if(this.tenantContext&&r.tenantScoped){let h={id:e,tenantId:this.tenantContext.tenantId};if(!chunkW4ZDETHA_cjs.d(h,n,this.tenantContext,chunkW4ZDETHA_cjs.b))return null}let i=[drizzleOrm.eq(a.id,e)];t&&a.tenantId&&i.push(drizzleOrm.eq(a.tenantId,t));let c=r.fields.find(h=>h.name==="status"),u=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(h=>h.value==="published");!o&&a.status&&u&&i.push(drizzleOrm.eq(a.status,"published"));let d=i.length>1?drizzleOrm.and(...i):i[0],T=await this.client.select().from(a).where(d);if(T.length===0)return null;let m=this.processResult(T[0],r);if(o){let h=await this.executeRaw(drizzleOrm.sql`
30
30
  SELECT * FROM kyro_versions
31
31
  WHERE collection_slug = ${n}
32
- AND document_id = ${h.id}
32
+ AND document_id = ${m.id}
33
33
  ORDER BY created_at DESC
34
34
  LIMIT 1
35
- `);if(m.length>0){let g=m[0],E=typeof g.data=="string"?JSON.parse(g.data):g.data;h={...h,...E,status:h.status};}}return h}async create(s){let{collection:n,data:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.prepareData(e,o);t&&(a.tenantId=t);let i=await this.client.insert(r).values(a).returning();return this.processResult(i[0],o)}async update(s){let{collection:n,id:e,data:t,tenantID:o}=s,r=this.getCollection(n),a=this.getTable(n),i=this.prepareData(t,r);delete i.id;let c=[drizzleOrm.eq(a.id,e)];o&&a.tenantId&&c.push(drizzleOrm.eq(a.tenantId,o));let u=await this.client.update(a).set(i).where(drizzleOrm.and(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(u[0],r)}async delete(s){let{collection:n,id:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=[drizzleOrm.eq(r.id,e)];t&&r.tenantId&&a.push(drizzleOrm.eq(r.tenantId,t));let i=await this.client.delete(r).where(drizzleOrm.and(...a)).returning();if(i.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(i[0],o)}async count(s){let{collection:n,where:e={},tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.buildWhereClause(e,o,r,t);try{let i=this.client.select({count:drizzleOrm.sql`count(*)`}).from(r);a.length>0&&(i=i.where(drizzleOrm.and(...a)));let c=await i;return Number(c[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:n,where:e={},tenantID:t,draft:o}=s;if(n.startsWith("_globals_")){let a=n.replace("_globals_",""),i=this.globals.get(a);if(!i)throw new Error(`Global "${a}" not found`);let c=this.getTable(n),u=this.client.select().from(c),d=i.fields.find(g=>g.name==="status"),T=d?.type==="select"&&d.options?.some(g=>g.value==="published");!o&&c.status&&T&&(u=u.where(drizzleOrm.eq(c.status,"published")));let h=await u.limit(1);if(h.length===0)return null;let m=this.processResult(h[0],i);if(o){let g=await this.executeRaw(drizzleOrm.sql`
35
+ `);if(h.length>0){let y=h[0],E=typeof y.data=="string"?JSON.parse(y.data):y.data;m={...m,...E,status:m.status};}}return m}async create(s){let{collection:n,data:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.prepareData(e,o);t&&(a.tenantId=t);let i=await this.client.insert(r).values(a).returning();return this.processResult(i[0],o)}async update(s){let{collection:n,id:e,data:t,tenantID:o}=s,r=this.getCollection(n),a=this.getTable(n),i=this.prepareData(t,r);delete i.id;let c=[drizzleOrm.eq(a.id,e)];o&&a.tenantId&&c.push(drizzleOrm.eq(a.tenantId,o));let u=await this.client.update(a).set(i).where(drizzleOrm.and(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(u[0],r)}async delete(s){let{collection:n,id:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=[drizzleOrm.eq(r.id,e)];t&&r.tenantId&&a.push(drizzleOrm.eq(r.tenantId,t));let i=await this.client.delete(r).where(drizzleOrm.and(...a)).returning();if(i.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(i[0],o)}async count(s){let{collection:n,where:e={},tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.buildWhereClause(e,o,r,t);try{let i=this.client.select({count:drizzleOrm.sql`count(*)`}).from(r);a.length>0&&(i=i.where(drizzleOrm.and(...a)));let c=await i;return Number(c[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:n,where:e={},tenantID:t,draft:o}=s;if(n.startsWith("_globals_")){let a=n.replace("_globals_",""),i=this.globals.get(a);if(!i)throw new Error(`Global "${a}" not found`);let c=this.getTable(n),u=this.client.select().from(c),d=i.fields.find(y=>y.name==="status"),T=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(y=>y.value==="published");!o&&c.status&&T&&(u=u.where(drizzleOrm.eq(c.status,"published")));let m=await u.limit(1);if(m.length===0)return null;let h=this.processResult(m[0],i);if(o){let y=await this.executeRaw(drizzleOrm.sql`
36
36
  SELECT * FROM kyro_versions
37
37
  WHERE collection_slug = ${n}
38
38
  AND document_id = ${a}
39
39
  ORDER BY created_at DESC
40
40
  LIMIT 1
41
- `);if(g.length>0){let E=g[0],R=typeof E.data=="string"?JSON.parse(E.data):E.data;m={...m,...R,status:m.status};}}return m}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:t=10,page:o=1,tenantID:r}=s,a=(o-1)*t,i=await this.executeRaw(drizzleOrm.sql`
41
+ `);if(y.length>0){let E=y[0],R=typeof E.data=="string"?JSON.parse(E.data):E.data;h={...h,...R,status:h.status};}}return h}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:t=10,page:o=1,tenantID:r}=s,a=(o-1)*t,i=await this.executeRaw(drizzleOrm.sql`
42
42
  SELECT count(*) as count
43
43
  FROM kyro_versions
44
44
  WHERE collection_slug = ${n}
@@ -129,5 +129,5 @@
129
129
  created_at text NOT NULL,
130
130
  updated_at text NOT NULL
131
131
  )
132
- `,await this.executeRaw(drizzleOrm.sql.raw(s));try{this.dialect==="postgres"?await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(s){let n=await this.client.execute(s);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}};function De(p){return new S(p)}var fe=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-RLDAQ7IH.cjs', document.baseURI).href))),pe="node:sqlite",{DatabaseSync:he}=fe(pe);function me(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function P(){return crypto.randomBytes(16).toString("hex")}async function $e(){let p=me();if(p==="sqlite"){let r=path.resolve(process.cwd(),"data","kyro.db");await promises.mkdir(path.dirname(r),{recursive:true});let a=new he(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:p,genId:P}}let s=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",n=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",t=oe__default.default(s,{max:n,ssl:e?"require":false,onnotice:()=>{}});return {db:postgresJs.drizzle(t),dialect:p,genId:P}}async function Se(p,s){}async function ve(p){let{roles:s}=await import('./schema-HIUSHSUI.cjs');await p.insert(s).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
132
+ `,await this.executeRaw(drizzleOrm.sql.raw(s));try{this.dialect==="postgres"?await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(s){let n=await this.client.execute(s);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}};function De(p){return new S(p)}var fe=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-QAJS4EXW.cjs', document.baseURI).href))),pe="node:sqlite",{DatabaseSync:he}=fe(pe);function me(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function P(){return crypto.randomBytes(16).toString("hex")}async function $e(){let p=me();if(p==="sqlite"){let r=path.resolve(process.cwd(),"data","kyro.db");await promises.mkdir(path.dirname(r),{recursive:true});let a=new he(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:p,genId:P}}let s=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",n=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",t=oe__default.default(s,{max:n,ssl:e?"require":false,onnotice:()=>{}});return {db:postgresJs.drizzle(t),dialect:p,genId:P}}async function Se(p,s){}async function ve(p){let{roles:s}=await import('./schema-HIUSHSUI.cjs');await p.insert(s).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
133
133
  exports.a=D;exports.b=Ae;exports.c=S;exports.d=De;exports.e=P;exports.f=$e;exports.g=Se;exports.h=ve;
@@ -0,0 +1,21 @@
1
+ 'use strict';var chunk65G73T7Z_cjs=require('./chunk-65G73T7Z.cjs'),chunkKD7LUCFY_cjs=require('./chunk-KD7LUCFY.cjs'),chunkBDBN4RN6_cjs=require('./chunk-BDBN4RN6.cjs'),chunkO7FYIPJW_cjs=require('./chunk-O7FYIPJW.cjs'),chunk43U2NBVS_cjs=require('./chunk-43U2NBVS.cjs'),chunk4FV3HQBI_cjs=require('./chunk-4FV3HQBI.cjs'),chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkF7SR5IDT_cjs=require('./chunk-F7SR5IDT.cjs'),chunkQAJS4EXW_cjs=require('./chunk-QAJS4EXW.cjs'),chunkMIOMMB23_cjs=require('./chunk-MIOMMB23.cjs'),chunkW4ZDETHA_cjs=require('./chunk-W4ZDETHA.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga'),module$1=require('module'),crypto=require('crypto');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function O(s,e){for(let t of s){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let n of t.tabs)if(O(n.fields,e))return true}if("fields"in t&&t.fields&&O(t.fields,e))return true}return false}var K=class extends Error{errors;constructor(e){super(`Configuration validation failed:
2
+ ${e.join(`
3
+ `)}`),this.name="ConfigValidationError",this.errors=e;}};function V(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Collection slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Collection "${s.slug}" has no fields defined`);else {let t=N(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,n]of Object.entries(s.access))typeof n!="boolean"&&typeof n!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(O(s.fields,s.admin.useAsTitle)||e.push(`Collection "${s.slug}" admin.useAsTitle references unknown field "${s.admin.useAsTitle}"`)),s.admin?.defaultColumns)for(let t of s.admin.defaultColumns)O(s.fields,t)||e.push(`Collection "${s.slug}" admin.defaultColumns references unknown field "${t}"`);if(s.upload&&s.upload.fileSize&&s.upload.fileSize<=0&&e.push(`Collection "${s.slug}" upload.fileSize must be positive`),s.versions&&s.versions.maxPerDoc&&s.versions.maxPerDoc<=0&&e.push(`Collection "${s.slug}" versions.maxPerDoc must be positive`),s.auth){let t=s.fields.some(a=>a.name==="email"),n=s.fields.some(a=>a.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),n||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function B(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Global slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Global "${s.slug}" has no fields defined`);else {let t=N(s.fields,`global:${s.slug}`);e.push(...t);}return e}function N(s,e){let t=[],n=new Set;for(let a=0;a<s.length;a++){let i=s[a];if(i.type==="row"||i.type==="collapsible"||i.type==="tabs"){if("fields"in i&&i.fields){let r=N(i.fields,e);t.push(...r);}else if("tabs"in i)for(let r of i.tabs){let c=N(r.fields,e);t.push(...c);}continue}let o=i.name;if(!o){t.push(`${e}: Field at index ${a} is missing a "name" property`);continue}if(n.has(o)&&t.push(`${e}: Duplicate field name "${o}"`),n.add(o),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(o)||t.push(`${e}: Field name "${o}" must be alphanumeric with underscores`),!i.type){t.push(`${e}: Field "${o}" is missing a "type" property`);continue}switch(i.type){case "relationship":i.relationTo||t.push(`${e}: Relationship field "${o}" is missing "relationTo"`);break;case "array":if(!i.fields||i.fields.length===0)t.push(`${e}: Array field "${o}" has no fields defined`);else {let r=N(i.fields,`${e}.${o}`);t.push(...r);}break;case "group":if(!i.fields||i.fields.length===0)t.push(`${e}: Group field "${o}" has no fields defined`);else {let r=N(i.fields,`${e}.${o}`);t.push(...r);}break;case "blocks":if(!i.blocks||i.blocks.length===0)t.push(`${e}: Blocks field "${o}" has no blocks defined`);else {let r=Fe(i.blocks,`${e}.${o}`);t.push(...r);}break;case "select":case "radio":if(typeof i.options=="function")break;if((!i.options||i.options.length===0)&&!i.dynamicOptions)t.push(`${e}: ${i.type} field "${o}" has no options defined`);else if(Array.isArray(i.options)){let r=i.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${i.type} field "${o}" has duplicate option values`);}break;case "upload":i.relationTo||t.push(`${e}: Upload field "${o}" is missing "relationTo"`);break}"min"in i&&"max"in i&&i.min>i.max&&t.push(`${e}: Field "${o}" has min greater than max`),"minLength"in i&&"maxLength"in i&&i.minLength>i.maxLength&&t.push(`${e}: Field "${o}" has minLength greater than maxLength`),"minRows"in i&&"maxRows"in i&&i.minRows>i.maxRows&&t.push(`${e}: Field "${o}" has minRows greater than maxRows`);}return t}function Fe(s,e){let t=[],n=new Set;for(let a of s){if(!a.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(a.slug)&&t.push(`${e}: Duplicate block slug "${a.slug}"`),n.add(a.slug),a.label||t.push(`${e}: Block "${a.slug}" is missing a "label" property`),!a.fields||a.fields.length===0)t.push(`${e}: Block "${a.slug}" has no fields defined`);else {let i=N(a.fields,`${e}.${a.slug}`);t.push(...i);}}return t}function fe(s,e=[]){let t=[],n=new Set;for(let a of s)n.has(a.slug)&&t.push(`Duplicate collection slug "${a.slug}"`),n.add(a.slug);for(let a of e)n.has(a.slug)&&t.push(`Duplicate global slug "${a.slug}"`),n.add(a.slug);for(let a of s){let i=V(a);t.push(...i);}for(let a of e){let i=B(a);t.push(...i);}for(let a of s){let i=$(a.fields,s);t.push(...i);}if(t.length>0)throw new K(t)}function $(s,e){let t=[],n=new Set(e.map(a=>a.slug));for(let a of s){if(a.type==="relationship"){let i=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let o of i)n.has(o)||console.warn(`[Kyro Config Warning]: Relationship field "${a.name}" references unknown collection "${o}". Select options will not be available until this collection is registered.`);}if(a.type==="upload"){let i=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let o of i)n.has(o)||t.push(`Upload field "${a.name}" references unknown collection "${o}"`);}if("fields"in a&&a.fields){let i=$(a.fields,e);t.push(...i);}if("tabs"in a)for(let i of a.tabs){let o=$(i.fields,e);t.push(...o);}if("blocks"in a)for(let i of a.blocks){let o=$(i.fields,e);t.push(...o);}}return t}function A(s){switch(s.type){case "text":return Ie(s);case "number":return $e(s);case "checkbox":return Oe(s);case "date":return Pe(s);case "email":return Le(s);case "password":return ke(s);case "textarea":return _e(s);case "select":return je(s);case "radio":return Ze(s);case "color":return qe(s);case "richtext":return Ue(s);case "json":return Ge(s);case "code":return Ke(s);case "upload":return ye(s);case "image":return ye(s);case "markdown":return Ve(s);case "relationship":return he(s);case "relationship-block":return he(s);case "array":return Be(s);case "list":return Me(s);case "group":return ze(s);case "blocks":return We(s);case "row":return Xe(s);case "collapsible":return Je(s);case "tabs":return He(s);default:return zod.z.any()}}function Ie(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.pattern&&(e=e.regex(new RegExp(s.pattern))),s.variant==="email"&&(e=e.email()),s.variant==="url"&&(e=e.url()),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function $e(s){let e=s.integer?zod.z.coerce.number().int():zod.z.coerce.number();return s.min!==void 0&&(e=e.min(s.min)),s.max!==void 0&&(e=e.max(s.max)),s.step&&(e=e.refine(t=>Number.isInteger(t/s.step),`Value must be divisible by ${s.step}`)),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Oe(s){let e=zod.z.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Pe(s){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return s.minDate&&(e=e.refine(t=>new Date(t)>=new Date(s.minDate),`Date must be after ${s.minDate}`)),s.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(s.maxDate),`Date must be before ${s.maxDate}`)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Le(s){let e=zod.z.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ke(s){let e=zod.z.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function _e(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function je(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);s.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=s.hasMany?zod.z.array(zod.z.string()):zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ze(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(n=>n.value);e=zod.z.enum(t);}else e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function qe(s){let e=zod.z.string();return s.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),s.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),s.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ue(s){let e=zod.z.array(zod.z.record(zod.z.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ge(s){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ke(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ye(s){let e;if(s.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ve(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function he(s){let e;return Array.isArray(s.relationTo)?e=zod.z.object({relationTo:zod.z.enum(s.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Be(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,A(n)]))).passthrough(),t=zod.z.array(e);return s.minRows&&(t=t.min(s.minRows)),s.maxRows&&(t=t.max(s.maxRows)),s.required||(t=t.optional().nullable()),s.validate&&(t=T(t,s.validate)),t}function Me(s){let e=zod.z.array(zod.z.string());return s.required||(e=e.optional().nullable()),e}function ze(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,A(t)])));return s.required?e:e.optional().nullable()}function We(s){let e=s.blocks||[];e.map(i=>zod.z.object({blockType:zod.z.literal(i.slug),...Object.fromEntries(i.fields.filter(o=>o.name).map(o=>[o.name,A(o)]))}));let n=e.map(i=>i.slug),a;if(n.length>0){let i=zod.z.object({blockType:zod.z.enum(n)}).catchall(zod.z.any()),o=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());a=zod.z.array(zod.z.union([i,o,zod.z.record(zod.z.any())]));}else a=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return s.minRows&&(a=a.min(s.minRows)),s.maxRows&&(a=a.max(s.maxRows)),s.required||(a=a.optional().nullable()),s.validate&&(a=T(a,s.validate)),a}function Xe(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function Je(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function He(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=A(n));return zod.z.object(e).passthrough().optional()}function T(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function R(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let i=R(a.fields);Object.assign(n,i);}e[t.name]=zod.z.object(n).passthrough().optional();}else if(t.type==="row"&&"fields"in t){let n=R(t.fields);Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(R(t.fields)).passthrough().optional():e[t.name]=A(t);return e}function E(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let i=E(a.fields);Object.assign(n,i);}e[t.name]=zod.z.object(n).passthrough().optional().nullable();}else if(t.type==="row"&&"fields"in t){let n=E(t.fields);Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).passthrough().optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).passthrough().optional().nullable():e[t.name]=A(t).optional().nullable();return e}function ge(s){let e=R(s.fields);return s.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),s.tenantScoped&&(e.tenantID=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function me(s){let e=R(s.fields);return zod.z.object(e).passthrough()}function be(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let i of a.fields)i.name&&(n[i.name]=A(i).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let a of t.fields)a.name&&(n[a.name]=A(a).optional().nullable());Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return zod.z.object(e).passthrough()}function Te(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Ce(s){let e=R(s.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ae(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let i of a.fields)i.name&&(n[i.name]=A(i).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return zod.z.object(e).passthrough()}var w=class{storageProviders=chunk43U2NBVS_cjs.f();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e};for(let a of this.plugins)a.extendCollection&&(t=a.extendCollection(t.slug,t));if(t.seo){let a=chunkKD7LUCFY_cjs.a(),i=t.fields.find(o=>o.type==="tabs"&&o.name==="mainTabs");i&&i.tabs?i.tabs.push({label:"SEO Settings",fields:a.fields}):t.fields.push(a);}t.fields=this.applyFieldDefaults(t);let n=V(t);if(n.length>0)throw new Error(`Invalid collection config: ${n.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=B(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let a of this.plugins)a.extendGlobal&&(n=a.extendGlobal(n.slug,n));this.globals.set(n.slug,n),this.clearSchemaCache(`global:${n.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let n=this.collections.get(e);if(n){let i=ge(n);return this.schemaCache.set(e,i),i}let a=this.globals.get(e);if(a){let i=Ce(a);return this.schemaCache.set(`global:${e}`,i),i}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let i=me(a);return this.schemaCache.set(t,i),i}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let o=be(a);return this.schemaCache.set(t,o),o}let i=this.globals.get(e);if(i){let o=Ae(i);return this.schemaCache.set(`global:${e}:update`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let i=Te(a);return this.schemaCache.set(t,i),i}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return A(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(n=>n.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(n=>n.name==="tenantID")&&t.push({name:"tenantID",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(n=>n.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(n=>n.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(n=>n.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let n=this.globals.get(e);if(n)return n.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),n=new Map,a=i=>{for(let o of i){if(o.name&&n.set(o.name,o),"fields"in o&&o.fields&&a(o.fields),"tabs"in o)for(let r of o.tabs)a(r.fields);if("blocks"in o)for(let r of o.blocks)a(r.fields);}};return a(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();fe(e,t);}async init(e){this.validate();for(let t of this.plugins)t.init&&await t.init(e||this);this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let n=this.collections.get(e)?.admin?.useAsTitle;return n||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(a=>a.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},v=null;function Ye(){return v||(v=new w),v}function Qe(){v=null;}function M(){return v=new w,v}var et={aws:{type:"aws",configKey:"s3",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1",admin:{placeholder:"us-east-1"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"endpoint",type:"text",label:"Endpoint URL",admin:{placeholder:"https://s3.custom.com"}},{name:"cdnUrl",type:"text",label:"CDN URL",admin:{placeholder:"https://cdn.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}]},r2:{type:"r2",configKey:"r2",displayName:"Cloudflare R2",configFields:[{name:"accountId",type:"text",label:"Account ID",required:true,admin:{placeholder:"Your Cloudflare Account ID"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"publicDevUrl",type:"text",label:"Public Dev URL ID",admin:{placeholder:"pub-xxxxxxxxxxxxxxxx",description:"Enter ONLY the ID (e.g., pub-b8d8c4cc8bcf4d868ddd95efc1b305aa). Do NOT include https:// or the full URL. Found in R2 Dashboard \u2192 Public Dev URL."}},{name:"cdnUrl",type:"text",label:"Custom CDN URL",admin:{placeholder:"https://assets.example.com (optional)"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads (optional)",description:"Optional prefix for all object keys. Do not use '/' as prefix."}}]},gcs:{type:"gcs",configKey:"gcs",displayName:"Google Cloud Storage",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"projectId",type:"text",label:"Project ID"},{name:"clientEmail",type:"text",label:"Client Email"},{name:"privateKey",type:"password",label:"Private Key"},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},digitalocean:{type:"digitalocean",configKey:"digitalocean",displayName:"DigitalOcean Spaces",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"nyc3"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},backblaze:{type:"backblaze",configKey:"backblaze",displayName:"Backblaze B2",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"accountId",type:"text",label:"Account ID"},{name:"applicationKeyId",type:"text",label:"Application Key ID",required:true},{name:"applicationKey",type:"password",label:"Application Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},wasabi:{type:"wasabi",configKey:"wasabi",displayName:"Wasabi",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]}};function tt(s,e){switch(s){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Se(s,e){return {provider:s,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:tt(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function st(s,e,t){let n=t[e.configKey]||{};return Se(s,n)}function nt(s,e,t){let n=t?.[e.configKey]||t;return Se(s,n)}var Ee={name:"@kyro-cms/storage-s3",version:"1.0.0",description:"S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)",init:s=>{let e=s.registry?.storageProviders;if(!e)return;let t="@kyro-cms/storage-s3";for(let n of Object.values(et))e.register({type:n.type,displayName:n.displayName,pluginName:t,configKey:n.configKey,configFields:n.configFields,extractConfig:a=>st(n.type,n,a),extractRawConfig:a=>nt(n.type,n,a),factory:a=>chunk43U2NBVS_cjs.a(a)});}};var xe={name:"@kyro-cms/storage-cloudinary",version:"1.0.0",description:"Cloudinary image and video storage",init:s=>{let e=s.registry?.storageProviders;e&&e.register({type:"cloudinary",displayName:"Cloudinary",pluginName:"@kyro-cms/storage-cloudinary",configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:t=>({cloudName:t.cloudinary?.cloudName||"",apiKey:t.cloudinary?.apiKey||"",apiSecret:t.cloudinary?.apiSecret||"",folder:t.cloudinary?.folder,uploadPreset:t.cloudinary?.uploadPreset}),extractRawConfig:t=>{let n=t?.cloudinary||t;return {cloudName:n?.cloudName||"",apiKey:n?.apiKey||"",apiSecret:n?.apiSecret||"",folder:n?.folder,uploadPreset:n?.uploadPreset}},factory:t=>chunk43U2NBVS_cjs.b(t)});}};var Ne={name:"@kyro-cms/storage-ftp",version:"1.0.0",description:"FTP/SFTP storage provider",init:s=>{let e=s.registry?.storageProviders;e&&e.register({type:"ftp",displayName:"FTP",pluginName:"@kyro-cms/storage-ftp",configKey:"ftp",configFields:[{name:"host",type:"text",label:"Host",required:true,admin:{placeholder:"ftp.example.com"}},{name:"port",type:"number",label:"Port",defaultValue:21,admin:{placeholder:"21 for FTP"}},{name:"user",type:"text",label:"Username",required:true},{name:"password",type:"password",label:"Password",required:true},{name:"secure",type:"checkbox",label:"Use TLS/SSL",defaultValue:false,admin:{description:"Enable TLS/SSL for secure connections (FTP only)"}},{name:"baseUrl",type:"text",label:"Base URL",required:true,admin:{placeholder:"https://files.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}],extractConfig:t=>({host:t.ftp?.host||"",port:t.ftp?.port||21,user:t.ftp?.user||"",password:t.ftp?.password||"",secure:t.ftp?.secure||false,baseUrl:t.ftp?.baseUrl||"",prefix:t.ftp?.prefix,type:"ftp"}),extractRawConfig:t=>{let n=t?.ftp||t;return {host:n?.host||"",port:n?.port||21,user:n?.user||"",password:n?.password||"",secure:n?.secure||false,baseUrl:n?.baseUrl||"",prefix:n?.prefix,type:"ftp"}},factory:t=>chunk43U2NBVS_cjs.c(t)});}};var it=[Ee,xe,Ne];function z(s,e,t){let n=e.split(".");if(n.length===0)return false;let a=n[0],i=n.slice(1).join(".");for(let o of s)if(o.name===a)return i?o.fields&&Array.isArray(o.fields)||o.type==="array"&&o.fields&&Array.isArray(o.fields)?z(o.fields,i,t):false:(Object.assign(o,t),true);return false}function ot(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:a,...i}=n;if(t.admin={...t.admin,...i},a&&t.fields&&Array.isArray(t.fields))for(let[o,r]of Object.entries(a))z(t.fields,o,r);}}}var W=class{registry;db;pubsub;webhookService;settings;wsServer;config;constructor(e){this.config=e,this.registry=M(),this.db=e.adapter,this.pubsub=new chunkF7SR5IDT_cjs.b(this.registry),this.webhookService=chunk4FV3HQBI_cjs.o(this.db);for(let t of it)this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&ot(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.registry.init(this),this.registry.addGlobalPostInit(chunk65G73T7Z_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkNY47CFVP_cjs.d,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},n={slug:chunk4FV3HQBI_cjs.f,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},a={slug:chunk4FV3HQBI_cjs.g,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},i=this.registry.getGlobals();if(this.db instanceof chunkQAJS4EXW_cjs.c&&this.db.dialect==="postgres"){let o=this.db,r=chunkNY47CFVP_cjs.d.replace(/-/g,"_");o.schema[r]||(o.schema[r]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,n,a],i),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),n={};try{let a=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});a&&a.states&&(n=a.states);}catch{}for(let a of t)n[a]!==void 0&&e.setPluginEnabled(a,n[a]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,a=t?.checkSession!==false;return chunk43U2NBVS_cjs.s({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:a,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkO7FYIPJW_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:a})=>{let i=chunkNY47CFVP_cjs.f(a),o,r;if(i&&this.db){let d=await chunkNY47CFVP_cjs.e(i,this.db);d.user&&(o=d.user,r=chunkNY47CFVP_cjs.g(d));}let c=e?.tenantID;return {db:this.db,registry:this.registry,user:o,req:a,tenantID:c,apiKey:r,relationLoader:new chunkO7FYIPJW_cjs.a({db:this.db,tenantID:c,user:o})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let i=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[o,...r]=i.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!o||!c)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let d=await chunkBDBN4RN6_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantID:e?.tenantID,settings:this.settings}),p=chunkBDBN4RN6_cjs.i(d)[o];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${o}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let m=p[c];if(typeof m!="function")return new Response(JSON.stringify({error:{message:`Procedure '${c}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let C=new URL(t.url).searchParams.get("input");if(C)try{y=JSON.parse(decodeURIComponent(C));}catch{}}let h=y?.["0"]??y,f=await m({...h,collection:o});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let h=y.message||"Internal error",f=h.includes("not found")?404:h.includes("denied")||h.includes("authentication required")?403:h.includes("conflict")?409:500,C=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:h,code:C,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let n=async a=>{let i=await chunkNY47CFVP_cjs.e(a,this.db);if(!i.valid)throw new Error(i.error||"Invalid API key");if(!i.user)throw new Error("API key has no associated user");return i.user};return this.wsServer=chunkF7SR5IDT_cjs.d({pubsub:this.pubsub,port:e?.port||8080,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||n}),this.wsServer}async shutdown(){this.wsServer&&await this.wsServer.close(),await this.db.disconnect();}};function Jt(s){return new W(s)}var lt=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-QEKTGNUJ.cjs', document.baseURI).href))),ct="node:sqlite",{DatabaseSync:dt}=lt(ct);function x(s){let e=[];for(let t of s)if(t.type==="tabs"&&"tabs"in t)for(let n of t.tabs)e.push(...x(n.fields));else t.type==="row"&&"fields"in t?e.push(...x(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...x(t.fields)):e.push(t);return e}function pt(s,e){let t=e,n=s[t.name];if(t.type==="json"||t.type==="richtext"||t.type==="array"||t.type==="group"||t.type==="blocks"||t.type==="list"||t.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(t.type==="checkbox"&&(n=!!n),t.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((t.type==="upload"||t.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(i=>typeof i=="object"&&i!==null?i:{id:i}):n=typeof a=="object"?a:{id:a};}catch{n={id:n};}if(t.type==="relationship"&&n)try{let a=JSON.parse(n);Array.isArray(a),n=a;}catch{n={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:n};}if(t.type==="list"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}if(t.type==="relationship-block"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}return n}function X(s,e){try{return s.prepare(`PRAGMA table_info(${e})`).all().map(n=>n.name)}catch{return []}}var J=class extends chunkW4ZDETHA_cjs.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 dt(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=n=>{let a=e(n),i=o=>typeof o=="boolean"?o?1:0:o===void 0?null:o;return new Proxy(a,{get(o,r,c){if(r==="all")return (...u)=>o.all(...u.map(i));if(r==="get")return (...u)=>o.get(...u.map(i));if(r==="run")return (...u)=>o.run(...u.map(i));let d=Reflect.get(o,r,c);return typeof d=="function"?d.bind(o):d}})};t.__wrapped=true,this.db.prepare=t;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){this.db&&this.db.close(),this.connected=false;}ensureTable(e,t){let n=t||this.getTableNameFor(e.slug),a=["id TEXT PRIMARY KEY"];for(let r of x(e.fields)){if(!r.name||r.name==="id")continue;let c=this.fieldToSQL(r);c&&a.push(c);}let i=x(e.fields);i.some(r=>r.name==="createdAt")||a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),i.some(r=>r.name==="updatedAt")||a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),i.some(r=>r.name==="status")||a.push("status TEXT DEFAULT 'draft'"),i.some(r=>r.name==="hasDraft")||a.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let o=X(this.db,n);if(o.length===0){let r=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(r),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let c of x(e.fields))c.name&&c.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${c.name} ON ${n}(${this.col(c.name)})`),c.name&&c.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${c.name}_unique ON ${n}(${this.col(c.name)})`);}else {let r=new Set(o);for(let c of a){let d=c.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!r.has(d)&&d!=="id")try{d==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} TEXT DEFAULT 'published'`):d==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
4
+ CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
5
+ id TEXT PRIMARY KEY,
6
+ collection_slug TEXT NOT NULL,
7
+ document_id TEXT NOT NULL,
8
+ tenant_id TEXT,
9
+ version INTEGER NOT NULL,
10
+ status TEXT NOT NULL DEFAULT 'draft',
11
+ autosave INTEGER NOT NULL DEFAULT 0,
12
+ data TEXT NOT NULL,
13
+ created_by TEXT,
14
+ change_description TEXT,
15
+ published_at TEXT,
16
+ created_at TEXT DEFAULT (datetime('now')),
17
+ updated_at TEXT DEFAULT (datetime('now'))
18
+ )
19
+ `);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)`);}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":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 t=e.replace("_globals_","");return {isGlobal:true,globalSlug:t,tableName:`global_${t.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:t,where:n={},sort:a,limit:i=10,page:o=1,tenantID:r,draft:c=false}=e,d=this.parseGlobalsSlug(t),u=d.isGlobal?this.globals.get(d.globalSlug):this.getCollection(t);this.ensureTable(u,d.tableName);let m=`SELECT * FROM ${d.tableName}`,y=[],h=[],f={...n};this.tenantContext&&u.tenantScoped&&(f=chunkW4ZDETHA_cjs.c({where:f},t,this.tenantContext,chunkW4ZDETHA_cjs.b).where||{});let C=u.fields.find(b=>b.name==="status"),g=C?.type==="select"&&Array.isArray(C.options)&&C.options.some(b=>b.value==="published");!c&&g&&(h.push("status = ?"),y.push("published")),r&&u.tenantScoped&&(h.push("tenant_id = ?"),y.push(r));for(let[b,S]of Object.entries(f))b==="AND"||b==="OR"||(typeof S=="object"&&S!==null?(S.equals!==void 0&&(h.push(`${this.col(b)} = ?`),y.push(S.equals)),S.in!==void 0&&(h.push(`${this.col(b)} IN (${S.in.map(()=>"?").join(", ")})`),y.push(...S.in)),S.not_equals!==void 0&&(h.push(`${this.col(b)} != ?`),y.push(S.not_equals))):(h.push(`${this.col(b)} = ?`),y.push(S)));h.length>0&&(m+=` WHERE ${h.join(" AND ")}`);let Re=this.col(a?.replace("-","")||"createdAt"),ve=a?.startsWith("-")?"DESC":"ASC";m+=` ORDER BY ${Re} ${ve}`;let De=m.replace("SELECT *","SELECT COUNT(*) as count"),F=this.db.prepare(De).get(...y)?.count||0;m+=" LIMIT ? OFFSET ?",y.push(i,(o-1)*i);let D=this.db.prepare(m).all(...y).map(b=>this.rowToDoc(b,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(D=D.filter(b=>chunkW4ZDETHA_cjs.d(b,t,this.tenantContext,chunkW4ZDETHA_cjs.b))),c&&(D=await Promise.all(D.map(async b=>{let S=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,b.id);if(S){let we=S.data?JSON.parse(S.data):{};return {...b,...we,status:b.status}}return b}))),{docs:D,totalDocs:F,limit:i,totalPages:Math.ceil(F/i),page:o,pagingCounter:(o-1)*i+1,hasPrevPage:o>1,hasNextPage:o<Math.ceil(F/i),prevPage:o>1?o-1:null,nextPage:o<Math.ceil(F/i)?o+1:null}}async findByID(e){let{collection:t,id:n,tenantID:a,draft:i=false}=e,o=this.parseGlobalsSlug(t),r=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(r,o.tableName);let d=`SELECT * FROM ${o.tableName} WHERE id = ?`,u=[n];if(this.tenantContext&&r.tenantScoped){let f={id:n,tenant_id:this.tenantContext.tenantId};if(!chunkW4ZDETHA_cjs.d(f,t,this.tenantContext,chunkW4ZDETHA_cjs.b))return null}let p=r.fields.find(f=>f.name==="status"),m=p?.type==="select"&&Array.isArray(p.options)&&p.options.some(f=>f.value==="published");!i&&m&&(d+=" AND status = ?",u.push("published")),a&&r.tenantScoped&&(d+=" AND tenant_id = ?",u.push(a));let y=this.db.prepare(d).get(...u);if(!y)return null;let h=this.rowToDoc(y,r);if(i){let f=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,h.id);if(f){let C=f.data?JSON.parse(f.data):{};h={...h,...C,status:h.status};}}return h}async create(e){let{collection:t,data:n,tenantID:a}=e,i=this.parseGlobalsSlug(t),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(o,i.tableName);let r=i.tableName,c=i.isGlobal?i.globalSlug:n.id||this.generateId(),d=this.prepareData(n,o);d.id=c,d.created_at=new Date().toISOString(),d.updated_at=new Date().toISOString(),a&&o.tenantScoped&&(d.tenant_id=a);let u=Object.keys(d),p=X(this.db,r),m={};for(let g of u)p.includes(g)&&(m[g]=d[g]);let y=Object.keys(m),h=y.map(g=>this.col(g)),f=y.map(()=>"?").join(", "),C=Object.values(m).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${r} (${h.join(", ")}) VALUES (${f})`).run(...C),this.ensureVersionsTable(),this.findByID({collection:t,id:c,tenantID:a,draft:true})}async update(e){let{collection:t,id:n,data:a,tenantID:i}=e,o=this.parseGlobalsSlug(t),r=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(r,o.tableName);let c=o.tableName,d=this.prepareData(a,r);d.updated_at=new Date().toISOString();let u=X(this.db,c),p={};for(let g of Object.keys(d))u.includes(g)&&(p[g]=d[g]);let y=Object.keys(p).map(g=>`${this.col(g)} = ?`).join(", "),h=Object.values(p).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g),f=`UPDATE ${c} SET ${y} WHERE id = ?`,C=[...h,n];return i&&r.tenantScoped&&(f+=" AND tenant_id = ?",C.push(i)),this.db.prepare(f).run(...C),this.ensureVersionsTable(),this.findByID({collection:t,id:n,tenantID:i,draft:true})}async delete(e){let{collection:t,id:n,tenantID:a}=e,i=this.parseGlobalsSlug(t),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(o,i.tableName),this.ensureVersionsTable();let r=await this.findByID({collection:t,id:n,tenantID:a,draft:true});if(!r)throw new Error(`Document not found: ${t}/${n}`);let d=`DELETE FROM ${i.tableName} WHERE id = ?`,u=[n];return a&&o.tenantScoped&&(d+=" AND tenant_id = ?",u.push(a)),this.db.prepare(d).run(...u),r}async count(e){let{collection:t,tenantID:n}=e,a=this.parseGlobalsSlug(t),i=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(t);this.ensureTable(i,a.tableName);let r=`SELECT COUNT(*) as count FROM ${a.tableName}`,c=[];return n&&i.tenantScoped&&(r+=" WHERE tenant_id = ?",c.push(n)),this.db.prepare(r).get(...c)?.count||0}async findOne(e){let t=this.parseGlobalsSlug(e.collection);if(t.isGlobal){let a=this.globals.get(t.globalSlug);if(!a)throw new Error(`Global "${t.globalSlug}" not found in adapter`);this.ensureTable(a,t.tableName);let i=`SELECT * FROM ${t.tableName}`,o=[],r=[],c=a.fields.find(p=>p.name==="status"),d=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(p=>p.value==="published");!e.draft&&a.versions&&d&&o.push("status = 'published'"),o.length>0&&(i+=` WHERE ${o.join(" AND ")}`),i+=" LIMIT 1";let u=this.db.prepare(i).get(...r);if(u){let p=this.rowToDoc(u,a);if(e.draft){let m=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,t.globalSlug);if(m){let y=m.data?JSON.parse(m.data):{};p={...p,...y,status:p.status};}}return p}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:t,documentId:n,tenantID:a,limit:i=20,page:o=1}=e,r=["collection_slug = ?","document_id = ?","autosave = 0"],c=[t,n];a?(r.push("tenant_id = ?"),c.push(a)):r.push("tenant_id IS NULL");let d=`WHERE ${r.join(" AND ")}`,p=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${d}`).get(...c)?.count||0,m=(o-1)*i;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${d} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...c,i,m).map(f=>this.rowToVersion(f)),totalDocs:p,limit:i,totalPages:Math.ceil(p/i),page:o,pagingCounter:(o-1)*i+1,hasPrevPage:o>1,hasNextPage:o<Math.ceil(p/i),prevPage:o>1?o-1:null,nextPage:o<Math.ceil(p/i)?o+1:null}}async findVersionByID(e){this.ensureVersionsTable();let t=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return t?this.rowToVersion(t):null}async createVersion(e){this.ensureVersionsTable();let t=new Date().toISOString();if(e.autosave){let r=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,c=[e.collection,e.documentId];e.tenantID?(r+=" AND tenant_id = ?",c.push(e.tenantID)):r+=" AND tenant_id IS NULL",r+=" LIMIT 1";let d=this.db.prepare(r).get(...c);if(d){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,t,d.id);let u=await this.findVersionByID({collection:e.collection,versionId:d.id});if(u)return u}}let n=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} (
20
+ id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
21
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,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"?t:null,t,t),!e.autosave){let c=this.collections.get(e.collection)?.versions?.maxPerDoc;c&&c>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:c,tenantID:e.tenantID});}return await this.findVersionByID({collection:e.collection,versionId:n})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:t,documentId:n,keepLatest:a,tenantID:i}=e;if(a&&a>0){let o=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(t,n),r=0,c=[];for(let d of o)d.status==="published"||d.autosave===1||(r++,r>a&&c.push(d.id));for(let d of c)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(d);}else {let o=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,r=[t,n];i&&(o+=" AND tenant_id = ?",r.push(i)),this.db.prepare(o).run(...r);}}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,t){let n={},a=x(t.fields),i=(o,r)=>{let c=o;if(c.type==="json"||c.type==="richtext"||c.type==="array"||c.type==="group"||c.type==="blocks"||c.type==="list"||c.type==="relationship-block")return r!=null?JSON.stringify(r):null;if(c.type==="checkbox")return r?1:0;if(c.type==="number")return r!==null&&r!==""?Number(r):null;if(c.type==="upload"||c.type==="image"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?u.id||u._id||u:String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify(r):String(r)}else if(o.type==="relationship"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?JSON.stringify({relationTo:o.relationTo,value:u.id||u}):String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify({relationTo:o.relationTo,value:r.id||r}):String(r)}return r};for(let o of a){if(!o.name||o.name==="id"||t.fields.some(d=>d.type==="tabs"&&"tabs"in d&&d.tabs.some(u=>u.fields.some(p=>p.name===o.name))))continue;let c=e[o.name];c!==void 0&&(n[o.name]=i(o,c));}for(let o of t.fields)if(o.type==="tabs"&&"tabs"in o&&o.name){let r=e[o.name];if(r&&typeof r=="object"){for(let c of o.tabs)for(let d of c.fields)if(d.name&&d.name!=="id"){let u=r[d.name];u!==void 0&&(n[d.name]=i(d,u));}}}return n}rowToDoc(e,t){let n={id:e.id};for(let a of x(t.fields)){if(!a.name||a.name==="id")continue;let i=a,o=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{o=o?JSON.parse(o):null;}catch{o=null;}if(a.type==="checkbox"&&(o=!!o),a.type==="date"&&o)try{let r=new Date(o);isNaN(r.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${a.name}":`,o),o=null):o=r.toISOString();}catch{o=null;}if((a.type==="upload"||a.type==="image")&&o)try{let r=JSON.parse(o);Array.isArray(r)?o=r.map(c=>typeof c=="object"&&c!==null?c:{id:c}):o=typeof r=="object"?r:{id:r};}catch{o={id:o};}if(a.type==="relationship"&&o)try{let r=JSON.parse(o);Array.isArray(r),o=r;}catch{o={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:o};}n[a.name]=o;}for(let a of t.fields)if(!(!a.name||a.name==="id"||a.name==="row"||a.name==="collapsible")&&a.type==="tabs"&&"tabs"in a){let i={};for(let o of a.tabs)for(let r of o.fields)r.name&&r.name!=="id"&&(i[r.name]=pt(e,r));n[a.name]=i;}if(t.timestamps){let a=e.createdAt||e.created_at,i=e.updatedAt||e.updated_at;if(a)try{let o=new Date(a);isNaN(o.getTime())||(n.createdAt=o.toISOString());}catch{}if(i)try{let o=new Date(i);isNaN(o.getTime())||(n.updatedAt=o.toISOString());}catch{}}return t.tenantScoped&&(n.tenantID=e.tenant_id),n.status=e.status??"published",n.hasDraft=e.hasDraft?!!e.hasDraft:false,n}generateId(){let e=Date.now().toString(16).padStart(12,"0"),t=crypto.randomBytes(6).toString("hex");return e+t}getMediaById(e){try{let t=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${t} WHERE id = ?`).get(e);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.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((t,n)=>{let a=this.db.transaction(async()=>e({db:this.db}));try{let i=a();t(i);}catch(i){n(i);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function us(s){return new J(s||{})}exports.a=K;exports.b=V;exports.c=B;exports.d=N;exports.e=fe;exports.f=A;exports.g=ge;exports.h=me;exports.i=be;exports.j=Te;exports.k=Ce;exports.l=w;exports.m=Ye;exports.n=Qe;exports.o=M;exports.p=W;exports.q=Jt;exports.r=J;exports.s=us;