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