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