@kyro-cms/core 0.13.5 → 0.13.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (325) hide show
  1. package/dist/api-handler-graphql.cjs +1 -1
  2. package/dist/api-handler-graphql.js +2 -2
  3. package/dist/api-handler-trpc.cjs +1 -1
  4. package/dist/api-handler-trpc.js +2 -2
  5. package/dist/api-handler.cjs +1 -1
  6. package/dist/api-handler.js +1 -1
  7. package/dist/auth-session-4WJUKESW.js +1 -0
  8. package/dist/auth-session-VHUHDBCL.cjs +1 -0
  9. package/dist/bootstrap-JYAUQ52D.cjs +1 -0
  10. package/dist/bootstrap-TTMLNQM3.js +1 -0
  11. package/dist/chunk-23RSKVJP.cjs +1 -0
  12. package/dist/chunk-24W5I6SJ.cjs +2 -0
  13. package/dist/{chunk-CH4TZZI5.js → chunk-2I2AXTKY.cjs} +38 -39
  14. package/dist/chunk-34LCWI5X.cjs +1 -0
  15. package/dist/chunk-3A5UO6OQ.cjs +114 -0
  16. package/dist/chunk-3N34WXBS.js +2 -0
  17. package/dist/chunk-3RIGRHON.js +109 -0
  18. package/dist/chunk-5BUAWCU6.js +91 -0
  19. package/dist/{chunk-7NKNSRCB.cjs → chunk-5I3BM5TV.js} +33 -32
  20. package/dist/chunk-5RBGM5N5.js +3 -0
  21. package/dist/chunk-7EY3GXRA.js +2 -0
  22. package/dist/chunk-7KTPBTH5.cjs +1 -0
  23. package/dist/chunk-A7763NCF.cjs +19 -0
  24. package/dist/chunk-AQWTJGML.cjs +1 -0
  25. package/dist/chunk-DCFOVCJX.cjs +1 -0
  26. package/dist/chunk-DCKJT247.cjs +1 -0
  27. package/dist/chunk-EG4SRTYS.cjs +2 -0
  28. package/dist/chunk-FAG2645P.js +2 -0
  29. package/dist/chunk-FIVTKI25.cjs +3 -0
  30. package/dist/chunk-FU76HURF.cjs +1 -0
  31. package/dist/chunk-GS4CMYKS.cjs +1 -0
  32. package/dist/chunk-GTAKGVUY.js +2 -0
  33. package/dist/chunk-GWUHIIPO.cjs +132 -0
  34. package/dist/chunk-H2IJDTA2.cjs +1 -0
  35. package/dist/chunk-HCM2G674.cjs +20 -0
  36. package/dist/chunk-I22MSXGL.js +2 -0
  37. package/dist/chunk-IIPSXKNV.js +115 -0
  38. package/dist/{chunk-WNU76M2C.js → chunk-IIVBEZC2.js} +6 -6
  39. package/dist/chunk-JHFD3IAU.cjs +1 -0
  40. package/dist/chunk-JJY2F6NL.cjs +3 -0
  41. package/dist/chunk-JQ4V2MGJ.cjs +2 -0
  42. package/dist/chunk-JXJTFBHG.js +3 -0
  43. package/dist/chunk-KOSR7235.cjs +1 -0
  44. package/dist/chunk-KUY4QDAL.js +2 -0
  45. package/dist/chunk-LGUHXOEW.js +3 -0
  46. package/dist/chunk-LXTVMP5F.cjs +6 -0
  47. package/dist/chunk-MCK2QRAU.cjs +4 -0
  48. package/dist/chunk-N2BMGZIX.cjs +90 -0
  49. package/dist/chunk-N7CDHWQH.cjs +2 -0
  50. package/dist/chunk-NGNXOXI5.js +2 -0
  51. package/dist/chunk-O2SA56P2.cjs +108 -0
  52. package/dist/chunk-O4PPZOVI.cjs +1 -0
  53. package/dist/chunk-O4RKZQYQ.js +2 -0
  54. package/dist/chunk-O6I26T6A.js +3 -0
  55. package/dist/chunk-OJBL4CXK.cjs +2 -0
  56. package/dist/chunk-OPKZYQV7.js +3 -0
  57. package/dist/chunk-OXEJCIOA.cjs +1 -0
  58. package/dist/chunk-OXH6CANN.js +2 -0
  59. package/dist/chunk-PPGZHOYR.cjs +1 -0
  60. package/dist/{chunk-EQN3HDES.cjs → chunk-PW6Y5MQL.cjs} +5 -5
  61. package/dist/chunk-RLW6AQF2.js +2 -0
  62. package/dist/chunk-SBFVITY2.js +7 -0
  63. package/dist/chunk-SEJ7LMYY.js +4 -0
  64. package/dist/chunk-SYE3OS5T.js +5 -0
  65. package/dist/chunk-SZY25KAE.js +21 -0
  66. package/dist/chunk-TJ6N5ZPZ.js +133 -0
  67. package/dist/chunk-TVWHTVLI.js +2 -0
  68. package/dist/chunk-UE7DTBD7.cjs +1 -0
  69. package/dist/chunk-V2RMDMWN.js +2 -0
  70. package/dist/chunk-V4SR7DU5.js +3 -0
  71. package/dist/chunk-VLFM66BZ.js +4 -0
  72. package/dist/chunk-VPBGZW4P.cjs +1 -0
  73. package/dist/chunk-W5GDZG64.js +2 -0
  74. package/dist/chunk-WLSVS3NC.js +2 -0
  75. package/dist/chunk-XL64URKD.cjs +2 -0
  76. package/dist/chunk-YNBJGPIU.js +2 -0
  77. package/dist/chunk-YNSKDTFG.js +2 -0
  78. package/dist/chunk-YOJOVQIH.cjs +1 -0
  79. package/dist/chunk-ZE2X3FBU.js +20 -0
  80. package/dist/chunk-ZMH35QYG.js +2 -0
  81. package/dist/cli/index.cjs +53 -182
  82. package/dist/cli/index.js +54 -183
  83. package/dist/drizzle/index.cjs +1 -1
  84. package/dist/drizzle/index.js +1 -1
  85. package/dist/fields/index.cjs +1 -1
  86. package/dist/fields/index.js +1 -1
  87. package/dist/graphql/index.cjs +1 -1
  88. package/dist/graphql/index.js +1 -1
  89. package/dist/index-B_39z2jP.d.cts +217 -0
  90. package/dist/index-xqpVL2Zq.d.ts +217 -0
  91. package/dist/index.cjs +30 -30
  92. package/dist/index.d.cts +2 -31
  93. package/dist/index.d.ts +2 -31
  94. package/dist/index.js +31 -31
  95. package/dist/integration.cjs +1 -1
  96. package/dist/integration.js +1 -1
  97. package/dist/local-DKP43BWQ.cjs +1 -0
  98. package/dist/local-TF5ZMHWW.js +1 -0
  99. package/dist/media-M3EIZ4QS.cjs +1 -0
  100. package/dist/media-WYEILC6K.js +1 -0
  101. package/dist/mongo-auth-adapter-22MV3TI3.cjs +1 -0
  102. package/dist/mongo-auth-adapter-66PWVRZW.js +1 -0
  103. package/dist/mongodb/index.cjs +1 -1
  104. package/dist/mongodb/index.d.cts +3 -130
  105. package/dist/mongodb/index.d.ts +3 -130
  106. package/dist/mongodb/index.js +1 -1
  107. package/dist/nodemailer-transport-7F3VLLBW.js +1 -0
  108. package/dist/nodemailer-transport-WAPZD3SJ.cjs +1 -0
  109. package/dist/postgres-auth-adapter-7BCPXNBO.js +1 -0
  110. package/dist/postgres-auth-adapter-HMXFUM5W.cjs +1 -0
  111. package/dist/redis-adapter-2E5AWMMA.cjs +1 -0
  112. package/dist/redis-adapter-GFH74CF4.js +1 -0
  113. package/dist/rest/index.cjs +1 -1
  114. package/dist/rest/index.js +1 -1
  115. package/dist/schema-FNIDQKIJ.cjs +1 -0
  116. package/dist/schema-KD736QFN.js +1 -0
  117. package/dist/sqlite-adapter-HL53RLSN.cjs +1 -0
  118. package/dist/sqlite-adapter-TT6ZASDG.js +1 -0
  119. package/dist/templates/index.cjs +1 -1
  120. package/dist/templates/index.js +1 -1
  121. package/dist/trpc/index.cjs +1 -1
  122. package/dist/trpc/index.js +1 -1
  123. package/dist/ws/index.cjs +1 -1
  124. package/dist/ws/index.js +1 -1
  125. package/package.json +2 -10
  126. package/dist/WebhookService-CGxHtw7E.d.cts +0 -143
  127. package/dist/WebhookService-CNC1lYz7.d.ts +0 -143
  128. package/dist/auth-session-DHVGXHOH.cjs +0 -1
  129. package/dist/auth-session-O7IIH7EP.js +0 -1
  130. package/dist/base-A9AJPCG5.d.ts +0 -219
  131. package/dist/base-C6wyX2nC.d.cts +0 -219
  132. package/dist/bcryptjs-WIQSWJGK.cjs +0 -1
  133. package/dist/bcryptjs-ZEEHSMAG.js +0 -2
  134. package/dist/better-sqlite3-5IISPX34.cjs +0 -1
  135. package/dist/better-sqlite3-B34RIU4C.js +0 -2
  136. package/dist/bootstrap-PG2LGDLB.js +0 -1
  137. package/dist/bootstrap-YD3GLTWX.cjs +0 -1
  138. package/dist/bowser-SB3ZUPO4.js +0 -11
  139. package/dist/bowser-VX6B6ZSE.cjs +0 -10
  140. package/dist/chokidar-5RVQZVHP.cjs +0 -5
  141. package/dist/chokidar-BOYGRT4Q.js +0 -6
  142. package/dist/chunk-262YP5XA.cjs +0 -1
  143. package/dist/chunk-2HA6EKXX.js +0 -24
  144. package/dist/chunk-2SPWRQ5O.js +0 -122
  145. package/dist/chunk-2TYITUOC.js +0 -122
  146. package/dist/chunk-35PGCW3S.cjs +0 -1
  147. package/dist/chunk-3CIMGC2F.cjs +0 -56
  148. package/dist/chunk-3KZXF4US.js +0 -2
  149. package/dist/chunk-3NSZZCOJ.js +0 -2
  150. package/dist/chunk-3TAUNYEM.js +0 -8
  151. package/dist/chunk-3VXEK5ZW.cjs +0 -1
  152. package/dist/chunk-47CXBWMA.js +0 -2
  153. package/dist/chunk-4BMWWGJN.js +0 -384
  154. package/dist/chunk-4NTIK6DF.cjs +0 -2
  155. package/dist/chunk-6E44MQQ5.js +0 -115
  156. package/dist/chunk-6LWF5MPL.js +0 -20
  157. package/dist/chunk-6NBZDW53.js +0 -133
  158. package/dist/chunk-6TPICJ2L.js +0 -7
  159. package/dist/chunk-6YS6XLOD.cjs +0 -121
  160. package/dist/chunk-73D2PNHD.cjs +0 -7
  161. package/dist/chunk-7ACHOBWY.cjs +0 -13
  162. package/dist/chunk-7GGZA5YU.cjs +0 -2
  163. package/dist/chunk-7JWQ2PZP.cjs +0 -1
  164. package/dist/chunk-7KLEANTO.cjs +0 -1
  165. package/dist/chunk-7MNDQU6K.js +0 -8
  166. package/dist/chunk-7NH7H3WA.js +0 -10
  167. package/dist/chunk-7WMMKGEO.cjs +0 -1
  168. package/dist/chunk-ALTU3FDG.js +0 -2
  169. package/dist/chunk-BAVN7VDR.cjs +0 -1
  170. package/dist/chunk-BCEE4NBZ.cjs +0 -2
  171. package/dist/chunk-BUNLC3II.cjs +0 -1
  172. package/dist/chunk-C7QCZX7X.js +0 -2
  173. package/dist/chunk-D6SDGHY6.js +0 -2
  174. package/dist/chunk-DVWYO3KK.cjs +0 -1
  175. package/dist/chunk-EHWUALGH.cjs +0 -1
  176. package/dist/chunk-EML5FDUU.js +0 -2
  177. package/dist/chunk-EN65ZEK2.cjs +0 -2
  178. package/dist/chunk-EW424IBO.cjs +0 -1
  179. package/dist/chunk-EZIDQBXI.cjs +0 -1
  180. package/dist/chunk-F2O4QO5N.cjs +0 -383
  181. package/dist/chunk-F4ITQ6XQ.cjs +0 -3
  182. package/dist/chunk-FK2BG4HU.js +0 -3
  183. package/dist/chunk-FLMUMPDE.js +0 -2
  184. package/dist/chunk-GIS6X43A.cjs +0 -3
  185. package/dist/chunk-GNEVCEJU.cjs +0 -3
  186. package/dist/chunk-GNOSG3PK.cjs +0 -1
  187. package/dist/chunk-GQGFNTDZ.js +0 -2
  188. package/dist/chunk-GTR7JAKP.cjs +0 -3
  189. package/dist/chunk-HPIJI7TM.js +0 -3
  190. package/dist/chunk-HPYH7GTS.cjs +0 -1
  191. package/dist/chunk-HRAY65XH.js +0 -3
  192. package/dist/chunk-HTYVI2HK.cjs +0 -9
  193. package/dist/chunk-IKGVPXMK.js +0 -3
  194. package/dist/chunk-J6V573PE.cjs +0 -1
  195. package/dist/chunk-JA44K75G.js +0 -2
  196. package/dist/chunk-JRUQ5ABB.js +0 -4
  197. package/dist/chunk-JV4HJBXW.js +0 -14
  198. package/dist/chunk-KEITOXIP.js +0 -2
  199. package/dist/chunk-KMFLHGD5.cjs +0 -1
  200. package/dist/chunk-KZHXYXSH.cjs +0 -10
  201. package/dist/chunk-L3Q64RUX.js +0 -3
  202. package/dist/chunk-LEBM6ZSZ.cjs +0 -10
  203. package/dist/chunk-LKRI5X2V.cjs +0 -1
  204. package/dist/chunk-LQ3YZTPU.cjs +0 -15
  205. package/dist/chunk-LVBHOZZF.js +0 -4
  206. package/dist/chunk-LWM4WABU.js +0 -3
  207. package/dist/chunk-LY7N3UHH.cjs +0 -23
  208. package/dist/chunk-MCIZG4A3.cjs +0 -1
  209. package/dist/chunk-MDLJTZLV.cjs +0 -1
  210. package/dist/chunk-N4FXLQE3.cjs +0 -132
  211. package/dist/chunk-N5POANYV.js +0 -2
  212. package/dist/chunk-NGNJSUGL.cjs +0 -1
  213. package/dist/chunk-NRE6VKL6.cjs +0 -121
  214. package/dist/chunk-O4YE57OS.cjs +0 -6
  215. package/dist/chunk-OBYAIJVU.js +0 -11
  216. package/dist/chunk-OLRCZ6E3.js +0 -2
  217. package/dist/chunk-OOVNTOZC.cjs +0 -56
  218. package/dist/chunk-P6JITOFF.js +0 -4
  219. package/dist/chunk-PITMDQYN.cjs +0 -18
  220. package/dist/chunk-PYUWSKKP.js +0 -57
  221. package/dist/chunk-Q5TFO66G.cjs +0 -1
  222. package/dist/chunk-QO5ZWQA3.cjs +0 -74
  223. package/dist/chunk-QYN6C3FZ.cjs +0 -114
  224. package/dist/chunk-REQ622YC.js +0 -3
  225. package/dist/chunk-RPRGGGIW.js +0 -11
  226. package/dist/chunk-RVBSJ4UQ.cjs +0 -7
  227. package/dist/chunk-RYHOWZLK.js +0 -2
  228. package/dist/chunk-RYXLEFS5.js +0 -2
  229. package/dist/chunk-SBNMXQNO.cjs +0 -2
  230. package/dist/chunk-SLMIYECU.js +0 -2
  231. package/dist/chunk-SRIXRJHL.js +0 -4
  232. package/dist/chunk-TBHNE4VV.js +0 -2
  233. package/dist/chunk-TCFL3UWT.cjs +0 -2
  234. package/dist/chunk-TYQYKKWJ.js +0 -16
  235. package/dist/chunk-U6KFONKM.js +0 -2
  236. package/dist/chunk-UNYXWPLZ.cjs +0 -2
  237. package/dist/chunk-UWHWSWDE.js +0 -2
  238. package/dist/chunk-V4FAL7AG.js +0 -2
  239. package/dist/chunk-VQ53TFYA.cjs +0 -1
  240. package/dist/chunk-VRZC4TTF.cjs +0 -1
  241. package/dist/chunk-W45TLOOT.js +0 -2
  242. package/dist/chunk-WAVGRSE6.js +0 -2
  243. package/dist/chunk-WPM6LFCY.js +0 -2
  244. package/dist/chunk-WXT2XW7T.js +0 -13
  245. package/dist/chunk-X473JI7Z.js +0 -75
  246. package/dist/chunk-X6HUA6EF.cjs +0 -20
  247. package/dist/chunk-XDPLVJRO.js +0 -21
  248. package/dist/chunk-XDQVYCIR.cjs +0 -1
  249. package/dist/chunk-XFYSADHV.cjs +0 -2
  250. package/dist/chunk-XOR64WUQ.cjs +0 -19
  251. package/dist/chunk-Y2YAKDEQ.js +0 -2
  252. package/dist/chunk-YENNL5HG.js +0 -2
  253. package/dist/chunk-YGI5W4RS.js +0 -2
  254. package/dist/chunk-YIFKTA5N.js +0 -57
  255. package/dist/chunk-YUUXFD73.js +0 -19
  256. package/dist/chunk-ZAKYTBEN.js +0 -3
  257. package/dist/chunk-ZHA446FA.cjs +0 -1
  258. package/dist/chunk-ZTLGK6R4.cjs +0 -12
  259. package/dist/chunk-ZUBJ6RLQ.cjs +0 -1
  260. package/dist/client.d.cts +0 -1291
  261. package/dist/client.d.ts +0 -1291
  262. package/dist/d1-5ZQJOFDX.cjs +0 -1
  263. package/dist/d1-HPB6B253.js +0 -2
  264. package/dist/dist-es-3SSNUZST.cjs +0 -1
  265. package/dist/dist-es-64F22JL2.js +0 -2
  266. package/dist/dist-es-A5OF2STN.cjs +0 -2
  267. package/dist/dist-es-BOW5V247.cjs +0 -6
  268. package/dist/dist-es-CRIMATLL.cjs +0 -2
  269. package/dist/dist-es-DL3VLVP6.cjs +0 -1
  270. package/dist/dist-es-F2ZR55UK.js +0 -4
  271. package/dist/dist-es-IPSSZNFP.js +0 -1
  272. package/dist/dist-es-M2F7M27Y.js +0 -2
  273. package/dist/dist-es-M66JKZF5.js +0 -7
  274. package/dist/dist-es-OKLLRYI3.js +0 -2
  275. package/dist/dist-es-P25IKLBI.cjs +0 -1
  276. package/dist/dist-es-SRPWSAF4.cjs +0 -1
  277. package/dist/dist-es-SVHZDVUF.js +0 -3
  278. package/dist/dist-es-T2H2W5BX.cjs +0 -3
  279. package/dist/dist-es-WFI55HKT.js +0 -3
  280. package/dist/drizzle-orm-47ELDEM6.cjs +0 -1
  281. package/dist/drizzle-orm-XRTSOQJS.js +0 -1
  282. package/dist/event-streams-7NAWZW2I.js +0 -1
  283. package/dist/event-streams-JBMWCI2O.cjs +0 -1
  284. package/dist/fs-KWBRQ6T6.js +0 -1
  285. package/dist/fs-ZQYOJOIO.cjs +0 -1
  286. package/dist/index-NGnJpSgf.d.ts +0 -105
  287. package/dist/index-Zrg3sZ6R.d.cts +0 -105
  288. package/dist/jsonwebtoken-DFB6ZBZA.cjs +0 -8
  289. package/dist/jsonwebtoken-OD67R5JS.js +0 -9
  290. package/dist/lib-A2D63VXD.cjs +0 -1
  291. package/dist/lib-JQD2JAOO.js +0 -2
  292. package/dist/loadSso-JY4WDQPS.cjs +0 -2
  293. package/dist/loadSso-UQR6545M.js +0 -3
  294. package/dist/local-6UUGBZ4M.js +0 -1
  295. package/dist/local-ZYHV3J2K.cjs +0 -1
  296. package/dist/media-3Z6YW5J4.cjs +0 -1
  297. package/dist/media-E762GEHL.js +0 -1
  298. package/dist/mongo-auth-adapter-2H2AXDRH.cjs +0 -1
  299. package/dist/mongo-auth-adapter-YWMEOC42.js +0 -1
  300. package/dist/nodemailer-IDML4L6W.cjs +0 -53
  301. package/dist/nodemailer-NITB45SS.js +0 -54
  302. package/dist/nodemailer-transport-3VWVUBM5.cjs +0 -1
  303. package/dist/nodemailer-transport-7RHATUKL.js +0 -1
  304. package/dist/postgres-auth-adapter-QKBNXVPT.js +0 -1
  305. package/dist/postgres-auth-adapter-WMLM4UUC.cjs +0 -1
  306. package/dist/postgres-js-7YBZKGXG.cjs +0 -1
  307. package/dist/postgres-js-JLFIWOBH.js +0 -1
  308. package/dist/redis-adapter-EVK2SMKH.cjs +0 -1
  309. package/dist/redis-adapter-LY2NBSAG.js +0 -1
  310. package/dist/schema-RT6WSUYC.cjs +0 -1
  311. package/dist/schema-YFMSJK2P.js +0 -2
  312. package/dist/signin-N3T2KF5Q.js +0 -3
  313. package/dist/signin-VFBLX7EL.cjs +0 -2
  314. package/dist/sqlite-adapter-KPSISY6E.cjs +0 -1
  315. package/dist/sqlite-adapter-PI6SIY7O.js +0 -1
  316. package/dist/src-6LAUXXDM.cjs +0 -1
  317. package/dist/src-QBADSZV4.js +0 -1
  318. package/dist/sso-oidc-54BIRYR6.cjs +0 -2
  319. package/dist/sso-oidc-UB7G4END.js +0 -3
  320. package/dist/sts-WAA6I22C.js +0 -3
  321. package/dist/sts-YLXXIB3X.cjs +0 -2
  322. package/dist/types-BCOhfwHC.d.ts +0 -839
  323. package/dist/types-DxaK39ix.d.cts +0 -330
  324. package/dist/types-DxaK39ix.d.ts +0 -330
  325. package/dist/types-QglJ7PwT.d.cts +0 -839
@@ -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 {J,G}from'./chunk-SYE3OS5T.js';import {e}from'./chunk-KUY4QDAL.js';import {m as m$1}from'./chunk-3RIGRHON.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-YNBJGPIU.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 @@
1
+ 'use strict';var h=require('bcryptjs'),crypto=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var h__default=/*#__PURE__*/_interopDefault(h);var p=class{db;adapter;client;prefix;sessionTTL;refreshTokenTTL;indexesEnsured=false;constructor(e){this.db=e.db,this.adapter=e.adapter,this.client=e.client,this.prefix=e.collectionPrefix||"",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}getDatabase(){let e=typeof this.db=="function"?this.db():this.db;if(!e&&this.adapter&&(this.adapter.db?e=this.adapter.db:this.adapter.client&&(this.adapter.db=this.adapter.client.db(this.adapter.database||"kyro_cms"),e=this.adapter.db)),!e&&globalThis.__KYRO_INSTANCE__?.db){let s=globalThis.__KYRO_INSTANCE__.db;s.db?e=s.db:s.client&&(s.db=s.client.db(s.database||"kyro_cms"),e=s.db);}if(!e)throw new Error("MongoDB database not initialized");return e}col(e){return this.getDatabase().collection(`${this.prefix}${e}`)}async connect(){this.adapter&&!this.adapter.connected&&await this.adapter.connect(),this.indexesEnsured||await this.ensureIndexes();}async disconnect(){if(this.client&&!this.adapter){let e=process.env.NODE_ENV==="production",s=process.env.NODE_ENV==="test"||!!process.env.VITEST;if(e||s)try{await this.client.close();}catch{}}}async ensureIndexes(){await this.col("users").createIndex({email:1},{unique:true}),await this.col("users").createIndex({tenantId:1}),await this.col("users").createIndex({role:1}),await this.col("sessions").createIndex({token:1},{unique:true}),await this.col("sessions").createIndex({refreshToken:1}),await this.col("sessions").createIndex({userId:1}),await this.col("sessions").createIndex({expiresAt:1},{expireAfterSeconds:0}),await this.col("audit_logs").createIndex({timestamp:-1}),await this.col("audit_logs").createIndex({userId:1}),await this.col("audit_logs").createIndex({action:1}),await this.col("audit_logs").createIndex({resource:1}),await this.col("password_history").createIndex({userId:1,createdAt:-1}),await this.col("lockouts").createIndex({userId:1},{unique:true}),await this.col("lockouts").createIndex({lockedUntil:1}),this.indexesEnsured=true;}async createUser(e){let s=crypto.randomUUID(),t=new Date,i=await this.hashPassword(e.password),n={_id:s,name:e.name||null,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",avatar:e.avatar||null,tenantId:e.tenantId||null,metadata:e.metadata||null,emailVerified:false,locked:false,lastLogin:null,failedLoginAttempts:0,createdAt:t,updatedAt:t};return await this.col("users").insertOne(n),this.docToAuthUser(n)}async findUserByEmail(e){let s=await this.col("users").findOne({email:e.toLowerCase()});return s?this.docToAuthUser(s):null}async findUserById(e){let s=await this.col("users").findOne({_id:e});return s?this.docToAuthUser(s):null}async updateUser(e,s){let t={updatedAt:new Date};s.name!==void 0&&(t.name=s.name),s.email!==void 0&&(t.email=s.email),s.passwordHash!==void 0&&(t.passwordHash=s.passwordHash),s.role!==void 0&&(t.role=s.role),s.avatar!==void 0&&(t.avatar=s.avatar),s.tenantId!==void 0&&(t.tenantId=s.tenantId),s.metadata!==void 0&&(t.metadata=s.metadata),s.emailVerified!==void 0&&(t.emailVerified=s.emailVerified),s.locked!==void 0&&(t.locked=s.locked),s.lastLogin!==void 0&&(t.lastLogin=s.lastLogin?new Date(s.lastLogin):null),s.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=s.failedLoginAttempts);let i=await this.col("users").findOneAndUpdate({_id:e},{$set:t},{returnDocument:"after"});return i?this.docToAuthUser(i):null}async deleteUser(e){return (await this.col("users").deleteOne({_id:e})).deletedCount>0}async verifyPassword(e,s){let t=await this.findUserByEmail(e);if(!t)return null;let i=await this.col("users").findOne({email:e.toLowerCase()},{projection:{passwordHash:1}});return i?.passwordHash&&await h__default.default.compare(s,i.passwordHash)?t:null}async hashPassword(e){return h__default.default.hash(e,12)}async createSession(e,s){let t=crypto.randomUUID(),i=crypto.randomBytes(32).toString("base64url"),n=crypto.randomBytes(32).toString("base64url"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:n,ipAddress:s?.ipAddress||null,userAgent:s?.userAgent||null,expiresAt:u,createdAt:o};return await this.col("sessions").insertOne(d),this.docToSession(d)}async findSessionByToken(e){let s=await this.col("sessions").findOne({token:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async findSessionByRefreshToken(e){let s=await this.col("sessions").findOne({refreshToken:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async deleteSession(e){return (await this.col("sessions").deleteOne({_id:e})).deletedCount>0}async deleteUserSessions(e){return (await this.col("sessions").deleteMany({userId:e})).deletedCount}async hasAnyUsers(){return await this.col("users").countDocuments()>0}async addPasswordToHistory(e,s){await this.col("password_history").insertOne({userId:e,passwordHash:s,createdAt:new Date});}async getPasswordHistory(e,s=5){return (await this.col("password_history").find({userId:e}).sort({createdAt:-1}).limit(s).toArray()).map(i=>i.passwordHash)}async isPasswordInHistory(e,s,t=5){let i=await this.getPasswordHistory(s,t);for(let n of i)if(await h__default.default.compare(e,n))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:n,resource:o,resourceId:u,success:d,startDate:c,endDate:f}=e,a={};i&&(a.userId=i),n&&(Array.isArray(n)?a.action={$in:n}:a.action=n),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(c||f)&&(a.timestamp={},c&&(a.timestamp.$gte=c),f&&(a.timestamp.$lte=f));let g=await this.col("audit_logs").countDocuments(a);return {logs:(await this.col("audit_logs").find(a).sort({timestamp:-1}).skip(t).limit(s).toArray()).map(r=>({id:r._id,timestamp:r.timestamp,action:r.action,userId:r.userId||void 0,userEmail:r.userEmail||void 0,role:r.role||void 0,resource:r.resource,resourceId:r.resourceId||void 0,changes:r.changes||void 0,ipAddress:r.ipAddress||void 0,userAgent:r.userAgent||void 0,success:r.success,error:r.error||void 0,metadata:r.metadata||void 0})),total:g}}async createAuditLog(e){let s=crypto.randomUUID(),t=new Date;return await this.col("audit_logs").insertOne({_id:s,action:e.action,userId:e.userId||null,userEmail:e.userEmail||null,role:e.role||null,resource:e.resource,resourceId:e.resourceId||null,changes:e.changes||null,ipAddress:e.ipAddress||null,userAgent:e.userAgent||null,success:e.success,error:e.error||null,metadata:e.metadata||null,timestamp:t}),{...e,id:s,timestamp:t}}docToAuthUser(e){return {id:e._id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,avatar:e.avatar||void 0,tenantId:e.tenantId||void 0,metadata:e.metadata||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?.toISOString?.()||e.lastLogin||void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:e.createdAt?.toISOString?.()||e.createdAt,updatedAt:e.updatedAt?.toISOString?.()||e.updatedAt}}docToSession(e){return {id:e._id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:e.expiresAt?.toISOString?.()||e.expiresAt,createdAt:e.createdAt?.toISOString?.()||e.createdAt,ipAddress:e.ipAddress||void 0,userAgent:e.userAgent||void 0}}async createEmailVerificationToken(e){let s=crypto.randomBytes(32).toString("hex"),t=new Date(Date.now()+1440*60*1e3),i=await import('mongodb'),n=i.ObjectId??i.default?.ObjectId;return await this.db.collection("email_verifications").insertOne({userId:new n(e),token:s,expiresAt:t,createdAt:new Date}),{token:s,expiresAt:t}}async verifyEmailToken(e){let s=await this.db.collection("email_verifications").findOne({token:e});return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.collection("users").updateOne({_id:s.userId},{$set:{emailVerified:true}}),await this.db.collection("email_verifications").deleteOne({_id:s._id}),{success:true,userId:s.userId.toString()}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=crypto.randomBytes(32).toString("hex"),i=new Date(Date.now()+3600*1e3),n=await import('mongodb'),o=n.ObjectId??n.default?.ObjectId;return await this.db.collection("password_resets").insertOne({userId:new o(s.id),token:t,expiresAt:i,createdAt:new Date}),{token:t,expiresAt:i}}async resetPasswordWithToken(e,s){let t=await this.db.collection("password_resets").findOne({token:e});if(!t)return {success:false,error:"Invalid reset token"};if(t.expiresAt<new Date)return {success:false,error:"Reset token has expired"};if(t.usedAt)return {success:false,error:"Reset token has already been used"};let i=await this.hashPassword(s);return await this.db.collection("users").updateOne({_id:t.userId},{$set:{passwordHash:i,updatedAt:new Date}}),await this.db.collection("password_resets").updateOne({_id:t._id},{$set:{usedAt:new Date}}),await this.db.collection("sessions").deleteMany({userId:t.userId}),{success:true}}};exports.a=p;
@@ -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,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
+ 'use strict';var chunkO4PPZOVI_cjs=require('./chunk-O4PPZOVI.cjs'),chunkJJY2F6NL_cjs=require('./chunk-JJY2F6NL.cjs'),chunkOXEJCIOA_cjs=require('./chunk-OXEJCIOA.cjs'),chunkJHFD3IAU_cjs=require('./chunk-JHFD3IAU.cjs'),crypto=require('crypto');function D(){let h=globalThis;return h.__KYRO_MONGO_CLIENTS__||(h.__KYRO_MONGO_CLIENTS__=new Map),h.__KYRO_MONGO_CLIENTS__}var C=class h extends chunkO4PPZOVI_cjs.a{dialect="mongodb";client;db;database;connectionString;options;constructor(o){if(super(),this.options=o||{},o.connectionString){this.connectionString=o.connectionString;try{let t=new URL(o.connectionString);this.database=o.database||t.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database=o.database||"kyro_cms";}}else this.client=o.client,this.database=o.database||"kyro_cms";}getPoolOptions(){let o=process.env.MONGODB_MAX_POOL_SIZE?parseInt(process.env.MONGODB_MAX_POOL_SIZE,10):void 0,t=process.env.MONGODB_MIN_POOL_SIZE?parseInt(process.env.MONGODB_MIN_POOL_SIZE,10):void 0,n=process.env.MONGODB_MAX_IDLE_TIME_MS?parseInt(process.env.MONGODB_MAX_IDLE_TIME_MS,10):void 0;return {maxPoolSize:this.options.maxPoolSize??o??10,minPoolSize:this.options.minPoolSize??t??1,maxIdleTimeMS:this.options.maxIdleTimeMS??n??3e4,serverSelectionTimeoutMS:this.options.serverSelectionTimeoutMS??5e3,connectTimeoutMS:this.options.connectTimeoutMS??1e4,...this.options.socketTimeoutMS?{socketTimeoutMS:this.options.socketTimeoutMS}:{},...this.options.clientOptions||{}}}async connect(){if(this.connectionString&&!this.client){let o=this.connectionString,t=!this.options.disableGlobalClientCache,n=D();if(t&&n.has(o)){let i=n.get(o);if(this.client=i.client,i.connectPromise)try{await i.connectPromise;}catch(e){throw n.delete(o),e}}else {let i;try{let r=await import('mongodb');i=r.MongoClient??r.default?.MongoClient;}catch{chunkJJY2F6NL_cjs.a(["mongodb"]);let c=await import('mongodb');i=c.MongoClient??c.default?.MongoClient;}let e=this.getPoolOptions(),s=new i(this.connectionString,e),a=s.connect();t&&n.set(o,{client:s,connectPromise:a});try{await a,this.client=s;}catch(r){throw t&&n.delete(o),r}}}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(o){if(this.client){let t=this.connectionString,n=D(),i=!this.options.disableGlobalClientCache&&t&&n.has(t),e=process.env.NODE_ENV==="production",s=process.env.NODE_ENV==="test"||!!process.env.VITEST;if(o?.force||!i||e||s){try{await this.client.close();}catch{}t&&n.delete(t);}this.connected=false;}}static async getDb(o){let t=typeof o=="string"?{connectionString:o}:o||{},n=globalThis;if(n.__KYRO_INSTANCE__?.db?.dialect==="mongodb"&&n.__KYRO_INSTANCE__.db.db)return n.__KYRO_INSTANCE__.db.db;let i=t.connectionString||process.env.MONGODB_URI;if(!i)throw new Error("[Kyro CMS] MONGODB_URI is required to get Mongo database");let e=new h({...t,connectionString:i});return await e.connect(),e.db}static async getClient(o){let t=typeof o=="string"?{connectionString:o}:o||{},n=globalThis;if(n.__KYRO_INSTANCE__?.db?.dialect==="mongodb"&&n.__KYRO_INSTANCE__.db.client)return n.__KYRO_INSTANCE__.db.client;let i=t.connectionString||process.env.MONGODB_URI;if(!i)throw new Error("[Kyro CMS] MONGODB_URI is required to get MongoClient");let e=new h({...t,connectionString:i});return await e.connect(),e.client}getMongoCollection(o){if(!this.db&&this.client&&(this.db=this.client.db(this.database),this.connected=true),!this.db)throw new Error("MongoDB not connected");return this.db.collection(o)}async find(o){let{collection:t,where:n={},sort:i,limit:e=10,page:s=1,tenantId:a,select:r,draft:c}=o,d=this.getCollectionConfig(t),f=this.getMongoCollection(t),g={...n};this.tenantContext&&d.tenantScoped&&(g=chunkO4PPZOVI_cjs.c({where:g},t,this.tenantContext,chunkO4PPZOVI_cjs.b).where||{});let u=this.buildFilter(g,d.tenantScoped?a:void 0),l=d.fields.find(p=>p.name==="status"),_=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(p=>p.value==="published");!c&&_&&(u.status="published");let y=this.parseSort(i),w={[y.field]:y.direction==="asc"?1:-1},R=(s-1)*e,[T,P]=await Promise.all([f.find(u).sort(w).skip(R).limit(e).project(this.buildProjection(r)).toArray(),f.countDocuments(u)]),b=T.map(p=>this.processResult(p,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(b=b.filter(p=>chunkO4PPZOVI_cjs.d(p,t,this.tenantContext,chunkO4PPZOVI_cjs.b))),c&&(b=await Promise.all(b.map(async p=>{let m=await this.getMongoCollection(`${t}_versions`).findOne({document_id:p.id},{sort:{createdAt:-1}});if(m){let x=typeof m.data=="string"?JSON.parse(m.data):m.data&&typeof m.data=="object"?m.data:{};return {...p,...x,status:p.status,_hasUnpublishedChanges:m.status==="draft"}}return p}))),{docs:b,...this.calculatePagination(s,e,P)}}buildIdFilter(o,t,n){let i=String(o||""),e=/^[0-9a-fA-F]{24}$/.test(i),s=[{_id:i},{id:i},{slug:i},{orderNumber:i}];if(e)try{let{ObjectId:r}=chunkJHFD3IAU_cjs.a("mongodb");s.unshift({_id:new r(i)});}catch{}let a={$or:s};return t&&n?.tenantScoped&&(a.tenantId=t),a}async findByID(o){let{collection:t,id:n,tenantId:i,draft:e}=o,s=this.getCollectionConfig(t),a=this.getMongoCollection(t);if(this.tenantContext&&s.tenantScoped){let u={_id:n,tenantId:this.tenantContext.tenantId};if(!chunkO4PPZOVI_cjs.d(u,t,this.tenantContext,chunkO4PPZOVI_cjs.b))return null}let r=this.buildIdFilter(n,i,s),c=s.fields.find(u=>u.name==="status"),d=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(u=>u.value==="published");!e&&d&&(r.status="published");let f=await a.findOne(r);if(!f)return null;let g=this.processResult(f,s);if(e){let l=await this.getMongoCollection(`${t}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(l){let _=typeof l.data=="string"?JSON.parse(l.data):l.data&&typeof l.data=="object"?l.data:{};g={...g,..._,status:g.status,_hasUnpublishedChanges:l.status==="draft"};}}return g}async create(o){let{collection:t,data:n,tenantId:i}=o,e=this.getCollectionConfig(t),s=this.getMongoCollection(t),a=this.prepareData(n,e),r=a.id||this.generateId();delete a.id;let c={...a,_id:r};return i&&e.tenantScoped&&(c.tenantId=i),await s.insertOne(c),this.processResult(c,e)}async update(o){let{collection:t,id:n,data:i,tenantId:e}=o,s=this.getCollectionConfig(t),a=this.getMongoCollection(t),r=this.buildIdFilter(n,e,s),c=this.prepareData(i,s),d=await a.findOneAndUpdate(r,{$set:c},{returnDocument:"after"});if(!d)throw new Error(`Document not found: ${t}/${n}`);return this.processResult(d,s)}async delete(o){let{collection:t,id:n,tenantId:i}=o,e=this.getCollectionConfig(t),s=this.getMongoCollection(t),a=this.buildIdFilter(n,i,e),r=await s.findOneAndDelete(a);if(!r)throw new Error(`Document not found: ${t}/${n}`);return this.processResult(r,e)}async count(o){let{collection:t,where:n={},tenantId:i}=o,e=this.getCollectionConfig(t),s=this.getMongoCollection(t),a=this.buildFilter(n,e.tenantScoped?i:void 0);return s.countDocuments(a)}async findOne(o){let{collection:t,where:n={},tenantId:i,draft:e}=o,s=this.getCollectionConfig(t),a=this.getMongoCollection(t),r=this.buildFilter(n,s.tenantScoped?i:void 0),c=s.fields.find(u=>u.name==="status"),d=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(u=>u.value==="published");!e&&d&&(r.status="published");let f=await a.findOne(r);if(!f)return null;let g=this.processResult(f,s);if(e){let l=await this.getMongoCollection(`${t}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(l){let _=typeof l.data=="string"?JSON.parse(l.data):l.data&&typeof l.data=="object"?l.data:{};g={...g,..._,status:g.status};}}return g}async findVersions(o){let{collection:t,documentId:n,sort:i,limit:e=10,page:s=1,tenantId:a}=o,r=this.getCollectionConfig(t),c=this.getMongoCollection(`${t}_versions`),d={document_id:n,autosave:{$ne:true}};a&&r.tenantScoped&&(d.tenant_id=a);let f=(s-1)*e,g=this.parseSort(i),u={[g.field]:g.direction==="asc"?1:-1},[l,_]=await Promise.all([c.find(d).sort(u).skip(f).limit(e).toArray(),c.countDocuments(d)]);return {docs:l.map(y=>this.processResult(y,{})),...this.calculatePagination(s,e,_)}}async findVersionByID(o){let{collection:t,versionId:n,tenantId:i}=o,e=this.getCollectionConfig(t),s=this.getMongoCollection(`${t}_versions`),a={_id:n};i&&e.tenantScoped&&(a.tenant_id=i);let r=await s.findOne(a);return r?this.processResult(r,{}):null}async createVersion(o){let{collection:t,documentId:n,data:i,status:e,createdBy:s,changeDescription:a,tenantId:r,autosave:c}=o,d=this.getCollectionConfig(t),f=this.getMongoCollection(`${t}_versions`);if(c){let l={document_id:n,collection_slug:t,autosave:true};r&&d.tenantScoped&&(l.tenant_id=r);let _=await f.findOne(l);if(_){let y=new Date().toISOString();return await f.updateOne({_id:_._id},{$set:{data:i,status:e,updatedAt:y}}),this.processResult({..._,data:i,status:e,updatedAt:y},{})}}let g=new Date().toISOString(),u={_id:this.generateId(),document_id:n,collection_slug:t,data:i,status:e,autosave:c===true,created_by:s,change_description:a,createdAt:g,updatedAt:g};if(r&&d.tenantScoped&&(u.tenant_id=r),await f.insertOne(u),!c){let l=this.getCollectionConfig(t);l.versions?.maxPerDoc&&await this.deleteVersions({collection:t,documentId:n,keepLatest:l.versions.maxPerDoc,tenantId:r});}return this.processResult(u,{})}async updateLatestVersion(o){return this.createVersion({...o,autosave:true})}async deleteVersions(o){let{collection:t,documentId:n,keepLatest:i,tenantId:e}=o,s=this.getCollectionConfig(t),a=this.getMongoCollection(`${t}_versions`);if(i){let r={document_id:n,autosave:{$ne:true}};e&&s.tenantScoped&&(r.tenant_id=e);let d=(await a.find(r).sort({createdAt:-1}).limit(i).project({_id:1}).toArray()).map(f=>f._id);d.length>0&&await a.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:d},...e&&s.tenantScoped?{tenant_id:e}:{}});}else {let r={document_id:n};e&&s.tenantScoped&&(r.tenant_id=e),await a.deleteMany(r);}}async migrate(){for(let o of this.collections.values()){let t=this.getMongoCollection(o.slug);await t.createIndex({_id:1}),o.tenantScoped&&await t.createIndex({tenantId:1}),o.timestamps&&await t.createIndex({createdAt:-1});for(let n of o.fields)n.unique&&n.name&&await t.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await t.createIndex({[n.name]:1});}}getCollectionConfig(o){if(o.startsWith("_globals_")){let n=o.replace("_globals_",""),i=this.globals.get(n);if(!i)throw new Error(`Global "${n}" not found`);return i}let t=this.collections.get(o);if(!t)throw new Error(`Collection "${o}" not found`);return t}buildFilter(o={},t){let n={};t&&(n.tenantId=t);for(let[i,e]of Object.entries(o))if(i==="AND"&&Array.isArray(e)){let s=e.map(a=>this.buildFilter(a));Object.assign(n,...s);}else if(i==="OR"&&Array.isArray(e))n.$or=e.map(s=>this.buildFilter(s));else if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let s={};if(e.equals!==void 0){n[i==="id"?"_id":i]=e.equals;continue}e.not_equals!==void 0&&(s.$ne=e.not_equals),e.in!==void 0&&(s.$in=e.in),e.not_in!==void 0&&(s.$nin=e.not_in),e.greater_than!==void 0&&(s.$gt=e.greater_than),e.greater_than_equal!==void 0&&(s.$gte=e.greater_than_equal),e.less_than!==void 0&&(s.$lt=e.less_than),e.less_than_equal!==void 0&&(s.$lte=e.less_than_equal),e.like!==void 0&&(s.$regex=new RegExp(e.like.replace(/%/g,".*"),"i")),e.not_like!==void 0&&(s.$not=new RegExp(e.not_like.replace(/%/g,".*"),"i")),e.contains!==void 0&&(s.$regex=new RegExp(`.*${e.contains}.*`,"i")),e.exists!==void 0&&(s.$exists=e.exists),Object.keys(s).length>0&&(n[i==="id"?"_id":i]=s);}else n[i==="id"?"_id":i]=e;return n}buildProjection(o){if(!o||o.length===0)return;let t={_id:1};for(let n of o)t[n]=1;return t}processResult(o,t){if(!o)return null;let n={...o};for(let i of Object.keys(n))/^\d+$/.test(i)&&delete n[i];return o._id&&(n.id=String(o._id),delete n._id),delete n.__v,n.createdAt&&(n.createdAt=new Date(n.createdAt).toISOString()),n.updatedAt&&(n.updatedAt=new Date(n.updatedAt).toISOString()),chunkOXEJCIOA_cjs.a(n)}generateId(){let o=Date.now().toString(16).padStart(12,"0"),t=crypto.randomBytes(6).toString("hex");return o+t}};function B(h){return new C(h)}async function F(h){return C.getDb(h)}async function V(h){return C.getClient(h)}
2
+ exports.a=C;exports.b=B;exports.c=F;exports.d=V;
@@ -0,0 +1,2 @@
1
+ import h from'bcryptjs';import {randomUUID,randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
+ var p=class{db;adapter;client;prefix;sessionTTL;refreshTokenTTL;indexesEnsured=false;constructor(e){this.db=e.db,this.adapter=e.adapter,this.client=e.client,this.prefix=e.collectionPrefix||"",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}getDatabase(){let e=typeof this.db=="function"?this.db():this.db;if(!e&&this.adapter&&(this.adapter.db?e=this.adapter.db:this.adapter.client&&(this.adapter.db=this.adapter.client.db(this.adapter.database||"kyro_cms"),e=this.adapter.db)),!e&&globalThis.__KYRO_INSTANCE__?.db){let s=globalThis.__KYRO_INSTANCE__.db;s.db?e=s.db:s.client&&(s.db=s.client.db(s.database||"kyro_cms"),e=s.db);}if(!e)throw new Error("MongoDB database not initialized");return e}col(e){return this.getDatabase().collection(`${this.prefix}${e}`)}async connect(){this.adapter&&!this.adapter.connected&&await this.adapter.connect(),this.indexesEnsured||await this.ensureIndexes();}async disconnect(){if(this.client&&!this.adapter){let e=process.env.NODE_ENV==="production",s=process.env.NODE_ENV==="test"||!!process.env.VITEST;if(e||s)try{await this.client.close();}catch{}}}async ensureIndexes(){await this.col("users").createIndex({email:1},{unique:true}),await this.col("users").createIndex({tenantId:1}),await this.col("users").createIndex({role:1}),await this.col("sessions").createIndex({token:1},{unique:true}),await this.col("sessions").createIndex({refreshToken:1}),await this.col("sessions").createIndex({userId:1}),await this.col("sessions").createIndex({expiresAt:1},{expireAfterSeconds:0}),await this.col("audit_logs").createIndex({timestamp:-1}),await this.col("audit_logs").createIndex({userId:1}),await this.col("audit_logs").createIndex({action:1}),await this.col("audit_logs").createIndex({resource:1}),await this.col("password_history").createIndex({userId:1,createdAt:-1}),await this.col("lockouts").createIndex({userId:1},{unique:true}),await this.col("lockouts").createIndex({lockedUntil:1}),this.indexesEnsured=true;}async createUser(e){let s=randomUUID(),t=new Date,i=await this.hashPassword(e.password),n={_id:s,name:e.name||null,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",avatar:e.avatar||null,tenantId:e.tenantId||null,metadata:e.metadata||null,emailVerified:false,locked:false,lastLogin:null,failedLoginAttempts:0,createdAt:t,updatedAt:t};return await this.col("users").insertOne(n),this.docToAuthUser(n)}async findUserByEmail(e){let s=await this.col("users").findOne({email:e.toLowerCase()});return s?this.docToAuthUser(s):null}async findUserById(e){let s=await this.col("users").findOne({_id:e});return s?this.docToAuthUser(s):null}async updateUser(e,s){let t={updatedAt:new Date};s.name!==void 0&&(t.name=s.name),s.email!==void 0&&(t.email=s.email),s.passwordHash!==void 0&&(t.passwordHash=s.passwordHash),s.role!==void 0&&(t.role=s.role),s.avatar!==void 0&&(t.avatar=s.avatar),s.tenantId!==void 0&&(t.tenantId=s.tenantId),s.metadata!==void 0&&(t.metadata=s.metadata),s.emailVerified!==void 0&&(t.emailVerified=s.emailVerified),s.locked!==void 0&&(t.locked=s.locked),s.lastLogin!==void 0&&(t.lastLogin=s.lastLogin?new Date(s.lastLogin):null),s.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=s.failedLoginAttempts);let i=await this.col("users").findOneAndUpdate({_id:e},{$set:t},{returnDocument:"after"});return i?this.docToAuthUser(i):null}async deleteUser(e){return (await this.col("users").deleteOne({_id:e})).deletedCount>0}async verifyPassword(e,s){let t=await this.findUserByEmail(e);if(!t)return null;let i=await this.col("users").findOne({email:e.toLowerCase()},{projection:{passwordHash:1}});return i?.passwordHash&&await h.compare(s,i.passwordHash)?t:null}async hashPassword(e){return h.hash(e,12)}async createSession(e,s){let t=randomUUID(),i=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:n,ipAddress:s?.ipAddress||null,userAgent:s?.userAgent||null,expiresAt:u,createdAt:o};return await this.col("sessions").insertOne(d),this.docToSession(d)}async findSessionByToken(e){let s=await this.col("sessions").findOne({token:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async findSessionByRefreshToken(e){let s=await this.col("sessions").findOne({refreshToken:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async deleteSession(e){return (await this.col("sessions").deleteOne({_id:e})).deletedCount>0}async deleteUserSessions(e){return (await this.col("sessions").deleteMany({userId:e})).deletedCount}async hasAnyUsers(){return await this.col("users").countDocuments()>0}async addPasswordToHistory(e,s){await this.col("password_history").insertOne({userId:e,passwordHash:s,createdAt:new Date});}async getPasswordHistory(e,s=5){return (await this.col("password_history").find({userId:e}).sort({createdAt:-1}).limit(s).toArray()).map(i=>i.passwordHash)}async isPasswordInHistory(e,s,t=5){let i=await this.getPasswordHistory(s,t);for(let n of i)if(await h.compare(e,n))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:n,resource:o,resourceId:u,success:d,startDate:c,endDate:f}=e,a={};i&&(a.userId=i),n&&(Array.isArray(n)?a.action={$in:n}:a.action=n),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(c||f)&&(a.timestamp={},c&&(a.timestamp.$gte=c),f&&(a.timestamp.$lte=f));let g=await this.col("audit_logs").countDocuments(a);return {logs:(await this.col("audit_logs").find(a).sort({timestamp:-1}).skip(t).limit(s).toArray()).map(r=>({id:r._id,timestamp:r.timestamp,action:r.action,userId:r.userId||void 0,userEmail:r.userEmail||void 0,role:r.role||void 0,resource:r.resource,resourceId:r.resourceId||void 0,changes:r.changes||void 0,ipAddress:r.ipAddress||void 0,userAgent:r.userAgent||void 0,success:r.success,error:r.error||void 0,metadata:r.metadata||void 0})),total:g}}async createAuditLog(e){let s=randomUUID(),t=new Date;return await this.col("audit_logs").insertOne({_id:s,action:e.action,userId:e.userId||null,userEmail:e.userEmail||null,role:e.role||null,resource:e.resource,resourceId:e.resourceId||null,changes:e.changes||null,ipAddress:e.ipAddress||null,userAgent:e.userAgent||null,success:e.success,error:e.error||null,metadata:e.metadata||null,timestamp:t}),{...e,id:s,timestamp:t}}docToAuthUser(e){return {id:e._id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,avatar:e.avatar||void 0,tenantId:e.tenantId||void 0,metadata:e.metadata||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?.toISOString?.()||e.lastLogin||void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:e.createdAt?.toISOString?.()||e.createdAt,updatedAt:e.updatedAt?.toISOString?.()||e.updatedAt}}docToSession(e){return {id:e._id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:e.expiresAt?.toISOString?.()||e.expiresAt,createdAt:e.createdAt?.toISOString?.()||e.createdAt,ipAddress:e.ipAddress||void 0,userAgent:e.userAgent||void 0}}async createEmailVerificationToken(e){let s=randomBytes(32).toString("hex"),t=new Date(Date.now()+1440*60*1e3),i=await import('mongodb'),n=i.ObjectId??i.default?.ObjectId;return await this.db.collection("email_verifications").insertOne({userId:new n(e),token:s,expiresAt:t,createdAt:new Date}),{token:s,expiresAt:t}}async verifyEmailToken(e){let s=await this.db.collection("email_verifications").findOne({token:e});return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.collection("users").updateOne({_id:s.userId},{$set:{emailVerified:true}}),await this.db.collection("email_verifications").deleteOne({_id:s._id}),{success:true,userId:s.userId.toString()}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=randomBytes(32).toString("hex"),i=new Date(Date.now()+3600*1e3),n=await import('mongodb'),o=n.ObjectId??n.default?.ObjectId;return await this.db.collection("password_resets").insertOne({userId:new o(s.id),token:t,expiresAt:i,createdAt:new Date}),{token:t,expiresAt:i}}async resetPasswordWithToken(e,s){let t=await this.db.collection("password_resets").findOne({token:e});if(!t)return {success:false,error:"Invalid reset token"};if(t.expiresAt<new Date)return {success:false,error:"Reset token has expired"};if(t.usedAt)return {success:false,error:"Reset token has already been used"};let i=await this.hashPassword(s);return await this.db.collection("users").updateOne({_id:t.userId},{$set:{passwordHash:i,updatedAt:new Date}}),await this.db.collection("password_resets").updateOne({_id:t._id},{$set:{usedAt:new Date}}),await this.db.collection("sessions").deleteMany({userId:t.userId}),{success:true}}};export{p as a};
@@ -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};