@kyro-cms/core 0.13.5 → 0.13.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +2 -2
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +2 -2
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/auth-session-4WJUKESW.js +1 -0
- package/dist/auth-session-VHUHDBCL.cjs +1 -0
- package/dist/bootstrap-JYAUQ52D.cjs +1 -0
- package/dist/bootstrap-TTMLNQM3.js +1 -0
- package/dist/chunk-23RSKVJP.cjs +1 -0
- package/dist/chunk-24W5I6SJ.cjs +2 -0
- package/dist/{chunk-CH4TZZI5.js → chunk-2I2AXTKY.cjs} +38 -39
- package/dist/chunk-34LCWI5X.cjs +1 -0
- package/dist/chunk-3A5UO6OQ.cjs +114 -0
- package/dist/chunk-3N34WXBS.js +2 -0
- package/dist/chunk-5BUAWCU6.js +91 -0
- package/dist/{chunk-7NKNSRCB.cjs → chunk-5I3BM5TV.js} +33 -32
- package/dist/chunk-5RBGM5N5.js +3 -0
- package/dist/chunk-7EY3GXRA.js +2 -0
- package/dist/chunk-7KTPBTH5.cjs +1 -0
- package/dist/chunk-A4XM33WO.js +109 -0
- package/dist/chunk-A7763NCF.cjs +19 -0
- package/dist/chunk-AQWTJGML.cjs +1 -0
- package/dist/chunk-CIWLQXB2.js +2 -0
- package/dist/chunk-DCFOVCJX.cjs +1 -0
- package/dist/chunk-DCKJT247.cjs +1 -0
- package/dist/chunk-EG4SRTYS.cjs +2 -0
- package/dist/chunk-FAG2645P.js +2 -0
- package/dist/chunk-FIVTKI25.cjs +3 -0
- package/dist/chunk-FU76HURF.cjs +1 -0
- package/dist/chunk-GDLMPZKD.cjs +2 -0
- package/dist/chunk-GS4CMYKS.cjs +1 -0
- package/dist/chunk-GTAKGVUY.js +2 -0
- package/dist/chunk-GWUHIIPO.cjs +132 -0
- package/dist/chunk-H2IJDTA2.cjs +1 -0
- package/dist/chunk-HACW42ZZ.cjs +108 -0
- package/dist/chunk-HCM2G674.cjs +20 -0
- package/dist/chunk-I22MSXGL.js +2 -0
- package/dist/chunk-IIPSXKNV.js +115 -0
- package/dist/{chunk-WNU76M2C.js → chunk-IIVBEZC2.js} +6 -6
- package/dist/chunk-JHFD3IAU.cjs +1 -0
- package/dist/chunk-JJY2F6NL.cjs +3 -0
- package/dist/chunk-JQ4V2MGJ.cjs +2 -0
- package/dist/chunk-JXJTFBHG.js +3 -0
- package/dist/chunk-KOSR7235.cjs +1 -0
- package/dist/chunk-KUY4QDAL.js +2 -0
- package/dist/chunk-LGUHXOEW.js +3 -0
- package/dist/chunk-LXTVMP5F.cjs +6 -0
- package/dist/chunk-N25DOGLQ.js +5 -0
- package/dist/chunk-N2BMGZIX.cjs +90 -0
- package/dist/chunk-N7CDHWQH.cjs +2 -0
- package/dist/chunk-NBBAMC2X.cjs +1 -0
- package/dist/chunk-NGNXOXI5.js +2 -0
- package/dist/chunk-O4PPZOVI.cjs +1 -0
- package/dist/chunk-O4RKZQYQ.js +2 -0
- package/dist/chunk-OJBL4CXK.cjs +2 -0
- package/dist/chunk-OPKZYQV7.js +3 -0
- package/dist/chunk-OXEJCIOA.cjs +1 -0
- package/dist/chunk-OXH6CANN.js +2 -0
- package/dist/{chunk-EQN3HDES.cjs → chunk-PW6Y5MQL.cjs} +5 -5
- package/dist/chunk-RLW6AQF2.js +2 -0
- package/dist/chunk-SBFVITY2.js +7 -0
- package/dist/chunk-SEJ7LMYY.js +4 -0
- package/dist/chunk-SZY25KAE.js +21 -0
- package/dist/chunk-TG5YQ4PB.cjs +4 -0
- package/dist/chunk-TJ6N5ZPZ.js +133 -0
- package/dist/chunk-V2RMDMWN.js +2 -0
- package/dist/chunk-V4SR7DU5.js +3 -0
- package/dist/chunk-VLFM66BZ.js +4 -0
- package/dist/chunk-VPBGZW4P.cjs +1 -0
- package/dist/chunk-VQWOCGJ2.cjs +1 -0
- package/dist/chunk-VWXHW74B.js +3 -0
- package/dist/chunk-W5GDZG64.js +2 -0
- package/dist/chunk-WLSVS3NC.js +2 -0
- package/dist/chunk-YLP3EKTQ.js +2 -0
- package/dist/chunk-YNSKDTFG.js +2 -0
- package/dist/chunk-YOJOVQIH.cjs +1 -0
- package/dist/chunk-ZE2X3FBU.js +20 -0
- package/dist/chunk-ZMH35QYG.js +2 -0
- package/dist/cli/index.cjs +53 -182
- package/dist/cli/index.js +54 -183
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/fields/index.cjs +1 -1
- package/dist/fields/index.js +1 -1
- package/dist/graphql/index.cjs +1 -1
- package/dist/graphql/index.js +1 -1
- package/dist/index.cjs +30 -30
- package/dist/index.js +31 -31
- package/dist/integration.cjs +1 -1
- package/dist/integration.js +1 -1
- package/dist/local-DKP43BWQ.cjs +1 -0
- package/dist/local-TF5ZMHWW.js +1 -0
- package/dist/media-M3EIZ4QS.cjs +1 -0
- package/dist/media-WYEILC6K.js +1 -0
- package/dist/mongo-auth-adapter-33M5ENM7.cjs +1 -0
- package/dist/mongo-auth-adapter-4ITULS2P.js +1 -0
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.js +1 -1
- package/dist/nodemailer-transport-7F3VLLBW.js +1 -0
- package/dist/nodemailer-transport-WAPZD3SJ.cjs +1 -0
- package/dist/postgres-auth-adapter-7BCPXNBO.js +1 -0
- package/dist/postgres-auth-adapter-HMXFUM5W.cjs +1 -0
- package/dist/redis-adapter-2E5AWMMA.cjs +1 -0
- package/dist/redis-adapter-GFH74CF4.js +1 -0
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/dist/schema-FNIDQKIJ.cjs +1 -0
- package/dist/schema-KD736QFN.js +1 -0
- package/dist/sqlite-adapter-HL53RLSN.cjs +1 -0
- package/dist/sqlite-adapter-TT6ZASDG.js +1 -0
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.js +1 -1
- package/dist/trpc/index.cjs +1 -1
- package/dist/trpc/index.js +1 -1
- package/dist/ws/index.cjs +1 -1
- package/dist/ws/index.js +1 -1
- package/package.json +2 -10
- package/dist/WebhookService-CGxHtw7E.d.cts +0 -143
- package/dist/WebhookService-CNC1lYz7.d.ts +0 -143
- package/dist/auth-session-DHVGXHOH.cjs +0 -1
- package/dist/auth-session-O7IIH7EP.js +0 -1
- package/dist/base-A9AJPCG5.d.ts +0 -219
- package/dist/base-C6wyX2nC.d.cts +0 -219
- package/dist/bcryptjs-WIQSWJGK.cjs +0 -1
- package/dist/bcryptjs-ZEEHSMAG.js +0 -2
- package/dist/better-sqlite3-5IISPX34.cjs +0 -1
- package/dist/better-sqlite3-B34RIU4C.js +0 -2
- package/dist/bootstrap-PG2LGDLB.js +0 -1
- package/dist/bootstrap-YD3GLTWX.cjs +0 -1
- package/dist/bowser-SB3ZUPO4.js +0 -11
- package/dist/bowser-VX6B6ZSE.cjs +0 -10
- package/dist/chokidar-5RVQZVHP.cjs +0 -5
- package/dist/chokidar-BOYGRT4Q.js +0 -6
- package/dist/chunk-262YP5XA.cjs +0 -1
- package/dist/chunk-2HA6EKXX.js +0 -24
- package/dist/chunk-2SPWRQ5O.js +0 -122
- package/dist/chunk-2TYITUOC.js +0 -122
- package/dist/chunk-35PGCW3S.cjs +0 -1
- package/dist/chunk-3CIMGC2F.cjs +0 -56
- package/dist/chunk-3KZXF4US.js +0 -2
- package/dist/chunk-3NSZZCOJ.js +0 -2
- package/dist/chunk-3TAUNYEM.js +0 -8
- package/dist/chunk-3VXEK5ZW.cjs +0 -1
- package/dist/chunk-47CXBWMA.js +0 -2
- package/dist/chunk-4BMWWGJN.js +0 -384
- package/dist/chunk-4NTIK6DF.cjs +0 -2
- package/dist/chunk-6E44MQQ5.js +0 -115
- package/dist/chunk-6LWF5MPL.js +0 -20
- package/dist/chunk-6NBZDW53.js +0 -133
- package/dist/chunk-6TPICJ2L.js +0 -7
- package/dist/chunk-6YS6XLOD.cjs +0 -121
- package/dist/chunk-73D2PNHD.cjs +0 -7
- package/dist/chunk-7ACHOBWY.cjs +0 -13
- package/dist/chunk-7GGZA5YU.cjs +0 -2
- package/dist/chunk-7JWQ2PZP.cjs +0 -1
- package/dist/chunk-7KLEANTO.cjs +0 -1
- package/dist/chunk-7MNDQU6K.js +0 -8
- package/dist/chunk-7NH7H3WA.js +0 -10
- package/dist/chunk-7WMMKGEO.cjs +0 -1
- package/dist/chunk-ALTU3FDG.js +0 -2
- package/dist/chunk-BAVN7VDR.cjs +0 -1
- package/dist/chunk-BCEE4NBZ.cjs +0 -2
- package/dist/chunk-BUNLC3II.cjs +0 -1
- package/dist/chunk-C7QCZX7X.js +0 -2
- package/dist/chunk-D6SDGHY6.js +0 -2
- package/dist/chunk-DVWYO3KK.cjs +0 -1
- package/dist/chunk-EHWUALGH.cjs +0 -1
- package/dist/chunk-EML5FDUU.js +0 -2
- package/dist/chunk-EN65ZEK2.cjs +0 -2
- package/dist/chunk-EW424IBO.cjs +0 -1
- package/dist/chunk-EZIDQBXI.cjs +0 -1
- package/dist/chunk-F2O4QO5N.cjs +0 -383
- package/dist/chunk-F4ITQ6XQ.cjs +0 -3
- package/dist/chunk-FK2BG4HU.js +0 -3
- package/dist/chunk-FLMUMPDE.js +0 -2
- package/dist/chunk-GIS6X43A.cjs +0 -3
- package/dist/chunk-GNEVCEJU.cjs +0 -3
- package/dist/chunk-GNOSG3PK.cjs +0 -1
- package/dist/chunk-GQGFNTDZ.js +0 -2
- package/dist/chunk-GTR7JAKP.cjs +0 -3
- package/dist/chunk-HPIJI7TM.js +0 -3
- package/dist/chunk-HPYH7GTS.cjs +0 -1
- package/dist/chunk-HRAY65XH.js +0 -3
- package/dist/chunk-HTYVI2HK.cjs +0 -9
- package/dist/chunk-IKGVPXMK.js +0 -3
- package/dist/chunk-J6V573PE.cjs +0 -1
- package/dist/chunk-JA44K75G.js +0 -2
- package/dist/chunk-JRUQ5ABB.js +0 -4
- package/dist/chunk-JV4HJBXW.js +0 -14
- package/dist/chunk-KEITOXIP.js +0 -2
- package/dist/chunk-KMFLHGD5.cjs +0 -1
- package/dist/chunk-KZHXYXSH.cjs +0 -10
- package/dist/chunk-L3Q64RUX.js +0 -3
- package/dist/chunk-LEBM6ZSZ.cjs +0 -10
- package/dist/chunk-LKRI5X2V.cjs +0 -1
- package/dist/chunk-LQ3YZTPU.cjs +0 -15
- package/dist/chunk-LVBHOZZF.js +0 -4
- package/dist/chunk-LWM4WABU.js +0 -3
- package/dist/chunk-LY7N3UHH.cjs +0 -23
- package/dist/chunk-MCIZG4A3.cjs +0 -1
- package/dist/chunk-MDLJTZLV.cjs +0 -1
- package/dist/chunk-N4FXLQE3.cjs +0 -132
- package/dist/chunk-N5POANYV.js +0 -2
- package/dist/chunk-NGNJSUGL.cjs +0 -1
- package/dist/chunk-NRE6VKL6.cjs +0 -121
- package/dist/chunk-O4YE57OS.cjs +0 -6
- package/dist/chunk-OBYAIJVU.js +0 -11
- package/dist/chunk-OLRCZ6E3.js +0 -2
- package/dist/chunk-OOVNTOZC.cjs +0 -56
- package/dist/chunk-P6JITOFF.js +0 -4
- package/dist/chunk-PITMDQYN.cjs +0 -18
- package/dist/chunk-PYUWSKKP.js +0 -57
- package/dist/chunk-Q5TFO66G.cjs +0 -1
- package/dist/chunk-QO5ZWQA3.cjs +0 -74
- package/dist/chunk-QYN6C3FZ.cjs +0 -114
- package/dist/chunk-REQ622YC.js +0 -3
- package/dist/chunk-RPRGGGIW.js +0 -11
- package/dist/chunk-RVBSJ4UQ.cjs +0 -7
- package/dist/chunk-RYHOWZLK.js +0 -2
- package/dist/chunk-RYXLEFS5.js +0 -2
- package/dist/chunk-SBNMXQNO.cjs +0 -2
- package/dist/chunk-SLMIYECU.js +0 -2
- package/dist/chunk-SRIXRJHL.js +0 -4
- package/dist/chunk-TBHNE4VV.js +0 -2
- package/dist/chunk-TCFL3UWT.cjs +0 -2
- package/dist/chunk-TYQYKKWJ.js +0 -16
- package/dist/chunk-U6KFONKM.js +0 -2
- package/dist/chunk-UNYXWPLZ.cjs +0 -2
- package/dist/chunk-UWHWSWDE.js +0 -2
- package/dist/chunk-V4FAL7AG.js +0 -2
- package/dist/chunk-VQ53TFYA.cjs +0 -1
- package/dist/chunk-VRZC4TTF.cjs +0 -1
- package/dist/chunk-W45TLOOT.js +0 -2
- package/dist/chunk-WAVGRSE6.js +0 -2
- package/dist/chunk-WPM6LFCY.js +0 -2
- package/dist/chunk-WXT2XW7T.js +0 -13
- package/dist/chunk-X473JI7Z.js +0 -75
- package/dist/chunk-X6HUA6EF.cjs +0 -20
- package/dist/chunk-XDPLVJRO.js +0 -21
- package/dist/chunk-XDQVYCIR.cjs +0 -1
- package/dist/chunk-XFYSADHV.cjs +0 -2
- package/dist/chunk-XOR64WUQ.cjs +0 -19
- package/dist/chunk-Y2YAKDEQ.js +0 -2
- package/dist/chunk-YENNL5HG.js +0 -2
- package/dist/chunk-YGI5W4RS.js +0 -2
- package/dist/chunk-YIFKTA5N.js +0 -57
- package/dist/chunk-YUUXFD73.js +0 -19
- package/dist/chunk-ZAKYTBEN.js +0 -3
- package/dist/chunk-ZHA446FA.cjs +0 -1
- package/dist/chunk-ZTLGK6R4.cjs +0 -12
- package/dist/chunk-ZUBJ6RLQ.cjs +0 -1
- package/dist/client.d.cts +0 -1291
- package/dist/client.d.ts +0 -1291
- package/dist/d1-5ZQJOFDX.cjs +0 -1
- package/dist/d1-HPB6B253.js +0 -2
- package/dist/dist-es-3SSNUZST.cjs +0 -1
- package/dist/dist-es-64F22JL2.js +0 -2
- package/dist/dist-es-A5OF2STN.cjs +0 -2
- package/dist/dist-es-BOW5V247.cjs +0 -6
- package/dist/dist-es-CRIMATLL.cjs +0 -2
- package/dist/dist-es-DL3VLVP6.cjs +0 -1
- package/dist/dist-es-F2ZR55UK.js +0 -4
- package/dist/dist-es-IPSSZNFP.js +0 -1
- package/dist/dist-es-M2F7M27Y.js +0 -2
- package/dist/dist-es-M66JKZF5.js +0 -7
- package/dist/dist-es-OKLLRYI3.js +0 -2
- package/dist/dist-es-P25IKLBI.cjs +0 -1
- package/dist/dist-es-SRPWSAF4.cjs +0 -1
- package/dist/dist-es-SVHZDVUF.js +0 -3
- package/dist/dist-es-T2H2W5BX.cjs +0 -3
- package/dist/dist-es-WFI55HKT.js +0 -3
- package/dist/drizzle-orm-47ELDEM6.cjs +0 -1
- package/dist/drizzle-orm-XRTSOQJS.js +0 -1
- package/dist/event-streams-7NAWZW2I.js +0 -1
- package/dist/event-streams-JBMWCI2O.cjs +0 -1
- package/dist/fs-KWBRQ6T6.js +0 -1
- package/dist/fs-ZQYOJOIO.cjs +0 -1
- package/dist/index-NGnJpSgf.d.ts +0 -105
- package/dist/index-Zrg3sZ6R.d.cts +0 -105
- package/dist/jsonwebtoken-DFB6ZBZA.cjs +0 -8
- package/dist/jsonwebtoken-OD67R5JS.js +0 -9
- package/dist/lib-A2D63VXD.cjs +0 -1
- package/dist/lib-JQD2JAOO.js +0 -2
- package/dist/loadSso-JY4WDQPS.cjs +0 -2
- package/dist/loadSso-UQR6545M.js +0 -3
- package/dist/local-6UUGBZ4M.js +0 -1
- package/dist/local-ZYHV3J2K.cjs +0 -1
- package/dist/media-3Z6YW5J4.cjs +0 -1
- package/dist/media-E762GEHL.js +0 -1
- package/dist/mongo-auth-adapter-2H2AXDRH.cjs +0 -1
- package/dist/mongo-auth-adapter-YWMEOC42.js +0 -1
- package/dist/nodemailer-IDML4L6W.cjs +0 -53
- package/dist/nodemailer-NITB45SS.js +0 -54
- package/dist/nodemailer-transport-3VWVUBM5.cjs +0 -1
- package/dist/nodemailer-transport-7RHATUKL.js +0 -1
- package/dist/postgres-auth-adapter-QKBNXVPT.js +0 -1
- package/dist/postgres-auth-adapter-WMLM4UUC.cjs +0 -1
- package/dist/postgres-js-7YBZKGXG.cjs +0 -1
- package/dist/postgres-js-JLFIWOBH.js +0 -1
- package/dist/redis-adapter-EVK2SMKH.cjs +0 -1
- package/dist/redis-adapter-LY2NBSAG.js +0 -1
- package/dist/schema-RT6WSUYC.cjs +0 -1
- package/dist/schema-YFMSJK2P.js +0 -2
- package/dist/signin-N3T2KF5Q.js +0 -3
- package/dist/signin-VFBLX7EL.cjs +0 -2
- package/dist/sqlite-adapter-KPSISY6E.cjs +0 -1
- package/dist/sqlite-adapter-PI6SIY7O.js +0 -1
- package/dist/src-6LAUXXDM.cjs +0 -1
- package/dist/src-QBADSZV4.js +0 -1
- package/dist/sso-oidc-54BIRYR6.cjs +0 -2
- package/dist/sso-oidc-UB7G4END.js +0 -3
- package/dist/sts-WAA6I22C.js +0 -3
- package/dist/sts-YLXXIB3X.cjs +0 -2
- package/dist/types-BCOhfwHC.d.ts +0 -839
- package/dist/types-DxaK39ix.d.cts +0 -330
- package/dist/types-DxaK39ix.d.ts +0 -330
- package/dist/types-QglJ7PwT.d.cts +0 -839
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var chunkN7CDHWQH_cjs=require('./chunk-N7CDHWQH.cjs'),chunkDCKJT247_cjs=require('./chunk-DCKJT247.cjs'),chunk7KTPBTH5_cjs=require('./chunk-7KTPBTH5.cjs'),chunk24W5I6SJ_cjs=require('./chunk-24W5I6SJ.cjs'),chunkHACW42ZZ_cjs=require('./chunk-HACW42ZZ.cjs'),chunkOJBL4CXK_cjs=require('./chunk-OJBL4CXK.cjs'),chunkDCFOVCJX_cjs=require('./chunk-DCFOVCJX.cjs'),chunkFU76HURF_cjs=require('./chunk-FU76HURF.cjs'),chunkGWUHIIPO_cjs=require('./chunk-GWUHIIPO.cjs'),chunk23RSKVJP_cjs=require('./chunk-23RSKVJP.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga');function P(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(P(n.fields,e))return true}if("fields"in t&&t.fields&&P(t.fields,e))return true}return false}var G=class extends Error{errors;constructor(e){super(`Configuration validation failed:
|
|
2
|
+
${e.join(`
|
|
3
|
+
`)}`),this.name="ConfigValidationError",this.errors=e;}};function N(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=k(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&&(P(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)P(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(i=>i.name==="email"),n=s.fields.some(i=>i.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 _(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=k(s.fields,`global:${s.slug}`);e.push(...t);}return e}function k(s,e){let t=[],n=new Set;for(let i=0;i<s.length;i++){let o=s[i];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let c=k(o.fields,e);t.push(...c);}else if("tabs"in o)for(let c of o.tabs){let l=k(c.fields,e);t.push(...l);}continue}let r=o.name;if(!r){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(n.has(r)&&t.push(`${e}: Duplicate field name "${r}"`),n.add(r),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r)||t.push(`${e}: Field name "${r}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${r}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${r}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${r}" has no fields defined`);else {let c=k(o.fields,`${e}.${r}`);t.push(...c);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${r}" has no blocks defined`);else {let c=Ie(o.blocks,`${e}.${r}`);t.push(...c);}break;case "select":case "radio":if(typeof o.options=="function")break;if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${r}" has no options defined`);else if(Array.isArray(o.options)){let c=o.options.map(u=>typeof u=="object"&&u!==null&&"value"in u?u.value:u),l=new Set(c);c.length!==l.size&&t.push(`${e}: ${o.type} field "${r}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${r}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${r}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${r}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${r}" has minRows greater than maxRows`);}return t}function Ie(s,e){let t=[],n=new Set;for(let i of s){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),n.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let o=k(i.fields,`${e}.${i.slug}`);t.push(...o);}}return t}function be(s,e=[]){let t=[],n=new Set;for(let i of s)n.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),n.add(i.slug);for(let i of e)n.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),n.add(i.slug);for(let i of s){let o=N(i);t.push(...o);}for(let i of e){let o=_(i);t.push(...o);}for(let i of s){let o=F(i.fields,s);t.push(...o);}if(t.length>0)throw new G(t)}function F(s,e){let t=[],n=new Set(e.map(i=>i.slug));for(let i of s){if(i.type==="relationship"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)r!=="*"&&!n.has(r)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${r}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let r of o)n.has(r)||t.push(`Upload field "${i.name}" references unknown collection "${r}"`);}if("fields"in i&&i.fields){let o=F(i.fields,e);t.push(...o);}if("tabs"in i)for(let o of i.tabs){let r=F(o.fields,e);t.push(...r);}if("blocks"in i)for(let o of i.blocks){let r=F(o.fields,e);t.push(...r);}}return t}function y(s){switch(s.type){case "text":return qe(s);case "number":return Le(s);case "checkbox":return De(s);case "date":return Ge(s);case "email":return Ne(s);case "password":return _e(s);case "textarea":return Ue(s);case "select":return ze(s);case "radio":return He(s);case "color":return Me(s);case "richtext":return Be(s);case "json":return Ve(s);case "code":return We(s);case "upload":return ve(s);case "image":return ve(s);case "markdown":return Ye(s);case "relationship":return Ce(s);case "relationship-block":return Ce(s);case "array":return Je(s);case "list":return Qe(s);case "group":return Xe(s);case "blocks":return et(s);case "row":return tt(s);case "collapsible":return st(s);case "tabs":return it(s);default:return zod.z.any()}}function qe(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=f(e,s.validate)),e}function Le(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=f(e,s.validate)),e}function De(s){let e=zod.z.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ge(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=f(e,s.validate)),e}function Ne(s){let e=zod.z.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function _e(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=f(e,s.validate)),e}function Ue(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=f(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);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=f(e,s.validate)),e}function He(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=f(e,s.validate)),e}function Me(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=f(e,s.validate)),e}function Be(s){let e=zod.z.array(zod.z.record(zod.z.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ve(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=f(e,s.validate)),e}function We(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function ve(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=f(e,s.validate)),e}function Ye(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=f(e,s.validate)),e}function Ce(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=f(e,s.validate)),e}function Je(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,y(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=f(t,s.validate)),t}function Qe(s){let e=zod.z.array(zod.z.string());return s.required||(e=e.optional().nullable()),e}function Xe(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])));return s.required?e:e.optional().nullable()}function et(s){let e=s.blocks||[];e.map(o=>zod.z.object({blockType:zod.z.literal(o.slug),...Object.fromEntries(o.fields.filter(r=>r.name).map(r=>[r.name,y(r)]))}));let n=e.map(o=>o.slug),i;if(n.length>0){let o=zod.z.object({blockType:zod.z.enum(n)}).catchall(zod.z.any()),r=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());i=zod.z.array(zod.z.union([o,r,zod.z.record(zod.z.any())]));}else i=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&&(i=i.min(s.minRows)),s.maxRows&&(i=i.max(s.maxRows)),s.required||(i=i.optional().nullable()),s.validate&&(i=f(i,s.validate)),i}function tt(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function st(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,y(t)])))}function it(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=y(n));return zod.z.object(e).passthrough().optional()}function f(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function S(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=S(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=S(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional():Object.assign(e,n);}else {if(!t.name)continue;e[t.name]=y(t);}return e}function A(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs){let o=A(i.fields);Object.assign(n,o);}t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="row"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="collapsible"&&"fields"in t){let n=A(t.fields);t.name?e[t.name]=zod.z.object(n).passthrough().optional().nullable():Object.assign(e,n);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=zod.z.object(A(t.fields)).passthrough().optional().nullable():Object.assign(e,A(t.fields));else {if(!t.name)continue;e[t.name]=y(t).optional().nullable();}return e}function xe(s){let e=S(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 Ae(s){let e=S(s.fields);return zod.z.object(e).passthrough()}function we(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let i of t.fields)i.name&&(n[i.name]=y(i).optional().nullable());Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}function ke(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 Se(s){let e=S(s.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Te(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let i of t.tabs)for(let o of i.fields)o.name&&(n[o.name]=y(o).optional().nullable());e[t.name]=zod.z.object(n).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(A(t.fields)).optional().nullable():e[t.name]=y(t).optional().nullable();return zod.z.object(e).passthrough()}var R=class{storageProviders=chunkHACW42ZZ_cjs.e();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,fields:[...e.fields]};for(let i of this.plugins){let o=i.extensions?.collections?.find(r=>r.slug===t.slug);o&&(t={...t,...o.config,fields:[...t.fields,...o.config.fields||[]]});}if(t.seo){let i=chunkDCKJT247_cjs.a(),o=t.fields.findIndex(r=>r.type==="tabs");if(o!==-1){let r=t.fields[o];t.fields[o]={...r,tabs:[...r.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let n=N(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=_(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let i of this.plugins){let o=i.extensions?.globals?.find(r=>r.slug===n.slug);o&&(n={...n,...o.config,fields:[...n.fields||[],...o.config.fields||[]]});}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 o=xe(n);return this.schemaCache.set(e,o),o}let i=this.globals.get(e);if(i){let o=Se(i);return this.schemaCache.set(`global:${e}`,o),o}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 i=this.collections.get(e);if(i){let o=Ae(i);return this.schemaCache.set(t,o),o}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 i=this.collections.get(e);if(i){let r=we(i);return this.schemaCache.set(t,r),r}let o=this.globals.get(e);if(o){let r=Te(o);return this.schemaCache.set(`global:${e}:update`,r),r}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 i=this.collections.get(e);if(i){let o=ke(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return y(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,i=o=>{for(let r of o){if(r.name&&n.set(r.name,r),"fields"in r&&r.fields&&i(r.fields),"tabs"in r)for(let c of r.tabs)i(c.fields);if("blocks"in r)for(let c of r.blocks)i(c.fields);}};return i(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();be(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let n=t.collections||[];for(let o of n)o.slug&&!this.hasCollection(o.slug)&&this.addCollection(o);let i=t.globals||[];for(let o of i)o.slug&&!this.hasGlobal(o.slug)&&this.addGlobal(o);}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(i=>i.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()}}},T=null;function ot(){return T||(T=new R),T}function nt(){T=null;}function U(){return T=new R,T}var C=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},O=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[n,i]of Object.entries(t))if(Array.isArray(i))for(let o of i)this.registerHook(n,o);}unregister(e){let t=this.plugins.get(e);if(!t)return;let n=t.getHooks?.()||{};for(let[i,o]of Object.entries(n))if(Array.isArray(o))for(let r of o)this.unregisterHook(i,r);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let n=this.hooks.get(e);if(n){let i=n.indexOf(t);i>-1&&n.splice(i,1);}}async executeHook(e,t){let n=this.hooks.get(e)||[],i=t;for(let o of n)try{let r=await o({...t,data:i});r!==void 0&&(i=r);}catch(r){console.error(`[PluginManager] Error in hook "${e}":`,r);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let n=t.getCollections?.()||[];e.push(...n);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let n=t.getGlobals?.()||[];e.push(...n);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},z=class extends C{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},H=class extends C{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},M=class extends C{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},B=class extends C{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},V=class extends C{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},kt={SEO:z,Analytics:H,Comments:M,Reviews:B,Wishlist:V};var Re=new Set(["type","admin","label","singularLabel","labelPlural","relationTo","required","hasMany","defaultValue","validate","options","dynamicOptions","filterOptions","hooks","min","max","minLength","maxLength","minRows","maxRows","minDate","maxDate","step","integer","variant","pattern","format","fields","tabs","blocks"]);function Fe(s){return typeof s!="object"||s===null||Array.isArray(s)?false:Object.keys(s).some(e=>Re.has(e))}function Z(s,e=""){let t={};for(let[n,i]of Object.entries(s)){let o=e?`${e}.${n}`:n;i&&typeof i=="object"&&!Array.isArray(i)&&!Fe(i)?Object.assign(t,Z(i,o)):t[o]=i;}return t}function v(s,e,t,n=true){let i=e.split(".");if(i.length===0)return false;let o=i[0],r=i.slice(1).join("."),c=o.match(/^(?:tab|tabs)\[(.+?)\]$/i);if(c){let l=c[1].toLowerCase();for(let u of s)if(u.type==="tabs"&&u.tabs&&Array.isArray(u.tabs)){for(let d of u.tabs)if((d.label||d.name||"").toLowerCase()===l&&d.fields&&Array.isArray(d.fields))return v(d.fields,r,t,n)}return false}for(let l of s){if(l.name===o)if(r){if(l.fields&&Array.isArray(l.fields))return v(l.fields,r,t,true);if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true;return false}if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");if(!g)return false;for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields))return v(p.fields,g,t,true);return false}return l.type==="array"&&l.fields&&Array.isArray(l.fields)?v(l.fields,r,t,true):false}else return Object.assign(l,t),true;if(l.type==="blocks"&&l.blocks&&Array.isArray(l.blocks)){if(o==="blocks"&&r){let d=r.split(".")[0],g=r.split(".").slice(1).join(".");for(let p of l.blocks)if(p.slug===d&&p.fields&&Array.isArray(p.fields)&&v(p.fields,g,t,true))return true}for(let d of l.blocks)if(d.slug===o&&d.fields&&Array.isArray(d.fields)&&v(d.fields,r,t,true))return true}if(!l.name||l.type==="tabs"||l.type==="row"||l.type==="collapsible"){if(l.fields&&Array.isArray(l.fields)&&v(l.fields,e,t,false))return true;if(l.type==="tabs"&&l.tabs&&Array.isArray(l.tabs)){for(let d of l.tabs)if(d.fields&&Array.isArray(d.fields)&&v(d.fields,e,t,false))return true}}}return n&&!r&&t&&t.type?(s.push({name:o,...t}),true):false}function W(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({slug:o?.slug||i,...o}));function n(i){for(let o of i){if(o.type==="blocks"){Array.isArray(o.blocks)||(o.blocks=[]);for(let r of t){let c=o.blocks.findIndex(l=>l.slug===r.slug);c>=0?o.blocks[c]={...o.blocks[c],...r}:o.blocks.push(r);}return true}if(o.fields&&Array.isArray(o.fields)&&n(o.fields))return true;if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let r of o.tabs)if(r.fields&&Array.isArray(r.fields)&&n(r.fields))return true}}return false}n(s);}function Y(s,e){if(!e)return;let t=Array.isArray(e)?e:Object.entries(e).map(([i,o])=>({label:o?.label||i,...Array.isArray(o)?{fields:o}:o})),n=s.find(i=>i.type==="tabs");if(n&&Array.isArray(n.tabs))for(let i of t){let o=n.tabs.find(r=>(r.label||r.name||"").toLowerCase()===(i.label||i.name||"").toLowerCase());o?(i.fields&&Array.isArray(i.fields)&&(Array.isArray(o.fields)||(o.fields=[]),o.fields.push(...i.fields)),Object.assign(o,i)):n.tabs.push(i);}else {let i=[...s];s.length=0,s.push({type:"tabs",tabs:[{label:"General",fields:i},...t]});}}function J(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,labels:c,label:l,singularLabel:u,labelPlural:d,hidden:g,timestamps:p,versions:h,seo:m,access:b,hooks:x,admin:ie,...oe}=n;if(l&&(t.label=l),u&&(t.singularLabel=u),d&&(t.labelPlural=d),c&&(c.singular&&(t.singularLabel=c.singular),c.plural&&(t.labelPlural=c.plural)),p!==void 0&&(t.timestamps=p),h!==void 0&&(t.versions={...t.versions,...h}),m!==void 0&&(t.seo=m),b&&(t.access={...t.access,...b}),x&&(t.hooks={...t.hooks,...x}),(ie||oe)&&(t.admin={...t.admin,...ie,...oe}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let Ee=Z(i);for(let[Ke,$e]of Object.entries(Ee))v(t.fields,Ke,$e);}}}}function Q(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:i,blocks:o,tabs:r,label:c,hidden:l,versions:u,access:d,hooks:g,admin:p,...h}=n;if(c&&(t.label=c),u!==void 0&&(t.versions={...t.versions,...u}),d&&(t.access={...t.access,...d}),g&&(t.hooks={...t.hooks,...g}),(p||h)&&(t.admin={...t.admin,...p,...h}),o&&W(t.fields,o),r&&Y(t.fields,r),i){let m=Z(i);for(let[b,x]of Object.entries(m))v(t.fields,b,x);}}}}var at={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 rt(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 Pe(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:rt(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function lt(s,e,t){let n=t[e.configKey]||{};return Pe(s,n)}function ct(s,e,t){let n=t?.[e.configKey]||t;return Pe(s,n)}var X=class extends C{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let n=this.name;for(let i of Object.values(at))t.register({type:i.type,displayName:i.displayName,pluginName:n,configKey:i.configKey,configFields:i.configFields,extractConfig:o=>lt(i.type,i,o),extractRawConfig:o=>ct(i.type,i,o),factory:o=>chunkHACW42ZZ_cjs.a(o)});}},Oe=new X;var ee=class extends C{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,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:n=>({cloudName:n.cloudinary?.cloudName||"",apiKey:n.cloudinary?.apiKey||"",apiSecret:n.cloudinary?.apiSecret||"",folder:n.cloudinary?.folder,uploadPreset:n.cloudinary?.uploadPreset}),extractRawConfig:n=>{let i=n?.cloudinary||n;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:n=>chunkHACW42ZZ_cjs.b(n)});}},Ze=new ee;var ut=[Oe,Ze],te=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=U(),this.db=e.adapter||e.db,this.pubsub=new chunkFU76HURF_cjs.b(this.registry),this.webhookService=chunkOJBL4CXK_cjs.n(this.db),this.pluginManager=new O;for(let t of ut)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&J(e.collections,e.admin.collectionOverrides),e.globals&&e.admin?.globalOverrides&&Q(e.globals,e.admin.globalOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(chunkN7CDHWQH_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:chunkDCFOVCJX_cjs.a,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:chunkOJBL4CXK_cjs.e,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:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:chunkOJBL4CXK_cjs.f,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"}]},o=this.registry.getGlobals();if(this.db instanceof chunkGWUHIIPO_cjs.c&&this.db.dialect==="postgres"){let r=this.db,c=chunkDCFOVCJX_cjs.a.replace(/-/g,"_");r.schema&&!r.schema[c]&&(r.schema[c]=chunk23RSKVJP_cjs.g);}await this.db.init([...this.registry.getCollections(),t,n,i],o),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 i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(n=i.states);}catch{}for(let i of t)n[i]!==void 0&&e.setPluginEnabled(i,n[i]);}async getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,i=t?.checkSession!==false;return chunkHACW42ZZ_cjs.n({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunk24W5I6SJ_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:i})=>{let o=chunkDCFOVCJX_cjs.c(i),r,c;if(o&&this.db){let u=await chunkDCFOVCJX_cjs.b(o,this.db);u.user&&(r=u.user,c=chunkDCFOVCJX_cjs.d(u));}let l=e?.tenantId;return {db:this.db,registry:this.registry,user:r,req:i,tenantId:l,apiKey:c,relationLoader:new chunk24W5I6SJ_cjs.a({db:this.db,tenantId:l,user:r})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[r,...c]=o.split("."),l=c.join(".");if(l=l.replace(/\.(query|mutate|subscribe)$/,""),!r||!l)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 u=await chunk7KTPBTH5_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),g=chunk7KTPBTH5_cjs.i(u)[r];if(!g)return new Response(JSON.stringify({error:{message:`Collection '${r}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let p=g[l];if(typeof p!="function")return new Response(JSON.stringify({error:{message:`Procedure '${l}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let h={};if(t.method==="POST"||t.method==="PATCH")h=await t.json().catch(()=>({}));else {let x=new URL(t.url).searchParams.get("input");if(x)try{h=JSON.parse(decodeURIComponent(x));}catch{}}let m=h?.["0"]??h,b=await p({...m,collection:r});return new Response(JSON.stringify({result:{data:b}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(h){let m=h.message||"Internal error",b=m.includes("not found")?404:m.includes("denied")||m.includes("authentication required")?403:m.includes("conflict")?409:500,x=b===404?-32601:b===403?-32001:b===409?-32002:-32603;return new Response(JSON.stringify({error:{message:m,code:x,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:b}}}),{status:b,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 r=>{let c=await chunkDCFOVCJX_cjs.b(r,this.db);if(!c.valid)throw new Error(c.error||"Invalid API key");if(!c.user)throw new Error("API key has no associated user");return c.user},i=e?.port||8080,o=globalThis;if(o.__KYRO_WS_SERVER__)try{await o.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=chunkFU76HURF_cjs.e({pubsub:this.pubsub,port:i,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||n}),o.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function pt(s){return new te(s)}function ns(s){let e=pt(s),t=null;return async function(i,o){return t||(t=e.init()),await t,(await e.getREST()).fetch(i,o)}}var je={debug:0,info:1,warn:2,error:3,none:4},se=class{level;constructor(){let e=typeof process<"u"?process.env?.KYRO_LOG_LEVEL:void 0;this.level=e||"info";}setLevel(e){this.level=e;}getLevel(){return this.level}shouldLog(e){return je[e]>=je[this.level]}debug(...e){this.shouldLog("debug")&&console.debug("[Kyro DEBUG]",...e);}info(...e){this.shouldLog("info")&&console.log("[Kyro]",...e);}warn(...e){this.shouldLog("warn")&&console.warn("[Kyro WARN]",...e);}error(...e){this.shouldLog("error")&&console.error("[Kyro ERROR]",...e);}},bs=new se;
|
|
4
|
+
exports.A=v;exports.B=W;exports.C=Y;exports.D=J;exports.E=Q;exports.F=te;exports.G=pt;exports.H=ns;exports.I=se;exports.J=bs;exports.a=G;exports.b=N;exports.c=_;exports.d=k;exports.e=be;exports.f=y;exports.g=xe;exports.h=Ae;exports.i=we;exports.j=ke;exports.k=Se;exports.l=R;exports.m=ot;exports.n=nt;exports.o=U;exports.p=C;exports.q=O;exports.r=z;exports.s=H;exports.t=M;exports.u=B;exports.v=V;exports.w=kt;exports.x=Re;exports.y=Fe;exports.z=Z;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import {d as d$1}from'./chunk-WLSVS3NC.js';import {a,c,b as b$1,d}from'./chunk-YNSKDTFG.js';import {a as a$1}from'./chunk-VLFM66BZ.js';import {a as a$2}from'./chunk-NGNXOXI5.js';import {sql,eq,desc,and,or,ne,inArray,ilike,like,gt,gte,lt,lte}from'drizzle-orm';import {text,uuid,jsonb,timestamp,boolean,decimal,integer as integer$1,varchar,pgTable,PgDialect}from'drizzle-orm/pg-core';import {text as text$1,integer,numeric,sqliteTable,SQLiteSyncDialect}from'drizzle-orm/sqlite-core';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
function b(m,t="postgres"){switch(m.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return m.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function z(m,t="postgres"){let i=m.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of m.fields){if(s.name==="id"||s.type==="password")continue;let n=b(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return m.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
|
|
3
|
+
`)}function N(m){if(typeof m!="string")return m;let t=m.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:m}var I=class extends a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let n=e[s.name];n&&typeof n=="string"&&(e[s.name]=new Date(n));}for(let s of i.fields){let r=b(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let o={};for(let[l,c]of Object.entries(a)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===l);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&c?o[l]=Array.isArray(c)||typeof c=="object"?JSON.stringify(c):c:o[l]=c;}e[s.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let a=t[s.name];a!=null&&(e[s.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=b(s,this.dialect);(n==="timestamp"||n==="jsonb"||n==="decimal"||n==="integer"||n==="numeric"||n==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('postgres')).default,i=(await import('drizzle-orm/postgres-js')).drizzle;}catch{a$1(["postgres","drizzle-orm"]),t=(await import('postgres')).default,i=(await import('drizzle-orm/postgres-js')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('drizzle-orm/better-sqlite3')).drizzle;}catch{a$1(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('drizzle-orm/better-sqlite3')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('drizzle-orm/d1');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e=this.getTableName(t.slug),s={id:i?text("id").primaryKey():uuid("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=b(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),l;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":l=text$1(o);break;case "integer":l=integer(o);break;case "decimal":case "numeric":l=numeric(o);break;case "boolean":l=integer(o,{mode:"boolean"});break;case "timestamp":l=text$1(o);break;case "jsonb":l=text$1(o);break;default:l=text$1(o);}else switch(r){case "varchar":l=varchar(o,{length:255});break;case "integer":l=integer$1(o);break;case "decimal":l=decimal(o);break;case "boolean":l=boolean(o);break;case "timestamp":l=timestamp(o);break;case "jsonb":l=jsonb(o);break;default:l=text(o);}n.required||(l=l.default(null)),s[a]=l;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?text$1("created_at").default(new Date().toISOString()):timestamp("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?text$1("updated_at").default(new Date().toISOString()):timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?text$1("status").default("draft"):varchar("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?integer("hasDraft",{mode:"boolean"}).default(false):boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteTable(e,s):pgTable(e,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),l=e.fields.some(u=>u.name==="status"),c=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
5
|
+
${u},
|
|
6
|
+
${r}
|
|
7
|
+
${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
8
|
+
${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
9
|
+
${l?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
|
|
10
|
+
${c?"":'"hasDraft" BOOLEAN DEFAULT false'}
|
|
11
|
+
)
|
|
12
|
+
`);}else i.push(`
|
|
13
|
+
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
14
|
+
"id" TEXT PRIMARY KEY,
|
|
15
|
+
${r}
|
|
16
|
+
${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
17
|
+
${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
18
|
+
${l?"":`"status" TEXT DEFAULT 'draft',`}
|
|
19
|
+
${c?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
20
|
+
)
|
|
21
|
+
`);}if(i.length>0)if(this.dialect==="postgres")await this.executeRaw(sql.raw(i.join(`;
|
|
22
|
+
`)));else for(let e of i)await this.executeRaw(sql.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=b(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),n=this.columnSqlType(e,i);return `"${s}" ${n} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(t){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(t,i){let e={},s=t.slug.startsWith("_globals_"),n=t.fields.some(l=>l.name==="createdAt"),r=t.fields.some(l=>l.name==="updatedAt"),a=t.fields.some(l=>l.name==="status"),o=t.fields.some(l=>l.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',n||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let l of t.fields){if(!l.name||l.name==="id")continue;let c=this.getColumnSqlDefinition(l,this.dialect),u=l.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=c;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.executeRaw(sql`PRAGMA table_info("${sql.raw(i)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(r=>!e.has(r));if(n.length>0){let r=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(sql.raw(r.join(`;
|
|
23
|
+
`)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=b(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),l=e.get(o);!l||l.type!=="character varying"||(a==="text"?await this.executeRaw(sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=b(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
|
|
24
|
+
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n=10,page:r=1,tenantId:a,select:o,draft:l}=t,c$1=this.getCollection(i),u=this.getTable(i),h={...e};this.tenantContext&&c$1.tenantScoped&&(h=c({where:h},i,this.tenantContext,b$1).where||{});let g=this.buildWhereClause(h,c$1,u,a),y=c$1.fields.find(p=>p.name==="status"),f=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(p=>p.value==="published");!l&&u.status&&f&&g.push(eq(u.status,"published"));let E=this.parseSort(s),T=!l&&u.status&&f?{...h,status:"published"}:h,J=await this.count({collection:i,where:T,tenantId:a}),H=(r-1)*n,F=[];try{let p=u[E.field]||u.createdAt||u.id,R=E.direction==="asc"?p:desc(p),_=this.client.select().from(u);g.length>0&&(_=_.where(and(...g))),F=await _.orderBy(R).limit(n).offset(H);}catch(p){console.error("[DrizzleAdapter] Query error:",p);}let C=F.map(p=>this.processResult(p,c$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(p=>d(p,i,this.tenantContext,b$1))),l&&(C=await Promise.all(C.map(async p=>{let R=await this.executeRaw(sql`
|
|
25
|
+
SELECT * FROM kyro_versions
|
|
26
|
+
WHERE collection_slug = ${i}
|
|
27
|
+
AND document_id = ${p.id}
|
|
28
|
+
ORDER BY created_at DESC
|
|
29
|
+
LIMIT 1
|
|
30
|
+
`);if(R.length>0){let _=R[0],w=_.data;for(;typeof w=="string";)try{w=JSON.parse(w);}catch{break}return (!w||typeof w!="object"||Array.isArray(w))&&(w={}),{...p,...w,status:p.status,_hasUnpublishedChanges:_.status==="draft"}}return p}))),{docs:C,...this.calculatePagination(r,n,J)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?N(e):e;if(this.tenantContext&&r.tenantScoped){let f={id:o,tenantId:this.tenantContext.tenantId};if(!d(f,i,this.tenantContext,b$1))return null}let l=[eq(a.id,o)];s&&a.tenantId&&l.push(eq(a.tenantId,s));let c=r.fields.find(f=>f.name==="status"),u=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(f=>f.value==="published");!n&&a.status&&u&&l.push(eq(a.status,"published"));let h=l.length>1?and(...l):l[0],g=await this.client.select().from(a).where(h);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n){let f=await this.executeRaw(sql`
|
|
31
|
+
SELECT * FROM kyro_versions
|
|
32
|
+
WHERE collection_slug = ${i}
|
|
33
|
+
AND document_id = ${y.id}
|
|
34
|
+
ORDER BY created_at DESC
|
|
35
|
+
LIMIT 1
|
|
36
|
+
`);if(f.length>0){let E=f[0],T=E.data;for(;typeof T=="string";)try{T=JSON.parse(T);}catch{break}(!T||typeof T!="object"||Array.isArray(T))&&(T={}),y={...y,...T,status:y.status,_hasUnpublishedChanges:E.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),l=this.dialect==="postgres"&&typeof e=="string"?N(e):e,c=[eq(a.id,l)];n&&a.tenantId&&c.push(eq(a.tenantId,n));let u=await this.client.update(a).set(o).where(and(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?N(e):e,o=[eq(r.id,a)];s&&r.tenantId&&o.push(eq(r.tenantId,s));let l=await this.client.delete(r).where(and(...o)).returning();if(l.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(l[0],n)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:sql`count(*)`}).from(r);a.length>0&&(o=o.where(and(...a)));let l=await o;return Number(l[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let l=this.getTable(i),c=this.client.select().from(l),u=o.fields.find(f=>f.name==="status"),h=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(f=>f.value==="published");!n&&l.status&&h&&(c=c.where(eq(l.status,"published")));let g=await c.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n){let f=await this.executeRaw(sql`
|
|
37
|
+
SELECT * FROM kyro_versions
|
|
38
|
+
WHERE collection_slug = ${i}
|
|
39
|
+
AND document_id = ${a}
|
|
40
|
+
ORDER BY created_at DESC
|
|
41
|
+
LIMIT 1
|
|
42
|
+
`);if(f.length>0){let E=f[0],T=typeof E.data=="string"?JSON.parse(E.data):E.data;y={...y,...T,status:y.status,_hasUnpublishedChanges:E.status==="draft"};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),l=await this.executeRaw(sql`
|
|
43
|
+
SELECT count(*) as count
|
|
44
|
+
FROM kyro_versions
|
|
45
|
+
WHERE collection_slug = ${i}
|
|
46
|
+
AND document_id = ${e}
|
|
47
|
+
AND autosave = 0
|
|
48
|
+
${r&&o.tenantScoped?sql`AND tenant_id = ${r}`:sql``}
|
|
49
|
+
`),c=parseInt(l[0]?.count||"0");return {docs:(await this.executeRaw(sql`
|
|
50
|
+
SELECT *
|
|
51
|
+
FROM kyro_versions
|
|
52
|
+
WHERE collection_slug = ${i}
|
|
53
|
+
AND document_id = ${e}
|
|
54
|
+
AND autosave = 0
|
|
55
|
+
${r&&o.tenantScoped?sql`AND tenant_id = ${r}`:sql``}
|
|
56
|
+
ORDER BY created_at DESC
|
|
57
|
+
LIMIT ${s}
|
|
58
|
+
OFFSET ${a}
|
|
59
|
+
`)).map(h=>({...h,data:typeof h.data=="string"?JSON.parse(h.data):h.data})),...this.calculatePagination(n,s,c)}}async findVersionByID(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=await this.executeRaw(sql`
|
|
60
|
+
SELECT * FROM kyro_versions
|
|
61
|
+
WHERE id = ${t.versionId}
|
|
62
|
+
AND collection_slug = ${t.collection}
|
|
63
|
+
${t.tenantId&&i.tenantScoped?sql`AND tenant_id = ${t.tenantId}`:sql``}
|
|
64
|
+
LIMIT 1
|
|
65
|
+
`);if(e.length===0)return null;let s=e[0];return {...s,data:typeof s.data=="string"?JSON.parse(s.data):s.data}}async createVersion(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=new Date().toISOString();if(t.autosave){let r=await this.executeRaw(sql`
|
|
66
|
+
SELECT * FROM kyro_versions
|
|
67
|
+
WHERE collection_slug = ${t.collection}
|
|
68
|
+
AND document_id = ${t.documentId}
|
|
69
|
+
AND autosave = 1
|
|
70
|
+
${t.tenantId&&i.tenantScoped?sql`AND tenant_id = ${t.tenantId}`:sql``}
|
|
71
|
+
LIMIT 1
|
|
72
|
+
`);if(r.length>0)return await this.executeRaw(sql`
|
|
73
|
+
UPDATE kyro_versions
|
|
74
|
+
SET data = ${JSON.stringify(t.data)},
|
|
75
|
+
status = ${t.status},
|
|
76
|
+
updated_at = ${e}
|
|
77
|
+
WHERE id = ${r[0].id}
|
|
78
|
+
`),this.findVersionByID({collection:t.collection,versionId:r[0].id,tenantId:t.tenantId})}let s=Math.random().toString(36).substring(2,15),n=typeof t.data=="string"?t.data:JSON.stringify(t.data);if(await this.executeRaw(sql`
|
|
79
|
+
INSERT INTO kyro_versions (
|
|
80
|
+
id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
|
|
81
|
+
) VALUES (
|
|
82
|
+
${s}, ${t.collection}, ${t.documentId}, ${t.tenantId&&i.tenantScoped?t.tenantId:null},
|
|
83
|
+
${n}, ${t.status}, ${t.autosave?1:0}, ${t.createdBy||null},
|
|
84
|
+
${t.changeDescription||null}, ${e}, ${e}
|
|
85
|
+
)
|
|
86
|
+
`),!t.autosave){let r=this.getCollection(t.collection);r.versions?.maxPerDoc&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:r.versions.maxPerDoc,tenantId:t.tenantId});}return this.findVersionByID({collection:t.collection,versionId:s,tenantId:t.tenantId})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection);if(t.keepLatest){let s=(await this.executeRaw(sql`
|
|
87
|
+
SELECT id FROM kyro_versions
|
|
88
|
+
WHERE collection_slug = ${t.collection}
|
|
89
|
+
AND document_id = ${t.documentId}
|
|
90
|
+
AND autosave = 0
|
|
91
|
+
${t.tenantId&&i.tenantScoped?sql`AND tenant_id = ${t.tenantId}`:sql``}
|
|
92
|
+
ORDER BY created_at DESC
|
|
93
|
+
LIMIT ${t.keepLatest}
|
|
94
|
+
`)).map(n=>n.id);s.length>0&&await this.executeRaw(sql`
|
|
95
|
+
DELETE FROM kyro_versions
|
|
96
|
+
WHERE collection_slug = ${t.collection}
|
|
97
|
+
AND document_id = ${t.documentId}
|
|
98
|
+
AND autosave = 0
|
|
99
|
+
AND id NOT IN (${sql.join(s.map(n=>sql`${n}`),sql`, `)})
|
|
100
|
+
`);}else await this.executeRaw(sql`
|
|
101
|
+
DELETE FROM kyro_versions
|
|
102
|
+
WHERE collection_slug = ${t.collection}
|
|
103
|
+
AND document_id = ${t.documentId}
|
|
104
|
+
${t.tenantId&&i.tenantScoped?sql`AND tenant_id = ${t.tenantId}`:sql``}
|
|
105
|
+
`);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t,i,e,s){let n=[];s&&i.tenantScoped&&e.tenantId&&n.push(eq(e.tenantId,s));for(let[r,a]of Object.entries(t)){let o=r,l=o.toUpperCase();if(o==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=N(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:N(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(c=>typeof c=="string"?N(c):c)}))),l==="AND"&&Array.isArray(a)){let c=a.map(u=>this.buildWhereClause(u,i,e)).flat().filter(Boolean);c.length>0&&n.push(and(...c));}else if(l==="OR"&&Array.isArray(a)){let c=a.map(u=>this.buildWhereClause(u,i,e)).flat().filter(Boolean);c.length>0&&n.push(or(...c));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=e[o]||e[o.replace(/-/g,"_")]||e[o.replace(/([A-Z])/g,"_$1").toLowerCase()]||(o==="created_at"?e.createdAt:void 0)||(o==="createdAt"?e.created_at:void 0)||(o==="updated_at"?e.updatedAt:void 0)||(o==="updatedAt"?e.updated_at:void 0);if(!c)continue;a.equals!==void 0&&n.push(eq(c,a.equals)),a.not_equals!==void 0&&n.push(ne(c,a.not_equals)),a.in&&Array.isArray(a.in)&&(a.in.length===0?n.push(sql`1 = 0`):n.push(inArray(c,a.in))),a.like!==void 0&&(this.dialect==="postgres"?n.push(ilike(c,a.like)):n.push(like(c,a.like))),a.contains!==void 0&&(this.dialect==="postgres"?n.push(ilike(c,`%${a.contains}%`)):n.push(like(c,`%${a.contains}%`))),a.greater_than!==void 0&&n.push(gt(c,a.greater_than)),a.greater_than_equal!==void 0&&n.push(gte(c,a.greater_than_equal)),a.less_than!==void 0&&n.push(lt(c,a.less_than)),a.less_than_equal!==void 0&&n.push(lte(c,a.less_than_equal));}else {let c=e[o]||e[o.replace(/-/g,"_")]||e[o.replace(/([A-Z])/g,"_$1").toLowerCase()];c&&n.push(eq(c,a));}}return n}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let n=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();n!==s.name&&e[n]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[n],delete e[n]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let n=s;if(e[n.name]&&typeof e[n.name]=="string")try{let r=JSON.parse(e[n.name]);e[n.name]=r;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let r=n.blocks||[];e[n.name]=d$1(e[n.name],r);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let r of s.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let o=e[s.name][a.name];if(typeof o=="string")try{let l=JSON.parse(o);e[s.name][a.name]=Array.isArray(l)?l.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof l.id=="string"?l.id:String(l.id||"");}catch{}else o&&typeof o=="object"&&(e[s.name][a.name]=Array.isArray(o)?o.map(l=>l&&typeof l=="object"&&typeof l.id=="string"?l.id:String(l||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[s.name]=="string")try{let r=JSON.parse(e[s.name]);if(typeof r=="object"&&r!==null){e[s.name]=r;continue}}catch{}let n={};for(let r of s.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let o=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(a.type==="upload"||a.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(l=>l&&typeof l=="object"&&typeof l.id=="string"?l.id:String(l||"")):typeof o.id=="string"?o.id:String(o.id||""));}n[a.name]=o,delete e[a.name];}e[s.name]=n;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),a$2(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
|
|
106
|
+
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
107
|
+
id text PRIMARY KEY,
|
|
108
|
+
collection_slug text NOT NULL,
|
|
109
|
+
document_id text NOT NULL,
|
|
110
|
+
tenant_id text,
|
|
111
|
+
data text NOT NULL,
|
|
112
|
+
status text NOT NULL DEFAULT 'draft',
|
|
113
|
+
autosave integer NOT NULL DEFAULT 0,
|
|
114
|
+
created_by text,
|
|
115
|
+
change_description text,
|
|
116
|
+
created_at text DEFAULT (datetime('now')),
|
|
117
|
+
updated_at text DEFAULT (datetime('now'))
|
|
118
|
+
)
|
|
119
|
+
`:t=`
|
|
120
|
+
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
121
|
+
id text PRIMARY KEY,
|
|
122
|
+
collection_slug text NOT NULL,
|
|
123
|
+
document_id text NOT NULL,
|
|
124
|
+
tenant_id text,
|
|
125
|
+
data text NOT NULL,
|
|
126
|
+
status text NOT NULL,
|
|
127
|
+
autosave integer NOT NULL DEFAULT 0,
|
|
128
|
+
created_by text,
|
|
129
|
+
change_description text,
|
|
130
|
+
created_at text NOT NULL,
|
|
131
|
+
updated_at text NOT NULL
|
|
132
|
+
)
|
|
133
|
+
`,await this.executeRaw(sql.raw(t));try{this.dialect==="postgres"?await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new PgDialect().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new SQLiteSyncDialect().sqlToQuery(t);i=n.sql,e=n.params;}else if(t&&typeof t.toSQL=="function"){let n=t.toSQL();i=n.sql,e=n.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let n=s.prepare(i);return (e.length>0?await n.bind(...e).all():await n.all()).results||[]}if(typeof this.client?.execute=="function"){let n=await this.client.execute(t);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}return []}};function pe(m){return new I(m)}export{b as a,z as b,I as c,pe as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {pgTable,timestamp,jsonb,varchar,text,integer,uuid,index}from'drizzle-orm/pg-core';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
var h=pgTable("media",{id:uuid("id").primaryKey().defaultRandom(),filename:varchar("filename",{length:255}).notNull().unique(),title:varchar("title",{length:255}),originalName:varchar("original_name",{length:255}).notNull(),mimeType:varchar("mime_type",{length:100}).notNull(),fileSize:integer("file_size").notNull(),width:integer("width"),height:integer("height"),url:text("url").notNull().unique(),thumbnailUrl:text("thumbnail_url"),folder:varchar("folder",{length:255}),provider:varchar("provider",{length:50}).notNull(),alt:text("alt"),caption:text("caption"),type:varchar("type",{length:50}).notNull().default("other"),status:varchar("status",{length:20}).notNull().default("active"),metadata:jsonb("metadata").$type(),createdAt:timestamp("created_at").defaultNow().notNull(),updatedAt:timestamp("updated_at").defaultNow().notNull()},t=>[index("media_folder_idx").on(t.folder),index("media_provider_idx").on(t.provider),index("media_filename_idx").on(t.filename)]),f=pgTable("media_folders",{path:varchar("path",{length:500}).primaryKey(),name:varchar("name",{length:255}).notNull(),parentPath:varchar("parent_path",{length:500}),createdAt:timestamp("created_at").defaultNow().notNull()},t=>[index("media_folders_parent_idx").on(t.parentPath)]);export{h as a,f as b};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a}from'./chunk-VLFM66BZ.js';import l from'bcryptjs';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
var w="kyro:auth:",y=86400,m=604800,p=class{_redis=null;prefix;tokenExpiration;refreshExpiration;options;constructor(e={}){this.options=e,this.prefix=e.keyPrefix||w,this.tokenExpiration=e.tokenExpiration||y,this.refreshExpiration=e.refreshTokenExpiration||m;}async getRedis(){if(!this._redis){let e,t="ioredis";try{e=(await import(t)).Redis;}catch{a([t]),e=(await import(t)).Redis;}let s=this.options.url||`redis://${this.options.host||"localhost"}:${this.options.port||6379}`;this._redis=new e(s,{password:this.options.password,db:this.options.db,lazyConnect:true,tls:this.options.tls?{}:void 0});}return this._redis}async connect(){await this.getRedis();}async disconnect(){await(await this.getRedis()).quit();}userKey(e){return `${this.prefix}users:${e}`}sessionKey(e){return `${this.prefix}sessions:${e}`}refreshKey(e){return `${this.prefix}refresh:${e}`}userByEmailKey(e){return `${this.prefix}users:email:${e.toLowerCase()}`}passwordHistoryKey(e){return `${this.prefix}users:${e}:password_history`}async createUser(e){let t=randomBytes(16).toString("hex"),s=new Date().toISOString(),i=await this.hashPassword(e.password),r={id:t,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",tenantId:e.tenantId,createdAt:s,updatedAt:s},n=(await this.getRedis()).pipeline();return n.hset(this.userKey(t),this.userToHash(r)),n.set(this.userByEmailKey(e.email),t),await n.exec(),r}async findUserByEmail(e){let t=await(await this.getRedis()).get(this.userByEmailKey(e.toLowerCase()));return t?this.findUserById(t):null}async findUserById(e){let t=await(await this.getRedis()).hgetall(this.userKey(e));return !t||Object.keys(t).length===0?null:this.hashToUser(t)}async updateUser(e,t){let s=await this.findUserById(e);if(!s)return null;let i={...s,...t,id:e,updatedAt:new Date().toISOString()};if(t.email&&t.email!==s.email){let r=(await this.getRedis()).pipeline();r.del(this.userByEmailKey(s.email)),r.set(this.userByEmailKey(t.email),e),await r.exec();}return await(await this.getRedis()).hset(this.userKey(e),this.userToHash(i)),i}async deleteUser(e){let t=await this.findUserById(e);if(!t)return false;let s=(await this.getRedis()).pipeline();return s.del(this.userKey(e)),s.del(this.userByEmailKey(t.email)),s.del(this.passwordHistoryKey(e)),await s.exec(),true}async hashPassword(e){return l.hash(e,12)}async verifyPassword(e,t){let s=await(await this.getRedis()).get(this.userByEmailKey(e));if(!s)return null;let i=await this.findUserById(s);return !i||!i.passwordHash?null:await l.compare(t,i.passwordHash)?i:null}async createSession(e,t={}){let s=randomBytes(32).toString("hex"),i=randomBytes(32).toString("base64url"),r=randomBytes(32).toString("base64url"),n=new Date,a={id:s,userId:e,token:i,refreshToken:r,expiresAt:new Date(n.getTime()+this.tokenExpiration*1e3).toISOString(),createdAt:n.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent},o=(await this.getRedis()).pipeline();return o.hset(this.sessionKey(s),this.sessionToHash(a)),o.setex(this.refreshKey(r),this.refreshExpiration,s),await o.exec(),a}async findSessionByToken(e){let t=await(await this.getRedis()).hgetall(this.sessionKey(e));return !t||Object.keys(t).length===0?null:this.hashToSession(t)}async findSessionByRefreshToken(e){let t=await(await this.getRedis()).get(this.refreshKey(e));if(!t)return null;let s=await(await this.getRedis()).hgetall(this.sessionKey(t));return !s||Object.keys(s).length===0?null:this.hashToSession(s)}async deleteSession(e){let t=await(await this.getRedis()).hgetall(this.sessionKey(e));if(!t||Object.keys(t).length===0)return false;let s=(await this.getRedis()).pipeline();return s.del(this.sessionKey(e)),t.refreshToken&&s.del(this.refreshKey(t.refreshToken)),await s.exec(),true}async deleteUserSessions(e){let t=`${this.prefix}sessions:*`,s="0",i=0;do{let[r,n]=await(await this.getRedis()).scan(s,"MATCH",t,"COUNT",100);s=r;for(let a of n)if((await(await this.getRedis()).hgetall(a)).userId===e){let g=a.replace(`${this.prefix}sessions:`,"");await this.deleteSession(g),i++;}}while(s!=="0");return i}async addPasswordToHistory(e,t){await(await this.getRedis()).lpush(this.passwordHistoryKey(e),t),await(await this.getRedis()).ltrim(this.passwordHistoryKey(e),0,4);}async getPasswordHistory(e,t=5){return (await this.getRedis()).lrange(this.passwordHistoryKey(e),0,t-1)}async isPasswordInHistory(e,t,s=5){let i=await this.getPasswordHistory(t,s);for(let r of i)if(await l.compare(e,r))return true;return false}userToHash(e){let t={id:e.id,email:e.email,passwordHash:e.passwordHash||"",role:e.role,createdAt:e.createdAt,updatedAt:e.updatedAt};return e.avatar&&(t.avatar=e.avatar),e.tenantId&&(t.tenantId=e.tenantId),e.metadata&&(t.metadata=JSON.stringify(e.metadata)),e.emailVerified!==void 0&&(t.emailVerified=String(e.emailVerified)),e.locked!==void 0&&(t.locked=String(e.locked)),e.lastLogin&&(t.lastLogin=e.lastLogin),e.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=String(e.failedLoginAttempts)),t}hashToUser(e){return {id:e.id,email:e.email,passwordHash:e.passwordHash,role:e.role,tenantId:e.tenantId,avatar:e.avatar,metadata:e.metadata?JSON.parse(e.metadata):void 0,createdAt:e.createdAt,updatedAt:e.updatedAt,emailVerified:e.emailVerified==="true",locked:e.locked==="true",lastLogin:e.lastLogin,failedLoginAttempts:e.failedLoginAttempts?parseInt(e.failedLoginAttempts,10):0}}sessionToHash(e){let t={id:e.id,userId:e.userId,token:e.token,expiresAt:e.expiresAt,createdAt:e.createdAt};return e.refreshToken&&(t.refreshToken=e.refreshToken),e.ipAddress&&(t.ipAddress=e.ipAddress),e.userAgent&&(t.userAgent=e.userAgent),t}hashToSession(e){return {id:e.id,userId:e.userId,token:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,createdAt:e.createdAt,ipAddress:e.ipAddress,userAgent:e.userAgent}}tokenKey(e,t){return `${this.prefix}tokens:${e}:${t}`}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),s=new Date(Date.now()+1440*60*1e3);return await(await this.getRedis()).setex(this.tokenKey("email-verify",t),86400,e),{token:t,expiresAt:s}}async verifyEmailToken(e){let t=await this.getRedis(),s=await t.get(this.tokenKey("email-verify",e));return s?(await t.del(this.tokenKey("email-verify",e)),{success:true,userId:s}):{success:false,error:"Invalid or expired token"}}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let s=randomBytes(32).toString("hex"),i=new Date(Date.now()+3600*1e3);return await(await this.getRedis()).setex(this.tokenKey("password-reset",s),3600,t.id),{token:s,expiresAt:i}}async resetPasswordWithToken(e,t){let s=await this.getRedis(),i=await s.get(this.tokenKey("password-reset",e));if(!i)return {success:false,error:"Invalid or expired token"};let r=await this.hashPassword(t);return await this.updateUser(i,{passwordHash:r}),await s.del(this.tokenKey("password-reset",e)),{success:true}}auditLogKey(e){return `${this.prefix}audit:logs:${e}`}auditLogIndexKey(){return `${this.prefix}audit:index`}async findAuditLogs(e){let{limit:t=50,offset:s=0}=e,i=this.auditLogIndexKey(),r=await(await this.getRedis()).zrevrange(i,0,-1),n=r.length,a=r.slice(s,s+t),o=[];for(let g of a){let u=await(await this.getRedis()).get(this.auditLogKey(g));if(u){let d=JSON.parse(u);(!e.userId||d.userId===e.userId)&&(!e.action||(Array.isArray(e.action)?e.action.includes(d.action):d.action===e.action))&&(!e.resource||d.resource===e.resource)&&(e.success===void 0||d.success===e.success)&&o.push({...d,timestamp:new Date(d.timestamp)});}}return {logs:o,total:n}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),i={...e,id:t,timestamp:new Date};await(await this.getRedis()).set(this.auditLogKey(t),JSON.stringify(i)),await(await this.getRedis()).zadd(this.auditLogIndexKey(),Date.now(),t);let r=await(await this.getRedis()).zcard(this.auditLogIndexKey());if(r>1e4){let n=await(await this.getRedis()).zrange(this.auditLogIndexKey(),0,r-10001);for(let a of n)await(await this.getRedis()).del(this.auditLogKey(a)),await(await this.getRedis()).zrem(this.auditLogIndexKey(),a);}return i}};
|
|
3
|
+
export{p as a};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {execSync}from'child_process';import {existsSync}from'fs';import {join}from'path';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
function e(){let n=process.cwd();return existsSync(join(n,"pnpm-lock.yaml"))?"pnpm":existsSync(join(n,"yarn.lock"))?"yarn":existsSync(join(n,"bun.lockb"))||existsSync(join(n,"bun.lock"))?"bun":"npm"}function u(n){let o=e();console.log(`
|
|
3
|
+
\u{1F4E6} [Kyro CMS] Auto-installing missing database drivers: ${n.join(", ")}...`);try{let i=o==="npm"?"npm install":`${o} add`;execSync(`${i} ${n.join(" ")}`,{stdio:"inherit"}),console.log(`\u2705 [Kyro CMS] Successfully installed drivers!
|
|
4
|
+
`);}catch(i){throw console.error(`\u274C [Kyro CMS] Failed to auto-install drivers. Please run manually: ${o==="npm"?"npm install":`${o} add`} ${n.join(" ")}`),i}}export{u as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkH2IJDTA2_cjs=require('./chunk-H2IJDTA2.cjs'),chunkPW6Y5MQL_cjs=require('./chunk-PW6Y5MQL.cjs'),chunk2I2AXTKY_cjs=require('./chunk-2I2AXTKY.cjs');async function f(t){let{adminEmail:e,adminPassword:r,adminRole:a="super_admin",tenantId:n,emailConfig:o,sendWelcomeEmail:c=false}=t,s=t.authAdapter||new chunkPW6Y5MQL_cjs.a({path:t.authDbPath||"./data/auth.db"});try{await s.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let u=new chunkH2IJDTA2_cjs.a().validate(r);if(!u.valid)return await s.disconnect?.(),{success:false,error:`Invalid password: ${u.errors.join(", ")}`};if(await s.findUserByEmail(e))return await s.disconnect?.(),{success:false,error:"Admin user already exists"};try{let i=await s.createUser({name:"Super Admin",email:e,password:r,role:a||"admin",tenantId:n});if(await s.updateUser?.(i.id,{emailVerified:!0}),c&&o){let l=new chunk2I2AXTKY_cjs.q(o),w=l.getTemplates().welcome(e.split("@")[0]);await l.send({to:e,...w});}return await s.disconnect?.(),{success:!0,user:i}}catch(i){return await s.disconnect?.(),{success:false,error:i instanceof Error?i.message:"Failed to create admin user"}}}async function S(t,e){return !await t.findUserByEmail(e)}function g(t){let e=t.KYRO_ADMIN_EMAIL,r=t.KYRO_ADMIN_PASSWORD;return !e||!r?null:{authDbPath:t.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:e,adminPassword:r,adminRole:t.KYRO_ADMIN_ROLE||"super_admin",tenantId:t.KYRO_ADMIN_TENANT_ID,emailConfig:t.SMTP_HOST?{provider:"smtp",smtp:{host:t.SMTP_HOST,port:parseInt(t.SMTP_PORT||"587",10),secure:t.SMTP_SECURE==="true",auth:{user:t.SMTP_USER||"",pass:t.SMTP_PASS||""}},from:t.SMTP_FROM||"noreply@example.com",fromName:t.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:t.KYRO_ADMIN_SEND_WELCOME==="true"}}function A(){return g(process.env)}async function h(){try{let{env:t}=await import('cloudflare:workers');if(t){let e=g(t);if(e)return e}}catch{}return null}async function U(t){let e=A()||await h();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await f(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function M(t,e=3,r=2e3){let a="";for(let n=0;n<e;n++){let o=await f(t);if(o.success||(a=o.error||"Unknown error",a.includes("already exists")))return o;n<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${a}`}}exports.a=f;exports.b=S;exports.c=g;exports.d=A;exports.e=U;exports.f=M;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkTG5YQ4PB_cjs=require('./chunk-TG5YQ4PB.cjs'),chunkVPBGZW4P_cjs=require('./chunk-VPBGZW4P.cjs'),chunkHACW42ZZ_cjs=require('./chunk-HACW42ZZ.cjs'),chunkPW6Y5MQL_cjs=require('./chunk-PW6Y5MQL.cjs'),chunkGWUHIIPO_cjs=require('./chunk-GWUHIIPO.cjs'),chunk3A5UO6OQ_cjs=require('./chunk-3A5UO6OQ.cjs'),chunkNBBAMC2X_cjs=require('./chunk-NBBAMC2X.cjs'),m=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var m__default=/*#__PURE__*/_interopDefault(m);exports.a=null;var c=null;async function T(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=m__default.default.default||m__default.default,t=e.adapter,r=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||r)){let s=globalThis.DB;e.adapter=new chunkGWUHIIPO_cjs.c({type:"sqlite",client:s}),chunkTG5YQ4PB_cjs.J.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunkTG5YQ4PB_cjs.G(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),l=a&&a.dialect==="mongodb",o;if(p)a.dialect==="postgres"?o=new chunk3A5UO6OQ_cjs.a({db:a.client}):a.dialect==="sqlite"&&(o=new chunkHACW42ZZ_cjs.m({db:a.rawClient||a.client}));else if(r&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new chunkPW6Y5MQL_cjs.a({path:s});}else l&&(o=new chunkNBBAMC2X_cjs.a({adapter:a}));if(o?.connect)try{await o.connect();}catch(s){chunkTG5YQ4PB_cjs.J.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunkTG5YQ4PB_cjs.J.warn("loadSettings warning:",s);}try{await chunkVPBGZW4P_cjs.e(o);}catch(s){chunkTG5YQ4PB_cjs.J.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,c=null,chunkTG5YQ4PB_cjs.J.error("Init failed, will retry:",e),e}}}async function b(e){let t=globalThis.DB?globalThis:null;try{let{env:r}=await import('cloudflare:workers');r&&(t=r);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),c||(c=T()),await c;}var w={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function _(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??w[e]??true:w[e]??true}var E=async e=>{if(!exports.a)try{await Promise.race([b(e),new Promise((t,r)=>setTimeout(()=>r(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let r=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(r===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!_("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(o.body,o)}if(r.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!_("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(o.body,o)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){let r=process.env.NODE_ENV==="production";return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:r?"An unexpected error occurred":t?.message||String(t),...r?{}:{stack:t?.stack}}),{status:500,headers:{"Content-Type":"application/json"}})}},N=E;exports.b=b;exports.c=E;exports.d=N;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a,c,b as b$1,d}from'./chunk-YNSKDTFG.js';import {a as a$1}from'./chunk-VLFM66BZ.js';import {a as a$3}from'./chunk-NGNXOXI5.js';import {a as a$2}from'./chunk-RLW6AQF2.js';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
var b=class extends a{dialect="mongodb";client;db;database;connectionString;constructor(i){if(super(),i.connectionString){this.connectionString=i.connectionString;try{let e=new URL(i.connectionString);this.database=e.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database="kyro_cms";}}else this.client=i.client,this.database=i.database;}async connect(){if(this.connectionString&&!this.client){let i;try{let e=await import('mongodb');i=e.MongoClient??e.default?.MongoClient;}catch{a$1(["mongodb"]);let n=await import('mongodb');i=n.MongoClient??n.default?.MongoClient;}this.client=new i(this.connectionString),await this.client.connect();}else if(this.client&&typeof this.client.connect=="function")try{await this.client.connect();}catch{}this.client&&(this.db=this.client.db(this.database),this.connected=true);}async disconnect(){this.client&&(await this.client.close(),this.connected=false);}getMongoCollection(i){if(!this.db&&this.client&&(this.db=this.client.db(this.database),this.connected=true),!this.db)throw new Error("MongoDB not connected");return this.db.collection(i)}async find(i){let{collection:e,where:n={},sort:s,limit:t=10,page:o=1,tenantId:r,select:a,draft:l}=i,d$1=this.getCollectionConfig(e),f=this.getMongoCollection(e),u={...n};this.tenantContext&&d$1.tenantScoped&&(u=c({where:u},e,this.tenantContext,b$1).where||{});let g=this.buildFilter(u,d$1.tenantScoped?r:void 0),c$1=d$1.fields.find(h=>h.name==="status"),p=c$1?.type==="select"&&Array.isArray(c$1.options)&&c$1.options.some(h=>h.value==="published");!l&&p&&(g.status="published");let y=this.parseSort(s),R={[y.field]:y.direction==="asc"?1:-1},$=(o-1)*t,[O,x]=await Promise.all([f.find(g).sort(R).skip($).limit(t).project(this.buildProjection(a)).toArray(),f.countDocuments(g)]),C=O.map(h=>this.processResult(h,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(h=>d(h,e,this.tenantContext,b$1))),l&&(C=await Promise.all(C.map(async h=>{let m=await this.getMongoCollection(`${e}_versions`).findOne({document_id:h.id},{sort:{createdAt:-1}});if(m){let M=typeof m.data=="string"?JSON.parse(m.data):m.data&&typeof m.data=="object"?m.data:{};return {...h,...M,status:h.status,_hasUnpublishedChanges:m.status==="draft"}}return h}))),{docs:C,...this.calculatePagination(o,t,x)}}buildIdFilter(i,e,n){let s=String(i||""),t=/^[0-9a-fA-F]{24}$/.test(s),o=[{_id:s},{id:s},{slug:s},{orderNumber:s}];if(t)try{let{ObjectId:a}=a$2("mongodb");o.unshift({_id:new a(s)});}catch{}let r={$or:o};return e&&n?.tenantScoped&&(r.tenantId=e),r}async findByID(i){let{collection:e,id:n,tenantId:s,draft:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e);if(this.tenantContext&&o.tenantScoped){let g={_id:n,tenantId:this.tenantContext.tenantId};if(!d(g,e,this.tenantContext,b$1))return null}let a=this.buildIdFilter(n,s,o),l=o.fields.find(g=>g.name==="status"),d$1=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(g=>g.value==="published");!t&&d$1&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let u=this.processResult(f,o);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:u.id},{sort:{createdAt:-1}});if(c){let p=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};u={...u,...p,status:u.status,_hasUnpublishedChanges:c.status==="draft"};}}return u}async create(i){let{collection:e,data:n,tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r=this.prepareData(n,t),a=r.id||this.generateId();delete r.id;let l={...r,_id:a};return s&&t.tenantScoped&&(l.tenantId=s),await o.insertOne(l),this.processResult(l,t)}async update(i){let{collection:e,id:n,data:s,tenantId:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildIdFilter(n,t,o),l=this.prepareData(s,o),d=await r.findOneAndUpdate(a,{$set:l},{returnDocument:"after"});if(!d)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(d,o)}async delete(i){let{collection:e,id:n,tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r=this.buildIdFilter(n,s,t),a=await o.findOneAndDelete(r);if(!a)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(a,t)}async count(i){let{collection:e,where:n={},tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r=this.buildFilter(n,t.tenantScoped?s:void 0);return o.countDocuments(r)}async findOne(i){let{collection:e,where:n={},tenantId:s,draft:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildFilter(n,o.tenantScoped?s:void 0),l=o.fields.find(g=>g.name==="status"),d=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(g=>g.value==="published");!t&&d&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let u=this.processResult(f,o);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:u.id},{sort:{createdAt:-1}});if(c){let p=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};u={...u,...p,status:u.status};}}return u}async findVersions(i){let{collection:e,documentId:n,sort:s,limit:t=10,page:o=1,tenantId:r}=i,a=this.getCollectionConfig(e),l=this.getMongoCollection(`${e}_versions`),d={document_id:n,autosave:{$ne:true}};r&&a.tenantScoped&&(d.tenant_id=r);let f=(o-1)*t,u=this.parseSort(s),g={[u.field]:u.direction==="asc"?1:-1},[c,p]=await Promise.all([l.find(d).sort(g).skip(f).limit(t).toArray(),l.countDocuments(d)]);return {docs:c.map(y=>this.processResult(y,{})),...this.calculatePagination(o,t,p)}}async findVersionByID(i){let{collection:e,versionId:n,tenantId:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(`${e}_versions`),r={_id:n};s&&t.tenantScoped&&(r.tenant_id=s);let a=await o.findOne(r);return a?this.processResult(a,{}):null}async createVersion(i){let{collection:e,documentId:n,data:s,status:t,createdBy:o,changeDescription:r,tenantId:a,autosave:l}=i,d=this.getCollectionConfig(e),f=this.getMongoCollection(`${e}_versions`);if(l){let c={document_id:n,collection_slug:e,autosave:true};a&&d.tenantScoped&&(c.tenant_id=a);let p=await f.findOne(c);if(p){let y=new Date().toISOString();return await f.updateOne({_id:p._id},{$set:{data:s,status:t,updatedAt:y}}),this.processResult({...p,data:s,status:t,updatedAt:y},{})}}let u=new Date().toISOString(),g={_id:this.generateId(),document_id:n,collection_slug:e,data:s,status:t,autosave:l===true,created_by:o,change_description:r,createdAt:u,updatedAt:u};if(a&&d.tenantScoped&&(g.tenant_id=a),await f.insertOne(g),!l){let c=this.getCollectionConfig(e);c.versions?.maxPerDoc&&await this.deleteVersions({collection:e,documentId:n,keepLatest:c.versions.maxPerDoc,tenantId:a});}return this.processResult(g,{})}async updateLatestVersion(i){return this.createVersion({...i,autosave:true})}async deleteVersions(i){let{collection:e,documentId:n,keepLatest:s,tenantId:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(`${e}_versions`);if(s){let a={document_id:n,autosave:{$ne:true}};t&&o.tenantScoped&&(a.tenant_id=t);let d=(await r.find(a).sort({createdAt:-1}).limit(s).project({_id:1}).toArray()).map(f=>f._id);d.length>0&&await r.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:d},...t&&o.tenantScoped?{tenant_id:t}:{}});}else {let a={document_id:n};t&&o.tenantScoped&&(a.tenant_id=t),await r.deleteMany(a);}}async migrate(){for(let i of this.collections.values()){let e=this.getMongoCollection(i.slug);await e.createIndex({_id:1}),i.tenantScoped&&await e.createIndex({tenantId:1}),i.timestamps&&await e.createIndex({createdAt:-1});for(let n of i.fields)n.unique&&n.name&&await e.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await e.createIndex({[n.name]:1});}}getCollectionConfig(i){if(i.startsWith("_globals_")){let n=i.replace("_globals_",""),s=this.globals.get(n);if(!s)throw new Error(`Global "${n}" not found`);return s}let e=this.collections.get(i);if(!e)throw new Error(`Collection "${i}" not found`);return e}buildFilter(i={},e){let n={};e&&(n.tenantId=e);for(let[s,t]of Object.entries(i))if(s==="AND"&&Array.isArray(t)){let o=t.map(r=>this.buildFilter(r));Object.assign(n,...o);}else if(s==="OR"&&Array.isArray(t))n.$or=t.map(o=>this.buildFilter(o));else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o={};if(t.equals!==void 0){n[s==="id"?"_id":s]=t.equals;continue}t.not_equals!==void 0&&(o.$ne=t.not_equals),t.in!==void 0&&(o.$in=t.in),t.not_in!==void 0&&(o.$nin=t.not_in),t.greater_than!==void 0&&(o.$gt=t.greater_than),t.greater_than_equal!==void 0&&(o.$gte=t.greater_than_equal),t.less_than!==void 0&&(o.$lt=t.less_than),t.less_than_equal!==void 0&&(o.$lte=t.less_than_equal),t.like!==void 0&&(o.$regex=new RegExp(t.like.replace(/%/g,".*"),"i")),t.not_like!==void 0&&(o.$not=new RegExp(t.not_like.replace(/%/g,".*"),"i")),t.contains!==void 0&&(o.$regex=new RegExp(`.*${t.contains}.*`,"i")),t.exists!==void 0&&(o.$exists=t.exists),Object.keys(o).length>0&&(n[s==="id"?"_id":s]=o);}else n[s==="id"?"_id":s]=t;return n}buildProjection(i){if(!i||i.length===0)return;let e={_id:1};for(let n of i)e[n]=1;return e}processResult(i,e){if(!i)return null;let n={...i};for(let s of Object.keys(n))/^\d+$/.test(s)&&delete n[s];return i._id&&(n.id=String(i._id),delete n._id),delete n.__v,n.createdAt&&(n.createdAt=new Date(n.createdAt).toISOString()),n.updatedAt&&(n.updatedAt=new Date(n.updatedAt).toISOString()),a$3(n)}generateId(){let i=Date.now().toString(16).padStart(12,"0"),e=randomBytes(6).toString("hex");return i+e}};function j(w){return new b(w)}
|
|
3
|
+
export{b as a,j as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {pgTable,timestamp,text,varchar}from'drizzle-orm/pg-core';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
var o=pgTable("settings",{key:varchar("key",{length:255}).primaryKey(),value:text("value").notNull(),description:text("description"),updatedAt:timestamp("updated_at").defaultNow()});export{o as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
function u(n){return n.map(o=>`${o.path.join(".")}: ${o.message}`).join(", ")}async function y(n,o,e,t,f="read"){if(!n||typeof n!="object"||e?.role==="super_admin")return n;let s=Array.isArray(n)?[...n]:{...n};for(let r of o)if(r.name){if(r.access&&typeof r.access[f]=="function"&&!await r.access[f]({user:e,req:t,doc:n,data:n})){delete s[r.name];continue}r.type==="group"&&Array.isArray(r.fields)&&s[r.name]?s[r.name]=await y(s[r.name],r.fields,e,t,f):r.type==="array"&&Array.isArray(r.fields)&&Array.isArray(s[r.name])&&(s[r.name]=await Promise.all(s[r.name].map(a=>y(a,r.fields||[],e,t,f))));}return s}function l(n){let o=[];for(let e of n)if(e.type==="tabs"&&Array.isArray(e.tabs))for(let t of e.tabs)Array.isArray(t.fields)&&o.push(...l(t.fields));else (e.type==="row"||e.type==="collapsible")&&Array.isArray(e.fields)?o.push(...l(e.fields)):o.push(e);return o}function c(n,o){return Array.isArray(n)?n.map(e=>{if(!e||typeof e!="object")return e;let t=e.data?{...e.data}:void 0;if(!t)return e;let f=o.find(i=>i.slug===e.type||i.slug===e.slug);if(!f||!Array.isArray(f.fields))return e;for(let i of f.fields){if(i.name&&(i.type==="upload"||i.type==="image")&&t[i.name]){let s=t[i.name];Array.isArray(s)?t[i.name]=s.map(r=>typeof r=="string"?{id:r}:r):typeof s=="string"&&(t[i.name]={id:s});}if(i.type==="blocks"&&i.name&&t[i.name]){let s=i.blocks||[];t[i.name]=c(t[i.name],s);}}return {...e,data:t}}):n}export{u as a,y as b,l as c,c as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {J,G}from'./chunk-N25DOGLQ.js';import {e}from'./chunk-KUY4QDAL.js';import {m as m$1}from'./chunk-A4XM33WO.js';import {a as a$1}from'./chunk-IIVBEZC2.js';import {c as c$1}from'./chunk-TJ6N5ZPZ.js';import {a}from'./chunk-IIPSXKNV.js';import {a as a$2}from'./chunk-CIWLQXB2.js';import m from'kyro:config';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
var n=null,c=null;async function T(){if(!n){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e$1=m.default||m,t=e$1.adapter,r=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||r)){let s=globalThis.DB;e$1.adapter=new c$1({type:"sqlite",client:s}),J.info("Hot-swapped to D1 DrizzleAdapter");}n=G(e$1),await n.init();let a$3=e$1.adapter,p=a$3&&a$3.dialect&&(a$3.dialect==="postgres"||a$3.dialect==="sqlite"),l=a$3&&a$3.dialect==="mongodb",o;if(p)a$3.dialect==="postgres"?o=new a({db:a$3.client}):a$3.dialect==="sqlite"&&(o=new m$1({db:a$3.rawClient||a$3.client}));else if(r&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a$1({path:s});}else l&&(o=new a$2({adapter:a$3}));if(o?.connect)try{await o.connect();}catch(s){J.warn("Auth connect warning:",s);}try{await n.loadSettings();}catch(s){J.warn("loadSettings warning:",s);}try{await e(o);}catch(s){J.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=n;}catch(e){throw n=null,c=null,J.error("Init failed, will retry:",e),e}}}async function b(e){let t=globalThis.DB?globalThis:null;try{let{env:r}=await import('cloudflare:workers');r&&(t=r);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),c||(c=T()),await c;}var w={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function _(e){return n?n.settings?.access?.apiAccess?.[e]??w[e]??true:w[e]??true}var E=async e=>{if(!n)try{await Promise.race([b(e),new Promise((t,r)=>setTimeout(()=>r(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let r=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(r===`${a}/graphql`&&typeof n.getGraphQL=="function"){if(!_("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await n.getGraphQL().fetch(e.request,e.locals);return new Response(o.body,o)}if(r.startsWith(`${a}/trpc/`)&&typeof n.getTRPC=="function"){if(!_("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await n.getTRPC().fetch(e.request,e.locals);return new Response(o.body,o)}return await(await n.getREST()).fetch(e.request,e.locals)}catch(t){let r=process.env.NODE_ENV==="production";return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:r?"An unexpected error occurred":t?.message||String(t),...r?{}:{stack:t?.stack}}),{status:500,headers:{"Content-Type":"application/json"}})}},q=E;export{n as a,b,E as c,q as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-O4RKZQYQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
var a=class{collections=new Map;globals=new Map;connected=false;tenantContext;setTenantContext(e){this.tenantContext=e;}getTenantContext(){return this.tenantContext}async init(e,n=[]){for(let t of e)this.collections.set(t.slug,t);for(let t of n)this.globals.set(t.slug,t);await this.connect();}getCollection(e){let n=this.collections.get(e);if(!n)throw console.error(`[Adapter] Missing collection "${e}". Available collections:`,Array.from(this.collections.keys())),new Error(`Collection "${e}" not found in adapter`);return n}applyTenantFilter(e={},n){return n?{...e,tenantId:{equals:n}}:e}getTableName(e){return e.replace(/-/g,"_")}prepareData(e,n){let t={...e};if(n.timestamps){let r=new Date().toISOString();t.updatedAt=r,t.createdAt||(t.createdAt=r);}return n.auth&&t.password,t}processRelationships(e,n,t){return e}parseSort(e){return e?e.startsWith("-")?{field:e.slice(1),direction:"desc"}:{field:e,direction:"asc"}:{field:"createdAt",direction:"desc"}}calculatePagination(e,n,t){let r=Math.ceil(t/n);return {totalDocs:t,limit:n,totalPages:r,page:e,pagingCounter:(e-1)*n+1,hasPrevPage:e>1,hasNextPage:e<r,prevPage:e>1?e-1:null,nextPage:e<r?e+1:null}}selectFields(e,n){if(!n||n.length===0)return e;let t={};for(let r of n)r in e&&(t[r]=e[r]);return t.id=e.id,t}isRelationshipField(e){return e.type==="relationship"}isUploadField(e){return e.type==="upload"}getRelationshipFields(e){let n=[];for(let t of e)t.type==="relationship"?n.push(t):"fields"in t&&t.fields&&n.push(...this.getRelationshipFields(t.fields));return n}getUploadFields(e){let n=[];for(let t of e)t.type==="upload"?n.push(t):"fields"in t&&t.fields&&n.push(...this.getUploadFields(t.fields));return n}};var s={tenantEnabled:true,tenantField:"tenantId",ownershipRules:{posts:{ownerField:"authorId",bypassRoles:["super_admin","admin","editor"]},pages:{ownerField:"authorId",bypassRoles:["super_admin","admin","editor"]},media:{ownerField:"uploadedBy",bypassRoles:["super_admin","admin","editor"]},orders:{ownerField:"customerId",bypassRoles:["super_admin","admin","editor"]},customers:{ownerField:"id",bypassRoles:["super_admin","admin"]},navigation:{ownerField:"id",bypassRoles:["super_admin","admin"]}}};function c(i,e,n=s){return !n.tenantEnabled||e.isSuperAdmin?i:{...i,where:{...i.where,[n.tenantField]:e.tenantId}}}function g(i,e,n,t=s){let r=t.ownershipRules[e];return !r||r.bypassRoles&&b({role:n.role},r.bypassRoles)?i:r.ownerField==="id"&&n.userId?{...i,where:{...i.where,id:n.userId}}:r.ownerField&&n.userId?{...i,where:{...i.where,[r.ownerField]:n.userId}}:i}function R(i,e,n,t=s){let r=i;return r=c(r,n,t),r=g(r,e,n,t),r}function m(i,e,n,t=s){if(n.isSuperAdmin)return true;if(t.tenantEnabled&&i[t.tenantField]!==n.tenantId)return false;let r=t.ownershipRules[e];return !r||r.bypassRoles&&b({role:n.role},r.bypassRoles)?true:r.ownerField==="id"?i.id===n.userId:r.ownerField?i[r.ownerField]===n.userId:true}export{a,s as b,R as c,m as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';function m(n){return n.map(o=>`${o.path.join(".")}: ${o.message}`).join(", ")}async function y(n,o,e,t,f="read"){if(!n||typeof n!="object"||e?.role==="super_admin")return n;let s=Array.isArray(n)?[...n]:{...n};for(let r of o)if(r.name){if(r.access&&typeof r.access[f]=="function"&&!await r.access[f]({user:e,req:t,doc:n,data:n})){delete s[r.name];continue}r.type==="group"&&Array.isArray(r.fields)&&s[r.name]?s[r.name]=await y(s[r.name],r.fields,e,t,f):r.type==="array"&&Array.isArray(r.fields)&&Array.isArray(s[r.name])&&(s[r.name]=await Promise.all(s[r.name].map(a=>y(a,r.fields||[],e,t,f))));}return s}function l(n){let o=[];for(let e of n)if(e.type==="tabs"&&Array.isArray(e.tabs))for(let t of e.tabs)Array.isArray(t.fields)&&o.push(...l(t.fields));else (e.type==="row"||e.type==="collapsible")&&Array.isArray(e.fields)?o.push(...l(e.fields)):o.push(e);return o}function c(n,o){return Array.isArray(n)?n.map(e=>{if(!e||typeof e!="object")return e;let t=e.data?{...e.data}:void 0;if(!t)return e;let f=o.find(i=>i.slug===e.type||i.slug===e.slug);if(!f||!Array.isArray(f.fields))return e;for(let i of f.fields){if(i.name&&(i.type==="upload"||i.type==="image")&&t[i.name]){let s=t[i.name];Array.isArray(s)?t[i.name]=s.map(r=>typeof r=="string"?{id:r}:r):typeof s=="string"&&(t[i.name]={id:s});}if(i.type==="blocks"&&i.name&&t[i.name]){let s=i.blocks||[];t[i.name]=c(t[i.name],s);}}return {...e,data:t}}):n}exports.a=m;exports.b=y;exports.c=l;exports.d=c;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {c,d as d$1}from'./chunk-WLSVS3NC.js';import {a,c as c$1,b,d}from'./chunk-YNSKDTFG.js';import {a as a$1}from'./chunk-NGNXOXI5.js';import {createRequire}from'module';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
function w(T,t){let i=t,n=T[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{n=n?JSON.parse(n):null;}catch{n=null;}if(i.type==="checkbox"&&(n=!!n),i.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((i.type==="upload"||i.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(o=>typeof o=="object"&&o!==null?o:{id:o}):n=typeof a=="object"?a:{id:a};}catch{n=typeof n=="string"?{id:n}:n;}return n}var C;function U(){return C||(C=createRequire("file:///")("node:sqlite").DatabaseSync,C)}function R(T,t){try{return T.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}catch{return []}}var I=class extends a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(t){super(),this.path=t.path,t.db?this.db=t.db:this.db=null;}async connect(){if(!this.db)this.db=new(U())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(U())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let t=this.db.prepare.bind(this.db),i=n=>{let a=t(n),o=e=>typeof e=="boolean"?e?1:0:e===void 0?null:e;return new Proxy(a,{get(e,s,r){if(s==="all")return (...c)=>e.all(...c.map(o));if(s==="get")return (...c)=>e.get(...c.map(o));if(s==="run")return (...c)=>e.run(...c.map(o));let l=Reflect.get(e,s,r);return typeof l=="function"?l.bind(e):l}})};i.__wrapped=true,this.db.prepare=i;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(t,i){let n=i||this.getTableNameFor(t.slug),a=["id TEXT PRIMARY KEY"];for(let s of c(t.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&a.push(r);}let o=c(t.fields);o.some(s=>s.name==="createdAt")||a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="updatedAt")||a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="status")||a.push("status TEXT DEFAULT 'draft'"),o.some(s=>s.name==="hasDraft")||a.push("hasDraft INTEGER DEFAULT 0"),t.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let e=R(this.db,n);if(e.length===0){let s=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let r of c(t.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${r.name} ON ${n}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${r.name}_unique ON ${n}(${this.col(r.name)})`);}else {let s=new Set(e);for(let r of a){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!s.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
|
|
4
|
+
id TEXT PRIMARY KEY,
|
|
5
|
+
collection_slug TEXT NOT NULL,
|
|
6
|
+
document_id TEXT NOT NULL,
|
|
7
|
+
tenant_id TEXT,
|
|
8
|
+
version INTEGER NOT NULL,
|
|
9
|
+
status TEXT NOT NULL DEFAULT 'draft',
|
|
10
|
+
autosave INTEGER NOT NULL DEFAULT 0,
|
|
11
|
+
data TEXT NOT NULL,
|
|
12
|
+
created_by TEXT,
|
|
13
|
+
change_description TEXT,
|
|
14
|
+
published_at TEXT,
|
|
15
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
16
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
17
|
+
)
|
|
18
|
+
`);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(t,i){let n=i.replace(/^-/,""),a=R(this.db,t);if(!a.includes(n)){if(n==="created_at"&&a.includes("createdAt"))return '"createdAt"';if(n==="createdAt"&&a.includes("created_at"))return '"created_at"';if(n==="updated_at"&&a.includes("updatedAt"))return '"updatedAt"';if(n==="updatedAt"&&a.includes("updated_at"))return '"updated_at"'}return this.col(n)}col(t){return `"${t}"`}fieldToSQL(t){switch(t.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(t.name)+" TEXT";case "number":return this.col(t.name)+" REAL";case "checkbox":return this.col(t.name)+" INTEGER DEFAULT 0";case "date":return this.col(t.name)+" TEXT";case "select":case "radio":return this.col(t.name)+" TEXT";case "relationship":case "upload":case "image":return this.col(t.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(t.name)+" TEXT";default:return null}}parseGlobalsSlug(t){if(t.startsWith("_globals_")){let i=t.replace("_globals_","");return {isGlobal:true,globalSlug:i,tableName:`global_${i.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(t)}}buildWhere(t,i){let n=[],a=[];for(let[o,e]of Object.entries(t)){let s=o.toUpperCase();if((s==="AND"||s==="OR")&&Array.isArray(e)){let l=[];for(let c of e)if(typeof c=="object"&&c!==null){let d=this.buildWhere(c,i);d.clause&&(l.push(`(${d.clause})`),a.push(...d.params));}l.length>0&&n.push(`(${l.join(` ${s} `)})`);continue}let r=this.resolveCol(i,o);typeof e=="object"&&e!==null&&!Array.isArray(e)?(e.equals!==void 0&&(n.push(`${r} = ?`),a.push(e.equals)),e.not_equals!==void 0&&(n.push(`${r} != ?`),a.push(e.not_equals)),e.in!==void 0&&Array.isArray(e.in)&&(e.in.length===0?n.push("1 = 0"):(n.push(`${r} IN (${e.in.map(()=>"?").join(", ")})`),a.push(...e.in))),e.contains!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(`%${e.contains}%`)),e.like!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(e.like)),e.greater_than!==void 0&&(n.push(`${r} > ?`),a.push(e.greater_than)),e.greater_than_equal!==void 0&&(n.push(`${r} >= ?`),a.push(e.greater_than_equal)),e.less_than!==void 0&&(n.push(`${r} < ?`),a.push(e.less_than)),e.less_than_equal!==void 0&&(n.push(`${r} <= ?`),a.push(e.less_than_equal))):e!==void 0&&(n.push(`${r} = ?`),a.push(e));}return {clause:n.join(" AND "),params:a}}async find(t){let{collection:i,where:n={},sort:a,limit:o=10,page:e=1,tenantId:s,select:r,draft:l=false}=t,c=this.parseGlobalsSlug(i),d$1=c.isGlobal?this.globals.get(c.globalSlug):this.getCollection(i);this.ensureTable(d$1,c.tableName);let m=c.tableName,h=`SELECT * FROM ${m}`,f=[],u=[],y={...n};this.tenantContext&&d$1.tenantScoped&&(y=c$1({where:y},i,this.tenantContext,b).where||{});let b$1=d$1.fields.find(p=>p.name==="status"),g=b$1?.type==="select"&&Array.isArray(b$1.options)&&b$1.options.some(p=>p.value==="published");if(!l&&g&&(u.push("status = ?"),f.push("published")),s&&d$1.tenantScoped&&(u.push("tenant_id = ?"),f.push(s)),y&&Object.keys(y).length>0){let p=this.buildWhere(y,m);p.clause&&(u.push(`(${p.clause})`),f.push(...p.params));}u.length>0&&(h+=` WHERE ${u.join(" AND ")}`);let O=a||"-createdAt",j=this.resolveCol(m,O),M=O.startsWith("-")?"DESC":"ASC";h+=` ORDER BY ${j} ${M}`;let V=h.replace("SELECT *","SELECT COUNT(*) as count"),A=this.db.prepare(V).get(...f)?.count||0;h+=" LIMIT ? OFFSET ?",f.push(o,(e-1)*o);let E=this.db.prepare(h).all(...f).map(p=>this.rowToDoc(p,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(E=E.filter(p=>d(p,i,this.tenantContext,b))),l&&(E=await Promise.all(E.map(async p=>{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(i,p.id);if(S){let X=S.data?JSON.parse(S.data):{};return a$1({...p,...X,status:p.status,_hasUnpublishedChanges:S.status==="draft"})}return p}))),E=E.map(p=>a$1(p)),{docs:E,totalDocs:A,limit:o,totalPages:Math.ceil(A/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(A/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(A/o)?e+1:null}}async findByID(t){let{collection:i,id:n,tenantId:a,draft:o=false}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let l=`SELECT * FROM ${e.tableName} WHERE id = ?`,c=[n];if(this.tenantContext&&s.tenantScoped){let u={id:n,tenant_id:this.tenantContext.tenantId};if(!d(u,i,this.tenantContext,b))return null}let d$1=s.fields.find(u=>u.name==="status"),m=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(u=>u.value==="published");!o&&m&&(l+=" AND status = ?",c.push("published")),a&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a));let h=this.db.prepare(l).get(...c);if(!h)return null;let f=this.rowToDoc(h,s);if(o){let u=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(i,f.id);if(u){let y=u.data?JSON.parse(u.data):{};f={...f,...y,status:f.status,_hasUnpublishedChanges:u.status==="draft"};}}return a$1(f)}async create(t){let{collection:i,data:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName);let s=o.tableName,r=o.isGlobal?o.globalSlug:n.id||this.generateId(),l=this.prepareData(n,e);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,a&&e.tenantScoped&&(l.tenant_id=a);let d=Object.keys(l),m=R(this.db,s),h={};for(let g of d)m.includes(g)&&(h[g]=l[g]);let f=Object.keys(h),u=f.map(g=>this.col(g)),y=f.map(()=>"?").join(", "),b=Object.values(h).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${u.join(", ")}) VALUES (${y})`).run(...b),this.ensureVersionsTable(),this.findByID({collection:i,id:r,tenantId:a,draft:true})}async update(t){let{collection:i,id:n,data:a,tenantId:o}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let r=e.tableName,l=this.prepareData(a,s);l.updated_at=new Date().toISOString();let c=R(this.db,r),d={};for(let b of Object.keys(l))c.includes(b)&&(d[b]=l[b]);let h=Object.keys(d).map(b=>`${this.col(b)} = ?`).join(", "),f=Object.values(d).map(b=>b!==null&&typeof b=="object"?JSON.stringify(b):b),u=`UPDATE ${r} SET ${h} WHERE id = ?`,y=[...f,n];return o&&s.tenantScoped&&(u+=" AND tenant_id = ?",y.push(o)),this.db.prepare(u).run(...y),this.ensureVersionsTable(),this.findByID({collection:i,id:n,tenantId:o,draft:true})}async delete(t){let{collection:i,id:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:i,id:n,tenantId:a,draft:true});if(!s)throw new Error(`Document not found: ${i}/${n}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[n];return a&&e.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a)),this.db.prepare(l).run(...c),s}async count(t){let{collection:i,tenantId:n}=t,a=this.parseGlobalsSlug(i),o=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(i);this.ensureTable(o,a.tableName);let e=a.tableName,s=`SELECT COUNT(*) as count FROM ${e}`,r=[],l=[];if(n&&o.tenantScoped&&(r.push("tenant_id = ?"),l.push(n)),t.where&&Object.keys(t.where).length>0){let d=this.buildWhere(t.where,e);d.clause&&(r.push(`(${d.clause})`),l.push(...d.params));}return r.length>0&&(s+=` WHERE ${r.join(" AND ")}`),this.db.prepare(s).get(...l)?.count||0}async findOne(t){let i=this.parseGlobalsSlug(t.collection);if(i.isGlobal){let a=this.globals.get(i.globalSlug);if(!a)throw new Error(`Global "${i.globalSlug}" not found in adapter`);this.ensureTable(a,i.tableName);let o=`SELECT * FROM ${i.tableName}`,e=[],s=[],r=a.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!t.draft&&a.versions&&l&&e.push("status = 'published'"),e.length>0&&(o+=` WHERE ${e.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...s);if(c){let d=this.rowToDoc(c,a);if(t.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(t.collection,i.globalSlug);if(m){let h=m.data?JSON.parse(m.data):{};d={...d,...h,status:d.status,_hasUnpublishedChanges:m.status==="draft"};}}return d}return null}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,tenantId:a,limit:o=20,page:e=1}=t,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[i,n];a?(s.push("tenant_id = ?"),r.push(a)):s.push("tenant_id IS NULL");let l=`WHERE ${s.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,m=(e-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,m).map(u=>this.rowToVersion(u)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(d/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(d/o)?e+1:null}}async findVersionByID(t){this.ensureVersionsTable();let i=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(t.versionId,t.collection);return i?this.rowToVersion(i):null}async createVersion(t){this.ensureVersionsTable();let i=new Date().toISOString();if(t.autosave){let s=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[t.collection,t.documentId];t.tenantId?(s+=" AND tenant_id = ?",r.push(t.tenantId)):s+=" AND tenant_id IS NULL",s+=" LIMIT 1";let l=this.db.prepare(s).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(t.data),t.status,i,l.id);let c=await this.findVersionByID({collection:t.collection,versionId:l.id});if(c)return c}}let n=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(t.collection,t.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
|
|
19
|
+
id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
|
|
20
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,t.collection,t.documentId,t.tenantId??null,o,t.status,t.autosave?1:0,JSON.stringify(t.data),t.createdBy??null,t.changeDescription??null,t.status==="published"?i:null,i,i),!t.autosave){let r=this.collections.get(t.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:r,tenantId:t.tenantId});}return await this.findVersionByID({collection:t.collection,versionId:n})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,keepLatest:a,tenantId:o}=t;if(a&&a>0){let e=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(i,n),s=0,r=[];for(let l of e)l.status==="published"||l.autosave===1||(s++,s>a&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let e=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,s=[i,n];o&&(e+=" AND tenant_id = ?",s.push(o)),this.db.prepare(e).run(...s);}}rowToVersion(t){return {id:String(t.id),collection:t.collection_slug,documentId:t.document_id,version:t.version,status:t.status,data:t.data?JSON.parse(t.data):{},createdBy:t.created_by??void 0,changeDescription:t.change_description??void 0,publishedAt:t.published_at??null,createdAt:t.created_at,updatedAt:t.updated_at}}prepareData(t,i){let n={},a=c(i.fields),o=(e,s)=>{let r=e;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return s!=null?JSON.stringify(s):null;if(r.type==="checkbox")return s?1:0;if(r.type==="number")return s!==null&&s!==""?Number(s):null;if(r.type==="upload"||r.type==="image"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify(s):String(s)}else if(e.type==="relationship"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:e.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify({relationTo:e.relationTo,value:s.id||s}):String(s)}return s};for(let e of a){if(!e.name||e.name==="id"||i.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===e.name))))continue;let r=t[e.name];r!==void 0&&(n[e.name]=o(e,r));}for(let e of i.fields)if(e.type==="tabs"&&"tabs"in e&&e.name){let s=t[e.name];if(s&&typeof s=="object"){for(let r of e.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=s[l.name];c!==void 0&&(n[l.name]=o(l,c));}}}return n}rowToDoc(t,i){let n={id:t.id};for(let a of c(i.fields)){if(!a.name||a.name==="id")continue;let o=a,e=t[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{e=e?JSON.parse(e):null;}catch{e=null;}if(o.type==="blocks"&&e&&Array.isArray(e)){let s=o.blocks||[];e=d$1(e,s);}if(a.type==="checkbox"&&(e=!!e),a.type==="date"&&e)try{let s=new Date(e);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${a.name}":`,e),e=null):e=s.toISOString();}catch{e=null;}if((a.type==="upload"||a.type==="image")&&e)try{let s=JSON.parse(e);Array.isArray(s)?e=s.map(r=>typeof r=="object"&&r!==null?r:{id:r}):e=typeof s=="object"?s:{id:s};}catch{e={id:e};}if(a.type==="relationship"&&e)try{let s=JSON.parse(e);Array.isArray(s),e=s;}catch{e={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:e};}n[a.name]=e;}for(let a of i.fields)if(!(!a.name||a.name==="id"||a.name==="row"||a.name==="collapsible")&&a.type==="tabs"&&"tabs"in a){let o={};for(let e of a.tabs)for(let s of e.fields)s.name&&s.name!=="id"&&(o[s.name]=w(t,s));n[a.name]=o;}if(i.timestamps){let a=t.createdAt||t.created_at,o=t.updatedAt||t.updated_at;if(a)try{let e=new Date(a);isNaN(e.getTime())||(n.createdAt=e.toISOString());}catch{}if(o)try{let e=new Date(o);isNaN(e.getTime())||(n.updatedAt=e.toISOString());}catch{}}i.tenantScoped&&(n.tenantId=t.tenant_id),n.status=t.status??"published",n.hasDraft=t.hasDraft?!!t.hasDraft:false;for(let a of Object.keys(n))/^\d+$/.test(a)&&delete n[a];return n}generateId(){let t=Date.now().toString(16).padStart(12,"0"),i=randomBytes(6).toString("hex");return t+i}getMediaById(t){try{let i=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${i} WHERE id = ?`).get(t);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.url}}catch{}return null}getTableNameFor(t){return t.replace(/-/g,"_")}async migrate(){for(let t of this.collections.values())this.ensureTable(t);}async rollback(){}async transaction(t){return new Promise((i,n)=>{let a=this.db.transaction(async()=>t({db:this.db}));try{let o=a();i(o);}catch(o){n(o);}})}getDatabase(){return this.db}exec(t){this.db.exec(t);}prepare(t){return this.db.prepare(t)}};function B(T){return new I(T||{})}export{I as a,B as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
function t(){return {name:"seo",type:"group",label:"SEO Settings",fields:[{name:"metaTitle",type:"text",label:"Meta Title",admin:{description:"The title used for search engines (recommended < 60 chars). Leave empty for AI auto-generation."}},{name:"metaDescription",type:"textarea",label:"Meta Description",admin:{description:"A brief summary for search engines (recommended < 160 chars). Leave empty for AI auto-generation."}},{name:"keywords",type:"text",label:"Keywords",admin:{description:"Comma-separated list of keywords for this page."}},{name:"ogImage",type:"upload",label:"OpenGraph Image",relationTo:"media",admin:{description:"The image shown when the post is shared on social media (Facebook, LinkedIn)."}},{name:"twitter",type:"group",label:"Twitter Card",fields:[{name:"title",type:"text",label:"Twitter Title"},{name:"description",type:"textarea",label:"Twitter Description"},{name:"image",type:"upload",label:"Twitter Image",relationTo:"media"}]},{name:"advanced",type:"group",label:"Advanced Search Settings",fields:[{name:"noindex",type:"checkbox",label:"Hide from search engines (noindex)",defaultValue:false},{name:"nofollow",type:"checkbox",label:"Do not follow links (nofollow)",defaultValue:false},{name:"canonicalUrl",type:"text",label:"Canonical URL Override",admin:{description:"Leave empty to use the default canonical URL."}},{name:"structuredData",type:"code",label:"JSON-LD Structured Data",admin:{description:"Custom JSON-LD schema for this specific page."}}]}]}}export{t as a};
|