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

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