@dyrected/core 2.8.3 → 2.9.0

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 (500) hide show
  1. package/dist/{app-config-BccpBUqJ.d.cts → app-config-gEQJFvnN.d.cts} +212 -85
  2. package/dist/{app-config-BccpBUqJ.d.ts → app-config-gEQJFvnN.d.ts} +212 -85
  3. package/dist/chunk-JSBRDJBE.js +30 -0
  4. package/dist/{chunk-GFFGDHST.js → chunk-XRIONGRY.js} +1769 -12
  5. package/dist/index.cjs +1813 -6
  6. package/dist/index.d.cts +19 -4
  7. package/dist/index.d.ts +19 -4
  8. package/dist/index.js +56 -4
  9. package/dist/{observability-KCMTV7GO.js → observability-HQF4EUSV.js} +1 -0
  10. package/dist/server.cjs +1979 -13
  11. package/dist/server.d.cts +37 -15
  12. package/dist/server.d.ts +37 -15
  13. package/dist/server.js +230 -15
  14. package/dist/{where-sanitizer-WJ2W2QCE.js → where-sanitizer-3MNFMYA2.js} +2 -0
  15. package/package.json +3 -3
  16. package/dist/__tests__/access-features.test.d.ts +0 -2
  17. package/dist/__tests__/access-features.test.d.ts.map +0 -1
  18. package/dist/__tests__/access-features.test.js +0 -159
  19. package/dist/__tests__/access-features.test.js.map +0 -1
  20. package/dist/__tests__/access-parity.test.d.ts +0 -2
  21. package/dist/__tests__/access-parity.test.d.ts.map +0 -1
  22. package/dist/__tests__/access-parity.test.js +0 -338
  23. package/dist/__tests__/access-parity.test.js.map +0 -1
  24. package/dist/__tests__/access.test.d.ts +0 -2
  25. package/dist/__tests__/access.test.d.ts.map +0 -1
  26. package/dist/__tests__/access.test.js +0 -137
  27. package/dist/__tests__/access.test.js.map +0 -1
  28. package/dist/__tests__/admin-auth.test.d.ts +0 -2
  29. package/dist/__tests__/admin-auth.test.d.ts.map +0 -1
  30. package/dist/__tests__/admin-auth.test.js +0 -440
  31. package/dist/__tests__/admin-auth.test.js.map +0 -1
  32. package/dist/__tests__/app.test.d.ts +0 -2
  33. package/dist/__tests__/app.test.d.ts.map +0 -1
  34. package/dist/__tests__/app.test.js +0 -112
  35. package/dist/__tests__/app.test.js.map +0 -1
  36. package/dist/__tests__/audit.test.d.ts +0 -2
  37. package/dist/__tests__/audit.test.d.ts.map +0 -1
  38. package/dist/__tests__/audit.test.js +0 -125
  39. package/dist/__tests__/audit.test.js.map +0 -1
  40. package/dist/__tests__/auth-hydration.test.d.ts +0 -2
  41. package/dist/__tests__/auth-hydration.test.d.ts.map +0 -1
  42. package/dist/__tests__/auth-hydration.test.js +0 -90
  43. package/dist/__tests__/auth-hydration.test.js.map +0 -1
  44. package/dist/__tests__/auth-invite.test.d.ts +0 -2
  45. package/dist/__tests__/auth-invite.test.d.ts.map +0 -1
  46. package/dist/__tests__/auth-invite.test.js +0 -152
  47. package/dist/__tests__/auth-invite.test.js.map +0 -1
  48. package/dist/__tests__/auth-lockout.test.d.ts +0 -2
  49. package/dist/__tests__/auth-lockout.test.d.ts.map +0 -1
  50. package/dist/__tests__/auth-lockout.test.js +0 -154
  51. package/dist/__tests__/auth-lockout.test.js.map +0 -1
  52. package/dist/__tests__/auth-sessions.test.d.ts +0 -2
  53. package/dist/__tests__/auth-sessions.test.d.ts.map +0 -1
  54. package/dist/__tests__/auth-sessions.test.js +0 -118
  55. package/dist/__tests__/auth-sessions.test.js.map +0 -1
  56. package/dist/__tests__/config.test.d.ts +0 -2
  57. package/dist/__tests__/config.test.d.ts.map +0 -1
  58. package/dist/__tests__/config.test.js +0 -402
  59. package/dist/__tests__/config.test.js.map +0 -1
  60. package/dist/__tests__/define-field.test.d.ts +0 -2
  61. package/dist/__tests__/define-field.test.d.ts.map +0 -1
  62. package/dist/__tests__/define-field.test.js +0 -121
  63. package/dist/__tests__/define-field.test.js.map +0 -1
  64. package/dist/__tests__/deleteMany.test.d.ts +0 -2
  65. package/dist/__tests__/deleteMany.test.d.ts.map +0 -1
  66. package/dist/__tests__/deleteMany.test.js +0 -75
  67. package/dist/__tests__/deleteMany.test.js.map +0 -1
  68. package/dist/__tests__/depth.test.d.ts +0 -2
  69. package/dist/__tests__/depth.test.d.ts.map +0 -1
  70. package/dist/__tests__/depth.test.js +0 -115
  71. package/dist/__tests__/depth.test.js.map +0 -1
  72. package/dist/__tests__/dynamic-options.test.d.ts +0 -2
  73. package/dist/__tests__/dynamic-options.test.d.ts.map +0 -1
  74. package/dist/__tests__/dynamic-options.test.js +0 -168
  75. package/dist/__tests__/dynamic-options.test.js.map +0 -1
  76. package/dist/__tests__/email.service.test.d.ts +0 -2
  77. package/dist/__tests__/email.service.test.d.ts.map +0 -1
  78. package/dist/__tests__/email.service.test.js +0 -52
  79. package/dist/__tests__/email.service.test.js.map +0 -1
  80. package/dist/__tests__/field-inference.test-types.d.ts +0 -161
  81. package/dist/__tests__/field-inference.test-types.d.ts.map +0 -1
  82. package/dist/__tests__/field-inference.test-types.js +0 -87
  83. package/dist/__tests__/field-inference.test-types.js.map +0 -1
  84. package/dist/__tests__/fixtures/editorial-workflow.d.ts +0 -14
  85. package/dist/__tests__/fixtures/editorial-workflow.d.ts.map +0 -1
  86. package/dist/__tests__/fixtures/editorial-workflow.js +0 -12
  87. package/dist/__tests__/fixtures/editorial-workflow.js.map +0 -1
  88. package/dist/__tests__/hooks.test.d.ts +0 -2
  89. package/dist/__tests__/hooks.test.d.ts.map +0 -1
  90. package/dist/__tests__/hooks.test.js +0 -320
  91. package/dist/__tests__/hooks.test.js.map +0 -1
  92. package/dist/__tests__/mocks.d.ts +0 -75
  93. package/dist/__tests__/mocks.d.ts.map +0 -1
  94. package/dist/__tests__/mocks.js +0 -170
  95. package/dist/__tests__/mocks.js.map +0 -1
  96. package/dist/__tests__/observability.test.d.ts +0 -2
  97. package/dist/__tests__/observability.test.d.ts.map +0 -1
  98. package/dist/__tests__/observability.test.js +0 -233
  99. package/dist/__tests__/observability.test.js.map +0 -1
  100. package/dist/__tests__/openapi.test.d.ts +0 -2
  101. package/dist/__tests__/openapi.test.d.ts.map +0 -1
  102. package/dist/__tests__/openapi.test.js +0 -105
  103. package/dist/__tests__/openapi.test.js.map +0 -1
  104. package/dist/__tests__/parse-sort.test.d.ts +0 -2
  105. package/dist/__tests__/parse-sort.test.d.ts.map +0 -1
  106. package/dist/__tests__/parse-sort.test.js +0 -24
  107. package/dist/__tests__/parse-sort.test.js.map +0 -1
  108. package/dist/__tests__/preferences.test.d.ts +0 -2
  109. package/dist/__tests__/preferences.test.d.ts.map +0 -1
  110. package/dist/__tests__/preferences.test.js +0 -168
  111. package/dist/__tests__/preferences.test.js.map +0 -1
  112. package/dist/__tests__/router.test.d.ts +0 -2
  113. package/dist/__tests__/router.test.d.ts.map +0 -1
  114. package/dist/__tests__/router.test.js +0 -70
  115. package/dist/__tests__/router.test.js.map +0 -1
  116. package/dist/__tests__/search.test.d.ts +0 -2
  117. package/dist/__tests__/search.test.d.ts.map +0 -1
  118. package/dist/__tests__/search.test.js +0 -174
  119. package/dist/__tests__/search.test.js.map +0 -1
  120. package/dist/__tests__/upload-validation.test.d.ts +0 -2
  121. package/dist/__tests__/upload-validation.test.d.ts.map +0 -1
  122. package/dist/__tests__/upload-validation.test.js +0 -41
  123. package/dist/__tests__/upload-validation.test.js.map +0 -1
  124. package/dist/__tests__/where.test.d.ts +0 -2
  125. package/dist/__tests__/where.test.d.ts.map +0 -1
  126. package/dist/__tests__/where.test.js +0 -105
  127. package/dist/__tests__/where.test.js.map +0 -1
  128. package/dist/__tests__/workflow.test.d.ts +0 -2
  129. package/dist/__tests__/workflow.test.d.ts.map +0 -1
  130. package/dist/__tests__/workflow.test.js +0 -684
  131. package/dist/__tests__/workflow.test.js.map +0 -1
  132. package/dist/app-config-7G-3tF_I.d.cts +0 -2259
  133. package/dist/app-config-7G-3tF_I.d.ts +0 -2259
  134. package/dist/app-config-9hs8DRED.d.cts +0 -1718
  135. package/dist/app-config-9hs8DRED.d.ts +0 -1718
  136. package/dist/app-config-B3ByBjCN.d.cts +0 -2222
  137. package/dist/app-config-B3ByBjCN.d.ts +0 -2222
  138. package/dist/app-config-B5tYsZaH.d.cts +0 -2404
  139. package/dist/app-config-B5tYsZaH.d.ts +0 -2404
  140. package/dist/app-config-BEuyPktb.d.cts +0 -2556
  141. package/dist/app-config-BEuyPktb.d.ts +0 -2556
  142. package/dist/app-config-BIkjQWzU.d.cts +0 -2218
  143. package/dist/app-config-BIkjQWzU.d.ts +0 -2218
  144. package/dist/app-config-BcuZIpvL.d.cts +0 -1951
  145. package/dist/app-config-BcuZIpvL.d.ts +0 -1951
  146. package/dist/app-config-BfpeE3bF.d.cts +0 -2100
  147. package/dist/app-config-BfpeE3bF.d.ts +0 -2100
  148. package/dist/app-config-Bm9-2Am6.d.cts +0 -1875
  149. package/dist/app-config-Bm9-2Am6.d.ts +0 -1875
  150. package/dist/app-config-BqhrBrSM.d.cts +0 -1522
  151. package/dist/app-config-BqhrBrSM.d.ts +0 -1522
  152. package/dist/app-config-Bxg_DVxv.d.cts +0 -1413
  153. package/dist/app-config-Bxg_DVxv.d.ts +0 -1413
  154. package/dist/app-config-C0twGIaF.d.cts +0 -1597
  155. package/dist/app-config-C0twGIaF.d.ts +0 -1597
  156. package/dist/app-config-C0uxEU7Q.d.cts +0 -1874
  157. package/dist/app-config-C0uxEU7Q.d.ts +0 -1874
  158. package/dist/app-config-C3X5BAyK.d.cts +0 -1539
  159. package/dist/app-config-C3X5BAyK.d.ts +0 -1539
  160. package/dist/app-config-C9VJ6rTv.d.cts +0 -2092
  161. package/dist/app-config-C9VJ6rTv.d.ts +0 -2092
  162. package/dist/app-config-CBOn8IyZ.d.cts +0 -1838
  163. package/dist/app-config-CBOn8IyZ.d.ts +0 -1838
  164. package/dist/app-config-CCe-yq9q.d.cts +0 -2222
  165. package/dist/app-config-CCe-yq9q.d.ts +0 -2222
  166. package/dist/app-config-CJAGGPrk.d.cts +0 -1900
  167. package/dist/app-config-CJAGGPrk.d.ts +0 -1900
  168. package/dist/app-config-CPOs7THF.d.cts +0 -2217
  169. package/dist/app-config-CPOs7THF.d.ts +0 -2217
  170. package/dist/app-config-CYV70eoF.d.cts +0 -2100
  171. package/dist/app-config-CYV70eoF.d.ts +0 -2100
  172. package/dist/app-config-ChsrBB7p.d.cts +0 -2100
  173. package/dist/app-config-ChsrBB7p.d.ts +0 -2100
  174. package/dist/app-config-CiEDJm0e.d.cts +0 -1912
  175. package/dist/app-config-CiEDJm0e.d.ts +0 -1912
  176. package/dist/app-config-CstocO9M.d.cts +0 -1580
  177. package/dist/app-config-CstocO9M.d.ts +0 -1580
  178. package/dist/app-config-Ctp454zB.d.cts +0 -2214
  179. package/dist/app-config-Ctp454zB.d.ts +0 -2214
  180. package/dist/app-config-CwaU1de2.d.cts +0 -1868
  181. package/dist/app-config-CwaU1de2.d.ts +0 -1868
  182. package/dist/app-config-DCDh8Gbx.d.cts +0 -1926
  183. package/dist/app-config-DCDh8Gbx.d.ts +0 -1926
  184. package/dist/app-config-DCWinlNK.d.cts +0 -2091
  185. package/dist/app-config-DCWinlNK.d.ts +0 -2091
  186. package/dist/app-config-DIwvzbpe.d.cts +0 -1555
  187. package/dist/app-config-DIwvzbpe.d.ts +0 -1555
  188. package/dist/app-config-DJmNYgYh.d.cts +0 -2305
  189. package/dist/app-config-DJmNYgYh.d.ts +0 -2305
  190. package/dist/app-config-DO3laV58.d.cts +0 -2397
  191. package/dist/app-config-DO3laV58.d.ts +0 -2397
  192. package/dist/app-config-DVdSospO.d.cts +0 -1842
  193. package/dist/app-config-DVdSospO.d.ts +0 -1842
  194. package/dist/app-config-DZf_mmi9.d.cts +0 -2211
  195. package/dist/app-config-DZf_mmi9.d.ts +0 -2211
  196. package/dist/app-config-DbK2Tv6i.d.cts +0 -2080
  197. package/dist/app-config-DbK2Tv6i.d.ts +0 -2080
  198. package/dist/app-config-Dkndq5ni.d.cts +0 -1580
  199. package/dist/app-config-Dkndq5ni.d.ts +0 -1580
  200. package/dist/app-config-Dms6kvE-.d.cts +0 -2072
  201. package/dist/app-config-Dms6kvE-.d.ts +0 -2072
  202. package/dist/app-config-DqCipvSI.d.cts +0 -1411
  203. package/dist/app-config-DqCipvSI.d.ts +0 -1411
  204. package/dist/app-config-Dv5XACR4.d.cts +0 -2065
  205. package/dist/app-config-Dv5XACR4.d.ts +0 -2065
  206. package/dist/app-config-P-SF5nnR.d.cts +0 -1568
  207. package/dist/app-config-P-SF5nnR.d.ts +0 -1568
  208. package/dist/app-config-SkUoN5JU.d.cts +0 -2192
  209. package/dist/app-config-SkUoN5JU.d.ts +0 -2192
  210. package/dist/app-config-WzqpuZMr.d.cts +0 -2566
  211. package/dist/app-config-WzqpuZMr.d.ts +0 -2566
  212. package/dist/app-config-_kkj71CB.d.cts +0 -2010
  213. package/dist/app-config-_kkj71CB.d.ts +0 -2010
  214. package/dist/app-config-fEjRm1o9.d.cts +0 -2402
  215. package/dist/app-config-fEjRm1o9.d.ts +0 -2402
  216. package/dist/app-config-oU1EGHND.d.cts +0 -1538
  217. package/dist/app-config-oU1EGHND.d.ts +0 -1538
  218. package/dist/app-config-ouBRb6Bf.d.cts +0 -1716
  219. package/dist/app-config-ouBRb6Bf.d.ts +0 -1716
  220. package/dist/app-config-oz8H_MOX.d.cts +0 -2224
  221. package/dist/app-config-oz8H_MOX.d.ts +0 -2224
  222. package/dist/app-config-tITj_0sn.d.cts +0 -1926
  223. package/dist/app-config-tITj_0sn.d.ts +0 -1926
  224. package/dist/app-config-wnLtFu6c.d.cts +0 -1538
  225. package/dist/app-config-wnLtFu6c.d.ts +0 -1538
  226. package/dist/app-config-x-CnipcA.d.cts +0 -2072
  227. package/dist/app-config-x-CnipcA.d.ts +0 -2072
  228. package/dist/app.d.ts +0 -35
  229. package/dist/app.d.ts.map +0 -1
  230. package/dist/app.js +0 -164
  231. package/dist/app.js.map +0 -1
  232. package/dist/auth/access.d.ts +0 -5
  233. package/dist/auth/access.d.ts.map +0 -1
  234. package/dist/auth/access.js +0 -59
  235. package/dist/auth/access.js.map +0 -1
  236. package/dist/auth/jexl.d.ts +0 -13
  237. package/dist/auth/jexl.d.ts.map +0 -1
  238. package/dist/auth/jexl.js +0 -30
  239. package/dist/auth/jexl.js.map +0 -1
  240. package/dist/auth/lockout.d.ts +0 -11
  241. package/dist/auth/lockout.d.ts.map +0 -1
  242. package/dist/auth/lockout.js +0 -37
  243. package/dist/auth/lockout.js.map +0 -1
  244. package/dist/auth/password.d.ts +0 -10
  245. package/dist/auth/password.d.ts.map +0 -1
  246. package/dist/auth/password.js +0 -28
  247. package/dist/auth/password.js.map +0 -1
  248. package/dist/auth/sessions.d.ts +0 -39
  249. package/dist/auth/sessions.d.ts.map +0 -1
  250. package/dist/auth/sessions.js +0 -126
  251. package/dist/auth/sessions.js.map +0 -1
  252. package/dist/auth/token.d.ts +0 -23
  253. package/dist/auth/token.d.ts.map +0 -1
  254. package/dist/auth/token.js +0 -40
  255. package/dist/auth/token.js.map +0 -1
  256. package/dist/chunk-23NM4LDU.js +0 -2883
  257. package/dist/chunk-2TKDCCIR.js +0 -2622
  258. package/dist/chunk-2UXLA4YN.js +0 -3139
  259. package/dist/chunk-2WODKOUB.js +0 -1627
  260. package/dist/chunk-35NM2WPO.js +0 -1658
  261. package/dist/chunk-3CMG2BH2.js +0 -1618
  262. package/dist/chunk-3SFITPX4.js +0 -2628
  263. package/dist/chunk-3TRRTN6U.js +0 -3441
  264. package/dist/chunk-57FNM42D.js +0 -2392
  265. package/dist/chunk-5U2WRCNH.js +0 -3140
  266. package/dist/chunk-5ZIA5COH.js +0 -3414
  267. package/dist/chunk-6TWQ6GTD.js +0 -3480
  268. package/dist/chunk-AKYYGMFS.js +0 -3365
  269. package/dist/chunk-AQO4HI2Y.js +0 -3204
  270. package/dist/chunk-BAMX7YUC.js +0 -1815
  271. package/dist/chunk-BQV3QW3Y.js +0 -2588
  272. package/dist/chunk-CQVTQ67D.js +0 -2632
  273. package/dist/chunk-CUOPCOU2.js +0 -1644
  274. package/dist/chunk-DCY7QHRB.js +0 -1637
  275. package/dist/chunk-DFBLNYUH.js +0 -3402
  276. package/dist/chunk-EH3MJGB5.js +0 -2571
  277. package/dist/chunk-EJG6AMYB.js +0 -3537
  278. package/dist/chunk-ELHRRPKX.js +0 -2863
  279. package/dist/chunk-EOW4YMAV.js +0 -1637
  280. package/dist/chunk-G43REXPX.js +0 -3147
  281. package/dist/chunk-GFKBPBJJ.js +0 -3637
  282. package/dist/chunk-HRLSFTLR.js +0 -3061
  283. package/dist/chunk-JFA22YFB.js +0 -1625
  284. package/dist/chunk-K3ASMUKV.js +0 -2601
  285. package/dist/chunk-KEKOEAX6.js +0 -3139
  286. package/dist/chunk-L65PQYDP.js +0 -1536
  287. package/dist/chunk-LFGSRQLX.js +0 -3568
  288. package/dist/chunk-M3HKRN7E.js +0 -1665
  289. package/dist/chunk-MQZH7RQC.js +0 -1667
  290. package/dist/chunk-NNZRYF3U.js +0 -3537
  291. package/dist/chunk-PRQ2RF5C.js +0 -3485
  292. package/dist/chunk-PYE2JSY4.js +0 -3568
  293. package/dist/chunk-PZMDK3MH.js +0 -3203
  294. package/dist/chunk-QCXLDKZO.js +0 -3272
  295. package/dist/chunk-QTIAQBNH.js +0 -3097
  296. package/dist/chunk-ROECUARS.js +0 -2615
  297. package/dist/chunk-SM32ND5M.js +0 -3472
  298. package/dist/chunk-T2DGC4MD.js +0 -3008
  299. package/dist/chunk-T626OZMH.js +0 -2602
  300. package/dist/chunk-TEGRS6J7.js +0 -2609
  301. package/dist/chunk-TLU77TLE.js +0 -3203
  302. package/dist/chunk-UKUEKTAO.js +0 -513
  303. package/dist/chunk-VCYYBN5J.js +0 -1873
  304. package/dist/chunk-VM43G3IG.js +0 -506
  305. package/dist/chunk-VWJKFZQU.js +0 -3139
  306. package/dist/chunk-WF5A6PDJ.js +0 -1618
  307. package/dist/chunk-WVD7PORQ.js +0 -1672
  308. package/dist/chunk-XX7N64NL.js +0 -3550
  309. package/dist/chunk-XZLIBQSO.js +0 -2397
  310. package/dist/chunk-YEBCT77K.js +0 -3269
  311. package/dist/chunk-YSSHLGQ6.js +0 -3139
  312. package/dist/chunk-YXEKNN5X.js +0 -3085
  313. package/dist/chunk-Z7CFUYVP.js +0 -3653
  314. package/dist/chunk-ZISFMAEL.js +0 -3550
  315. package/dist/controllers/admin-auth.controller.d.ts +0 -71
  316. package/dist/controllers/admin-auth.controller.d.ts.map +0 -1
  317. package/dist/controllers/admin-auth.controller.js +0 -450
  318. package/dist/controllers/admin-auth.controller.js.map +0 -1
  319. package/dist/controllers/audit.controller.d.ts +0 -42
  320. package/dist/controllers/audit.controller.d.ts.map +0 -1
  321. package/dist/controllers/audit.controller.js +0 -149
  322. package/dist/controllers/audit.controller.js.map +0 -1
  323. package/dist/controllers/auth.controller.d.ts +0 -143
  324. package/dist/controllers/auth.controller.d.ts.map +0 -1
  325. package/dist/controllers/auth.controller.js +0 -572
  326. package/dist/controllers/auth.controller.js.map +0 -1
  327. package/dist/controllers/collection.controller.d.ts +0 -170
  328. package/dist/controllers/collection.controller.d.ts.map +0 -1
  329. package/dist/controllers/collection.controller.js +0 -1033
  330. package/dist/controllers/collection.controller.js.map +0 -1
  331. package/dist/controllers/global.controller.d.ts +0 -20
  332. package/dist/controllers/global.controller.d.ts.map +0 -1
  333. package/dist/controllers/global.controller.js +0 -182
  334. package/dist/controllers/global.controller.js.map +0 -1
  335. package/dist/controllers/media.controller.d.ts +0 -39
  336. package/dist/controllers/media.controller.d.ts.map +0 -1
  337. package/dist/controllers/media.controller.js +0 -178
  338. package/dist/controllers/media.controller.js.map +0 -1
  339. package/dist/controllers/preview.controller.d.ts +0 -37
  340. package/dist/controllers/preview.controller.d.ts.map +0 -1
  341. package/dist/controllers/preview.controller.js +0 -48
  342. package/dist/controllers/preview.controller.js.map +0 -1
  343. package/dist/index.d.ts.map +0 -1
  344. package/dist/index.js.map +0 -1
  345. package/dist/middleware/auth.d.ts +0 -19
  346. package/dist/middleware/auth.d.ts.map +0 -1
  347. package/dist/middleware/auth.js +0 -157
  348. package/dist/middleware/auth.js.map +0 -1
  349. package/dist/middleware/rate-limit.d.ts +0 -9
  350. package/dist/middleware/rate-limit.d.ts.map +0 -1
  351. package/dist/middleware/rate-limit.js +0 -75
  352. package/dist/middleware/rate-limit.js.map +0 -1
  353. package/dist/network.d.ts +0 -6
  354. package/dist/network.d.ts.map +0 -1
  355. package/dist/network.js +0 -70
  356. package/dist/network.js.map +0 -1
  357. package/dist/observability-CNM4QFE4.js +0 -34
  358. package/dist/observability-L5BORBB2.js +0 -34
  359. package/dist/observability.d.ts +0 -113
  360. package/dist/observability.d.ts.map +0 -1
  361. package/dist/observability.js +0 -497
  362. package/dist/observability.js.map +0 -1
  363. package/dist/router.d.ts +0 -8
  364. package/dist/router.d.ts.map +0 -1
  365. package/dist/router.js +0 -704
  366. package/dist/router.js.map +0 -1
  367. package/dist/server.d.ts.map +0 -1
  368. package/dist/server.js.map +0 -1
  369. package/dist/services/audit.service.d.ts +0 -23
  370. package/dist/services/audit.service.d.ts.map +0 -1
  371. package/dist/services/audit.service.js +0 -39
  372. package/dist/services/audit.service.js.map +0 -1
  373. package/dist/services/defaults.service.d.ts +0 -8
  374. package/dist/services/defaults.service.d.ts.map +0 -1
  375. package/dist/services/defaults.service.js +0 -55
  376. package/dist/services/defaults.service.js.map +0 -1
  377. package/dist/services/email-template.d.ts +0 -46
  378. package/dist/services/email-template.d.ts.map +0 -1
  379. package/dist/services/email-template.js +0 -88
  380. package/dist/services/email-template.js.map +0 -1
  381. package/dist/services/email.service.d.ts +0 -34
  382. package/dist/services/email.service.d.ts.map +0 -1
  383. package/dist/services/email.service.js +0 -129
  384. package/dist/services/email.service.js.map +0 -1
  385. package/dist/services/media.service.d.ts +0 -20
  386. package/dist/services/media.service.d.ts.map +0 -1
  387. package/dist/services/media.service.js +0 -49
  388. package/dist/services/media.service.js.map +0 -1
  389. package/dist/services/population.service.d.ts +0 -20
  390. package/dist/services/population.service.d.ts.map +0 -1
  391. package/dist/services/population.service.js +0 -224
  392. package/dist/services/population.service.js.map +0 -1
  393. package/dist/types/access.d.ts +0 -48
  394. package/dist/types/access.d.ts.map +0 -1
  395. package/dist/types/access.js +0 -2
  396. package/dist/types/access.js.map +0 -1
  397. package/dist/types/adapters.d.ts +0 -152
  398. package/dist/types/adapters.d.ts.map +0 -1
  399. package/dist/types/adapters.js +0 -2
  400. package/dist/types/adapters.js.map +0 -1
  401. package/dist/types/admin-auth.d.ts +0 -132
  402. package/dist/types/admin-auth.d.ts.map +0 -1
  403. package/dist/types/admin-auth.js +0 -2
  404. package/dist/types/admin-auth.js.map +0 -1
  405. package/dist/types/admin.d.ts +0 -86
  406. package/dist/types/admin.d.ts.map +0 -1
  407. package/dist/types/admin.js +0 -2
  408. package/dist/types/admin.js.map +0 -1
  409. package/dist/types/app-config.d.ts +0 -279
  410. package/dist/types/app-config.d.ts.map +0 -1
  411. package/dist/types/app-config.js +0 -2
  412. package/dist/types/app-config.js.map +0 -1
  413. package/dist/types/documents.d.ts +0 -65
  414. package/dist/types/documents.d.ts.map +0 -1
  415. package/dist/types/documents.js +0 -2
  416. package/dist/types/documents.js.map +0 -1
  417. package/dist/types/hooks.d.ts +0 -122
  418. package/dist/types/hooks.d.ts.map +0 -1
  419. package/dist/types/hooks.js +0 -2
  420. package/dist/types/hooks.js.map +0 -1
  421. package/dist/types/index.d.ts +0 -13
  422. package/dist/types/index.d.ts.map +0 -1
  423. package/dist/types/index.js +0 -13
  424. package/dist/types/index.js.map +0 -1
  425. package/dist/types/request.d.ts +0 -42
  426. package/dist/types/request.d.ts.map +0 -1
  427. package/dist/types/request.js +0 -2
  428. package/dist/types/request.js.map +0 -1
  429. package/dist/types/schema-config.d.ts +0 -443
  430. package/dist/types/schema-config.d.ts.map +0 -1
  431. package/dist/types/schema-config.js +0 -2
  432. package/dist/types/schema-config.js.map +0 -1
  433. package/dist/types/schema-core.d.ts +0 -628
  434. package/dist/types/schema-core.d.ts.map +0 -1
  435. package/dist/types/schema-core.js +0 -2
  436. package/dist/types/schema-core.js.map +0 -1
  437. package/dist/types/schema-inference.d.ts +0 -73
  438. package/dist/types/schema-inference.d.ts.map +0 -1
  439. package/dist/types/schema-inference.js +0 -2
  440. package/dist/types/schema-inference.js.map +0 -1
  441. package/dist/types/workflows.d.ts +0 -121
  442. package/dist/types/workflows.d.ts.map +0 -1
  443. package/dist/types/workflows.js +0 -7
  444. package/dist/types/workflows.js.map +0 -1
  445. package/dist/utils/access-control.d.ts +0 -35
  446. package/dist/utils/access-control.d.ts.map +0 -1
  447. package/dist/utils/access-control.js +0 -161
  448. package/dist/utils/access-control.js.map +0 -1
  449. package/dist/utils/admin-auth.d.ts +0 -5
  450. package/dist/utils/admin-auth.d.ts.map +0 -1
  451. package/dist/utils/admin-auth.js +0 -39
  452. package/dist/utils/admin-auth.js.map +0 -1
  453. package/dist/utils/block-references.d.ts +0 -10
  454. package/dist/utils/block-references.d.ts.map +0 -1
  455. package/dist/utils/block-references.js +0 -100
  456. package/dist/utils/block-references.js.map +0 -1
  457. package/dist/utils/collection-search.d.ts +0 -11
  458. package/dist/utils/collection-search.d.ts.map +0 -1
  459. package/dist/utils/collection-search.js +0 -204
  460. package/dist/utils/collection-search.js.map +0 -1
  461. package/dist/utils/config.d.ts +0 -8
  462. package/dist/utils/config.d.ts.map +0 -1
  463. package/dist/utils/config.js +0 -336
  464. package/dist/utils/config.js.map +0 -1
  465. package/dist/utils/hooks.d.ts +0 -41
  466. package/dist/utils/hooks.d.ts.map +0 -1
  467. package/dist/utils/hooks.js +0 -177
  468. package/dist/utils/hooks.js.map +0 -1
  469. package/dist/utils/openapi.d.ts +0 -6
  470. package/dist/utils/openapi.d.ts.map +0 -1
  471. package/dist/utils/openapi.js +0 -981
  472. package/dist/utils/openapi.js.map +0 -1
  473. package/dist/utils/parse-sort.d.ts +0 -43
  474. package/dist/utils/parse-sort.d.ts.map +0 -1
  475. package/dist/utils/parse-sort.js +0 -70
  476. package/dist/utils/parse-sort.js.map +0 -1
  477. package/dist/utils/parse-where.d.ts +0 -69
  478. package/dist/utils/parse-where.d.ts.map +0 -1
  479. package/dist/utils/parse-where.js +0 -202
  480. package/dist/utils/parse-where.js.map +0 -1
  481. package/dist/utils/readonly-db.d.ts +0 -9
  482. package/dist/utils/readonly-db.d.ts.map +0 -1
  483. package/dist/utils/readonly-db.js +0 -21
  484. package/dist/utils/readonly-db.js.map +0 -1
  485. package/dist/utils/swagger.d.ts +0 -11
  486. package/dist/utils/swagger.d.ts.map +0 -1
  487. package/dist/utils/swagger.js +0 -62
  488. package/dist/utils/swagger.js.map +0 -1
  489. package/dist/utils/upload-validation.d.ts +0 -23
  490. package/dist/utils/upload-validation.d.ts.map +0 -1
  491. package/dist/utils/upload-validation.js +0 -46
  492. package/dist/utils/upload-validation.js.map +0 -1
  493. package/dist/utils/where-sanitizer.d.ts +0 -10
  494. package/dist/utils/where-sanitizer.d.ts.map +0 -1
  495. package/dist/utils/where-sanitizer.js +0 -67
  496. package/dist/utils/where-sanitizer.js.map +0 -1
  497. package/dist/workflows.d.ts +0 -86
  498. package/dist/workflows.d.ts.map +0 -1
  499. package/dist/workflows.js +0 -405
  500. package/dist/workflows.js.map +0 -1
@@ -1,3147 +0,0 @@
1
- import {
2
- getConfigLogger
3
- } from "./chunk-FRSJJO27.js";
4
-
5
- // src/workflows.ts
6
- var WORKFLOW_HISTORY_COLLECTION = "__workflow_history";
7
- var LIFECYCLE_EVENTS_COLLECTION = "__lifecycle_events";
8
- var EDITOR_CAPABILITIES = ["entry.edit", "entry.submit"];
9
- var PUBLISHER_CAPABILITIES = ["entry.edit", "entry.submit", "entry.publish", "entry.unpublish"];
10
- function definePublishingWorkflow(options = {}) {
11
- const editors = options.editors ?? ["editor"];
12
- const publishers = options.publishers ?? ["publisher", "admin"];
13
- return {
14
- initialState: "draft",
15
- draftState: "draft",
16
- states: [
17
- { name: "draft", label: "Draft", color: "neutral" },
18
- { name: "in_review", label: "In review", color: "warning" },
19
- { name: "published", label: "Published", color: "success", published: true }
20
- ],
21
- transitions: [
22
- {
23
- name: "submit",
24
- label: "Submit for review",
25
- from: "draft",
26
- to: "in_review",
27
- requiredCapabilities: ["entry.submit"]
28
- },
29
- {
30
- name: "publish",
31
- label: "Publish",
32
- from: "in_review",
33
- to: "published",
34
- requiredCapabilities: ["entry.publish"]
35
- },
36
- {
37
- name: "reject",
38
- label: "Request changes",
39
- from: "in_review",
40
- to: "draft",
41
- requiredCapabilities: ["entry.publish"],
42
- requireComment: true
43
- },
44
- {
45
- name: "unpublish",
46
- label: "Unpublish",
47
- from: "published",
48
- to: "draft",
49
- requiredCapabilities: ["entry.unpublish"],
50
- unpublish: true
51
- }
52
- ],
53
- roles: [
54
- ...editors.map((role) => ({ role, capabilities: [...EDITOR_CAPABILITIES] })),
55
- ...publishers.map((role) => ({ role, capabilities: [...PUBLISHER_CAPABILITIES] }))
56
- ]
57
- };
58
- }
59
- function publishingWorkflow() {
60
- return definePublishingWorkflow();
61
- }
62
- function simplePublishingWorkflow() {
63
- return {
64
- initialState: "draft",
65
- draftState: "draft",
66
- states: [
67
- { name: "draft", label: "Draft", color: "neutral" },
68
- { name: "published", label: "Published", color: "success", published: true }
69
- ],
70
- transitions: [
71
- { name: "publish", label: "Publish", from: ["draft", "published"], to: "published" },
72
- { name: "unpublish", label: "Unpublish", from: "published", to: "draft", unpublish: true }
73
- ]
74
- // Intentionally no `roles`: this lightweight workflow (synthesized from
75
- // `drafts: true`) does no capability-based gating. Draft visibility for a
76
- // no-roles workflow is handled in `canViewWorkflowDraft`.
77
- };
78
- }
79
- function publicMetadata(meta) {
80
- const { availableTransitions: _availableTransitions, ...safe } = meta;
81
- return safe;
82
- }
83
- function workflowCapabilities(workflow, user) {
84
- const capabilities = new Set(Array.isArray(user?.capabilities) ? user.capabilities : []);
85
- const roles = Array.isArray(user?.roles) ? user.roles : [];
86
- for (const mapping of workflow.roles ?? []) {
87
- if (roles.includes(mapping.role)) mapping.capabilities.forEach((capability) => capabilities.add(capability));
88
- }
89
- return capabilities;
90
- }
91
- function canViewWorkflowDraft(workflow, user) {
92
- if (!user) return false;
93
- const capabilities = workflowCapabilities(workflow, user);
94
- if (capabilities.has("entry.edit")) return true;
95
- if (workflow.transitions.some(
96
- (transition) => (transition.requiredCapabilities ?? []).some((capability) => capabilities.has(capability))
97
- )) {
98
- return true;
99
- }
100
- if (!workflow.roles || workflow.roles.length === 0) return true;
101
- return false;
102
- }
103
- function availableWorkflowTransitions(workflow, state, user) {
104
- const capabilities = workflowCapabilities(workflow, user);
105
- return workflow.transitions.filter((transition) => {
106
- const from = Array.isArray(transition.from) ? transition.from : [transition.from];
107
- return from.includes(state) && (transition.requiredCapabilities ?? []).every((item) => capabilities.has(item));
108
- });
109
- }
110
- function initializeWorkflowDocument(data, workflow) {
111
- return {
112
- ...data,
113
- __workflow: { state: workflow.initialState, revision: 1 }
114
- };
115
- }
116
- function publishedStateName(workflow) {
117
- return workflow.states.find((state) => state.published)?.name ?? workflow.states[workflow.states.length - 1]?.name ?? workflow.initialState;
118
- }
119
- function materializeWorkflowDocument(doc, workflow, user) {
120
- const meta = doc.__workflow;
121
- const publishedState = publishedStateName(workflow);
122
- if (!meta) {
123
- const { __published: _legacyPublished, __workflow: _legacyWorkflow, ...working2 } = doc;
124
- const state = publishedStateName(workflow);
125
- return {
126
- ...working2,
127
- _workflow: {
128
- state,
129
- revision: 1,
130
- availableTransitions: availableWorkflowTransitions(workflow, state, user).map((item) => item.name)
131
- }
132
- };
133
- }
134
- const { __published, __workflow, ...working } = doc;
135
- if (!canViewWorkflowDraft(workflow, user)) {
136
- if (!__published || typeof __published !== "object") {
137
- if (meta.state === publishedState) {
138
- return { ...working, _workflow: publicMetadata(meta) };
139
- }
140
- return null;
141
- }
142
- return { id: doc.id, ...__published, _workflow: publicMetadata(meta) };
143
- }
144
- return {
145
- ...working,
146
- _workflow: {
147
- ...meta,
148
- availableTransitions: availableWorkflowTransitions(workflow, meta.state, user).map((item) => item.name)
149
- }
150
- };
151
- }
152
- function eventId() {
153
- return globalThis.crypto?.randomUUID?.() ?? `evt_${Date.now()}_${Math.random().toString(36).slice(2)}`;
154
- }
155
- function createLifecycleEvent(args) {
156
- return {
157
- id: eventId(),
158
- name: args.name,
159
- collection: args.collection,
160
- documentId: args.documentId,
161
- occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
162
- actorId: args.actorId,
163
- payload: args.payload,
164
- attempts: 0,
165
- status: "pending"
166
- };
167
- }
168
- async function persistEvent(db, event) {
169
- await db.create({ collection: LIFECYCLE_EVENTS_COLLECTION, data: event });
170
- }
171
- async function dispatchLifecycleEvent(config, event) {
172
- const db = config.db;
173
- if (!db || !config.events?.handlers.length) return;
174
- const maxAttempts = config.events.maxAttempts ?? 8;
175
- const retryDelayMs = config.events.retryDelayMs ?? 1e3;
176
- const attempts = event.attempts + 1;
177
- try {
178
- await db.update({
179
- collection: LIFECYCLE_EVENTS_COLLECTION,
180
- id: event.id,
181
- data: { status: "processing", attempts }
182
- });
183
- for (const handler of config.events.handlers) await handler({ ...event, status: "processing", attempts });
184
- await db.update({
185
- collection: LIFECYCLE_EVENTS_COLLECTION,
186
- id: event.id,
187
- data: { status: "delivered", attempts, deliveredAt: (/* @__PURE__ */ new Date()).toISOString(), lastError: null }
188
- });
189
- } catch (error) {
190
- const exhausted = attempts >= maxAttempts;
191
- await db.update({
192
- collection: LIFECYCLE_EVENTS_COLLECTION,
193
- id: event.id,
194
- data: {
195
- status: "failed",
196
- attempts,
197
- lastError: error instanceof Error ? error.message : String(error),
198
- nextAttemptAt: exhausted ? null : new Date(Date.now() + retryDelayMs * 2 ** (attempts - 1)).toISOString()
199
- }
200
- });
201
- }
202
- }
203
- async function dispatchPendingLifecycleEvents(config, limit = 50) {
204
- if (!config.db || !config.events?.handlers.length) return 0;
205
- const maxAttempts = config.events.maxAttempts ?? 8;
206
- const result = await config.db.find({
207
- collection: LIFECYCLE_EVENTS_COLLECTION,
208
- where: { status: { in: ["pending", "failed"] } },
209
- sort: "occurredAt",
210
- limit
211
- });
212
- const now2 = Date.now();
213
- const due = result.docs.filter(
214
- (doc) => Number(doc.attempts ?? 0) < maxAttempts && (!doc.nextAttemptAt || new Date(doc.nextAttemptAt).getTime() <= now2)
215
- );
216
- for (const event of due) await dispatchLifecycleEvent(config, event);
217
- return due.length;
218
- }
219
- async function saveWorkflowDraft(args) {
220
- const { config, collection, id, originalDoc, data, user } = args;
221
- const db = config.db;
222
- const workflow = collection.workflow;
223
- if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
224
- const previous = originalDoc.__workflow;
225
- const isLegacyPublishedDoc = !previous;
226
- const baselineRevision = previous?.revision ?? 1;
227
- const event = createLifecycleEvent({
228
- name: "revision.created",
229
- collection: collection.slug,
230
- documentId: id,
231
- actorId: user?.sub,
232
- payload: {
233
- revision: baselineRevision + 1,
234
- previousRevision: isLegacyPublishedDoc ? baselineRevision : previous?.revision ?? null
235
- }
236
- });
237
- const doc = await db.transaction(async (tx) => {
238
- const nextMeta = {
239
- ...previous ?? {},
240
- state: isLegacyPublishedDoc ? workflow.draftState ?? workflow.initialState : originalDoc.__published ? workflow.draftState ?? workflow.initialState : previous.state,
241
- revision: baselineRevision + 1,
242
- ...isLegacyPublishedDoc ? { publishedRevision: baselineRevision } : {}
243
- };
244
- const updateData = {
245
- ...data,
246
- __workflow: nextMeta
247
- };
248
- if (isLegacyPublishedDoc) {
249
- const { __workflow: _legacyWorkflow, __published: _legacyPublished, ...publishedSnapshot } = originalDoc;
250
- updateData.__published = publishedSnapshot;
251
- }
252
- const updated = await tx.update({ collection: collection.slug, id, data: updateData });
253
- await persistEvent(tx, event);
254
- return updated;
255
- });
256
- void dispatchLifecycleEvent(config, event);
257
- return { doc, event };
258
- }
259
- async function createWorkflowDocument(args) {
260
- const { config, collection, data, user } = args;
261
- const db = config.db;
262
- if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
263
- let event;
264
- const doc = await db.transaction(async (tx) => {
265
- const created = await tx.create({ collection: collection.slug, data });
266
- event = createLifecycleEvent({
267
- name: "revision.created",
268
- collection: collection.slug,
269
- documentId: created.id,
270
- actorId: user?.sub,
271
- payload: { revision: 1, previousRevision: null }
272
- });
273
- await persistEvent(tx, event);
274
- return created;
275
- });
276
- void dispatchLifecycleEvent(config, event);
277
- return { doc, event };
278
- }
279
- async function transitionWorkflow(args) {
280
- const { config, collection, id, transitionName, expectedRevision, comment, user, req } = args;
281
- const db = config.db;
282
- const workflow = collection.workflow;
283
- if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
284
- const original = await db.findOne({ collection: collection.slug, id });
285
- if (!original) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
286
- const meta = original.__workflow;
287
- if (!meta) throw Object.assign(new Error("Entry has no workflow metadata"), { statusCode: 409 });
288
- if (expectedRevision !== void 0 && expectedRevision !== meta.revision) {
289
- throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), {
290
- statusCode: 409
291
- });
292
- }
293
- const transition = workflow.transitions.find((item) => item.name === transitionName);
294
- const fromStates = transition ? Array.isArray(transition.from) ? transition.from : [transition.from] : [];
295
- if (!transition || !fromStates.includes(meta.state)) {
296
- throw Object.assign(new Error(`Transition "${transitionName}" is not valid from "${meta.state}".`), {
297
- statusCode: 409
298
- });
299
- }
300
- if (!availableWorkflowTransitions(workflow, meta.state, user).some((item) => item.name === transition.name)) {
301
- throw Object.assign(new Error(`You do not have permission to perform "${transition.label}".`), { statusCode: 403 });
302
- }
303
- if (transition.requireComment && !comment?.trim()) {
304
- throw Object.assign(new Error(`A comment is required for "${transition.label}".`), { statusCode: 400 });
305
- }
306
- const hookContext = { transition, from: meta.state, to: transition.to, doc: original, user, comment, req, db };
307
- for (const hook of workflow.hooks?.beforeTransition ?? []) await hook(hookContext);
308
- const events = [
309
- createLifecycleEvent({
310
- name: "workflow.transitioned",
311
- collection: collection.slug,
312
- documentId: id,
313
- actorId: user?.sub,
314
- payload: { transition: transition.name, from: meta.state, to: transition.to, revision: meta.revision, comment }
315
- })
316
- ];
317
- const targetState = workflow.states.find((state) => state.name === transition.to);
318
- if (targetState.published) {
319
- events.push(
320
- createLifecycleEvent({
321
- name: "entry.published",
322
- collection: collection.slug,
323
- documentId: id,
324
- actorId: user?.sub,
325
- payload: { revision: meta.revision }
326
- })
327
- );
328
- } else if (transition.unpublish) {
329
- events.push(
330
- createLifecycleEvent({
331
- name: "entry.unpublished",
332
- collection: collection.slug,
333
- documentId: id,
334
- actorId: user?.sub,
335
- payload: { revision: meta.publishedRevision }
336
- })
337
- );
338
- }
339
- const updated = await db.transaction(async (tx) => {
340
- const locked = await tx.findOne({ collection: collection.slug, id });
341
- if (!locked) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
342
- const lockedMeta = locked.__workflow;
343
- if (lockedMeta.revision !== meta.revision || lockedMeta.state !== meta.state || expectedRevision !== void 0 && lockedMeta.revision !== expectedRevision) {
344
- throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), {
345
- statusCode: 409
346
- });
347
- }
348
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
349
- const { __published: _published, __workflow: _workflow, id: _id, ...working } = locked;
350
- const nextMeta = {
351
- ...lockedMeta,
352
- state: transition.to,
353
- ...targetState.published ? { publishedRevision: lockedMeta.revision, publishedAt: now2, publishedBy: user?.sub } : {},
354
- ...transition.unpublish ? { publishedRevision: void 0, publishedAt: void 0, publishedBy: void 0 } : {}
355
- };
356
- const data = { __workflow: nextMeta };
357
- if (targetState.published) data.__published = working;
358
- if (transition.unpublish) data.__published = null;
359
- const next = await tx.update({ collection: collection.slug, id, data });
360
- await tx.create({
361
- collection: WORKFLOW_HISTORY_COLLECTION,
362
- data: {
363
- collection: collection.slug,
364
- documentId: id,
365
- transition: transition.name,
366
- from: lockedMeta.state,
367
- to: transition.to,
368
- revision: lockedMeta.revision,
369
- comment: comment ?? null,
370
- actorId: user?.sub ?? null,
371
- createdAt: now2
372
- }
373
- });
374
- for (const event of events) await persistEvent(tx, event);
375
- if (collection.audit) {
376
- await tx.create({
377
- collection: "__audit",
378
- data: {
379
- collection: collection.slug,
380
- documentId: id,
381
- operation: "workflow.transition",
382
- user: user?.sub ?? null,
383
- timestamp: now2,
384
- changes: JSON.stringify({
385
- transition: transition.name,
386
- from: lockedMeta.state,
387
- to: transition.to,
388
- revision: lockedMeta.revision
389
- })
390
- }
391
- });
392
- }
393
- return next;
394
- });
395
- for (const event of events) void dispatchLifecycleEvent(config, event);
396
- for (const hook of workflow.hooks?.afterTransition ?? []) {
397
- try {
398
- await hook({ ...hookContext, doc: updated, event: events[0] });
399
- } catch (error) {
400
- try {
401
- const { getConfigLogger: getConfigLogger2, getObservabilityRuntime } = await import("./observability-KCMTV7GO.js");
402
- getObservabilityRuntime(config)?.recordWorkflowHookFailure({
403
- collection: collection.slug,
404
- transition: transition.name
405
- });
406
- getConfigLogger2(config, "workflow").error({
407
- err: error,
408
- msg: "afterTransition hook failed",
409
- collection: collection.slug,
410
- transition: transition.name,
411
- documentId: id
412
- });
413
- } catch {
414
- console.error("afterTransition hook failed:", error);
415
- }
416
- }
417
- }
418
- return updated;
419
- }
420
-
421
- // src/utils/admin-auth.ts
422
- function getAdminAuthCollection(config) {
423
- const adminCollection = resolveAdminAuthCollection(config.collections, config.adminAuth?.collectionSlug);
424
- return adminCollection ?? null;
425
- }
426
- function resolveAdminAuthCollection(collections, collectionSlug) {
427
- const adminsCollection = collections.find((collection) => collection.slug === "__admins");
428
- if (adminsCollection) return adminsCollection;
429
- if (collectionSlug) {
430
- const requestedCollection = collections.find((collection) => collection.slug === collectionSlug);
431
- if (requestedCollection) return requestedCollection;
432
- }
433
- return collections.find((collection) => collection.auth);
434
- }
435
- function getPublicAdminAuthConfig(adminAuth, collections) {
436
- const providers = (adminAuth?.providers ?? []).map((provider) => ({
437
- id: provider.id,
438
- type: provider.type,
439
- displayName: provider.displayName || humanizeProviderName(provider.id, provider.type),
440
- autoRedirect: provider.autoRedirect
441
- }));
442
- const resolvedCollectionSlug = collections ? resolveAdminAuthCollection(collections, adminAuth?.collectionSlug)?.slug : adminAuth?.collectionSlug;
443
- return {
444
- mode: adminAuth?.mode ?? "local",
445
- collectionSlug: resolvedCollectionSlug,
446
- provisioningMode: adminAuth?.provisioningMode,
447
- providers
448
- };
449
- }
450
- function humanizeProviderName(id, type) {
451
- const cleaned = id.replace(/[-_]+/g, " ").trim();
452
- if (!cleaned) return type.toUpperCase();
453
- return cleaned.replace(/\b\w/g, (char) => char.toUpperCase());
454
- }
455
-
456
- // src/utils/jexl-helpers.ts
457
- import jexl from "jexl";
458
- function slugify(val) {
459
- if (val === void 0 || val === null) return "";
460
- return String(val).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
461
- }
462
- function lower(val) {
463
- if (val === void 0 || val === null) return "";
464
- return String(val).toLowerCase();
465
- }
466
- function upper(val) {
467
- if (val === void 0 || val === null) return "";
468
- return String(val).toUpperCase();
469
- }
470
- function trim(val) {
471
- if (val === void 0 || val === null) return "";
472
- return String(val).trim();
473
- }
474
- function capitalize(val) {
475
- if (val === void 0 || val === null) return "";
476
- const str = String(val).trim();
477
- if (!str) return "";
478
- return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
479
- }
480
- function truncate(val, length2, ellipsis = "...") {
481
- if (val === void 0 || val === null) return "";
482
- const str = String(val);
483
- const maxLen = typeof length2 === "number" && length2 > 0 ? length2 : 100;
484
- if (str.length <= maxLen) return str;
485
- return str.slice(0, maxLen).trim() + String(ellipsis ?? "...");
486
- }
487
- function readingTime(val, wpm = 200) {
488
- if (val === void 0 || val === null) return 1;
489
- const str = String(val).trim();
490
- if (!str) return 1;
491
- const words = str.split(/\s+/).filter(Boolean).length;
492
- return Math.max(1, Math.ceil(words / (typeof wpm === "number" && wpm > 0 ? wpm : 200)));
493
- }
494
- function wordCount(val) {
495
- if (val === void 0 || val === null) return 0;
496
- const str = String(val).trim();
497
- if (!str) return 0;
498
- return str.split(/\s+/).filter(Boolean).length;
499
- }
500
- function replace(val, search, replacement) {
501
- if (val === void 0 || val === null) return "";
502
- return String(val).replace(new RegExp(String(search || ""), "g"), String(replacement ?? ""));
503
- }
504
- function startsWith(str, prefix) {
505
- if (str === void 0 || str === null) return false;
506
- return String(str).startsWith(String(prefix ?? ""));
507
- }
508
- function endsWith(str, suffix) {
509
- if (str === void 0 || str === null) return false;
510
- return String(str).endsWith(String(suffix ?? ""));
511
- }
512
- function now() {
513
- return (/* @__PURE__ */ new Date()).toISOString();
514
- }
515
- function today() {
516
- return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
517
- }
518
- function formatDate(val, style = "short") {
519
- if (!val) return "";
520
- const d = new Date(val);
521
- if (Number.isNaN(d.getTime())) return "";
522
- const styleStr = String(style).toLowerCase();
523
- if (styleStr === "iso" || styleStr === "date") return d.toISOString().slice(0, 10);
524
- if (styleStr === "datetime" || styleStr === "full") return d.toISOString();
525
- return d.toLocaleDateString("en-US", {
526
- year: "numeric",
527
- month: "short",
528
- day: "numeric"
529
- });
530
- }
531
- function addDays(val, days) {
532
- const d = val ? new Date(val) : /* @__PURE__ */ new Date();
533
- if (Number.isNaN(d.getTime())) return "";
534
- const daysNum = typeof days === "number" ? days : Number(days) || 0;
535
- d.setDate(d.getDate() + daysNum);
536
- return d.toISOString();
537
- }
538
- function diffDays(dateA, dateB) {
539
- const dA = dateA ? new Date(dateA) : /* @__PURE__ */ new Date();
540
- const dB = dateB ? new Date(dateB) : /* @__PURE__ */ new Date();
541
- if (Number.isNaN(dA.getTime()) || Number.isNaN(dB.getTime())) return 0;
542
- const diffMs = Math.abs(dA.getTime() - dB.getTime());
543
- return Math.floor(diffMs / (1e3 * 60 * 60 * 24));
544
- }
545
- function isPast(val) {
546
- if (!val) return false;
547
- const d = new Date(val);
548
- if (Number.isNaN(d.getTime())) return false;
549
- return d.getTime() < Date.now();
550
- }
551
- function isFuture(val) {
552
- if (!val) return false;
553
- const d = new Date(val);
554
- if (Number.isNaN(d.getTime())) return false;
555
- return d.getTime() > Date.now();
556
- }
557
- function includes(arrOrStr, item) {
558
- if (Array.isArray(arrOrStr)) {
559
- return arrOrStr.includes(item);
560
- }
561
- if (typeof arrOrStr === "string") {
562
- return arrOrStr.includes(String(item ?? ""));
563
- }
564
- return false;
565
- }
566
- function join(arr, separator = ", ") {
567
- if (!Array.isArray(arr)) return "";
568
- return arr.filter((item) => item !== void 0 && item !== null).join(String(separator));
569
- }
570
- function first(arr) {
571
- if (Array.isArray(arr)) return arr[0] ?? null;
572
- return null;
573
- }
574
- function last(arr) {
575
- if (Array.isArray(arr)) return arr[arr.length - 1] ?? null;
576
- return null;
577
- }
578
- function compact(arr) {
579
- if (!Array.isArray(arr)) return [];
580
- return arr.filter((item) => item !== void 0 && item !== null && item !== "");
581
- }
582
- function unique(arr) {
583
- if (!Array.isArray(arr)) return [];
584
- return Array.from(new Set(arr));
585
- }
586
- function length(val) {
587
- if (Array.isArray(val) || typeof val === "string") return val.length;
588
- if (val && typeof val === "object") return Object.keys(val).length;
589
- return 0;
590
- }
591
- function round(val, decimals = 0) {
592
- const num = Number(val);
593
- if (Number.isNaN(num)) return 0;
594
- const dec = typeof decimals === "number" ? decimals : Number(decimals) || 0;
595
- const factor = Math.pow(10, dec);
596
- return Math.round(num * factor) / factor;
597
- }
598
- function clamp(val, minVal, maxVal) {
599
- const num = Number(val) || 0;
600
- const min = Number(minVal) || 0;
601
- const max = Number(maxVal) || 0;
602
- return Math.min(Math.max(num, min), max);
603
- }
604
- function defaultValue(val, fallback) {
605
- if (val === void 0 || val === null || val === "") return fallback;
606
- return val;
607
- }
608
- function coalesce(...args) {
609
- for (const arg of args) {
610
- if (arg !== void 0 && arg !== null && arg !== "") return arg;
611
- }
612
- return null;
613
- }
614
- function isEmpty(val) {
615
- if (val === void 0 || val === null || val === "") return true;
616
- if (Array.isArray(val)) return val.length === 0;
617
- if (typeof val === "object") return Object.keys(val).length === 0;
618
- return false;
619
- }
620
- function get(obj, path, fallback = null) {
621
- if (!obj || typeof obj !== "object") return fallback;
622
- const pathStr = String(path || "").trim();
623
- if (!pathStr) return fallback;
624
- const parts = pathStr.split(".");
625
- let curr = obj;
626
- for (const part of parts) {
627
- if (curr === void 0 || curr === null) return fallback;
628
- curr = curr[part];
629
- }
630
- return curr === void 0 || curr === null ? fallback : curr;
631
- }
632
- function registerJexlHelpers(jexlInstance = jexl) {
633
- const helpers = {
634
- // Strings
635
- slugify,
636
- lower,
637
- upper,
638
- trim,
639
- capitalize,
640
- truncate,
641
- readingTime,
642
- wordCount,
643
- replace,
644
- startsWith,
645
- endsWith,
646
- // Dates
647
- now,
648
- today,
649
- formatDate,
650
- addDays,
651
- diffDays,
652
- isPast,
653
- isFuture,
654
- // Arrays
655
- includes,
656
- join,
657
- first,
658
- last,
659
- compact,
660
- unique,
661
- length,
662
- // Math
663
- round,
664
- clamp,
665
- // Objects & Logical
666
- default: defaultValue,
667
- coalesce,
668
- isEmpty,
669
- get
670
- };
671
- for (const [name, fn] of Object.entries(helpers)) {
672
- try {
673
- jexlInstance.addFunction(name, fn);
674
- } catch {
675
- }
676
- }
677
- }
678
- registerJexlHelpers(jexl);
679
- var BUILTIN_JEXL_HELPERS = [
680
- // Strings
681
- "slugify",
682
- "lower",
683
- "upper",
684
- "trim",
685
- "capitalize",
686
- "truncate",
687
- "readingTime",
688
- "wordCount",
689
- "replace",
690
- "startsWith",
691
- "endsWith",
692
- // Dates
693
- "now",
694
- "today",
695
- "formatDate",
696
- "addDays",
697
- "diffDays",
698
- "isPast",
699
- "isFuture",
700
- // Arrays
701
- "includes",
702
- "join",
703
- "first",
704
- "last",
705
- "compact",
706
- "unique",
707
- "length",
708
- // Math
709
- "round",
710
- "clamp",
711
- // Objects & Logical
712
- "default",
713
- "coalesce",
714
- "isEmpty",
715
- "get"
716
- ];
717
-
718
- // src/utils/declarative-hooks.ts
719
- import jexl2 from "jexl";
720
- registerJexlHelpers(jexl2);
721
- var SURFACE_ROOTS = {
722
- "collection.beforeRead": ["req", "user", "query", ...BUILTIN_JEXL_HELPERS],
723
- "collection.afterRead": ["req", "user", "doc", ...BUILTIN_JEXL_HELPERS],
724
- "collection.beforeChange": ["req", "user", "data", "doc", "operation", ...BUILTIN_JEXL_HELPERS],
725
- "global.beforeRead": ["req", "user", "query", ...BUILTIN_JEXL_HELPERS],
726
- "global.afterRead": ["req", "user", "doc", ...BUILTIN_JEXL_HELPERS],
727
- "global.beforeChange": ["req", "user", "data", "doc", "operation", ...BUILTIN_JEXL_HELPERS],
728
- "field.beforeChange": ["value", "data", "originalDoc", "user", ...BUILTIN_JEXL_HELPERS],
729
- "field.admin.onChange": ["value", "siblingData", "data", ...BUILTIN_JEXL_HELPERS]
730
- };
731
- var ACCESS_ROOTS = ["user", "req", "doc", "data", "id", "config", ...BUILTIN_JEXL_HELPERS];
732
- var ADMIN_CONDITION_RESERVED_ROOTS = ["data", "siblingData", "user", "id", ...BUILTIN_JEXL_HELPERS];
733
- var PREVIEW_URL_RESERVED_ROOTS = ["siteUrl", "id", ...BUILTIN_JEXL_HELPERS];
734
- var COMPILE_CACHE = /* @__PURE__ */ new Map();
735
- function compileExpression(expression) {
736
- const cached = COMPILE_CACHE.get(expression);
737
- if (cached) return cached;
738
- const compiled = jexl2.compile(expression);
739
- const next = { ast: compiled._ast };
740
- COMPILE_CACHE.set(expression, next);
741
- return next;
742
- }
743
- function isPlainObject(value) {
744
- return !!value && typeof value === "object" && !Array.isArray(value);
745
- }
746
- function quoteSegment(value) {
747
- return `["${value.replace(/"/g, '\\"')}"]`;
748
- }
749
- function fieldSegment(field, index) {
750
- return typeof field.name === "string" && field.name.length > 0 ? `fields${quoteSegment(field.name)}` : `fields[${index}]`;
751
- }
752
- function blockSegment(block, index) {
753
- return typeof block.slug === "string" && block.slug.length > 0 ? `blocks${quoteSegment(block.slug)}` : `blocks[${index}]`;
754
- }
755
- function collectionSegment(collection, index) {
756
- return typeof collection.slug === "string" && collection.slug.length > 0 ? `collections${quoteSegment(collection.slug)}` : `collections[${index}]`;
757
- }
758
- function globalSegment(global, index) {
759
- return typeof global.slug === "string" && global.slug.length > 0 ? `globals${quoteSegment(global.slug)}` : `globals[${index}]`;
760
- }
761
- function colorize(value, code, enabled) {
762
- return enabled ? `\x1B[${code}m${value}\x1B[0m` : value;
763
- }
764
- function collectRootIdentifiers(node, roots, seen) {
765
- if (!node || typeof node !== "object" || seen.has(node)) return;
766
- seen.add(node);
767
- const candidate = node;
768
- if (candidate.type === "Identifier") {
769
- if (candidate.from) {
770
- collectRootIdentifiers(candidate.from, roots, seen);
771
- return;
772
- }
773
- if (typeof candidate.value === "string" && candidate.value !== "null") {
774
- roots.add(candidate.value);
775
- }
776
- return;
777
- }
778
- if (Array.isArray(node)) {
779
- for (const entry of node) collectRootIdentifiers(entry, roots, seen);
780
- return;
781
- }
782
- for (const value of Object.values(node)) {
783
- if (Array.isArray(value)) {
784
- for (const entry of value) collectRootIdentifiers(entry, roots, seen);
785
- continue;
786
- }
787
- if (value && typeof value === "object") {
788
- collectRootIdentifiers(value, roots, seen);
789
- }
790
- }
791
- }
792
- function getInvalidRoots(expression, allowedRoots) {
793
- const { ast } = compileExpression(expression);
794
- const roots = /* @__PURE__ */ new Set();
795
- collectRootIdentifiers(ast, roots, /* @__PURE__ */ new Set());
796
- const allowed = new Set(allowedRoots);
797
- return [...roots].filter((root) => !allowed.has(root));
798
- }
799
- function validateDeclarativeHookExpression(expression, surface, path) {
800
- try {
801
- const invalidRoots = getInvalidRoots(expression, SURFACE_ROOTS[surface]);
802
- if (invalidRoots.length === 0) return [];
803
- return [
804
- {
805
- path,
806
- surface,
807
- expression,
808
- message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${SURFACE_ROOTS[surface].map((root) => `"${root}"`).join(", ")}`
809
- }
810
- ];
811
- } catch (error) {
812
- return [
813
- {
814
- path,
815
- surface,
816
- expression,
817
- message: `has invalid syntax: ${error.message}`
818
- }
819
- ];
820
- }
821
- }
822
- function validateDeclarativeAccessExpression(expression, surface, path) {
823
- try {
824
- const invalidRoots = getInvalidRoots(expression, ACCESS_ROOTS);
825
- if (invalidRoots.length === 0) return [];
826
- return [
827
- {
828
- path,
829
- surface,
830
- expression,
831
- message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${ACCESS_ROOTS.map((root) => `"${root}"`).join(", ")}`
832
- }
833
- ];
834
- } catch (error) {
835
- return [
836
- {
837
- path,
838
- surface,
839
- expression,
840
- message: `has invalid syntax: ${error.message}`
841
- }
842
- ];
843
- }
844
- }
845
- function validateAdminConditionExpression(expression, path, allowedRoots) {
846
- try {
847
- const invalidRoots = getInvalidRoots(expression, allowedRoots);
848
- if (invalidRoots.length === 0) return [];
849
- return [
850
- {
851
- path,
852
- surface: "field.admin.condition",
853
- expression,
854
- message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${allowedRoots.map((root) => `"${root}"`).join(", ")}`
855
- }
856
- ];
857
- } catch (error) {
858
- return [
859
- {
860
- path,
861
- surface: "field.admin.condition",
862
- expression,
863
- message: `has invalid syntax: ${error.message}`
864
- }
865
- ];
866
- }
867
- }
868
- function validatePreviewUrlExpression(expression, path, allowedRoots) {
869
- try {
870
- const invalidRoots = getInvalidRoots(expression, allowedRoots);
871
- if (invalidRoots.length === 0) return [];
872
- return [
873
- {
874
- path,
875
- surface: "collection.admin.previewUrl",
876
- expression,
877
- message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${allowedRoots.map((root) => `"${root}"`).join(", ")}`
878
- }
879
- ];
880
- } catch (error) {
881
- return [
882
- {
883
- path,
884
- surface: "collection.admin.previewUrl",
885
- expression,
886
- message: `has invalid syntax: ${error.message}`
887
- }
888
- ];
889
- }
890
- }
891
- function assertValidDeclarativeHookExpression(expression, surface, path) {
892
- const issues = validateDeclarativeHookExpression(expression, surface, path);
893
- if (issues.length === 0) return;
894
- throw new Error(`Invalid declarative hook at ${path}: ${issues[0].message}`);
895
- }
896
- function assertValidDeclarativeHookResult(result, surface, path) {
897
- if (isPlainObject(result)) return;
898
- throw new Error(`Invalid declarative hook result at ${path}: ${surface} expressions must return an object`);
899
- }
900
- function collectFieldIssues(fields, path, issues) {
901
- fields.forEach((field, index) => {
902
- const fieldPath = `${path}.${fieldSegment(field, index)}`;
903
- field.hooks?.beforeChange?.forEach((hook, hookIndex) => {
904
- if (typeof hook !== "string") return;
905
- issues.push(
906
- ...validateDeclarativeHookExpression(
907
- hook,
908
- "field.beforeChange",
909
- `${fieldPath}.hooks.beforeChange[${hookIndex}]`
910
- )
911
- );
912
- });
913
- field.hooks?.afterRead?.forEach((hook, hookIndex) => {
914
- if (typeof hook !== "string") return;
915
- issues.push({
916
- path: `${fieldPath}.hooks.afterRead[${hookIndex}]`,
917
- surface: "unsupported",
918
- expression: hook,
919
- message: "declarative strings are not supported on field hooks.afterRead"
920
- });
921
- });
922
- if (typeof field.admin?.hooks?.onChange === "string") {
923
- issues.push(
924
- ...validateDeclarativeHookExpression(
925
- field.admin.hooks.onChange,
926
- "field.admin.onChange",
927
- `${fieldPath}.admin.hooks.onChange`
928
- )
929
- );
930
- }
931
- if (typeof field.admin?.hooks?.options === "string") {
932
- issues.push({
933
- path: `${fieldPath}.admin.hooks.options`,
934
- surface: "unsupported",
935
- expression: field.admin.hooks.options,
936
- message: "declarative strings are not supported on field admin.hooks.options"
937
- });
938
- }
939
- if (Array.isArray(field.fields)) {
940
- collectFieldIssues(field.fields, fieldPath, issues);
941
- }
942
- if (Array.isArray(field.blocks)) {
943
- field.blocks.forEach((block, blockIndex) => {
944
- if (!Array.isArray(block.fields)) return;
945
- collectFieldIssues(block.fields, `${fieldPath}.${blockSegment(block, blockIndex)}`, issues);
946
- });
947
- }
948
- });
949
- }
950
- function collectFieldNames(fields) {
951
- return fields.flatMap(
952
- (field) => typeof field.name === "string" && field.name.length > 0 ? [field.name] : []
953
- );
954
- }
955
- function collectAdminConditionIssues(fields, path, rootFieldNames, issues) {
956
- const scopeFieldNames = collectFieldNames(fields);
957
- const allowedRoots = [.../* @__PURE__ */ new Set([...ADMIN_CONDITION_RESERVED_ROOTS, ...rootFieldNames, ...scopeFieldNames])];
958
- fields.forEach((field, index) => {
959
- const fieldPath = `${path}.${fieldSegment(field, index)}`;
960
- if (typeof field.admin?.condition === "string") {
961
- issues.push(
962
- ...validateAdminConditionExpression(
963
- field.admin.condition,
964
- `${fieldPath}.admin.condition`,
965
- allowedRoots
966
- )
967
- );
968
- }
969
- if (Array.isArray(field.fields)) {
970
- collectAdminConditionIssues(field.fields, fieldPath, rootFieldNames, issues);
971
- }
972
- if (Array.isArray(field.blocks)) {
973
- field.blocks.forEach((block, blockIndex) => {
974
- if (!Array.isArray(block.fields)) return;
975
- collectAdminConditionIssues(
976
- block.fields,
977
- `${fieldPath}.${blockSegment(block, blockIndex)}`,
978
- rootFieldNames,
979
- issues
980
- );
981
- });
982
- }
983
- });
984
- }
985
- function collectFieldAccessIssues(fields, path, issues) {
986
- fields.forEach((field, index) => {
987
- const fieldPath = `${path}.${fieldSegment(field, index)}`;
988
- if (typeof field.access?.read === "string") {
989
- issues.push(...validateDeclarativeAccessExpression(field.access.read, "field.access", `${fieldPath}.access.read`));
990
- }
991
- if (typeof field.access?.create === "string") {
992
- issues.push(
993
- ...validateDeclarativeAccessExpression(field.access.create, "field.access", `${fieldPath}.access.create`)
994
- );
995
- }
996
- if (typeof field.access?.update === "string") {
997
- issues.push(
998
- ...validateDeclarativeAccessExpression(field.access.update, "field.access", `${fieldPath}.access.update`)
999
- );
1000
- }
1001
- if (Array.isArray(field.fields)) {
1002
- collectFieldAccessIssues(field.fields, fieldPath, issues);
1003
- }
1004
- if (Array.isArray(field.blocks)) {
1005
- field.blocks.forEach((block, blockIndex) => {
1006
- if (!Array.isArray(block.fields)) return;
1007
- collectFieldAccessIssues(
1008
- block.fields,
1009
- `${fieldPath}.${blockSegment(block, blockIndex)}`,
1010
- issues
1011
- );
1012
- });
1013
- }
1014
- });
1015
- }
1016
- function collectHookIssues(hooks, scope, path, issues) {
1017
- if (!hooks) return;
1018
- const supported = {
1019
- beforeRead: `${scope}.beforeRead`,
1020
- afterRead: `${scope}.afterRead`,
1021
- beforeChange: `${scope}.beforeChange`
1022
- };
1023
- for (const [key, value] of Object.entries(hooks)) {
1024
- if (!Array.isArray(value)) continue;
1025
- value.forEach((hook, index) => {
1026
- if (typeof hook !== "string") return;
1027
- const surface = supported[key];
1028
- if (!surface) {
1029
- issues.push({
1030
- path: `${path}.${key}[${index}]`,
1031
- surface: "unsupported",
1032
- expression: hook,
1033
- message: `declarative strings are not supported on ${scope} hooks.${key}`
1034
- });
1035
- return;
1036
- }
1037
- issues.push(...validateDeclarativeHookExpression(hook, surface, `${path}.${key}[${index}]`));
1038
- });
1039
- }
1040
- }
1041
- function collectDeclarativeHookValidationIssues(config) {
1042
- const issues = [];
1043
- config.blocks?.forEach((block, blockIndex) => {
1044
- if (!Array.isArray(block.fields)) return;
1045
- collectFieldIssues(
1046
- block.fields,
1047
- blockSegment(block, blockIndex),
1048
- issues
1049
- );
1050
- });
1051
- config.collections.forEach((collection, collectionIndex) => {
1052
- const collectionPath = collectionSegment(collection, collectionIndex);
1053
- collectHookIssues(
1054
- collection.hooks,
1055
- "collection",
1056
- `${collectionPath}.hooks`,
1057
- issues
1058
- );
1059
- collectFieldIssues(collection.fields, collectionPath, issues);
1060
- });
1061
- config.globals?.forEach((global, globalIndex) => {
1062
- const globalPath = globalSegment(global, globalIndex);
1063
- collectHookIssues(
1064
- global.hooks,
1065
- "global",
1066
- `${globalPath}.hooks`,
1067
- issues
1068
- );
1069
- collectFieldIssues(global.fields, globalPath, issues);
1070
- });
1071
- return issues;
1072
- }
1073
- function collectDeclarativeAccessValidationIssues(config) {
1074
- const issues = [];
1075
- Object.entries(config.accessPolicies ?? {}).forEach(([name, value]) => {
1076
- if (typeof value !== "string") return;
1077
- issues.push(
1078
- ...validateDeclarativeAccessExpression(value, "config.accessPolicy", `accessPolicies.${name}`)
1079
- );
1080
- });
1081
- config.blocks?.forEach((block, blockIndex) => {
1082
- if (!Array.isArray(block.fields)) return;
1083
- collectFieldAccessIssues(
1084
- block.fields,
1085
- blockSegment(block, blockIndex),
1086
- issues
1087
- );
1088
- });
1089
- config.collections.forEach((collection, collectionIndex) => {
1090
- const collectionPath = collectionSegment(collection, collectionIndex);
1091
- if (typeof collection.access?.read === "string") {
1092
- issues.push(
1093
- ...validateDeclarativeAccessExpression(
1094
- collection.access.read,
1095
- "collection.access",
1096
- `${collectionPath}.access.read`
1097
- )
1098
- );
1099
- }
1100
- if (typeof collection.access?.create === "string") {
1101
- issues.push(
1102
- ...validateDeclarativeAccessExpression(
1103
- collection.access.create,
1104
- "collection.access",
1105
- `${collectionPath}.access.create`
1106
- )
1107
- );
1108
- }
1109
- if (typeof collection.access?.update === "string") {
1110
- issues.push(
1111
- ...validateDeclarativeAccessExpression(
1112
- collection.access.update,
1113
- "collection.access",
1114
- `${collectionPath}.access.update`
1115
- )
1116
- );
1117
- }
1118
- if (typeof collection.access?.delete === "string") {
1119
- issues.push(
1120
- ...validateDeclarativeAccessExpression(
1121
- collection.access.delete,
1122
- "collection.access",
1123
- `${collectionPath}.access.delete`
1124
- )
1125
- );
1126
- }
1127
- if (typeof collection.access?.readAudit === "string") {
1128
- issues.push(
1129
- ...validateDeclarativeAccessExpression(
1130
- collection.access.readAudit,
1131
- "collection.access",
1132
- `${collectionPath}.access.readAudit`
1133
- )
1134
- );
1135
- }
1136
- collectFieldAccessIssues(collection.fields, collectionPath, issues);
1137
- });
1138
- config.globals?.forEach((global, globalIndex) => {
1139
- const globalPath = globalSegment(global, globalIndex);
1140
- if (typeof global.access?.read === "string") {
1141
- issues.push(
1142
- ...validateDeclarativeAccessExpression(global.access.read, "global.access", `${globalPath}.access.read`)
1143
- );
1144
- }
1145
- if (typeof global.access?.update === "string") {
1146
- issues.push(
1147
- ...validateDeclarativeAccessExpression(
1148
- global.access.update,
1149
- "global.access",
1150
- `${globalPath}.access.update`
1151
- )
1152
- );
1153
- }
1154
- collectFieldAccessIssues(global.fields, globalPath, issues);
1155
- });
1156
- return issues;
1157
- }
1158
- function collectAdminConditionValidationIssues(config) {
1159
- const issues = [];
1160
- config.blocks?.forEach((block, blockIndex) => {
1161
- if (!Array.isArray(block.fields)) return;
1162
- collectAdminConditionIssues(
1163
- block.fields,
1164
- blockSegment(block, blockIndex),
1165
- collectFieldNames(block.fields),
1166
- issues
1167
- );
1168
- });
1169
- config.collections.forEach((collection, collectionIndex) => {
1170
- const collectionPath = collectionSegment(collection, collectionIndex);
1171
- const rootFieldNames = collectFieldNames(collection.fields);
1172
- collectAdminConditionIssues(collection.fields, collectionPath, rootFieldNames, issues);
1173
- });
1174
- config.globals?.forEach((global, globalIndex) => {
1175
- const globalPath = globalSegment(global, globalIndex);
1176
- const rootFieldNames = collectFieldNames(global.fields);
1177
- collectAdminConditionIssues(global.fields, globalPath, rootFieldNames, issues);
1178
- });
1179
- return issues;
1180
- }
1181
- function collectPreviewUrlValidationIssues(config) {
1182
- const issues = [];
1183
- config.collections.forEach((collection, collectionIndex) => {
1184
- if (typeof collection.admin?.previewUrl !== "string") return;
1185
- const collectionPath = collectionSegment(collection, collectionIndex);
1186
- const allowedRoots = [
1187
- .../* @__PURE__ */ new Set([...PREVIEW_URL_RESERVED_ROOTS, ...collectFieldNames(collection.fields)])
1188
- ];
1189
- issues.push(
1190
- ...validatePreviewUrlExpression(
1191
- collection.admin.previewUrl,
1192
- `${collectionPath}.admin.previewUrl`,
1193
- allowedRoots
1194
- )
1195
- );
1196
- });
1197
- return issues;
1198
- }
1199
- function assertValidAdminConditionsInConfig(config, source = "config") {
1200
- const diagnostics = collectAdminConditionValidationIssues(config).map((issue) => ({
1201
- severity: "error",
1202
- source: "adminCondition",
1203
- path: issue.path,
1204
- surface: issue.surface,
1205
- message: issue.message,
1206
- expression: issue.expression
1207
- }));
1208
- if (diagnostics.length === 0) return;
1209
- throw new ConfigValidationError(source, diagnostics);
1210
- }
1211
- function assertValidPreviewUrlsInConfig(config, source = "config") {
1212
- const diagnostics = collectPreviewUrlValidationIssues(config).map((issue) => ({
1213
- severity: "error",
1214
- source: "previewUrl",
1215
- path: issue.path,
1216
- surface: issue.surface,
1217
- message: issue.message,
1218
- expression: issue.expression
1219
- }));
1220
- if (diagnostics.length === 0) return;
1221
- throw new ConfigValidationError(source, diagnostics);
1222
- }
1223
- function collectConfigDiagnostics(config) {
1224
- const hookIssues = collectDeclarativeHookValidationIssues(config).map((issue) => ({
1225
- severity: "error",
1226
- source: "declarativeHook",
1227
- path: issue.path,
1228
- surface: issue.surface,
1229
- message: issue.message,
1230
- expression: issue.expression
1231
- }));
1232
- const accessIssues = collectDeclarativeAccessValidationIssues(config).map((issue) => ({
1233
- severity: "error",
1234
- source: "declarativeAccess",
1235
- path: issue.path,
1236
- surface: issue.surface,
1237
- message: issue.message,
1238
- expression: issue.expression
1239
- }));
1240
- const adminConditionIssues = collectAdminConditionValidationIssues(config).map((issue) => ({
1241
- severity: "error",
1242
- source: "adminCondition",
1243
- path: issue.path,
1244
- surface: issue.surface,
1245
- message: issue.message,
1246
- expression: issue.expression
1247
- }));
1248
- const previewUrlIssues = collectPreviewUrlValidationIssues(config).map((issue) => ({
1249
- severity: "error",
1250
- source: "previewUrl",
1251
- path: issue.path,
1252
- surface: issue.surface,
1253
- message: issue.message,
1254
- expression: issue.expression
1255
- }));
1256
- return [...hookIssues, ...accessIssues, ...adminConditionIssues, ...previewUrlIssues];
1257
- }
1258
- function formatConfigDiagnostics(source, diagnostics, options = {}) {
1259
- const color = options.color ?? false;
1260
- const header = `${colorize("Config validation failed", 31, color)} in ${colorize(source, 36, color)}`;
1261
- const docLink = `${colorize(" Learn how to write declarative rules:", 90, color)} ${colorize("https://docs.dyrected.com/docs/features/admin/form-and-field-hooks", 34, color)}`;
1262
- const lines = diagnostics.flatMap((issue, index) => [
1263
- `${colorize(`${index + 1}.`, 31, color)} ${colorize(issue.path, 1, color)}`,
1264
- ` ${issue.message}`,
1265
- ` ${colorize("surface:", 90, color)} ${issue.surface}`
1266
- ]);
1267
- return `${header}
1268
- ${lines.join("\n")}
1269
-
1270
- ${docLink}`;
1271
- }
1272
- var ConfigValidationError = class extends Error {
1273
- diagnostics;
1274
- source;
1275
- constructor(source, diagnostics) {
1276
- super(formatConfigDiagnostics(source, diagnostics));
1277
- this.name = "ConfigValidationError";
1278
- this.source = source;
1279
- this.diagnostics = diagnostics;
1280
- }
1281
- };
1282
- function isConfigValidationError(error) {
1283
- return error instanceof ConfigValidationError;
1284
- }
1285
- function assertValidDeclarativeHooksInConfig(config, source = "config") {
1286
- const diagnostics = collectDeclarativeHookValidationIssues(config).map((issue) => ({
1287
- severity: "error",
1288
- source: "declarativeHook",
1289
- path: issue.path,
1290
- surface: issue.surface,
1291
- message: issue.message,
1292
- expression: issue.expression
1293
- }));
1294
- if (diagnostics.length === 0) return;
1295
- throw new ConfigValidationError(source, diagnostics);
1296
- }
1297
- function assertValidDeclarativeAccessInConfig(config, source = "config") {
1298
- const diagnostics = collectDeclarativeAccessValidationIssues(config).map((issue) => ({
1299
- severity: "error",
1300
- source: "declarativeAccess",
1301
- path: issue.path,
1302
- surface: issue.surface,
1303
- message: issue.message,
1304
- expression: issue.expression
1305
- }));
1306
- if (diagnostics.length === 0) return;
1307
- throw new ConfigValidationError(source, diagnostics);
1308
- }
1309
-
1310
- // src/auth/token.ts
1311
- import { SignJWT, jwtVerify, decodeJwt } from "jose";
1312
- import { TextEncoder } from "util";
1313
- function getSecret() {
1314
- const secret = process.env.DYRECTED_JWT_SECRET;
1315
- if (!secret) {
1316
- throw new Error(
1317
- "[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
1318
- );
1319
- }
1320
- return new TextEncoder().encode(secret);
1321
- }
1322
- var DEFAULT_EXPIRY = "7d";
1323
- async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
1324
- return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
1325
- }
1326
- async function verifyCollectionToken(token) {
1327
- const { payload } = await jwtVerify(token, getSecret());
1328
- return payload;
1329
- }
1330
- function decodeCollectionToken(token) {
1331
- try {
1332
- return decodeJwt(token);
1333
- } catch {
1334
- return null;
1335
- }
1336
- }
1337
-
1338
- // src/auth/sessions.ts
1339
- var AUTH_SESSIONS_COLLECTION = "__auth_sessions";
1340
- async function issueAuthSessionToken(args) {
1341
- const sessionId = createSessionId();
1342
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
1343
- const db = args.config.db;
1344
- if (db) {
1345
- await db.create({
1346
- collection: AUTH_SESSIONS_COLLECTION,
1347
- data: {
1348
- id: sessionId,
1349
- userId: args.userId,
1350
- email: args.email,
1351
- collection: args.collection,
1352
- authSource: args.authSource ?? "local",
1353
- providerId: args.providerId,
1354
- lastIp: args.ip,
1355
- lastSeenAt: now2,
1356
- revokedAt: null,
1357
- expiresAt: null
1358
- }
1359
- });
1360
- }
1361
- const token = await signCollectionToken(
1362
- {
1363
- sub: args.userId,
1364
- email: args.email,
1365
- collection: args.collection,
1366
- authSource: args.authSource,
1367
- providerId: args.providerId,
1368
- sid: sessionId
1369
- },
1370
- args.expiresIn
1371
- );
1372
- const payload = decodeCollectionToken(token);
1373
- const expiresAt = payload?.exp != null ? new Date(payload.exp * 1e3).toISOString() : null;
1374
- if (db && expiresAt) {
1375
- await db.update({
1376
- collection: AUTH_SESSIONS_COLLECTION,
1377
- id: sessionId,
1378
- data: {
1379
- expiresAt,
1380
- lastSeenAt: now2,
1381
- lastIp: args.ip
1382
- }
1383
- });
1384
- }
1385
- return token;
1386
- }
1387
- async function getAuthSession(config, sessionId) {
1388
- const db = config.db;
1389
- if (!db) return null;
1390
- return await db.findOne({
1391
- collection: AUTH_SESSIONS_COLLECTION,
1392
- id: sessionId
1393
- });
1394
- }
1395
- function isAuthSessionActive(session) {
1396
- if (!session) return false;
1397
- if (session.revokedAt) return false;
1398
- if (session.expiresAt && new Date(session.expiresAt).getTime() <= Date.now()) {
1399
- return false;
1400
- }
1401
- return true;
1402
- }
1403
- async function touchAuthSession(config, sessionId, args) {
1404
- const db = config.db;
1405
- if (!db) return;
1406
- await db.update({
1407
- collection: AUTH_SESSIONS_COLLECTION,
1408
- id: sessionId,
1409
- data: {
1410
- lastSeenAt: (/* @__PURE__ */ new Date()).toISOString(),
1411
- ...args.ip ? { lastIp: args.ip } : {}
1412
- }
1413
- });
1414
- }
1415
- async function revokeAuthSession(config, sessionId) {
1416
- const db = config.db;
1417
- if (!db) return;
1418
- await db.update({
1419
- collection: AUTH_SESSIONS_COLLECTION,
1420
- id: sessionId,
1421
- data: {
1422
- revokedAt: (/* @__PURE__ */ new Date()).toISOString()
1423
- }
1424
- });
1425
- }
1426
- async function revokeAllAuthSessions(config, args) {
1427
- const db = config.db;
1428
- if (!db) return 0;
1429
- let page = 1;
1430
- let revoked = 0;
1431
- while (true) {
1432
- const result = await db.find({
1433
- collection: AUTH_SESSIONS_COLLECTION,
1434
- where: {
1435
- userId: { equals: args.userId },
1436
- collection: { equals: args.collection }
1437
- },
1438
- page,
1439
- limit: 100
1440
- });
1441
- for (const session of result.docs) {
1442
- if (session.revokedAt) continue;
1443
- await revokeAuthSession(config, session.id);
1444
- revoked += 1;
1445
- }
1446
- if (!result.hasNextPage) break;
1447
- page += 1;
1448
- }
1449
- return revoked;
1450
- }
1451
- function createSessionId() {
1452
- return globalThis.crypto?.randomUUID?.() ? globalThis.crypto.randomUUID() : `sess_${Date.now()}_${Math.random().toString(36).slice(2)}`;
1453
- }
1454
-
1455
- // src/utils/block-references.ts
1456
- function mergeUniqueBlocks(blocks) {
1457
- const seen = /* @__PURE__ */ new Map();
1458
- for (const block of blocks) {
1459
- const existing = seen.get(block.slug);
1460
- if (existing && existing !== block) {
1461
- throw new Error(
1462
- `Duplicate block slug "${block.slug}" found in the reusable block registry. Block slugs must be unique.`
1463
- );
1464
- }
1465
- if (!existing) seen.set(block.slug, block);
1466
- }
1467
- return Array.from(seen.values());
1468
- }
1469
- function buildRegistry(blocks) {
1470
- return new Map(blocks.map((block) => [block.slug, block]));
1471
- }
1472
- function resolveField(field, registry, blockCache) {
1473
- const next = { ...field };
1474
- if (next.fields) {
1475
- next.fields = next.fields.map(
1476
- (child) => resolveField(child, registry, blockCache)
1477
- );
1478
- }
1479
- if (next.type !== "blocks") return next;
1480
- const hasInlineBlocks = Array.isArray(next.blocks) && next.blocks.length > 0;
1481
- const hasReferences = Array.isArray(next.blockReferences) && next.blockReferences.length > 0;
1482
- if (hasInlineBlocks && hasReferences) {
1483
- throw new Error(
1484
- `Blocks field "${next.name ?? "(unnamed)"}" cannot define both "blocks" and "blockReferences". Use one or the other.`
1485
- );
1486
- }
1487
- if (hasReferences) {
1488
- next.blocks = next.blockReferences.map((slug) => {
1489
- const block = registry.get(slug);
1490
- if (!block) {
1491
- throw new Error(
1492
- `Unknown block reference "${slug}" on blocks field "${next.name ?? "(unnamed)"}". Add it to defineConfig({ blocks: [...] }).`
1493
- );
1494
- }
1495
- return resolveBlock(block, registry, blockCache);
1496
- });
1497
- return next;
1498
- }
1499
- if (hasInlineBlocks) {
1500
- next.blocks = next.blocks.map(
1501
- (block) => resolveBlock(block, registry, blockCache)
1502
- );
1503
- }
1504
- return next;
1505
- }
1506
- function resolveBlock(block, registry, blockCache) {
1507
- const cached = blockCache.get(block);
1508
- if (cached) return cached;
1509
- const resolved = {
1510
- ...block,
1511
- fields: []
1512
- };
1513
- blockCache.set(block, resolved);
1514
- resolved.fields = block.fields.map(
1515
- (field) => resolveField(field, registry, blockCache)
1516
- );
1517
- return resolved;
1518
- }
1519
- function resolveFields(fields, registry, blockCache) {
1520
- return fields.map((field) => resolveField(field, registry, blockCache));
1521
- }
1522
- function normalizeSchemaFragment(fragment) {
1523
- const reusableBlocks = mergeUniqueBlocks(fragment.blocks ?? []);
1524
- const registry = buildRegistry(reusableBlocks);
1525
- const blockCache = /* @__PURE__ */ new WeakMap();
1526
- const resolvedBlocks = reusableBlocks.map(
1527
- (block) => resolveBlock(block, registry, blockCache)
1528
- );
1529
- const resolvedCollections = (fragment.collections ?? []).map(
1530
- (collection) => ({
1531
- ...collection,
1532
- fields: resolveFields(collection.fields ?? [], registry, blockCache)
1533
- })
1534
- );
1535
- const resolvedGlobals = (fragment.globals ?? []).map((global) => ({
1536
- ...global,
1537
- fields: resolveFields(global.fields ?? [], registry, blockCache)
1538
- }));
1539
- return {
1540
- ...fragment,
1541
- ...fragment.blocks ? { blocks: resolvedBlocks } : {},
1542
- ...fragment.collections ? { collections: resolvedCollections } : {},
1543
- ...fragment.globals ? { globals: resolvedGlobals } : {}
1544
- };
1545
- }
1546
- function mergeDynamicConfig(baseConfig, dynamic) {
1547
- const normalizedDynamic = normalizeSchemaFragment({
1548
- ...dynamic,
1549
- blocks: [...baseConfig.blocks ?? [], ...dynamic.blocks ?? []]
1550
- });
1551
- return {
1552
- ...baseConfig,
1553
- ...normalizedDynamic.blocks ? { blocks: normalizedDynamic.blocks } : {},
1554
- ...dynamic.accessPolicies ? {
1555
- accessPolicies: {
1556
- ...baseConfig.accessPolicies ?? {},
1557
- ...dynamic.accessPolicies
1558
- }
1559
- } : {},
1560
- ...dynamic.admin ? { admin: { ...baseConfig.admin, ...dynamic.admin } } : {},
1561
- ...dynamic.adminAuth ? { adminAuth: { ...baseConfig.adminAuth, ...dynamic.adminAuth } } : {},
1562
- collections: normalizedDynamic.collections ? [...baseConfig.collections, ...normalizedDynamic.collections] : baseConfig.collections,
1563
- globals: normalizedDynamic.globals ? [...baseConfig.globals, ...normalizedDynamic.globals] : baseConfig.globals
1564
- };
1565
- }
1566
-
1567
- // src/utils/config.ts
1568
- var AUDIT_COLLECTION_SLUG = "__audit";
1569
- var SYSTEM_FIELDS = [
1570
- {
1571
- name: "createdAt",
1572
- type: "date",
1573
- label: "Created At",
1574
- admin: { readOnly: true, hidden: true }
1575
- },
1576
- {
1577
- name: "updatedAt",
1578
- type: "date",
1579
- label: "Updated At",
1580
- admin: { readOnly: true, hidden: true }
1581
- },
1582
- {
1583
- name: "createdBy",
1584
- type: "text",
1585
- label: "Created By",
1586
- admin: { readOnly: true, hidden: true }
1587
- },
1588
- {
1589
- name: "updatedBy",
1590
- type: "text",
1591
- label: "Updated By",
1592
- admin: { readOnly: true, hidden: true }
1593
- }
1594
- ];
1595
- var AUDIT_COLLECTION = {
1596
- slug: AUDIT_COLLECTION_SLUG,
1597
- labels: { singular: "Audit Log", plural: "Audit Logs" },
1598
- fields: [
1599
- { name: "collection", type: "text", label: "Collection", required: true },
1600
- { name: "documentId", type: "text", label: "Document ID" },
1601
- {
1602
- name: "operation",
1603
- type: "select",
1604
- label: "Operation",
1605
- options: ["create", "update", "delete"],
1606
- required: true
1607
- },
1608
- { name: "user", type: "text", label: "User ID" },
1609
- { name: "timestamp", type: "date", label: "Timestamp", required: true },
1610
- { name: "changes", type: "json", label: "Changes" }
1611
- ],
1612
- access: {
1613
- read: () => false,
1614
- create: () => false,
1615
- update: () => false,
1616
- delete: () => false
1617
- },
1618
- admin: { hidden: true }
1619
- };
1620
- var WORKFLOW_HISTORY_COLLECTION_CONFIG = {
1621
- slug: WORKFLOW_HISTORY_COLLECTION,
1622
- labels: { singular: "Workflow transition", plural: "Workflow transitions" },
1623
- fields: [
1624
- { name: "collection", type: "text", required: true },
1625
- { name: "documentId", type: "text", required: true },
1626
- { name: "transition", type: "text", required: true },
1627
- { name: "from", type: "text", required: true },
1628
- { name: "to", type: "text", required: true },
1629
- { name: "revision", type: "number", required: true },
1630
- { name: "comment", type: "textarea" },
1631
- { name: "actorId", type: "text" },
1632
- { name: "createdAt", type: "date", required: true }
1633
- ],
1634
- access: {
1635
- read: ({ user }) => !!user,
1636
- create: () => false,
1637
- update: () => false,
1638
- delete: () => false
1639
- },
1640
- admin: { hidden: true }
1641
- };
1642
- var LIFECYCLE_EVENTS_COLLECTION_CONFIG = {
1643
- slug: LIFECYCLE_EVENTS_COLLECTION,
1644
- labels: { singular: "Lifecycle event", plural: "Lifecycle events" },
1645
- fields: [
1646
- { name: "name", type: "text", required: true },
1647
- { name: "collection", type: "text", required: true },
1648
- { name: "documentId", type: "text", required: true },
1649
- { name: "occurredAt", type: "date", required: true },
1650
- { name: "actorId", type: "text" },
1651
- { name: "payload", type: "json", required: true },
1652
- { name: "attempts", type: "number", required: true },
1653
- {
1654
- name: "status",
1655
- type: "select",
1656
- options: ["pending", "processing", "delivered", "failed"],
1657
- required: true
1658
- },
1659
- { name: "nextAttemptAt", type: "date" },
1660
- { name: "deliveredAt", type: "date" },
1661
- { name: "lastError", type: "textarea" }
1662
- ],
1663
- access: {
1664
- read: ({ user }) => !!user?.roles?.includes("admin"),
1665
- create: () => false,
1666
- update: () => false,
1667
- delete: () => false
1668
- },
1669
- admin: { hidden: true }
1670
- };
1671
- var AUTH_SESSIONS_COLLECTION_CONFIG = {
1672
- slug: AUTH_SESSIONS_COLLECTION,
1673
- labels: { singular: "Auth session", plural: "Auth sessions" },
1674
- fields: [
1675
- { name: "userId", type: "text", required: true },
1676
- { name: "email", type: "email", required: true },
1677
- { name: "collection", type: "text", required: true },
1678
- { name: "authSource", type: "text" },
1679
- { name: "providerId", type: "text" },
1680
- { name: "lastIp", type: "text" },
1681
- { name: "lastSeenAt", type: "date" },
1682
- { name: "expiresAt", type: "date" },
1683
- { name: "revokedAt", type: "date" }
1684
- ],
1685
- access: {
1686
- read: () => false,
1687
- create: () => false,
1688
- update: () => false,
1689
- delete: () => false
1690
- },
1691
- admin: { hidden: true }
1692
- };
1693
- function normalizeConfig(config) {
1694
- const schemaAwareConfig = normalizeSchemaFragment(config);
1695
- assertValidDeclarativeHooksInConfig(schemaAwareConfig, "config");
1696
- assertValidDeclarativeAccessInConfig(schemaAwareConfig, "config");
1697
- assertValidAdminConditionsInConfig(schemaAwareConfig, "config");
1698
- assertValidPreviewUrlsInConfig(schemaAwareConfig, "config");
1699
- const collections = schemaAwareConfig?.collections || [];
1700
- const globals = schemaAwareConfig?.globals || [];
1701
- const needsAudit = collections.some((col) => col.audit);
1702
- const needsWorkflow = collections.some((col) => col.workflow || col.drafts);
1703
- const needsAuthSessions = collections.some((col) => !!col.auth);
1704
- const adminAuthCollectionSlug = getAdminAuthCollection({
1705
- collections,
1706
- adminAuth: schemaAwareConfig.adminAuth
1707
- })?.slug;
1708
- const normalizedCollections = collections.map((col) => {
1709
- let fields = col.fields || [];
1710
- const existingFieldNames = new Set(fields.map((f) => f.name));
1711
- if (col.auth) {
1712
- if (!existingFieldNames.has("email")) {
1713
- fields = [
1714
- ...fields,
1715
- {
1716
- name: "email",
1717
- type: "email",
1718
- label: "Email",
1719
- required: true,
1720
- unique: true,
1721
- promoted: true,
1722
- access: {
1723
- update: "!id"
1724
- }
1725
- }
1726
- ];
1727
- }
1728
- if (!existingFieldNames.has("password")) {
1729
- fields = [
1730
- ...fields,
1731
- {
1732
- name: "password",
1733
- type: "text",
1734
- label: "Password",
1735
- required: true,
1736
- access: {
1737
- update: "!id || user.id == id"
1738
- }
1739
- }
1740
- ];
1741
- }
1742
- if (!existingFieldNames.has("roles")) {
1743
- fields = [
1744
- ...fields,
1745
- {
1746
- name: "roles",
1747
- type: "select",
1748
- label: "Roles",
1749
- defaultValue: [],
1750
- options: [
1751
- { value: "admin", label: "Admin" },
1752
- { value: "editor", label: "Editor" },
1753
- { value: "viewer", label: "Viewer" }
1754
- ],
1755
- access: {
1756
- update: "user.roles && 'admin' in user.roles"
1757
- }
1758
- }
1759
- ];
1760
- }
1761
- if (!existingFieldNames.has("status")) {
1762
- fields = [
1763
- ...fields,
1764
- {
1765
- name: "status",
1766
- type: "select",
1767
- label: "Status",
1768
- defaultValue: "active",
1769
- options: [
1770
- { value: "active", label: "Active" },
1771
- { value: "pending", label: "Pending" }
1772
- ],
1773
- access: {
1774
- update: "user.roles && 'admin' in user.roles && user.id != id"
1775
- },
1776
- admin: {
1777
- condition: `!(data.roles && "admin" in data.roles)`
1778
- }
1779
- }
1780
- ];
1781
- }
1782
- fields = fields.map((field) => {
1783
- if (field.name === "email") {
1784
- return {
1785
- ...field,
1786
- // Email is the login identifier. Keep the integrity constraints
1787
- // auth relies on even when the field is explicitly redefined, so a
1788
- // custom `email` field can never silently drop uniqueness.
1789
- required: true,
1790
- unique: true,
1791
- promoted: true,
1792
- access: {
1793
- ...field.access || {},
1794
- update: "!id"
1795
- }
1796
- };
1797
- }
1798
- if (field.name === "password") {
1799
- return {
1800
- ...field,
1801
- // Password is required to authenticate; enforce it regardless of
1802
- // how the field was declared.
1803
- required: true,
1804
- admin: { ...field.admin || {} },
1805
- access: {
1806
- ...field.access || {},
1807
- update: "!id || user.id == id"
1808
- }
1809
- };
1810
- }
1811
- if (field.name === "roles") {
1812
- return {
1813
- ...field,
1814
- access: {
1815
- ...field.access || {},
1816
- // Must be an admin; cannot edit own roles (no self-elevation).
1817
- update: "user.roles && 'admin' in user.roles && user.id != id"
1818
- }
1819
- };
1820
- }
1821
- if (field.name === "status") {
1822
- return {
1823
- ...field,
1824
- access: {
1825
- ...field.access || {},
1826
- update: "user.roles && 'admin' in user.roles && user.id != id"
1827
- }
1828
- };
1829
- }
1830
- return field;
1831
- });
1832
- }
1833
- if (adminAuthCollectionSlug && col.slug === adminAuthCollectionSlug && schemaAwareConfig.adminAuth?.mode === "external") {
1834
- const externalAdminFields = [
1835
- {
1836
- name: "authProvider",
1837
- type: "text",
1838
- label: "Auth Provider",
1839
- admin: { readOnly: true, hidden: true }
1840
- },
1841
- {
1842
- name: "externalSubject",
1843
- type: "text",
1844
- label: "External Subject",
1845
- admin: { readOnly: true, hidden: true }
1846
- },
1847
- {
1848
- name: "authSource",
1849
- type: "text",
1850
- label: "Auth Source",
1851
- admin: { readOnly: true, hidden: true }
1852
- },
1853
- {
1854
- name: "lastLoginAt",
1855
- type: "date",
1856
- label: "Last Login At",
1857
- admin: { readOnly: true, hidden: true }
1858
- }
1859
- ];
1860
- for (const field of externalAdminFields) {
1861
- if (!existingFieldNames.has(field.name)) {
1862
- fields = [...fields, field];
1863
- }
1864
- }
1865
- }
1866
- const updatedFieldNames = new Set(fields.map((f) => f.name));
1867
- const fieldsToInject = SYSTEM_FIELDS.filter((f) => !updatedFieldNames.has(f.name));
1868
- const workflow = col.workflow || (col.drafts ? simplePublishingWorkflow() : void 0);
1869
- return {
1870
- ...col,
1871
- workflow,
1872
- fields: [...fields, ...fieldsToInject]
1873
- };
1874
- });
1875
- const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
1876
- const systemCollections = [];
1877
- if (needsAudit && !hasAuditCollection) systemCollections.push(AUDIT_COLLECTION);
1878
- if (needsWorkflow && !normalizedCollections.some((col) => col.slug === WORKFLOW_HISTORY_COLLECTION)) {
1879
- systemCollections.push(WORKFLOW_HISTORY_COLLECTION_CONFIG);
1880
- }
1881
- if (needsWorkflow && !normalizedCollections.some((col) => col.slug === LIFECYCLE_EVENTS_COLLECTION)) {
1882
- systemCollections.push(LIFECYCLE_EVENTS_COLLECTION_CONFIG);
1883
- }
1884
- if (needsAuthSessions && !normalizedCollections.some((col) => col.slug === AUTH_SESSIONS_COLLECTION)) {
1885
- systemCollections.push(AUTH_SESSIONS_COLLECTION_CONFIG);
1886
- }
1887
- return {
1888
- ...schemaAwareConfig,
1889
- collections: [...normalizedCollections, ...systemCollections],
1890
- globals
1891
- };
1892
- }
1893
-
1894
- // src/utils/hooks.ts
1895
- import jexl3 from "jexl";
1896
- async function runCollectionHooks(hooks, args, options = {}) {
1897
- if (!hooks || hooks.length === 0) {
1898
- return args.data ?? args.doc ?? args.query ?? void 0;
1899
- }
1900
- const payloadKey = args.data !== void 0 ? "data" : args.doc !== void 0 ? "doc" : "query" in args ? "query" : void 0;
1901
- let currentPayload = payloadKey === void 0 ? void 0 : args[payloadKey];
1902
- for (const hook of hooks) {
1903
- try {
1904
- const hookArgs = {
1905
- ...args,
1906
- ...payloadKey !== void 0 ? { [payloadKey]: currentPayload } : {}
1907
- };
1908
- const result = typeof hook === "string" ? await (() => {
1909
- if (options.surface) {
1910
- assertValidDeclarativeHookExpression(
1911
- hook,
1912
- options.surface,
1913
- options.path ?? options.surface
1914
- );
1915
- }
1916
- return jexl3.eval(hook, hookArgs);
1917
- })() : await hook(hookArgs);
1918
- if (result !== void 0) {
1919
- if (typeof hook === "string" && options.surface) {
1920
- assertValidDeclarativeHookResult(
1921
- result,
1922
- options.surface,
1923
- options.path ?? options.surface
1924
- );
1925
- }
1926
- currentPayload = typeof hook === "string" && currentPayload && typeof currentPayload === "object" && !Array.isArray(currentPayload) && result && typeof result === "object" && !Array.isArray(result) ? {
1927
- ...currentPayload,
1928
- ...result
1929
- } : result;
1930
- }
1931
- } catch (err) {
1932
- if (options.isolated) {
1933
- getConfigLogger(void 0, "hooks").error({
1934
- err,
1935
- msg: "Side-effect hook failed after a successful write"
1936
- });
1937
- } else {
1938
- throw err;
1939
- }
1940
- }
1941
- }
1942
- return currentPayload;
1943
- }
1944
- async function executeFieldBeforeChange(fields, data, originalDoc, user, db, pathPrefix = "") {
1945
- if (!data || typeof data !== "object") return data;
1946
- const result = { ...data };
1947
- for (const field of fields) {
1948
- if (!field.name) continue;
1949
- const fieldPath = pathPrefix ? `${pathPrefix}.${field.name}` : field.name;
1950
- const value = result[field.name];
1951
- const origValue = originalDoc?.[field.name];
1952
- let updatedValue = value;
1953
- if (field.hooks?.beforeChange) {
1954
- for (const hook of field.hooks.beforeChange) {
1955
- const hookArgs = {
1956
- value: updatedValue,
1957
- originalDoc: originalDoc ?? void 0,
1958
- data: result,
1959
- user,
1960
- db
1961
- };
1962
- updatedValue = typeof hook === "string" ? await (() => {
1963
- assertValidDeclarativeHookExpression(
1964
- hook,
1965
- "field.beforeChange",
1966
- fieldPath
1967
- );
1968
- return jexl3.eval(hook, hookArgs);
1969
- })() : await hook(hookArgs);
1970
- }
1971
- result[field.name] = updatedValue;
1972
- }
1973
- if (updatedValue !== void 0 && updatedValue !== null) {
1974
- if (field.type === "object" && field.fields) {
1975
- result[field.name] = await executeFieldBeforeChange(
1976
- field.fields,
1977
- updatedValue,
1978
- origValue,
1979
- user,
1980
- db,
1981
- fieldPath
1982
- );
1983
- } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
1984
- const arrayResult = [];
1985
- for (let i = 0; i < updatedValue.length; i++) {
1986
- const item = updatedValue[i];
1987
- const origItem = Array.isArray(origValue) ? origValue[i] : null;
1988
- arrayResult.push(
1989
- await executeFieldBeforeChange(
1990
- field.fields,
1991
- item,
1992
- origItem,
1993
- user,
1994
- db,
1995
- fieldPath
1996
- )
1997
- );
1998
- }
1999
- result[field.name] = arrayResult;
2000
- } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
2001
- const blocksResult = [];
2002
- for (let i = 0; i < updatedValue.length; i++) {
2003
- const blockData = updatedValue[i];
2004
- const origBlock = Array.isArray(origValue) ? origValue[i] : null;
2005
- const blockConfig = field.blocks.find(
2006
- (b) => b.slug === blockData.blockType
2007
- );
2008
- if (blockConfig) {
2009
- blocksResult.push(
2010
- await executeFieldBeforeChange(
2011
- blockConfig.fields,
2012
- blockData,
2013
- origBlock,
2014
- user,
2015
- db,
2016
- fieldPath
2017
- )
2018
- );
2019
- } else {
2020
- blocksResult.push(blockData);
2021
- }
2022
- }
2023
- result[field.name] = blocksResult;
2024
- }
2025
- }
2026
- }
2027
- return result;
2028
- }
2029
- async function executeFieldAfterRead(fields, doc, user, db) {
2030
- if (!doc || typeof doc !== "object") return doc;
2031
- const result = { ...doc };
2032
- for (const field of fields) {
2033
- if (!field.name) continue;
2034
- const value = result[field.name];
2035
- let updatedValue = value;
2036
- if (field.hooks?.afterRead) {
2037
- for (const hook of field.hooks.afterRead) {
2038
- const typedHook = hook;
2039
- const hookArgs = {
2040
- value: updatedValue,
2041
- doc: result,
2042
- user,
2043
- db
2044
- };
2045
- updatedValue = await typedHook(hookArgs);
2046
- }
2047
- result[field.name] = updatedValue;
2048
- }
2049
- if (updatedValue !== void 0 && updatedValue !== null) {
2050
- if (field.type === "object" && field.fields) {
2051
- result[field.name] = await executeFieldAfterRead(
2052
- field.fields,
2053
- updatedValue,
2054
- user,
2055
- db
2056
- );
2057
- } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
2058
- const arrayResult = [];
2059
- for (const item of updatedValue) {
2060
- arrayResult.push(
2061
- await executeFieldAfterRead(
2062
- field.fields,
2063
- item,
2064
- user,
2065
- db
2066
- )
2067
- );
2068
- }
2069
- result[field.name] = arrayResult;
2070
- } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
2071
- const blocksResult = [];
2072
- for (const blockData of updatedValue) {
2073
- const typedBlock = blockData;
2074
- const blockConfig = field.blocks.find(
2075
- (b) => b.slug === typedBlock.blockType
2076
- );
2077
- if (blockConfig) {
2078
- blocksResult.push(
2079
- await executeFieldAfterRead(
2080
- blockConfig.fields,
2081
- typedBlock,
2082
- user,
2083
- db
2084
- )
2085
- );
2086
- } else {
2087
- blocksResult.push(blockData);
2088
- }
2089
- }
2090
- result[field.name] = blocksResult;
2091
- }
2092
- }
2093
- }
2094
- return result;
2095
- }
2096
-
2097
- // src/utils/openapi.ts
2098
- function getCollectionLabels(collection) {
2099
- return collection.labels || { singular: collection.slug, plural: collection.slug };
2100
- }
2101
- function getCollectionTag(collection) {
2102
- return `Collection: ${getCollectionLabels(collection).plural}`;
2103
- }
2104
- function getGlobalTag(global) {
2105
- return `Global: ${global.label || global.slug}`;
2106
- }
2107
- function generateOpenApi(config) {
2108
- const spec = {
2109
- openapi: "3.0.0",
2110
- info: {
2111
- title: "Dyrected API",
2112
- version: "1.0.0",
2113
- description: "Automatically generated OpenAPI specification for the Dyrected project."
2114
- },
2115
- components: {
2116
- schemas: {
2117
- WorkflowMetadata: {
2118
- type: "object",
2119
- required: ["state", "revision"],
2120
- properties: {
2121
- state: { type: "string" },
2122
- revision: { type: "integer", minimum: 1 },
2123
- publishedRevision: { type: "integer", minimum: 1 },
2124
- publishedAt: { type: "string", format: "date-time" },
2125
- publishedBy: { type: "string" },
2126
- availableTransitions: { type: "array", items: { type: "string" } }
2127
- }
2128
- },
2129
- WorkflowTransitionRequest: {
2130
- type: "object",
2131
- properties: {
2132
- expectedRevision: { type: "integer", minimum: 1 },
2133
- comment: { type: "string" }
2134
- }
2135
- },
2136
- WorkflowHistoryEntry: {
2137
- type: "object",
2138
- required: [
2139
- "collection",
2140
- "documentId",
2141
- "transition",
2142
- "from",
2143
- "to",
2144
- "revision",
2145
- "createdAt"
2146
- ],
2147
- properties: {
2148
- id: { type: "string" },
2149
- collection: { type: "string" },
2150
- documentId: { type: "string" },
2151
- transition: { type: "string" },
2152
- from: { type: "string" },
2153
- to: { type: "string" },
2154
- revision: { type: "integer" },
2155
- comment: { type: "string", nullable: true },
2156
- actorId: { type: "string", nullable: true },
2157
- createdAt: { type: "string", format: "date-time" }
2158
- }
2159
- },
2160
- AuditEntry: {
2161
- type: "object",
2162
- required: ["collection", "operation", "timestamp"],
2163
- properties: {
2164
- id: { type: "string" },
2165
- collection: { type: "string" },
2166
- documentId: { type: "string", nullable: true },
2167
- operation: { type: "string" },
2168
- user: { type: "string", nullable: true },
2169
- timestamp: { type: "string", format: "date-time" },
2170
- changes: {
2171
- oneOf: [
2172
- { type: "string" },
2173
- { type: "object", additionalProperties: true },
2174
- { type: "null" }
2175
- ]
2176
- }
2177
- }
2178
- },
2179
- Error: {
2180
- type: "object",
2181
- properties: {
2182
- message: { type: "string" },
2183
- errors: {
2184
- type: "array",
2185
- items: { type: "object", additionalProperties: true }
2186
- }
2187
- }
2188
- },
2189
- AuthCredentials: {
2190
- type: "object",
2191
- required: ["email", "password"],
2192
- properties: {
2193
- email: { type: "string", format: "email" },
2194
- password: { type: "string" }
2195
- }
2196
- },
2197
- TokenResponse: {
2198
- type: "object",
2199
- properties: {
2200
- token: { type: "string" },
2201
- user: { type: "object", additionalProperties: true }
2202
- }
2203
- }
2204
- },
2205
- securitySchemes: {
2206
- ApiKeyAuth: {
2207
- type: "apiKey",
2208
- in: "header",
2209
- name: "x-api-key"
2210
- }
2211
- }
2212
- },
2213
- paths: {},
2214
- security: [{ ApiKeyAuth: [] }]
2215
- };
2216
- spec.paths["/api/schemas"] = {
2217
- get: {
2218
- tags: ["System"],
2219
- summary: "Get the serialized Dyrected schema",
2220
- security: [],
2221
- responses: {
2222
- 200: { description: "Collection and global schema definitions" }
2223
- }
2224
- }
2225
- };
2226
- spec.paths["/api/openapi.json"] = {
2227
- get: {
2228
- tags: ["System"],
2229
- summary: "Get the OpenAPI specification",
2230
- security: [],
2231
- responses: { 200: { description: "OpenAPI 3.0 document" } }
2232
- }
2233
- };
2234
- spec.paths["/api/docs"] = {
2235
- get: {
2236
- tags: ["System"],
2237
- summary: "Open interactive API documentation",
2238
- security: [],
2239
- responses: { 200: { description: "Swagger UI HTML" } }
2240
- }
2241
- };
2242
- spec.paths["/api/dyrected/options/{collection}/{field}"] = {
2243
- get: {
2244
- tags: ["System"],
2245
- summary: "Resolve dynamic field options",
2246
- parameters: [
2247
- {
2248
- name: "collection",
2249
- in: "path",
2250
- required: true,
2251
- schema: { type: "string" }
2252
- },
2253
- {
2254
- name: "field",
2255
- in: "path",
2256
- required: true,
2257
- schema: { type: "string" }
2258
- }
2259
- ],
2260
- responses: { 200: { description: "Resolved option items" } }
2261
- }
2262
- };
2263
- spec.paths["/api/preferences/{key}"] = {
2264
- get: {
2265
- tags: ["Preferences"],
2266
- summary: "Get an authenticated user preference",
2267
- parameters: [
2268
- { name: "key", in: "path", required: true, schema: { type: "string" } }
2269
- ],
2270
- responses: { 200: { description: "Preference value" } }
2271
- },
2272
- put: {
2273
- tags: ["Preferences"],
2274
- summary: "Set an authenticated user preference",
2275
- parameters: [
2276
- { name: "key", in: "path", required: true, schema: { type: "string" } }
2277
- ],
2278
- requestBody: {
2279
- required: true,
2280
- content: { "application/json": { schema: { type: "object" } } }
2281
- },
2282
- responses: { 200: { description: "Updated preference" } }
2283
- }
2284
- };
2285
- spec.paths["/api/preview-token"] = {
2286
- post: {
2287
- tags: ["Preview"],
2288
- summary: "Create a preview token",
2289
- responses: { 200: { description: "Short-lived preview token" } }
2290
- }
2291
- };
2292
- spec.paths["/api/preview-data"] = {
2293
- get: {
2294
- tags: ["Preview"],
2295
- summary: "Resolve preview data from a token",
2296
- security: [],
2297
- parameters: [
2298
- {
2299
- name: "token",
2300
- in: "query",
2301
- required: true,
2302
- schema: { type: "string" }
2303
- }
2304
- ],
2305
- responses: { 200: { description: "Preview document data" } }
2306
- }
2307
- };
2308
- spec.paths["/api/audit"] = {
2309
- get: {
2310
- tags: ["Audit"],
2311
- summary: "Get audit entries across all readable audited collections",
2312
- parameters: [
2313
- {
2314
- name: "limit",
2315
- in: "query",
2316
- schema: { type: "integer", default: 50, maximum: 100 }
2317
- },
2318
- { name: "page", in: "query", schema: { type: "integer", default: 1 } },
2319
- {
2320
- name: "where",
2321
- in: "query",
2322
- schema: { type: "string" },
2323
- description: "JSON filter"
2324
- },
2325
- {
2326
- name: "sort",
2327
- in: "query",
2328
- schema: { type: "string", default: "-timestamp" }
2329
- }
2330
- ],
2331
- responses: {
2332
- 200: {
2333
- description: "Audit entries",
2334
- content: {
2335
- "application/json": {
2336
- schema: {
2337
- type: "object",
2338
- properties: {
2339
- docs: {
2340
- type: "array",
2341
- items: { $ref: "#/components/schemas/AuditEntry" }
2342
- },
2343
- total: { type: "integer" },
2344
- limit: { type: "integer" },
2345
- page: { type: "integer" }
2346
- }
2347
- }
2348
- }
2349
- }
2350
- }
2351
- }
2352
- }
2353
- };
2354
- for (const collection of config.collections) {
2355
- spec.components.schemas[collection.slug] = collectionToSchema(collection);
2356
- }
2357
- for (const global of config.globals) {
2358
- spec.components.schemas[global.slug] = globalToSchema(global);
2359
- }
2360
- for (const collection of config.collections) {
2361
- const slug = collection.slug;
2362
- const path = `/api/collections/${slug}`;
2363
- const labels = getCollectionLabels(collection);
2364
- const collectionTag = getCollectionTag(collection);
2365
- spec.paths[path] = {
2366
- get: {
2367
- tags: [collectionTag],
2368
- summary: `Find ${labels.plural}`,
2369
- parameters: [
2370
- {
2371
- name: "limit",
2372
- in: "query",
2373
- schema: { type: "integer", default: 10 }
2374
- },
2375
- {
2376
- name: "page",
2377
- in: "query",
2378
- schema: { type: "integer", default: 1 }
2379
- },
2380
- {
2381
- name: "where",
2382
- in: "query",
2383
- schema: { type: "string" },
2384
- description: "JSON filter"
2385
- },
2386
- {
2387
- name: "search",
2388
- in: "query",
2389
- schema: { type: "string" },
2390
- description: "Free-text search across configured searchable fields"
2391
- },
2392
- {
2393
- name: "sort",
2394
- in: "query",
2395
- schema: { type: "string" },
2396
- description: "Sort field (e.g. -createdAt)"
2397
- }
2398
- ],
2399
- responses: {
2400
- 200: {
2401
- description: "Success",
2402
- content: {
2403
- "application/json": {
2404
- schema: {
2405
- type: "object",
2406
- properties: {
2407
- docs: {
2408
- type: "array",
2409
- items: { $ref: `#/components/schemas/${slug}` }
2410
- },
2411
- total: { type: "integer" },
2412
- limit: { type: "integer" },
2413
- page: { type: "integer" }
2414
- }
2415
- }
2416
- }
2417
- }
2418
- }
2419
- }
2420
- },
2421
- post: {
2422
- tags: [collectionTag],
2423
- summary: `Create ${labels.singular}`,
2424
- requestBody: {
2425
- required: true,
2426
- content: {
2427
- "application/json": {
2428
- schema: { $ref: `#/components/schemas/${slug}` }
2429
- }
2430
- }
2431
- },
2432
- responses: {
2433
- 201: {
2434
- description: "Created",
2435
- content: {
2436
- "application/json": {
2437
- schema: { $ref: `#/components/schemas/${slug}` }
2438
- }
2439
- }
2440
- }
2441
- }
2442
- }
2443
- };
2444
- spec.paths[`${path}/{id}`] = {
2445
- get: {
2446
- tags: [collectionTag],
2447
- summary: `Get a single ${labels.singular}`,
2448
- parameters: [
2449
- {
2450
- name: "id",
2451
- in: "path",
2452
- required: true,
2453
- schema: { type: "string" }
2454
- }
2455
- ],
2456
- responses: {
2457
- 200: {
2458
- description: "Success",
2459
- content: {
2460
- "application/json": {
2461
- schema: { $ref: `#/components/schemas/${slug}` }
2462
- }
2463
- }
2464
- }
2465
- }
2466
- },
2467
- patch: {
2468
- tags: [collectionTag],
2469
- summary: `Update ${labels.singular}`,
2470
- parameters: [
2471
- {
2472
- name: "id",
2473
- in: "path",
2474
- required: true,
2475
- schema: { type: "string" }
2476
- }
2477
- ],
2478
- requestBody: {
2479
- required: true,
2480
- content: {
2481
- "application/json": {
2482
- schema: { $ref: `#/components/schemas/${slug}` }
2483
- }
2484
- }
2485
- },
2486
- responses: {
2487
- 200: {
2488
- description: "Updated",
2489
- content: {
2490
- "application/json": {
2491
- schema: { $ref: `#/components/schemas/${slug}` }
2492
- }
2493
- }
2494
- }
2495
- }
2496
- },
2497
- delete: {
2498
- tags: [collectionTag],
2499
- summary: `Delete ${labels.singular}`,
2500
- parameters: [
2501
- {
2502
- name: "id",
2503
- in: "path",
2504
- required: true,
2505
- schema: { type: "string" }
2506
- }
2507
- ],
2508
- responses: {
2509
- 204: { description: "Deleted" }
2510
- }
2511
- }
2512
- };
2513
- spec.paths[`${path}/delete-many`] = {
2514
- delete: {
2515
- tags: [collectionTag],
2516
- summary: `Delete multiple ${labels.plural}`,
2517
- requestBody: {
2518
- required: true,
2519
- content: {
2520
- "application/json": {
2521
- schema: {
2522
- type: "object",
2523
- required: ["ids"],
2524
- properties: {
2525
- ids: { type: "array", items: { type: "string" } }
2526
- }
2527
- }
2528
- }
2529
- }
2530
- },
2531
- responses: { 200: { description: "Deleted and failed document IDs" } }
2532
- }
2533
- };
2534
- if (collection.audit) {
2535
- spec.paths[`${path}/__audit`] = {
2536
- get: {
2537
- tags: [collectionTag],
2538
- summary: `Get ${labels.singular} audit entries`,
2539
- parameters: [
2540
- {
2541
- name: "limit",
2542
- in: "query",
2543
- schema: { type: "integer", default: 50, maximum: 100 }
2544
- },
2545
- {
2546
- name: "page",
2547
- in: "query",
2548
- schema: { type: "integer", default: 1 }
2549
- },
2550
- {
2551
- name: "where",
2552
- in: "query",
2553
- schema: { type: "string" },
2554
- description: "JSON filter"
2555
- },
2556
- {
2557
- name: "sort",
2558
- in: "query",
2559
- schema: { type: "string", default: "-timestamp" }
2560
- }
2561
- ],
2562
- responses: {
2563
- 200: {
2564
- description: "Audit entries for this collection",
2565
- content: {
2566
- "application/json": {
2567
- schema: {
2568
- type: "object",
2569
- properties: {
2570
- docs: {
2571
- type: "array",
2572
- items: { $ref: "#/components/schemas/AuditEntry" }
2573
- },
2574
- total: { type: "integer" },
2575
- limit: { type: "integer" },
2576
- page: { type: "integer" }
2577
- }
2578
- }
2579
- }
2580
- }
2581
- },
2582
- 403: { description: "Collection read access denied" },
2583
- 404: { description: "Audit is not enabled for this collection" }
2584
- }
2585
- }
2586
- };
2587
- }
2588
- if (collection.upload) {
2589
- spec.paths[`${path}/media`] = {
2590
- get: {
2591
- tags: [collectionTag],
2592
- summary: `List ${labels.plural}`,
2593
- responses: { 200: { description: "Paginated media documents" } }
2594
- },
2595
- post: {
2596
- tags: [collectionTag],
2597
- summary: `Upload ${labels.singular}`,
2598
- requestBody: {
2599
- required: true,
2600
- content: {
2601
- "multipart/form-data": {
2602
- schema: {
2603
- type: "object",
2604
- required: ["file"],
2605
- properties: { file: { type: "string", format: "binary" } }
2606
- }
2607
- }
2608
- }
2609
- },
2610
- responses: { 201: { description: "Uploaded media document" } }
2611
- }
2612
- };
2613
- spec.paths[`${path}/media/{filename}`] = {
2614
- get: {
2615
- tags: [collectionTag],
2616
- summary: `Serve ${labels.singular} bytes`,
2617
- parameters: [
2618
- {
2619
- name: "filename",
2620
- in: "path",
2621
- required: true,
2622
- schema: { type: "string" }
2623
- }
2624
- ],
2625
- security: [],
2626
- responses: {
2627
- 200: { description: "Stored file" },
2628
- 404: { description: "File not found" }
2629
- }
2630
- }
2631
- };
2632
- }
2633
- if (collection.auth) {
2634
- const publicAuthPost = (summary) => ({
2635
- tags: [collectionTag],
2636
- summary,
2637
- security: [],
2638
- requestBody: {
2639
- required: true,
2640
- content: {
2641
- "application/json": {
2642
- schema: { type: "object", additionalProperties: true }
2643
- }
2644
- }
2645
- },
2646
- responses: {
2647
- 200: { description: "Success" },
2648
- 400: { description: "Invalid request" }
2649
- }
2650
- });
2651
- spec.paths[`${path}/login`] = {
2652
- post: {
2653
- ...publicAuthPost(`Log in to ${labels.plural}`),
2654
- requestBody: {
2655
- required: true,
2656
- content: {
2657
- "application/json": {
2658
- schema: { $ref: "#/components/schemas/AuthCredentials" }
2659
- }
2660
- }
2661
- },
2662
- responses: {
2663
- 200: {
2664
- description: "Authenticated",
2665
- content: {
2666
- "application/json": {
2667
- schema: { $ref: "#/components/schemas/TokenResponse" }
2668
- }
2669
- }
2670
- },
2671
- 401: { description: "Invalid credentials" }
2672
- }
2673
- }
2674
- };
2675
- spec.paths[`${path}/logout`] = {
2676
- post: {
2677
- tags: [collectionTag],
2678
- summary: `Log out of ${labels.plural}`,
2679
- parameters: [
2680
- {
2681
- name: "allSessions",
2682
- in: "query",
2683
- required: false,
2684
- schema: { type: "boolean" },
2685
- description: "Revoke every active session for this account instead of only the current one."
2686
- }
2687
- ],
2688
- responses: { 200: { description: "Logged out" } }
2689
- }
2690
- };
2691
- spec.paths[`${path}/init`] = {
2692
- get: {
2693
- tags: [collectionTag],
2694
- summary: `Get ${labels.plural} initialization state`,
2695
- security: [],
2696
- responses: { 200: { description: "Initialization state" } }
2697
- }
2698
- };
2699
- spec.paths[`${path}/first-user`] = {
2700
- post: publicAuthPost(`Register the first ${labels.singular}`)
2701
- };
2702
- spec.paths[`${path}/me`] = {
2703
- get: {
2704
- tags: [collectionTag],
2705
- summary: `Get the current ${labels.singular}`,
2706
- responses: { 200: { description: "Authenticated user" } }
2707
- }
2708
- };
2709
- spec.paths[`${path}/refresh-token`] = {
2710
- post: {
2711
- tags: [collectionTag],
2712
- summary: "Refresh an authentication token",
2713
- responses: {
2714
- 200: {
2715
- description: "Refreshed token for the current active session"
2716
- }
2717
- }
2718
- }
2719
- };
2720
- spec.paths[`${path}/forgot-password`] = {
2721
- post: publicAuthPost("Request a password reset")
2722
- };
2723
- spec.paths[`${path}/reset-password`] = {
2724
- post: publicAuthPost("Reset a password")
2725
- };
2726
- spec.paths[`${path}/invite`] = {
2727
- post: {
2728
- tags: [collectionTag],
2729
- summary: `Invite a ${labels.singular}`,
2730
- responses: { 200: { description: "Invitation sent" } }
2731
- }
2732
- };
2733
- spec.paths[`${path}/accept-invite`] = {
2734
- post: publicAuthPost("Accept an invitation")
2735
- };
2736
- spec.paths[`${path}/{id}/change-password`] = {
2737
- post: {
2738
- tags: [collectionTag],
2739
- summary: `Change a ${labels.singular} password`,
2740
- parameters: [
2741
- {
2742
- name: "id",
2743
- in: "path",
2744
- required: true,
2745
- schema: { type: "string" }
2746
- }
2747
- ],
2748
- responses: {
2749
- 200: {
2750
- description: "Password changed and active sessions revoked"
2751
- }
2752
- }
2753
- }
2754
- };
2755
- }
2756
- if (collection.workflow) {
2757
- spec.paths[`${path}/{id}/transitions/{transition}`] = {
2758
- post: {
2759
- tags: [collectionTag],
2760
- summary: `Transition ${labels.singular} workflow`,
2761
- parameters: [
2762
- {
2763
- name: "id",
2764
- in: "path",
2765
- required: true,
2766
- schema: { type: "string" }
2767
- },
2768
- {
2769
- name: "transition",
2770
- in: "path",
2771
- required: true,
2772
- schema: {
2773
- type: "string",
2774
- enum: collection.workflow.transitions.map((item) => item.name)
2775
- }
2776
- }
2777
- ],
2778
- requestBody: {
2779
- content: {
2780
- "application/json": {
2781
- schema: {
2782
- $ref: "#/components/schemas/WorkflowTransitionRequest"
2783
- }
2784
- }
2785
- }
2786
- },
2787
- responses: {
2788
- 200: {
2789
- description: "Transition applied",
2790
- content: {
2791
- "application/json": {
2792
- schema: { $ref: `#/components/schemas/${slug}` }
2793
- }
2794
- }
2795
- },
2796
- 400: { description: "Required transition input is missing" },
2797
- 403: { description: "Transition capability denied" },
2798
- 409: { description: "Invalid state or stale revision" }
2799
- }
2800
- }
2801
- };
2802
- spec.paths[`${path}/{id}/workflow-history`] = {
2803
- get: {
2804
- tags: [collectionTag],
2805
- summary: `Get ${labels.singular} workflow history`,
2806
- parameters: [
2807
- {
2808
- name: "id",
2809
- in: "path",
2810
- required: true,
2811
- schema: { type: "string" }
2812
- },
2813
- {
2814
- name: "limit",
2815
- in: "query",
2816
- schema: { type: "integer", default: 50, maximum: 100 }
2817
- }
2818
- ],
2819
- responses: {
2820
- 200: {
2821
- description: "Workflow transition history",
2822
- content: {
2823
- "application/json": {
2824
- schema: {
2825
- type: "object",
2826
- properties: {
2827
- docs: {
2828
- type: "array",
2829
- items: {
2830
- $ref: "#/components/schemas/WorkflowHistoryEntry"
2831
- }
2832
- },
2833
- total: { type: "integer" },
2834
- limit: { type: "integer" },
2835
- page: { type: "integer" }
2836
- }
2837
- }
2838
- }
2839
- }
2840
- },
2841
- 403: { description: "Collection read access denied" }
2842
- }
2843
- }
2844
- };
2845
- }
2846
- }
2847
- for (const global of config.globals) {
2848
- const slug = global.slug;
2849
- const path = `/api/globals/${slug}`;
2850
- const globalTag = getGlobalTag(global);
2851
- spec.paths[path] = {
2852
- get: {
2853
- tags: [globalTag],
2854
- summary: `Get ${global.label || slug}`,
2855
- responses: {
2856
- 200: {
2857
- description: "Success",
2858
- content: {
2859
- "application/json": {
2860
- schema: { $ref: `#/components/schemas/${slug}` }
2861
- }
2862
- }
2863
- }
2864
- }
2865
- },
2866
- patch: {
2867
- tags: [globalTag],
2868
- summary: `Update ${global.label || slug}`,
2869
- requestBody: {
2870
- required: true,
2871
- content: {
2872
- "application/json": {
2873
- schema: { $ref: `#/components/schemas/${slug}` }
2874
- }
2875
- }
2876
- },
2877
- responses: {
2878
- 200: {
2879
- description: "Updated",
2880
- content: {
2881
- "application/json": {
2882
- schema: { $ref: `#/components/schemas/${slug}` }
2883
- }
2884
- }
2885
- }
2886
- }
2887
- }
2888
- };
2889
- }
2890
- if (config.storage) {
2891
- spec.paths["/api/media/{filename}"] = {
2892
- get: {
2893
- tags: ["Media"],
2894
- summary: "Serve a stored file",
2895
- security: [],
2896
- parameters: [
2897
- {
2898
- name: "filename",
2899
- in: "path",
2900
- required: true,
2901
- schema: { type: "string" }
2902
- }
2903
- ],
2904
- responses: {
2905
- 200: { description: "Stored file bytes" },
2906
- 404: { description: "File not found" }
2907
- }
2908
- }
2909
- };
2910
- }
2911
- return spec;
2912
- }
2913
- function collectionToSchema(collection) {
2914
- const { properties, required } = fieldsToProperties(collection.fields);
2915
- return {
2916
- type: "object",
2917
- properties: {
2918
- id: { type: "string" },
2919
- createdAt: { type: "string", format: "date-time" },
2920
- updatedAt: { type: "string", format: "date-time" },
2921
- ...collection.workflow ? { _workflow: { $ref: "#/components/schemas/WorkflowMetadata" } } : {},
2922
- ...properties
2923
- },
2924
- required: ["id", ...required]
2925
- };
2926
- }
2927
- function globalToSchema(global) {
2928
- const { properties, required } = fieldsToProperties(global.fields);
2929
- return {
2930
- type: "object",
2931
- properties,
2932
- required
2933
- };
2934
- }
2935
- function fieldsToProperties(fields) {
2936
- const props = {};
2937
- const required = [];
2938
- for (const field of fields) {
2939
- if (field.type === "row") {
2940
- const nested = fieldsToProperties(field.fields || []);
2941
- Object.assign(props, nested.properties);
2942
- required.push(...nested.required);
2943
- continue;
2944
- }
2945
- if (!field.name) continue;
2946
- props[field.name] = fieldToSchema(field);
2947
- if (field.required) {
2948
- required.push(field.name);
2949
- }
2950
- }
2951
- return { properties: props, required };
2952
- }
2953
- function fieldToSchema(field) {
2954
- let schema;
2955
- switch (field.type) {
2956
- case "text":
2957
- case "textarea":
2958
- case "email":
2959
- schema = { type: "string" };
2960
- break;
2961
- case "url":
2962
- schema = {
2963
- oneOf: [
2964
- { type: "string" },
2965
- { type: "object", additionalProperties: true }
2966
- ]
2967
- };
2968
- break;
2969
- case "icon":
2970
- schema = { type: "string" };
2971
- break;
2972
- case "number":
2973
- schema = { type: "number" };
2974
- break;
2975
- case "boolean":
2976
- schema = { type: "boolean" };
2977
- break;
2978
- case "date":
2979
- schema = { type: "string", format: "date" };
2980
- break;
2981
- case "datetime":
2982
- schema = { type: "string", format: "date-time" };
2983
- break;
2984
- case "time":
2985
- schema = { type: "string", format: "time" };
2986
- break;
2987
- case "select":
2988
- case "radio":
2989
- schema = {
2990
- type: "string",
2991
- enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
2992
- };
2993
- break;
2994
- case "multiSelect":
2995
- schema = {
2996
- type: "array",
2997
- items: {
2998
- type: "string",
2999
- enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
3000
- }
3001
- };
3002
- break;
3003
- case "relationship":
3004
- case "image": {
3005
- const valueSchema = {
3006
- type: "string",
3007
- description: `ID of a ${field.relationTo} record`
3008
- };
3009
- schema = field.hasMany ? { type: "array", items: valueSchema } : valueSchema;
3010
- break;
3011
- }
3012
- case "join":
3013
- schema = {
3014
- type: "array",
3015
- readOnly: true,
3016
- items: { type: "object", additionalProperties: true }
3017
- };
3018
- break;
3019
- case "object": {
3020
- const { properties, required } = fieldsToProperties(field.fields || []);
3021
- schema = { type: "object", properties, required };
3022
- break;
3023
- }
3024
- case "array": {
3025
- const { properties, required } = fieldsToProperties(field.fields || []);
3026
- schema = {
3027
- type: "array",
3028
- items: { type: "object", properties, required }
3029
- };
3030
- break;
3031
- }
3032
- case "json":
3033
- case "richText":
3034
- schema = { type: "object", additionalProperties: true };
3035
- break;
3036
- case "blocks":
3037
- schema = {
3038
- type: "array",
3039
- items: {
3040
- oneOf: field.blocks?.map((block) => {
3041
- const { properties, required } = fieldsToProperties(block.fields);
3042
- return {
3043
- type: "object",
3044
- properties: {
3045
- blockType: { type: "string", enum: [block.slug] },
3046
- ...properties
3047
- },
3048
- required: ["blockType", ...required]
3049
- };
3050
- })
3051
- }
3052
- };
3053
- break;
3054
- default:
3055
- schema = { type: "string" };
3056
- }
3057
- if (field.label) schema.description = field.label;
3058
- return schema;
3059
- }
3060
-
3061
- export {
3062
- signCollectionToken,
3063
- verifyCollectionToken,
3064
- issueAuthSessionToken,
3065
- getAuthSession,
3066
- isAuthSessionActive,
3067
- touchAuthSession,
3068
- revokeAuthSession,
3069
- revokeAllAuthSessions,
3070
- WORKFLOW_HISTORY_COLLECTION,
3071
- LIFECYCLE_EVENTS_COLLECTION,
3072
- definePublishingWorkflow,
3073
- publishingWorkflow,
3074
- simplePublishingWorkflow,
3075
- workflowCapabilities,
3076
- canViewWorkflowDraft,
3077
- availableWorkflowTransitions,
3078
- initializeWorkflowDocument,
3079
- publishedStateName,
3080
- materializeWorkflowDocument,
3081
- createLifecycleEvent,
3082
- dispatchLifecycleEvent,
3083
- dispatchPendingLifecycleEvents,
3084
- saveWorkflowDraft,
3085
- createWorkflowDocument,
3086
- transitionWorkflow,
3087
- getAdminAuthCollection,
3088
- resolveAdminAuthCollection,
3089
- getPublicAdminAuthConfig,
3090
- mergeDynamicConfig,
3091
- slugify,
3092
- lower,
3093
- upper,
3094
- trim,
3095
- capitalize,
3096
- truncate,
3097
- readingTime,
3098
- wordCount,
3099
- replace,
3100
- startsWith,
3101
- endsWith,
3102
- now,
3103
- today,
3104
- formatDate,
3105
- addDays,
3106
- diffDays,
3107
- isPast,
3108
- isFuture,
3109
- includes,
3110
- join,
3111
- first,
3112
- last,
3113
- compact,
3114
- unique,
3115
- length,
3116
- round,
3117
- clamp,
3118
- defaultValue,
3119
- coalesce,
3120
- isEmpty,
3121
- get,
3122
- registerJexlHelpers,
3123
- BUILTIN_JEXL_HELPERS,
3124
- validateDeclarativeHookExpression,
3125
- validateDeclarativeAccessExpression,
3126
- validateAdminConditionExpression,
3127
- validatePreviewUrlExpression,
3128
- assertValidDeclarativeHookExpression,
3129
- assertValidDeclarativeHookResult,
3130
- collectDeclarativeHookValidationIssues,
3131
- collectDeclarativeAccessValidationIssues,
3132
- collectAdminConditionValidationIssues,
3133
- collectPreviewUrlValidationIssues,
3134
- assertValidAdminConditionsInConfig,
3135
- assertValidPreviewUrlsInConfig,
3136
- collectConfigDiagnostics,
3137
- formatConfigDiagnostics,
3138
- ConfigValidationError,
3139
- isConfigValidationError,
3140
- assertValidDeclarativeHooksInConfig,
3141
- assertValidDeclarativeAccessInConfig,
3142
- normalizeConfig,
3143
- runCollectionHooks,
3144
- executeFieldBeforeChange,
3145
- executeFieldAfterRead,
3146
- generateOpenApi
3147
- };