@dyrected/core 2.5.53 → 2.5.56

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 (409) hide show
  1. package/dist/{app-config-oOarB6Fw.d.cts → app-config-Bxg_DVxv.d.cts} +3 -1
  2. package/dist/{app-config-oOarB6Fw.d.ts → app-config-Bxg_DVxv.d.ts} +3 -1
  3. package/dist/index.d.cts +2 -2
  4. package/dist/index.d.ts +2 -2
  5. package/dist/server.d.cts +1 -1
  6. package/dist/server.d.ts +1 -1
  7. package/package.json +1 -1
  8. package/dist/__tests__/admin-auth.test.d.ts +0 -2
  9. package/dist/__tests__/admin-auth.test.d.ts.map +0 -1
  10. package/dist/__tests__/admin-auth.test.js +0 -440
  11. package/dist/__tests__/admin-auth.test.js.map +0 -1
  12. package/dist/__tests__/app.test.d.ts +0 -2
  13. package/dist/__tests__/app.test.d.ts.map +0 -1
  14. package/dist/__tests__/app.test.js +0 -27
  15. package/dist/__tests__/app.test.js.map +0 -1
  16. package/dist/__tests__/config.test.d.ts +0 -2
  17. package/dist/__tests__/config.test.d.ts.map +0 -1
  18. package/dist/__tests__/config.test.js +0 -91
  19. package/dist/__tests__/config.test.js.map +0 -1
  20. package/dist/__tests__/deleteMany.test.d.ts +0 -2
  21. package/dist/__tests__/deleteMany.test.d.ts.map +0 -1
  22. package/dist/__tests__/deleteMany.test.js +0 -75
  23. package/dist/__tests__/deleteMany.test.js.map +0 -1
  24. package/dist/__tests__/depth.test.d.ts +0 -2
  25. package/dist/__tests__/depth.test.d.ts.map +0 -1
  26. package/dist/__tests__/depth.test.js +0 -81
  27. package/dist/__tests__/depth.test.js.map +0 -1
  28. package/dist/__tests__/dynamic-options.test.d.ts +0 -2
  29. package/dist/__tests__/dynamic-options.test.d.ts.map +0 -1
  30. package/dist/__tests__/dynamic-options.test.js +0 -132
  31. package/dist/__tests__/dynamic-options.test.js.map +0 -1
  32. package/dist/__tests__/email.service.test.d.ts +0 -2
  33. package/dist/__tests__/email.service.test.d.ts.map +0 -1
  34. package/dist/__tests__/email.service.test.js +0 -46
  35. package/dist/__tests__/email.service.test.js.map +0 -1
  36. package/dist/__tests__/field-inference.test-types.d.ts +0 -24
  37. package/dist/__tests__/field-inference.test-types.d.ts.map +0 -1
  38. package/dist/__tests__/field-inference.test-types.js +0 -87
  39. package/dist/__tests__/field-inference.test-types.js.map +0 -1
  40. package/dist/__tests__/fixtures/editorial-workflow.d.ts +0 -9
  41. package/dist/__tests__/fixtures/editorial-workflow.d.ts.map +0 -1
  42. package/dist/__tests__/fixtures/editorial-workflow.js +0 -12
  43. package/dist/__tests__/fixtures/editorial-workflow.js.map +0 -1
  44. package/dist/__tests__/hooks.test.d.ts +0 -2
  45. package/dist/__tests__/hooks.test.d.ts.map +0 -1
  46. package/dist/__tests__/hooks.test.js +0 -320
  47. package/dist/__tests__/hooks.test.js.map +0 -1
  48. package/dist/__tests__/mocks.d.ts +0 -74
  49. package/dist/__tests__/mocks.d.ts.map +0 -1
  50. package/dist/__tests__/mocks.js +0 -159
  51. package/dist/__tests__/mocks.js.map +0 -1
  52. package/dist/__tests__/openapi.test.d.ts +0 -2
  53. package/dist/__tests__/openapi.test.d.ts.map +0 -1
  54. package/dist/__tests__/openapi.test.js +0 -95
  55. package/dist/__tests__/openapi.test.js.map +0 -1
  56. package/dist/__tests__/parse-sort.test.d.ts +0 -2
  57. package/dist/__tests__/parse-sort.test.d.ts.map +0 -1
  58. package/dist/__tests__/parse-sort.test.js +0 -24
  59. package/dist/__tests__/parse-sort.test.js.map +0 -1
  60. package/dist/__tests__/preferences.test.d.ts +0 -2
  61. package/dist/__tests__/preferences.test.d.ts.map +0 -1
  62. package/dist/__tests__/preferences.test.js +0 -168
  63. package/dist/__tests__/preferences.test.js.map +0 -1
  64. package/dist/__tests__/router.test.d.ts +0 -2
  65. package/dist/__tests__/router.test.d.ts.map +0 -1
  66. package/dist/__tests__/router.test.js +0 -52
  67. package/dist/__tests__/router.test.js.map +0 -1
  68. package/dist/__tests__/where.test.d.ts +0 -2
  69. package/dist/__tests__/where.test.d.ts.map +0 -1
  70. package/dist/__tests__/where.test.js +0 -105
  71. package/dist/__tests__/where.test.js.map +0 -1
  72. package/dist/__tests__/workflow.test.d.ts +0 -2
  73. package/dist/__tests__/workflow.test.d.ts.map +0 -1
  74. package/dist/__tests__/workflow.test.js +0 -497
  75. package/dist/__tests__/workflow.test.js.map +0 -1
  76. package/dist/app-B2tg7Djj.d.cts +0 -1575
  77. package/dist/app-B2tg7Djj.d.ts +0 -1575
  78. package/dist/app-BElen1tP.d.cts +0 -1690
  79. package/dist/app-BElen1tP.d.ts +0 -1690
  80. package/dist/app-BOrsS7Tz.d.cts +0 -1771
  81. package/dist/app-BOrsS7Tz.d.ts +0 -1771
  82. package/dist/app-Bh4_Opv0.d.cts +0 -1522
  83. package/dist/app-Bh4_Opv0.d.ts +0 -1522
  84. package/dist/app-BibuoHQG.d.cts +0 -1764
  85. package/dist/app-BibuoHQG.d.ts +0 -1764
  86. package/dist/app-Bv9gaDAN.d.cts +0 -561
  87. package/dist/app-Bv9gaDAN.d.ts +0 -561
  88. package/dist/app-BvG3bRc8.d.cts +0 -419
  89. package/dist/app-BvG3bRc8.d.ts +0 -419
  90. package/dist/app-C-HgyliB.d.cts +0 -1694
  91. package/dist/app-C-HgyliB.d.ts +0 -1694
  92. package/dist/app-C3B9N1KR.d.cts +0 -1522
  93. package/dist/app-C3B9N1KR.d.ts +0 -1522
  94. package/dist/app-Cc2mG3zi.d.cts +0 -373
  95. package/dist/app-Cc2mG3zi.d.ts +0 -373
  96. package/dist/app-Ctfmo2Re.d.cts +0 -1692
  97. package/dist/app-Ctfmo2Re.d.ts +0 -1692
  98. package/dist/app-D0ffogDd.d.cts +0 -1690
  99. package/dist/app-D0ffogDd.d.ts +0 -1690
  100. package/dist/app-D2uR47gK.d.cts +0 -1690
  101. package/dist/app-D2uR47gK.d.ts +0 -1690
  102. package/dist/app-DDJJa0ep.d.cts +0 -1621
  103. package/dist/app-DDJJa0ep.d.ts +0 -1621
  104. package/dist/app-DO1s9YW1.d.cts +0 -1621
  105. package/dist/app-DO1s9YW1.d.ts +0 -1621
  106. package/dist/app-DTP3-9PJ.d.cts +0 -561
  107. package/dist/app-DTP3-9PJ.d.ts +0 -561
  108. package/dist/app-DZt5nslu.d.cts +0 -374
  109. package/dist/app-DZt5nslu.d.ts +0 -377
  110. package/dist/app-DbKDGYTI.d.cts +0 -566
  111. package/dist/app-DbKDGYTI.d.ts +0 -566
  112. package/dist/app-Dk3SzV1a.d.cts +0 -374
  113. package/dist/app-Dk3SzV1a.d.ts +0 -374
  114. package/dist/app-DnX9mNsh.d.cts +0 -374
  115. package/dist/app-DnX9mNsh.d.ts +0 -374
  116. package/dist/app-DqRO-CMi.d.cts +0 -1457
  117. package/dist/app-DqRO-CMi.d.ts +0 -1457
  118. package/dist/app-DvaFpOtj.d.cts +0 -398
  119. package/dist/app-DvaFpOtj.d.ts +0 -398
  120. package/dist/app-FGzip4XM.d.cts +0 -1563
  121. package/dist/app-FGzip4XM.d.ts +0 -1563
  122. package/dist/app-KApbf4XL.d.cts +0 -362
  123. package/dist/app-KApbf4XL.d.ts +0 -362
  124. package/dist/app-T0alZAE0.d.cts +0 -383
  125. package/dist/app-T0alZAE0.d.ts +0 -383
  126. package/dist/app-aW2FMuYM.d.cts +0 -1759
  127. package/dist/app-aW2FMuYM.d.ts +0 -1759
  128. package/dist/app-config-2vF6W56z.d.cts +0 -1335
  129. package/dist/app-config-2vF6W56z.d.ts +0 -1335
  130. package/dist/app-config-3XBnu9Xz.d.cts +0 -1379
  131. package/dist/app-config-3XBnu9Xz.d.ts +0 -1379
  132. package/dist/app-config-BLMX-9MN.d.cts +0 -1045
  133. package/dist/app-config-BLMX-9MN.d.ts +0 -1045
  134. package/dist/app-config-CaEQH0Kb.d.cts +0 -1383
  135. package/dist/app-config-CaEQH0Kb.d.ts +0 -1383
  136. package/dist/app-config-DLK6bCaP.d.cts +0 -1390
  137. package/dist/app-config-DLK6bCaP.d.ts +0 -1390
  138. package/dist/app-oQt5-9MU.d.cts +0 -1560
  139. package/dist/app-oQt5-9MU.d.ts +0 -1560
  140. package/dist/app-rZj1VFer.d.cts +0 -1621
  141. package/dist/app-rZj1VFer.d.ts +0 -1621
  142. package/dist/app-wo82JRHl.d.cts +0 -445
  143. package/dist/app-wo82JRHl.d.ts +0 -445
  144. package/dist/app.d.ts +0 -21
  145. package/dist/app.d.ts.map +0 -1
  146. package/dist/app.js +0 -56
  147. package/dist/app.js.map +0 -1
  148. package/dist/auth/jexl.d.ts +0 -10
  149. package/dist/auth/jexl.d.ts.map +0 -1
  150. package/dist/auth/jexl.js +0 -22
  151. package/dist/auth/jexl.js.map +0 -1
  152. package/dist/auth/password.d.ts +0 -10
  153. package/dist/auth/password.d.ts.map +0 -1
  154. package/dist/auth/password.js +0 -28
  155. package/dist/auth/password.js.map +0 -1
  156. package/dist/auth/token.d.ts +0 -22
  157. package/dist/auth/token.d.ts.map +0 -1
  158. package/dist/auth/token.js +0 -40
  159. package/dist/auth/token.js.map +0 -1
  160. package/dist/chunk-22JTWD74.js +0 -1784
  161. package/dist/chunk-23URSKPI.js +0 -2371
  162. package/dist/chunk-2JMA3M5S.js +0 -2475
  163. package/dist/chunk-3FZEUK36.js +0 -2470
  164. package/dist/chunk-3VUH2MNW.js +0 -1903
  165. package/dist/chunk-44O2LDPT.js +0 -1513
  166. package/dist/chunk-45JDQDA2.js +0 -1899
  167. package/dist/chunk-4C4L6SD2.js +0 -1524
  168. package/dist/chunk-4EDMZAM5.js +0 -2692
  169. package/dist/chunk-52T4RCFU.js +0 -1972
  170. package/dist/chunk-6ZXEGKT6.js +0 -619
  171. package/dist/chunk-7GGHK75W.js +0 -1835
  172. package/dist/chunk-ALNQINX7.js +0 -2496
  173. package/dist/chunk-B6KDKYXB.js +0 -2502
  174. package/dist/chunk-BEONZV6M.js +0 -1951
  175. package/dist/chunk-C4GEQ5RP.js +0 -1993
  176. package/dist/chunk-CQDVPMEU.js +0 -613
  177. package/dist/chunk-DOJHZ7XN.js +0 -2394
  178. package/dist/chunk-EH7G3LLL.js +0 -2065
  179. package/dist/chunk-EXXOPW3I.js +0 -2483
  180. package/dist/chunk-F4ZC6TXR.js +0 -2065
  181. package/dist/chunk-FCXE5CVC.js +0 -1528
  182. package/dist/chunk-FDQYPPG3.js +0 -2698
  183. package/dist/chunk-FURYJ254.mjs +0 -33
  184. package/dist/chunk-G2QQLBHW.js +0 -24
  185. package/dist/chunk-GM4WW6IE.js +0 -66
  186. package/dist/chunk-GZODLJ3C.js +0 -1861
  187. package/dist/chunk-IIY3E7Q7.js +0 -1996
  188. package/dist/chunk-JJN4J5NS.js +0 -2069
  189. package/dist/chunk-MRUHCNDM.js +0 -1940
  190. package/dist/chunk-NKDX67AW.js +0 -2698
  191. package/dist/chunk-NYUB4AHZ.js +0 -1951
  192. package/dist/chunk-OD4SLW7H.js +0 -1930
  193. package/dist/chunk-OE5MH3NB.js +0 -2070
  194. package/dist/chunk-PH36WQYS.js +0 -1875
  195. package/dist/chunk-PKNFV7KE.js +0 -2469
  196. package/dist/chunk-SUGK7UYL.js +0 -311
  197. package/dist/chunk-TIJHR54M.js +0 -1879
  198. package/dist/chunk-TUUHGLB5.js +0 -2609
  199. package/dist/chunk-UBTRANFX.js +0 -2476
  200. package/dist/chunk-VJWUG2XK.js +0 -1951
  201. package/dist/chunk-W6KURRMW.js +0 -2471
  202. package/dist/chunk-Y4AYI52W.js +0 -631
  203. package/dist/chunk-YDOBB7MY.js +0 -1457
  204. package/dist/chunk-YNJ3YC4N.js +0 -2483
  205. package/dist/chunk-ZFAOBRHT.js +0 -2709
  206. package/dist/controllers/admin-auth.controller.d.ts +0 -68
  207. package/dist/controllers/admin-auth.controller.d.ts.map +0 -1
  208. package/dist/controllers/admin-auth.controller.js +0 -414
  209. package/dist/controllers/admin-auth.controller.js.map +0 -1
  210. package/dist/controllers/auth.controller.d.ts +0 -125
  211. package/dist/controllers/auth.controller.d.ts.map +0 -1
  212. package/dist/controllers/auth.controller.js +0 -323
  213. package/dist/controllers/auth.controller.js.map +0 -1
  214. package/dist/controllers/collection.controller.d.ts +0 -157
  215. package/dist/controllers/collection.controller.d.ts.map +0 -1
  216. package/dist/controllers/collection.controller.js +0 -779
  217. package/dist/controllers/collection.controller.js.map +0 -1
  218. package/dist/controllers/global.controller.d.ts +0 -17
  219. package/dist/controllers/global.controller.d.ts.map +0 -1
  220. package/dist/controllers/global.controller.js +0 -132
  221. package/dist/controllers/global.controller.js.map +0 -1
  222. package/dist/controllers/media.controller.d.ts +0 -38
  223. package/dist/controllers/media.controller.d.ts.map +0 -1
  224. package/dist/controllers/media.controller.js +0 -162
  225. package/dist/controllers/media.controller.js.map +0 -1
  226. package/dist/controllers/preview.controller.d.ts +0 -37
  227. package/dist/controllers/preview.controller.d.ts.map +0 -1
  228. package/dist/controllers/preview.controller.js +0 -48
  229. package/dist/controllers/preview.controller.js.map +0 -1
  230. package/dist/index-BKYugiYp.d.cts +0 -1988
  231. package/dist/index-BKYugiYp.d.ts +0 -1988
  232. package/dist/index-BSWCiAen.d.cts +0 -1983
  233. package/dist/index-BSWCiAen.d.ts +0 -1983
  234. package/dist/index-BfLDb3b0.d.cts +0 -1467
  235. package/dist/index-BfLDb3b0.d.ts +0 -1467
  236. package/dist/index-Bi4sX_eC.d.cts +0 -1491
  237. package/dist/index-Bi4sX_eC.d.ts +0 -1491
  238. package/dist/index-Bp7PDOYG.d.cts +0 -1750
  239. package/dist/index-Bp7PDOYG.d.ts +0 -1750
  240. package/dist/index-ByXooLy-.d.cts +0 -1762
  241. package/dist/index-ByXooLy-.d.ts +0 -1762
  242. package/dist/index-C9Vp1DCT.d.cts +0 -1563
  243. package/dist/index-C9Vp1DCT.d.ts +0 -1563
  244. package/dist/index-CFezd8p1.d.cts +0 -1986
  245. package/dist/index-CFezd8p1.d.ts +0 -1986
  246. package/dist/index-CdQwnbfh.d.cts +0 -1889
  247. package/dist/index-CdQwnbfh.d.ts +0 -1889
  248. package/dist/index-D38_E0gf.d.cts +0 -336
  249. package/dist/index-D38_E0gf.d.ts +0 -336
  250. package/dist/index-DR2z1rrf.d.cts +0 -1503
  251. package/dist/index-DR2z1rrf.d.ts +0 -1503
  252. package/dist/index-DTrpTru7.d.cts +0 -1881
  253. package/dist/index-DTrpTru7.d.ts +0 -1881
  254. package/dist/index-DfAmTZXk.d.cts +0 -1749
  255. package/dist/index-DfAmTZXk.d.ts +0 -1749
  256. package/dist/index-DfkPT4NR.d.cts +0 -1584
  257. package/dist/index-DfkPT4NR.d.ts +0 -1584
  258. package/dist/index-DzUlE5Hc.d.cts +0 -1751
  259. package/dist/index-DzUlE5Hc.d.ts +0 -1751
  260. package/dist/index-M_m6dXZV.d.cts +0 -1889
  261. package/dist/index-M_m6dXZV.d.ts +0 -1889
  262. package/dist/index-RylhgOwj.d.cts +0 -340
  263. package/dist/index-RylhgOwj.d.ts +0 -340
  264. package/dist/index-qhLus8ZO.d.cts +0 -1881
  265. package/dist/index-qhLus8ZO.d.ts +0 -1881
  266. package/dist/index-xB1lMg79.d.cts +0 -1456
  267. package/dist/index-xB1lMg79.d.ts +0 -1456
  268. package/dist/index.d.mts +0 -417
  269. package/dist/index.d.ts.map +0 -1
  270. package/dist/index.js.map +0 -1
  271. package/dist/index.mjs +0 -1974
  272. package/dist/middleware/auth.d.ts +0 -18
  273. package/dist/middleware/auth.d.ts.map +0 -1
  274. package/dist/middleware/auth.js +0 -45
  275. package/dist/middleware/auth.js.map +0 -1
  276. package/dist/password-ACI2YUGZ.js +0 -8
  277. package/dist/router.d.ts +0 -8
  278. package/dist/router.d.ts.map +0 -1
  279. package/dist/router.js +0 -625
  280. package/dist/router.js.map +0 -1
  281. package/dist/server.d.ts.map +0 -1
  282. package/dist/server.js.map +0 -1
  283. package/dist/services/audit.service.d.ts +0 -23
  284. package/dist/services/audit.service.d.ts.map +0 -1
  285. package/dist/services/audit.service.js +0 -28
  286. package/dist/services/audit.service.js.map +0 -1
  287. package/dist/services/defaults.service.d.ts +0 -8
  288. package/dist/services/defaults.service.d.ts.map +0 -1
  289. package/dist/services/defaults.service.js +0 -55
  290. package/dist/services/defaults.service.js.map +0 -1
  291. package/dist/services/email-template.d.ts +0 -46
  292. package/dist/services/email-template.d.ts.map +0 -1
  293. package/dist/services/email-template.js +0 -88
  294. package/dist/services/email-template.js.map +0 -1
  295. package/dist/services/email.service.d.ts +0 -33
  296. package/dist/services/email.service.d.ts.map +0 -1
  297. package/dist/services/email.service.js +0 -96
  298. package/dist/services/email.service.js.map +0 -1
  299. package/dist/services/media.service.d.ts +0 -20
  300. package/dist/services/media.service.d.ts.map +0 -1
  301. package/dist/services/media.service.js +0 -49
  302. package/dist/services/media.service.js.map +0 -1
  303. package/dist/services/population.service.d.ts +0 -20
  304. package/dist/services/population.service.d.ts.map +0 -1
  305. package/dist/services/population.service.js +0 -194
  306. package/dist/services/population.service.js.map +0 -1
  307. package/dist/token-7QG5DBME.mjs +0 -10
  308. package/dist/types/access.d.ts +0 -38
  309. package/dist/types/access.d.ts.map +0 -1
  310. package/dist/types/access.js +0 -2
  311. package/dist/types/access.js.map +0 -1
  312. package/dist/types/adapters.d.ts +0 -146
  313. package/dist/types/adapters.d.ts.map +0 -1
  314. package/dist/types/adapters.js +0 -2
  315. package/dist/types/adapters.js.map +0 -1
  316. package/dist/types/admin-auth.d.ts +0 -132
  317. package/dist/types/admin-auth.d.ts.map +0 -1
  318. package/dist/types/admin-auth.js +0 -2
  319. package/dist/types/admin-auth.js.map +0 -1
  320. package/dist/types/admin.d.ts +0 -65
  321. package/dist/types/admin.d.ts.map +0 -1
  322. package/dist/types/admin.js +0 -2
  323. package/dist/types/admin.js.map +0 -1
  324. package/dist/types/app-config.d.ts +0 -143
  325. package/dist/types/app-config.d.ts.map +0 -1
  326. package/dist/types/app-config.js +0 -2
  327. package/dist/types/app-config.js.map +0 -1
  328. package/dist/types/documents.d.ts +0 -65
  329. package/dist/types/documents.d.ts.map +0 -1
  330. package/dist/types/documents.js +0 -2
  331. package/dist/types/documents.js.map +0 -1
  332. package/dist/types/hooks.d.ts +0 -122
  333. package/dist/types/hooks.d.ts.map +0 -1
  334. package/dist/types/hooks.js +0 -2
  335. package/dist/types/hooks.js.map +0 -1
  336. package/dist/types/index.d.ts +0 -13
  337. package/dist/types/index.d.ts.map +0 -1
  338. package/dist/types/index.js +0 -13
  339. package/dist/types/index.js.map +0 -1
  340. package/dist/types/request.d.ts +0 -42
  341. package/dist/types/request.d.ts.map +0 -1
  342. package/dist/types/request.js +0 -2
  343. package/dist/types/request.js.map +0 -1
  344. package/dist/types/schema-config.d.ts +0 -303
  345. package/dist/types/schema-config.d.ts.map +0 -1
  346. package/dist/types/schema-config.js +0 -2
  347. package/dist/types/schema-config.js.map +0 -1
  348. package/dist/types/schema-core.d.ts +0 -294
  349. package/dist/types/schema-core.d.ts.map +0 -1
  350. package/dist/types/schema-core.js +0 -2
  351. package/dist/types/schema-core.js.map +0 -1
  352. package/dist/types/schema-inference.d.ts +0 -73
  353. package/dist/types/schema-inference.d.ts.map +0 -1
  354. package/dist/types/schema-inference.js +0 -2
  355. package/dist/types/schema-inference.js.map +0 -1
  356. package/dist/types/workflows.d.ts +0 -84
  357. package/dist/types/workflows.d.ts.map +0 -1
  358. package/dist/types/workflows.js +0 -7
  359. package/dist/types/workflows.js.map +0 -1
  360. package/dist/utils/admin-auth.d.ts +0 -5
  361. package/dist/utils/admin-auth.d.ts.map +0 -1
  362. package/dist/utils/admin-auth.js +0 -39
  363. package/dist/utils/admin-auth.js.map +0 -1
  364. package/dist/utils/config.d.ts +0 -8
  365. package/dist/utils/config.d.ts.map +0 -1
  366. package/dist/utils/config.js +0 -238
  367. package/dist/utils/config.js.map +0 -1
  368. package/dist/utils/hooks.d.ts +0 -41
  369. package/dist/utils/hooks.d.ts.map +0 -1
  370. package/dist/utils/hooks.js +0 -173
  371. package/dist/utils/hooks.js.map +0 -1
  372. package/dist/utils/openapi.d.ts +0 -6
  373. package/dist/utils/openapi.d.ts.map +0 -1
  374. package/dist/utils/openapi.js +0 -842
  375. package/dist/utils/openapi.js.map +0 -1
  376. package/dist/utils/parse-sort.d.ts +0 -7
  377. package/dist/utils/parse-sort.d.ts.map +0 -1
  378. package/dist/utils/parse-sort.js +0 -23
  379. package/dist/utils/parse-sort.js.map +0 -1
  380. package/dist/utils/parse-where.d.ts +0 -63
  381. package/dist/utils/parse-where.d.ts.map +0 -1
  382. package/dist/utils/parse-where.js +0 -196
  383. package/dist/utils/parse-where.js.map +0 -1
  384. package/dist/utils/readonly-db.d.ts +0 -9
  385. package/dist/utils/readonly-db.d.ts.map +0 -1
  386. package/dist/utils/readonly-db.js +0 -21
  387. package/dist/utils/readonly-db.js.map +0 -1
  388. package/dist/utils/setup-prompt.d.ts +0 -11
  389. package/dist/utils/setup-prompt.d.ts.map +0 -1
  390. package/dist/utils/setup-prompt.js +0 -863
  391. package/dist/utils/setup-prompt.js.map +0 -1
  392. package/dist/utils/swagger.d.ts +0 -11
  393. package/dist/utils/swagger.d.ts.map +0 -1
  394. package/dist/utils/swagger.js +0 -62
  395. package/dist/utils/swagger.js.map +0 -1
  396. package/dist/utils/upload-validation.d.ts +0 -23
  397. package/dist/utils/upload-validation.d.ts.map +0 -1
  398. package/dist/utils/upload-validation.js +0 -44
  399. package/dist/utils/upload-validation.js.map +0 -1
  400. package/dist/utils/where-sanitizer.d.ts +0 -10
  401. package/dist/utils/where-sanitizer.d.ts.map +0 -1
  402. package/dist/utils/where-sanitizer.js +0 -67
  403. package/dist/utils/where-sanitizer.js.map +0 -1
  404. package/dist/where-sanitizer-7Q4JXMX6.js +0 -57
  405. package/dist/where-sanitizer-DQIWTQZW.js +0 -50
  406. package/dist/workflows.d.ts +0 -54
  407. package/dist/workflows.d.ts.map +0 -1
  408. package/dist/workflows.js +0 -282
  409. package/dist/workflows.js.map +0 -1
@@ -1,2394 +0,0 @@
1
- // src/utils/config.ts
2
- var AUDIT_COLLECTION_SLUG = "__audit";
3
- var SYSTEM_FIELDS = [
4
- {
5
- name: "createdAt",
6
- type: "date",
7
- label: "Created At",
8
- admin: { readOnly: true, hidden: true }
9
- },
10
- {
11
- name: "updatedAt",
12
- type: "date",
13
- label: "Updated At",
14
- admin: { readOnly: true, hidden: true }
15
- },
16
- {
17
- name: "createdBy",
18
- type: "text",
19
- label: "Created By",
20
- admin: { readOnly: true, hidden: true }
21
- },
22
- {
23
- name: "updatedBy",
24
- type: "text",
25
- label: "Updated By",
26
- admin: { readOnly: true, hidden: true }
27
- }
28
- ];
29
- var AUDIT_COLLECTION = {
30
- slug: AUDIT_COLLECTION_SLUG,
31
- labels: { singular: "Audit Log", plural: "Audit Logs" },
32
- fields: [
33
- { name: "collection", type: "text", label: "Collection", required: true },
34
- { name: "documentId", type: "text", label: "Document ID" },
35
- { name: "operation", type: "select", label: "Operation", options: ["create", "update", "delete"], required: true },
36
- { name: "user", type: "text", label: "User ID" },
37
- { name: "timestamp", type: "date", label: "Timestamp", required: true },
38
- { name: "changes", type: "json", label: "Changes" }
39
- ],
40
- admin: { hidden: true }
41
- };
42
- function normalizeConfig(config) {
43
- const collections = config?.collections || [];
44
- const globals = config?.globals || [];
45
- const needsAudit = collections.some((col) => col.audit);
46
- const normalizedCollections = collections.map((col) => {
47
- let fields = col.fields || [];
48
- const existingFieldNames = new Set(fields.map((f) => f.name));
49
- if (col.auth) {
50
- if (!existingFieldNames.has("email")) {
51
- fields = [
52
- ...fields,
53
- {
54
- name: "email",
55
- type: "email",
56
- label: "Email",
57
- required: true,
58
- unique: true,
59
- promoted: true,
60
- access: {
61
- update: "!id"
62
- }
63
- }
64
- ];
65
- }
66
- if (!existingFieldNames.has("password")) {
67
- fields = [
68
- ...fields,
69
- {
70
- name: "password",
71
- type: "text",
72
- label: "Password",
73
- required: true,
74
- access: {
75
- update: "!id || user.id == id"
76
- }
77
- }
78
- ];
79
- }
80
- if (!existingFieldNames.has("roles")) {
81
- fields = [
82
- ...fields,
83
- {
84
- name: "roles",
85
- type: "select",
86
- label: "Roles",
87
- defaultValue: [],
88
- options: [
89
- { value: "admin", label: "Admin" },
90
- { value: "editor", label: "Editor" },
91
- { value: "viewer", label: "Viewer" }
92
- ],
93
- access: {
94
- update: "user.roles && 'admin' in user.roles"
95
- }
96
- }
97
- ];
98
- }
99
- fields = fields.map((field) => {
100
- if (field.name === "email") {
101
- return {
102
- ...field,
103
- access: {
104
- ...field.access || {},
105
- update: "!id"
106
- }
107
- };
108
- }
109
- if (field.name === "password") {
110
- return {
111
- ...field,
112
- admin: { ...field.admin || {} },
113
- access: {
114
- ...field.access || {},
115
- update: "!id || user.id == id"
116
- }
117
- };
118
- }
119
- if (field.name === "roles") {
120
- return {
121
- ...field,
122
- access: {
123
- ...field.access || {},
124
- // Must be an admin; cannot edit own roles (no self-elevation).
125
- update: "user.roles && 'admin' in user.roles && user.id != id"
126
- }
127
- };
128
- }
129
- return field;
130
- });
131
- }
132
- const updatedFieldNames = new Set(fields.map((f) => f.name));
133
- const fieldsToInject = SYSTEM_FIELDS.filter((f) => !updatedFieldNames.has(f.name));
134
- return {
135
- ...col,
136
- fields: [...fields, ...fieldsToInject]
137
- };
138
- });
139
- const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
140
- return {
141
- ...config,
142
- collections: [...normalizedCollections, ...needsAudit && !hasAuditCollection ? [AUDIT_COLLECTION] : []],
143
- globals
144
- };
145
- }
146
-
147
- // src/utils/hooks.ts
148
- async function runCollectionHooks(hooks, args) {
149
- if (!hooks || hooks.length === 0) {
150
- return args.data ?? args.doc ?? void 0;
151
- }
152
- let currentPayload = args.data ?? args.doc ?? void 0;
153
- for (const hook of hooks) {
154
- const result = await hook({
155
- ...args,
156
- data: args.data !== void 0 ? currentPayload : void 0,
157
- doc: args.doc !== void 0 ? currentPayload : void 0
158
- });
159
- if (result !== void 0) {
160
- currentPayload = result;
161
- }
162
- }
163
- return currentPayload;
164
- }
165
- async function executeFieldBeforeChange(fields, data, originalDoc, user) {
166
- if (!data || typeof data !== "object") return data;
167
- const result = { ...data };
168
- for (const field of fields) {
169
- if (!field.name) continue;
170
- const value = result[field.name];
171
- const origValue = originalDoc?.[field.name];
172
- let updatedValue = value;
173
- if (field.hooks?.beforeChange) {
174
- for (const hook of field.hooks.beforeChange) {
175
- updatedValue = await hook({
176
- value: updatedValue,
177
- originalDoc,
178
- data: result,
179
- user
180
- });
181
- }
182
- result[field.name] = updatedValue;
183
- }
184
- if (updatedValue !== void 0 && updatedValue !== null) {
185
- if (field.type === "object" && field.fields) {
186
- result[field.name] = await executeFieldBeforeChange(
187
- field.fields,
188
- updatedValue,
189
- origValue,
190
- user
191
- );
192
- } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
193
- const arrayResult = [];
194
- for (let i = 0; i < updatedValue.length; i++) {
195
- const item = updatedValue[i];
196
- const origItem = Array.isArray(origValue) ? origValue[i] : void 0;
197
- const processedItem = await executeFieldBeforeChange(
198
- field.fields,
199
- item,
200
- origItem,
201
- user
202
- );
203
- arrayResult.push(processedItem);
204
- }
205
- result[field.name] = arrayResult;
206
- } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
207
- const blocksResult = [];
208
- for (let i = 0; i < updatedValue.length; i++) {
209
- const blockData = updatedValue[i];
210
- const origBlock = Array.isArray(origValue) ? origValue[i] : void 0;
211
- const blockConfig = field.blocks.find((b) => b.slug === blockData.blockType);
212
- if (blockConfig) {
213
- const processedBlock = await executeFieldBeforeChange(
214
- blockConfig.fields,
215
- blockData,
216
- origBlock,
217
- user
218
- );
219
- blocksResult.push(processedBlock);
220
- } else {
221
- blocksResult.push(blockData);
222
- }
223
- }
224
- result[field.name] = blocksResult;
225
- }
226
- }
227
- }
228
- return result;
229
- }
230
- async function executeFieldAfterRead(fields, doc, user) {
231
- if (!doc || typeof doc !== "object") return doc;
232
- const result = { ...doc };
233
- for (const field of fields) {
234
- if (!field.name) continue;
235
- const value = result[field.name];
236
- let updatedValue = value;
237
- if (field.hooks?.afterRead) {
238
- for (const hook of field.hooks.afterRead) {
239
- updatedValue = await hook({
240
- value: updatedValue,
241
- doc: result,
242
- user
243
- });
244
- }
245
- result[field.name] = updatedValue;
246
- }
247
- if (updatedValue !== void 0 && updatedValue !== null) {
248
- if (field.type === "object" && field.fields) {
249
- result[field.name] = await executeFieldAfterRead(
250
- field.fields,
251
- updatedValue,
252
- user
253
- );
254
- } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
255
- const arrayResult = [];
256
- for (const item of updatedValue) {
257
- const processedItem = await executeFieldAfterRead(
258
- field.fields,
259
- item,
260
- user
261
- );
262
- arrayResult.push(processedItem);
263
- }
264
- result[field.name] = arrayResult;
265
- } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
266
- const blocksResult = [];
267
- for (const blockData of updatedValue) {
268
- const blockConfig = field.blocks.find((b) => b.slug === blockData.blockType);
269
- if (blockConfig) {
270
- const processedBlock = await executeFieldAfterRead(
271
- blockConfig.fields,
272
- blockData,
273
- user
274
- );
275
- blocksResult.push(processedBlock);
276
- } else {
277
- blocksResult.push(blockData);
278
- }
279
- }
280
- result[field.name] = blocksResult;
281
- }
282
- }
283
- }
284
- return result;
285
- }
286
-
287
- // src/services/defaults.service.ts
288
- var DefaultsService = class {
289
- /**
290
- * Recursively apply default values to a data object based on field definitions.
291
- */
292
- static apply(fields, data = {}) {
293
- const result = { ...data || {} };
294
- fields.forEach((field) => {
295
- if (field.type === "join") return;
296
- if (field.type === "row" && field.fields) {
297
- Object.assign(result, this.apply(field.fields, data));
298
- return;
299
- }
300
- if (!field.name) return;
301
- let value = result[field.name];
302
- if ((value === void 0 || value === null) && field.renameTo) {
303
- const legacyValue = result[field.renameTo];
304
- if (legacyValue !== void 0 && legacyValue !== null) {
305
- value = legacyValue;
306
- result[field.name] = legacyValue;
307
- }
308
- }
309
- if (value === void 0 || value === null) {
310
- if (field.defaultValue !== void 0) {
311
- result[field.name] = field.defaultValue;
312
- } else {
313
- if (field.type === "boolean") result[field.name] = false;
314
- else if (field.type === "array") result[field.name] = [];
315
- else if (field.type === "multiSelect") result[field.name] = [];
316
- else if (field.type === "object") {
317
- result[field.name] = this.apply(field.fields || [], {});
318
- }
319
- }
320
- } else if (field.type === "object" && field.fields) {
321
- result[field.name] = this.apply(field.fields, value);
322
- } else if (field.type === "array" && field.fields && Array.isArray(value)) {
323
- result[field.name] = value.map((item) => this.apply(field.fields, item));
324
- }
325
- });
326
- return result;
327
- }
328
- };
329
-
330
- // src/services/population.service.ts
331
- var PopulationService = class {
332
- db;
333
- collections;
334
- constructor(db, collections) {
335
- this.db = db;
336
- this.collections = collections;
337
- }
338
- /**
339
- * Recursively populate relationship fields in a document or array of documents.
340
- */
341
- async populate(args) {
342
- const { data, fields, currentDepth = 0, maxDepth = 10 } = args;
343
- if (currentDepth >= maxDepth || !data) {
344
- return data;
345
- }
346
- if (Array.isArray(data)) {
347
- return Promise.all(data.map((item) => this.populate({ ...args, data: item })));
348
- }
349
- const populatedDoc = { ...data };
350
- for (const field of fields) {
351
- if (field.type === "join") continue;
352
- if (field.type === "row" && field.fields) {
353
- const rowPopulated = await this.populate({ data, fields: field.fields, currentDepth, maxDepth });
354
- Object.assign(populatedDoc, rowPopulated);
355
- continue;
356
- }
357
- if (!field.name) continue;
358
- const value = populatedDoc[field.name];
359
- if (field.type === "relationship" && field.relationTo && value) {
360
- const relatedCollection = this.collections.find((c) => c.slug === field.relationTo);
361
- if (!relatedCollection) continue;
362
- if (Array.isArray(value)) {
363
- populatedDoc[field.name] = await Promise.all(
364
- value.map(async (id) => {
365
- if (!id) return id;
366
- let doc = id;
367
- if (typeof id === "string") {
368
- doc = await this.db.findOne({ collection: field.relationTo, id });
369
- }
370
- if (!doc || typeof doc !== "object") return id;
371
- const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
372
- return this.populate({
373
- data: docWithDefaults,
374
- fields: relatedCollection.fields,
375
- currentDepth: currentDepth + 1,
376
- maxDepth
377
- });
378
- })
379
- );
380
- } else if (value) {
381
- let doc = value;
382
- if (typeof value === "string") {
383
- doc = await this.db.findOne({ collection: field.relationTo, id: value });
384
- }
385
- if (doc && typeof doc === "object") {
386
- const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
387
- populatedDoc[field.name] = await this.populate({
388
- data: docWithDefaults,
389
- fields: relatedCollection.fields,
390
- currentDepth: currentDepth + 1,
391
- maxDepth
392
- });
393
- }
394
- }
395
- }
396
- if (field.type === "url" && value && typeof value === "object" && value.type === "internal" && value.relationTo && value.value) {
397
- const relatedCollection = this.collections.find((c) => c.slug === value.relationTo);
398
- if (relatedCollection) {
399
- const doc = await this.db.findOne({ collection: value.relationTo, id: value.value });
400
- if (doc && typeof doc === "object") {
401
- const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
402
- const populatedDocValue = await this.populate({
403
- data: docWithDefaults,
404
- fields: relatedCollection.fields,
405
- currentDepth: currentDepth + 1,
406
- maxDepth
407
- });
408
- const identifier = docWithDefaults.slug || docWithDefaults.id;
409
- const resolvedUrl = `/collections/${value.relationTo}/${identifier}`;
410
- populatedDoc[field.name] = {
411
- ...value,
412
- url: resolvedUrl,
413
- doc: populatedDocValue
414
- };
415
- }
416
- }
417
- }
418
- if ((field.type === "array" || field.type === "object") && field.fields && value) {
419
- populatedDoc[field.name] = await this.populate({
420
- data: value,
421
- fields: field.fields,
422
- currentDepth,
423
- // Nested fields don't consume depth, only relationships do
424
- maxDepth
425
- });
426
- }
427
- if (field.type === "blocks" && field.blocks && Array.isArray(value)) {
428
- populatedDoc[field.name] = await Promise.all(
429
- value.map(async (blockData) => {
430
- const blockConfig = field.blocks.find((b) => b.slug === blockData.blockType);
431
- if (!blockConfig) return blockData;
432
- return this.populate({
433
- data: blockData,
434
- fields: blockConfig.fields,
435
- currentDepth,
436
- maxDepth
437
- });
438
- })
439
- );
440
- }
441
- }
442
- return populatedDoc;
443
- }
444
- /**
445
- * Helper to populate a PaginatedResult
446
- */
447
- async populateResult(result, fields, maxDepth) {
448
- if (maxDepth <= 0) return result;
449
- const populatedDocs = await this.populate({
450
- data: result.docs,
451
- fields,
452
- currentDepth: 0,
453
- maxDepth
454
- });
455
- return {
456
- ...result,
457
- docs: populatedDocs
458
- };
459
- }
460
- };
461
-
462
- // src/services/audit.service.ts
463
- var AuditService = class {
464
- /**
465
- * Writes a single entry to the __audit collection.
466
- * Called without await — runs asynchronously and never blocks the primary operation.
467
- */
468
- static async log(db, args) {
469
- try {
470
- await db.create({
471
- collection: "__audit",
472
- data: {
473
- collection: args.collection,
474
- documentId: args.documentId ?? null,
475
- operation: args.operation,
476
- user: args.user?.id ?? null,
477
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
478
- changes: JSON.stringify({
479
- before: args.before ?? null,
480
- after: args.after ?? null
481
- })
482
- }
483
- });
484
- } catch (err) {
485
- console.error("[dyrected/audit] Failed to write audit log:", err);
486
- }
487
- }
488
- };
489
-
490
- // src/auth/password.ts
491
- import { promisify } from "util";
492
- import { scrypt, randomBytes, timingSafeEqual } from "crypto";
493
- var scryptAsync = promisify(scrypt);
494
- var SALT_LEN = 16;
495
- var KEY_LEN = 64;
496
- async function hashPassword(plain) {
497
- const salt = randomBytes(SALT_LEN).toString("hex");
498
- const derivedKey = await scryptAsync(plain, salt, KEY_LEN);
499
- return `${salt}:${derivedKey.toString("hex")}`;
500
- }
501
- async function verifyPassword(plain, stored) {
502
- const [salt, storedHash] = stored.split(":");
503
- if (!salt || !storedHash) return false;
504
- const derivedKey = await scryptAsync(plain, salt, KEY_LEN);
505
- const storedBuffer = Buffer.from(storedHash, "hex");
506
- if (derivedKey.length !== storedBuffer.length) return false;
507
- return timingSafeEqual(derivedKey, storedBuffer);
508
- }
509
-
510
- // src/controllers/collection.controller.ts
511
- var CollectionController = class {
512
- collection;
513
- constructor(collection) {
514
- this.collection = collection;
515
- }
516
- async find(c) {
517
- const config = c.get("config");
518
- const db = config.db;
519
- if (!db) return c.json({ message: "Database not configured" }, 500);
520
- const limit = Number(c.req.query("limit")) || 10;
521
- const page = Number(c.req.query("page")) || 1;
522
- const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 2;
523
- const sort = c.req.query("sort") || void 0;
524
- const user = c.get("user");
525
- let where = void 0;
526
- const whereRaw = c.req.query("where");
527
- if (whereRaw) {
528
- try {
529
- where = JSON.parse(decodeURIComponent(whereRaw));
530
- } catch {
531
- }
532
- }
533
- const beforeReadResult = await runCollectionHooks(this.collection.hooks?.beforeRead, {
534
- req: c.req,
535
- query: where,
536
- user
537
- });
538
- if (beforeReadResult !== void 0) {
539
- where = beforeReadResult;
540
- }
541
- let result = await db.find({
542
- collection: this.collection.slug,
543
- limit,
544
- page,
545
- sort,
546
- where
547
- });
548
- if (result.total === 0 && this.collection.initialData && !where && page === 1) {
549
- console.log(`[dyrected/core] Auto-seeding collection "${this.collection.slug}" from config.initialData`);
550
- for (const data of this.collection.initialData) {
551
- await db.create({ collection: this.collection.slug, data });
552
- }
553
- result = await db.find({
554
- collection: this.collection.slug,
555
- limit,
556
- page,
557
- sort,
558
- where
559
- });
560
- }
561
- result.docs = result.docs.map((doc) => DefaultsService.apply(this.collection.fields, doc));
562
- const processedDocs = [];
563
- for (const doc of result.docs) {
564
- const docWithCollectionHooks = await runCollectionHooks(this.collection.hooks?.afterRead, {
565
- doc,
566
- req: c.req,
567
- user
568
- });
569
- const docWithFieldHooks = await executeFieldAfterRead(this.collection.fields, docWithCollectionHooks, user);
570
- processedDocs.push(docWithFieldHooks);
571
- }
572
- result.docs = processedDocs;
573
- if (depth > 0) {
574
- const populationService = new PopulationService(db, config.collections);
575
- result = await populationService.populateResult(result, this.collection.fields, depth);
576
- }
577
- return c.json(result);
578
- }
579
- async findOne(c) {
580
- const config = c.get("config");
581
- const db = config.db;
582
- if (!db) return c.json({ message: "Database not configured" }, 500);
583
- const id = c.req.param("id");
584
- const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 10;
585
- const user = c.get("user");
586
- if (!id) return c.json({ message: "Missing ID" }, 400);
587
- const doc = await db.findOne({ collection: this.collection.slug, id });
588
- if (!doc) return c.json({ message: "Not Found" }, 404);
589
- const docWithDefaults = DefaultsService.apply(this.collection.fields, doc);
590
- const docWithCollectionHooks = await runCollectionHooks(this.collection.hooks?.afterRead, {
591
- doc: docWithDefaults,
592
- req: c.req,
593
- user
594
- });
595
- const docWithFieldHooks = await executeFieldAfterRead(this.collection.fields, docWithCollectionHooks, user);
596
- if (depth > 0 && docWithFieldHooks) {
597
- const populationService = new PopulationService(db, config.collections);
598
- const populatedDoc = await populationService.populate({
599
- data: docWithFieldHooks,
600
- fields: this.collection.fields,
601
- currentDepth: 0,
602
- maxDepth: depth
603
- });
604
- return c.json(populatedDoc);
605
- }
606
- return c.json(docWithFieldHooks);
607
- }
608
- async create(c) {
609
- const config = c.get("config");
610
- const db = config.db;
611
- if (!db) return c.json({ message: "Database not configured" }, 500);
612
- const contentType = c.req.header("Content-Type") || "";
613
- if (contentType.toLowerCase().includes("multipart/form-data")) {
614
- return this.upload(c);
615
- }
616
- const body = await c.req.json();
617
- const user = c.get("user");
618
- const now = (/* @__PURE__ */ new Date()).toISOString();
619
- let data = {
620
- ...body,
621
- createdAt: now,
622
- updatedAt: now,
623
- createdBy: user?.sub ?? null,
624
- updatedBy: user?.sub ?? null
625
- };
626
- if (this.collection.auth && data.password) {
627
- data.password = await hashPassword(data.password);
628
- }
629
- data = await executeFieldBeforeChange(this.collection.fields, data, null, user);
630
- data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
631
- data,
632
- req: c.req,
633
- user,
634
- operation: "create"
635
- });
636
- const doc = await db.create({ collection: this.collection.slug, data });
637
- if (this.collection.audit && db) {
638
- AuditService.log(db, {
639
- operation: "create",
640
- collection: this.collection.slug,
641
- documentId: doc.id,
642
- user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
643
- before: null,
644
- after: doc
645
- });
646
- }
647
- await runCollectionHooks(this.collection.hooks?.afterChange, {
648
- doc,
649
- user,
650
- req: c.req,
651
- operation: "create"
652
- });
653
- const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
654
- doc,
655
- req: c.req,
656
- user
657
- });
658
- const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user);
659
- return c.json(finalDoc, 201);
660
- }
661
- async upload(c) {
662
- const config = c.get("config");
663
- const storage = config.storage;
664
- if (!storage) return c.json({ message: "Storage not configured" }, 500);
665
- const formData = await c.req.formData();
666
- const file = formData.get("file");
667
- if (!file) return c.json({ message: "No file uploaded" }, 400);
668
- const buffer = new Uint8Array(await file.arrayBuffer());
669
- const siteId = c.get("siteId");
670
- const workspaceId = c.get("workspaceId");
671
- const prefix = workspaceId ? `${workspaceId}/${siteId}` : siteId;
672
- const fileData = await storage.upload({
673
- filename: file.name,
674
- buffer,
675
- mimeType: file.type,
676
- prefix
677
- });
678
- const otherData = {};
679
- formData.forEach((value, key) => {
680
- if (key !== "file" && typeof value === "string") {
681
- otherData[key] = value;
682
- }
683
- });
684
- const user = c.get("user");
685
- const now = (/* @__PURE__ */ new Date()).toISOString();
686
- let data = {
687
- ...otherData,
688
- ...fileData,
689
- createdAt: now,
690
- updatedAt: now,
691
- createdBy: user?.sub ?? null,
692
- updatedBy: user?.sub ?? null
693
- };
694
- data = await executeFieldBeforeChange(this.collection.fields, data, null, user);
695
- data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
696
- data,
697
- req: c.req,
698
- user,
699
- operation: "create"
700
- });
701
- const doc = await config.db.create({
702
- collection: this.collection.slug,
703
- data
704
- });
705
- await runCollectionHooks(this.collection.hooks?.afterChange, {
706
- doc,
707
- user,
708
- req: c.req,
709
- operation: "create"
710
- });
711
- const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
712
- doc,
713
- req: c.req,
714
- user
715
- });
716
- const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user);
717
- return c.json(finalDoc, 201);
718
- }
719
- async update(c) {
720
- const config = c.get("config");
721
- const db = config.db;
722
- if (!db) return c.json({ message: "Database not configured" }, 500);
723
- const id = c.req.param("id");
724
- if (!id) return c.json({ message: "Missing ID" }, 400);
725
- const body = await c.req.json();
726
- const user = c.get("user");
727
- let data = { ...body };
728
- if (this.collection.auth) {
729
- delete data.password;
730
- delete data.oldPassword;
731
- delete data.confirmPassword;
732
- }
733
- Object.assign(data, {
734
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
735
- updatedBy: user?.sub ?? null
736
- });
737
- const originalDoc = await db.findOne({ collection: this.collection.slug, id });
738
- if (!originalDoc) return c.json({ message: "Not Found" }, 404);
739
- let before = null;
740
- if (this.collection.audit) {
741
- before = originalDoc;
742
- }
743
- data = await executeFieldBeforeChange(this.collection.fields, data, originalDoc, user);
744
- data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
745
- data,
746
- doc: originalDoc,
747
- req: c.req,
748
- user,
749
- operation: "update"
750
- });
751
- const doc = await db.update({ collection: this.collection.slug, id, data });
752
- if (this.collection.audit && db) {
753
- AuditService.log(db, {
754
- operation: "update",
755
- collection: this.collection.slug,
756
- documentId: id,
757
- user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
758
- before,
759
- after: doc
760
- });
761
- }
762
- await runCollectionHooks(this.collection.hooks?.afterChange, {
763
- doc,
764
- previousDoc: originalDoc,
765
- user,
766
- req: c.req,
767
- operation: "update"
768
- });
769
- const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
770
- doc,
771
- req: c.req,
772
- user
773
- });
774
- const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user);
775
- return c.json(finalDoc);
776
- }
777
- /**
778
- * POST /api/collections/:slug/:id/change-password
779
- *
780
- * Dedicated endpoint for password changes. Requires the caller to supply:
781
- * { oldPassword, newPassword, confirmPassword }
782
- *
783
- * Rules:
784
- * - Only the account owner or an admin may change the password.
785
- * - Non-admin callers MUST provide a valid oldPassword.
786
- * - newPassword and confirmPassword must match.
787
- */
788
- async changePassword(c) {
789
- const config = c.get("config");
790
- const db = config.db;
791
- if (!db) return c.json({ message: "Database not configured" }, 500);
792
- if (!this.collection.auth) {
793
- return c.json({ message: "This collection does not support authentication" }, 400);
794
- }
795
- const id = c.req.param("id");
796
- if (!id) return c.json({ message: "Missing ID" }, 400);
797
- const user = c.get("user");
798
- if (!user) return c.json({ message: "Authentication required" }, 401);
799
- const body = await c.req.json().catch(() => null);
800
- const { oldPassword, newPassword, confirmPassword } = body ?? {};
801
- if (!newPassword) {
802
- return c.json({ message: "newPassword is required" }, 400);
803
- }
804
- if (newPassword !== confirmPassword) {
805
- return c.json({ message: "Passwords do not match" }, 400);
806
- }
807
- if (newPassword.length < 8) {
808
- return c.json({ message: "Password must be at least 8 characters" }, 400);
809
- }
810
- const isAdmin = Array.isArray(user.roles) && user.roles.includes("admin");
811
- const isSelf = user.sub === id;
812
- if (!isAdmin && !isSelf) {
813
- return c.json({ message: "You are not authorised to change this password" }, 403);
814
- }
815
- if (!isAdmin) {
816
- if (!oldPassword) {
817
- return c.json({ message: "Current password is required" }, 400);
818
- }
819
- const existing = await db.findOne({ collection: this.collection.slug, id });
820
- if (!existing) return c.json({ message: "User not found" }, 404);
821
- const valid = await verifyPassword(oldPassword, existing.password);
822
- if (!valid) {
823
- return c.json({ message: "Invalid current password" }, 400);
824
- }
825
- }
826
- const hashed = await hashPassword(newPassword);
827
- const doc = await db.update({
828
- collection: this.collection.slug,
829
- id,
830
- data: {
831
- password: hashed,
832
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
833
- updatedBy: user.sub
834
- }
835
- });
836
- if (this.collection.audit) {
837
- AuditService.log(db, {
838
- operation: "update",
839
- collection: this.collection.slug,
840
- documentId: id,
841
- user: { id: user.sub, collection: user.collection, email: user.email },
842
- before: null,
843
- after: { id }
844
- });
845
- }
846
- return c.json({ success: true, message: "Password updated successfully" });
847
- }
848
- async delete(c) {
849
- const config = c.get("config");
850
- const db = config.db;
851
- if (!db) return c.json({ message: "Database not configured" }, 500);
852
- const id = c.req.param("id");
853
- if (!id) return c.json({ message: "Missing ID" }, 400);
854
- const user = c.get("user");
855
- const doc = await db.findOne({ collection: this.collection.slug, id });
856
- if (!doc) return c.json({ message: "Not Found" }, 404);
857
- let before = null;
858
- if (this.collection.audit) {
859
- before = doc;
860
- }
861
- await runCollectionHooks(this.collection.hooks?.beforeDelete, {
862
- id,
863
- doc,
864
- user,
865
- req: c.req
866
- });
867
- await db.delete({ collection: this.collection.slug, id });
868
- if (this.collection.audit && db) {
869
- AuditService.log(db, {
870
- operation: "delete",
871
- collection: this.collection.slug,
872
- documentId: id,
873
- user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
874
- before,
875
- after: null
876
- });
877
- }
878
- await runCollectionHooks(this.collection.hooks?.afterDelete, {
879
- id,
880
- doc,
881
- user,
882
- req: c.req
883
- });
884
- return c.json({ message: "Deleted" });
885
- }
886
- async deleteMany(c) {
887
- const config = c.get("config");
888
- const db = config.db;
889
- if (!db) return c.json({ message: "Database not configured" }, 500);
890
- const user = c.get("user");
891
- let ids = [];
892
- try {
893
- const body = await c.req.json().catch(() => null);
894
- if (body?.ids && Array.isArray(body.ids)) {
895
- ids = body.ids;
896
- }
897
- } catch {
898
- }
899
- if (!ids.length) {
900
- const raw = c.req.queries("ids") ?? c.req.queries("ids[]") ?? [];
901
- ids = raw.filter(Boolean);
902
- }
903
- if (!ids.length) return c.json({ message: "No IDs provided" }, 400);
904
- const deleted = [];
905
- const failed = [];
906
- for (const id of ids) {
907
- try {
908
- const doc = await db.findOne({ collection: this.collection.slug, id });
909
- if (!doc) {
910
- failed.push({ id, error: "Not Found" });
911
- continue;
912
- }
913
- let before = null;
914
- if (this.collection.audit) {
915
- before = doc;
916
- }
917
- await runCollectionHooks(this.collection.hooks?.beforeDelete, {
918
- id,
919
- doc,
920
- user,
921
- req: c.req
922
- });
923
- await db.delete({ collection: this.collection.slug, id });
924
- deleted.push(id);
925
- if (this.collection.audit) {
926
- AuditService.log(db, {
927
- operation: "delete",
928
- collection: this.collection.slug,
929
- documentId: id,
930
- user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
931
- before,
932
- after: null
933
- });
934
- }
935
- await runCollectionHooks(this.collection.hooks?.afterDelete, {
936
- id,
937
- doc,
938
- user,
939
- req: c.req
940
- });
941
- } catch (err) {
942
- failed.push({ id, error: err?.message ?? "Unknown error" });
943
- }
944
- }
945
- return c.json({
946
- message: `Deleted ${deleted.length} document(s)`,
947
- deleted,
948
- ...failed.length ? { failed } : {}
949
- });
950
- }
951
- async seed(c) {
952
- const config = c.get("config");
953
- const db = config.db;
954
- if (!db) return c.json({ message: "Database not configured" }, 500);
955
- const body = await c.req.json();
956
- const initialData = body.data;
957
- if (!initialData || !Array.isArray(initialData)) {
958
- return c.json({ message: "Invalid initial data" }, 400);
959
- }
960
- const result = await db.find({ collection: this.collection.slug, limit: 1 });
961
- if (result.total > 0) {
962
- return c.json({ message: "Collection is not empty, skipping seed" });
963
- }
964
- console.log(`[dyrected/core] Auto-seeding collection: ${this.collection.slug}`);
965
- const createdDocs = [];
966
- for (const data of initialData) {
967
- const doc = await db.create({ collection: this.collection.slug, data });
968
- createdDocs.push(doc);
969
- }
970
- return c.json({ message: "Seed successful", count: createdDocs.length }, 201);
971
- }
972
- };
973
-
974
- // src/controllers/global.controller.ts
975
- var GlobalController = class {
976
- global;
977
- constructor(global) {
978
- this.global = global;
979
- }
980
- async get(c) {
981
- const config = c.get("config");
982
- const db = config.db;
983
- if (!db) return c.json({ message: "Database not configured" }, 500);
984
- const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 10;
985
- const user = c.get("user");
986
- let query = void 0;
987
- const beforeReadResult = await runCollectionHooks(this.global.hooks?.beforeRead, {
988
- req: c.req,
989
- query,
990
- user
991
- });
992
- if (beforeReadResult !== void 0) {
993
- query = beforeReadResult;
994
- }
995
- let data = await db.getGlobal({ slug: this.global.slug });
996
- const isEmpty = !data || Object.keys(data).length === 0;
997
- if (isEmpty && this.global.initialData) {
998
- console.log(`[dyrected/core] Auto-seeding global "${this.global.slug}" from config.initialData`);
999
- await db.updateGlobal({ slug: this.global.slug, data: this.global.initialData });
1000
- data = this.global.initialData;
1001
- }
1002
- const dataWithDefaults = DefaultsService.apply(this.global.fields, data);
1003
- const docWithCollectionHooks = await runCollectionHooks(this.global.hooks?.afterRead, {
1004
- doc: dataWithDefaults,
1005
- req: c.req,
1006
- user
1007
- });
1008
- const docWithFieldHooks = await executeFieldAfterRead(this.global.fields, docWithCollectionHooks, user);
1009
- if (depth > 0 && docWithFieldHooks) {
1010
- const populationService = new PopulationService(db, config.collections);
1011
- const populatedData = await populationService.populate({
1012
- data: docWithFieldHooks,
1013
- fields: this.global.fields,
1014
- currentDepth: 0,
1015
- maxDepth: depth
1016
- });
1017
- return c.json(populatedData);
1018
- }
1019
- return c.json(docWithFieldHooks);
1020
- }
1021
- async update(c) {
1022
- const db = c.get("config").db;
1023
- if (!db) return c.json({ message: "Database not configured" }, 500);
1024
- const body = await c.req.json();
1025
- const user = c.get("user");
1026
- const originalDoc = await db.getGlobal({ slug: this.global.slug }) || {};
1027
- let data = await executeFieldBeforeChange(this.global.fields, body, originalDoc, user);
1028
- data = await runCollectionHooks(this.global.hooks?.beforeChange, {
1029
- data,
1030
- doc: originalDoc,
1031
- req: c.req,
1032
- user,
1033
- operation: "update"
1034
- });
1035
- const updated = await db.updateGlobal({ slug: this.global.slug, data });
1036
- await runCollectionHooks(this.global.hooks?.afterChange, {
1037
- doc: updated,
1038
- previousDoc: originalDoc,
1039
- user,
1040
- req: c.req,
1041
- operation: "update"
1042
- });
1043
- const readDoc = await runCollectionHooks(this.global.hooks?.afterRead, {
1044
- doc: updated,
1045
- req: c.req,
1046
- user
1047
- });
1048
- const finalDoc = await executeFieldAfterRead(this.global.fields, readDoc, user);
1049
- return c.json(finalDoc);
1050
- }
1051
- async seed(c) {
1052
- const config = c.get("config");
1053
- const db = config.db;
1054
- if (!db) return c.json({ message: "Database not configured" }, 500);
1055
- const body = await c.req.json();
1056
- const initialData = body.data;
1057
- if (!initialData) {
1058
- return c.json({ message: "Invalid initial data" }, 400);
1059
- }
1060
- const existing = await db.getGlobal({ slug: this.global.slug });
1061
- if (existing && Object.keys(existing).length > 0) {
1062
- return c.json({ message: "Global is not empty, skipping seed" });
1063
- }
1064
- console.log(`[dyrected/core] Auto-seeding global: ${this.global.slug}`);
1065
- await db.updateGlobal({ slug: this.global.slug, data: initialData });
1066
- return c.json({ message: "Seed successful", data: initialData }, 201);
1067
- }
1068
- };
1069
-
1070
- // src/controllers/media.controller.ts
1071
- var MediaController = class {
1072
- collection;
1073
- constructor(collection = "media") {
1074
- this.collection = collection;
1075
- }
1076
- async upload(c) {
1077
- const config = c.get("config");
1078
- const storage = config.storage;
1079
- const imageService = config.image;
1080
- if (!storage) {
1081
- return c.json({ message: "Storage not configured" }, 500);
1082
- }
1083
- const body = await c.req.parseBody();
1084
- const file = body["file"];
1085
- const focalPointStr = body["focalPoint"];
1086
- const focalPoint = focalPointStr ? JSON.parse(focalPointStr) : void 0;
1087
- if (!file) {
1088
- return c.json({ message: "No file uploaded" }, 400);
1089
- }
1090
- const buffer = new Uint8Array(await file.arrayBuffer());
1091
- const siteId = c.get("siteId");
1092
- const workspaceId = c.get("workspaceId");
1093
- const prefix = workspaceId ? `${workspaceId}/${siteId}` : siteId || "default";
1094
- let imageMetadata = {};
1095
- let imageSizes = {};
1096
- if (imageService && file.type.startsWith("image/")) {
1097
- let colConfig = config.collections.find((col) => col.slug === this.collection);
1098
- if (!colConfig && config.onSchemaFetch && siteId) {
1099
- const dynamic = await config.onSchemaFetch(siteId);
1100
- colConfig = dynamic.collections?.find((col) => col.slug === this.collection);
1101
- }
1102
- try {
1103
- const processed = await imageService.process({
1104
- buffer,
1105
- mimeType: file.type,
1106
- config: colConfig?.upload,
1107
- focalPoint
1108
- });
1109
- imageMetadata = processed.metadata;
1110
- imageSizes = processed.sizes;
1111
- } catch (err) {
1112
- console.error("[MediaController] Image processing failed:", err);
1113
- }
1114
- }
1115
- const fileData = await storage.upload({
1116
- filename: file.name,
1117
- buffer,
1118
- mimeType: file.type,
1119
- prefix
1120
- });
1121
- const finalFileData = {
1122
- ...fileData,
1123
- ...imageMetadata,
1124
- focalPoint,
1125
- sizes: {}
1126
- };
1127
- if (imageSizes) {
1128
- for (const [sizeName, sizeData] of Object.entries(imageSizes)) {
1129
- const ext = file.name.split(".").pop();
1130
- const baseName = file.name.substring(0, file.name.lastIndexOf("."));
1131
- const sizeFilename = `${baseName}-${sizeName}.${ext}`;
1132
- try {
1133
- const sizeFileData = await storage.upload({
1134
- filename: sizeFilename,
1135
- buffer: sizeData.buffer,
1136
- mimeType: file.type,
1137
- prefix
1138
- });
1139
- finalFileData.sizes[sizeName] = {
1140
- ...sizeFileData,
1141
- width: sizeData.width,
1142
- height: sizeData.height
1143
- };
1144
- } catch (err) {
1145
- console.error(`[MediaController] Failed to upload size ${sizeName}:`, err);
1146
- }
1147
- }
1148
- }
1149
- const db = config.db;
1150
- if (!db) return c.json({ message: "Database not configured" }, 500);
1151
- const doc = await db.create({
1152
- collection: this.collection,
1153
- data: finalFileData
1154
- });
1155
- return c.json(doc, 201);
1156
- }
1157
- async find(c) {
1158
- const db = c.get("config").db;
1159
- if (!db) return c.json({ message: "Database not configured" }, 500);
1160
- const limit = Number(c.req.query("limit")) || 10;
1161
- const page = Number(c.req.query("page")) || 1;
1162
- const result = await db.find({
1163
- collection: this.collection,
1164
- limit,
1165
- page
1166
- });
1167
- return c.json(result);
1168
- }
1169
- async delete(c) {
1170
- const config = c.get("config");
1171
- const storage = config.storage;
1172
- const db = config.db;
1173
- if (!db) return c.json({ message: "Database not configured" }, 500);
1174
- const id = c.req.param("id");
1175
- if (!id) return c.json({ message: "Missing ID" }, 400);
1176
- const doc = await db.findOne({ collection: this.collection, id });
1177
- if (!doc) return c.json({ message: "Not Found" }, 404);
1178
- if (storage) {
1179
- await storage.delete({ filename: doc.filename });
1180
- if (doc.sizes) {
1181
- for (const size of Object.values(doc.sizes)) {
1182
- if (size.filename) {
1183
- await storage.delete({ filename: size.filename });
1184
- }
1185
- }
1186
- }
1187
- }
1188
- await db.delete({ collection: this.collection, id });
1189
- return c.json({ message: "Deleted" });
1190
- }
1191
- async serve(c) {
1192
- const config = c.get("config");
1193
- const storage = config.storage;
1194
- if (!storage || !storage.resolve) {
1195
- return c.json({ message: "Storage not configured for serving" }, 404);
1196
- }
1197
- const filename = c.req.param("filename");
1198
- if (!filename) return c.json({ message: "Missing filename" }, 400);
1199
- let res = await storage.resolve({ filename });
1200
- if (!res && !filename.includes("/")) {
1201
- res = await storage.resolve({ filename: `default/${filename}` });
1202
- }
1203
- if (!res) return c.json({ message: "Not Found" }, 404);
1204
- c.header("Content-Type", res.mimeType);
1205
- return c.body(res.buffer);
1206
- }
1207
- };
1208
-
1209
- // src/auth/token.ts
1210
- import { SignJWT, jwtVerify, decodeJwt } from "jose";
1211
- import { TextEncoder } from "util";
1212
- function getSecret() {
1213
- const secret = process.env.DYRECTED_JWT_SECRET || process.env.JWT_SECRET;
1214
- if (!secret) {
1215
- throw new Error(
1216
- "[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
1217
- );
1218
- }
1219
- return new TextEncoder().encode(secret);
1220
- }
1221
- var DEFAULT_EXPIRY = "7d";
1222
- async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
1223
- return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
1224
- }
1225
- async function verifyCollectionToken(token) {
1226
- const { payload } = await jwtVerify(token, getSecret());
1227
- return payload;
1228
- }
1229
-
1230
- // src/services/email.service.ts
1231
- var _devSend = null;
1232
- var _devSendPromise = null;
1233
- async function getDevSend() {
1234
- if (_devSend) return _devSend;
1235
- if (_devSendPromise) return _devSendPromise;
1236
- _devSendPromise = (async () => {
1237
- try {
1238
- const nodemailer = await import("nodemailer");
1239
- const account = await nodemailer.default.createTestAccount();
1240
- const transport = nodemailer.default.createTransport({
1241
- host: "smtp.ethereal.email",
1242
- port: 587,
1243
- auth: { user: account.user, pass: account.pass }
1244
- });
1245
- console.log("[dyrected/core] No email config \u2014 using Ethereal for dev email preview.");
1246
- console.log(`[dyrected/core] Ethereal login: https://ethereal.email user: ${account.user} pass: ${account.pass}`);
1247
- _devSend = async ({ to, subject, html }) => {
1248
- const info = await transport.sendMail({ from: '"Dyrected Dev" <dev@dyrected.local>', to, subject, html });
1249
- console.log(`[dyrected/core] Email preview URL: ${nodemailer.default.getTestMessageUrl(info)}`);
1250
- };
1251
- return _devSend;
1252
- } catch {
1253
- console.warn("[dyrected/core] nodemailer not available \u2014 emails will not be sent in dev.");
1254
- return null;
1255
- }
1256
- })();
1257
- return _devSendPromise;
1258
- }
1259
- async function sendEmail(config, payload) {
1260
- if (config.email) {
1261
- await config.email.send(payload);
1262
- return;
1263
- }
1264
- if (process.env.NODE_ENV !== "production") {
1265
- const devSend = await getDevSend();
1266
- await devSend?.(payload);
1267
- }
1268
- }
1269
- function buildWelcomeEmail(config, args) {
1270
- const custom = config.email?.templates?.welcome?.(args);
1271
- return {
1272
- subject: custom?.subject ?? "Welcome \u2014 your account is ready",
1273
- html: custom?.html ?? `
1274
- <div style="font-family:sans-serif;max-width:600px;margin:0 auto">
1275
- <h2>Welcome!</h2>
1276
- <p>Your account has been created. You can now log in with:</p>
1277
- <p><strong>${args.email}</strong></p>
1278
- </div>`
1279
- };
1280
- }
1281
- function buildInviteEmail(config, args) {
1282
- const custom = config.email?.templates?.invite?.(args);
1283
- return {
1284
- subject: custom?.subject ?? "You've been invited",
1285
- html: custom?.html ?? `
1286
- <div style="font-family:sans-serif;max-width:600px;margin:0 auto">
1287
- <h2>You've been invited</h2>
1288
- ${args.invitedByEmail ? `<p>Invited by <strong>${args.invitedByEmail}</strong>.</p>` : ""}
1289
- <p>Use the token below to accept your invitation. It expires in 7 days.</p>
1290
- <pre style="background:#f4f4f4;padding:12px;border-radius:4px;word-break:break-all">${args.token}</pre>
1291
- </div>`
1292
- };
1293
- }
1294
- function buildResetPasswordEmail(config, args) {
1295
- const custom = config.email?.templates?.resetPassword?.(args);
1296
- return {
1297
- subject: custom?.subject ?? "Reset your password",
1298
- html: custom?.html ?? `
1299
- <div style="font-family:sans-serif;max-width:600px;margin:0 auto">
1300
- <h2>Reset your password</h2>
1301
- <p>Use the token below to reset your password. It expires in 1 hour.</p>
1302
- <pre style="background:#f4f4f4;padding:12px;border-radius:4px;word-break:break-all">${args.token}</pre>
1303
- </div>`
1304
- };
1305
- }
1306
- function buildPasswordChangedEmail(config, args) {
1307
- const custom = config.email?.templates?.passwordChanged?.(args);
1308
- return {
1309
- subject: custom?.subject ?? "Your password has been changed",
1310
- html: custom?.html ?? `
1311
- <div style="font-family:sans-serif;max-width:600px;margin:0 auto">
1312
- <h2>Password changed</h2>
1313
- <p>The password for <strong>${args.email}</strong> was just changed.</p>
1314
- <p>If you did not make this change, please contact support immediately.</p>
1315
- </div>`
1316
- };
1317
- }
1318
-
1319
- // src/controllers/auth.controller.ts
1320
- var AuthController = class {
1321
- collection;
1322
- constructor(collection) {
1323
- this.collection = collection;
1324
- }
1325
- // ---------------------------------------------------------------------------
1326
- // GET /init
1327
- // Checks if the first user needs to be created.
1328
- // ---------------------------------------------------------------------------
1329
- async init(c) {
1330
- const db = c.get("config").db;
1331
- if (!db) return c.json({ message: "Database not configured" }, 500);
1332
- const result = await db.find({
1333
- collection: this.collection.slug,
1334
- limit: 1
1335
- });
1336
- return c.json({
1337
- initialized: result.total > 0
1338
- });
1339
- }
1340
- // ---------------------------------------------------------------------------
1341
- // POST /first-user
1342
- // Creates the first user if none exist.
1343
- // ---------------------------------------------------------------------------
1344
- async registerFirstUser(c) {
1345
- const config = c.get("config");
1346
- const db = config.db;
1347
- if (!db) return c.json({ message: "Database not configured" }, 500);
1348
- const check = await db.find({
1349
- collection: this.collection.slug,
1350
- limit: 1
1351
- });
1352
- if (check.total > 0) {
1353
- return c.json({ error: true, message: "Initial user already exists." }, 403);
1354
- }
1355
- const body = await c.req.json().catch(() => null);
1356
- if (!body?.email || !body?.password) {
1357
- return c.json({ error: true, message: "email and password are required." }, 400);
1358
- }
1359
- const hashedPassword = await hashPassword(body.password);
1360
- const user = await db.create({
1361
- collection: this.collection.slug,
1362
- data: {
1363
- ...body,
1364
- password: hashedPassword,
1365
- roles: ["admin"]
1366
- // Default first user to admin
1367
- }
1368
- });
1369
- const token = await signCollectionToken({
1370
- sub: user.id,
1371
- email: user.email,
1372
- collection: this.collection.slug
1373
- });
1374
- const { subject, html } = buildWelcomeEmail(config, { email: body.email });
1375
- sendEmail(config, { to: body.email, subject, html }).catch(
1376
- (err) => console.error("[dyrected/core] Failed to send welcome email:", err)
1377
- );
1378
- const { password: _, ...safeUser } = user;
1379
- return c.json({ token, user: safeUser });
1380
- }
1381
- // ---------------------------------------------------------------------------
1382
- // POST /login
1383
- // ---------------------------------------------------------------------------
1384
- async login(c) {
1385
- const db = c.get("config").db;
1386
- if (!db) return c.json({ message: "Database not configured" }, 500);
1387
- const body = await c.req.json().catch(() => null);
1388
- if (!body?.email || !body?.password) {
1389
- return c.json({ error: true, message: "email and password are required." }, 400);
1390
- }
1391
- const result = await db.find({
1392
- collection: this.collection.slug,
1393
- where: { email: body.email },
1394
- limit: 1
1395
- });
1396
- const user = result.docs[0];
1397
- if (!user) {
1398
- return c.json({ error: true, message: "Invalid email or password." }, 401);
1399
- }
1400
- const valid = await verifyPassword(body.password, user.password);
1401
- if (!valid) {
1402
- return c.json({ error: true, message: "Invalid email or password." }, 401);
1403
- }
1404
- const token = await signCollectionToken({
1405
- sub: user.id,
1406
- email: user.email,
1407
- collection: this.collection.slug
1408
- });
1409
- const { password: _, ...safeUser } = user;
1410
- return c.json({ token, user: safeUser });
1411
- }
1412
- // ---------------------------------------------------------------------------
1413
- // POST /logout
1414
- // Auth collections use stateless JWTs — logout is handled client-side.
1415
- // This endpoint exists so clients have a consistent API surface.
1416
- // ---------------------------------------------------------------------------
1417
- async logout(c) {
1418
- return c.json({ success: true, message: "Logged out. Discard your token." });
1419
- }
1420
- // ---------------------------------------------------------------------------
1421
- // GET /me
1422
- // ---------------------------------------------------------------------------
1423
- async me(c) {
1424
- const db = c.get("config").db;
1425
- if (!db) return c.json({ message: "Database not configured" }, 500);
1426
- const requestUser = c.get("user");
1427
- if (!requestUser) {
1428
- return c.json({ error: true, message: "Authentication required." }, 401);
1429
- }
1430
- const user = await db.findOne({ collection: this.collection.slug, id: requestUser.sub });
1431
- if (!user) {
1432
- return c.json({ error: true, message: "User not found." }, 404);
1433
- }
1434
- const { password: _, ...safeUser } = user;
1435
- return c.json(safeUser);
1436
- }
1437
- // ---------------------------------------------------------------------------
1438
- // POST /refresh-token
1439
- // ---------------------------------------------------------------------------
1440
- async refreshToken(c) {
1441
- const requestUser = c.get("user");
1442
- if (!requestUser) {
1443
- return c.json({ error: true, message: "Authentication required." }, 401);
1444
- }
1445
- const token = await signCollectionToken({
1446
- sub: requestUser.sub,
1447
- email: requestUser.email,
1448
- collection: this.collection.slug
1449
- });
1450
- return c.json({ token });
1451
- }
1452
- // ---------------------------------------------------------------------------
1453
- // POST /forgot-password
1454
- // Requires config.email to be set. Silently succeeds if email not found
1455
- // to prevent email enumeration.
1456
- // ---------------------------------------------------------------------------
1457
- async forgotPassword(c) {
1458
- const config = c.get("config");
1459
- const db = config.db;
1460
- if (!db) return c.json({ message: "Database not configured" }, 500);
1461
- const body = await c.req.json().catch(() => null);
1462
- if (!body?.email) {
1463
- return c.json({ error: true, message: "email is required." }, 400);
1464
- }
1465
- const result = await db.find({
1466
- collection: this.collection.slug,
1467
- where: { email: body.email },
1468
- limit: 1
1469
- });
1470
- const user = result.docs[0];
1471
- if (user) {
1472
- const resetToken = await signCollectionToken(
1473
- { sub: user.id, email: user.email, collection: this.collection.slug, purpose: "reset" },
1474
- "1h"
1475
- );
1476
- try {
1477
- const { subject, html } = buildResetPasswordEmail(config, { token: resetToken });
1478
- await sendEmail(config, { to: user.email, subject, html });
1479
- } catch (err) {
1480
- console.error("[dyrected/core] Failed to send password reset email:", err);
1481
- }
1482
- }
1483
- return c.json({
1484
- success: true,
1485
- message: "If an account with that email exists, a reset link has been sent."
1486
- });
1487
- }
1488
- // ---------------------------------------------------------------------------
1489
- // POST /reset-password
1490
- // Expects { token: string, password: string } in body.
1491
- // The token is the reset JWT issued by /forgot-password.
1492
- // ---------------------------------------------------------------------------
1493
- async resetPassword(c) {
1494
- const config = c.get("config");
1495
- const db = config.db;
1496
- if (!db) return c.json({ message: "Database not configured" }, 500);
1497
- const body = await c.req.json().catch(() => null);
1498
- if (!body?.token || !body?.password) {
1499
- return c.json({ error: true, message: "token and password are required." }, 400);
1500
- }
1501
- let payload;
1502
- try {
1503
- payload = await verifyCollectionToken(body.token);
1504
- } catch {
1505
- return c.json({ error: true, message: "Reset token is invalid or has expired." }, 400);
1506
- }
1507
- if (payload.collection !== this.collection.slug || payload.purpose !== "reset") {
1508
- return c.json({ error: true, message: "Reset token is invalid or has expired." }, 400);
1509
- }
1510
- const hashedPassword = await hashPassword(body.password);
1511
- await db.update({
1512
- collection: this.collection.slug,
1513
- id: payload.sub,
1514
- data: { password: hashedPassword }
1515
- });
1516
- const { subject, html } = buildPasswordChangedEmail(config, { email: payload.email });
1517
- sendEmail(config, { to: payload.email, subject, html }).catch(
1518
- (err) => console.error("[dyrected/core] Failed to send password-changed email:", err)
1519
- );
1520
- return c.json({ success: true, message: "Password has been reset. You can now log in." });
1521
- }
1522
- // ---------------------------------------------------------------------------
1523
- // POST /invite
1524
- // Requires auth. Issues a signed invite token and emails it to the invitee.
1525
- // ---------------------------------------------------------------------------
1526
- async invite(c) {
1527
- const config = c.get("config");
1528
- const db = config.db;
1529
- if (!db) return c.json({ message: "Database not configured" }, 500);
1530
- const requestUser = c.get("user");
1531
- if (!requestUser) {
1532
- return c.json({ error: true, message: "Authentication required." }, 401);
1533
- }
1534
- const body = await c.req.json().catch(() => null);
1535
- if (!body?.email) {
1536
- return c.json({ error: true, message: "email is required." }, 400);
1537
- }
1538
- const existing = await db.find({
1539
- collection: this.collection.slug,
1540
- where: { email: body.email },
1541
- limit: 1
1542
- });
1543
- if (existing.total > 0) {
1544
- return c.json({ error: true, message: "An account with that email already exists." }, 409);
1545
- }
1546
- const inviteToken = await signCollectionToken(
1547
- { sub: body.email, email: body.email, collection: this.collection.slug, purpose: "invite" },
1548
- "7d"
1549
- );
1550
- try {
1551
- const { subject, html } = buildInviteEmail(config, {
1552
- token: inviteToken,
1553
- invitedByEmail: requestUser.email
1554
- });
1555
- await sendEmail(config, { to: body.email, subject, html });
1556
- } catch (err) {
1557
- console.error("[dyrected/core] Failed to send invite email:", err);
1558
- }
1559
- return c.json({ success: true, message: `Invite sent to ${body.email}.` });
1560
- }
1561
- // ---------------------------------------------------------------------------
1562
- // POST /accept-invite
1563
- // Public. Validates the invite token and creates the user account.
1564
- // Body: { token, password, ...extraFields }
1565
- // ---------------------------------------------------------------------------
1566
- async acceptInvite(c) {
1567
- const config = c.get("config");
1568
- const db = config.db;
1569
- if (!db) return c.json({ message: "Database not configured" }, 500);
1570
- const body = await c.req.json().catch(() => null);
1571
- if (!body?.token || !body?.password) {
1572
- return c.json({ error: true, message: "token and password are required." }, 400);
1573
- }
1574
- let payload;
1575
- try {
1576
- payload = await verifyCollectionToken(body.token);
1577
- } catch {
1578
- return c.json({ error: true, message: "Invite token is invalid or has expired." }, 400);
1579
- }
1580
- if (payload.collection !== this.collection.slug || payload.purpose !== "invite") {
1581
- return c.json({ error: true, message: "Invite token is invalid or has expired." }, 400);
1582
- }
1583
- const inviteeEmail = payload.sub;
1584
- const existing = await db.find({
1585
- collection: this.collection.slug,
1586
- where: { email: inviteeEmail },
1587
- limit: 1
1588
- });
1589
- if (existing.total > 0) {
1590
- return c.json({ error: true, message: "An account with that email already exists." }, 409);
1591
- }
1592
- const { token: _t, password: _p, ...extraFields } = body;
1593
- const hashedPassword = await hashPassword(body.password);
1594
- const user = await db.create({
1595
- collection: this.collection.slug,
1596
- data: { ...extraFields, email: inviteeEmail, password: hashedPassword }
1597
- });
1598
- const sessionToken = await signCollectionToken({
1599
- sub: user.id,
1600
- email: inviteeEmail,
1601
- collection: this.collection.slug
1602
- });
1603
- const { subject, html } = buildWelcomeEmail(config, { email: inviteeEmail });
1604
- sendEmail(config, { to: inviteeEmail, subject, html }).catch(
1605
- (err) => console.error("[dyrected/core] Failed to send welcome email:", err)
1606
- );
1607
- const { password: _, ...safeUser } = user;
1608
- return c.json({ token: sessionToken, user: safeUser }, 201);
1609
- }
1610
- };
1611
-
1612
- // src/controllers/preview.controller.ts
1613
- import { SignJWT as SignJWT2, jwtVerify as jwtVerify2 } from "jose";
1614
- import { TextEncoder as TextEncoder2 } from "util";
1615
- var PreviewController = class {
1616
- getSecret() {
1617
- const secret = process.env.DYRECTED_JWT_SECRET || process.env.JWT_SECRET || "dyrected-preview-secret-change-me";
1618
- return new TextEncoder2().encode(secret);
1619
- }
1620
- /**
1621
- * POST /api/preview-token
1622
- * Generates a short-lived token for previewing unsaved data.
1623
- */
1624
- async createToken(c) {
1625
- const body = await c.req.json().catch(() => null);
1626
- if (!body?.collectionSlug || !body?.data) {
1627
- return c.json({ error: true, message: "collectionSlug and data are required." }, 400);
1628
- }
1629
- const token = await new SignJWT2({
1630
- collectionSlug: body.collectionSlug,
1631
- documentId: body.documentId,
1632
- data: body.data
1633
- }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("15m").sign(this.getSecret());
1634
- const expiresAt = new Date(Date.now() + 15 * 60 * 1e3).toISOString();
1635
- return c.json({ token, expiresAt });
1636
- }
1637
- /**
1638
- * GET /api/preview-data?token=<jwt>
1639
- * Returns the data stored in the preview token.
1640
- */
1641
- async getData(c) {
1642
- const token = c.req.query("token");
1643
- if (!token) {
1644
- return c.json({ error: true, message: "token query parameter is required." }, 400);
1645
- }
1646
- try {
1647
- const { payload } = await jwtVerify2(token, this.getSecret());
1648
- return c.json(payload);
1649
- } catch (err) {
1650
- return c.json({ error: true, message: "Invalid or expired preview token." }, 401);
1651
- }
1652
- }
1653
- };
1654
-
1655
- // src/middleware/auth.ts
1656
- function requireAuth() {
1657
- return async (c, next) => {
1658
- const authHeader = c.req.header("Authorization");
1659
- const token = authHeader?.replace(/^Bearer\s+/i, "");
1660
- if (!token) {
1661
- return c.json({ error: true, message: "Authentication required." }, 401);
1662
- }
1663
- try {
1664
- const user = await verifyCollectionToken(token);
1665
- c.set("user", user);
1666
- await next();
1667
- } catch {
1668
- return c.json({ error: true, message: "Invalid or expired token." }, 401);
1669
- }
1670
- };
1671
- }
1672
- function optionalAuth() {
1673
- return async (c, next) => {
1674
- const authHeader = c.req.header("Authorization");
1675
- const token = authHeader?.replace(/^Bearer\s+/i, "");
1676
- if (token) {
1677
- try {
1678
- const user = await verifyCollectionToken(token);
1679
- c.set("user", user);
1680
- } catch {
1681
- }
1682
- }
1683
- await next();
1684
- };
1685
- }
1686
-
1687
- // src/utils/openapi.ts
1688
- function generateOpenApi(config) {
1689
- const spec = {
1690
- openapi: "3.0.0",
1691
- info: {
1692
- title: "Dyrected API",
1693
- version: "1.0.0",
1694
- description: "Automatically generated OpenAPI specification for the Dyrected project."
1695
- },
1696
- components: {
1697
- schemas: {},
1698
- securitySchemes: {
1699
- ApiKeyAuth: {
1700
- type: "apiKey",
1701
- in: "header",
1702
- name: "x-api-key"
1703
- }
1704
- }
1705
- },
1706
- paths: {},
1707
- security: [{ ApiKeyAuth: [] }]
1708
- };
1709
- for (const collection of config.collections) {
1710
- spec.components.schemas[collection.slug] = collectionToSchema(collection);
1711
- }
1712
- for (const global of config.globals) {
1713
- spec.components.schemas[global.slug] = globalToSchema(global);
1714
- }
1715
- for (const collection of config.collections) {
1716
- const slug = collection.slug;
1717
- const path = `/api/collections/${slug}`;
1718
- const labels = collection.labels || { singular: slug, plural: `${slug}s` };
1719
- spec.paths[path] = {
1720
- get: {
1721
- tags: ["Collections"],
1722
- summary: `Find ${labels.plural}`,
1723
- parameters: [
1724
- { name: "limit", in: "query", schema: { type: "integer", default: 10 } },
1725
- { name: "page", in: "query", schema: { type: "integer", default: 1 } },
1726
- { name: "where", in: "query", schema: { type: "string" }, description: "JSON filter" },
1727
- { name: "sort", in: "query", schema: { type: "string" }, description: "Sort field (e.g. -createdAt)" }
1728
- ],
1729
- responses: {
1730
- 200: {
1731
- description: "Success",
1732
- content: {
1733
- "application/json": {
1734
- schema: {
1735
- type: "object",
1736
- properties: {
1737
- docs: { type: "array", items: { $ref: `#/components/schemas/${slug}` } },
1738
- total: { type: "integer" },
1739
- limit: { type: "integer" },
1740
- page: { type: "integer" }
1741
- }
1742
- }
1743
- }
1744
- }
1745
- }
1746
- }
1747
- },
1748
- post: {
1749
- tags: ["Collections"],
1750
- summary: `Create ${labels.singular}`,
1751
- requestBody: {
1752
- required: true,
1753
- content: {
1754
- "application/json": {
1755
- schema: { $ref: `#/components/schemas/${slug}` }
1756
- }
1757
- }
1758
- },
1759
- responses: {
1760
- 201: {
1761
- description: "Created",
1762
- content: {
1763
- "application/json": {
1764
- schema: { $ref: `#/components/schemas/${slug}` }
1765
- }
1766
- }
1767
- }
1768
- }
1769
- }
1770
- };
1771
- spec.paths[`${path}/{id}`] = {
1772
- get: {
1773
- tags: ["Collections"],
1774
- summary: `Get a single ${labels.singular}`,
1775
- parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
1776
- responses: {
1777
- 200: {
1778
- description: "Success",
1779
- content: {
1780
- "application/json": {
1781
- schema: { $ref: `#/components/schemas/${slug}` }
1782
- }
1783
- }
1784
- }
1785
- }
1786
- },
1787
- patch: {
1788
- tags: ["Collections"],
1789
- summary: `Update ${labels.singular}`,
1790
- parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
1791
- requestBody: {
1792
- required: true,
1793
- content: {
1794
- "application/json": {
1795
- schema: { $ref: `#/components/schemas/${slug}` }
1796
- }
1797
- }
1798
- },
1799
- responses: {
1800
- 200: {
1801
- description: "Updated",
1802
- content: {
1803
- "application/json": {
1804
- schema: { $ref: `#/components/schemas/${slug}` }
1805
- }
1806
- }
1807
- }
1808
- }
1809
- },
1810
- delete: {
1811
- tags: ["Collections"],
1812
- summary: `Delete ${labels.singular}`,
1813
- parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
1814
- responses: {
1815
- 204: { description: "Deleted" }
1816
- }
1817
- }
1818
- };
1819
- }
1820
- for (const global of config.globals) {
1821
- const slug = global.slug;
1822
- const path = `/api/globals/${slug}`;
1823
- spec.paths[path] = {
1824
- get: {
1825
- tags: ["Globals"],
1826
- summary: `Get ${global.label || slug}`,
1827
- responses: {
1828
- 200: {
1829
- description: "Success",
1830
- content: {
1831
- "application/json": {
1832
- schema: { $ref: `#/components/schemas/${slug}` }
1833
- }
1834
- }
1835
- }
1836
- }
1837
- },
1838
- patch: {
1839
- tags: ["Globals"],
1840
- summary: `Update ${global.label || slug}`,
1841
- requestBody: {
1842
- required: true,
1843
- content: {
1844
- "application/json": {
1845
- schema: { $ref: `#/components/schemas/${slug}` }
1846
- }
1847
- }
1848
- },
1849
- responses: {
1850
- 200: {
1851
- description: "Updated",
1852
- content: {
1853
- "application/json": {
1854
- schema: { $ref: `#/components/schemas/${slug}` }
1855
- }
1856
- }
1857
- }
1858
- }
1859
- }
1860
- };
1861
- }
1862
- if (config.storage) {
1863
- spec.paths["/api/media"] = {
1864
- get: {
1865
- tags: ["Media"],
1866
- summary: "List Media",
1867
- responses: {
1868
- 200: {
1869
- description: "Success",
1870
- content: {
1871
- "application/json": {
1872
- schema: {
1873
- type: "object",
1874
- properties: {
1875
- docs: { type: "array", items: { type: "object", additionalProperties: true } }
1876
- }
1877
- }
1878
- }
1879
- }
1880
- }
1881
- }
1882
- },
1883
- post: {
1884
- tags: ["Media"],
1885
- summary: "Upload Media",
1886
- requestBody: {
1887
- content: {
1888
- "multipart/form-data": {
1889
- schema: {
1890
- type: "object",
1891
- properties: {
1892
- file: { type: "string", format: "binary" }
1893
- }
1894
- }
1895
- }
1896
- }
1897
- },
1898
- responses: {
1899
- 201: { description: "Uploaded" }
1900
- }
1901
- }
1902
- };
1903
- }
1904
- return spec;
1905
- }
1906
- function collectionToSchema(collection) {
1907
- const { properties, required } = fieldsToProperties(collection.fields);
1908
- return {
1909
- type: "object",
1910
- properties: {
1911
- id: { type: "string" },
1912
- createdAt: { type: "string", format: "date-time" },
1913
- updatedAt: { type: "string", format: "date-time" },
1914
- ...properties
1915
- },
1916
- required: ["id", ...required]
1917
- };
1918
- }
1919
- function globalToSchema(global) {
1920
- const { properties, required } = fieldsToProperties(global.fields);
1921
- return {
1922
- type: "object",
1923
- properties,
1924
- required
1925
- };
1926
- }
1927
- function fieldsToProperties(fields) {
1928
- const props = {};
1929
- const required = [];
1930
- for (const field of fields) {
1931
- if (!field.name || field.type === "join" || field.type === "row") continue;
1932
- props[field.name] = fieldToSchema(field);
1933
- if (field.required) {
1934
- required.push(field.name);
1935
- }
1936
- }
1937
- return { properties: props, required };
1938
- }
1939
- function fieldToSchema(field) {
1940
- let schema = {};
1941
- switch (field.type) {
1942
- case "text":
1943
- case "textarea":
1944
- case "email":
1945
- case "url":
1946
- schema = { type: "string" };
1947
- break;
1948
- case "number":
1949
- schema = { type: "number" };
1950
- break;
1951
- case "boolean":
1952
- schema = { type: "boolean" };
1953
- break;
1954
- case "date":
1955
- schema = { type: "string", format: "date-time" };
1956
- break;
1957
- case "select":
1958
- schema = { type: "string", enum: field.options?.map((o) => typeof o === "string" ? o : o.value) };
1959
- break;
1960
- case "multiSelect":
1961
- schema = {
1962
- type: "array",
1963
- items: { type: "string", enum: field.options?.map((o) => typeof o === "string" ? o : o.value) }
1964
- };
1965
- break;
1966
- case "relationship":
1967
- schema = { type: "string", description: `ID of a ${field.relationTo} record` };
1968
- break;
1969
- case "object": {
1970
- const { properties, required } = fieldsToProperties(field.fields || []);
1971
- schema = { type: "object", properties, required };
1972
- break;
1973
- }
1974
- case "array": {
1975
- const { properties, required } = fieldsToProperties(field.fields || []);
1976
- schema = { type: "array", items: { type: "object", properties, required } };
1977
- break;
1978
- }
1979
- case "json":
1980
- case "richText":
1981
- schema = { type: "object", additionalProperties: true };
1982
- break;
1983
- case "blocks":
1984
- schema = {
1985
- type: "array",
1986
- items: {
1987
- oneOf: field.blocks?.map((block) => {
1988
- const { properties, required } = fieldsToProperties(block.fields);
1989
- return {
1990
- type: "object",
1991
- properties: {
1992
- blockType: { type: "string", enum: [block.slug] },
1993
- ...properties
1994
- },
1995
- required: ["blockType", ...required]
1996
- };
1997
- })
1998
- }
1999
- };
2000
- break;
2001
- default:
2002
- schema = { type: "string" };
2003
- }
2004
- if (field.label) schema.description = field.label;
2005
- return schema;
2006
- }
2007
-
2008
- // src/utils/swagger.ts
2009
- function getSwaggerHtml(specUrl = "/api/openapi.json") {
2010
- return `
2011
- <!DOCTYPE html>
2012
- <html lang="en">
2013
- <head>
2014
- <meta charset="utf-8" />
2015
- <meta name="viewport" content="width=device-width, initial-scale=1" />
2016
- <meta name="description" content="SwaggerUI" />
2017
- <title>Dyrected API Documentation</title>
2018
- <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui.css" />
2019
- </head>
2020
- <body>
2021
- <div id="swagger-ui"></div>
2022
- <script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-bundle.js" charset="UTF-8"></script>
2023
- <script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-standalone-preset.js" charset="UTF-8"></script>
2024
- <script>
2025
- window.onload = () => {
2026
- // Forward the apikey query param when loading the spec and making API calls
2027
- const params = new URLSearchParams(window.location.search);
2028
- const apiKey = params.get('apikey');
2029
- const specUrlWithKey = apiKey ? '${specUrl}?apikey=' + encodeURIComponent(apiKey) : '${specUrl}';
2030
-
2031
- window.ui = SwaggerUIBundle({
2032
- url: specUrlWithKey,
2033
- dom_id: '#swagger-ui',
2034
- presets: [
2035
- SwaggerUIBundle.presets.apis,
2036
- SwaggerUIStandalonePreset
2037
- ],
2038
- layout: "BaseLayout",
2039
- deepLinking: true,
2040
- showExtensions: true,
2041
- showCommonExtensions: true,
2042
- // Inject x-api-key header on every request made from the Swagger UI
2043
- requestInterceptor: (request) => {
2044
- if (apiKey) {
2045
- request.headers['x-api-key'] = apiKey;
2046
- }
2047
- return request;
2048
- }
2049
- });
2050
- };
2051
- </script>
2052
- </body>
2053
- </html>
2054
- `;
2055
- }
2056
-
2057
- // src/auth/jexl.ts
2058
- import jexl from "jexl";
2059
- async function evaluateAccess(expression, context) {
2060
- if (expression === void 0 || expression === null) return false;
2061
- if (typeof expression === "boolean") return expression;
2062
- try {
2063
- const result = await jexl.eval(expression, context);
2064
- return !!result;
2065
- } catch (err) {
2066
- console.error("[dyrected/core] Jexl evaluation failed:", err);
2067
- return false;
2068
- }
2069
- }
2070
-
2071
- // src/router.ts
2072
- function accessGate(target, action) {
2073
- return async (c, next) => {
2074
- const user = c.get("user");
2075
- const accessExpr = target.access?.[action];
2076
- if (accessExpr === void 0 || accessExpr === null) {
2077
- return await next();
2078
- }
2079
- const accessArgs = { user, req: c.req, doc: null };
2080
- const allowed = await evaluateAccess(accessExpr, accessArgs);
2081
- if (!allowed) {
2082
- return c.json({ error: true, message: `Access denied: ${action} on ${target.slug}` }, 403);
2083
- }
2084
- await next();
2085
- };
2086
- }
2087
- function serializeAdminHooksForField(f) {
2088
- if (!f) return f;
2089
- const serialized = { ...f };
2090
- if (serialized.admin?.hooks) {
2091
- serialized.admin = {
2092
- ...serialized.admin,
2093
- hooks: {
2094
- ...serialized.admin.hooks,
2095
- onChange: typeof serialized.admin.hooks.onChange === "function" ? serialized.admin.hooks.onChange.toString() : serialized.admin.hooks.onChange
2096
- }
2097
- };
2098
- }
2099
- if (serialized.fields) {
2100
- serialized.fields = serialized.fields.map(serializeAdminHooksForField);
2101
- }
2102
- if (serialized.blocks) {
2103
- serialized.blocks = serialized.blocks.map((b) => ({
2104
- ...b,
2105
- fields: b.fields?.map(serializeAdminHooksForField)
2106
- }));
2107
- }
2108
- return serialized;
2109
- }
2110
- function registerRoutes(app, config) {
2111
- app.get("/api/schemas", optionalAuth(), async (c) => {
2112
- const siteId = c.req.header("X-Site-Id");
2113
- let collections = [...config.collections];
2114
- let globals = [...config.globals];
2115
- if (siteId && config.onSchemaFetch) {
2116
- const dynamic = await config.onSchemaFetch(siteId);
2117
- if (dynamic.collections) collections = [...collections, ...dynamic.collections];
2118
- if (dynamic.globals) globals = [...globals, ...dynamic.globals];
2119
- if (dynamic.admin) {
2120
- config.admin = { ...config.admin, ...dynamic.admin };
2121
- }
2122
- }
2123
- const user = c.get("user");
2124
- const accessArgs = { user, req: c.req, doc: null };
2125
- const resolveAccess = async (access) => {
2126
- if (access === void 0 || access === null) return true;
2127
- if (typeof access === "function") {
2128
- try {
2129
- const result = await access(accessArgs);
2130
- return typeof result === "boolean" ? result : !!result;
2131
- } catch (err) {
2132
- console.error("[dyrected/core] Functional access check failed:", err);
2133
- return false;
2134
- }
2135
- }
2136
- if (typeof access === "string" || typeof access === "boolean") {
2137
- return evaluateAccess(access, accessArgs);
2138
- }
2139
- return true;
2140
- };
2141
- const serializeAccess = async (access) => {
2142
- if (typeof access === "string") return access;
2143
- if (typeof access === "boolean") return access;
2144
- return resolveAccess(access);
2145
- };
2146
- const filteredCollections = await Promise.all(collections.filter((col) => !siteId || col.shared || !col.siteId || col.siteId === siteId).map(async (col) => ({
2147
- slug: col.slug,
2148
- labels: col.labels,
2149
- access: {
2150
- read: await serializeAccess(col.access?.read),
2151
- create: await serializeAccess(col.access?.create),
2152
- update: await serializeAccess(col.access?.update),
2153
- delete: await serializeAccess(col.access?.delete)
2154
- },
2155
- fields: await Promise.all(col.fields.map(serializeAdminHooksForField).map(async (f) => ({
2156
- name: f.name,
2157
- type: f.type,
2158
- label: f.label,
2159
- required: f.required,
2160
- defaultValue: f.defaultValue,
2161
- options: f.options,
2162
- relationTo: f.relationTo,
2163
- hasMany: f.hasMany,
2164
- fields: f.fields,
2165
- blocks: f.blocks,
2166
- admin: f.admin,
2167
- access: {
2168
- read: await serializeAccess(f.access?.read),
2169
- update: await serializeAccess(f.access?.update)
2170
- }
2171
- }))),
2172
- upload: !!col.upload,
2173
- auth: !!col.auth,
2174
- admin: col.admin
2175
- })));
2176
- const filteredGlobals = await Promise.all(globals.filter((glb) => !siteId || glb.shared || !glb.siteId || glb.siteId === siteId).map(async (glb) => ({
2177
- slug: glb.slug,
2178
- label: glb.label,
2179
- access: {
2180
- read: await serializeAccess(glb.access?.read),
2181
- update: await serializeAccess(glb.access?.update)
2182
- },
2183
- fields: await Promise.all(glb.fields.map(serializeAdminHooksForField).map(async (f) => ({
2184
- name: f.name,
2185
- type: f.type,
2186
- label: f.label,
2187
- required: f.required,
2188
- defaultValue: f.defaultValue,
2189
- options: f.options,
2190
- relationTo: f.relationTo,
2191
- hasMany: f.hasMany,
2192
- fields: f.fields,
2193
- blocks: f.blocks,
2194
- admin: f.admin,
2195
- access: {
2196
- read: await serializeAccess(f.access?.read),
2197
- update: await serializeAccess(f.access?.update)
2198
- }
2199
- }))),
2200
- admin: glb.admin
2201
- })));
2202
- return c.json({
2203
- collections: filteredCollections,
2204
- globals: filteredGlobals,
2205
- admin: config.admin || {}
2206
- });
2207
- });
2208
- app.get("/api/openapi.json", (c) => {
2209
- return c.json(generateOpenApi(config));
2210
- });
2211
- app.get("/api/docs", (c) => {
2212
- return c.html(getSwaggerHtml());
2213
- });
2214
- app.get("/api/media/:filename{.+$}", async (c) => {
2215
- const mediaController = new MediaController("media");
2216
- return mediaController.serve(c);
2217
- });
2218
- app.get("/media/:filename{.+$}", async (c) => {
2219
- const mediaController = new MediaController("media");
2220
- return mediaController.serve(c);
2221
- });
2222
- if (config.storage) {
2223
- const uploadCollections = config.collections.filter((c) => c.upload);
2224
- for (const col of uploadCollections) {
2225
- const mediaController = new MediaController(col.slug);
2226
- const prefix = `/api/collections/${col.slug}`;
2227
- app.get(`${prefix}/media`, accessGate(col, "read"), (c) => mediaController.find(c));
2228
- app.get(`${prefix}/media/:filename{.+$}`, (c) => mediaController.serve(c));
2229
- app.post(`${prefix}/media`, accessGate(col, "create"), (c) => mediaController.upload(c));
2230
- app.delete(`${prefix}/media/:id`, accessGate(col, "delete"), (c) => mediaController.delete(c));
2231
- }
2232
- }
2233
- for (const collection of config.collections) {
2234
- if (!collection.auth) continue;
2235
- const path = `/api/collections/${collection.slug}`;
2236
- const authController = new AuthController(collection);
2237
- app.post(`${path}/login`, (c) => authController.login(c));
2238
- app.post(`${path}/logout`, (c) => authController.logout(c));
2239
- app.get(`${path}/init`, (c) => authController.init(c));
2240
- app.post(`${path}/first-user`, (c) => authController.registerFirstUser(c));
2241
- app.get(`${path}/me`, requireAuth(), (c) => authController.me(c));
2242
- app.post(`${path}/refresh-token`, requireAuth(), (c) => authController.refreshToken(c));
2243
- app.post(`${path}/forgot-password`, (c) => authController.forgotPassword(c));
2244
- app.post(`${path}/reset-password`, (c) => authController.resetPassword(c));
2245
- app.post(`${path}/invite`, requireAuth(), (c) => authController.invite(c));
2246
- app.post(`${path}/accept-invite`, (c) => authController.acceptInvite(c));
2247
- }
2248
- for (const collection of config.collections) {
2249
- const path = `/api/collections/${collection.slug}`;
2250
- const controller = new CollectionController(collection);
2251
- app.get(path, accessGate(collection, "read"), (c) => controller.find(c));
2252
- app.post(path, accessGate(collection, "create"), (c) => controller.create(c));
2253
- app.post(`${path}/media`, accessGate(collection, "create"), (c) => controller.create(c));
2254
- app.delete(`${path}/delete-many`, accessGate(collection, "delete"), (c) => controller.deleteMany(c));
2255
- app.get(`${path}/:id`, accessGate(collection, "read"), (c) => controller.findOne(c));
2256
- app.patch(`${path}/:id`, accessGate(collection, "update"), (c) => controller.update(c));
2257
- app.delete(`${path}/:id`, accessGate(collection, "delete"), (c) => controller.delete(c));
2258
- app.post(`${path}/seed`, (c) => controller.seed(c));
2259
- if (collection.auth) {
2260
- app.post(`${path}/:id/change-password`, requireAuth(), (c) => controller.changePassword(c));
2261
- }
2262
- }
2263
- for (const global of config.globals) {
2264
- const path = `/api/globals/${global.slug}`;
2265
- const controller = new GlobalController(global);
2266
- app.get(path, accessGate(global, "read"), (c) => controller.get(c));
2267
- app.patch(path, accessGate(global, "update"), (c) => controller.update(c));
2268
- app.post(`${path}/seed`, (c) => controller.seed(c));
2269
- }
2270
- const previewController = new PreviewController();
2271
- app.post("/api/preview-token", requireAuth(), (c) => previewController.createToken(c));
2272
- app.get("/api/preview-data", (c) => previewController.getData(c));
2273
- app.all("/api/collections/:slug/:id?", async (c) => {
2274
- const slug = c.req.param("slug");
2275
- const id = c.req.param("id");
2276
- const siteId = c.req.header("X-Site-Id") || c.get("siteId");
2277
- const config2 = c.get("config");
2278
- if (config2.collections.some((col) => col.slug === slug)) {
2279
- return c.json({ message: "Method Not Allowed" }, 405);
2280
- }
2281
- if (config2.onSchemaFetch && siteId) {
2282
- const dynamic = await config2.onSchemaFetch(siteId);
2283
- let collection = dynamic.collections?.find((col) => col.slug === slug);
2284
- if (!collection && slug === "media") {
2285
- collection = {
2286
- slug: "media",
2287
- labels: { singular: "Media", plural: "Media" },
2288
- upload: true,
2289
- fields: []
2290
- };
2291
- }
2292
- if (collection) {
2293
- if (collection.auth && id) {
2294
- const authController = new AuthController(collection);
2295
- const method2 = c.req.method;
2296
- if (method2 === "POST" && id === "login") return authController.login(c);
2297
- if (method2 === "POST" && id === "logout") return authController.logout(c);
2298
- if (method2 === "GET" && id === "me") return authController.me(c);
2299
- if (method2 === "POST" && id === "refresh-token") return authController.refreshToken(c);
2300
- if (method2 === "POST" && id === "forgot-password") return authController.forgotPassword(c);
2301
- if (method2 === "POST" && id === "reset-password") return authController.resetPassword(c);
2302
- }
2303
- const controller = new CollectionController(collection);
2304
- const method = c.req.method;
2305
- if (id) {
2306
- if (method === "GET") return controller.findOne(c);
2307
- if (method === "PATCH") return controller.update(c);
2308
- if (method === "DELETE" && id === "delete-many") return controller.deleteMany(c);
2309
- if (method === "DELETE") return controller.delete(c);
2310
- if (method === "POST" && id === "media") return controller.create(c);
2311
- if (method === "POST" && id === "seed") return controller.seed(c);
2312
- } else {
2313
- if (method === "GET") return controller.find(c);
2314
- if (method === "POST") return controller.create(c);
2315
- }
2316
- }
2317
- }
2318
- return c.json({ message: `Collection "${slug}" not found` }, 404);
2319
- });
2320
- app.all("/api/globals/:slug", async (c) => {
2321
- const slug = c.req.param("slug");
2322
- const siteId = c.req.header("X-Site-Id") || c.get("siteId");
2323
- const config2 = c.get("config");
2324
- if (config2.globals.some((glb) => glb.slug === slug)) {
2325
- return c.json({ message: "Method Not Allowed" }, 405);
2326
- }
2327
- if (config2.onSchemaFetch && siteId) {
2328
- const dynamic = await config2.onSchemaFetch(siteId);
2329
- const global = dynamic.globals?.find((glb) => glb.slug === slug);
2330
- if (global) {
2331
- const controller = new GlobalController(global);
2332
- if (c.req.method === "GET") return controller.get(c);
2333
- if (c.req.method === "PATCH") return controller.update(c);
2334
- }
2335
- }
2336
- return c.json({ message: `Global "${slug}" not found` }, 404);
2337
- });
2338
- }
2339
-
2340
- // src/app.ts
2341
- import { Hono } from "hono";
2342
- import { cors } from "hono/cors";
2343
- import { requestId } from "hono/request-id";
2344
- async function createDyrectedApp(rawConfig) {
2345
- const config = normalizeConfig(rawConfig);
2346
- const app = new Hono();
2347
- if (config.db?.sync) {
2348
- await config.db.sync(config.collections, config.globals);
2349
- }
2350
- app.use("*", requestId());
2351
- app.use("*", optionalAuth());
2352
- app.use("*", async (c, next) => {
2353
- const start = Date.now();
2354
- await next();
2355
- const ms = Date.now() - start;
2356
- console.log(`[dyrected/api] ${c.req.method} ${c.req.path} ${c.res.status} - ${ms}ms`);
2357
- });
2358
- app.use("*", cors());
2359
- app.use("*", async (c, next) => {
2360
- c.set("config", config);
2361
- if (!c.get("siteId")) {
2362
- c.set("siteId", "default");
2363
- }
2364
- await next();
2365
- });
2366
- app.get("/health", (c) => c.json({ status: "ok", version: "0.0.1" }));
2367
- app.get("/routes", (c) => {
2368
- const routes = app.routes.map((r) => ({ method: r.method, path: r.path }));
2369
- return c.json({ routes });
2370
- });
2371
- app.onError((err, c) => {
2372
- console.error(`[dyrected/core] Uncaught Error:`, err);
2373
- return c.json({
2374
- message: err.message || "Internal Server Error",
2375
- stack: process.env.NODE_ENV === "development" ? err.stack : void 0
2376
- }, 500);
2377
- });
2378
- registerRoutes(app, config);
2379
- return app;
2380
- }
2381
-
2382
- export {
2383
- normalizeConfig,
2384
- runCollectionHooks,
2385
- executeFieldBeforeChange,
2386
- executeFieldAfterRead,
2387
- CollectionController,
2388
- GlobalController,
2389
- MediaController,
2390
- AuthController,
2391
- PreviewController,
2392
- registerRoutes,
2393
- createDyrectedApp
2394
- };