@strapi/content-manager 0.0.0 → 5.0.0-beta.10

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 (510) hide show
  1. package/README.md +9 -1
  2. package/dist/_chunks/CardDragPreview-C0QyJgRA.js +69 -0
  3. package/dist/_chunks/CardDragPreview-C0QyJgRA.js.map +1 -0
  4. package/dist/_chunks/CardDragPreview-DOxamsuj.mjs +70 -0
  5. package/dist/_chunks/CardDragPreview-DOxamsuj.mjs.map +1 -0
  6. package/dist/_chunks/ComponentConfigurationPage-BNrZY1Rt.js +255 -0
  7. package/dist/_chunks/ComponentConfigurationPage-BNrZY1Rt.js.map +1 -0
  8. package/dist/_chunks/ComponentConfigurationPage-DF4KsgJw.mjs +236 -0
  9. package/dist/_chunks/ComponentConfigurationPage-DF4KsgJw.mjs.map +1 -0
  10. package/dist/_chunks/ComponentIcon-BXdiCGQp.js +176 -0
  11. package/dist/_chunks/ComponentIcon-BXdiCGQp.js.map +1 -0
  12. package/dist/_chunks/ComponentIcon-u4bIXTFY.mjs +157 -0
  13. package/dist/_chunks/ComponentIcon-u4bIXTFY.mjs.map +1 -0
  14. package/dist/_chunks/EditConfigurationPage-CzBCnSlY.js +151 -0
  15. package/dist/_chunks/EditConfigurationPage-CzBCnSlY.js.map +1 -0
  16. package/dist/_chunks/EditConfigurationPage-Dn7sFfOu.mjs +132 -0
  17. package/dist/_chunks/EditConfigurationPage-Dn7sFfOu.mjs.map +1 -0
  18. package/dist/_chunks/EditViewPage-CEemNwSu.js +222 -0
  19. package/dist/_chunks/EditViewPage-CEemNwSu.js.map +1 -0
  20. package/dist/_chunks/EditViewPage-D2uq2uZS.mjs +203 -0
  21. package/dist/_chunks/EditViewPage-D2uq2uZS.mjs.map +1 -0
  22. package/dist/_chunks/Field-DvB4ig_f.mjs +5466 -0
  23. package/dist/_chunks/Field-DvB4ig_f.mjs.map +1 -0
  24. package/dist/_chunks/Field-KHBYihjn.js +5498 -0
  25. package/dist/_chunks/Field-KHBYihjn.js.map +1 -0
  26. package/dist/_chunks/FieldTypeIcon-CMlNO8PE.mjs +50 -0
  27. package/dist/_chunks/FieldTypeIcon-CMlNO8PE.mjs.map +1 -0
  28. package/dist/_chunks/FieldTypeIcon-Dnwq_IRF.js +49 -0
  29. package/dist/_chunks/FieldTypeIcon-Dnwq_IRF.js.map +1 -0
  30. package/dist/_chunks/Form-BGmF27Mb.mjs +739 -0
  31. package/dist/_chunks/Form-BGmF27Mb.mjs.map +1 -0
  32. package/dist/_chunks/Form-De_O8dNp.js +760 -0
  33. package/dist/_chunks/Form-De_O8dNp.js.map +1 -0
  34. package/dist/_chunks/History-Cqq6Csvj.mjs +1007 -0
  35. package/dist/_chunks/History-Cqq6Csvj.mjs.map +1 -0
  36. package/dist/_chunks/History-aALwb_34.js +1028 -0
  37. package/dist/_chunks/History-aALwb_34.js.map +1 -0
  38. package/dist/_chunks/ListConfigurationPage-Bke2024Z.mjs +620 -0
  39. package/dist/_chunks/ListConfigurationPage-Bke2024Z.mjs.map +1 -0
  40. package/dist/_chunks/ListConfigurationPage-DimG1pln.js +640 -0
  41. package/dist/_chunks/ListConfigurationPage-DimG1pln.js.map +1 -0
  42. package/dist/_chunks/ListViewPage-BO-JvrUA.js +834 -0
  43. package/dist/_chunks/ListViewPage-BO-JvrUA.js.map +1 -0
  44. package/dist/_chunks/ListViewPage-Cjbh5jyY.mjs +810 -0
  45. package/dist/_chunks/ListViewPage-Cjbh5jyY.mjs.map +1 -0
  46. package/dist/_chunks/NoContentTypePage-S-R1DXX2.js +51 -0
  47. package/dist/_chunks/NoContentTypePage-S-R1DXX2.js.map +1 -0
  48. package/dist/_chunks/NoContentTypePage-m6_m6mFn.mjs +51 -0
  49. package/dist/_chunks/NoContentTypePage-m6_m6mFn.mjs.map +1 -0
  50. package/dist/_chunks/NoPermissionsPage-CCMchuOR.mjs +23 -0
  51. package/dist/_chunks/NoPermissionsPage-CCMchuOR.mjs.map +1 -0
  52. package/dist/_chunks/NoPermissionsPage-wFEMKcdV.js +23 -0
  53. package/dist/_chunks/NoPermissionsPage-wFEMKcdV.js.map +1 -0
  54. package/dist/_chunks/Relations-PjEVbLqZ.js +714 -0
  55. package/dist/_chunks/Relations-PjEVbLqZ.js.map +1 -0
  56. package/dist/_chunks/Relations-i8F_imXr.mjs +694 -0
  57. package/dist/_chunks/Relations-i8F_imXr.mjs.map +1 -0
  58. package/dist/_chunks/ar-BUUWXIYu.js +226 -0
  59. package/dist/_chunks/ar-BUUWXIYu.js.map +1 -0
  60. package/dist/_chunks/ar-CCEVvqGG.mjs +226 -0
  61. package/dist/_chunks/ar-CCEVvqGG.mjs.map +1 -0
  62. package/dist/_chunks/ca-5U32ON2v.mjs +201 -0
  63. package/dist/_chunks/ca-5U32ON2v.mjs.map +1 -0
  64. package/dist/_chunks/ca-Cmk45QO6.js +201 -0
  65. package/dist/_chunks/ca-Cmk45QO6.js.map +1 -0
  66. package/dist/_chunks/cs-CM2aBUar.mjs +125 -0
  67. package/dist/_chunks/cs-CM2aBUar.mjs.map +1 -0
  68. package/dist/_chunks/cs-CkJy6B2v.js +125 -0
  69. package/dist/_chunks/cs-CkJy6B2v.js.map +1 -0
  70. package/dist/_chunks/de-C72KDNOl.mjs +199 -0
  71. package/dist/_chunks/de-C72KDNOl.mjs.map +1 -0
  72. package/dist/_chunks/de-CCEmbAah.js +199 -0
  73. package/dist/_chunks/de-CCEmbAah.js.map +1 -0
  74. package/dist/_chunks/en-Ux26r5pl.mjs +291 -0
  75. package/dist/_chunks/en-Ux26r5pl.mjs.map +1 -0
  76. package/dist/_chunks/en-fbKQxLGn.js +291 -0
  77. package/dist/_chunks/en-fbKQxLGn.js.map +1 -0
  78. package/dist/_chunks/es-CeXiYflN.mjs +196 -0
  79. package/dist/_chunks/es-CeXiYflN.mjs.map +1 -0
  80. package/dist/_chunks/es-EUonQTon.js +196 -0
  81. package/dist/_chunks/es-EUonQTon.js.map +1 -0
  82. package/dist/_chunks/eu-CdALomew.mjs +202 -0
  83. package/dist/_chunks/eu-CdALomew.mjs.map +1 -0
  84. package/dist/_chunks/eu-VDH-3ovk.js +202 -0
  85. package/dist/_chunks/eu-VDH-3ovk.js.map +1 -0
  86. package/dist/_chunks/fr-B7kGGg3E.js +206 -0
  87. package/dist/_chunks/fr-B7kGGg3E.js.map +1 -0
  88. package/dist/_chunks/fr-CD9VFbPM.mjs +206 -0
  89. package/dist/_chunks/fr-CD9VFbPM.mjs.map +1 -0
  90. package/dist/_chunks/gu-BRmF601H.js +200 -0
  91. package/dist/_chunks/gu-BRmF601H.js.map +1 -0
  92. package/dist/_chunks/gu-CNpaMDpH.mjs +200 -0
  93. package/dist/_chunks/gu-CNpaMDpH.mjs.map +1 -0
  94. package/dist/_chunks/hi-CCJBptSq.js +200 -0
  95. package/dist/_chunks/hi-CCJBptSq.js.map +1 -0
  96. package/dist/_chunks/hi-Dwvd04m3.mjs +200 -0
  97. package/dist/_chunks/hi-Dwvd04m3.mjs.map +1 -0
  98. package/dist/_chunks/hooks-BAaaKPS_.js +7 -0
  99. package/dist/_chunks/hooks-BAaaKPS_.js.map +1 -0
  100. package/dist/_chunks/hooks-E5u1mcgM.mjs +8 -0
  101. package/dist/_chunks/hooks-E5u1mcgM.mjs.map +1 -0
  102. package/dist/_chunks/hu-CeYvaaO0.mjs +202 -0
  103. package/dist/_chunks/hu-CeYvaaO0.mjs.map +1 -0
  104. package/dist/_chunks/hu-sNV_yLYy.js +202 -0
  105. package/dist/_chunks/hu-sNV_yLYy.js.map +1 -0
  106. package/dist/_chunks/id-B5Ser98A.js +160 -0
  107. package/dist/_chunks/id-B5Ser98A.js.map +1 -0
  108. package/dist/_chunks/id-BtwA9WJT.mjs +160 -0
  109. package/dist/_chunks/id-BtwA9WJT.mjs.map +1 -0
  110. package/dist/_chunks/index-B4Gj2Oe9.js +3791 -0
  111. package/dist/_chunks/index-B4Gj2Oe9.js.map +1 -0
  112. package/dist/_chunks/index-BAGok3Xa.mjs +3772 -0
  113. package/dist/_chunks/index-BAGok3Xa.mjs.map +1 -0
  114. package/dist/_chunks/it-BrVPqaf1.mjs +162 -0
  115. package/dist/_chunks/it-BrVPqaf1.mjs.map +1 -0
  116. package/dist/_chunks/it-DkBIs7vD.js +162 -0
  117. package/dist/_chunks/it-DkBIs7vD.js.map +1 -0
  118. package/dist/_chunks/ja-CcFe8diO.js +196 -0
  119. package/dist/_chunks/ja-CcFe8diO.js.map +1 -0
  120. package/dist/_chunks/ja-CtsUxOvk.mjs +196 -0
  121. package/dist/_chunks/ja-CtsUxOvk.mjs.map +1 -0
  122. package/dist/_chunks/ko-HVQRlfUI.mjs +195 -0
  123. package/dist/_chunks/ko-HVQRlfUI.mjs.map +1 -0
  124. package/dist/_chunks/ko-woFZPmLk.js +195 -0
  125. package/dist/_chunks/ko-woFZPmLk.js.map +1 -0
  126. package/dist/_chunks/layout-BybbePH7.mjs +458 -0
  127. package/dist/_chunks/layout-BybbePH7.mjs.map +1 -0
  128. package/dist/_chunks/layout-aK6fNSLK.js +476 -0
  129. package/dist/_chunks/layout-aK6fNSLK.js.map +1 -0
  130. package/dist/_chunks/ml-BihZwQit.mjs +200 -0
  131. package/dist/_chunks/ml-BihZwQit.mjs.map +1 -0
  132. package/dist/_chunks/ml-C2W8N8k1.js +200 -0
  133. package/dist/_chunks/ml-C2W8N8k1.js.map +1 -0
  134. package/dist/_chunks/ms-BuFotyP_.js +144 -0
  135. package/dist/_chunks/ms-BuFotyP_.js.map +1 -0
  136. package/dist/_chunks/ms-m_WjyWx7.mjs +144 -0
  137. package/dist/_chunks/ms-m_WjyWx7.mjs.map +1 -0
  138. package/dist/_chunks/nl-D4R9gHx5.mjs +202 -0
  139. package/dist/_chunks/nl-D4R9gHx5.mjs.map +1 -0
  140. package/dist/_chunks/nl-bbEOHChV.js +202 -0
  141. package/dist/_chunks/nl-bbEOHChV.js.map +1 -0
  142. package/dist/_chunks/objects-gigeqt7s.js +49 -0
  143. package/dist/_chunks/objects-gigeqt7s.js.map +1 -0
  144. package/dist/_chunks/objects-mKMAmfec.mjs +47 -0
  145. package/dist/_chunks/objects-mKMAmfec.mjs.map +1 -0
  146. package/dist/_chunks/pl-sbx9mSt_.mjs +199 -0
  147. package/dist/_chunks/pl-sbx9mSt_.mjs.map +1 -0
  148. package/dist/_chunks/pl-uzwG-hk7.js +199 -0
  149. package/dist/_chunks/pl-uzwG-hk7.js.map +1 -0
  150. package/dist/_chunks/pt-BR-BiOz37D9.js +201 -0
  151. package/dist/_chunks/pt-BR-BiOz37D9.js.map +1 -0
  152. package/dist/_chunks/pt-BR-C71iDxnh.mjs +201 -0
  153. package/dist/_chunks/pt-BR-C71iDxnh.mjs.map +1 -0
  154. package/dist/_chunks/pt-BsaFvS8-.mjs +95 -0
  155. package/dist/_chunks/pt-BsaFvS8-.mjs.map +1 -0
  156. package/dist/_chunks/pt-CeXQuq50.js +95 -0
  157. package/dist/_chunks/pt-CeXQuq50.js.map +1 -0
  158. package/dist/_chunks/relations-BZicUuRc.mjs +135 -0
  159. package/dist/_chunks/relations-BZicUuRc.mjs.map +1 -0
  160. package/dist/_chunks/relations-yBDEAWeN.js +134 -0
  161. package/dist/_chunks/relations-yBDEAWeN.js.map +1 -0
  162. package/dist/_chunks/ru-BE6A4Exp.mjs +231 -0
  163. package/dist/_chunks/ru-BE6A4Exp.mjs.map +1 -0
  164. package/dist/_chunks/ru-BT3ybNny.js +231 -0
  165. package/dist/_chunks/ru-BT3ybNny.js.map +1 -0
  166. package/dist/_chunks/sa-CcvkYInH.js +200 -0
  167. package/dist/_chunks/sa-CcvkYInH.js.map +1 -0
  168. package/dist/_chunks/sa-Dag0k-Z8.mjs +200 -0
  169. package/dist/_chunks/sa-Dag0k-Z8.mjs.map +1 -0
  170. package/dist/_chunks/sk-BFg-R8qJ.mjs +202 -0
  171. package/dist/_chunks/sk-BFg-R8qJ.mjs.map +1 -0
  172. package/dist/_chunks/sk-CvY09Xjv.js +202 -0
  173. package/dist/_chunks/sk-CvY09Xjv.js.map +1 -0
  174. package/dist/_chunks/sv-CUnfWGsh.mjs +202 -0
  175. package/dist/_chunks/sv-CUnfWGsh.mjs.map +1 -0
  176. package/dist/_chunks/sv-MYDuzgvT.js +202 -0
  177. package/dist/_chunks/sv-MYDuzgvT.js.map +1 -0
  178. package/dist/_chunks/th-BqbI8lIT.mjs +148 -0
  179. package/dist/_chunks/th-BqbI8lIT.mjs.map +1 -0
  180. package/dist/_chunks/th-D9_GfAjc.js +148 -0
  181. package/dist/_chunks/th-D9_GfAjc.js.map +1 -0
  182. package/dist/_chunks/tr-CgeK3wJM.mjs +199 -0
  183. package/dist/_chunks/tr-CgeK3wJM.mjs.map +1 -0
  184. package/dist/_chunks/tr-D9UH-O_R.js +199 -0
  185. package/dist/_chunks/tr-D9UH-O_R.js.map +1 -0
  186. package/dist/_chunks/uk-C8EiqJY7.js +144 -0
  187. package/dist/_chunks/uk-C8EiqJY7.js.map +1 -0
  188. package/dist/_chunks/uk-CR-zDhAY.mjs +144 -0
  189. package/dist/_chunks/uk-CR-zDhAY.mjs.map +1 -0
  190. package/dist/_chunks/useDragAndDrop-DdHgKsqq.mjs +231 -0
  191. package/dist/_chunks/useDragAndDrop-DdHgKsqq.mjs.map +1 -0
  192. package/dist/_chunks/useDragAndDrop-J0TUUbR6.js +249 -0
  193. package/dist/_chunks/useDragAndDrop-J0TUUbR6.js.map +1 -0
  194. package/dist/_chunks/usePrev-B9w_-eYc.js +15 -0
  195. package/dist/_chunks/usePrev-B9w_-eYc.js.map +1 -0
  196. package/dist/_chunks/usePrev-DH6iah0A.mjs +16 -0
  197. package/dist/_chunks/usePrev-DH6iah0A.mjs.map +1 -0
  198. package/dist/_chunks/vi-CJlYDheJ.js +111 -0
  199. package/dist/_chunks/vi-CJlYDheJ.js.map +1 -0
  200. package/dist/_chunks/vi-DUXIk_fw.mjs +111 -0
  201. package/dist/_chunks/vi-DUXIk_fw.mjs.map +1 -0
  202. package/dist/_chunks/zh-BWZspA60.mjs +209 -0
  203. package/dist/_chunks/zh-BWZspA60.mjs.map +1 -0
  204. package/dist/_chunks/zh-CQQfszqR.js +209 -0
  205. package/dist/_chunks/zh-CQQfszqR.js.map +1 -0
  206. package/dist/_chunks/zh-Hans-9kOncHGw.js +952 -0
  207. package/dist/_chunks/zh-Hans-9kOncHGw.js.map +1 -0
  208. package/dist/_chunks/zh-Hans-BPQcRIyH.mjs +952 -0
  209. package/dist/_chunks/zh-Hans-BPQcRIyH.mjs.map +1 -0
  210. package/dist/admin/index.js +12 -0
  211. package/dist/admin/index.js.map +1 -0
  212. package/dist/admin/index.mjs +12 -0
  213. package/dist/admin/index.mjs.map +1 -0
  214. package/dist/admin/src/components/ComponentIcon.d.ts +11 -0
  215. package/dist/admin/src/components/ConfigurationForm/EditFieldForm.d.ts +9 -0
  216. package/dist/admin/src/components/ConfigurationForm/Fields.d.ts +21 -0
  217. package/dist/admin/src/components/ConfigurationForm/Form.d.ts +32 -0
  218. package/dist/admin/src/components/DragLayer.d.ts +13 -0
  219. package/dist/admin/src/components/DragPreviews/CardDragPreview.d.ts +7 -0
  220. package/dist/admin/src/components/DragPreviews/ComponentDragPreview.d.ts +6 -0
  221. package/dist/admin/src/components/DragPreviews/RelationDragPreview.d.ts +11 -0
  222. package/dist/admin/src/components/FieldTypeIcon.d.ts +9 -0
  223. package/dist/admin/src/components/InjectionZone.d.ts +45 -0
  224. package/dist/admin/src/components/LeftMenu.d.ts +2 -0
  225. package/dist/admin/src/components/RelativeTime.d.ts +28 -0
  226. package/dist/admin/src/constants/attributes.d.ts +14 -0
  227. package/dist/admin/src/constants/collections.d.ts +3 -0
  228. package/dist/admin/src/constants/dragAndDrop.d.ts +8 -0
  229. package/dist/admin/src/constants/hooks.d.ts +26 -0
  230. package/dist/admin/src/constants/plugin.d.ts +3 -0
  231. package/dist/admin/src/content-manager.d.ts +133 -0
  232. package/dist/admin/src/exports.d.ts +12 -0
  233. package/dist/admin/src/features/DocumentRBAC.d.ts +36 -0
  234. package/dist/admin/src/history/components/HistoryAction.d.ts +3 -0
  235. package/dist/admin/src/history/components/VersionContent.d.ts +17 -0
  236. package/dist/admin/src/history/components/VersionHeader.d.ts +5 -0
  237. package/dist/admin/src/history/components/VersionInputRenderer.d.ts +19 -0
  238. package/dist/admin/src/history/components/VersionsList.d.ts +2 -0
  239. package/dist/admin/src/history/pages/History.d.ts +27 -0
  240. package/dist/admin/src/history/routes.d.ts +6 -0
  241. package/dist/admin/src/history/services/historyVersion.d.ts +12 -0
  242. package/dist/admin/src/hooks/useContentManagerInitData.d.ts +15 -0
  243. package/dist/admin/src/hooks/useContentTypeSchema.d.ts +25 -0
  244. package/dist/admin/src/hooks/useDebounce.d.ts +1 -0
  245. package/dist/admin/src/hooks/useDocument.d.ts +87 -0
  246. package/dist/admin/src/hooks/useDocumentActions.d.ts +123 -0
  247. package/dist/admin/src/hooks/useDocumentLayout.d.ts +137 -0
  248. package/dist/admin/src/hooks/useDragAndDrop.d.ts +51 -0
  249. package/dist/admin/src/hooks/useKeyboardDragAndDrop.d.ts +14 -0
  250. package/dist/admin/src/hooks/useLazyComponents.d.ts +13 -0
  251. package/dist/admin/src/hooks/useOnce.d.ts +2 -0
  252. package/dist/admin/src/hooks/usePrev.d.ts +1 -0
  253. package/dist/admin/src/index.d.ts +16 -0
  254. package/dist/admin/src/layout.d.ts +2 -0
  255. package/dist/admin/src/modules/app.d.ts +20 -0
  256. package/dist/admin/src/modules/hooks.d.ts +10 -0
  257. package/dist/admin/src/modules/reducers.d.ts +6 -0
  258. package/dist/admin/src/pages/ComponentConfigurationPage.d.ts +3 -0
  259. package/dist/admin/src/pages/EditConfigurationPage.d.ts +3 -0
  260. package/dist/admin/src/pages/EditView/EditViewPage.d.ts +3 -0
  261. package/dist/admin/src/pages/EditView/components/DocumentActions.d.ts +75 -0
  262. package/dist/admin/src/pages/EditView/components/DocumentStatus.d.ts +16 -0
  263. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Code.d.ts +3 -0
  264. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Heading.d.ts +3 -0
  265. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Image.d.ts +3 -0
  266. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Link.d.ts +3 -0
  267. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/List.d.ts +3 -0
  268. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Paragraph.d.ts +3 -0
  269. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Quote.d.ts +3 -0
  270. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/BlocksContent.d.ts +6 -0
  271. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/BlocksEditor.d.ts +61 -0
  272. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/BlocksInput.d.ts +11 -0
  273. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/BlocksToolbar.d.ts +10 -0
  274. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/EditorLayout.d.ts +10 -0
  275. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Modifiers.d.ts +16 -0
  276. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/plugins/withImages.d.ts +11 -0
  277. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/plugins/withLinks.d.ts +9 -0
  278. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/plugins/withStrapiSchema.d.ts +8 -0
  279. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/constants.d.ts +4 -0
  280. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/conversions.d.ts +13 -0
  281. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/enterKey.d.ts +6 -0
  282. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/links.d.ts +10 -0
  283. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/types.d.ts +10 -0
  284. package/dist/admin/src/pages/EditView/components/FormInputs/Component/Initializer.d.ts +9 -0
  285. package/dist/admin/src/pages/EditView/components/FormInputs/Component/Input.d.ts +18 -0
  286. package/dist/admin/src/pages/EditView/components/FormInputs/Component/NonRepeatable.d.ts +5 -0
  287. package/dist/admin/src/pages/EditView/components/FormInputs/Component/Repeatable.d.ts +5 -0
  288. package/dist/admin/src/pages/EditView/components/FormInputs/ComponentContext.d.ts +42 -0
  289. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/AddComponentButton.d.ts +11 -0
  290. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/ComponentCard.d.ts +9 -0
  291. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/ComponentCategory.d.ts +15 -0
  292. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/ComponentPicker.d.ts +9 -0
  293. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/DynamicComponent.d.ts +14 -0
  294. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/DynamicZoneLabel.d.ts +12 -0
  295. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/Field.d.ts +14 -0
  296. package/dist/admin/src/pages/EditView/components/FormInputs/NotAllowed.d.ts +7 -0
  297. package/dist/admin/src/pages/EditView/components/FormInputs/Relations.d.ts +18 -0
  298. package/dist/admin/src/pages/EditView/components/FormInputs/UID.d.ts +9 -0
  299. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/Editor.d.ts +17 -0
  300. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/EditorLayout.d.ts +14 -0
  301. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/Field.d.ts +11 -0
  302. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/PreviewWysiwyg.d.ts +5 -0
  303. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/WysiwygFooter.d.ts +7 -0
  304. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/WysiwygNav.d.ts +17 -0
  305. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/WysiwygStyles.d.ts +62 -0
  306. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/utils/continueList.d.ts +5 -0
  307. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/utils/mdRenderer.d.ts +4 -0
  308. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/utils/utils.d.ts +16 -0
  309. package/dist/admin/src/pages/EditView/components/FormLayout.d.ts +5 -0
  310. package/dist/admin/src/pages/EditView/components/Header.d.ts +35 -0
  311. package/dist/admin/src/pages/EditView/components/InputRenderer.d.ts +9 -0
  312. package/dist/admin/src/pages/EditView/components/Panels.d.ts +10 -0
  313. package/dist/admin/src/pages/EditView/utils/data.d.ts +33 -0
  314. package/dist/admin/src/pages/EditView/utils/forms.d.ts +9 -0
  315. package/dist/admin/src/pages/ListConfiguration/ListConfigurationPage.d.ts +10 -0
  316. package/dist/admin/src/pages/ListConfiguration/components/DraggableCard.d.ts +12 -0
  317. package/dist/admin/src/pages/ListConfiguration/components/EditFieldForm.d.ts +8 -0
  318. package/dist/admin/src/pages/ListConfiguration/components/Header.d.ts +8 -0
  319. package/dist/admin/src/pages/ListConfiguration/components/Settings.d.ts +19 -0
  320. package/dist/admin/src/pages/ListConfiguration/components/SortDisplayedFields.d.ts +6 -0
  321. package/dist/admin/src/pages/ListView/ListViewPage.d.ts +3 -0
  322. package/dist/admin/src/pages/ListView/components/AutoCloneFailureModal.d.ts +7 -0
  323. package/dist/admin/src/pages/ListView/components/BulkActions/Actions.d.ts +24 -0
  324. package/dist/admin/src/pages/ListView/components/BulkActions/ConfirmBulkActionDialog.d.ts +15 -0
  325. package/dist/admin/src/pages/ListView/components/BulkActions/PublishAction.d.ts +14 -0
  326. package/dist/admin/src/pages/ListView/components/Filters.d.ts +8 -0
  327. package/dist/admin/src/pages/ListView/components/TableActions.d.ts +8 -0
  328. package/dist/admin/src/pages/ListView/components/TableCells/CellContent.d.ts +9 -0
  329. package/dist/admin/src/pages/ListView/components/TableCells/CellValue.d.ts +8 -0
  330. package/dist/admin/src/pages/ListView/components/TableCells/Components.d.ts +12 -0
  331. package/dist/admin/src/pages/ListView/components/TableCells/Media.d.ts +23 -0
  332. package/dist/admin/src/pages/ListView/components/TableCells/Relations.d.ts +12 -0
  333. package/dist/admin/src/pages/ListView/components/ViewSettingsMenu.d.ts +10 -0
  334. package/dist/admin/src/pages/NoContentTypePage.d.ts +2 -0
  335. package/dist/admin/src/pages/NoPermissionsPage.d.ts +2 -0
  336. package/dist/admin/src/router.d.ts +5 -0
  337. package/dist/admin/src/services/api.d.ts +2 -0
  338. package/dist/admin/src/services/components.d.ts +5 -0
  339. package/dist/admin/src/services/contentTypes.d.ts +17 -0
  340. package/dist/admin/src/services/documents.d.ts +101 -0
  341. package/dist/admin/src/services/init.d.ts +9 -0
  342. package/dist/admin/src/services/relations.d.ts +49 -0
  343. package/dist/admin/src/services/uid.d.ts +32 -0
  344. package/dist/admin/src/utils/api.d.ts +24 -0
  345. package/dist/admin/src/utils/attributes.d.ts +19 -0
  346. package/dist/admin/src/utils/objects.d.ts +33 -0
  347. package/dist/admin/src/utils/relations.d.ts +12 -0
  348. package/dist/admin/src/utils/strings.d.ts +2 -0
  349. package/dist/admin/src/utils/translations.d.ts +4 -0
  350. package/dist/admin/src/utils/urls.d.ts +2 -0
  351. package/dist/admin/src/utils/users.d.ts +6 -0
  352. package/dist/admin/src/utils/validation.d.ts +7 -0
  353. package/dist/server/index.js +4365 -0
  354. package/dist/server/index.js.map +1 -0
  355. package/dist/server/index.mjs +4341 -0
  356. package/dist/server/index.mjs.map +1 -0
  357. package/dist/server/src/bootstrap.d.ts +3 -0
  358. package/dist/server/src/bootstrap.d.ts.map +1 -0
  359. package/dist/server/src/config.d.ts +6 -0
  360. package/dist/server/src/config.d.ts.map +1 -0
  361. package/dist/server/src/constants/index.d.ts +6 -0
  362. package/dist/server/src/constants/index.d.ts.map +1 -0
  363. package/dist/server/src/controllers/collection-types.d.ts +23 -0
  364. package/dist/server/src/controllers/collection-types.d.ts.map +1 -0
  365. package/dist/server/src/controllers/components.d.ts +7 -0
  366. package/dist/server/src/controllers/components.d.ts.map +1 -0
  367. package/dist/server/src/controllers/content-types.d.ts +8 -0
  368. package/dist/server/src/controllers/content-types.d.ts.map +1 -0
  369. package/dist/server/src/controllers/index.d.ts +53 -0
  370. package/dist/server/src/controllers/index.d.ts.map +1 -0
  371. package/dist/server/src/controllers/init.d.ts +5 -0
  372. package/dist/server/src/controllers/init.d.ts.map +1 -0
  373. package/dist/server/src/controllers/relations.d.ts +13 -0
  374. package/dist/server/src/controllers/relations.d.ts.map +1 -0
  375. package/dist/server/src/controllers/single-types.d.ts +11 -0
  376. package/dist/server/src/controllers/single-types.d.ts.map +1 -0
  377. package/dist/server/src/controllers/uid.d.ts +6 -0
  378. package/dist/server/src/controllers/uid.d.ts.map +1 -0
  379. package/dist/server/src/controllers/utils/clone.d.ts +12 -0
  380. package/dist/server/src/controllers/utils/clone.d.ts.map +1 -0
  381. package/dist/server/src/controllers/utils/metadata.d.ts +8 -0
  382. package/dist/server/src/controllers/utils/metadata.d.ts.map +1 -0
  383. package/dist/server/src/controllers/validation/dimensions.d.ts +9 -0
  384. package/dist/server/src/controllers/validation/dimensions.d.ts.map +1 -0
  385. package/dist/server/src/controllers/validation/index.d.ts +20 -0
  386. package/dist/server/src/controllers/validation/index.d.ts.map +1 -0
  387. package/dist/server/src/controllers/validation/model-configuration.d.ts +22 -0
  388. package/dist/server/src/controllers/validation/model-configuration.d.ts.map +1 -0
  389. package/dist/server/src/controllers/validation/relations.d.ts +4 -0
  390. package/dist/server/src/controllers/validation/relations.d.ts.map +1 -0
  391. package/dist/server/src/destroy.d.ts +4 -0
  392. package/dist/server/src/destroy.d.ts.map +1 -0
  393. package/dist/server/src/history/constants.d.ts +3 -0
  394. package/dist/server/src/history/constants.d.ts.map +1 -0
  395. package/dist/server/src/history/controllers/history-version.d.ts +19 -0
  396. package/dist/server/src/history/controllers/history-version.d.ts.map +1 -0
  397. package/dist/server/src/history/controllers/index.d.ts +2 -0
  398. package/dist/server/src/history/controllers/index.d.ts.map +1 -0
  399. package/dist/server/src/history/controllers/validation/history-version.d.ts +2 -0
  400. package/dist/server/src/history/controllers/validation/history-version.d.ts.map +1 -0
  401. package/dist/server/src/history/index.d.ts +4 -0
  402. package/dist/server/src/history/index.d.ts.map +1 -0
  403. package/dist/server/src/history/models/history-version.d.ts +4 -0
  404. package/dist/server/src/history/models/history-version.d.ts.map +1 -0
  405. package/dist/server/src/history/routes/history-version.d.ts +4 -0
  406. package/dist/server/src/history/routes/history-version.d.ts.map +1 -0
  407. package/dist/server/src/history/routes/index.d.ts +8 -0
  408. package/dist/server/src/history/routes/index.d.ts.map +1 -0
  409. package/dist/server/src/history/services/history.d.ts +16 -0
  410. package/dist/server/src/history/services/history.d.ts.map +1 -0
  411. package/dist/server/src/history/services/index.d.ts +19 -0
  412. package/dist/server/src/history/services/index.d.ts.map +1 -0
  413. package/dist/server/src/history/services/lifecycles.d.ts +9 -0
  414. package/dist/server/src/history/services/lifecycles.d.ts.map +1 -0
  415. package/dist/server/src/history/services/utils.d.ts +44 -0
  416. package/dist/server/src/history/services/utils.d.ts.map +1 -0
  417. package/dist/server/src/history/utils.d.ts +22 -0
  418. package/dist/server/src/history/utils.d.ts.map +1 -0
  419. package/dist/server/src/index.d.ts +353 -0
  420. package/dist/server/src/index.d.ts.map +1 -0
  421. package/dist/server/src/middlewares/index.d.ts +3 -0
  422. package/dist/server/src/middlewares/index.d.ts.map +1 -0
  423. package/dist/server/src/middlewares/routing.d.ts +4 -0
  424. package/dist/server/src/middlewares/routing.d.ts.map +1 -0
  425. package/dist/server/src/policies/hasPermissions.d.ts +7 -0
  426. package/dist/server/src/policies/hasPermissions.d.ts.map +1 -0
  427. package/dist/server/src/policies/index.d.ts +9 -0
  428. package/dist/server/src/policies/index.d.ts.map +1 -0
  429. package/dist/server/src/register.d.ts +4 -0
  430. package/dist/server/src/register.d.ts.map +1 -0
  431. package/dist/server/src/routes/admin.d.ts +41 -0
  432. package/dist/server/src/routes/admin.d.ts.map +1 -0
  433. package/dist/server/src/routes/index.d.ts +43 -0
  434. package/dist/server/src/routes/index.d.ts.map +1 -0
  435. package/dist/server/src/services/components.d.ts +32 -0
  436. package/dist/server/src/services/components.d.ts.map +1 -0
  437. package/dist/server/src/services/configuration.d.ts +20 -0
  438. package/dist/server/src/services/configuration.d.ts.map +1 -0
  439. package/dist/server/src/services/content-types.d.ts +18 -0
  440. package/dist/server/src/services/content-types.d.ts.map +1 -0
  441. package/dist/server/src/services/data-mapper.d.ts +20 -0
  442. package/dist/server/src/services/data-mapper.d.ts.map +1 -0
  443. package/dist/server/src/services/document-manager.d.ts +48 -0
  444. package/dist/server/src/services/document-manager.d.ts.map +1 -0
  445. package/dist/server/src/services/document-metadata.d.ts +67 -0
  446. package/dist/server/src/services/document-metadata.d.ts.map +1 -0
  447. package/dist/server/src/services/field-sizes.d.ts +19 -0
  448. package/dist/server/src/services/field-sizes.d.ts.map +1 -0
  449. package/dist/server/src/services/index.d.ts +245 -0
  450. package/dist/server/src/services/index.d.ts.map +1 -0
  451. package/dist/server/src/services/metrics.d.ts +9 -0
  452. package/dist/server/src/services/metrics.d.ts.map +1 -0
  453. package/dist/server/src/services/permission-checker.d.ts +54 -0
  454. package/dist/server/src/services/permission-checker.d.ts.map +1 -0
  455. package/dist/server/src/services/permission.d.ts +12 -0
  456. package/dist/server/src/services/permission.d.ts.map +1 -0
  457. package/dist/server/src/services/populate-builder.d.ts +30 -0
  458. package/dist/server/src/services/populate-builder.d.ts.map +1 -0
  459. package/dist/server/src/services/uid.d.ts +25 -0
  460. package/dist/server/src/services/uid.d.ts.map +1 -0
  461. package/dist/server/src/services/utils/configuration/attributes.d.ts +17 -0
  462. package/dist/server/src/services/utils/configuration/attributes.d.ts.map +1 -0
  463. package/dist/server/src/services/utils/configuration/index.d.ts +21 -0
  464. package/dist/server/src/services/utils/configuration/index.d.ts.map +1 -0
  465. package/dist/server/src/services/utils/configuration/layouts.d.ts +14 -0
  466. package/dist/server/src/services/utils/configuration/layouts.d.ts.map +1 -0
  467. package/dist/server/src/services/utils/configuration/metadatas.d.ts +5 -0
  468. package/dist/server/src/services/utils/configuration/metadatas.d.ts.map +1 -0
  469. package/dist/server/src/services/utils/configuration/settings.d.ts +5 -0
  470. package/dist/server/src/services/utils/configuration/settings.d.ts.map +1 -0
  471. package/dist/server/src/services/utils/count.d.ts +5 -0
  472. package/dist/server/src/services/utils/count.d.ts.map +1 -0
  473. package/dist/server/src/services/utils/draft.d.ts +11 -0
  474. package/dist/server/src/services/utils/draft.d.ts.map +1 -0
  475. package/dist/server/src/services/utils/populate.d.ts +42 -0
  476. package/dist/server/src/services/utils/populate.d.ts.map +1 -0
  477. package/dist/server/src/services/utils/store.d.ts +16 -0
  478. package/dist/server/src/services/utils/store.d.ts.map +1 -0
  479. package/dist/server/src/utils/index.d.ts +9 -0
  480. package/dist/server/src/utils/index.d.ts.map +1 -0
  481. package/dist/server/src/validation/policies/hasPermissions.d.ts +2 -0
  482. package/dist/server/src/validation/policies/hasPermissions.d.ts.map +1 -0
  483. package/dist/shared/contracts/collection-types.d.ts +336 -0
  484. package/dist/shared/contracts/collection-types.d.ts.map +1 -0
  485. package/dist/shared/contracts/components.d.ts +65 -0
  486. package/dist/shared/contracts/components.d.ts.map +1 -0
  487. package/dist/shared/contracts/content-types.d.ts +113 -0
  488. package/dist/shared/contracts/content-types.d.ts.map +1 -0
  489. package/dist/shared/contracts/history-versions.d.ts +92 -0
  490. package/dist/shared/contracts/history-versions.d.ts.map +1 -0
  491. package/dist/shared/contracts/index.d.ts +10 -0
  492. package/dist/shared/contracts/index.d.ts.map +1 -0
  493. package/dist/shared/contracts/init.d.ts +24 -0
  494. package/dist/shared/contracts/init.d.ts.map +1 -0
  495. package/dist/shared/contracts/relations.d.ts +70 -0
  496. package/dist/shared/contracts/relations.d.ts.map +1 -0
  497. package/dist/shared/contracts/review-workflows.d.ts +78 -0
  498. package/dist/shared/contracts/review-workflows.d.ts.map +1 -0
  499. package/dist/shared/contracts/single-types.d.ts +113 -0
  500. package/dist/shared/contracts/single-types.d.ts.map +1 -0
  501. package/dist/shared/contracts/uid.d.ts +48 -0
  502. package/dist/shared/contracts/uid.d.ts.map +1 -0
  503. package/dist/shared/index.d.ts +2 -0
  504. package/dist/shared/index.d.ts.map +1 -0
  505. package/dist/shared/index.js +43 -0
  506. package/dist/shared/index.js.map +1 -0
  507. package/dist/shared/index.mjs +43 -0
  508. package/dist/shared/index.mjs.map +1 -0
  509. package/package.json +113 -2
  510. package/strapi-server.js +3 -0
@@ -0,0 +1,4341 @@
1
+ import strapiUtils, { validateYupSchema, errors, async, contentTypes as contentTypes$1, yup as yup$1, validateYupSchemaSync, policy, traverse, setCreatorFields, isOperatorOfType, relations as relations$1, traverseEntity, pagination } from "@strapi/utils";
2
+ import { pick, omit, difference, intersection, pipe, propOr, isEqual, isEmpty, set, has, prop, assoc, mapValues, flow, uniq, uniqBy, concat, isNil as isNil$1, getOr, propEq, merge, groupBy, castArray } from "lodash/fp";
3
+ import "@strapi/types";
4
+ import * as yup from "yup";
5
+ import { scheduleJob } from "node-schedule";
6
+ import isNil from "lodash/isNil";
7
+ import _, { intersection as intersection$1, difference as difference$1 } from "lodash";
8
+ import qs from "qs";
9
+ import slugify from "@sindresorhus/slugify";
10
+ const getService$1 = (name) => {
11
+ return strapi.plugin("content-manager").service(name);
12
+ };
13
+ function getService(strapi2, name) {
14
+ return strapi2.service(`plugin::content-manager.${name}`);
15
+ }
16
+ const historyRestoreVersionSchema = yup.object().shape({
17
+ contentType: yup.string().trim().required()
18
+ }).required();
19
+ const validateRestoreVersion = validateYupSchema(historyRestoreVersionSchema);
20
+ const getValidPagination = ({ page, pageSize }) => {
21
+ let pageNumber = 1;
22
+ let pageSizeNumber = 20;
23
+ if (page) {
24
+ const parsedPage = parseInt(page, 10);
25
+ pageNumber = parseInt(page, 10);
26
+ if (!Number.isNaN(parsedPage) && parsedPage >= 1) {
27
+ pageNumber = parsedPage;
28
+ }
29
+ }
30
+ if (pageSize) {
31
+ const parsedPageSize = parseInt(pageSize, 10);
32
+ if (!Number.isNaN(parsedPageSize) && parsedPageSize >= 1 && parsedPageSize <= 100) {
33
+ pageSizeNumber = parsedPageSize;
34
+ }
35
+ }
36
+ return { page: pageNumber, pageSize: pageSizeNumber };
37
+ };
38
+ const createHistoryVersionController = ({ strapi: strapi2 }) => {
39
+ return {
40
+ async findMany(ctx) {
41
+ const contentTypeUid = ctx.query.contentType;
42
+ const isSingleType = strapi2.getModel(contentTypeUid)?.kind === "singleType";
43
+ if (isSingleType && !contentTypeUid) {
44
+ throw new errors.ForbiddenError("contentType is required");
45
+ }
46
+ if (!isSingleType && (!contentTypeUid || !ctx.query.documentId)) {
47
+ throw new errors.ForbiddenError("contentType and documentId are required");
48
+ }
49
+ const permissionChecker2 = getService$1("permission-checker").create({
50
+ userAbility: ctx.state.userAbility,
51
+ model: ctx.query.contentType
52
+ });
53
+ if (permissionChecker2.cannot.read()) {
54
+ return ctx.forbidden();
55
+ }
56
+ const query = await permissionChecker2.sanitizeQuery(ctx.query);
57
+ const { results, pagination: pagination2 } = await getService(strapi2, "history").findVersionsPage({
58
+ query: {
59
+ ...query,
60
+ ...getValidPagination({ page: query.page, pageSize: query.pageSize })
61
+ },
62
+ state: { userAbility: ctx.state.userAbility }
63
+ });
64
+ const sanitizedResults = await async.map(
65
+ results,
66
+ async (version) => {
67
+ return {
68
+ ...version,
69
+ data: await permissionChecker2.sanitizeOutput(version.data),
70
+ createdBy: version.createdBy ? pick(["id", "firstname", "lastname", "username", "email"], version.createdBy) : void 0
71
+ };
72
+ }
73
+ );
74
+ return {
75
+ data: sanitizedResults,
76
+ meta: { pagination: pagination2 }
77
+ };
78
+ },
79
+ async restoreVersion(ctx) {
80
+ const request = ctx.request;
81
+ await validateRestoreVersion(request.body, "contentType is required");
82
+ const permissionChecker2 = getService$1("permission-checker").create({
83
+ userAbility: ctx.state.userAbility,
84
+ model: request.body.contentType
85
+ });
86
+ if (permissionChecker2.cannot.update()) {
87
+ throw new errors.ForbiddenError();
88
+ }
89
+ const restoredDocument = await getService(strapi2, "history").restoreVersion(
90
+ request.params.versionId
91
+ );
92
+ return {
93
+ data: { documentId: restoredDocument.documentId }
94
+ };
95
+ }
96
+ };
97
+ };
98
+ const controllers$1 = {
99
+ "history-version": createHistoryVersionController
100
+ /**
101
+ * Casting is needed because the types aren't aware that Strapi supports
102
+ * passing a controller factory as the value, instead of a controller object directly
103
+ */
104
+ };
105
+ const HISTORY_VERSION_UID = "plugin::content-manager.history-version";
106
+ const FIELDS_TO_IGNORE = [
107
+ "createdAt",
108
+ "updatedAt",
109
+ "publishedAt",
110
+ "createdBy",
111
+ "updatedBy",
112
+ "strapi_stage",
113
+ "strapi_assignee"
114
+ ];
115
+ const DEFAULT_RETENTION_DAYS = 90;
116
+ const createServiceUtils = ({ strapi: strapi2 }) => {
117
+ const getSchemaAttributesDiff = (versionSchemaAttributes, contentTypeSchemaAttributes) => {
118
+ const sanitizedContentTypeSchemaAttributes = omit(
119
+ FIELDS_TO_IGNORE,
120
+ contentTypeSchemaAttributes
121
+ );
122
+ const reduceDifferenceToAttributesObject = (diffKeys, source) => {
123
+ return diffKeys.reduce(
124
+ (previousAttributesObject, diffKey) => {
125
+ previousAttributesObject[diffKey] = source[diffKey];
126
+ return previousAttributesObject;
127
+ },
128
+ {}
129
+ );
130
+ };
131
+ const versionSchemaKeys = Object.keys(versionSchemaAttributes);
132
+ const contentTypeSchemaAttributesKeys = Object.keys(sanitizedContentTypeSchemaAttributes);
133
+ const uniqueToContentType = difference(contentTypeSchemaAttributesKeys, versionSchemaKeys);
134
+ const added = reduceDifferenceToAttributesObject(
135
+ uniqueToContentType,
136
+ sanitizedContentTypeSchemaAttributes
137
+ );
138
+ const uniqueToVersion = difference(versionSchemaKeys, contentTypeSchemaAttributesKeys);
139
+ const removed = reduceDifferenceToAttributesObject(uniqueToVersion, versionSchemaAttributes);
140
+ return { added, removed };
141
+ };
142
+ const getRelationRestoreValue = async (versionRelationData, attribute) => {
143
+ if (Array.isArray(versionRelationData)) {
144
+ if (versionRelationData.length === 0)
145
+ return versionRelationData;
146
+ const existingAndMissingRelations = await Promise.all(
147
+ versionRelationData.map((relation) => {
148
+ return strapi2.documents(attribute.target).findOne({
149
+ documentId: relation.documentId,
150
+ locale: relation.locale || void 0
151
+ });
152
+ })
153
+ );
154
+ return existingAndMissingRelations.filter(
155
+ (relation) => relation !== null
156
+ );
157
+ }
158
+ return strapi2.documents(attribute.target).findOne({
159
+ documentId: versionRelationData.documentId,
160
+ locale: versionRelationData.locale || void 0
161
+ });
162
+ };
163
+ const getMediaRestoreValue = async (versionRelationData, attribute) => {
164
+ if (attribute.multiple) {
165
+ const existingAndMissingMedias = await Promise.all(
166
+ // @ts-expect-error Fix the type definitions so this isn't any
167
+ versionRelationData.map((media) => {
168
+ return strapi2.db.query("plugin::upload.file").findOne({ where: { id: media.id } });
169
+ })
170
+ );
171
+ return existingAndMissingMedias.filter((media) => media != null);
172
+ }
173
+ return strapi2.db.query("plugin::upload.file").findOne({ where: { id: versionRelationData.id } });
174
+ };
175
+ const localesService = strapi2.plugin("i18n")?.service("locales");
176
+ const getDefaultLocale = async () => localesService ? localesService.getDefaultLocale() : null;
177
+ const getLocaleDictionary = async () => {
178
+ if (!localesService)
179
+ return {};
180
+ const locales = await localesService.find() || [];
181
+ return locales.reduce(
182
+ (acc, locale) => {
183
+ acc[locale.code] = { name: locale.name, code: locale.code };
184
+ return acc;
185
+ },
186
+ {}
187
+ );
188
+ };
189
+ const getRetentionDays = () => {
190
+ const featureConfig = strapi2.ee.features.get("cms-content-history");
191
+ const licenseRetentionDays = typeof featureConfig === "object" && featureConfig?.options.retentionDays;
192
+ const userRetentionDays = strapi2.config.get("admin.history.retentionDays");
193
+ if (userRetentionDays && userRetentionDays < licenseRetentionDays) {
194
+ return userRetentionDays;
195
+ }
196
+ return Math.min(licenseRetentionDays, DEFAULT_RETENTION_DAYS);
197
+ };
198
+ const getVersionStatus = async (contentTypeUid, document) => {
199
+ const documentMetadataService = strapi2.plugin("content-manager").service("document-metadata");
200
+ const meta = await documentMetadataService.getMetadata(contentTypeUid, document);
201
+ return documentMetadataService.getStatus(document, meta.availableStatus);
202
+ };
203
+ const getDeepPopulate2 = (uid2) => {
204
+ const model = strapi2.getModel(uid2);
205
+ const attributes = Object.entries(model.attributes);
206
+ return attributes.reduce((acc, [attributeName, attribute]) => {
207
+ switch (attribute.type) {
208
+ case "relation": {
209
+ const isVisible2 = contentTypes$1.isVisibleAttribute(model, attributeName);
210
+ if (isVisible2) {
211
+ acc[attributeName] = { fields: ["documentId", "locale", "publishedAt"] };
212
+ }
213
+ break;
214
+ }
215
+ case "media": {
216
+ acc[attributeName] = { fields: ["id"] };
217
+ break;
218
+ }
219
+ case "component": {
220
+ const populate = getDeepPopulate2(attribute.component);
221
+ acc[attributeName] = { populate };
222
+ break;
223
+ }
224
+ case "dynamiczone": {
225
+ const populatedComponents = (attribute.components || []).reduce(
226
+ (acc2, componentUID) => {
227
+ acc2[componentUID] = { populate: getDeepPopulate2(componentUID) };
228
+ return acc2;
229
+ },
230
+ {}
231
+ );
232
+ acc[attributeName] = { on: populatedComponents };
233
+ break;
234
+ }
235
+ }
236
+ return acc;
237
+ }, {});
238
+ };
239
+ const buildMediaResponse = async (values) => {
240
+ return values.slice(0, 25).reduce(
241
+ async (currentRelationDataPromise, entry) => {
242
+ const currentRelationData = await currentRelationDataPromise;
243
+ if (!entry) {
244
+ return currentRelationData;
245
+ }
246
+ const relatedEntry = await strapi2.db.query("plugin::upload.file").findOne({ where: { id: entry.id } });
247
+ if (relatedEntry) {
248
+ currentRelationData.results.push(relatedEntry);
249
+ } else {
250
+ currentRelationData.meta.missingCount += 1;
251
+ }
252
+ return currentRelationData;
253
+ },
254
+ Promise.resolve({
255
+ results: [],
256
+ meta: { missingCount: 0 }
257
+ })
258
+ );
259
+ };
260
+ const buildRelationReponse = async (values, attributeSchema) => {
261
+ return values.slice(0, 25).reduce(
262
+ async (currentRelationDataPromise, entry) => {
263
+ const currentRelationData = await currentRelationDataPromise;
264
+ if (!entry) {
265
+ return currentRelationData;
266
+ }
267
+ const relatedEntry = await strapi2.documents(attributeSchema.target).findOne({ documentId: entry.documentId, locale: entry.locale || void 0 });
268
+ if (relatedEntry) {
269
+ currentRelationData.results.push({
270
+ ...relatedEntry,
271
+ status: await getVersionStatus(attributeSchema.target, relatedEntry)
272
+ });
273
+ } else {
274
+ currentRelationData.meta.missingCount += 1;
275
+ }
276
+ return currentRelationData;
277
+ },
278
+ Promise.resolve({
279
+ results: [],
280
+ meta: { missingCount: 0 }
281
+ })
282
+ );
283
+ };
284
+ return {
285
+ getSchemaAttributesDiff,
286
+ getRelationRestoreValue,
287
+ getMediaRestoreValue,
288
+ getDefaultLocale,
289
+ getLocaleDictionary,
290
+ getRetentionDays,
291
+ getVersionStatus,
292
+ getDeepPopulate: getDeepPopulate2,
293
+ buildMediaResponse,
294
+ buildRelationReponse
295
+ };
296
+ };
297
+ const createHistoryService = ({ strapi: strapi2 }) => {
298
+ const query = strapi2.db.query(HISTORY_VERSION_UID);
299
+ const serviceUtils = createServiceUtils({ strapi: strapi2 });
300
+ return {
301
+ async createVersion(historyVersionData) {
302
+ await query.create({
303
+ data: {
304
+ ...historyVersionData,
305
+ createdAt: /* @__PURE__ */ new Date(),
306
+ createdBy: strapi2.requestContext.get()?.state?.user.id
307
+ }
308
+ });
309
+ },
310
+ async findVersionsPage(params) {
311
+ const locale = params.query.locale || await serviceUtils.getDefaultLocale();
312
+ const [{ results, pagination: pagination2 }, localeDictionary] = await Promise.all([
313
+ query.findPage({
314
+ ...params.query,
315
+ where: {
316
+ $and: [
317
+ { contentType: params.query.contentType },
318
+ ...params.query.documentId ? [{ relatedDocumentId: params.query.documentId }] : [],
319
+ ...locale ? [{ locale }] : []
320
+ ]
321
+ },
322
+ populate: ["createdBy"],
323
+ orderBy: [{ createdAt: "desc" }]
324
+ }),
325
+ serviceUtils.getLocaleDictionary()
326
+ ]);
327
+ const populateEntryRelations = async (entry) => {
328
+ const entryWithRelations = await Object.entries(entry.schema).reduce(
329
+ async (currentDataWithRelations, [attributeKey, attributeSchema]) => {
330
+ const attributeValue = entry.data[attributeKey];
331
+ const attributeValues = Array.isArray(attributeValue) ? attributeValue : [attributeValue];
332
+ if (attributeSchema.type === "media") {
333
+ const permissionChecker2 = getService$1("permission-checker").create({
334
+ userAbility: params.state.userAbility,
335
+ model: "plugin::upload.file"
336
+ });
337
+ const response = await serviceUtils.buildMediaResponse(attributeValues);
338
+ const sanitizedResults = await Promise.all(
339
+ response.results.map((media) => permissionChecker2.sanitizeOutput(media))
340
+ );
341
+ return {
342
+ ...await currentDataWithRelations,
343
+ [attributeKey]: {
344
+ results: sanitizedResults,
345
+ meta: response.meta
346
+ }
347
+ };
348
+ }
349
+ if (attributeSchema.type === "relation" && attributeSchema.relation !== "morphToOne" && attributeSchema.relation !== "morphToMany") {
350
+ if (attributeSchema.target === "admin::user") {
351
+ const adminUsers = await Promise.all(
352
+ attributeValues.map((userToPopulate) => {
353
+ if (userToPopulate == null) {
354
+ return null;
355
+ }
356
+ return strapi2.query("admin::user").findOne({ where: { id: userToPopulate.id } });
357
+ })
358
+ );
359
+ return {
360
+ ...await currentDataWithRelations,
361
+ /**
362
+ * Ideally we would return the same "{results: [], meta: {}}" shape, however,
363
+ * when sanitizing the data as a whole in the controller before sending to the client,
364
+ * the data for admin relation user is completely sanitized if we return an object here as opposed to an array.
365
+ */
366
+ [attributeKey]: adminUsers
367
+ };
368
+ }
369
+ const permissionChecker2 = getService$1("permission-checker").create({
370
+ userAbility: params.state.userAbility,
371
+ model: attributeSchema.target
372
+ });
373
+ const response = await serviceUtils.buildRelationReponse(
374
+ attributeValues,
375
+ attributeSchema
376
+ );
377
+ const sanitizedResults = await Promise.all(
378
+ response.results.map((media) => permissionChecker2.sanitizeOutput(media))
379
+ );
380
+ return {
381
+ ...await currentDataWithRelations,
382
+ [attributeKey]: {
383
+ results: sanitizedResults,
384
+ meta: response.meta
385
+ }
386
+ };
387
+ }
388
+ return currentDataWithRelations;
389
+ },
390
+ Promise.resolve(entry.data)
391
+ );
392
+ return entryWithRelations;
393
+ };
394
+ const formattedResults = await Promise.all(
395
+ results.map(async (result) => {
396
+ return {
397
+ ...result,
398
+ data: await populateEntryRelations(result),
399
+ meta: {
400
+ unknownAttributes: serviceUtils.getSchemaAttributesDiff(
401
+ result.schema,
402
+ strapi2.getModel(params.query.contentType).attributes
403
+ )
404
+ },
405
+ locale: result.locale ? localeDictionary[result.locale] : null
406
+ };
407
+ })
408
+ );
409
+ return {
410
+ results: formattedResults,
411
+ pagination: pagination2
412
+ };
413
+ },
414
+ async restoreVersion(versionId) {
415
+ const version = await query.findOne({ where: { id: versionId } });
416
+ const contentTypeSchemaAttributes = strapi2.getModel(version.contentType).attributes;
417
+ const schemaDiff = serviceUtils.getSchemaAttributesDiff(
418
+ version.schema,
419
+ contentTypeSchemaAttributes
420
+ );
421
+ const dataWithoutAddedAttributes = Object.keys(schemaDiff.added).reduce(
422
+ (currentData, addedKey) => {
423
+ currentData[addedKey] = null;
424
+ return currentData;
425
+ },
426
+ // Clone to avoid mutating the original version data
427
+ structuredClone(version.data)
428
+ );
429
+ const sanitizedSchemaAttributes = omit(
430
+ FIELDS_TO_IGNORE,
431
+ contentTypeSchemaAttributes
432
+ );
433
+ const reducer = async.reduce(Object.entries(sanitizedSchemaAttributes));
434
+ const dataWithoutMissingRelations = await reducer(
435
+ async (previousRelationAttributes, [name, attribute]) => {
436
+ const versionRelationData = version.data[name];
437
+ if (!versionRelationData) {
438
+ return previousRelationAttributes;
439
+ }
440
+ if (attribute.type === "relation" && // TODO: handle polymorphic relations
441
+ attribute.relation !== "morphToOne" && attribute.relation !== "morphToMany") {
442
+ const data2 = await serviceUtils.getRelationRestoreValue(versionRelationData, attribute);
443
+ previousRelationAttributes[name] = data2;
444
+ }
445
+ if (attribute.type === "media") {
446
+ const data2 = await serviceUtils.getMediaRestoreValue(versionRelationData, attribute);
447
+ previousRelationAttributes[name] = data2;
448
+ }
449
+ return previousRelationAttributes;
450
+ },
451
+ // Clone to avoid mutating the original version data
452
+ structuredClone(dataWithoutAddedAttributes)
453
+ );
454
+ const data = omit(["id", ...Object.keys(schemaDiff.removed)], dataWithoutMissingRelations);
455
+ const restoredDocument = await strapi2.documents(version.contentType).update({
456
+ documentId: version.relatedDocumentId,
457
+ locale: version.locale,
458
+ data
459
+ });
460
+ if (!restoredDocument) {
461
+ throw new errors.ApplicationError("Failed to restore version");
462
+ }
463
+ return restoredDocument;
464
+ }
465
+ };
466
+ };
467
+ const createLifecyclesService = ({ strapi: strapi2 }) => {
468
+ const state = {
469
+ deleteExpiredJob: null,
470
+ isInitialized: false
471
+ };
472
+ const serviceUtils = createServiceUtils({ strapi: strapi2 });
473
+ return {
474
+ async bootstrap() {
475
+ if (state.isInitialized) {
476
+ return;
477
+ }
478
+ strapi2.documents.use(async (context, next) => {
479
+ if (!strapi2.requestContext.get()?.request.url.startsWith("/content-manager")) {
480
+ return next();
481
+ }
482
+ if (context.action !== "create" && context.action !== "update" && context.action !== "clone" && context.action !== "publish" && context.action !== "unpublish" && context.action !== "discardDraft") {
483
+ return next();
484
+ }
485
+ if (context.action === "update" && strapi2.requestContext.get()?.request.url.endsWith("/actions/publish")) {
486
+ return next();
487
+ }
488
+ const contentTypeUid = context.contentType.uid;
489
+ if (!contentTypeUid.startsWith("api::")) {
490
+ return next();
491
+ }
492
+ const result = await next();
493
+ const documentContext = {
494
+ documentId: context.action === "create" || context.action === "clone" ? result.documentId : context.params.documentId,
495
+ locale: context.params?.locale
496
+ };
497
+ const defaultLocale = await serviceUtils.getDefaultLocale();
498
+ const locale = documentContext.locale || defaultLocale;
499
+ if (Array.isArray(locale)) {
500
+ strapi2.log.warn(
501
+ "[Content manager history middleware]: An array of locales was provided, but only a single locale is supported for the findOne operation."
502
+ );
503
+ return next();
504
+ }
505
+ const document = await strapi2.documents(contentTypeUid).findOne({
506
+ documentId: documentContext.documentId,
507
+ locale,
508
+ populate: serviceUtils.getDeepPopulate(contentTypeUid)
509
+ });
510
+ const status = await serviceUtils.getVersionStatus(contentTypeUid, document);
511
+ const attributesSchema = strapi2.getModel(contentTypeUid).attributes;
512
+ const componentsSchemas = Object.keys(
513
+ attributesSchema
514
+ ).reduce((currentComponentSchemas, key) => {
515
+ const fieldSchema = attributesSchema[key];
516
+ if (fieldSchema.type === "component") {
517
+ const componentSchema = strapi2.getModel(fieldSchema.component).attributes;
518
+ return {
519
+ ...currentComponentSchemas,
520
+ [fieldSchema.component]: componentSchema
521
+ };
522
+ }
523
+ return currentComponentSchemas;
524
+ }, {});
525
+ await strapi2.db.transaction(async ({ onCommit }) => {
526
+ onCommit(() => {
527
+ getService(strapi2, "history").createVersion({
528
+ contentType: contentTypeUid,
529
+ data: omit(FIELDS_TO_IGNORE, document),
530
+ schema: omit(FIELDS_TO_IGNORE, attributesSchema),
531
+ componentsSchemas,
532
+ relatedDocumentId: documentContext.documentId,
533
+ locale,
534
+ status
535
+ });
536
+ });
537
+ });
538
+ return result;
539
+ });
540
+ state.deleteExpiredJob = scheduleJob("0 0 * * *", () => {
541
+ const retentionDaysInMilliseconds = serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1e3;
542
+ const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);
543
+ strapi2.db.query(HISTORY_VERSION_UID).deleteMany({
544
+ where: {
545
+ created_at: {
546
+ $lt: expirationDate.toISOString()
547
+ }
548
+ }
549
+ });
550
+ });
551
+ state.isInitialized = true;
552
+ },
553
+ async destroy() {
554
+ if (state.deleteExpiredJob) {
555
+ state.deleteExpiredJob.cancel();
556
+ }
557
+ }
558
+ };
559
+ };
560
+ const services$1 = {
561
+ history: createHistoryService,
562
+ lifecycles: createLifecyclesService
563
+ };
564
+ const info = { pluginName: "content-manager", type: "admin" };
565
+ const historyVersionRouter = {
566
+ type: "admin",
567
+ routes: [
568
+ {
569
+ method: "GET",
570
+ info,
571
+ path: "/history-versions",
572
+ handler: "history-version.findMany",
573
+ config: {
574
+ policies: ["admin::isAuthenticatedAdmin"]
575
+ }
576
+ },
577
+ {
578
+ method: "PUT",
579
+ info,
580
+ path: "/history-versions/:versionId/restore",
581
+ handler: "history-version.restoreVersion",
582
+ config: {
583
+ policies: ["admin::isAuthenticatedAdmin"]
584
+ }
585
+ }
586
+ ]
587
+ };
588
+ const routes$1 = {
589
+ "history-version": historyVersionRouter
590
+ };
591
+ const historyVersion = {
592
+ uid: HISTORY_VERSION_UID,
593
+ tableName: "strapi_history_versions",
594
+ singularName: "history-version",
595
+ attributes: {
596
+ id: {
597
+ type: "increments"
598
+ },
599
+ contentType: {
600
+ type: "string",
601
+ column: { notNullable: true }
602
+ },
603
+ relatedDocumentId: {
604
+ type: "string",
605
+ // TODO: notNullable should be true once history can record publish actions
606
+ column: { notNullable: false }
607
+ },
608
+ locale: {
609
+ type: "string"
610
+ },
611
+ status: {
612
+ type: "enumeration",
613
+ enum: ["draft", "published", "modified"]
614
+ },
615
+ data: {
616
+ type: "json"
617
+ },
618
+ schema: {
619
+ type: "json"
620
+ },
621
+ createdAt: {
622
+ type: "datetime",
623
+ default: () => /* @__PURE__ */ new Date()
624
+ },
625
+ // FIXME: joinTable should be optional
626
+ // @ts-expect-error database model is not yet updated to support useJoinTable
627
+ createdBy: {
628
+ type: "relation",
629
+ relation: "oneToOne",
630
+ target: "admin::user",
631
+ useJoinTable: false
632
+ }
633
+ }
634
+ };
635
+ const getFeature = () => {
636
+ if (strapi.ee.features.isEnabled("cms-content-history")) {
637
+ return {
638
+ register({ strapi: strapi2 }) {
639
+ strapi2.get("models").add(historyVersion);
640
+ },
641
+ bootstrap({ strapi: strapi2 }) {
642
+ getService(strapi2, "lifecycles").bootstrap();
643
+ },
644
+ destroy({ strapi: strapi2 }) {
645
+ getService(strapi2, "lifecycles").destroy();
646
+ },
647
+ controllers: controllers$1,
648
+ services: services$1,
649
+ routes: routes$1
650
+ };
651
+ }
652
+ return {
653
+ register({ strapi: strapi2 }) {
654
+ strapi2.get("models").add(historyVersion);
655
+ }
656
+ };
657
+ };
658
+ const history = getFeature();
659
+ const register = async ({ strapi: strapi2 }) => {
660
+ await history.register?.({ strapi: strapi2 });
661
+ };
662
+ const ALLOWED_WEBHOOK_EVENTS = {
663
+ ENTRY_PUBLISH: "entry.publish",
664
+ ENTRY_UNPUBLISH: "entry.unpublish"
665
+ };
666
+ const bootstrap = async () => {
667
+ Object.entries(ALLOWED_WEBHOOK_EVENTS).forEach(([key, value]) => {
668
+ strapi.get("webhookStore").addAllowedEvent(key, value);
669
+ });
670
+ getService$1("field-sizes").setCustomFieldInputSizes();
671
+ await getService$1("components").syncConfigurations();
672
+ await getService$1("content-types").syncConfigurations();
673
+ await getService$1("permission").registerPermissions();
674
+ await history.bootstrap?.({ strapi });
675
+ };
676
+ const destroy = async ({ strapi: strapi2 }) => {
677
+ await history.destroy?.({ strapi: strapi2 });
678
+ };
679
+ const routing = async (ctx, next) => {
680
+ const { model } = ctx.params;
681
+ const ct = strapi.contentTypes[model];
682
+ if (!ct) {
683
+ return ctx.send({ error: "contentType.notFound" }, 404);
684
+ }
685
+ let controllers2;
686
+ if (!ct.plugin || ct.plugin === "admin") {
687
+ controllers2 = strapi.admin.controllers;
688
+ } else {
689
+ controllers2 = strapi.plugin(ct.plugin).controllers;
690
+ }
691
+ const { route } = ctx.state;
692
+ if (typeof route.handler !== "string") {
693
+ return next();
694
+ }
695
+ const [, action] = route.handler.split(".");
696
+ let actionConfig;
697
+ if (!ct.plugin || ct.plugin === "admin") {
698
+ actionConfig = strapi.config.get(`admin.layout.${ct.modelName}.actions.${action}`);
699
+ } else {
700
+ actionConfig = strapi.plugin(ct.plugin).config(`layout.${ct.modelName}.actions.${action}`);
701
+ }
702
+ if (!isNil(actionConfig)) {
703
+ const [controller, action2] = actionConfig.split(".");
704
+ if (controller && action2) {
705
+ return controllers2[controller.toLowerCase()][action2](ctx, next);
706
+ }
707
+ }
708
+ await next();
709
+ };
710
+ const admin = {
711
+ type: "admin",
712
+ routes: [
713
+ {
714
+ method: "GET",
715
+ path: "/init",
716
+ handler: "init.getInitData",
717
+ config: {
718
+ policies: []
719
+ }
720
+ },
721
+ {
722
+ method: "GET",
723
+ path: "/content-types",
724
+ handler: "content-types.findContentTypes",
725
+ config: {
726
+ policies: []
727
+ }
728
+ },
729
+ {
730
+ method: "GET",
731
+ path: "/content-types-settings",
732
+ handler: "content-types.findContentTypesSettings",
733
+ config: {
734
+ policies: []
735
+ }
736
+ },
737
+ {
738
+ method: "GET",
739
+ path: "/content-types/:uid/configuration",
740
+ handler: "content-types.findContentTypeConfiguration",
741
+ config: {
742
+ policies: []
743
+ }
744
+ },
745
+ {
746
+ method: "PUT",
747
+ path: "/content-types/:uid/configuration",
748
+ handler: "content-types.updateContentTypeConfiguration",
749
+ config: {
750
+ policies: ["admin::isAuthenticatedAdmin"]
751
+ }
752
+ },
753
+ {
754
+ method: "GET",
755
+ path: "/components",
756
+ handler: "components.findComponents",
757
+ config: {
758
+ policies: []
759
+ }
760
+ },
761
+ {
762
+ method: "GET",
763
+ path: "/components/:uid/configuration",
764
+ handler: "components.findComponentConfiguration",
765
+ config: {
766
+ policies: []
767
+ }
768
+ },
769
+ {
770
+ method: "PUT",
771
+ path: "/components/:uid/configuration",
772
+ handler: "components.updateComponentConfiguration",
773
+ config: {
774
+ policies: []
775
+ }
776
+ },
777
+ {
778
+ method: "POST",
779
+ path: "/uid/generate",
780
+ handler: "uid.generateUID",
781
+ config: {
782
+ policies: []
783
+ }
784
+ },
785
+ {
786
+ method: "POST",
787
+ path: "/uid/check-availability",
788
+ handler: "uid.checkUIDAvailability",
789
+ config: {
790
+ policies: []
791
+ }
792
+ },
793
+ {
794
+ method: "GET",
795
+ path: "/relations/:model/:targetField",
796
+ handler: "relations.findAvailable",
797
+ config: {
798
+ policies: ["admin::isAuthenticatedAdmin"]
799
+ }
800
+ },
801
+ {
802
+ method: "GET",
803
+ path: "/relations/:model/:id/:targetField",
804
+ handler: "relations.findExisting",
805
+ config: {
806
+ policies: ["admin::isAuthenticatedAdmin"]
807
+ }
808
+ },
809
+ {
810
+ method: "GET",
811
+ path: "/single-types/:model",
812
+ handler: "single-types.find",
813
+ config: {
814
+ middlewares: [routing],
815
+ policies: [
816
+ "admin::isAuthenticatedAdmin",
817
+ {
818
+ name: "plugin::content-manager.hasPermissions",
819
+ config: { actions: ["plugin::content-manager.explorer.read"] }
820
+ }
821
+ ]
822
+ }
823
+ },
824
+ {
825
+ method: "PUT",
826
+ path: "/single-types/:model",
827
+ handler: "single-types.createOrUpdate",
828
+ config: {
829
+ middlewares: [routing],
830
+ policies: [
831
+ "admin::isAuthenticatedAdmin",
832
+ {
833
+ name: "plugin::content-manager.hasPermissions",
834
+ config: {
835
+ actions: [
836
+ "plugin::content-manager.explorer.create",
837
+ "plugin::content-manager.explorer.update"
838
+ ],
839
+ hasAtLeastOne: true
840
+ }
841
+ }
842
+ ]
843
+ }
844
+ },
845
+ {
846
+ method: "DELETE",
847
+ path: "/single-types/:model",
848
+ handler: "single-types.delete",
849
+ config: {
850
+ middlewares: [routing],
851
+ policies: [
852
+ "admin::isAuthenticatedAdmin",
853
+ {
854
+ name: "plugin::content-manager.hasPermissions",
855
+ config: { actions: ["plugin::content-manager.explorer.delete"] }
856
+ }
857
+ ]
858
+ }
859
+ },
860
+ {
861
+ method: "POST",
862
+ path: "/single-types/:model/actions/publish",
863
+ handler: "single-types.publish",
864
+ config: {
865
+ middlewares: [routing],
866
+ policies: [
867
+ "admin::isAuthenticatedAdmin",
868
+ {
869
+ name: "plugin::content-manager.hasPermissions",
870
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
871
+ }
872
+ ]
873
+ }
874
+ },
875
+ {
876
+ method: "POST",
877
+ path: "/single-types/:model/actions/unpublish",
878
+ handler: "single-types.unpublish",
879
+ config: {
880
+ middlewares: [routing],
881
+ policies: [
882
+ "admin::isAuthenticatedAdmin",
883
+ {
884
+ name: "plugin::content-manager.hasPermissions",
885
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
886
+ }
887
+ ]
888
+ }
889
+ },
890
+ {
891
+ method: "POST",
892
+ path: "/single-types/:model/actions/discard",
893
+ handler: "single-types.discard",
894
+ config: {
895
+ middlewares: [routing],
896
+ policies: [
897
+ "admin::isAuthenticatedAdmin",
898
+ {
899
+ name: "plugin::content-manager.hasPermissions",
900
+ config: { actions: ["plugin::content-manager.explorer.update"] }
901
+ }
902
+ ]
903
+ }
904
+ },
905
+ {
906
+ method: "GET",
907
+ path: "/single-types/:model/actions/countDraftRelations",
908
+ handler: "single-types.countDraftRelations",
909
+ config: {
910
+ middlewares: [routing],
911
+ policies: [
912
+ "admin::isAuthenticatedAdmin",
913
+ {
914
+ name: "plugin::content-manager.hasPermissions",
915
+ config: { actions: ["plugin::content-manager.explorer.read"] }
916
+ }
917
+ ]
918
+ }
919
+ },
920
+ {
921
+ method: "GET",
922
+ path: "/collection-types/:model",
923
+ handler: "collection-types.find",
924
+ config: {
925
+ middlewares: [routing],
926
+ policies: [
927
+ "admin::isAuthenticatedAdmin",
928
+ {
929
+ name: "plugin::content-manager.hasPermissions",
930
+ config: { actions: ["plugin::content-manager.explorer.read"] }
931
+ }
932
+ ]
933
+ }
934
+ },
935
+ {
936
+ method: "POST",
937
+ path: "/collection-types/:model",
938
+ handler: "collection-types.create",
939
+ config: {
940
+ middlewares: [routing],
941
+ policies: [
942
+ "admin::isAuthenticatedAdmin",
943
+ {
944
+ name: "plugin::content-manager.hasPermissions",
945
+ config: { actions: ["plugin::content-manager.explorer.create"] }
946
+ }
947
+ ]
948
+ }
949
+ },
950
+ {
951
+ method: "POST",
952
+ path: "/collection-types/:model/clone/:sourceId",
953
+ handler: "collection-types.clone",
954
+ config: {
955
+ middlewares: [routing],
956
+ policies: [
957
+ "admin::isAuthenticatedAdmin",
958
+ {
959
+ name: "plugin::content-manager.hasPermissions",
960
+ config: { actions: ["plugin::content-manager.explorer.create"] }
961
+ }
962
+ ]
963
+ }
964
+ },
965
+ {
966
+ method: "POST",
967
+ path: "/collection-types/:model/auto-clone/:sourceId",
968
+ handler: "collection-types.autoClone",
969
+ config: {
970
+ middlewares: [routing],
971
+ policies: [
972
+ "admin::isAuthenticatedAdmin",
973
+ {
974
+ name: "plugin::content-manager.hasPermissions",
975
+ config: { actions: ["plugin::content-manager.explorer.create"] }
976
+ }
977
+ ]
978
+ }
979
+ },
980
+ {
981
+ method: "GET",
982
+ path: "/collection-types/:model/:id",
983
+ handler: "collection-types.findOne",
984
+ config: {
985
+ middlewares: [routing],
986
+ policies: [
987
+ "admin::isAuthenticatedAdmin",
988
+ {
989
+ name: "plugin::content-manager.hasPermissions",
990
+ config: { actions: ["plugin::content-manager.explorer.read"] }
991
+ }
992
+ ]
993
+ }
994
+ },
995
+ {
996
+ method: "PUT",
997
+ path: "/collection-types/:model/:id",
998
+ handler: "collection-types.update",
999
+ config: {
1000
+ middlewares: [routing],
1001
+ policies: [
1002
+ "admin::isAuthenticatedAdmin",
1003
+ {
1004
+ name: "plugin::content-manager.hasPermissions",
1005
+ config: { actions: ["plugin::content-manager.explorer.update"] }
1006
+ }
1007
+ ]
1008
+ }
1009
+ },
1010
+ {
1011
+ method: "DELETE",
1012
+ path: "/collection-types/:model/:id",
1013
+ handler: "collection-types.delete",
1014
+ config: {
1015
+ middlewares: [routing],
1016
+ policies: [
1017
+ "admin::isAuthenticatedAdmin",
1018
+ {
1019
+ name: "plugin::content-manager.hasPermissions",
1020
+ config: { actions: ["plugin::content-manager.explorer.delete"] }
1021
+ }
1022
+ ]
1023
+ }
1024
+ },
1025
+ {
1026
+ method: "POST",
1027
+ path: "/collection-types/:model/actions/publish",
1028
+ handler: "collection-types.publish",
1029
+ config: {
1030
+ middlewares: [routing],
1031
+ policies: [
1032
+ "admin::isAuthenticatedAdmin",
1033
+ {
1034
+ name: "plugin::content-manager.hasPermissions",
1035
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1036
+ }
1037
+ ]
1038
+ }
1039
+ },
1040
+ {
1041
+ method: "POST",
1042
+ path: "/collection-types/:model/:id/actions/publish",
1043
+ handler: "collection-types.publish",
1044
+ config: {
1045
+ middlewares: [routing],
1046
+ policies: [
1047
+ "admin::isAuthenticatedAdmin",
1048
+ {
1049
+ name: "plugin::content-manager.hasPermissions",
1050
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1051
+ }
1052
+ ]
1053
+ }
1054
+ },
1055
+ {
1056
+ method: "POST",
1057
+ path: "/collection-types/:model/:id/actions/unpublish",
1058
+ handler: "collection-types.unpublish",
1059
+ config: {
1060
+ middlewares: [routing],
1061
+ policies: [
1062
+ "admin::isAuthenticatedAdmin",
1063
+ {
1064
+ name: "plugin::content-manager.hasPermissions",
1065
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1066
+ }
1067
+ ]
1068
+ }
1069
+ },
1070
+ {
1071
+ method: "POST",
1072
+ path: "/collection-types/:model/:id/actions/discard",
1073
+ handler: "collection-types.discard",
1074
+ config: {
1075
+ middlewares: [routing],
1076
+ policies: [
1077
+ "admin::isAuthenticatedAdmin",
1078
+ {
1079
+ name: "plugin::content-manager.hasPermissions",
1080
+ config: { actions: ["plugin::content-manager.explorer.update"] }
1081
+ }
1082
+ ]
1083
+ }
1084
+ },
1085
+ {
1086
+ method: "POST",
1087
+ path: "/collection-types/:model/actions/bulkDelete",
1088
+ handler: "collection-types.bulkDelete",
1089
+ config: {
1090
+ middlewares: [routing],
1091
+ policies: [
1092
+ "admin::isAuthenticatedAdmin",
1093
+ {
1094
+ name: "plugin::content-manager.hasPermissions",
1095
+ config: { actions: ["plugin::content-manager.explorer.delete"] }
1096
+ }
1097
+ ]
1098
+ }
1099
+ },
1100
+ {
1101
+ method: "POST",
1102
+ path: "/collection-types/:model/actions/bulkPublish",
1103
+ handler: "collection-types.bulkPublish",
1104
+ config: {
1105
+ middlewares: [routing],
1106
+ policies: [
1107
+ "admin::isAuthenticatedAdmin",
1108
+ {
1109
+ name: "plugin::content-manager.hasPermissions",
1110
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1111
+ }
1112
+ ]
1113
+ }
1114
+ },
1115
+ {
1116
+ method: "POST",
1117
+ path: "/collection-types/:model/actions/bulkUnpublish",
1118
+ handler: "collection-types.bulkUnpublish",
1119
+ config: {
1120
+ middlewares: [routing],
1121
+ policies: [
1122
+ "admin::isAuthenticatedAdmin",
1123
+ {
1124
+ name: "plugin::content-manager.hasPermissions",
1125
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1126
+ }
1127
+ ]
1128
+ }
1129
+ },
1130
+ {
1131
+ method: "GET",
1132
+ path: "/collection-types/:model/:id/actions/countDraftRelations",
1133
+ handler: "collection-types.countDraftRelations",
1134
+ config: {
1135
+ middlewares: [routing],
1136
+ policies: [
1137
+ "admin::isAuthenticatedAdmin",
1138
+ {
1139
+ name: "plugin::content-manager.hasPermissions",
1140
+ config: { actions: ["plugin::content-manager.explorer.read"] }
1141
+ }
1142
+ ]
1143
+ }
1144
+ },
1145
+ {
1146
+ method: "GET",
1147
+ path: "/collection-types/:model/actions/countManyEntriesDraftRelations",
1148
+ handler: "collection-types.countManyEntriesDraftRelations",
1149
+ config: {
1150
+ middlewares: [routing],
1151
+ policies: [
1152
+ "admin::isAuthenticatedAdmin",
1153
+ {
1154
+ name: "plugin::content-manager.hasPermissions",
1155
+ config: { actions: ["plugin::content-manager.explorer.read"] }
1156
+ }
1157
+ ]
1158
+ }
1159
+ }
1160
+ ]
1161
+ };
1162
+ const routes = {
1163
+ admin,
1164
+ ...history.routes ? history.routes : {}
1165
+ };
1166
+ const hasPermissionsSchema = yup$1.object({
1167
+ actions: yup$1.array().of(yup$1.string()),
1168
+ hasAtLeastOne: yup$1.boolean()
1169
+ });
1170
+ const validateHasPermissionsInput = validateYupSchemaSync(hasPermissionsSchema);
1171
+ const { createPolicy } = policy;
1172
+ const hasPermissions = createPolicy({
1173
+ name: "plugin::content-manager.hasPermissions",
1174
+ validator: validateHasPermissionsInput,
1175
+ handler(ctx, config = {}) {
1176
+ const { actions = [], hasAtLeastOne = false } = config;
1177
+ const { userAbility } = ctx.state;
1178
+ const { model } = ctx.params;
1179
+ const isAuthorized = hasAtLeastOne ? actions.some((action) => userAbility.can(action, model)) : actions.every((action) => userAbility.can(action, model));
1180
+ return isAuthorized;
1181
+ }
1182
+ });
1183
+ const policies = {
1184
+ hasPermissions
1185
+ };
1186
+ const { getNonVisibleAttributes, getWritableAttributes } = contentTypes$1;
1187
+ const { PUBLISHED_AT_ATTRIBUTE: PUBLISHED_AT_ATTRIBUTE$3, CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE } = contentTypes$1.constants;
1188
+ const NON_SORTABLES = ["component", "json", "media", "richtext", "dynamiczone", "blocks"];
1189
+ const SORTABLE_RELATIONS = ["oneToOne", "manyToOne"];
1190
+ const NON_LISTABLES = ["json", "password", "richtext", "dynamiczone", "blocks"];
1191
+ const LISTABLE_RELATIONS = ["oneToOne", "oneToMany", "manyToOne", "manyToMany"];
1192
+ const isHidden = (schema, name) => {
1193
+ if (!_.has(schema.attributes, name)) {
1194
+ return false;
1195
+ }
1196
+ const isHidden2 = _.get(schema, ["config", "attributes", name, "hidden"], false);
1197
+ if (isHidden2 === true) {
1198
+ return true;
1199
+ }
1200
+ return false;
1201
+ };
1202
+ const isListable = (schema, name) => {
1203
+ if (!_.has(schema.attributes, name)) {
1204
+ return false;
1205
+ }
1206
+ if (isHidden(schema, name)) {
1207
+ return false;
1208
+ }
1209
+ const attribute = schema.attributes[name];
1210
+ if (NON_LISTABLES.includes(attribute.type)) {
1211
+ return false;
1212
+ }
1213
+ if (isRelation$1(attribute) && !LISTABLE_RELATIONS.includes(attribute.relationType)) {
1214
+ return false;
1215
+ }
1216
+ return true;
1217
+ };
1218
+ const isSortable = (schema, name) => {
1219
+ if (!_.has(schema.attributes, name)) {
1220
+ return false;
1221
+ }
1222
+ if (schema.modelType === "component" && name === "id")
1223
+ return false;
1224
+ const attribute = schema.attributes[name];
1225
+ if (NON_SORTABLES.includes(attribute.type)) {
1226
+ return false;
1227
+ }
1228
+ if (isRelation$1(attribute) && !SORTABLE_RELATIONS.includes(attribute.relationType)) {
1229
+ return false;
1230
+ }
1231
+ return true;
1232
+ };
1233
+ const isSearchable = (schema, name) => {
1234
+ return isSortable(schema, name);
1235
+ };
1236
+ const isVisible$1 = (schema, name) => {
1237
+ if (!_.has(schema.attributes, name)) {
1238
+ return false;
1239
+ }
1240
+ if (isHidden(schema, name)) {
1241
+ return false;
1242
+ }
1243
+ if (isTimestamp(schema, name) || name === "id") {
1244
+ return false;
1245
+ }
1246
+ if (isPublicationField(name)) {
1247
+ return false;
1248
+ }
1249
+ if (isCreatorField(schema, name)) {
1250
+ return false;
1251
+ }
1252
+ return true;
1253
+ };
1254
+ const isPublicationField = (name) => PUBLISHED_AT_ATTRIBUTE$3 === name;
1255
+ const isTimestamp = (schema, name) => {
1256
+ if (!_.has(schema.attributes, name)) {
1257
+ return false;
1258
+ }
1259
+ const timestamps = contentTypes$1.getTimestamps(schema);
1260
+ if (!timestamps || !Array.isArray(timestamps)) {
1261
+ return false;
1262
+ }
1263
+ if (timestamps.includes(name)) {
1264
+ return true;
1265
+ }
1266
+ };
1267
+ const isCreatorField = (schema, name) => {
1268
+ if (!_.has(schema.attributes, name)) {
1269
+ return false;
1270
+ }
1271
+ const creatorFields = contentTypes$1.getCreatorFields(schema);
1272
+ if (!creatorFields || !Array.isArray(creatorFields)) {
1273
+ return false;
1274
+ }
1275
+ if (creatorFields.includes(name)) {
1276
+ return true;
1277
+ }
1278
+ };
1279
+ const isRelation$1 = (attribute) => attribute.type === "relation";
1280
+ const hasRelationAttribute = (schema, name) => {
1281
+ if (!_.has(schema.attributes, name)) {
1282
+ return false;
1283
+ }
1284
+ if (isHidden(schema, name)) {
1285
+ return false;
1286
+ }
1287
+ if (!isVisible$1(schema, name)) {
1288
+ return false;
1289
+ }
1290
+ return isRelation$1(schema.attributes[name]);
1291
+ };
1292
+ const hasEditableAttribute = (schema, name) => {
1293
+ if (!_.has(schema.attributes, name)) {
1294
+ return false;
1295
+ }
1296
+ if (isHidden(schema, name)) {
1297
+ return false;
1298
+ }
1299
+ if (!isVisible$1(schema, name)) {
1300
+ return false;
1301
+ }
1302
+ return true;
1303
+ };
1304
+ const findFirstStringAttribute = (schema) => {
1305
+ return Object.keys(schema.attributes || {}).find((key) => {
1306
+ const { type } = schema.attributes[key];
1307
+ return type === "string" && key !== "id";
1308
+ });
1309
+ };
1310
+ const getDefaultMainField = (schema) => findFirstStringAttribute(schema) || "id";
1311
+ const getSortableAttributes = (schema) => {
1312
+ const validAttributes = Object.keys(schema.attributes).filter((key) => isListable(schema, key));
1313
+ const model = strapi.getModel(schema.uid);
1314
+ const nonVisibleWritableAttributes = intersection(
1315
+ getNonVisibleAttributes(model),
1316
+ getWritableAttributes(model)
1317
+ );
1318
+ return [
1319
+ "id",
1320
+ ...validAttributes,
1321
+ ...nonVisibleWritableAttributes,
1322
+ CREATED_BY_ATTRIBUTE,
1323
+ UPDATED_BY_ATTRIBUTE
1324
+ ];
1325
+ };
1326
+ const DEFAULT_SETTINGS = {
1327
+ bulkable: true,
1328
+ filterable: true,
1329
+ searchable: true,
1330
+ pageSize: 10
1331
+ };
1332
+ const settingsFields = [
1333
+ "searchable",
1334
+ "filterable",
1335
+ "bulkable",
1336
+ "pageSize",
1337
+ "mainField",
1338
+ "defaultSortBy",
1339
+ "defaultSortOrder"
1340
+ ];
1341
+ const getModelSettings = pipe([propOr({}, "config.settings"), pick(settingsFields)]);
1342
+ async function isValidDefaultSort(schema, value) {
1343
+ const parsedValue = qs.parse(value);
1344
+ const omitNonSortableAttributes = ({ schema: schema2, key }, { remove }) => {
1345
+ const sortableAttributes = getSortableAttributes(schema2);
1346
+ if (!sortableAttributes.includes(key)) {
1347
+ remove(key);
1348
+ }
1349
+ };
1350
+ const sanitizedValue = await traverse.traverseQuerySort(
1351
+ omitNonSortableAttributes,
1352
+ { schema, getModel: strapi.getModel.bind(strapi) },
1353
+ parsedValue
1354
+ );
1355
+ return isEqual(parsedValue, sanitizedValue);
1356
+ }
1357
+ const createDefaultSettings = async (schema) => {
1358
+ const defaultField = getDefaultMainField(schema);
1359
+ return {
1360
+ ...DEFAULT_SETTINGS,
1361
+ mainField: defaultField,
1362
+ defaultSortBy: defaultField,
1363
+ defaultSortOrder: "ASC",
1364
+ ...getModelSettings(schema)
1365
+ };
1366
+ };
1367
+ const syncSettings = async (configuration, schema) => {
1368
+ if (isEmpty(configuration.settings))
1369
+ return createDefaultSettings(schema);
1370
+ const defaultField = getDefaultMainField(schema);
1371
+ const { mainField = defaultField, defaultSortBy = defaultField } = configuration.settings || {};
1372
+ return {
1373
+ ...configuration.settings,
1374
+ mainField: isSortable(schema, mainField) ? mainField : defaultField,
1375
+ defaultSortBy: await isValidDefaultSort(schema, defaultSortBy) ? defaultSortBy : defaultField
1376
+ };
1377
+ };
1378
+ const createModelConfigurationSchema = (schema, opts = {}) => yup$1.object().shape({
1379
+ settings: createSettingsSchema(schema).default(null).nullable(),
1380
+ metadatas: createMetadasSchema(schema).default(null).nullable(),
1381
+ layouts: createLayoutsSchema(schema, opts).default(null).nullable(),
1382
+ options: yup$1.object().optional()
1383
+ }).noUnknown();
1384
+ const createSettingsSchema = (schema) => {
1385
+ const validAttributes = Object.keys(schema.attributes).filter((key) => isListable(schema, key));
1386
+ return yup$1.object().shape({
1387
+ bulkable: yup$1.boolean().required(),
1388
+ filterable: yup$1.boolean().required(),
1389
+ pageSize: yup$1.number().integer().min(10).max(100).required(),
1390
+ searchable: yup$1.boolean().required(),
1391
+ // should be reset when the type changes
1392
+ mainField: yup$1.string().oneOf(validAttributes.concat("id")).default("id"),
1393
+ // should be reset when the type changes
1394
+ defaultSortBy: yup$1.string().test(
1395
+ "is-valid-sort-attribute",
1396
+ "${path} is not a valid sort attribute",
1397
+ async (value) => isValidDefaultSort(schema, value)
1398
+ ).default("id"),
1399
+ defaultSortOrder: yup$1.string().oneOf(["ASC", "DESC"]).default("ASC")
1400
+ }).noUnknown();
1401
+ };
1402
+ const createMetadasSchema = (schema) => {
1403
+ return yup$1.object().shape(
1404
+ Object.keys(schema.attributes).reduce((acc, key) => {
1405
+ acc[key] = yup$1.object().shape({
1406
+ edit: yup$1.object().shape({
1407
+ label: yup$1.string(),
1408
+ description: yup$1.string(),
1409
+ placeholder: yup$1.string(),
1410
+ editable: yup$1.boolean(),
1411
+ visible: yup$1.boolean(),
1412
+ mainField: yup$1.lazy((value) => {
1413
+ if (!value) {
1414
+ return yup$1.string();
1415
+ }
1416
+ const targetSchema = getService$1("content-types").findContentType(
1417
+ schema.attributes[key].targetModel
1418
+ );
1419
+ if (!targetSchema) {
1420
+ return yup$1.string();
1421
+ }
1422
+ const validAttributes = Object.keys(targetSchema.attributes).filter(
1423
+ (key2) => isListable(targetSchema, key2)
1424
+ );
1425
+ return yup$1.string().oneOf(validAttributes.concat("id")).default("id");
1426
+ })
1427
+ }).noUnknown().required(),
1428
+ list: yup$1.object().shape({
1429
+ label: yup$1.string(),
1430
+ searchable: yup$1.boolean(),
1431
+ sortable: yup$1.boolean()
1432
+ }).noUnknown().required()
1433
+ }).noUnknown();
1434
+ return acc;
1435
+ }, {})
1436
+ );
1437
+ };
1438
+ const createArrayTest = ({ allowUndefined = false } = {}) => ({
1439
+ name: "isArray",
1440
+ message: "${path} is required and must be an array",
1441
+ test: (val) => allowUndefined === true && val === void 0 ? true : Array.isArray(val)
1442
+ });
1443
+ const createLayoutsSchema = (schema, opts = {}) => {
1444
+ const validAttributes = Object.keys(schema.attributes).filter((key) => isListable(schema, key));
1445
+ const editAttributes = Object.keys(schema.attributes).filter(
1446
+ (key) => hasEditableAttribute(schema, key)
1447
+ );
1448
+ return yup$1.object().shape({
1449
+ edit: yup$1.array().of(
1450
+ yup$1.array().of(
1451
+ yup$1.object().shape({
1452
+ name: yup$1.string().oneOf(editAttributes).required(),
1453
+ size: yup$1.number().integer().positive().required()
1454
+ }).noUnknown()
1455
+ )
1456
+ ).test(createArrayTest(opts)),
1457
+ list: yup$1.array().of(yup$1.string().oneOf(validAttributes)).test(createArrayTest(opts))
1458
+ });
1459
+ };
1460
+ const { PaginationError, ValidationError } = errors;
1461
+ const TYPES = ["singleType", "collectionType"];
1462
+ const kindSchema = yup$1.string().oneOf(TYPES).nullable();
1463
+ const bulkActionInputSchema = yup$1.object({
1464
+ documentIds: yup$1.array().of(yup$1.strapiID()).min(1).required()
1465
+ }).required();
1466
+ const generateUIDInputSchema = yup$1.object({
1467
+ contentTypeUID: yup$1.string().required(),
1468
+ field: yup$1.string().required(),
1469
+ data: yup$1.object().required()
1470
+ });
1471
+ const checkUIDAvailabilityInputSchema = yup$1.object({
1472
+ contentTypeUID: yup$1.string().required(),
1473
+ field: yup$1.string().required(),
1474
+ value: yup$1.string().matches(/^[A-Za-z0-9-_.~]*$/).required()
1475
+ });
1476
+ const validateUIDField = (contentTypeUID, field) => {
1477
+ const model = strapi.contentTypes[contentTypeUID];
1478
+ if (!model) {
1479
+ throw new ValidationError("ContentType not found");
1480
+ }
1481
+ if (!_.has(model, ["attributes", field]) || _.get(model, ["attributes", field, "type"]) !== "uid") {
1482
+ throw new ValidationError(`${field} must be a valid \`uid\` attribute`);
1483
+ }
1484
+ };
1485
+ const validateKind = validateYupSchema(kindSchema);
1486
+ const validateBulkActionInput = validateYupSchema(bulkActionInputSchema);
1487
+ const validateGenerateUIDInput = validateYupSchema(generateUIDInputSchema);
1488
+ const validateCheckUIDAvailabilityInput = validateYupSchema(checkUIDAvailabilityInputSchema);
1489
+ const { isVisibleAttribute: isVisibleAttribute$2 } = strapiUtils.contentTypes;
1490
+ function checkRelation(model, attributeName, path) {
1491
+ if (!isVisibleAttribute$2(model, attributeName)) {
1492
+ return [];
1493
+ }
1494
+ const { relation, inversedBy, mappedBy } = model.attributes[attributeName];
1495
+ if (["oneToOne", "oneToMany"].includes(relation) && [mappedBy, inversedBy].some((key) => key != null)) {
1496
+ return [[[...path, attributeName], "relation"]];
1497
+ }
1498
+ return [];
1499
+ }
1500
+ const getProhibitedCloningFields = (uid2, pathPrefix = []) => {
1501
+ const model = strapi.getModel(uid2);
1502
+ const prohibitedFields = Object.keys(model.attributes).reduce(
1503
+ (acc, attributeName) => {
1504
+ const attribute = model.attributes[attributeName];
1505
+ const attributePath = [...pathPrefix, attributeName];
1506
+ switch (attribute.type) {
1507
+ case "relation":
1508
+ return [...acc, ...checkRelation(model, attributeName, pathPrefix)];
1509
+ case "component":
1510
+ return [...acc, ...getProhibitedCloningFields(attribute.component, attributePath)];
1511
+ case "dynamiczone":
1512
+ return [
1513
+ ...acc,
1514
+ ...(attribute.components || []).flatMap(
1515
+ (componentUID) => getProhibitedCloningFields(componentUID, [
1516
+ ...attributePath,
1517
+ strapi.getModel(componentUID).info.displayName
1518
+ ])
1519
+ )
1520
+ ];
1521
+ case "uid":
1522
+ return [...acc, [attributePath, "unique"]];
1523
+ default:
1524
+ if (attribute?.unique) {
1525
+ return [...acc, [attributePath, "unique"]];
1526
+ }
1527
+ return acc;
1528
+ }
1529
+ },
1530
+ []
1531
+ );
1532
+ return prohibitedFields;
1533
+ };
1534
+ const excludeNotCreatableFields = (uid2, permissionChecker2) => (body, path = []) => {
1535
+ const model = strapi.getModel(uid2);
1536
+ const canCreate = (path2) => permissionChecker2.can.create(null, path2);
1537
+ return Object.keys(model.attributes).reduce((body2, attributeName) => {
1538
+ const attribute = model.attributes[attributeName];
1539
+ const attributePath = [...path, attributeName].join(".");
1540
+ if (!isVisibleAttribute$2(model, attributeName)) {
1541
+ return body2;
1542
+ }
1543
+ switch (attribute.type) {
1544
+ case "relation": {
1545
+ if (canCreate(attributePath))
1546
+ return body2;
1547
+ return set(attributePath, { set: [] }, body2);
1548
+ }
1549
+ case "component": {
1550
+ return excludeNotCreatableFields(attribute.component, permissionChecker2)(body2, [
1551
+ ...path,
1552
+ attributeName
1553
+ ]);
1554
+ }
1555
+ default: {
1556
+ if (canCreate(attributePath))
1557
+ return body2;
1558
+ return set(attributePath, null, body2);
1559
+ }
1560
+ }
1561
+ }, body);
1562
+ };
1563
+ const singleLocaleSchema = yup$1.string().nullable();
1564
+ const multipleLocaleSchema = yup$1.lazy(
1565
+ (value) => Array.isArray(value) ? yup$1.array().of(singleLocaleSchema.required()) : singleLocaleSchema
1566
+ );
1567
+ const statusSchema = yup$1.mixed().oneOf(["draft", "published"], "Invalid status");
1568
+ const getDocumentLocaleAndStatus = async (request, opts = { allowMultipleLocales: false }) => {
1569
+ const { allowMultipleLocales } = opts;
1570
+ const { locale, status, ...rest } = request || {};
1571
+ const schema = yup$1.object().shape({
1572
+ locale: allowMultipleLocales ? multipleLocaleSchema : singleLocaleSchema,
1573
+ status: statusSchema
1574
+ });
1575
+ try {
1576
+ await validateYupSchema(schema, { strict: true, abortEarly: false })(request);
1577
+ return { locale, status, ...rest };
1578
+ } catch (error) {
1579
+ throw new errors.ValidationError(`Validation error: ${error.message}`);
1580
+ }
1581
+ };
1582
+ const formatDocumentWithMetadata = async (permissionChecker2, uid2, document, opts = {}) => {
1583
+ const documentMetadata2 = getService$1("document-metadata");
1584
+ const serviceOutput = await documentMetadata2.formatDocumentWithMetadata(uid2, document, opts);
1585
+ let {
1586
+ meta: { availableLocales, availableStatus }
1587
+ } = serviceOutput;
1588
+ const metadataSanitizer = permissionChecker2.sanitizeOutput;
1589
+ availableLocales = await async.map(
1590
+ availableLocales,
1591
+ async (localeDocument) => metadataSanitizer(localeDocument)
1592
+ );
1593
+ availableStatus = await async.map(
1594
+ availableStatus,
1595
+ async (statusDocument) => metadataSanitizer(statusDocument)
1596
+ );
1597
+ return {
1598
+ ...serviceOutput,
1599
+ meta: {
1600
+ availableLocales,
1601
+ availableStatus
1602
+ }
1603
+ };
1604
+ };
1605
+ const createDocument = async (ctx, opts) => {
1606
+ const { userAbility, user } = ctx.state;
1607
+ const { model } = ctx.params;
1608
+ const { body } = ctx.request;
1609
+ const documentManager2 = getService$1("document-manager");
1610
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1611
+ if (permissionChecker2.cannot.create()) {
1612
+ throw new errors.ForbiddenError();
1613
+ }
1614
+ const pickPermittedFields = permissionChecker2.sanitizeCreateInput;
1615
+ const setCreator = setCreatorFields({ user });
1616
+ const sanitizeFn = async.pipe(pickPermittedFields, setCreator);
1617
+ const sanitizedBody = await sanitizeFn(body);
1618
+ const { locale, status = "draft" } = await getDocumentLocaleAndStatus(body);
1619
+ return documentManager2.create(model, {
1620
+ data: sanitizedBody,
1621
+ locale,
1622
+ status,
1623
+ populate: opts?.populate
1624
+ });
1625
+ };
1626
+ const updateDocument = async (ctx, opts) => {
1627
+ const { userAbility, user } = ctx.state;
1628
+ const { id, model } = ctx.params;
1629
+ const { body } = ctx.request;
1630
+ const documentManager2 = getService$1("document-manager");
1631
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1632
+ if (permissionChecker2.cannot.update()) {
1633
+ throw new errors.ForbiddenError();
1634
+ }
1635
+ const permissionQuery = await permissionChecker2.sanitizedQuery.update(ctx.query);
1636
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
1637
+ const { locale } = await getDocumentLocaleAndStatus(body);
1638
+ const [documentVersion, documentExists] = await Promise.all([
1639
+ documentManager2.findOne(id, model, { populate, locale, status: "draft" }),
1640
+ documentManager2.exists(model, id)
1641
+ ]);
1642
+ if (!documentExists) {
1643
+ throw new errors.NotFoundError();
1644
+ }
1645
+ if (documentVersion) {
1646
+ if (permissionChecker2.cannot.update(documentVersion)) {
1647
+ throw new errors.ForbiddenError();
1648
+ }
1649
+ } else if (permissionChecker2.cannot.create()) {
1650
+ throw new errors.ForbiddenError();
1651
+ }
1652
+ const pickPermittedFields = documentVersion ? permissionChecker2.sanitizeUpdateInput(documentVersion) : permissionChecker2.sanitizeCreateInput;
1653
+ const setCreator = setCreatorFields({ user, isEdition: true });
1654
+ const sanitizeFn = async.pipe(pickPermittedFields, setCreator);
1655
+ const sanitizedBody = await sanitizeFn(body);
1656
+ return documentManager2.update(documentVersion?.documentId || id, model, {
1657
+ data: sanitizedBody,
1658
+ populate: opts?.populate,
1659
+ locale
1660
+ });
1661
+ };
1662
+ const collectionTypes = {
1663
+ async find(ctx) {
1664
+ const { userAbility } = ctx.state;
1665
+ const { model } = ctx.params;
1666
+ const { query } = ctx.request;
1667
+ const documentMetadata2 = getService$1("document-metadata");
1668
+ const documentManager2 = getService$1("document-manager");
1669
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1670
+ if (permissionChecker2.cannot.read()) {
1671
+ return ctx.forbidden();
1672
+ }
1673
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(query);
1674
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).populateDeep(1).countRelations({ toOne: false, toMany: true }).build();
1675
+ const { locale, status } = await getDocumentLocaleAndStatus(query);
1676
+ const { results: documents, pagination: pagination2 } = await documentManager2.findPage(
1677
+ { ...permissionQuery, populate, locale, status },
1678
+ model
1679
+ );
1680
+ const documentsAvailableStatus = await documentMetadata2.getManyAvailableStatus(
1681
+ model,
1682
+ documents
1683
+ );
1684
+ const setStatus = (document) => {
1685
+ const availableStatuses = documentsAvailableStatus.filter(
1686
+ (d) => d.documentId === document.documentId
1687
+ );
1688
+ document.status = documentMetadata2.getStatus(document, availableStatuses);
1689
+ return document;
1690
+ };
1691
+ const results = await async.map(
1692
+ documents,
1693
+ async.pipe(permissionChecker2.sanitizeOutput, setStatus)
1694
+ );
1695
+ ctx.body = {
1696
+ results,
1697
+ pagination: pagination2
1698
+ };
1699
+ },
1700
+ async findOne(ctx) {
1701
+ const { userAbility } = ctx.state;
1702
+ const { model, id } = ctx.params;
1703
+ const documentManager2 = getService$1("document-manager");
1704
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1705
+ if (permissionChecker2.cannot.read()) {
1706
+ return ctx.forbidden();
1707
+ }
1708
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(ctx.query);
1709
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).populateDeep(Infinity).countRelations().build();
1710
+ const { locale, status = "draft" } = await getDocumentLocaleAndStatus(ctx.query);
1711
+ const version = await documentManager2.findOne(id, model, {
1712
+ populate,
1713
+ locale,
1714
+ status
1715
+ });
1716
+ if (!version) {
1717
+ const exists = await documentManager2.exists(model, id);
1718
+ if (!exists) {
1719
+ return ctx.notFound();
1720
+ }
1721
+ const { meta } = await formatDocumentWithMetadata(
1722
+ permissionChecker2,
1723
+ model,
1724
+ // @ts-expect-error TODO: fix
1725
+ { id, locale, publishedAt: null },
1726
+ { availableLocales: true, availableStatus: false }
1727
+ );
1728
+ ctx.body = { data: {}, meta };
1729
+ return;
1730
+ }
1731
+ if (permissionChecker2.cannot.read(version)) {
1732
+ return ctx.forbidden();
1733
+ }
1734
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(version);
1735
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
1736
+ },
1737
+ async create(ctx) {
1738
+ const { userAbility } = ctx.state;
1739
+ const { model } = ctx.params;
1740
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1741
+ const [totalEntries, document] = await Promise.all([
1742
+ strapi.db.query(model).count(),
1743
+ createDocument(ctx)
1744
+ ]);
1745
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(document);
1746
+ ctx.status = 201;
1747
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument, {
1748
+ // Empty metadata as it's not relevant for a new document
1749
+ availableLocales: false,
1750
+ availableStatus: false
1751
+ });
1752
+ if (totalEntries === 0) {
1753
+ strapi.telemetry.send("didCreateFirstContentTypeEntry", {
1754
+ eventProperties: { model }
1755
+ });
1756
+ }
1757
+ },
1758
+ async update(ctx) {
1759
+ const { userAbility } = ctx.state;
1760
+ const { model } = ctx.params;
1761
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1762
+ const updatedVersion = await updateDocument(ctx);
1763
+ const sanitizedVersion = await permissionChecker2.sanitizeOutput(updatedVersion);
1764
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedVersion);
1765
+ },
1766
+ async clone(ctx) {
1767
+ const { userAbility, user } = ctx.state;
1768
+ const { model, sourceId: id } = ctx.params;
1769
+ const { body } = ctx.request;
1770
+ const documentManager2 = getService$1("document-manager");
1771
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1772
+ if (permissionChecker2.cannot.create()) {
1773
+ return ctx.forbidden();
1774
+ }
1775
+ const permissionQuery = await permissionChecker2.sanitizedQuery.create(ctx.query);
1776
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
1777
+ const { locale } = await getDocumentLocaleAndStatus(body);
1778
+ const document = await documentManager2.findOne(id, model, {
1779
+ populate,
1780
+ locale,
1781
+ status: "draft"
1782
+ });
1783
+ if (!document) {
1784
+ return ctx.notFound();
1785
+ }
1786
+ const pickPermittedFields = permissionChecker2.sanitizeCreateInput;
1787
+ const setCreator = setCreatorFields({ user });
1788
+ const excludeNotCreatable = excludeNotCreatableFields(model, permissionChecker2);
1789
+ const sanitizeFn = async.pipe(pickPermittedFields, setCreator, excludeNotCreatable);
1790
+ const sanitizedBody = await sanitizeFn(body);
1791
+ const clonedDocument = await documentManager2.clone(document.documentId, sanitizedBody, model);
1792
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(clonedDocument);
1793
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument, {
1794
+ // Empty metadata as it's not relevant for a new document
1795
+ availableLocales: false,
1796
+ availableStatus: false
1797
+ });
1798
+ },
1799
+ async autoClone(ctx) {
1800
+ const { model } = ctx.params;
1801
+ const prohibitedFields = getProhibitedCloningFields(model);
1802
+ if (prohibitedFields.length > 0) {
1803
+ return ctx.badRequest(
1804
+ "Entity could not be cloned as it has unique and/or relational fields. Please edit those fields manually and save to complete the cloning.",
1805
+ {
1806
+ prohibitedFields
1807
+ }
1808
+ );
1809
+ }
1810
+ await this.clone(ctx);
1811
+ },
1812
+ async delete(ctx) {
1813
+ const { userAbility } = ctx.state;
1814
+ const { id, model } = ctx.params;
1815
+ const documentManager2 = getService$1("document-manager");
1816
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1817
+ if (permissionChecker2.cannot.delete()) {
1818
+ return ctx.forbidden();
1819
+ }
1820
+ const permissionQuery = await permissionChecker2.sanitizedQuery.delete(ctx.query);
1821
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
1822
+ const { locale } = await getDocumentLocaleAndStatus(ctx.query);
1823
+ const documentLocales = await documentManager2.findLocales(id, model, { populate, locale });
1824
+ if (documentLocales.length === 0) {
1825
+ return ctx.notFound();
1826
+ }
1827
+ for (const document of documentLocales) {
1828
+ if (permissionChecker2.cannot.delete(document)) {
1829
+ return ctx.forbidden();
1830
+ }
1831
+ }
1832
+ const result = await documentManager2.delete(id, model, { locale });
1833
+ ctx.body = await permissionChecker2.sanitizeOutput(result);
1834
+ },
1835
+ /**
1836
+ * Publish a document version.
1837
+ * Supports creating/saving a document and publishing it in one request.
1838
+ */
1839
+ async publish(ctx) {
1840
+ const { userAbility } = ctx.state;
1841
+ const { id, model } = ctx.params;
1842
+ const { body } = ctx.request;
1843
+ const documentManager2 = getService$1("document-manager");
1844
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1845
+ if (permissionChecker2.cannot.publish()) {
1846
+ return ctx.forbidden();
1847
+ }
1848
+ const publishedDocument = await strapi.db.transaction(async () => {
1849
+ const permissionQuery = await permissionChecker2.sanitizedQuery.publish(ctx.query);
1850
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).populateDeep(Infinity).countRelations().build();
1851
+ const document = id ? await updateDocument(ctx, { populate }) : await createDocument(ctx, { populate });
1852
+ if (permissionChecker2.cannot.publish(document)) {
1853
+ throw new errors.ForbiddenError();
1854
+ }
1855
+ const { locale } = await getDocumentLocaleAndStatus(body);
1856
+ const publishResult = await documentManager2.publish(document.documentId, model, {
1857
+ locale
1858
+ // TODO: Allow setting creator fields on publish
1859
+ // data: setCreatorFields({ user, isEdition: true })({}),
1860
+ });
1861
+ if (!publishResult || publishResult.length === 0) {
1862
+ throw new errors.NotFoundError("Document not found or already published.");
1863
+ }
1864
+ return publishResult[0];
1865
+ });
1866
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(publishedDocument);
1867
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
1868
+ },
1869
+ async bulkPublish(ctx) {
1870
+ const { userAbility } = ctx.state;
1871
+ const { model } = ctx.params;
1872
+ const { body } = ctx.request;
1873
+ const { documentIds } = body;
1874
+ await validateBulkActionInput(body);
1875
+ const documentManager2 = getService$1("document-manager");
1876
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1877
+ if (permissionChecker2.cannot.publish()) {
1878
+ return ctx.forbidden();
1879
+ }
1880
+ const permissionQuery = await permissionChecker2.sanitizedQuery.publish(ctx.query);
1881
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).populateDeep(Infinity).countRelations().build();
1882
+ const { locale } = await getDocumentLocaleAndStatus(body, { allowMultipleLocales: true });
1883
+ const entityPromises = documentIds.map(
1884
+ (documentId) => documentManager2.findLocales(documentId, model, { populate, locale, isPublished: false })
1885
+ );
1886
+ const entities = (await Promise.all(entityPromises)).flat();
1887
+ for (const entity of entities) {
1888
+ if (!entity) {
1889
+ return ctx.notFound();
1890
+ }
1891
+ if (permissionChecker2.cannot.publish(entity)) {
1892
+ return ctx.forbidden();
1893
+ }
1894
+ }
1895
+ const count = await documentManager2.publishMany(model, documentIds, locale);
1896
+ ctx.body = { count };
1897
+ },
1898
+ async bulkUnpublish(ctx) {
1899
+ const { userAbility } = ctx.state;
1900
+ const { model } = ctx.params;
1901
+ const { body } = ctx.request;
1902
+ const { documentIds } = body;
1903
+ await validateBulkActionInput(body);
1904
+ const documentManager2 = getService$1("document-manager");
1905
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1906
+ if (permissionChecker2.cannot.unpublish()) {
1907
+ return ctx.forbidden();
1908
+ }
1909
+ const { locale } = await getDocumentLocaleAndStatus(body);
1910
+ const entityPromises = documentIds.map(
1911
+ (documentId) => documentManager2.findLocales(documentId, model, { locale, isPublished: true })
1912
+ );
1913
+ const entities = (await Promise.all(entityPromises)).flat();
1914
+ for (const entity of entities) {
1915
+ if (!entity) {
1916
+ return ctx.notFound();
1917
+ }
1918
+ if (permissionChecker2.cannot.publish(entity)) {
1919
+ return ctx.forbidden();
1920
+ }
1921
+ }
1922
+ const entitiesIds = entities.map((document) => document.documentId);
1923
+ const { count } = await documentManager2.unpublishMany(entitiesIds, model, { locale });
1924
+ ctx.body = { count };
1925
+ },
1926
+ async unpublish(ctx) {
1927
+ const { userAbility } = ctx.state;
1928
+ const { id, model } = ctx.params;
1929
+ const {
1930
+ body: { discardDraft, ...body }
1931
+ } = ctx.request;
1932
+ const documentManager2 = getService$1("document-manager");
1933
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1934
+ if (permissionChecker2.cannot.unpublish()) {
1935
+ return ctx.forbidden();
1936
+ }
1937
+ if (discardDraft && permissionChecker2.cannot.discard()) {
1938
+ return ctx.forbidden();
1939
+ }
1940
+ const permissionQuery = await permissionChecker2.sanitizedQuery.unpublish(ctx.query);
1941
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
1942
+ const { locale } = await getDocumentLocaleAndStatus(body);
1943
+ const document = await documentManager2.findOne(id, model, {
1944
+ populate,
1945
+ locale,
1946
+ status: "published"
1947
+ });
1948
+ if (!document) {
1949
+ throw new errors.NotFoundError();
1950
+ }
1951
+ if (permissionChecker2.cannot.unpublish(document)) {
1952
+ throw new errors.ForbiddenError();
1953
+ }
1954
+ if (discardDraft && permissionChecker2.cannot.discard(document)) {
1955
+ throw new errors.ForbiddenError();
1956
+ }
1957
+ await strapi.db.transaction(async () => {
1958
+ if (discardDraft) {
1959
+ await documentManager2.discardDraft(document.documentId, model, { locale });
1960
+ }
1961
+ ctx.body = await async.pipe(
1962
+ (document2) => documentManager2.unpublish(document2.documentId, model, { locale }),
1963
+ permissionChecker2.sanitizeOutput,
1964
+ (document2) => formatDocumentWithMetadata(permissionChecker2, model, document2)
1965
+ )(document);
1966
+ });
1967
+ },
1968
+ async discard(ctx) {
1969
+ const { userAbility } = ctx.state;
1970
+ const { id, model } = ctx.params;
1971
+ const { body } = ctx.request;
1972
+ const documentManager2 = getService$1("document-manager");
1973
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1974
+ if (permissionChecker2.cannot.discard()) {
1975
+ return ctx.forbidden();
1976
+ }
1977
+ const permissionQuery = await permissionChecker2.sanitizedQuery.discard(ctx.query);
1978
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
1979
+ const { locale } = await getDocumentLocaleAndStatus(body);
1980
+ const document = await documentManager2.findOne(id, model, {
1981
+ populate,
1982
+ locale,
1983
+ status: "published"
1984
+ });
1985
+ if (!document) {
1986
+ return ctx.notFound();
1987
+ }
1988
+ if (permissionChecker2.cannot.discard(document)) {
1989
+ return ctx.forbidden();
1990
+ }
1991
+ ctx.body = await async.pipe(
1992
+ (document2) => documentManager2.discardDraft(document2.documentId, model, { locale }),
1993
+ permissionChecker2.sanitizeOutput,
1994
+ (document2) => formatDocumentWithMetadata(permissionChecker2, model, document2)
1995
+ )(document);
1996
+ },
1997
+ async bulkDelete(ctx) {
1998
+ const { userAbility } = ctx.state;
1999
+ const { model } = ctx.params;
2000
+ const { query, body } = ctx.request;
2001
+ const { documentIds } = body;
2002
+ await validateBulkActionInput(body);
2003
+ const documentManager2 = getService$1("document-manager");
2004
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2005
+ if (permissionChecker2.cannot.delete()) {
2006
+ return ctx.forbidden();
2007
+ }
2008
+ const permissionQuery = await permissionChecker2.sanitizedQuery.delete(query);
2009
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
2010
+ const { locale } = await getDocumentLocaleAndStatus(body);
2011
+ const documentLocales = await documentManager2.findLocales(documentIds, model, {
2012
+ populate,
2013
+ locale
2014
+ });
2015
+ if (documentLocales.length === 0) {
2016
+ return ctx.notFound();
2017
+ }
2018
+ for (const document of documentLocales) {
2019
+ if (permissionChecker2.cannot.delete(document)) {
2020
+ return ctx.forbidden();
2021
+ }
2022
+ }
2023
+ const localeDocumentsIds = documentLocales.map((document) => document.documentId);
2024
+ const { count } = await documentManager2.deleteMany(localeDocumentsIds, model, { locale });
2025
+ ctx.body = { count };
2026
+ },
2027
+ async countDraftRelations(ctx) {
2028
+ const { userAbility } = ctx.state;
2029
+ const { model, id } = ctx.params;
2030
+ const documentManager2 = getService$1("document-manager");
2031
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2032
+ if (permissionChecker2.cannot.read()) {
2033
+ return ctx.forbidden();
2034
+ }
2035
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(ctx.query);
2036
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
2037
+ const { locale, status = "draft" } = await getDocumentLocaleAndStatus(ctx.query);
2038
+ const entity = await documentManager2.findOne(id, model, { populate, locale, status });
2039
+ if (!entity) {
2040
+ return ctx.notFound();
2041
+ }
2042
+ if (permissionChecker2.cannot.read(entity)) {
2043
+ return ctx.forbidden();
2044
+ }
2045
+ const number = await documentManager2.countDraftRelations(id, model, locale);
2046
+ return {
2047
+ data: number
2048
+ };
2049
+ },
2050
+ async countManyEntriesDraftRelations(ctx) {
2051
+ const { userAbility } = ctx.state;
2052
+ const ids = ctx.request.query.documentIds;
2053
+ const locale = ctx.request.query.locale;
2054
+ const { model } = ctx.params;
2055
+ const documentManager2 = getService$1("document-manager");
2056
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2057
+ if (permissionChecker2.cannot.read()) {
2058
+ return ctx.forbidden();
2059
+ }
2060
+ const entities = await documentManager2.findMany(
2061
+ {
2062
+ filters: {
2063
+ documentId: ids
2064
+ },
2065
+ locale
2066
+ },
2067
+ model
2068
+ );
2069
+ if (!entities) {
2070
+ return ctx.notFound();
2071
+ }
2072
+ const number = await documentManager2.countManyEntriesDraftRelations(ids, model, locale);
2073
+ return {
2074
+ data: number
2075
+ };
2076
+ }
2077
+ };
2078
+ const components$1 = {
2079
+ findComponents(ctx) {
2080
+ const components2 = getService$1("components").findAllComponents();
2081
+ const { toDto } = getService$1("data-mapper");
2082
+ ctx.body = { data: components2.map(toDto) };
2083
+ },
2084
+ async findComponentConfiguration(ctx) {
2085
+ const { uid: uid2 } = ctx.params;
2086
+ const componentService = getService$1("components");
2087
+ const component = componentService.findComponent(uid2);
2088
+ if (!component) {
2089
+ return ctx.notFound("component.notFound");
2090
+ }
2091
+ const configuration = await componentService.findConfiguration(component);
2092
+ const componentsConfigurations = await componentService.findComponentsConfigurations(component);
2093
+ ctx.body = {
2094
+ data: {
2095
+ component: configuration,
2096
+ components: componentsConfigurations
2097
+ }
2098
+ };
2099
+ },
2100
+ async updateComponentConfiguration(ctx) {
2101
+ const { uid: uid2 } = ctx.params;
2102
+ const { body } = ctx.request;
2103
+ const componentService = getService$1("components");
2104
+ const component = componentService.findComponent(uid2);
2105
+ if (!component) {
2106
+ return ctx.notFound("component.notFound");
2107
+ }
2108
+ let input;
2109
+ try {
2110
+ input = await createModelConfigurationSchema(component).validate(body, {
2111
+ abortEarly: false,
2112
+ stripUnknown: true,
2113
+ strict: true
2114
+ });
2115
+ } catch (error) {
2116
+ return ctx.badRequest(null, {
2117
+ name: "validationError",
2118
+ errors: error.errors
2119
+ });
2120
+ }
2121
+ const newConfiguration = await componentService.updateConfiguration(component, input);
2122
+ ctx.body = { data: newConfiguration };
2123
+ }
2124
+ };
2125
+ const hasEditMainField = has("edit.mainField");
2126
+ const getEditMainField = prop("edit.mainField");
2127
+ const assocListMainField = assoc("list.mainField");
2128
+ const assocMainField = (metadata) => hasEditMainField(metadata) ? assocListMainField(getEditMainField(metadata), metadata) : metadata;
2129
+ const contentTypes = {
2130
+ async findContentTypes(ctx) {
2131
+ const { kind } = ctx.query;
2132
+ try {
2133
+ await validateKind(kind);
2134
+ } catch (error) {
2135
+ return ctx.send({ error }, 400);
2136
+ }
2137
+ const contentTypes2 = getService$1("content-types").findContentTypesByKind(kind);
2138
+ const { toDto } = getService$1("data-mapper");
2139
+ ctx.body = { data: contentTypes2.map(toDto) };
2140
+ },
2141
+ async findContentTypesSettings(ctx) {
2142
+ const { findAllContentTypes, findConfiguration } = getService$1("content-types");
2143
+ const contentTypes2 = await findAllContentTypes();
2144
+ const configurations = await Promise.all(
2145
+ contentTypes2.map(async (contentType) => {
2146
+ const { uid: uid2, settings } = await findConfiguration(contentType);
2147
+ return { uid: uid2, settings };
2148
+ })
2149
+ );
2150
+ ctx.body = {
2151
+ data: configurations
2152
+ };
2153
+ },
2154
+ async findContentTypeConfiguration(ctx) {
2155
+ const { uid: uid2 } = ctx.params;
2156
+ const contentTypeService = getService$1("content-types");
2157
+ const contentType = await contentTypeService.findContentType(uid2);
2158
+ if (!contentType) {
2159
+ return ctx.notFound("contentType.notFound");
2160
+ }
2161
+ const configuration = await contentTypeService.findConfiguration(contentType);
2162
+ const confWithUpdatedMetadata = {
2163
+ ...configuration,
2164
+ metadatas: mapValues(assocMainField, configuration.metadatas)
2165
+ };
2166
+ const components2 = await contentTypeService.findComponentsConfigurations(contentType);
2167
+ ctx.body = {
2168
+ data: {
2169
+ contentType: confWithUpdatedMetadata,
2170
+ components: components2
2171
+ }
2172
+ };
2173
+ },
2174
+ async updateContentTypeConfiguration(ctx) {
2175
+ const { userAbility } = ctx.state;
2176
+ const { uid: uid2 } = ctx.params;
2177
+ const { body } = ctx.request;
2178
+ const contentTypeService = getService$1("content-types");
2179
+ const metricsService = getService$1("metrics");
2180
+ const contentType = await contentTypeService.findContentType(uid2);
2181
+ if (!contentType) {
2182
+ return ctx.notFound("contentType.notFound");
2183
+ }
2184
+ if (!getService$1("permission").canConfigureContentType({ userAbility, contentType })) {
2185
+ return ctx.forbidden();
2186
+ }
2187
+ let input;
2188
+ try {
2189
+ input = await createModelConfigurationSchema(contentType).validate(body, {
2190
+ abortEarly: false,
2191
+ stripUnknown: true,
2192
+ strict: true
2193
+ });
2194
+ } catch (error) {
2195
+ return ctx.badRequest(null, {
2196
+ name: "validationError",
2197
+ errors: error.errors
2198
+ });
2199
+ }
2200
+ const newConfiguration = await contentTypeService.updateConfiguration(contentType, input);
2201
+ await metricsService.sendDidConfigureListView(contentType, newConfiguration);
2202
+ const confWithUpdatedMetadata = {
2203
+ ...newConfiguration,
2204
+ metadatas: mapValues(assocMainField, newConfiguration.metadatas)
2205
+ };
2206
+ const components2 = await contentTypeService.findComponentsConfigurations(contentType);
2207
+ ctx.body = {
2208
+ data: {
2209
+ contentType: confWithUpdatedMetadata,
2210
+ components: components2
2211
+ }
2212
+ };
2213
+ }
2214
+ };
2215
+ const init = {
2216
+ getInitData(ctx) {
2217
+ const { toDto } = getService$1("data-mapper");
2218
+ const { findAllComponents } = getService$1("components");
2219
+ const { getAllFieldSizes } = getService$1("field-sizes");
2220
+ const { findAllContentTypes } = getService$1("content-types");
2221
+ ctx.body = {
2222
+ data: {
2223
+ fieldSizes: getAllFieldSizes(),
2224
+ components: findAllComponents().map(toDto),
2225
+ contentTypes: findAllContentTypes().map(toDto)
2226
+ }
2227
+ };
2228
+ }
2229
+ };
2230
+ const validateFindAvailableSchema = yup$1.object().shape({
2231
+ component: yup$1.string(),
2232
+ id: yup$1.strapiID(),
2233
+ _q: yup$1.string(),
2234
+ idsToOmit: yup$1.array().of(yup$1.strapiID()),
2235
+ idsToInclude: yup$1.array().of(yup$1.strapiID()),
2236
+ page: yup$1.number().integer().min(1),
2237
+ pageSize: yup$1.number().integer().min(1).max(100),
2238
+ locale: yup$1.string().nullable(),
2239
+ status: yup$1.string().oneOf(["published", "draft"]).nullable()
2240
+ }).required();
2241
+ const validateFindExistingSchema = yup$1.object().shape({
2242
+ page: yup$1.number().integer().min(1),
2243
+ pageSize: yup$1.number().integer().min(1).max(100),
2244
+ locale: yup$1.string().nullable(),
2245
+ status: yup$1.string().oneOf(["published", "draft"]).nullable()
2246
+ }).required();
2247
+ const validateFindAvailable = validateYupSchema(validateFindAvailableSchema, { strict: false });
2248
+ const validateFindExisting = validateYupSchema(validateFindExistingSchema, { strict: false });
2249
+ const { PUBLISHED_AT_ATTRIBUTE: PUBLISHED_AT_ATTRIBUTE$2, UPDATED_AT_ATTRIBUTE } = contentTypes$1.constants;
2250
+ const addFiltersClause = (params, filtersClause) => {
2251
+ params.filters = params.filters || {};
2252
+ params.filters.$and = params.filters.$and || [];
2253
+ params.filters.$and.push(filtersClause);
2254
+ };
2255
+ const sanitizeMainField = (model, mainField, userAbility) => {
2256
+ const permissionChecker2 = getService$1("permission-checker").create({
2257
+ userAbility,
2258
+ model: model.uid
2259
+ });
2260
+ if (!isListable(model, mainField)) {
2261
+ return "id";
2262
+ }
2263
+ if (permissionChecker2.cannot.read(null, mainField)) {
2264
+ if (model.uid === "plugin::users-permissions.role") {
2265
+ const userPermissionChecker = getService$1("permission-checker").create({
2266
+ userAbility,
2267
+ model: "plugin::users-permissions.user"
2268
+ });
2269
+ if (userPermissionChecker.can.read()) {
2270
+ return "name";
2271
+ }
2272
+ }
2273
+ return "id";
2274
+ }
2275
+ return mainField;
2276
+ };
2277
+ const addStatusToRelations = async (uid2, relations2) => {
2278
+ if (!contentTypes$1.hasDraftAndPublish(strapi.contentTypes[uid2])) {
2279
+ return relations2;
2280
+ }
2281
+ const documentMetadata2 = getService$1("document-metadata");
2282
+ const documentsAvailableStatus = await documentMetadata2.getManyAvailableStatus(uid2, relations2);
2283
+ return relations2.map((relation) => {
2284
+ const availableStatuses = documentsAvailableStatus.filter(
2285
+ (availableDocument) => availableDocument.documentId === relation.documentId
2286
+ );
2287
+ return {
2288
+ ...relation,
2289
+ status: documentMetadata2.getStatus(relation, availableStatuses)
2290
+ };
2291
+ });
2292
+ };
2293
+ const getPublishedAtClause = (status, uid2) => {
2294
+ const model = strapi.getModel(uid2);
2295
+ if (!model || !contentTypes$1.hasDraftAndPublish(model)) {
2296
+ return {};
2297
+ }
2298
+ return status === "published" ? { $notNull: true } : { $null: true };
2299
+ };
2300
+ const validateLocale = (sourceUid, targetUid, locale) => {
2301
+ const sourceModel = strapi.getModel(sourceUid);
2302
+ const targetModel = strapi.getModel(targetUid);
2303
+ const isLocalized = strapi.plugin("i18n").service("content-types").isLocalizedContentType;
2304
+ const isSourceLocalized = isLocalized(sourceModel);
2305
+ const isTargetLocalized = isLocalized(targetModel);
2306
+ let validatedLocale = locale;
2307
+ if (!targetModel || !isTargetLocalized)
2308
+ validatedLocale = void 0;
2309
+ return {
2310
+ locale: validatedLocale,
2311
+ isSourceLocalized,
2312
+ isTargetLocalized
2313
+ };
2314
+ };
2315
+ const validateStatus = (sourceUid, status) => {
2316
+ const sourceModel = strapi.getModel(sourceUid);
2317
+ const isDP = contentTypes$1.hasDraftAndPublish;
2318
+ const isSourceDP = isDP(sourceModel);
2319
+ if (!isSourceDP)
2320
+ return { status: void 0 };
2321
+ switch (status) {
2322
+ case "published":
2323
+ return { status: "published" };
2324
+ default:
2325
+ return { status: "draft" };
2326
+ }
2327
+ };
2328
+ const relations = {
2329
+ async extractAndValidateRequestInfo(ctx, id) {
2330
+ const { userAbility } = ctx.state;
2331
+ const { model, targetField } = ctx.params;
2332
+ const sourceSchema = strapi.getModel(model);
2333
+ if (!sourceSchema) {
2334
+ throw new errors.ValidationError(`The model ${model} doesn't exist`);
2335
+ }
2336
+ const attribute = sourceSchema.attributes[targetField];
2337
+ if (!attribute || attribute.type !== "relation") {
2338
+ throw new errors.ValidationError(
2339
+ `The relational field ${targetField} doesn't exist on ${model}`
2340
+ );
2341
+ }
2342
+ const sourceUid = model;
2343
+ const targetUid = attribute.target;
2344
+ const { locale, isSourceLocalized, isTargetLocalized } = validateLocale(
2345
+ sourceUid,
2346
+ targetUid,
2347
+ ctx.request?.query?.locale
2348
+ );
2349
+ const { status } = validateStatus(sourceUid, ctx.request?.query?.status);
2350
+ const permissionChecker2 = getService$1("permission-checker").create({
2351
+ userAbility,
2352
+ model
2353
+ });
2354
+ const isComponent2 = sourceSchema.modelType === "component";
2355
+ if (!isComponent2) {
2356
+ if (permissionChecker2.cannot.read(null, targetField)) {
2357
+ return ctx.forbidden();
2358
+ }
2359
+ }
2360
+ let entryId = null;
2361
+ if (id) {
2362
+ const where = {};
2363
+ if (!isComponent2) {
2364
+ where.documentId = id;
2365
+ if (status) {
2366
+ where.publishedAt = getPublishedAtClause(status, sourceUid);
2367
+ }
2368
+ if (locale && isSourceLocalized) {
2369
+ where.locale = locale;
2370
+ }
2371
+ } else {
2372
+ where.id = id;
2373
+ }
2374
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(ctx.query);
2375
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
2376
+ const currentEntity = await strapi.db.query(model).findOne({
2377
+ where,
2378
+ populate
2379
+ });
2380
+ if (!currentEntity) {
2381
+ throw new errors.NotFoundError();
2382
+ }
2383
+ if (!isComponent2) {
2384
+ if (permissionChecker2.cannot.read(currentEntity, targetField)) {
2385
+ throw new errors.ForbiddenError();
2386
+ }
2387
+ }
2388
+ entryId = currentEntity.id;
2389
+ }
2390
+ const modelConfig = isComponent2 ? await getService$1("components").findConfiguration(sourceSchema) : await getService$1("content-types").findConfiguration(sourceSchema);
2391
+ const targetSchema = strapi.getModel(targetUid);
2392
+ const mainField = flow(
2393
+ prop(`metadatas.${targetField}.edit.mainField`),
2394
+ (mainField2) => mainField2 || "id",
2395
+ (mainField2) => sanitizeMainField(targetSchema, mainField2, userAbility)
2396
+ )(modelConfig);
2397
+ const fieldsToSelect = uniq([
2398
+ mainField,
2399
+ PUBLISHED_AT_ATTRIBUTE$2,
2400
+ UPDATED_AT_ATTRIBUTE,
2401
+ "documentId"
2402
+ ]);
2403
+ if (isTargetLocalized) {
2404
+ fieldsToSelect.push("locale");
2405
+ }
2406
+ return {
2407
+ entryId,
2408
+ locale,
2409
+ status,
2410
+ attribute,
2411
+ fieldsToSelect,
2412
+ mainField,
2413
+ source: { schema: sourceSchema },
2414
+ target: { schema: targetSchema, isLocalized: isTargetLocalized },
2415
+ sourceSchema,
2416
+ targetSchema,
2417
+ targetField
2418
+ };
2419
+ },
2420
+ /**
2421
+ * Used to find new relations to add in a relational field.
2422
+ *
2423
+ * Component and document relations are dealt a bit differently (they don't have a document_id).
2424
+ */
2425
+ async findAvailable(ctx) {
2426
+ const { id } = ctx.request.query;
2427
+ await validateFindAvailable(ctx.request.query);
2428
+ const {
2429
+ locale,
2430
+ status,
2431
+ targetField,
2432
+ fieldsToSelect,
2433
+ mainField,
2434
+ source: {
2435
+ schema: { uid: sourceUid, modelType: sourceModelType }
2436
+ },
2437
+ target: {
2438
+ schema: { uid: targetUid },
2439
+ isLocalized: isTargetLocalized
2440
+ }
2441
+ } = await this.extractAndValidateRequestInfo(ctx, id);
2442
+ const { idsToOmit, idsToInclude, _q, ...query } = ctx.request.query;
2443
+ const permissionChecker2 = getService$1("permission-checker").create({
2444
+ userAbility: ctx.state.userAbility,
2445
+ model: targetUid
2446
+ });
2447
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(query);
2448
+ const queryParams = {
2449
+ sort: mainField,
2450
+ // cannot select other fields as the user may not have the permissions
2451
+ fields: fieldsToSelect,
2452
+ ...permissionQuery
2453
+ };
2454
+ addFiltersClause(queryParams, {
2455
+ publishedAt: getPublishedAtClause(status, targetUid)
2456
+ });
2457
+ const filterByLocale = isTargetLocalized && locale;
2458
+ if (filterByLocale) {
2459
+ addFiltersClause(queryParams, { locale });
2460
+ }
2461
+ if (id) {
2462
+ const subQuery = strapi.db.queryBuilder(sourceUid);
2463
+ const alias = subQuery.getAlias();
2464
+ const where = {
2465
+ [`${alias}.id`]: { $notNull: true },
2466
+ [`${alias}.document_id`]: { $notNull: true }
2467
+ };
2468
+ if (sourceModelType === "contentType") {
2469
+ where.document_id = id;
2470
+ } else {
2471
+ where.id = id;
2472
+ }
2473
+ if (status) {
2474
+ where[`${alias}.published_at`] = getPublishedAtClause(status, targetUid);
2475
+ }
2476
+ if (filterByLocale) {
2477
+ where[`${alias}.locale`] = locale;
2478
+ }
2479
+ if ((idsToInclude?.length ?? 0) !== 0) {
2480
+ where[`${alias}.id`].$notIn = idsToInclude;
2481
+ }
2482
+ const knexSubQuery = subQuery.where(where).join({ alias, targetField }).select(`${alias}.id`).getKnexQuery();
2483
+ addFiltersClause(queryParams, {
2484
+ id: { $notIn: knexSubQuery }
2485
+ });
2486
+ }
2487
+ if (_q) {
2488
+ const _filter = isOperatorOfType("where", query._filter) ? query._filter : "$containsi";
2489
+ addFiltersClause(queryParams, { [mainField]: { [_filter]: _q } });
2490
+ }
2491
+ if (idsToOmit?.length > 0) {
2492
+ addFiltersClause(queryParams, {
2493
+ id: { $notIn: uniq(idsToOmit) }
2494
+ });
2495
+ }
2496
+ const res = await strapi.db.query(targetUid).findPage(strapi.get("query-params").transform(targetUid, queryParams));
2497
+ ctx.body = {
2498
+ ...res,
2499
+ results: await addStatusToRelations(targetUid, res.results)
2500
+ };
2501
+ },
2502
+ async findExisting(ctx) {
2503
+ const { userAbility } = ctx.state;
2504
+ const { id } = ctx.params;
2505
+ await validateFindExisting(ctx.request.query);
2506
+ const {
2507
+ entryId,
2508
+ attribute,
2509
+ targetField,
2510
+ fieldsToSelect,
2511
+ source: {
2512
+ schema: { uid: sourceUid }
2513
+ },
2514
+ target: {
2515
+ schema: { uid: targetUid }
2516
+ }
2517
+ } = await this.extractAndValidateRequestInfo(ctx, id);
2518
+ const permissionQuery = await getService$1("permission-checker").create({ userAbility, model: targetUid }).sanitizedQuery.read({ fields: fieldsToSelect });
2519
+ const dbQuery = strapi.db.query(sourceUid);
2520
+ const loadRelations = relations$1.isAnyToMany(attribute) ? (...args) => dbQuery.loadPages(...args) : (...args) => dbQuery.load(...args).then((res2) => ({ results: res2 ? [res2] : [] }));
2521
+ const res = await loadRelations({ id: entryId }, targetField, {
2522
+ select: ["id", "documentId", "locale", "publishedAt"],
2523
+ ordering: "desc",
2524
+ page: ctx.request.query.page,
2525
+ pageSize: ctx.request.query.pageSize
2526
+ });
2527
+ const loadedIds = res.results.map((item) => item.id);
2528
+ addFiltersClause(permissionQuery, { id: { $in: loadedIds } });
2529
+ const sanitizedRes = await loadRelations({ id: entryId }, targetField, {
2530
+ ...strapi.get("query-params").transform(targetUid, permissionQuery),
2531
+ ordering: "desc",
2532
+ page: ctx.request.query.page,
2533
+ pageSize: ctx.request.query.pageSize
2534
+ });
2535
+ const relationsUnion = uniqBy("id", concat(sanitizedRes.results, res.results));
2536
+ ctx.body = {
2537
+ pagination: res.pagination || {
2538
+ page: 1,
2539
+ pageCount: 1,
2540
+ pageSize: 10,
2541
+ total: relationsUnion.length
2542
+ },
2543
+ results: await addStatusToRelations(targetUid, relationsUnion)
2544
+ };
2545
+ }
2546
+ };
2547
+ const buildPopulateFromQuery = async (query, model) => {
2548
+ return getService$1("populate-builder")(model).populateFromQuery(query).populateDeep(Infinity).countRelations().build();
2549
+ };
2550
+ const findDocument = async (query, uid2, opts = {}) => {
2551
+ const documentManager2 = getService$1("document-manager");
2552
+ const populate = await buildPopulateFromQuery(query, uid2);
2553
+ return documentManager2.findMany({ ...opts, populate }, uid2).then((documents) => documents[0]);
2554
+ };
2555
+ const createOrUpdateDocument = async (ctx, opts) => {
2556
+ const { user, userAbility } = ctx.state;
2557
+ const { model } = ctx.params;
2558
+ const { body, query } = ctx.request;
2559
+ const documentManager2 = getService$1("document-manager");
2560
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2561
+ if (permissionChecker2.cannot.create() && permissionChecker2.cannot.update()) {
2562
+ throw new errors.ForbiddenError();
2563
+ }
2564
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.update(query);
2565
+ const { locale } = await getDocumentLocaleAndStatus(body);
2566
+ const [documentVersion, otherDocumentVersion] = await Promise.all([
2567
+ findDocument(sanitizedQuery, model, { locale, status: "draft" }),
2568
+ // Find the first document to check if it exists
2569
+ strapi.db.query(model).findOne({ select: ["documentId"] })
2570
+ ]);
2571
+ const documentId = otherDocumentVersion?.documentId;
2572
+ const pickPermittedFields = documentVersion ? permissionChecker2.sanitizeUpdateInput(documentVersion) : permissionChecker2.sanitizeCreateInput;
2573
+ const setCreator = documentVersion ? setCreatorFields({ user, isEdition: true }) : setCreatorFields({ user });
2574
+ const sanitizeFn = async.pipe(pickPermittedFields, setCreator);
2575
+ if (documentVersion) {
2576
+ if (permissionChecker2.cannot.update(documentVersion)) {
2577
+ throw new errors.ForbiddenError();
2578
+ }
2579
+ } else if (permissionChecker2.cannot.create()) {
2580
+ throw new errors.ForbiddenError();
2581
+ }
2582
+ const sanitizedBody = await sanitizeFn(body);
2583
+ if (!documentId) {
2584
+ return documentManager2.create(model, {
2585
+ data: sanitizedBody,
2586
+ ...sanitizedQuery,
2587
+ locale
2588
+ });
2589
+ }
2590
+ return documentManager2.update(documentId, model, {
2591
+ data: sanitizedBody,
2592
+ populate: opts?.populate,
2593
+ locale
2594
+ });
2595
+ };
2596
+ const singleTypes = {
2597
+ async find(ctx) {
2598
+ const { userAbility } = ctx.state;
2599
+ const { model } = ctx.params;
2600
+ const { query = {} } = ctx.request;
2601
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2602
+ if (permissionChecker2.cannot.read()) {
2603
+ return ctx.forbidden();
2604
+ }
2605
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(query);
2606
+ const { locale, status } = await getDocumentLocaleAndStatus(query);
2607
+ const version = await findDocument(permissionQuery, model, { locale, status });
2608
+ if (!version) {
2609
+ if (permissionChecker2.cannot.create()) {
2610
+ return ctx.forbidden();
2611
+ }
2612
+ const document = await strapi.db.query(model).findOne({});
2613
+ if (!document) {
2614
+ return ctx.notFound();
2615
+ }
2616
+ const { meta } = await formatDocumentWithMetadata(
2617
+ permissionChecker2,
2618
+ model,
2619
+ // @ts-expect-error - fix types
2620
+ { id: document.documentId, locale, publishedAt: null },
2621
+ { availableLocales: true, availableStatus: false }
2622
+ );
2623
+ ctx.body = { data: {}, meta };
2624
+ return;
2625
+ }
2626
+ if (permissionChecker2.cannot.read(version)) {
2627
+ return ctx.forbidden();
2628
+ }
2629
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(version);
2630
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
2631
+ },
2632
+ async createOrUpdate(ctx) {
2633
+ const { userAbility } = ctx.state;
2634
+ const { model } = ctx.params;
2635
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2636
+ const document = await createOrUpdateDocument(ctx);
2637
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(document);
2638
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
2639
+ },
2640
+ async delete(ctx) {
2641
+ const { userAbility } = ctx.state;
2642
+ const { model } = ctx.params;
2643
+ const { query = {} } = ctx.request;
2644
+ const documentManager2 = getService$1("document-manager");
2645
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2646
+ if (permissionChecker2.cannot.delete()) {
2647
+ return ctx.forbidden();
2648
+ }
2649
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.delete(query);
2650
+ const populate = await buildPopulateFromQuery(sanitizedQuery, model);
2651
+ const { locale } = await getDocumentLocaleAndStatus(query);
2652
+ const documentLocales = await documentManager2.findLocales(void 0, model, {
2653
+ populate,
2654
+ locale
2655
+ });
2656
+ if (documentLocales.length === 0) {
2657
+ return ctx.notFound();
2658
+ }
2659
+ for (const document of documentLocales) {
2660
+ if (permissionChecker2.cannot.delete(document)) {
2661
+ return ctx.forbidden();
2662
+ }
2663
+ }
2664
+ const deletedEntity = await documentManager2.delete(documentLocales.at(0).documentId, model, {
2665
+ locale
2666
+ });
2667
+ ctx.body = await permissionChecker2.sanitizeOutput(deletedEntity);
2668
+ },
2669
+ async publish(ctx) {
2670
+ const { userAbility } = ctx.state;
2671
+ const { model } = ctx.params;
2672
+ const { query = {} } = ctx.request;
2673
+ const documentManager2 = getService$1("document-manager");
2674
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2675
+ if (permissionChecker2.cannot.publish()) {
2676
+ return ctx.forbidden();
2677
+ }
2678
+ const publishedDocument = await strapi.db.transaction(async () => {
2679
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.publish(query);
2680
+ const populate = await buildPopulateFromQuery(sanitizedQuery, model);
2681
+ const document = await createOrUpdateDocument(ctx, { populate });
2682
+ if (!document) {
2683
+ throw new errors.NotFoundError();
2684
+ }
2685
+ if (permissionChecker2.cannot.publish(document)) {
2686
+ throw new errors.ForbiddenError();
2687
+ }
2688
+ const { locale } = await getDocumentLocaleAndStatus(document);
2689
+ const publishResult = await documentManager2.publish(document.documentId, model, { locale });
2690
+ return publishResult.at(0);
2691
+ });
2692
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(publishedDocument);
2693
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
2694
+ },
2695
+ async unpublish(ctx) {
2696
+ const { userAbility } = ctx.state;
2697
+ const { model } = ctx.params;
2698
+ const {
2699
+ body: { discardDraft, ...body },
2700
+ query = {}
2701
+ } = ctx.request;
2702
+ const documentManager2 = getService$1("document-manager");
2703
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2704
+ if (permissionChecker2.cannot.unpublish()) {
2705
+ return ctx.forbidden();
2706
+ }
2707
+ if (discardDraft && permissionChecker2.cannot.discard()) {
2708
+ return ctx.forbidden();
2709
+ }
2710
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.unpublish(query);
2711
+ const { locale } = await getDocumentLocaleAndStatus(body);
2712
+ const document = await findDocument(sanitizedQuery, model, { locale });
2713
+ if (!document) {
2714
+ return ctx.notFound();
2715
+ }
2716
+ if (permissionChecker2.cannot.unpublish(document)) {
2717
+ return ctx.forbidden();
2718
+ }
2719
+ if (discardDraft && permissionChecker2.cannot.discard(document)) {
2720
+ return ctx.forbidden();
2721
+ }
2722
+ await strapi.db.transaction(async () => {
2723
+ if (discardDraft) {
2724
+ await documentManager2.discardDraft(document.documentId, model, { locale });
2725
+ }
2726
+ ctx.body = await async.pipe(
2727
+ (document2) => documentManager2.unpublish(document2.documentId, model, { locale }),
2728
+ permissionChecker2.sanitizeOutput,
2729
+ (document2) => formatDocumentWithMetadata(permissionChecker2, model, document2)
2730
+ )(document);
2731
+ });
2732
+ },
2733
+ async discard(ctx) {
2734
+ const { userAbility } = ctx.state;
2735
+ const { model } = ctx.params;
2736
+ const { body, query = {} } = ctx.request;
2737
+ const documentManager2 = getService$1("document-manager");
2738
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2739
+ if (permissionChecker2.cannot.discard()) {
2740
+ return ctx.forbidden();
2741
+ }
2742
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.discard(query);
2743
+ const { locale } = await getDocumentLocaleAndStatus(body);
2744
+ const document = await findDocument(sanitizedQuery, model, { locale, status: "published" });
2745
+ if (!document) {
2746
+ return ctx.notFound();
2747
+ }
2748
+ if (permissionChecker2.cannot.discard(document)) {
2749
+ return ctx.forbidden();
2750
+ }
2751
+ ctx.body = await async.pipe(
2752
+ (document2) => documentManager2.discardDraft(document2.documentId, model, { locale }),
2753
+ permissionChecker2.sanitizeOutput,
2754
+ (document2) => formatDocumentWithMetadata(permissionChecker2, model, document2)
2755
+ )(document);
2756
+ },
2757
+ async countDraftRelations(ctx) {
2758
+ const { userAbility } = ctx.state;
2759
+ const { model } = ctx.params;
2760
+ const { query } = ctx.request;
2761
+ const documentManager2 = getService$1("document-manager");
2762
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2763
+ const { locale } = await getDocumentLocaleAndStatus(query);
2764
+ if (permissionChecker2.cannot.read()) {
2765
+ return ctx.forbidden();
2766
+ }
2767
+ const document = await findDocument({}, model);
2768
+ if (!document) {
2769
+ return ctx.notFound();
2770
+ }
2771
+ if (permissionChecker2.cannot.read(document)) {
2772
+ return ctx.forbidden();
2773
+ }
2774
+ const number = await documentManager2.countDraftRelations(document.documentId, model, locale);
2775
+ return {
2776
+ data: number
2777
+ };
2778
+ }
2779
+ };
2780
+ const uid$1 = {
2781
+ async generateUID(ctx) {
2782
+ const { contentTypeUID, field, data } = await validateGenerateUIDInput(ctx.request.body);
2783
+ const { query = {} } = ctx.request;
2784
+ const { locale } = await getDocumentLocaleAndStatus(query);
2785
+ await validateUIDField(contentTypeUID, field);
2786
+ const uidService = getService$1("uid");
2787
+ ctx.body = {
2788
+ data: await uidService.generateUIDField({ contentTypeUID, field, data, locale })
2789
+ };
2790
+ },
2791
+ async checkUIDAvailability(ctx) {
2792
+ const { contentTypeUID, field, value } = await validateCheckUIDAvailabilityInput(
2793
+ ctx.request.body
2794
+ );
2795
+ const { query = {} } = ctx.request;
2796
+ const { locale } = await getDocumentLocaleAndStatus(query);
2797
+ await validateUIDField(contentTypeUID, field);
2798
+ const uidService = getService$1("uid");
2799
+ const isAvailable = await uidService.checkUIDAvailability({
2800
+ contentTypeUID,
2801
+ field,
2802
+ value,
2803
+ locale
2804
+ });
2805
+ ctx.body = {
2806
+ isAvailable,
2807
+ suggestion: !isAvailable ? await uidService.findUniqueUID({ contentTypeUID, field, value, locale }) : null
2808
+ };
2809
+ }
2810
+ };
2811
+ const controllers = {
2812
+ "collection-types": collectionTypes,
2813
+ components: components$1,
2814
+ "content-types": contentTypes,
2815
+ init,
2816
+ relations,
2817
+ "single-types": singleTypes,
2818
+ uid: uid$1,
2819
+ ...history.controllers ? history.controllers : {}
2820
+ };
2821
+ const keys = {
2822
+ CONFIGURATION: "configuration"
2823
+ };
2824
+ const getStore = () => strapi.store({ type: "plugin", name: "content_manager" });
2825
+ const EMPTY_CONFIG = {
2826
+ settings: {},
2827
+ metadatas: {},
2828
+ layouts: {}
2829
+ };
2830
+ const configurationKey = (key) => `${keys.CONFIGURATION}_${key}`;
2831
+ const getModelConfiguration = async (key) => {
2832
+ const config = await getStore().get({ key: configurationKey(key) });
2833
+ return _.merge({}, EMPTY_CONFIG, config);
2834
+ };
2835
+ const setModelConfiguration = async (key, value) => {
2836
+ const storedConfig = await getStore().get({ key: configurationKey(key) }) || {};
2837
+ const currentConfig = { ...storedConfig };
2838
+ Object.keys(value).forEach((key2) => {
2839
+ if (value[key2] !== null && value[key2] !== void 0) {
2840
+ _.set(currentConfig, key2, value[key2]);
2841
+ }
2842
+ });
2843
+ if (!_.isEqual(currentConfig, storedConfig)) {
2844
+ return getStore().set({
2845
+ key: configurationKey(key),
2846
+ value: currentConfig
2847
+ });
2848
+ }
2849
+ };
2850
+ const deleteKey = (key) => {
2851
+ return strapi.db.query("strapi::core-store").delete({ where: { key: `plugin_content_manager_configuration_${key}` } });
2852
+ };
2853
+ const findByKey = async (key) => {
2854
+ const results = await strapi.db.query("strapi::core-store").findMany({
2855
+ where: {
2856
+ key: {
2857
+ $startsWith: key
2858
+ }
2859
+ }
2860
+ });
2861
+ return results.map(({ value }) => JSON.parse(value));
2862
+ };
2863
+ const getAllConfigurations = () => findByKey("plugin_content_manager_configuration");
2864
+ const storeUtils = {
2865
+ getAllConfigurations,
2866
+ findByKey,
2867
+ getModelConfiguration,
2868
+ setModelConfiguration,
2869
+ deleteKey,
2870
+ keys
2871
+ };
2872
+ function createDefaultMetadatas(schema) {
2873
+ return {
2874
+ ...Object.keys(schema.attributes).reduce((acc, name) => {
2875
+ acc[name] = createDefaultMetadata(schema, name);
2876
+ return acc;
2877
+ }, {}),
2878
+ id: {
2879
+ edit: {},
2880
+ list: {
2881
+ label: "id",
2882
+ searchable: true,
2883
+ sortable: true
2884
+ }
2885
+ }
2886
+ };
2887
+ }
2888
+ function createDefaultMetadata(schema, name) {
2889
+ const edit = {
2890
+ label: name,
2891
+ description: "",
2892
+ placeholder: "",
2893
+ visible: isVisible$1(schema, name),
2894
+ editable: true
2895
+ };
2896
+ const fieldAttributes = schema.attributes[name];
2897
+ if (isRelation$1(fieldAttributes)) {
2898
+ const { targetModel } = fieldAttributes;
2899
+ const targetSchema = getTargetSchema(targetModel);
2900
+ if (targetSchema) {
2901
+ edit.mainField = getDefaultMainField(targetSchema);
2902
+ }
2903
+ }
2904
+ _.assign(
2905
+ edit,
2906
+ _.pick(_.get(schema, ["config", "metadatas", name, "edit"], {}), [
2907
+ "label",
2908
+ "description",
2909
+ "placeholder",
2910
+ "visible",
2911
+ "editable",
2912
+ "mainField"
2913
+ ])
2914
+ );
2915
+ const list = {
2916
+ // @ts-expect-error we need to specify these properties
2917
+ label: name,
2918
+ // @ts-expect-error we need to specify these properties
2919
+ searchable: isSearchable(schema, name),
2920
+ // @ts-expect-error we need to specify these properties
2921
+ sortable: isSortable(schema, name),
2922
+ ..._.pick(_.get(schema, ["config", "metadatas", name, "list"], {}), [
2923
+ "label",
2924
+ "searchable",
2925
+ "sortable"
2926
+ ])
2927
+ };
2928
+ return { edit, list };
2929
+ }
2930
+ async function syncMetadatas(configuration, schema) {
2931
+ if (_.isEmpty(configuration.metadatas)) {
2932
+ return createDefaultMetadatas(schema);
2933
+ }
2934
+ const metasWithValidKeys = _.pick(configuration.metadatas, Object.keys(schema.attributes));
2935
+ const metasWithDefaults = _.merge({}, createDefaultMetadatas(schema), metasWithValidKeys);
2936
+ const updatedMetas = Object.keys(metasWithDefaults).reduce((acc, key) => {
2937
+ const { edit, list } = metasWithDefaults[key];
2938
+ const attr = schema.attributes[key];
2939
+ const updatedMeta = { edit, list };
2940
+ if (list.sortable && !isSortable(schema, key)) {
2941
+ _.set(updatedMeta, ["list", "sortable"], false);
2942
+ _.set(acc, [key], updatedMeta);
2943
+ }
2944
+ if (list.searchable && !isSearchable(schema, key)) {
2945
+ _.set(updatedMeta, ["list", "searchable"], false);
2946
+ _.set(acc, [key], updatedMeta);
2947
+ }
2948
+ if (!_.has(edit, "mainField"))
2949
+ return acc;
2950
+ if (!isRelation$1(attr)) {
2951
+ _.set(updatedMeta, "edit", _.omit(edit, ["mainField"]));
2952
+ _.set(acc, [key], updatedMeta);
2953
+ return acc;
2954
+ }
2955
+ if (edit.mainField === "id")
2956
+ return acc;
2957
+ const targetSchema = getTargetSchema(attr.targetModel);
2958
+ if (!targetSchema)
2959
+ return acc;
2960
+ if (!isSortable(targetSchema, edit.mainField) && !isListable(targetSchema, edit.mainField)) {
2961
+ _.set(updatedMeta, ["edit", "mainField"], getDefaultMainField(targetSchema));
2962
+ _.set(acc, [key], updatedMeta);
2963
+ return acc;
2964
+ }
2965
+ return acc;
2966
+ }, {});
2967
+ return _.assign(metasWithDefaults, updatedMetas);
2968
+ }
2969
+ const getTargetSchema = (targetModel) => {
2970
+ return getService$1("content-types").findContentType(targetModel);
2971
+ };
2972
+ const DEFAULT_LIST_LENGTH = 4;
2973
+ const MAX_ROW_SIZE = 12;
2974
+ const isAllowedFieldSize = (type, size) => {
2975
+ const { getFieldSize } = getService$1("field-sizes");
2976
+ const fieldSize = getFieldSize(type);
2977
+ if (!fieldSize.isResizable && size !== fieldSize.default) {
2978
+ return false;
2979
+ }
2980
+ return size <= MAX_ROW_SIZE;
2981
+ };
2982
+ const getDefaultFieldSize = (attribute) => {
2983
+ const { hasFieldSize, getFieldSize } = getService$1("field-sizes");
2984
+ return getFieldSize(hasFieldSize(attribute.customField) ? attribute.customField : attribute.type).default;
2985
+ };
2986
+ async function createDefaultLayouts(schema) {
2987
+ return {
2988
+ // @ts-expect-error necessary to provide this default layout
2989
+ list: createDefaultListLayout(schema),
2990
+ // @ts-expect-error necessary to provide this default layout
2991
+ edit: createDefaultEditLayout(schema),
2992
+ ..._.pick(_.get(schema, ["config", "layouts"], {}), ["list", "edit"])
2993
+ };
2994
+ }
2995
+ function createDefaultListLayout(schema) {
2996
+ return Object.keys(schema.attributes).filter((name) => isListable(schema, name)).slice(0, DEFAULT_LIST_LENGTH);
2997
+ }
2998
+ const rowSize = (els) => els.reduce((sum, el) => sum + el.size, 0);
2999
+ function createDefaultEditLayout(schema) {
3000
+ const keys2 = Object.keys(schema.attributes).filter((name) => hasEditableAttribute(schema, name));
3001
+ return appendToEditLayout([], keys2, schema);
3002
+ }
3003
+ function syncLayouts(configuration, schema) {
3004
+ if (_.isEmpty(configuration.layouts))
3005
+ return createDefaultLayouts(schema);
3006
+ const { list = [], editRelations = [], edit = [] } = configuration.layouts || {};
3007
+ let cleanList = list.filter((attr) => isListable(schema, attr));
3008
+ const cleanEditRelations = editRelations.filter(
3009
+ (attr) => hasRelationAttribute(schema, attr)
3010
+ );
3011
+ const elementsToReAppend = [...cleanEditRelations];
3012
+ let cleanEdit = [];
3013
+ for (const row of edit) {
3014
+ const newRow = [];
3015
+ for (const el of row) {
3016
+ if (!hasEditableAttribute(schema, el.name))
3017
+ continue;
3018
+ const { hasFieldSize } = getService$1("field-sizes");
3019
+ const fieldType = hasFieldSize(schema.attributes[el.name].customField) ? schema.attributes[el.name].customField : schema.attributes[el.name].type;
3020
+ if (!isAllowedFieldSize(fieldType, el.size)) {
3021
+ elementsToReAppend.push(el.name);
3022
+ continue;
3023
+ }
3024
+ newRow.push(el);
3025
+ }
3026
+ if (newRow.length > 0) {
3027
+ cleanEdit.push(newRow);
3028
+ }
3029
+ }
3030
+ cleanEdit = appendToEditLayout(cleanEdit, elementsToReAppend, schema);
3031
+ const newAttributes = _.difference(
3032
+ Object.keys(schema.attributes),
3033
+ Object.keys(configuration.metadatas)
3034
+ );
3035
+ if (cleanList.length < DEFAULT_LIST_LENGTH) {
3036
+ cleanList = _.uniq(
3037
+ cleanList.concat(newAttributes.filter((key) => isListable(schema, key))).slice(0, DEFAULT_LIST_LENGTH)
3038
+ );
3039
+ }
3040
+ const newEditAttributes = newAttributes.filter((key) => hasEditableAttribute(schema, key));
3041
+ cleanEdit = appendToEditLayout(cleanEdit, newEditAttributes, schema);
3042
+ return {
3043
+ list: cleanList.length > 0 ? cleanList : createDefaultListLayout(schema),
3044
+ edit: cleanEdit.length > 0 ? cleanEdit : createDefaultEditLayout(schema)
3045
+ };
3046
+ }
3047
+ const appendToEditLayout = (layout = [], keysToAppend, schema) => {
3048
+ if (keysToAppend.length === 0)
3049
+ return layout;
3050
+ let currentRowIndex = Math.max(layout.length - 1, 0);
3051
+ if (!layout[currentRowIndex]) {
3052
+ layout[currentRowIndex] = [];
3053
+ }
3054
+ for (const key of keysToAppend) {
3055
+ const attribute = schema.attributes[key];
3056
+ const attributeSize = getDefaultFieldSize(attribute);
3057
+ const currenRowSize = rowSize(layout[currentRowIndex]);
3058
+ if (currenRowSize + attributeSize > MAX_ROW_SIZE) {
3059
+ currentRowIndex += 1;
3060
+ layout[currentRowIndex] = [];
3061
+ }
3062
+ layout[currentRowIndex].push({
3063
+ name: key,
3064
+ size: attributeSize
3065
+ });
3066
+ }
3067
+ return layout;
3068
+ };
3069
+ async function validateCustomConfig(schema) {
3070
+ try {
3071
+ await createModelConfigurationSchema(schema, {
3072
+ allowUndefined: true
3073
+ }).validate(schema.config);
3074
+ } catch (error) {
3075
+ throw new Error(
3076
+ `Invalid Model configuration for model ${schema.uid}. Verify your {{ modelName }}.config.js(on) file:
3077
+ - ${error.message}
3078
+ `
3079
+ );
3080
+ }
3081
+ }
3082
+ async function createDefaultConfiguration(schema) {
3083
+ await validateCustomConfig(schema);
3084
+ return {
3085
+ settings: await createDefaultSettings(schema),
3086
+ metadatas: await createDefaultMetadatas(schema),
3087
+ layouts: await createDefaultLayouts(schema)
3088
+ };
3089
+ }
3090
+ async function syncConfiguration(conf, schema) {
3091
+ await validateCustomConfig(schema);
3092
+ return {
3093
+ settings: await syncSettings(conf, schema),
3094
+ layouts: await syncLayouts(conf, schema),
3095
+ metadatas: await syncMetadatas(conf, schema)
3096
+ };
3097
+ }
3098
+ const createConfigurationService = ({
3099
+ isComponent: isComponent2,
3100
+ prefix,
3101
+ storeUtils: storeUtils2,
3102
+ getModels
3103
+ }) => {
3104
+ const uidToStoreKey = (uid2) => {
3105
+ return `${prefix}::${uid2}`;
3106
+ };
3107
+ const getConfiguration = (uid2) => {
3108
+ const storeKey = uidToStoreKey(uid2);
3109
+ return storeUtils2.getModelConfiguration(storeKey);
3110
+ };
3111
+ const setConfiguration = (uid2, input) => {
3112
+ const configuration = {
3113
+ ...input,
3114
+ uid: uid2,
3115
+ isComponent: isComponent2 ?? void 0
3116
+ };
3117
+ const storeKey = uidToStoreKey(uid2);
3118
+ return storeUtils2.setModelConfiguration(storeKey, configuration);
3119
+ };
3120
+ const deleteConfiguration = (uid2) => {
3121
+ const storeKey = uidToStoreKey(uid2);
3122
+ return storeUtils2.deleteKey(storeKey);
3123
+ };
3124
+ const syncConfigurations = async () => {
3125
+ const models = getModels();
3126
+ const configurations = await storeUtils2.findByKey(
3127
+ `plugin_content_manager_configuration_${prefix}`
3128
+ );
3129
+ const updateConfiguration = async (uid2) => {
3130
+ const conf = configurations.find((conf2) => conf2.uid === uid2);
3131
+ return setConfiguration(uid2, await syncConfiguration(conf, models[uid2]));
3132
+ };
3133
+ const generateNewConfiguration = async (uid2) => {
3134
+ return setConfiguration(uid2, await createDefaultConfiguration(models[uid2]));
3135
+ };
3136
+ const currentUIDS = Object.keys(models);
3137
+ const DBUIDs = configurations.map(({ uid: uid2 }) => uid2);
3138
+ const contentTypesToUpdate = intersection$1(currentUIDS, DBUIDs);
3139
+ const contentTypesToAdd = difference$1(currentUIDS, DBUIDs);
3140
+ const contentTypesToDelete = difference$1(DBUIDs, currentUIDS);
3141
+ await Promise.all(contentTypesToDelete.map((uid2) => deleteConfiguration(uid2)));
3142
+ await Promise.all(contentTypesToAdd.map((uid2) => generateNewConfiguration(uid2)));
3143
+ await Promise.all(contentTypesToUpdate.map((uid2) => updateConfiguration(uid2)));
3144
+ };
3145
+ return {
3146
+ getConfiguration,
3147
+ setConfiguration,
3148
+ deleteConfiguration,
3149
+ syncConfigurations
3150
+ };
3151
+ };
3152
+ const STORE_KEY_PREFIX = "components";
3153
+ const configurationService$1 = createConfigurationService({
3154
+ storeUtils,
3155
+ isComponent: true,
3156
+ prefix: STORE_KEY_PREFIX,
3157
+ getModels() {
3158
+ const { toContentManagerModel } = getService$1("data-mapper");
3159
+ return mapValues(toContentManagerModel, strapi.components);
3160
+ }
3161
+ });
3162
+ const components = ({ strapi: strapi2 }) => ({
3163
+ findAllComponents() {
3164
+ const { toContentManagerModel } = getService$1("data-mapper");
3165
+ return Object.values(strapi2.components).map(toContentManagerModel);
3166
+ },
3167
+ findComponent(uid2) {
3168
+ const { toContentManagerModel } = getService$1("data-mapper");
3169
+ const component = strapi2.components[uid2];
3170
+ return isNil$1(component) ? component : toContentManagerModel(component);
3171
+ },
3172
+ async findConfiguration(component) {
3173
+ const configuration = await configurationService$1.getConfiguration(component.uid);
3174
+ return {
3175
+ uid: component.uid,
3176
+ category: component.category,
3177
+ ...configuration
3178
+ };
3179
+ },
3180
+ async updateConfiguration(component, newConfiguration) {
3181
+ await configurationService$1.setConfiguration(component.uid, newConfiguration);
3182
+ return this.findConfiguration(component);
3183
+ },
3184
+ async findComponentsConfigurations(model) {
3185
+ const componentsMap = {};
3186
+ const getComponentConfigurations = async (uid2) => {
3187
+ const component = this.findComponent(uid2);
3188
+ if (has(uid2, componentsMap)) {
3189
+ return;
3190
+ }
3191
+ const componentConfiguration = await this.findConfiguration(component);
3192
+ const componentsConfigurations = await this.findComponentsConfigurations(component);
3193
+ Object.assign(componentsMap, {
3194
+ [uid2]: componentConfiguration,
3195
+ ...componentsConfigurations
3196
+ });
3197
+ };
3198
+ for (const key of Object.keys(model.attributes)) {
3199
+ const attribute = model.attributes[key];
3200
+ if (attribute.type === "component") {
3201
+ await getComponentConfigurations(attribute.component);
3202
+ }
3203
+ if (attribute.type === "dynamiczone") {
3204
+ for (const componentUid of attribute.components) {
3205
+ await getComponentConfigurations(componentUid);
3206
+ }
3207
+ }
3208
+ }
3209
+ return componentsMap;
3210
+ },
3211
+ syncConfigurations() {
3212
+ return configurationService$1.syncConfigurations();
3213
+ }
3214
+ });
3215
+ const configurationService = createConfigurationService({
3216
+ storeUtils,
3217
+ prefix: "content_types",
3218
+ getModels() {
3219
+ const { toContentManagerModel } = getService$1("data-mapper");
3220
+ return mapValues(toContentManagerModel, strapi.contentTypes);
3221
+ }
3222
+ });
3223
+ const service = ({ strapi: strapi2 }) => ({
3224
+ findAllContentTypes() {
3225
+ const { toContentManagerModel } = getService$1("data-mapper");
3226
+ return Object.values(strapi2.contentTypes).map(toContentManagerModel);
3227
+ },
3228
+ findContentType(uid2) {
3229
+ const { toContentManagerModel } = getService$1("data-mapper");
3230
+ const contentType = strapi2.contentTypes[uid2];
3231
+ return isNil$1(contentType) ? contentType : toContentManagerModel(contentType);
3232
+ },
3233
+ findDisplayedContentTypes() {
3234
+ return this.findAllContentTypes().filter(
3235
+ // TODO
3236
+ // @ts-expect-error should be resolved from data-mapper types
3237
+ ({ isDisplayed }) => isDisplayed === true
3238
+ );
3239
+ },
3240
+ findContentTypesByKind(kind) {
3241
+ if (!kind) {
3242
+ return this.findAllContentTypes();
3243
+ }
3244
+ return this.findAllContentTypes().filter(contentTypes$1.isKind(kind));
3245
+ },
3246
+ async findConfiguration(contentType) {
3247
+ const configuration = await configurationService.getConfiguration(contentType.uid);
3248
+ return {
3249
+ uid: contentType.uid,
3250
+ ...configuration
3251
+ };
3252
+ },
3253
+ async updateConfiguration(contentType, newConfiguration) {
3254
+ await configurationService.setConfiguration(contentType.uid, newConfiguration);
3255
+ return this.findConfiguration(contentType);
3256
+ },
3257
+ findComponentsConfigurations(contentType) {
3258
+ return getService$1("components").findComponentsConfigurations(contentType);
3259
+ },
3260
+ syncConfigurations() {
3261
+ return configurationService.syncConfigurations();
3262
+ }
3263
+ });
3264
+ const dtoFields = [
3265
+ "uid",
3266
+ "isDisplayed",
3267
+ "apiID",
3268
+ "kind",
3269
+ "category",
3270
+ "info",
3271
+ "options",
3272
+ "pluginOptions",
3273
+ "attributes",
3274
+ "pluginOptions"
3275
+ ];
3276
+ const dataMapper = () => ({
3277
+ toContentManagerModel(contentType) {
3278
+ return {
3279
+ ...contentType,
3280
+ apiID: contentType.modelName,
3281
+ isDisplayed: isVisible(contentType),
3282
+ attributes: {
3283
+ id: {
3284
+ type: "integer"
3285
+ },
3286
+ ...formatAttributes(contentType)
3287
+ }
3288
+ };
3289
+ },
3290
+ toDto: pick(dtoFields)
3291
+ });
3292
+ const formatAttributes = (contentType) => {
3293
+ const { getVisibleAttributes, getTimestamps, getCreatorFields } = contentTypes$1;
3294
+ return getVisibleAttributes(contentType).concat(getTimestamps(contentType)).concat(getCreatorFields(contentType)).reduce((acc, key) => {
3295
+ const attribute = contentType.attributes[key];
3296
+ if (attribute.type === "relation" && attribute.relation.toLowerCase().includes("morph")) {
3297
+ return acc;
3298
+ }
3299
+ acc[key] = formatAttribute(key, attribute);
3300
+ return acc;
3301
+ }, {});
3302
+ };
3303
+ const formatAttribute = (key, attribute) => {
3304
+ if (attribute.type === "relation") {
3305
+ return toRelation(attribute);
3306
+ }
3307
+ return attribute;
3308
+ };
3309
+ const toRelation = (attribute) => {
3310
+ return {
3311
+ ...attribute,
3312
+ type: "relation",
3313
+ targetModel: "target" in attribute ? attribute.target : void 0,
3314
+ relationType: attribute.relation
3315
+ };
3316
+ };
3317
+ const isVisible = (model) => getOr(true, "pluginOptions.content-manager.visible", model) === true;
3318
+ const { ApplicationError: ApplicationError$1 } = errors;
3319
+ const needsFullSize = {
3320
+ default: 12,
3321
+ isResizable: false
3322
+ };
3323
+ const smallSize = {
3324
+ default: 4,
3325
+ isResizable: true
3326
+ };
3327
+ const defaultSize = {
3328
+ default: 6,
3329
+ isResizable: true
3330
+ };
3331
+ const fieldSizes = {
3332
+ // Full row and not resizable
3333
+ dynamiczone: needsFullSize,
3334
+ component: needsFullSize,
3335
+ json: needsFullSize,
3336
+ richtext: needsFullSize,
3337
+ blocks: needsFullSize,
3338
+ // Small and resizable
3339
+ checkbox: smallSize,
3340
+ boolean: smallSize,
3341
+ date: smallSize,
3342
+ time: smallSize,
3343
+ biginteger: smallSize,
3344
+ decimal: smallSize,
3345
+ float: smallSize,
3346
+ integer: smallSize,
3347
+ number: smallSize,
3348
+ // Medium and resizable
3349
+ datetime: defaultSize,
3350
+ email: defaultSize,
3351
+ enumeration: defaultSize,
3352
+ media: defaultSize,
3353
+ password: defaultSize,
3354
+ relation: defaultSize,
3355
+ string: defaultSize,
3356
+ text: defaultSize,
3357
+ timestamp: defaultSize,
3358
+ uid: defaultSize
3359
+ };
3360
+ const createFieldSizesService = ({ strapi: strapi2 }) => {
3361
+ const fieldSizesService = {
3362
+ getAllFieldSizes() {
3363
+ return fieldSizes;
3364
+ },
3365
+ hasFieldSize(type) {
3366
+ return !!fieldSizes[type];
3367
+ },
3368
+ getFieldSize(type) {
3369
+ if (!type) {
3370
+ throw new ApplicationError$1("The type is required");
3371
+ }
3372
+ const fieldSize = fieldSizes[type];
3373
+ if (!fieldSize) {
3374
+ throw new ApplicationError$1(`Could not find field size for type ${type}`);
3375
+ }
3376
+ return fieldSize;
3377
+ },
3378
+ setFieldSize(type, size) {
3379
+ if (!type) {
3380
+ throw new ApplicationError$1("The type is required");
3381
+ }
3382
+ if (!size) {
3383
+ throw new ApplicationError$1("The size is required");
3384
+ }
3385
+ fieldSizes[type] = size;
3386
+ },
3387
+ setCustomFieldInputSizes() {
3388
+ const customFields = strapi2.get("custom-fields").getAll();
3389
+ Object.entries(customFields).forEach(([uid2, customField]) => {
3390
+ if (customField.inputSize) {
3391
+ fieldSizesService.setFieldSize(uid2, customField.inputSize);
3392
+ }
3393
+ });
3394
+ }
3395
+ };
3396
+ return fieldSizesService;
3397
+ };
3398
+ const { getRelationalFields } = relations$1;
3399
+ const metrics = ({ strapi: strapi2 }) => {
3400
+ const sendDidConfigureListView = async (contentType, configuration) => {
3401
+ const displayedFields = prop("length", configuration.layouts.list);
3402
+ const relationalFields = getRelationalFields(contentType);
3403
+ const displayedRelationalFields = intersection(
3404
+ relationalFields,
3405
+ configuration.layouts.list
3406
+ ).length;
3407
+ const data = {
3408
+ eventProperties: { containsRelationalFields: !!displayedRelationalFields }
3409
+ };
3410
+ if (data.eventProperties.containsRelationalFields) {
3411
+ Object.assign(data.eventProperties, {
3412
+ displayedFields,
3413
+ displayedRelationalFields
3414
+ });
3415
+ }
3416
+ try {
3417
+ await strapi2.telemetry.send("didConfigureListView", data);
3418
+ } catch (e) {
3419
+ }
3420
+ };
3421
+ return {
3422
+ sendDidConfigureListView
3423
+ };
3424
+ };
3425
+ const ACTIONS = {
3426
+ read: "plugin::content-manager.explorer.read",
3427
+ create: "plugin::content-manager.explorer.create",
3428
+ update: "plugin::content-manager.explorer.update",
3429
+ delete: "plugin::content-manager.explorer.delete",
3430
+ publish: "plugin::content-manager.explorer.publish",
3431
+ unpublish: "plugin::content-manager.explorer.publish",
3432
+ discard: "plugin::content-manager.explorer.update"
3433
+ };
3434
+ const createPermissionChecker = (strapi2) => ({ userAbility, model }) => {
3435
+ const permissionsManager = strapi2.service("admin::permission").createPermissionsManager({
3436
+ ability: userAbility,
3437
+ model
3438
+ });
3439
+ const toSubject = (entity) => entity ? permissionsManager.toSubject(entity, model) : model;
3440
+ const can = (action, entity, field) => {
3441
+ return userAbility.can(action, toSubject(entity), field);
3442
+ };
3443
+ const cannot = (action, entity, field) => {
3444
+ return userAbility.cannot(action, toSubject(entity), field);
3445
+ };
3446
+ const sanitizeOutput = (data, { action = ACTIONS.read } = {}) => {
3447
+ return permissionsManager.sanitizeOutput(data, { subject: toSubject(data), action });
3448
+ };
3449
+ const sanitizeQuery = (query, { action = ACTIONS.read } = {}) => {
3450
+ return permissionsManager.sanitizeQuery(query, { subject: model, action });
3451
+ };
3452
+ const sanitizeInput = (action, data, entity) => {
3453
+ return permissionsManager.sanitizeInput(data, {
3454
+ subject: entity ? toSubject(entity) : model,
3455
+ action
3456
+ });
3457
+ };
3458
+ const validateQuery = (query, { action = ACTIONS.read } = {}) => {
3459
+ return permissionsManager.validateQuery(query, { subject: model, action });
3460
+ };
3461
+ const validateInput = (action, data, entity) => {
3462
+ return permissionsManager.validateInput(data, {
3463
+ subject: entity ? toSubject(entity) : model,
3464
+ action
3465
+ });
3466
+ };
3467
+ const sanitizeCreateInput = (data) => sanitizeInput(ACTIONS.create, data);
3468
+ const sanitizeUpdateInput = (entity) => (data) => sanitizeInput(ACTIONS.update, data, entity);
3469
+ const buildPermissionQuery = (query, action = {}) => {
3470
+ return permissionsManager.addPermissionsQueryTo(query, action);
3471
+ };
3472
+ const sanitizedQuery = (query, action = {}) => {
3473
+ return async.pipe(
3474
+ (q) => sanitizeQuery(q, action),
3475
+ (q) => buildPermissionQuery(q, action)
3476
+ )(query);
3477
+ };
3478
+ Object.keys(ACTIONS).forEach((action) => {
3479
+ sanitizedQuery[action] = (query) => sanitizedQuery(query, ACTIONS[action]);
3480
+ });
3481
+ Object.keys(ACTIONS).forEach((action) => {
3482
+ can[action] = (...args) => can(ACTIONS[action], ...args);
3483
+ cannot[action] = (...args) => cannot(ACTIONS[action], ...args);
3484
+ });
3485
+ return {
3486
+ // Permission utils
3487
+ can,
3488
+ // check if you have the permission
3489
+ cannot,
3490
+ // check if you don't have the permission
3491
+ // Sanitizers
3492
+ sanitizeOutput,
3493
+ sanitizeQuery,
3494
+ sanitizeCreateInput,
3495
+ sanitizeUpdateInput,
3496
+ // Validators
3497
+ validateQuery,
3498
+ validateInput,
3499
+ // Queries Builder
3500
+ sanitizedQuery
3501
+ };
3502
+ };
3503
+ const permissionChecker = ({ strapi: strapi2 }) => ({
3504
+ create: createPermissionChecker(strapi2)
3505
+ });
3506
+ const permission = ({ strapi: strapi2 }) => ({
3507
+ canConfigureContentType({
3508
+ userAbility,
3509
+ contentType
3510
+ }) {
3511
+ const action = contentTypes$1.isSingleType(contentType) ? "plugin::content-manager.single-types.configure-view" : "plugin::content-manager.collection-types.configure-view";
3512
+ return userAbility.can(action);
3513
+ },
3514
+ async registerPermissions() {
3515
+ const displayedContentTypes = getService$1("content-types").findDisplayedContentTypes();
3516
+ const contentTypesUids = displayedContentTypes.map(prop("uid"));
3517
+ const actions = [
3518
+ {
3519
+ section: "contentTypes",
3520
+ displayName: "Create",
3521
+ uid: "explorer.create",
3522
+ pluginName: "content-manager",
3523
+ subjects: contentTypesUids,
3524
+ options: {
3525
+ applyToProperties: ["fields"]
3526
+ }
3527
+ },
3528
+ {
3529
+ section: "contentTypes",
3530
+ displayName: "Read",
3531
+ uid: "explorer.read",
3532
+ pluginName: "content-manager",
3533
+ subjects: contentTypesUids,
3534
+ options: {
3535
+ applyToProperties: ["fields"]
3536
+ }
3537
+ },
3538
+ {
3539
+ section: "contentTypes",
3540
+ displayName: "Update",
3541
+ uid: "explorer.update",
3542
+ pluginName: "content-manager",
3543
+ subjects: contentTypesUids,
3544
+ options: {
3545
+ applyToProperties: ["fields"]
3546
+ }
3547
+ },
3548
+ {
3549
+ section: "contentTypes",
3550
+ displayName: "Delete",
3551
+ uid: "explorer.delete",
3552
+ pluginName: "content-manager",
3553
+ subjects: contentTypesUids
3554
+ },
3555
+ {
3556
+ section: "contentTypes",
3557
+ displayName: "Publish",
3558
+ uid: "explorer.publish",
3559
+ pluginName: "content-manager",
3560
+ subjects: contentTypesUids
3561
+ },
3562
+ {
3563
+ section: "plugins",
3564
+ displayName: "Configure view",
3565
+ uid: "single-types.configure-view",
3566
+ subCategory: "single types",
3567
+ pluginName: "content-manager"
3568
+ },
3569
+ {
3570
+ section: "plugins",
3571
+ displayName: "Configure view",
3572
+ uid: "collection-types.configure-view",
3573
+ subCategory: "collection types",
3574
+ pluginName: "content-manager"
3575
+ },
3576
+ {
3577
+ section: "plugins",
3578
+ displayName: "Configure Layout",
3579
+ uid: "components.configure-layout",
3580
+ subCategory: "components",
3581
+ pluginName: "content-manager"
3582
+ }
3583
+ ];
3584
+ await strapi2.service("admin::permission").actionProvider.registerMany(actions);
3585
+ }
3586
+ });
3587
+ const { isVisibleAttribute: isVisibleAttribute$1, isScalarAttribute, getDoesAttributeRequireValidation } = strapiUtils.contentTypes;
3588
+ const { isAnyToMany } = strapiUtils.relations;
3589
+ const { PUBLISHED_AT_ATTRIBUTE: PUBLISHED_AT_ATTRIBUTE$1 } = strapiUtils.contentTypes.constants;
3590
+ const isMorphToRelation = (attribute) => isRelation(attribute) && attribute.relation.includes("morphTo");
3591
+ const isMedia = propEq("type", "media");
3592
+ const isRelation = propEq("type", "relation");
3593
+ const isComponent = propEq("type", "component");
3594
+ const isDynamicZone = propEq("type", "dynamiczone");
3595
+ function getPopulateForRelation(attribute, model, attributeName, { countMany, countOne, initialPopulate }) {
3596
+ const isManyRelation = isAnyToMany(attribute);
3597
+ if (initialPopulate) {
3598
+ return initialPopulate;
3599
+ }
3600
+ if (!isVisibleAttribute$1(model, attributeName)) {
3601
+ return true;
3602
+ }
3603
+ if (isManyRelation && countMany || !isManyRelation && countOne) {
3604
+ return { count: true };
3605
+ }
3606
+ return true;
3607
+ }
3608
+ function getPopulateForDZ(attribute, options, level) {
3609
+ const populatedComponents = (attribute.components || []).reduce(
3610
+ (acc, componentUID) => ({
3611
+ ...acc,
3612
+ [componentUID]: {
3613
+ populate: getDeepPopulate(componentUID, options, level + 1)
3614
+ }
3615
+ }),
3616
+ {}
3617
+ );
3618
+ return { on: populatedComponents };
3619
+ }
3620
+ function getPopulateFor(attributeName, model, options, level) {
3621
+ const attribute = model.attributes[attributeName];
3622
+ switch (attribute.type) {
3623
+ case "relation":
3624
+ return {
3625
+ [attributeName]: getPopulateForRelation(attribute, model, attributeName, options)
3626
+ };
3627
+ case "component":
3628
+ return {
3629
+ [attributeName]: {
3630
+ populate: getDeepPopulate(attribute.component, options, level + 1)
3631
+ }
3632
+ };
3633
+ case "media":
3634
+ return {
3635
+ [attributeName]: {
3636
+ populate: {
3637
+ folder: true
3638
+ }
3639
+ }
3640
+ };
3641
+ case "dynamiczone":
3642
+ return {
3643
+ [attributeName]: getPopulateForDZ(attribute, options, level)
3644
+ };
3645
+ default:
3646
+ return {};
3647
+ }
3648
+ }
3649
+ const getDeepPopulate = (uid2, {
3650
+ initialPopulate = {},
3651
+ countMany = false,
3652
+ countOne = false,
3653
+ maxLevel = Infinity
3654
+ } = {}, level = 1) => {
3655
+ if (level > maxLevel) {
3656
+ return {};
3657
+ }
3658
+ const model = strapi.getModel(uid2);
3659
+ return Object.keys(model.attributes).reduce(
3660
+ (populateAcc, attributeName) => merge(
3661
+ populateAcc,
3662
+ getPopulateFor(
3663
+ attributeName,
3664
+ model,
3665
+ {
3666
+ // @ts-expect-error - improve types
3667
+ initialPopulate: initialPopulate?.[attributeName],
3668
+ countMany,
3669
+ countOne,
3670
+ maxLevel
3671
+ },
3672
+ level
3673
+ )
3674
+ ),
3675
+ {}
3676
+ );
3677
+ };
3678
+ const getValidatableFieldsPopulate = (uid2, {
3679
+ initialPopulate = {},
3680
+ countMany = false,
3681
+ countOne = false,
3682
+ maxLevel = Infinity
3683
+ } = {}, level = 1) => {
3684
+ if (level > maxLevel) {
3685
+ return {};
3686
+ }
3687
+ const model = strapi.getModel(uid2);
3688
+ return Object.entries(model.attributes).reduce((populateAcc, [attributeName, attribute]) => {
3689
+ if (!getDoesAttributeRequireValidation(attribute)) {
3690
+ return populateAcc;
3691
+ }
3692
+ if (isScalarAttribute(attribute)) {
3693
+ return merge(populateAcc, {
3694
+ [attributeName]: true
3695
+ });
3696
+ }
3697
+ return merge(
3698
+ populateAcc,
3699
+ getPopulateFor(
3700
+ attributeName,
3701
+ model,
3702
+ {
3703
+ // @ts-expect-error - improve types
3704
+ initialPopulate: initialPopulate?.[attributeName],
3705
+ countMany,
3706
+ countOne,
3707
+ maxLevel
3708
+ },
3709
+ level
3710
+ )
3711
+ );
3712
+ }, {});
3713
+ };
3714
+ const getDeepPopulateDraftCount = (uid2) => {
3715
+ const model = strapi.getModel(uid2);
3716
+ let hasRelations = false;
3717
+ const populate = Object.keys(model.attributes).reduce((populateAcc, attributeName) => {
3718
+ const attribute = model.attributes[attributeName];
3719
+ switch (attribute.type) {
3720
+ case "relation": {
3721
+ if (isVisibleAttribute$1(model, attributeName)) {
3722
+ populateAcc[attributeName] = {
3723
+ count: true,
3724
+ filters: { [PUBLISHED_AT_ATTRIBUTE$1]: { $null: true } }
3725
+ };
3726
+ hasRelations = true;
3727
+ }
3728
+ break;
3729
+ }
3730
+ case "component": {
3731
+ const { populate: populate2, hasRelations: childHasRelations } = getDeepPopulateDraftCount(
3732
+ attribute.component
3733
+ );
3734
+ if (childHasRelations) {
3735
+ populateAcc[attributeName] = {
3736
+ populate: populate2
3737
+ };
3738
+ hasRelations = true;
3739
+ }
3740
+ break;
3741
+ }
3742
+ case "dynamiczone": {
3743
+ const dzPopulateFragment = attribute.components?.reduce((acc, componentUID) => {
3744
+ const { populate: componentPopulate, hasRelations: componentHasRelations } = getDeepPopulateDraftCount(componentUID);
3745
+ if (componentHasRelations) {
3746
+ hasRelations = true;
3747
+ return { ...acc, [componentUID]: { populate: componentPopulate } };
3748
+ }
3749
+ return acc;
3750
+ }, {});
3751
+ if (!isEmpty(dzPopulateFragment)) {
3752
+ populateAcc[attributeName] = { on: dzPopulateFragment };
3753
+ }
3754
+ break;
3755
+ }
3756
+ }
3757
+ return populateAcc;
3758
+ }, {});
3759
+ return { populate, hasRelations };
3760
+ };
3761
+ const getQueryPopulate = async (uid2, query) => {
3762
+ let populateQuery = {};
3763
+ await strapiUtils.traverse.traverseQueryFilters(
3764
+ /**
3765
+ *
3766
+ * @param {Object} param0
3767
+ * @param {string} param0.key - Attribute name
3768
+ * @param {Object} param0.attribute - Attribute definition
3769
+ * @param {string} param0.path - Content Type path to the attribute
3770
+ * @returns
3771
+ */
3772
+ ({ attribute, path }) => {
3773
+ if (!attribute || isDynamicZone(attribute) || isMorphToRelation(attribute)) {
3774
+ return;
3775
+ }
3776
+ if (isRelation(attribute) || isMedia(attribute) || isComponent(attribute)) {
3777
+ const populatePath = path.attribute.replace(/\./g, ".populate.");
3778
+ populateQuery = set(populatePath, {}, populateQuery);
3779
+ }
3780
+ },
3781
+ { schema: strapi.getModel(uid2), getModel: strapi.getModel.bind(strapi) },
3782
+ query
3783
+ );
3784
+ return populateQuery;
3785
+ };
3786
+ const buildDeepPopulate = (uid2) => {
3787
+ return getService$1("populate-builder")(uid2).populateDeep(Infinity).countRelations().build();
3788
+ };
3789
+ const populateBuilder = (uid2) => {
3790
+ let getInitialPopulate = async () => {
3791
+ return void 0;
3792
+ };
3793
+ const deepPopulateOptions = {
3794
+ countMany: false,
3795
+ countOne: false,
3796
+ maxLevel: -1
3797
+ };
3798
+ const builder = {
3799
+ /**
3800
+ * Populates all attribute fields present in a query.
3801
+ * @param query - Strapi query object
3802
+ */
3803
+ populateFromQuery(query) {
3804
+ getInitialPopulate = async () => getQueryPopulate(uid2, query);
3805
+ return builder;
3806
+ },
3807
+ /**
3808
+ * Populate relations as count.
3809
+ * @param [options]
3810
+ * @param [options.toMany] - Populate XtoMany relations as count if true.
3811
+ * @param [options.toOne] - Populate XtoOne relations as count if true.
3812
+ */
3813
+ countRelations({ toMany, toOne } = { toMany: true, toOne: true }) {
3814
+ if (!isNil$1(toMany)) {
3815
+ deepPopulateOptions.countMany = toMany;
3816
+ }
3817
+ if (!isNil$1(toOne)) {
3818
+ deepPopulateOptions.countOne = toOne;
3819
+ }
3820
+ return builder;
3821
+ },
3822
+ /**
3823
+ * Populate relations deeply, up to a certain level.
3824
+ * @param [level=Infinity] - Max level of nested populate.
3825
+ */
3826
+ populateDeep(level = Infinity) {
3827
+ deepPopulateOptions.maxLevel = level;
3828
+ return builder;
3829
+ },
3830
+ /**
3831
+ * Construct the populate object based on the builder options.
3832
+ * @returns Populate object
3833
+ */
3834
+ async build() {
3835
+ const initialPopulate = await getInitialPopulate();
3836
+ if (deepPopulateOptions.maxLevel === -1) {
3837
+ return initialPopulate;
3838
+ }
3839
+ return getDeepPopulate(uid2, { ...deepPopulateOptions, initialPopulate });
3840
+ }
3841
+ };
3842
+ return builder;
3843
+ };
3844
+ const populateBuilder$1 = () => populateBuilder;
3845
+ const uid = ({ strapi: strapi2 }) => ({
3846
+ async generateUIDField({
3847
+ contentTypeUID,
3848
+ field,
3849
+ data,
3850
+ locale
3851
+ }) {
3852
+ const contentType = strapi2.contentTypes[contentTypeUID];
3853
+ const { attributes } = contentType;
3854
+ const {
3855
+ targetField,
3856
+ default: defaultValue,
3857
+ options
3858
+ } = attributes[field];
3859
+ const targetValue = _.get(data, targetField);
3860
+ if (!_.isEmpty(targetValue)) {
3861
+ return this.findUniqueUID({
3862
+ contentTypeUID,
3863
+ field,
3864
+ value: slugify(targetValue, options),
3865
+ locale
3866
+ });
3867
+ }
3868
+ return this.findUniqueUID({
3869
+ contentTypeUID,
3870
+ field,
3871
+ value: slugify(
3872
+ _.isFunction(defaultValue) ? defaultValue() : defaultValue || contentType.modelName,
3873
+ options
3874
+ ),
3875
+ locale
3876
+ });
3877
+ },
3878
+ async findUniqueUID({
3879
+ contentTypeUID,
3880
+ field,
3881
+ value,
3882
+ locale
3883
+ }) {
3884
+ const foundDocuments = await strapi2.documents(contentTypeUID).findMany({
3885
+ filters: {
3886
+ [field]: { $startsWith: value }
3887
+ },
3888
+ locale,
3889
+ // TODO: Check UX. When modifying an entry, it only makes sense to check for collisions with other drafts
3890
+ // However, when publishing this "available" UID might collide with another published entry
3891
+ status: "draft"
3892
+ });
3893
+ if (!foundDocuments || foundDocuments.length === 0) {
3894
+ return value;
3895
+ }
3896
+ let possibleCollisions;
3897
+ if (!Array.isArray(foundDocuments)) {
3898
+ possibleCollisions = [foundDocuments[field]];
3899
+ } else {
3900
+ possibleCollisions = foundDocuments.map((doc) => doc[field]);
3901
+ }
3902
+ if (!possibleCollisions.includes(value)) {
3903
+ return value;
3904
+ }
3905
+ let i = 1;
3906
+ let tmpUId = `${value}-${i}`;
3907
+ while (possibleCollisions.includes(tmpUId)) {
3908
+ i += 1;
3909
+ tmpUId = `${value}-${i}`;
3910
+ }
3911
+ return tmpUId;
3912
+ },
3913
+ async checkUIDAvailability({
3914
+ contentTypeUID,
3915
+ field,
3916
+ value,
3917
+ locale
3918
+ }) {
3919
+ const documentCount = await strapi2.documents(contentTypeUID).count({
3920
+ filters: {
3921
+ [field]: value
3922
+ },
3923
+ locale,
3924
+ // TODO: Check UX. When modifying an entry, it only makes sense to check for collisions with other drafts
3925
+ // However, when publishing this "available" UID might collide with another published entry
3926
+ status: "draft"
3927
+ });
3928
+ if (documentCount && documentCount > 0) {
3929
+ return false;
3930
+ }
3931
+ return true;
3932
+ }
3933
+ });
3934
+ const AVAILABLE_STATUS_FIELDS = [
3935
+ "id",
3936
+ "locale",
3937
+ "updatedAt",
3938
+ "createdAt",
3939
+ "publishedAt",
3940
+ "createdBy",
3941
+ "updatedBy",
3942
+ "status"
3943
+ ];
3944
+ const AVAILABLE_LOCALES_FIELDS = [
3945
+ "id",
3946
+ "locale",
3947
+ "updatedAt",
3948
+ "createdAt",
3949
+ "status",
3950
+ "publishedAt",
3951
+ "documentId"
3952
+ ];
3953
+ const CONTENT_MANAGER_STATUS = {
3954
+ PUBLISHED: "published",
3955
+ DRAFT: "draft",
3956
+ MODIFIED: "modified"
3957
+ };
3958
+ const getIsVersionLatestModification = (version, otherVersion) => {
3959
+ if (!version || !version.updatedAt) {
3960
+ return false;
3961
+ }
3962
+ const versionUpdatedAt = version?.updatedAt ? new Date(version.updatedAt).getTime() : 0;
3963
+ const otherUpdatedAt = otherVersion?.updatedAt ? new Date(otherVersion.updatedAt).getTime() : 0;
3964
+ return versionUpdatedAt > otherUpdatedAt;
3965
+ };
3966
+ const documentMetadata = ({ strapi: strapi2 }) => ({
3967
+ /**
3968
+ * Returns available locales of a document for the current status
3969
+ */
3970
+ async getAvailableLocales(uid2, version, allVersions, validatableFields = []) {
3971
+ const versionsByLocale = groupBy("locale", allVersions);
3972
+ delete versionsByLocale[version.locale];
3973
+ const model = strapi2.getModel(uid2);
3974
+ const keysToKeep = [...AVAILABLE_LOCALES_FIELDS, ...validatableFields];
3975
+ const traversalFunction = async (localeVersion) => traverseEntity(
3976
+ ({ key }, { remove }) => {
3977
+ if (keysToKeep.includes(key)) {
3978
+ return;
3979
+ }
3980
+ remove(key);
3981
+ },
3982
+ { schema: model, getModel: strapi2.getModel.bind(strapi2) },
3983
+ // @ts-expect-error fix types DocumentVersion incompatible with Data
3984
+ localeVersion
3985
+ );
3986
+ const mappingResult = await async.map(
3987
+ Object.values(versionsByLocale),
3988
+ async (localeVersions) => {
3989
+ const mappedLocaleVersions = await async.map(
3990
+ localeVersions,
3991
+ traversalFunction
3992
+ );
3993
+ if (!contentTypes$1.hasDraftAndPublish(model)) {
3994
+ return mappedLocaleVersions[0];
3995
+ }
3996
+ const draftVersion = mappedLocaleVersions.find((v) => v.publishedAt === null);
3997
+ const otherVersions = mappedLocaleVersions.filter((v) => v.id !== draftVersion?.id);
3998
+ if (!draftVersion) {
3999
+ return;
4000
+ }
4001
+ return {
4002
+ ...draftVersion,
4003
+ status: this.getStatus(draftVersion, otherVersions)
4004
+ };
4005
+ }
4006
+ );
4007
+ return mappingResult.filter(Boolean);
4008
+ },
4009
+ /**
4010
+ * Returns available status of a document for the current locale
4011
+ */
4012
+ getAvailableStatus(version, allVersions) {
4013
+ const status = version.publishedAt !== null ? CONTENT_MANAGER_STATUS.DRAFT : CONTENT_MANAGER_STATUS.PUBLISHED;
4014
+ const availableStatus = allVersions.find((v) => {
4015
+ const matchLocale = v.locale === version.locale;
4016
+ const matchStatus = status === "published" ? v.publishedAt !== null : v.publishedAt === null;
4017
+ return matchLocale && matchStatus;
4018
+ });
4019
+ if (!availableStatus)
4020
+ return availableStatus;
4021
+ return pick(AVAILABLE_STATUS_FIELDS, availableStatus);
4022
+ },
4023
+ /**
4024
+ * Get the available status of many documents, useful for batch operations
4025
+ * @param uid
4026
+ * @param documents
4027
+ * @returns
4028
+ */
4029
+ async getManyAvailableStatus(uid2, documents) {
4030
+ if (!documents.length)
4031
+ return [];
4032
+ const status = documents[0].publishedAt !== null ? "published" : "draft";
4033
+ const locale = documents[0]?.locale;
4034
+ const otherStatus = status === "published" ? "draft" : "published";
4035
+ return strapi2.documents(uid2).findMany({
4036
+ filters: {
4037
+ documentId: { $in: documents.map((d) => d.documentId).filter(Boolean) }
4038
+ },
4039
+ status: otherStatus,
4040
+ locale,
4041
+ fields: ["documentId", "locale", "updatedAt", "createdAt", "publishedAt"]
4042
+ });
4043
+ },
4044
+ getStatus(version, otherDocumentStatuses) {
4045
+ let draftVersion;
4046
+ let publishedVersion;
4047
+ if (version.publishedAt) {
4048
+ publishedVersion = version;
4049
+ } else {
4050
+ draftVersion = version;
4051
+ }
4052
+ const otherVersion = otherDocumentStatuses?.at(0);
4053
+ if (otherVersion?.publishedAt) {
4054
+ publishedVersion = otherVersion;
4055
+ } else if (otherVersion) {
4056
+ draftVersion = otherVersion;
4057
+ }
4058
+ if (!draftVersion)
4059
+ return CONTENT_MANAGER_STATUS.PUBLISHED;
4060
+ if (!publishedVersion)
4061
+ return CONTENT_MANAGER_STATUS.DRAFT;
4062
+ const isDraftModified = getIsVersionLatestModification(draftVersion, publishedVersion);
4063
+ return isDraftModified ? CONTENT_MANAGER_STATUS.MODIFIED : CONTENT_MANAGER_STATUS.PUBLISHED;
4064
+ },
4065
+ // TODO is it necessary to return metadata on every page of the CM
4066
+ // We could refactor this so the locales are only loaded when they're
4067
+ // needed. e.g. in the bulk locale action modal.
4068
+ async getMetadata(uid2, version, { availableLocales = true, availableStatus = true } = {}) {
4069
+ const populate = getValidatableFieldsPopulate(uid2);
4070
+ const versions = await strapi2.db.query(uid2).findMany({
4071
+ where: { documentId: version.documentId },
4072
+ populate: {
4073
+ // Populate only fields that require validation for bulk locale actions
4074
+ ...populate,
4075
+ // NOTE: creator fields are selected in this way to avoid exposing sensitive data
4076
+ createdBy: {
4077
+ select: ["id", "firstname", "lastname", "email"]
4078
+ },
4079
+ updatedBy: {
4080
+ select: ["id", "firstname", "lastname", "email"]
4081
+ }
4082
+ }
4083
+ });
4084
+ const availableLocalesResult = availableLocales ? await this.getAvailableLocales(uid2, version, versions, Object.keys(populate)) : [];
4085
+ const availableStatusResult = availableStatus ? this.getAvailableStatus(version, versions) : null;
4086
+ return {
4087
+ availableLocales: availableLocalesResult,
4088
+ availableStatus: availableStatusResult ? [availableStatusResult] : []
4089
+ };
4090
+ },
4091
+ /**
4092
+ * Returns associated metadata of a document:
4093
+ * - Available locales of the document for the current status
4094
+ * - Available status of the document for the current locale
4095
+ */
4096
+ async formatDocumentWithMetadata(uid2, document, opts = {}) {
4097
+ if (!document) {
4098
+ return document;
4099
+ }
4100
+ const hasDraftAndPublish = contentTypes$1.hasDraftAndPublish(strapi2.getModel(uid2));
4101
+ if (!hasDraftAndPublish) {
4102
+ opts.availableStatus = false;
4103
+ }
4104
+ const meta = await this.getMetadata(uid2, document, opts);
4105
+ return {
4106
+ data: {
4107
+ ...document,
4108
+ // Add status to the document only if draft and publish is enabled
4109
+ status: hasDraftAndPublish ? this.getStatus(document, meta.availableStatus) : void 0
4110
+ },
4111
+ meta
4112
+ };
4113
+ }
4114
+ });
4115
+ const { isVisibleAttribute } = strapiUtils.contentTypes;
4116
+ const sumDraftCounts = (entity, uid2) => {
4117
+ const model = strapi.getModel(uid2);
4118
+ return Object.keys(model.attributes).reduce((sum, attributeName) => {
4119
+ const attribute = model.attributes[attributeName];
4120
+ const value = entity[attributeName];
4121
+ if (!value) {
4122
+ return sum;
4123
+ }
4124
+ switch (attribute.type) {
4125
+ case "relation": {
4126
+ if (isVisibleAttribute(model, attributeName)) {
4127
+ return sum + value.count;
4128
+ }
4129
+ return sum;
4130
+ }
4131
+ case "component": {
4132
+ const compoSum = castArray(value).reduce((acc, componentValue) => {
4133
+ return acc + sumDraftCounts(componentValue, attribute.component);
4134
+ }, 0);
4135
+ return sum + compoSum;
4136
+ }
4137
+ case "dynamiczone": {
4138
+ const dzSum = value.reduce((acc, componentValue) => {
4139
+ return acc + sumDraftCounts(componentValue, componentValue.__component);
4140
+ }, 0);
4141
+ return sum + dzSum;
4142
+ }
4143
+ default:
4144
+ return sum;
4145
+ }
4146
+ }, 0);
4147
+ };
4148
+ const { ApplicationError } = errors;
4149
+ const { PUBLISHED_AT_ATTRIBUTE } = contentTypes$1.constants;
4150
+ const omitPublishedAtField = omit(PUBLISHED_AT_ATTRIBUTE);
4151
+ const omitIdField = omit("id");
4152
+ const documentManager = ({ strapi: strapi2 }) => {
4153
+ return {
4154
+ async findOne(id, uid2, opts = {}) {
4155
+ return strapi2.documents(uid2).findOne({ ...opts, documentId: id });
4156
+ },
4157
+ /**
4158
+ * Find multiple (or all) locales for a document
4159
+ */
4160
+ async findLocales(id, uid2, opts) {
4161
+ const where = {};
4162
+ if (id) {
4163
+ where.documentId = id;
4164
+ }
4165
+ if (Array.isArray(opts.locale)) {
4166
+ where.locale = { $in: opts.locale };
4167
+ } else if (opts.locale && opts.locale !== "*") {
4168
+ where.locale = opts.locale;
4169
+ }
4170
+ if (typeof opts.isPublished === "boolean") {
4171
+ where.publishedAt = { $notNull: opts.isPublished };
4172
+ }
4173
+ return strapi2.db.query(uid2).findMany({ populate: opts.populate, where });
4174
+ },
4175
+ async findMany(opts, uid2) {
4176
+ const params = { ...opts, populate: getDeepPopulate(uid2) };
4177
+ return strapi2.documents(uid2).findMany(params);
4178
+ },
4179
+ async findPage(opts, uid2) {
4180
+ const params = pagination.withDefaultPagination(opts || {}, {
4181
+ maxLimit: 1e3
4182
+ });
4183
+ const [documents, total = 0] = await Promise.all([
4184
+ strapi2.documents(uid2).findMany(params),
4185
+ strapi2.documents(uid2).count(params)
4186
+ ]);
4187
+ return {
4188
+ results: documents,
4189
+ pagination: pagination.transformPagedPaginationInfo(params, total)
4190
+ };
4191
+ },
4192
+ async create(uid2, opts = {}) {
4193
+ const populate = opts.populate ?? await buildDeepPopulate(uid2);
4194
+ const params = { ...opts, status: "draft", populate };
4195
+ return strapi2.documents(uid2).create(params);
4196
+ },
4197
+ async update(id, uid2, opts = {}) {
4198
+ const publishData = pipe(omitPublishedAtField, omitIdField)(opts.data || {});
4199
+ const populate = opts.populate ?? await buildDeepPopulate(uid2);
4200
+ const params = { ...opts, data: publishData, populate, status: "draft" };
4201
+ return strapi2.documents(uid2).update({ ...params, documentId: id });
4202
+ },
4203
+ async clone(id, body, uid2) {
4204
+ const populate = await buildDeepPopulate(uid2);
4205
+ const params = {
4206
+ data: {
4207
+ ...omitIdField(body),
4208
+ [PUBLISHED_AT_ATTRIBUTE]: null
4209
+ },
4210
+ populate
4211
+ };
4212
+ return strapi2.documents(uid2).clone({ ...params, documentId: id }).then((result) => result?.entries.at(0));
4213
+ },
4214
+ /**
4215
+ * Check if a document exists
4216
+ */
4217
+ async exists(uid2, id) {
4218
+ if (id) {
4219
+ const count2 = await strapi2.db.query(uid2).count({ where: { documentId: id } });
4220
+ return count2 > 0;
4221
+ }
4222
+ const count = await strapi2.db.query(uid2).count();
4223
+ return count > 0;
4224
+ },
4225
+ async delete(id, uid2, opts = {}) {
4226
+ const populate = await buildDeepPopulate(uid2);
4227
+ await strapi2.documents(uid2).delete({
4228
+ ...opts,
4229
+ documentId: id,
4230
+ populate
4231
+ });
4232
+ return {};
4233
+ },
4234
+ // FIXME: handle relations
4235
+ async deleteMany(documentIds, uid2, opts = {}) {
4236
+ const deletedEntries = await strapi2.db.transaction(async () => {
4237
+ return Promise.all(documentIds.map(async (id) => this.delete(id, uid2, opts)));
4238
+ });
4239
+ return { count: deletedEntries.length };
4240
+ },
4241
+ async publish(id, uid2, opts = {}) {
4242
+ const populate = await buildDeepPopulate(uid2);
4243
+ const params = { ...opts, populate };
4244
+ return strapi2.documents(uid2).publish({ ...params, documentId: id }).then((result) => result?.entries);
4245
+ },
4246
+ async publishMany(uid2, documentIds, locale) {
4247
+ return strapi2.db.transaction(async () => {
4248
+ const results = await Promise.all(
4249
+ documentIds.map((documentId) => this.publish(documentId, uid2, { locale }))
4250
+ );
4251
+ const publishedEntitiesCount = results.flat().filter(Boolean).length;
4252
+ return publishedEntitiesCount;
4253
+ });
4254
+ },
4255
+ async unpublishMany(documentIds, uid2, opts = {}) {
4256
+ const unpublishedEntries = await strapi2.db.transaction(async () => {
4257
+ return Promise.all(
4258
+ documentIds.map(
4259
+ (id) => strapi2.documents(uid2).unpublish({ ...opts, documentId: id }).then((result) => result?.entries)
4260
+ )
4261
+ );
4262
+ });
4263
+ const unpublishedEntitiesCount = unpublishedEntries.flat().filter(Boolean).length;
4264
+ return { count: unpublishedEntitiesCount };
4265
+ },
4266
+ async unpublish(id, uid2, opts = {}) {
4267
+ const populate = await buildDeepPopulate(uid2);
4268
+ const params = { ...opts, populate };
4269
+ return strapi2.documents(uid2).unpublish({ ...params, documentId: id }).then((result) => result?.entries.at(0));
4270
+ },
4271
+ async discardDraft(id, uid2, opts = {}) {
4272
+ const populate = await buildDeepPopulate(uid2);
4273
+ const params = { ...opts, populate };
4274
+ return strapi2.documents(uid2).discardDraft({ ...params, documentId: id }).then((result) => result?.entries.at(0));
4275
+ },
4276
+ async countDraftRelations(id, uid2, locale) {
4277
+ const { populate, hasRelations } = getDeepPopulateDraftCount(uid2);
4278
+ if (!hasRelations) {
4279
+ return 0;
4280
+ }
4281
+ const document = await strapi2.documents(uid2).findOne({ documentId: id, populate, locale });
4282
+ if (!document) {
4283
+ throw new ApplicationError(
4284
+ `Unable to count draft relations, document with id ${id} and locale ${locale} not found`
4285
+ );
4286
+ }
4287
+ return sumDraftCounts(document, uid2);
4288
+ },
4289
+ async countManyEntriesDraftRelations(documentIds, uid2, locale) {
4290
+ const { populate, hasRelations } = getDeepPopulateDraftCount(uid2);
4291
+ if (!hasRelations) {
4292
+ return 0;
4293
+ }
4294
+ let localeFilter = {};
4295
+ if (locale) {
4296
+ localeFilter = Array.isArray(locale) ? { locale: { $in: locale } } : { locale };
4297
+ }
4298
+ const entities = await strapi2.db.query(uid2).findMany({
4299
+ populate,
4300
+ where: {
4301
+ documentId: { $in: documentIds },
4302
+ ...localeFilter
4303
+ }
4304
+ });
4305
+ const totalNumberDraftRelations = entities.reduce(
4306
+ (count, entity) => sumDraftCounts(entity, uid2) + count,
4307
+ 0
4308
+ );
4309
+ return totalNumberDraftRelations;
4310
+ }
4311
+ };
4312
+ };
4313
+ const services = {
4314
+ components,
4315
+ "content-types": service,
4316
+ "data-mapper": dataMapper,
4317
+ "document-metadata": documentMetadata,
4318
+ "document-manager": documentManager,
4319
+ "field-sizes": createFieldSizesService,
4320
+ metrics,
4321
+ "permission-checker": permissionChecker,
4322
+ permission,
4323
+ "populate-builder": populateBuilder$1,
4324
+ uid,
4325
+ ...history.services ? history.services : {}
4326
+ };
4327
+ const index = () => {
4328
+ return {
4329
+ register,
4330
+ bootstrap,
4331
+ destroy,
4332
+ controllers,
4333
+ routes,
4334
+ policies,
4335
+ services
4336
+ };
4337
+ };
4338
+ export {
4339
+ index as default
4340
+ };
4341
+ //# sourceMappingURL=index.mjs.map