@strapi/core 0.0.0-experimental.62ce06180fe9a772eaeb3d43d238b26644f39f7c → 0.0.0-experimental.6340da17068c3bed7fb006e7bcc554c71129e282

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 (1162) hide show
  1. package/LICENSE +18 -3
  2. package/dist/Strapi.d.ts +5 -1
  3. package/dist/Strapi.d.ts.map +1 -1
  4. package/dist/Strapi.js +467 -378
  5. package/dist/Strapi.js.map +1 -1
  6. package/dist/Strapi.mjs +461 -377
  7. package/dist/Strapi.mjs.map +1 -1
  8. package/dist/ai.d.ts +2 -0
  9. package/dist/ai.d.ts.map +1 -0
  10. package/dist/ai.js +8 -0
  11. package/dist/ai.js.map +1 -0
  12. package/dist/ai.mjs +3 -0
  13. package/dist/ai.mjs.map +1 -0
  14. package/dist/compile.d.ts.map +1 -1
  15. package/dist/compile.js +35 -14
  16. package/dist/compile.js.map +1 -1
  17. package/dist/compile.mjs +34 -14
  18. package/dist/compile.mjs.map +1 -1
  19. package/dist/configuration/config-loader.d.ts.map +1 -1
  20. package/dist/configuration/config-loader.js +115 -97
  21. package/dist/configuration/config-loader.js.map +1 -1
  22. package/dist/configuration/config-loader.mjs +109 -96
  23. package/dist/configuration/config-loader.mjs.map +1 -1
  24. package/dist/configuration/get-dirs.d.ts.map +1 -1
  25. package/dist/configuration/get-dirs.js +31 -29
  26. package/dist/configuration/get-dirs.js.map +1 -1
  27. package/dist/configuration/get-dirs.mjs +30 -30
  28. package/dist/configuration/get-dirs.mjs.map +1 -1
  29. package/dist/configuration/index.d.ts +25 -3
  30. package/dist/configuration/index.d.ts.map +1 -1
  31. package/dist/configuration/index.js +110 -69
  32. package/dist/configuration/index.js.map +1 -1
  33. package/dist/configuration/index.mjs +101 -64
  34. package/dist/configuration/index.mjs.map +1 -1
  35. package/dist/configuration/server-config.d.ts +11 -0
  36. package/dist/configuration/server-config.d.ts.map +1 -0
  37. package/dist/configuration/server-config.js +16 -0
  38. package/dist/configuration/server-config.js.map +1 -0
  39. package/dist/configuration/server-config.mjs +14 -0
  40. package/dist/configuration/server-config.mjs.map +1 -0
  41. package/dist/configuration/urls.d.ts.map +1 -1
  42. package/dist/configuration/urls.js +78 -61
  43. package/dist/configuration/urls.js.map +1 -1
  44. package/dist/configuration/urls.mjs +73 -62
  45. package/dist/configuration/urls.mjs.map +1 -1
  46. package/dist/constants.d.ts +3 -0
  47. package/dist/constants.d.ts.map +1 -0
  48. package/dist/constants.js +6 -0
  49. package/dist/constants.js.map +1 -0
  50. package/dist/constants.mjs +4 -0
  51. package/dist/constants.mjs.map +1 -0
  52. package/dist/container.js +27 -23
  53. package/dist/container.js.map +1 -1
  54. package/dist/container.mjs +26 -24
  55. package/dist/container.mjs.map +1 -1
  56. package/dist/core-api/controller/collection-type.d.ts.map +1 -1
  57. package/dist/core-api/controller/collection-type.js +77 -76
  58. package/dist/core-api/controller/collection-type.js.map +1 -1
  59. package/dist/core-api/controller/collection-type.mjs +76 -77
  60. package/dist/core-api/controller/collection-type.mjs.map +1 -1
  61. package/dist/core-api/controller/index.d.ts.map +1 -1
  62. package/dist/core-api/controller/index.js +65 -48
  63. package/dist/core-api/controller/index.js.map +1 -1
  64. package/dist/core-api/controller/index.mjs +64 -49
  65. package/dist/core-api/controller/index.mjs.map +1 -1
  66. package/dist/core-api/controller/single-type.d.ts.map +1 -1
  67. package/dist/core-api/controller/single-type.js +41 -40
  68. package/dist/core-api/controller/single-type.js.map +1 -1
  69. package/dist/core-api/controller/single-type.mjs +40 -41
  70. package/dist/core-api/controller/single-type.mjs.map +1 -1
  71. package/dist/core-api/controller/transform.d.ts +3 -2
  72. package/dist/core-api/controller/transform.d.ts.map +1 -1
  73. package/dist/core-api/controller/transform.js +83 -64
  74. package/dist/core-api/controller/transform.js.map +1 -1
  75. package/dist/core-api/controller/transform.mjs +82 -65
  76. package/dist/core-api/controller/transform.mjs.map +1 -1
  77. package/dist/core-api/routes/index.d.ts +4 -22
  78. package/dist/core-api/routes/index.d.ts.map +1 -1
  79. package/dist/core-api/routes/index.js +221 -61
  80. package/dist/core-api/routes/index.js.map +1 -1
  81. package/dist/core-api/routes/index.mjs +200 -62
  82. package/dist/core-api/routes/index.mjs.map +1 -1
  83. package/dist/core-api/routes/validation/attributes.d.ts +244 -0
  84. package/dist/core-api/routes/validation/attributes.d.ts.map +1 -0
  85. package/dist/core-api/routes/validation/attributes.js +560 -0
  86. package/dist/core-api/routes/validation/attributes.js.map +1 -0
  87. package/dist/core-api/routes/validation/attributes.mjs +521 -0
  88. package/dist/core-api/routes/validation/attributes.mjs.map +1 -0
  89. package/dist/core-api/routes/validation/common.d.ts +105 -0
  90. package/dist/core-api/routes/validation/common.d.ts.map +1 -0
  91. package/dist/core-api/routes/validation/common.js +117 -0
  92. package/dist/core-api/routes/validation/common.js.map +1 -0
  93. package/dist/core-api/routes/validation/common.mjs +95 -0
  94. package/dist/core-api/routes/validation/common.mjs.map +1 -0
  95. package/dist/core-api/routes/validation/component.d.ts +34 -0
  96. package/dist/core-api/routes/validation/component.d.ts.map +1 -0
  97. package/dist/core-api/routes/validation/component.js +45 -0
  98. package/dist/core-api/routes/validation/component.js.map +1 -0
  99. package/dist/core-api/routes/validation/component.mjs +43 -0
  100. package/dist/core-api/routes/validation/component.mjs.map +1 -0
  101. package/dist/core-api/routes/validation/constants.d.ts +8 -0
  102. package/dist/core-api/routes/validation/constants.d.ts.map +1 -0
  103. package/dist/core-api/routes/validation/constants.js +18 -0
  104. package/dist/core-api/routes/validation/constants.js.map +1 -0
  105. package/dist/core-api/routes/validation/constants.mjs +16 -0
  106. package/dist/core-api/routes/validation/constants.mjs.map +1 -0
  107. package/dist/core-api/routes/validation/content-type.d.ts +144 -0
  108. package/dist/core-api/routes/validation/content-type.d.ts.map +1 -0
  109. package/dist/core-api/routes/validation/content-type.js +228 -0
  110. package/dist/core-api/routes/validation/content-type.js.map +1 -0
  111. package/dist/core-api/routes/validation/content-type.mjs +206 -0
  112. package/dist/core-api/routes/validation/content-type.mjs.map +1 -0
  113. package/dist/core-api/routes/validation/index.d.ts +5 -0
  114. package/dist/core-api/routes/validation/index.d.ts.map +1 -0
  115. package/dist/core-api/routes/validation/mappers.d.ts +105 -0
  116. package/dist/core-api/routes/validation/mappers.d.ts.map +1 -0
  117. package/dist/core-api/routes/validation/mappers.js +266 -0
  118. package/dist/core-api/routes/validation/mappers.js.map +1 -0
  119. package/dist/core-api/routes/validation/mappers.mjs +241 -0
  120. package/dist/core-api/routes/validation/mappers.mjs.map +1 -0
  121. package/dist/core-api/routes/validation/utils.d.ts +47 -0
  122. package/dist/core-api/routes/validation/utils.d.ts.map +1 -0
  123. package/dist/core-api/routes/validation/utils.js +126 -0
  124. package/dist/core-api/routes/validation/utils.js.map +1 -0
  125. package/dist/core-api/routes/validation/utils.mjs +103 -0
  126. package/dist/core-api/routes/validation/utils.mjs.map +1 -0
  127. package/dist/core-api/service/collection-type.d.ts +2 -2
  128. package/dist/core-api/service/collection-type.d.ts.map +1 -1
  129. package/dist/core-api/service/collection-type.js +73 -60
  130. package/dist/core-api/service/collection-type.js.map +1 -1
  131. package/dist/core-api/service/collection-type.mjs +72 -62
  132. package/dist/core-api/service/collection-type.mjs.map +1 -1
  133. package/dist/core-api/service/core-service.js +9 -8
  134. package/dist/core-api/service/core-service.js.map +1 -1
  135. package/dist/core-api/service/core-service.mjs +8 -9
  136. package/dist/core-api/service/core-service.mjs.map +1 -1
  137. package/dist/core-api/service/index.js +13 -13
  138. package/dist/core-api/service/index.js.map +1 -1
  139. package/dist/core-api/service/index.mjs +12 -14
  140. package/dist/core-api/service/index.mjs.map +1 -1
  141. package/dist/core-api/service/pagination.d.ts.map +1 -1
  142. package/dist/core-api/service/pagination.js +69 -43
  143. package/dist/core-api/service/pagination.js.map +1 -1
  144. package/dist/core-api/service/pagination.mjs +68 -47
  145. package/dist/core-api/service/pagination.mjs.map +1 -1
  146. package/dist/core-api/service/single-type.d.ts.map +1 -1
  147. package/dist/core-api/service/single-type.js +43 -39
  148. package/dist/core-api/service/single-type.js.map +1 -1
  149. package/dist/core-api/service/single-type.mjs +42 -41
  150. package/dist/core-api/service/single-type.mjs.map +1 -1
  151. package/dist/domain/content-type/index.d.ts.map +1 -1
  152. package/dist/domain/content-type/index.js +114 -99
  153. package/dist/domain/content-type/index.js.map +1 -1
  154. package/dist/domain/content-type/index.mjs +109 -99
  155. package/dist/domain/content-type/index.mjs.map +1 -1
  156. package/dist/domain/content-type/validator.d.ts.map +1 -1
  157. package/dist/domain/content-type/validator.js +88 -69
  158. package/dist/domain/content-type/validator.js.map +1 -1
  159. package/dist/domain/content-type/validator.mjs +83 -68
  160. package/dist/domain/content-type/validator.mjs.map +1 -1
  161. package/dist/domain/module/index.d.ts.map +1 -1
  162. package/dist/domain/module/index.js +116 -100
  163. package/dist/domain/module/index.js.map +1 -1
  164. package/dist/domain/module/index.mjs +111 -99
  165. package/dist/domain/module/index.mjs.map +1 -1
  166. package/dist/domain/module/validation.d.ts.map +1 -1
  167. package/dist/domain/module/validation.js +25 -20
  168. package/dist/domain/module/validation.js.map +1 -1
  169. package/dist/domain/module/validation.mjs +24 -21
  170. package/dist/domain/module/validation.mjs.map +1 -1
  171. package/dist/ee/index.d.ts +11 -1
  172. package/dist/ee/index.d.ts.map +1 -1
  173. package/dist/ee/index.js +203 -132
  174. package/dist/ee/index.js.map +1 -1
  175. package/dist/ee/index.mjs +202 -134
  176. package/dist/ee/index.mjs.map +1 -1
  177. package/dist/ee/license.d.ts +5 -1
  178. package/dist/ee/license.d.ts.map +1 -1
  179. package/dist/ee/license.js +109 -75
  180. package/dist/ee/license.js.map +1 -1
  181. package/dist/ee/license.mjs +102 -76
  182. package/dist/ee/license.mjs.map +1 -1
  183. package/dist/factories.d.ts +3 -1
  184. package/dist/factories.d.ts.map +1 -1
  185. package/dist/factories.js +80 -67
  186. package/dist/factories.js.map +1 -1
  187. package/dist/factories.mjs +77 -70
  188. package/dist/factories.mjs.map +1 -1
  189. package/dist/index.d.ts +19 -1
  190. package/dist/index.d.ts.map +1 -1
  191. package/dist/index.js +31 -26
  192. package/dist/index.js.map +1 -1
  193. package/dist/index.mjs +31 -29
  194. package/dist/index.mjs.map +1 -1
  195. package/dist/loaders/admin.d.ts.map +1 -1
  196. package/dist/loaders/admin.js +25 -20
  197. package/dist/loaders/admin.js.map +1 -1
  198. package/dist/loaders/admin.mjs +20 -20
  199. package/dist/loaders/admin.mjs.map +1 -1
  200. package/dist/loaders/apis.js +148 -120
  201. package/dist/loaders/apis.js.map +1 -1
  202. package/dist/loaders/apis.mjs +142 -119
  203. package/dist/loaders/apis.mjs.map +1 -1
  204. package/dist/loaders/components.js +37 -34
  205. package/dist/loaders/components.js.map +1 -1
  206. package/dist/loaders/components.mjs +32 -34
  207. package/dist/loaders/components.mjs.map +1 -1
  208. package/dist/loaders/index.js +22 -20
  209. package/dist/loaders/index.js.map +1 -1
  210. package/dist/loaders/index.mjs +21 -21
  211. package/dist/loaders/index.mjs.map +1 -1
  212. package/dist/loaders/middlewares.js +33 -25
  213. package/dist/loaders/middlewares.js.map +1 -1
  214. package/dist/loaders/middlewares.mjs +28 -25
  215. package/dist/loaders/middlewares.mjs.map +1 -1
  216. package/dist/loaders/plugins/get-enabled-plugins.d.ts.map +1 -1
  217. package/dist/loaders/plugins/get-enabled-plugins.js +129 -102
  218. package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
  219. package/dist/loaders/plugins/get-enabled-plugins.mjs +124 -101
  220. package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
  221. package/dist/loaders/plugins/get-user-plugins-config.js +29 -24
  222. package/dist/loaders/plugins/get-user-plugins-config.js.map +1 -1
  223. package/dist/loaders/plugins/get-user-plugins-config.mjs +24 -23
  224. package/dist/loaders/plugins/get-user-plugins-config.mjs.map +1 -1
  225. package/dist/loaders/plugins/index.d.ts.map +1 -1
  226. package/dist/loaders/plugins/index.js +155 -104
  227. package/dist/loaders/plugins/index.js.map +1 -1
  228. package/dist/loaders/plugins/index.mjs +131 -104
  229. package/dist/loaders/plugins/index.mjs.map +1 -1
  230. package/dist/loaders/policies.js +28 -20
  231. package/dist/loaders/policies.js.map +1 -1
  232. package/dist/loaders/policies.mjs +23 -20
  233. package/dist/loaders/policies.mjs.map +1 -1
  234. package/dist/loaders/sanitizers.d.ts.map +1 -1
  235. package/dist/loaders/sanitizers.js +10 -4
  236. package/dist/loaders/sanitizers.js.map +1 -1
  237. package/dist/loaders/sanitizers.mjs +9 -6
  238. package/dist/loaders/sanitizers.mjs.map +1 -1
  239. package/dist/loaders/src-index.d.ts.map +1 -1
  240. package/dist/loaders/src-index.js +35 -27
  241. package/dist/loaders/src-index.js.map +1 -1
  242. package/dist/loaders/src-index.mjs +34 -29
  243. package/dist/loaders/src-index.mjs.map +1 -1
  244. package/dist/loaders/validators.d.ts.map +1 -1
  245. package/dist/loaders/validators.js +9 -4
  246. package/dist/loaders/validators.js.map +1 -1
  247. package/dist/loaders/validators.mjs +8 -6
  248. package/dist/loaders/validators.mjs.map +1 -1
  249. package/dist/mcp.d.ts +4 -0
  250. package/dist/mcp.d.ts.map +1 -0
  251. package/dist/mcp.js +12 -0
  252. package/dist/mcp.js.map +1 -0
  253. package/dist/mcp.mjs +4 -0
  254. package/dist/mcp.mjs.map +1 -0
  255. package/dist/middlewares/body.d.ts.map +1 -1
  256. package/dist/middlewares/body.js +63 -54
  257. package/dist/middlewares/body.js.map +1 -1
  258. package/dist/middlewares/body.mjs +57 -51
  259. package/dist/middlewares/body.mjs.map +1 -1
  260. package/dist/middlewares/compression.js +10 -6
  261. package/dist/middlewares/compression.js.map +1 -1
  262. package/dist/middlewares/compression.mjs +5 -5
  263. package/dist/middlewares/compression.mjs.map +1 -1
  264. package/dist/middlewares/cors.d.ts +9 -1
  265. package/dist/middlewares/cors.d.ts.map +1 -1
  266. package/dist/middlewares/cors.js +85 -44
  267. package/dist/middlewares/cors.js.map +1 -1
  268. package/dist/middlewares/cors.mjs +78 -42
  269. package/dist/middlewares/cors.mjs.map +1 -1
  270. package/dist/middlewares/errors.d.ts +5 -0
  271. package/dist/middlewares/errors.d.ts.map +1 -1
  272. package/dist/middlewares/errors.js +32 -30
  273. package/dist/middlewares/errors.js.map +1 -1
  274. package/dist/middlewares/errors.mjs +31 -31
  275. package/dist/middlewares/errors.mjs.map +1 -1
  276. package/dist/middlewares/favicon.d.ts +0 -1
  277. package/dist/middlewares/favicon.d.ts.map +1 -1
  278. package/dist/middlewares/favicon.js +30 -17
  279. package/dist/middlewares/favicon.js.map +1 -1
  280. package/dist/middlewares/favicon.mjs +25 -16
  281. package/dist/middlewares/favicon.mjs.map +1 -1
  282. package/dist/middlewares/index.js +32 -30
  283. package/dist/middlewares/index.js.map +1 -1
  284. package/dist/middlewares/index.mjs +31 -31
  285. package/dist/middlewares/index.mjs.map +1 -1
  286. package/dist/middlewares/ip.js +10 -6
  287. package/dist/middlewares/ip.js.map +1 -1
  288. package/dist/middlewares/ip.mjs +5 -5
  289. package/dist/middlewares/ip.mjs.map +1 -1
  290. package/dist/middlewares/logger.js +10 -9
  291. package/dist/middlewares/logger.js.map +1 -1
  292. package/dist/middlewares/logger.mjs +9 -10
  293. package/dist/middlewares/logger.mjs.map +1 -1
  294. package/dist/middlewares/powered-by.js +13 -9
  295. package/dist/middlewares/powered-by.js.map +1 -1
  296. package/dist/middlewares/powered-by.mjs +12 -10
  297. package/dist/middlewares/powered-by.mjs.map +1 -1
  298. package/dist/middlewares/public.js +37 -29
  299. package/dist/middlewares/public.js.map +1 -1
  300. package/dist/middlewares/public.mjs +32 -28
  301. package/dist/middlewares/public.mjs.map +1 -1
  302. package/dist/middlewares/query.d.ts.map +1 -1
  303. package/dist/middlewares/query.js +39 -32
  304. package/dist/middlewares/query.js.map +1 -1
  305. package/dist/middlewares/query.mjs +34 -31
  306. package/dist/middlewares/query.mjs.map +1 -1
  307. package/dist/middlewares/response-time.js +10 -9
  308. package/dist/middlewares/response-time.js.map +1 -1
  309. package/dist/middlewares/response-time.mjs +9 -10
  310. package/dist/middlewares/response-time.mjs.map +1 -1
  311. package/dist/middlewares/responses.js +14 -12
  312. package/dist/middlewares/responses.js.map +1 -1
  313. package/dist/middlewares/responses.mjs +13 -13
  314. package/dist/middlewares/responses.mjs.map +1 -1
  315. package/dist/middlewares/security.d.ts.map +1 -1
  316. package/dist/middlewares/security.js +100 -71
  317. package/dist/middlewares/security.js.map +1 -1
  318. package/dist/middlewares/security.mjs +95 -70
  319. package/dist/middlewares/security.mjs.map +1 -1
  320. package/dist/middlewares/session.d.ts +2 -2
  321. package/dist/middlewares/session.d.ts.map +1 -1
  322. package/dist/middlewares/session.js +26 -25
  323. package/dist/middlewares/session.js.map +1 -1
  324. package/dist/middlewares/session.mjs +25 -24
  325. package/dist/middlewares/session.mjs.map +1 -1
  326. package/dist/migrations/database/5.0.0-discard-drafts.d.ts +29 -11
  327. package/dist/migrations/database/5.0.0-discard-drafts.d.ts.map +1 -1
  328. package/dist/migrations/database/5.0.0-discard-drafts.js +2563 -35
  329. package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
  330. package/dist/migrations/database/5.0.0-discard-drafts.mjs +2558 -37
  331. package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
  332. package/dist/migrations/draft-publish.d.ts +2 -2
  333. package/dist/migrations/draft-publish.d.ts.map +1 -1
  334. package/dist/migrations/draft-publish.js +61 -34
  335. package/dist/migrations/draft-publish.js.map +1 -1
  336. package/dist/migrations/draft-publish.mjs +60 -36
  337. package/dist/migrations/draft-publish.mjs.map +1 -1
  338. package/dist/migrations/first-published-at.d.ts +4 -0
  339. package/dist/migrations/first-published-at.d.ts.map +1 -0
  340. package/dist/migrations/first-published-at.js +55 -0
  341. package/dist/migrations/first-published-at.js.map +1 -0
  342. package/dist/migrations/first-published-at.mjs +49 -0
  343. package/dist/migrations/first-published-at.mjs.map +1 -0
  344. package/dist/migrations/i18n.d.ts +5 -0
  345. package/dist/migrations/i18n.d.ts.map +1 -0
  346. package/dist/migrations/i18n.js +71 -0
  347. package/dist/migrations/i18n.js.map +1 -0
  348. package/dist/migrations/i18n.mjs +68 -0
  349. package/dist/migrations/i18n.mjs.map +1 -0
  350. package/dist/migrations/index.d.ts +5 -0
  351. package/dist/migrations/index.d.ts.map +1 -0
  352. package/dist/migrations/index.js +34 -0
  353. package/dist/migrations/index.js.map +1 -0
  354. package/dist/migrations/index.mjs +31 -0
  355. package/dist/migrations/index.mjs.map +1 -0
  356. package/dist/package.json.js +191 -0
  357. package/dist/package.json.js.map +1 -0
  358. package/dist/package.json.mjs +168 -0
  359. package/dist/package.json.mjs.map +1 -0
  360. package/dist/providers/admin.d.ts.map +1 -1
  361. package/dist/providers/admin.js +27 -17
  362. package/dist/providers/admin.js.map +1 -1
  363. package/dist/providers/admin.mjs +26 -19
  364. package/dist/providers/admin.mjs.map +1 -1
  365. package/dist/providers/ai.d.ts +3 -0
  366. package/dist/providers/ai.d.ts.map +1 -0
  367. package/dist/providers/ai.js +13 -0
  368. package/dist/providers/ai.js.map +1 -0
  369. package/dist/providers/ai.mjs +11 -0
  370. package/dist/providers/ai.mjs.map +1 -0
  371. package/dist/providers/coreStore.js +13 -8
  372. package/dist/providers/coreStore.js.map +1 -1
  373. package/dist/providers/coreStore.mjs +12 -10
  374. package/dist/providers/coreStore.mjs.map +1 -1
  375. package/dist/providers/cron.js +19 -16
  376. package/dist/providers/cron.js.map +1 -1
  377. package/dist/providers/cron.mjs +18 -18
  378. package/dist/providers/cron.mjs.map +1 -1
  379. package/dist/providers/index.d.ts.map +1 -1
  380. package/dist/providers/index.js +24 -9
  381. package/dist/providers/index.js.map +1 -1
  382. package/dist/providers/index.mjs +23 -10
  383. package/dist/providers/index.mjs.map +1 -1
  384. package/dist/providers/mcp.d.ts +3 -0
  385. package/dist/providers/mcp.d.ts.map +1 -0
  386. package/dist/providers/mcp.js +39 -0
  387. package/dist/providers/mcp.js.map +1 -0
  388. package/dist/providers/mcp.mjs +37 -0
  389. package/dist/providers/mcp.mjs.map +1 -0
  390. package/dist/providers/provider.d.ts.map +1 -1
  391. package/dist/providers/provider.js +4 -3
  392. package/dist/providers/provider.js.map +1 -1
  393. package/dist/providers/provider.mjs +3 -4
  394. package/dist/providers/provider.mjs.map +1 -1
  395. package/dist/providers/registries.js +37 -32
  396. package/dist/providers/registries.js.map +1 -1
  397. package/dist/providers/registries.mjs +36 -34
  398. package/dist/providers/registries.mjs.map +1 -1
  399. package/dist/providers/session-manager.d.ts +3 -0
  400. package/dist/providers/session-manager.d.ts.map +1 -0
  401. package/dist/providers/session-manager.js +25 -0
  402. package/dist/providers/session-manager.js.map +1 -0
  403. package/dist/providers/session-manager.mjs +23 -0
  404. package/dist/providers/session-manager.mjs.map +1 -0
  405. package/dist/providers/telemetry.js +19 -16
  406. package/dist/providers/telemetry.js.map +1 -1
  407. package/dist/providers/telemetry.mjs +18 -18
  408. package/dist/providers/telemetry.mjs.map +1 -1
  409. package/dist/providers/webhooks.js +28 -26
  410. package/dist/providers/webhooks.js.map +1 -1
  411. package/dist/providers/webhooks.mjs +27 -28
  412. package/dist/providers/webhooks.mjs.map +1 -1
  413. package/dist/registries/apis.d.ts.map +1 -1
  414. package/dist/registries/apis.js +23 -20
  415. package/dist/registries/apis.js.map +1 -1
  416. package/dist/registries/apis.mjs +22 -22
  417. package/dist/registries/apis.mjs.map +1 -1
  418. package/dist/registries/components.d.ts +1 -1
  419. package/dist/registries/components.d.ts.map +1 -1
  420. package/dist/registries/components.js +35 -37
  421. package/dist/registries/components.js.map +1 -1
  422. package/dist/registries/components.mjs +34 -39
  423. package/dist/registries/components.mjs.map +1 -1
  424. package/dist/registries/content-types.d.ts +2 -3
  425. package/dist/registries/content-types.d.ts.map +1 -1
  426. package/dist/registries/content-types.js +54 -59
  427. package/dist/registries/content-types.js.map +1 -1
  428. package/dist/registries/content-types.mjs +53 -61
  429. package/dist/registries/content-types.mjs.map +1 -1
  430. package/dist/registries/controllers.d.ts +3 -3
  431. package/dist/registries/controllers.d.ts.map +1 -1
  432. package/dist/registries/controllers.js +70 -71
  433. package/dist/registries/controllers.js.map +1 -1
  434. package/dist/registries/controllers.mjs +69 -73
  435. package/dist/registries/controllers.mjs.map +1 -1
  436. package/dist/registries/custom-fields.d.ts.map +1 -1
  437. package/dist/registries/custom-fields.js +75 -65
  438. package/dist/registries/custom-fields.js.map +1 -1
  439. package/dist/registries/custom-fields.mjs +74 -67
  440. package/dist/registries/custom-fields.mjs.map +1 -1
  441. package/dist/registries/hooks.d.ts +3 -4
  442. package/dist/registries/hooks.d.ts.map +1 -1
  443. package/dist/registries/hooks.js +46 -49
  444. package/dist/registries/hooks.js.map +1 -1
  445. package/dist/registries/hooks.mjs +45 -51
  446. package/dist/registries/hooks.mjs.map +1 -1
  447. package/dist/registries/middlewares.d.ts +2 -3
  448. package/dist/registries/middlewares.d.ts.map +1 -1
  449. package/dist/registries/middlewares.js +49 -51
  450. package/dist/registries/middlewares.js.map +1 -1
  451. package/dist/registries/middlewares.mjs +48 -53
  452. package/dist/registries/middlewares.mjs.map +1 -1
  453. package/dist/registries/models.d.ts +1 -1
  454. package/dist/registries/models.js +14 -13
  455. package/dist/registries/models.js.map +1 -1
  456. package/dist/registries/models.mjs +13 -14
  457. package/dist/registries/models.mjs.map +1 -1
  458. package/dist/registries/modules.d.ts.map +1 -1
  459. package/dist/registries/modules.js +39 -36
  460. package/dist/registries/modules.js.map +1 -1
  461. package/dist/registries/modules.mjs +38 -38
  462. package/dist/registries/modules.mjs.map +1 -1
  463. package/dist/registries/namespace.d.ts.map +1 -1
  464. package/dist/registries/namespace.js +21 -20
  465. package/dist/registries/namespace.js.map +1 -1
  466. package/dist/registries/namespace.mjs +20 -23
  467. package/dist/registries/namespace.mjs.map +1 -1
  468. package/dist/registries/plugins.d.ts.map +1 -1
  469. package/dist/registries/plugins.js +23 -20
  470. package/dist/registries/plugins.js.map +1 -1
  471. package/dist/registries/plugins.mjs +22 -22
  472. package/dist/registries/plugins.mjs.map +1 -1
  473. package/dist/registries/policies.d.ts +2 -3
  474. package/dist/registries/policies.d.ts.map +1 -1
  475. package/dist/registries/policies.js +103 -96
  476. package/dist/registries/policies.js.map +1 -1
  477. package/dist/registries/policies.mjs +102 -98
  478. package/dist/registries/policies.mjs.map +1 -1
  479. package/dist/registries/sanitizers.d.ts +2 -2
  480. package/dist/registries/sanitizers.js +27 -22
  481. package/dist/registries/sanitizers.js.map +1 -1
  482. package/dist/registries/sanitizers.mjs +22 -22
  483. package/dist/registries/sanitizers.mjs.map +1 -1
  484. package/dist/registries/services.d.ts +3 -3
  485. package/dist/registries/services.d.ts.map +1 -1
  486. package/dist/registries/services.js +71 -71
  487. package/dist/registries/services.js.map +1 -1
  488. package/dist/registries/services.mjs +70 -73
  489. package/dist/registries/services.mjs.map +1 -1
  490. package/dist/registries/validators.d.ts +2 -2
  491. package/dist/registries/validators.js +27 -22
  492. package/dist/registries/validators.js.map +1 -1
  493. package/dist/registries/validators.mjs +22 -22
  494. package/dist/registries/validators.mjs.map +1 -1
  495. package/dist/services/ai.d.ts +3 -0
  496. package/dist/services/ai.d.ts.map +1 -0
  497. package/dist/services/ai.js +13 -0
  498. package/dist/services/ai.js.map +1 -0
  499. package/dist/services/ai.mjs +11 -0
  500. package/dist/services/ai.mjs.map +1 -0
  501. package/dist/services/auth/index.js +78 -74
  502. package/dist/services/auth/index.js.map +1 -1
  503. package/dist/services/auth/index.mjs +73 -74
  504. package/dist/services/auth/index.mjs.map +1 -1
  505. package/dist/services/config.d.ts.map +1 -1
  506. package/dist/services/config.js +47 -43
  507. package/dist/services/config.js.map +1 -1
  508. package/dist/services/config.mjs +46 -44
  509. package/dist/services/config.mjs.map +1 -1
  510. package/dist/services/content-api/index.d.ts +15 -14
  511. package/dist/services/content-api/index.d.ts.map +1 -1
  512. package/dist/services/content-api/index.js +244 -77
  513. package/dist/services/content-api/index.js.map +1 -1
  514. package/dist/services/content-api/index.mjs +221 -78
  515. package/dist/services/content-api/index.mjs.map +1 -1
  516. package/dist/services/content-api/permissions/engine.d.ts.map +1 -1
  517. package/dist/services/content-api/permissions/engine.js +12 -5
  518. package/dist/services/content-api/permissions/engine.js.map +1 -1
  519. package/dist/services/content-api/permissions/engine.mjs +7 -5
  520. package/dist/services/content-api/permissions/engine.mjs.map +1 -1
  521. package/dist/services/content-api/permissions/index.d.ts +8 -10
  522. package/dist/services/content-api/permissions/index.d.ts.map +1 -1
  523. package/dist/services/content-api/permissions/index.js +105 -81
  524. package/dist/services/content-api/permissions/index.js.map +1 -1
  525. package/dist/services/content-api/permissions/index.mjs +100 -81
  526. package/dist/services/content-api/permissions/index.mjs.map +1 -1
  527. package/dist/services/content-api/permissions/providers/action.d.ts +4 -5
  528. package/dist/services/content-api/permissions/providers/action.d.ts.map +1 -1
  529. package/dist/services/content-api/permissions/providers/action.js +17 -14
  530. package/dist/services/content-api/permissions/providers/action.js.map +1 -1
  531. package/dist/services/content-api/permissions/providers/action.mjs +16 -16
  532. package/dist/services/content-api/permissions/providers/action.mjs.map +1 -1
  533. package/dist/services/content-api/permissions/providers/condition.d.ts +4 -5
  534. package/dist/services/content-api/permissions/providers/condition.d.ts.map +1 -1
  535. package/dist/services/content-api/permissions/providers/condition.js +17 -14
  536. package/dist/services/content-api/permissions/providers/condition.js.map +1 -1
  537. package/dist/services/content-api/permissions/providers/condition.mjs +16 -16
  538. package/dist/services/content-api/permissions/providers/condition.mjs.map +1 -1
  539. package/dist/services/content-source-maps.d.ts +13 -0
  540. package/dist/services/content-source-maps.d.ts.map +1 -0
  541. package/dist/services/content-source-maps.js +116 -0
  542. package/dist/services/content-source-maps.js.map +1 -0
  543. package/dist/services/content-source-maps.mjs +114 -0
  544. package/dist/services/content-source-maps.mjs.map +1 -0
  545. package/dist/services/core-store.d.ts +2 -2
  546. package/dist/services/core-store.d.ts.map +1 -1
  547. package/dist/services/core-store.js +115 -95
  548. package/dist/services/core-store.js.map +1 -1
  549. package/dist/services/core-store.mjs +114 -97
  550. package/dist/services/core-store.mjs.map +1 -1
  551. package/dist/services/cron.d.ts +8 -8
  552. package/dist/services/cron.d.ts.map +1 -1
  553. package/dist/services/cron.js +85 -60
  554. package/dist/services/cron.js.map +1 -1
  555. package/dist/services/cron.mjs +83 -61
  556. package/dist/services/cron.mjs.map +1 -1
  557. package/dist/services/custom-fields.d.ts.map +1 -1
  558. package/dist/services/custom-fields.js +9 -7
  559. package/dist/services/custom-fields.js.map +1 -1
  560. package/dist/services/custom-fields.mjs +8 -9
  561. package/dist/services/custom-fields.mjs.map +1 -1
  562. package/dist/services/document-service/attributes/index.d.ts +0 -1
  563. package/dist/services/document-service/attributes/index.d.ts.map +1 -1
  564. package/dist/services/document-service/attributes/index.js +23 -18
  565. package/dist/services/document-service/attributes/index.js.map +1 -1
  566. package/dist/services/document-service/attributes/index.mjs +22 -19
  567. package/dist/services/document-service/attributes/index.mjs.map +1 -1
  568. package/dist/services/document-service/attributes/transforms.js +20 -15
  569. package/dist/services/document-service/attributes/transforms.js.map +1 -1
  570. package/dist/services/document-service/attributes/transforms.mjs +15 -15
  571. package/dist/services/document-service/attributes/transforms.mjs.map +1 -1
  572. package/dist/services/document-service/common.d.ts +1 -1
  573. package/dist/services/document-service/common.d.ts.map +1 -1
  574. package/dist/services/document-service/common.js +5 -4
  575. package/dist/services/document-service/common.js.map +1 -1
  576. package/dist/services/document-service/common.mjs +4 -5
  577. package/dist/services/document-service/common.mjs.map +1 -1
  578. package/dist/services/document-service/components.d.ts +33 -3
  579. package/dist/services/document-service/components.d.ts.map +1 -1
  580. package/dist/services/document-service/components.js +368 -257
  581. package/dist/services/document-service/components.js.map +1 -1
  582. package/dist/services/document-service/components.mjs +359 -261
  583. package/dist/services/document-service/components.mjs.map +1 -1
  584. package/dist/services/document-service/draft-and-publish.d.ts +5 -6
  585. package/dist/services/document-service/draft-and-publish.d.ts.map +1 -1
  586. package/dist/services/document-service/draft-and-publish.js +94 -54
  587. package/dist/services/document-service/draft-and-publish.js.map +1 -1
  588. package/dist/services/document-service/draft-and-publish.mjs +87 -54
  589. package/dist/services/document-service/draft-and-publish.mjs.map +1 -1
  590. package/dist/services/document-service/entries.d.ts +3 -3
  591. package/dist/services/document-service/entries.d.ts.map +1 -1
  592. package/dist/services/document-service/entries.js +156 -92
  593. package/dist/services/document-service/entries.js.map +1 -1
  594. package/dist/services/document-service/entries.mjs +155 -93
  595. package/dist/services/document-service/entries.mjs.map +1 -1
  596. package/dist/services/document-service/events.d.ts +1 -1
  597. package/dist/services/document-service/events.d.ts.map +1 -1
  598. package/dist/services/document-service/events.js +48 -41
  599. package/dist/services/document-service/events.js.map +1 -1
  600. package/dist/services/document-service/events.mjs +47 -42
  601. package/dist/services/document-service/events.mjs.map +1 -1
  602. package/dist/services/document-service/first-published-at.d.ts +7 -0
  603. package/dist/services/document-service/first-published-at.d.ts.map +1 -0
  604. package/dist/services/document-service/first-published-at.js +41 -0
  605. package/dist/services/document-service/first-published-at.js.map +1 -0
  606. package/dist/services/document-service/first-published-at.mjs +38 -0
  607. package/dist/services/document-service/first-published-at.mjs.map +1 -0
  608. package/dist/services/document-service/index.d.ts +2 -1
  609. package/dist/services/document-service/index.d.ts.map +1 -1
  610. package/dist/services/document-service/index.js +53 -32
  611. package/dist/services/document-service/index.js.map +1 -1
  612. package/dist/services/document-service/index.mjs +52 -33
  613. package/dist/services/document-service/index.mjs.map +1 -1
  614. package/dist/services/document-service/internationalization.d.ts +10 -6
  615. package/dist/services/document-service/internationalization.d.ts.map +1 -1
  616. package/dist/services/document-service/internationalization.js +139 -50
  617. package/dist/services/document-service/internationalization.js.map +1 -1
  618. package/dist/services/document-service/internationalization.mjs +133 -50
  619. package/dist/services/document-service/internationalization.mjs.map +1 -1
  620. package/dist/services/document-service/middlewares/errors.js +23 -19
  621. package/dist/services/document-service/middlewares/errors.js.map +1 -1
  622. package/dist/services/document-service/middlewares/errors.mjs +22 -20
  623. package/dist/services/document-service/middlewares/errors.mjs.map +1 -1
  624. package/dist/services/document-service/middlewares/middleware-manager.d.ts.map +1 -1
  625. package/dist/services/document-service/middlewares/middleware-manager.js +46 -44
  626. package/dist/services/document-service/middlewares/middleware-manager.js.map +1 -1
  627. package/dist/services/document-service/middlewares/middleware-manager.mjs +45 -45
  628. package/dist/services/document-service/middlewares/middleware-manager.mjs.map +1 -1
  629. package/dist/services/document-service/params.d.ts +25 -1
  630. package/dist/services/document-service/params.d.ts.map +1 -1
  631. package/dist/services/document-service/params.js +44 -5
  632. package/dist/services/document-service/params.js.map +1 -1
  633. package/dist/services/document-service/params.mjs +40 -6
  634. package/dist/services/document-service/params.mjs.map +1 -1
  635. package/dist/services/document-service/publication-filter.d.ts +6 -0
  636. package/dist/services/document-service/publication-filter.d.ts.map +1 -0
  637. package/dist/services/document-service/publication-filter.js +20 -0
  638. package/dist/services/document-service/publication-filter.js.map +1 -0
  639. package/dist/services/document-service/publication-filter.mjs +15 -0
  640. package/dist/services/document-service/publication-filter.mjs.map +1 -0
  641. package/dist/services/document-service/repository.d.ts.map +1 -1
  642. package/dist/services/document-service/repository.js +550 -269
  643. package/dist/services/document-service/repository.js.map +1 -1
  644. package/dist/services/document-service/repository.mjs +549 -270
  645. package/dist/services/document-service/repository.mjs.map +1 -1
  646. package/dist/services/document-service/transform/data.d.ts +2 -0
  647. package/dist/services/document-service/transform/data.d.ts.map +1 -1
  648. package/dist/services/document-service/transform/data.js +35 -12
  649. package/dist/services/document-service/transform/data.js.map +1 -1
  650. package/dist/services/document-service/transform/data.mjs +32 -12
  651. package/dist/services/document-service/transform/data.mjs.map +1 -1
  652. package/dist/services/document-service/transform/fields.d.ts.map +1 -1
  653. package/dist/services/document-service/transform/fields.js +26 -17
  654. package/dist/services/document-service/transform/fields.js.map +1 -1
  655. package/dist/services/document-service/transform/fields.mjs +25 -18
  656. package/dist/services/document-service/transform/fields.mjs.map +1 -1
  657. package/dist/services/document-service/transform/id-map.d.ts +1 -1
  658. package/dist/services/document-service/transform/id-map.d.ts.map +1 -1
  659. package/dist/services/document-service/transform/id-map.js +119 -69
  660. package/dist/services/document-service/transform/id-map.js.map +1 -1
  661. package/dist/services/document-service/transform/id-map.mjs +118 -70
  662. package/dist/services/document-service/transform/id-map.mjs.map +1 -1
  663. package/dist/services/document-service/transform/id-transform.d.ts +1 -2
  664. package/dist/services/document-service/transform/id-transform.d.ts.map +1 -1
  665. package/dist/services/document-service/transform/id-transform.js +38 -30
  666. package/dist/services/document-service/transform/id-transform.js.map +1 -1
  667. package/dist/services/document-service/transform/id-transform.mjs +36 -30
  668. package/dist/services/document-service/transform/id-transform.mjs.map +1 -1
  669. package/dist/services/document-service/transform/populate.d.ts.map +1 -1
  670. package/dist/services/document-service/transform/populate.js +23 -18
  671. package/dist/services/document-service/transform/populate.js.map +1 -1
  672. package/dist/services/document-service/transform/populate.mjs +22 -19
  673. package/dist/services/document-service/transform/populate.mjs.map +1 -1
  674. package/dist/services/document-service/transform/query.d.ts +1 -2
  675. package/dist/services/document-service/transform/query.d.ts.map +1 -1
  676. package/dist/services/document-service/transform/query.js +60 -6
  677. package/dist/services/document-service/transform/query.js.map +1 -1
  678. package/dist/services/document-service/transform/query.mjs +59 -7
  679. package/dist/services/document-service/transform/query.mjs.map +1 -1
  680. package/dist/services/document-service/transform/relations/extract/data-ids.d.ts +1 -1
  681. package/dist/services/document-service/transform/relations/extract/data-ids.d.ts.map +1 -1
  682. package/dist/services/document-service/transform/relations/extract/data-ids.js +74 -48
  683. package/dist/services/document-service/transform/relations/extract/data-ids.js.map +1 -1
  684. package/dist/services/document-service/transform/relations/extract/data-ids.mjs +73 -49
  685. package/dist/services/document-service/transform/relations/extract/data-ids.mjs.map +1 -1
  686. package/dist/services/document-service/transform/relations/transform/data-ids.d.ts.map +1 -1
  687. package/dist/services/document-service/transform/relations/transform/data-ids.js +100 -63
  688. package/dist/services/document-service/transform/relations/transform/data-ids.js.map +1 -1
  689. package/dist/services/document-service/transform/relations/transform/data-ids.mjs +99 -64
  690. package/dist/services/document-service/transform/relations/transform/data-ids.mjs.map +1 -1
  691. package/dist/services/document-service/transform/relations/transform/default-locale.d.ts.map +1 -1
  692. package/dist/services/document-service/transform/relations/transform/default-locale.js +47 -29
  693. package/dist/services/document-service/transform/relations/transform/default-locale.js.map +1 -1
  694. package/dist/services/document-service/transform/relations/transform/default-locale.mjs +46 -30
  695. package/dist/services/document-service/transform/relations/transform/default-locale.mjs.map +1 -1
  696. package/dist/services/document-service/transform/relations/utils/data.d.ts.map +1 -1
  697. package/dist/services/document-service/transform/relations/utils/dp.d.ts +2 -2
  698. package/dist/services/document-service/transform/relations/utils/dp.d.ts.map +1 -1
  699. package/dist/services/document-service/transform/relations/utils/dp.js +52 -26
  700. package/dist/services/document-service/transform/relations/utils/dp.js.map +1 -1
  701. package/dist/services/document-service/transform/relations/utils/dp.mjs +51 -27
  702. package/dist/services/document-service/transform/relations/utils/dp.mjs.map +1 -1
  703. package/dist/services/document-service/transform/relations/utils/i18n.d.ts +1 -1
  704. package/dist/services/document-service/transform/relations/utils/i18n.d.ts.map +1 -1
  705. package/dist/services/document-service/transform/relations/utils/i18n.js +20 -18
  706. package/dist/services/document-service/transform/relations/utils/i18n.js.map +1 -1
  707. package/dist/services/document-service/transform/relations/utils/i18n.mjs +19 -21
  708. package/dist/services/document-service/transform/relations/utils/i18n.mjs.map +1 -1
  709. package/dist/services/document-service/transform/relations/utils/map-relation.d.ts +0 -1
  710. package/dist/services/document-service/transform/relations/utils/map-relation.d.ts.map +1 -1
  711. package/dist/services/document-service/transform/relations/utils/map-relation.js +122 -79
  712. package/dist/services/document-service/transform/relations/utils/map-relation.js.map +1 -1
  713. package/dist/services/document-service/transform/relations/utils/map-relation.mjs +119 -79
  714. package/dist/services/document-service/transform/relations/utils/map-relation.mjs.map +1 -1
  715. package/dist/services/document-service/transform/relations/utils/xto-one.d.ts +8 -0
  716. package/dist/services/document-service/transform/relations/utils/xto-one.d.ts.map +1 -0
  717. package/dist/services/document-service/transform/relations/utils/xto-one.js +41 -0
  718. package/dist/services/document-service/transform/relations/utils/xto-one.js.map +1 -0
  719. package/dist/services/document-service/transform/relations/utils/xto-one.mjs +39 -0
  720. package/dist/services/document-service/transform/relations/utils/xto-one.mjs.map +1 -0
  721. package/dist/services/document-service/utils/bidirectional-relations.d.ts +101 -0
  722. package/dist/services/document-service/utils/bidirectional-relations.d.ts.map +1 -0
  723. package/dist/services/document-service/utils/bidirectional-relations.js +265 -0
  724. package/dist/services/document-service/utils/bidirectional-relations.js.map +1 -0
  725. package/dist/services/document-service/utils/bidirectional-relations.mjs +262 -0
  726. package/dist/services/document-service/utils/bidirectional-relations.mjs.map +1 -0
  727. package/dist/services/document-service/utils/clean-component-join-table.d.ts +7 -0
  728. package/dist/services/document-service/utils/clean-component-join-table.d.ts.map +1 -0
  729. package/dist/services/document-service/utils/clean-component-join-table.js +145 -0
  730. package/dist/services/document-service/utils/clean-component-join-table.js.map +1 -0
  731. package/dist/services/document-service/utils/clean-component-join-table.mjs +143 -0
  732. package/dist/services/document-service/utils/clean-component-join-table.mjs.map +1 -0
  733. package/dist/services/document-service/utils/ordered-parallel.d.ts +5 -0
  734. package/dist/services/document-service/utils/ordered-parallel.d.ts.map +1 -0
  735. package/dist/services/document-service/utils/ordered-parallel.js +18 -0
  736. package/dist/services/document-service/utils/ordered-parallel.js.map +1 -0
  737. package/dist/services/document-service/utils/ordered-parallel.mjs +16 -0
  738. package/dist/services/document-service/utils/ordered-parallel.mjs.map +1 -0
  739. package/dist/services/document-service/utils/populate.d.ts +2 -2
  740. package/dist/services/document-service/utils/populate.d.ts.map +1 -1
  741. package/dist/services/document-service/utils/populate.js +63 -37
  742. package/dist/services/document-service/utils/populate.js.map +1 -1
  743. package/dist/services/document-service/utils/populate.mjs +62 -38
  744. package/dist/services/document-service/utils/populate.mjs.map +1 -1
  745. package/dist/services/document-service/utils/self-referential-relations.d.ts +37 -0
  746. package/dist/services/document-service/utils/self-referential-relations.d.ts.map +1 -0
  747. package/dist/services/document-service/utils/self-referential-relations.js +111 -0
  748. package/dist/services/document-service/utils/self-referential-relations.js.map +1 -0
  749. package/dist/services/document-service/utils/self-referential-relations.mjs +108 -0
  750. package/dist/services/document-service/utils/self-referential-relations.mjs.map +1 -0
  751. package/dist/services/document-service/utils/unidirectional-relations.d.ts +53 -0
  752. package/dist/services/document-service/utils/unidirectional-relations.d.ts.map +1 -0
  753. package/dist/services/document-service/utils/unidirectional-relations.js +146 -0
  754. package/dist/services/document-service/utils/unidirectional-relations.js.map +1 -0
  755. package/dist/services/document-service/utils/unidirectional-relations.mjs +143 -0
  756. package/dist/services/document-service/utils/unidirectional-relations.mjs.map +1 -0
  757. package/dist/services/entity-service/index.d.ts.map +1 -1
  758. package/dist/services/entity-service/index.js +235 -161
  759. package/dist/services/entity-service/index.js.map +1 -1
  760. package/dist/services/entity-service/index.mjs +229 -160
  761. package/dist/services/entity-service/index.mjs.map +1 -1
  762. package/dist/services/entity-validator/blocks-validator.d.ts +1 -2
  763. package/dist/services/entity-validator/blocks-validator.d.ts.map +1 -1
  764. package/dist/services/entity-validator/blocks-validator.js +137 -104
  765. package/dist/services/entity-validator/blocks-validator.js.map +1 -1
  766. package/dist/services/entity-validator/blocks-validator.mjs +135 -105
  767. package/dist/services/entity-validator/blocks-validator.mjs.map +1 -1
  768. package/dist/services/entity-validator/index.d.ts +15 -1
  769. package/dist/services/entity-validator/index.d.ts.map +1 -1
  770. package/dist/services/entity-validator/index.js +372 -307
  771. package/dist/services/entity-validator/index.js.map +1 -1
  772. package/dist/services/entity-validator/index.mjs +366 -307
  773. package/dist/services/entity-validator/index.mjs.map +1 -1
  774. package/dist/services/entity-validator/validators.d.ts +37 -25
  775. package/dist/services/entity-validator/validators.d.ts.map +1 -1
  776. package/dist/services/entity-validator/validators.js +368 -122
  777. package/dist/services/entity-validator/validators.js.map +1 -1
  778. package/dist/services/entity-validator/validators.mjs +354 -119
  779. package/dist/services/entity-validator/validators.mjs.map +1 -1
  780. package/dist/services/errors.d.ts.map +1 -1
  781. package/dist/services/errors.js +69 -65
  782. package/dist/services/errors.js.map +1 -1
  783. package/dist/services/errors.mjs +64 -66
  784. package/dist/services/errors.mjs.map +1 -1
  785. package/dist/services/event-hub.js +82 -69
  786. package/dist/services/event-hub.js.map +1 -1
  787. package/dist/services/event-hub.mjs +81 -71
  788. package/dist/services/event-hub.mjs.map +1 -1
  789. package/dist/services/features.d.ts.map +1 -1
  790. package/dist/services/features.js +19 -14
  791. package/dist/services/features.js.map +1 -1
  792. package/dist/services/features.mjs +18 -15
  793. package/dist/services/features.mjs.map +1 -1
  794. package/dist/services/fs.d.ts.map +1 -1
  795. package/dist/services/fs.js +46 -40
  796. package/dist/services/fs.js.map +1 -1
  797. package/dist/services/fs.mjs +40 -39
  798. package/dist/services/fs.mjs.map +1 -1
  799. package/dist/services/mcp/authentication.d.ts +23 -0
  800. package/dist/services/mcp/authentication.d.ts.map +1 -0
  801. package/dist/services/mcp/authentication.js +45 -0
  802. package/dist/services/mcp/authentication.js.map +1 -0
  803. package/dist/services/mcp/authentication.mjs +43 -0
  804. package/dist/services/mcp/authentication.mjs.map +1 -0
  805. package/dist/services/mcp/handlers/handlePost.d.ts +4 -0
  806. package/dist/services/mcp/handlers/handlePost.d.ts.map +1 -0
  807. package/dist/services/mcp/handlers/handlePost.js +59 -0
  808. package/dist/services/mcp/handlers/handlePost.js.map +1 -0
  809. package/dist/services/mcp/handlers/handlePost.mjs +57 -0
  810. package/dist/services/mcp/handlers/handlePost.mjs.map +1 -0
  811. package/dist/services/mcp/handlers/types.d.ts +12 -0
  812. package/dist/services/mcp/handlers/types.d.ts.map +1 -0
  813. package/dist/services/mcp/index.d.ts +6 -0
  814. package/dist/services/mcp/index.d.ts.map +1 -0
  815. package/dist/services/mcp/index.js +101 -0
  816. package/dist/services/mcp/index.js.map +1 -0
  817. package/dist/services/mcp/index.mjs +99 -0
  818. package/dist/services/mcp/index.mjs.map +1 -0
  819. package/dist/services/mcp/internal/McpCapabilityDefinitionRegistry.d.ts +13 -0
  820. package/dist/services/mcp/internal/McpCapabilityDefinitionRegistry.d.ts.map +1 -0
  821. package/dist/services/mcp/internal/McpCapabilityDefinitionRegistry.js +53 -0
  822. package/dist/services/mcp/internal/McpCapabilityDefinitionRegistry.js.map +1 -0
  823. package/dist/services/mcp/internal/McpCapabilityDefinitionRegistry.mjs +51 -0
  824. package/dist/services/mcp/internal/McpCapabilityDefinitionRegistry.mjs.map +1 -0
  825. package/dist/services/mcp/internal/McpCapabilityRegistry.d.ts +43 -0
  826. package/dist/services/mcp/internal/McpCapabilityRegistry.d.ts.map +1 -0
  827. package/dist/services/mcp/internal/McpCapabilityRegistry.js +108 -0
  828. package/dist/services/mcp/internal/McpCapabilityRegistry.js.map +1 -0
  829. package/dist/services/mcp/internal/McpCapabilityRegistry.mjs +106 -0
  830. package/dist/services/mcp/internal/McpCapabilityRegistry.mjs.map +1 -0
  831. package/dist/services/mcp/internal/McpConfiguration.d.ts +11 -0
  832. package/dist/services/mcp/internal/McpConfiguration.d.ts.map +1 -0
  833. package/dist/services/mcp/internal/McpConfiguration.js +34 -0
  834. package/dist/services/mcp/internal/McpConfiguration.js.map +1 -0
  835. package/dist/services/mcp/internal/McpConfiguration.mjs +32 -0
  836. package/dist/services/mcp/internal/McpConfiguration.mjs.map +1 -0
  837. package/dist/services/mcp/internal/McpServerFactory.d.ts +37 -0
  838. package/dist/services/mcp/internal/McpServerFactory.d.ts.map +1 -0
  839. package/dist/services/mcp/internal/McpServerFactory.js +71 -0
  840. package/dist/services/mcp/internal/McpServerFactory.js.map +1 -0
  841. package/dist/services/mcp/internal/McpServerFactory.mjs +69 -0
  842. package/dist/services/mcp/internal/McpServerFactory.mjs.map +1 -0
  843. package/dist/services/mcp/internal/syncMcpSessionCapabilities.d.ts +21 -0
  844. package/dist/services/mcp/internal/syncMcpSessionCapabilities.d.ts.map +1 -0
  845. package/dist/services/mcp/internal/syncMcpSessionCapabilities.js +76 -0
  846. package/dist/services/mcp/internal/syncMcpSessionCapabilities.js.map +1 -0
  847. package/dist/services/mcp/internal/syncMcpSessionCapabilities.mjs +73 -0
  848. package/dist/services/mcp/internal/syncMcpSessionCapabilities.mjs.map +1 -0
  849. package/dist/services/mcp/metrics/metrics.d.ts +29 -0
  850. package/dist/services/mcp/metrics/metrics.d.ts.map +1 -0
  851. package/dist/services/mcp/metrics/metrics.js +97 -0
  852. package/dist/services/mcp/metrics/metrics.js.map +1 -0
  853. package/dist/services/mcp/metrics/metrics.mjs +88 -0
  854. package/dist/services/mcp/metrics/metrics.mjs.map +1 -0
  855. package/dist/services/mcp/metrics/normalizeMcpCapability.d.ts +11 -0
  856. package/dist/services/mcp/metrics/normalizeMcpCapability.d.ts.map +1 -0
  857. package/dist/services/mcp/metrics/normalizeMcpCapability.js +10 -0
  858. package/dist/services/mcp/metrics/normalizeMcpCapability.js.map +1 -0
  859. package/dist/services/mcp/metrics/normalizeMcpCapability.mjs +8 -0
  860. package/dist/services/mcp/metrics/normalizeMcpCapability.mjs.map +1 -0
  861. package/dist/services/mcp/metrics/wrapCapabilityHandlerForMetrics.d.ts +4 -0
  862. package/dist/services/mcp/metrics/wrapCapabilityHandlerForMetrics.d.ts.map +1 -0
  863. package/dist/services/mcp/metrics/wrapCapabilityHandlerForMetrics.js +27 -0
  864. package/dist/services/mcp/metrics/wrapCapabilityHandlerForMetrics.js.map +1 -0
  865. package/dist/services/mcp/metrics/wrapCapabilityHandlerForMetrics.mjs +25 -0
  866. package/dist/services/mcp/metrics/wrapCapabilityHandlerForMetrics.mjs.map +1 -0
  867. package/dist/services/mcp/middleware/oauthDiscoveryFallback.d.ts +3 -0
  868. package/dist/services/mcp/middleware/oauthDiscoveryFallback.d.ts.map +1 -0
  869. package/dist/services/mcp/middleware/oauthDiscoveryFallback.js +47 -0
  870. package/dist/services/mcp/middleware/oauthDiscoveryFallback.js.map +1 -0
  871. package/dist/services/mcp/middleware/oauthDiscoveryFallback.mjs +45 -0
  872. package/dist/services/mcp/middleware/oauthDiscoveryFallback.mjs.map +1 -0
  873. package/dist/services/mcp/prompt-registry.d.ts +44 -0
  874. package/dist/services/mcp/prompt-registry.d.ts.map +1 -0
  875. package/dist/services/mcp/prompt-registry.js +108 -0
  876. package/dist/services/mcp/prompt-registry.js.map +1 -0
  877. package/dist/services/mcp/prompt-registry.mjs +105 -0
  878. package/dist/services/mcp/prompt-registry.mjs.map +1 -0
  879. package/dist/services/mcp/resource-registry.d.ts +44 -0
  880. package/dist/services/mcp/resource-registry.d.ts.map +1 -0
  881. package/dist/services/mcp/resource-registry.js +98 -0
  882. package/dist/services/mcp/resource-registry.js.map +1 -0
  883. package/dist/services/mcp/resource-registry.mjs +95 -0
  884. package/dist/services/mcp/resource-registry.mjs.map +1 -0
  885. package/dist/services/mcp/routes.d.ts +11 -0
  886. package/dist/services/mcp/routes.d.ts.map +1 -0
  887. package/dist/services/mcp/routes.js +58 -0
  888. package/dist/services/mcp/routes.js.map +1 -0
  889. package/dist/services/mcp/routes.mjs +56 -0
  890. package/dist/services/mcp/routes.mjs.map +1 -0
  891. package/dist/services/mcp/tool-registry.d.ts +52 -0
  892. package/dist/services/mcp/tool-registry.d.ts.map +1 -0
  893. package/dist/services/mcp/tool-registry.js +134 -0
  894. package/dist/services/mcp/tool-registry.js.map +1 -0
  895. package/dist/services/mcp/tool-registry.mjs +131 -0
  896. package/dist/services/mcp/tool-registry.mjs.map +1 -0
  897. package/dist/services/mcp/tools/log.d.ts +17 -0
  898. package/dist/services/mcp/tools/log.d.ts.map +1 -0
  899. package/dist/services/mcp/tools/log.js +88 -0
  900. package/dist/services/mcp/tools/log.js.map +1 -0
  901. package/dist/services/mcp/tools/log.mjs +86 -0
  902. package/dist/services/mcp/tools/log.mjs.map +1 -0
  903. package/dist/services/mcp/utils/createSafeCapabilityRegistration.d.ts +36 -0
  904. package/dist/services/mcp/utils/createSafeCapabilityRegistration.d.ts.map +1 -0
  905. package/dist/services/mcp/utils/createSafeCapabilityRegistration.js +59 -0
  906. package/dist/services/mcp/utils/createSafeCapabilityRegistration.js.map +1 -0
  907. package/dist/services/mcp/utils/createSafeCapabilityRegistration.mjs +56 -0
  908. package/dist/services/mcp/utils/createSafeCapabilityRegistration.mjs.map +1 -0
  909. package/dist/services/mcp/utils/jsonRpcErrors.d.ts +22 -0
  910. package/dist/services/mcp/utils/jsonRpcErrors.d.ts.map +1 -0
  911. package/dist/services/mcp/utils/jsonRpcErrors.js +25 -0
  912. package/dist/services/mcp/utils/jsonRpcErrors.js.map +1 -0
  913. package/dist/services/mcp/utils/jsonRpcErrors.mjs +23 -0
  914. package/dist/services/mcp/utils/jsonRpcErrors.mjs.map +1 -0
  915. package/dist/services/mcp/utils/safeHandlerWrapper.d.ts +18 -0
  916. package/dist/services/mcp/utils/safeHandlerWrapper.d.ts.map +1 -0
  917. package/dist/services/mcp/utils/safeHandlerWrapper.js +29 -0
  918. package/dist/services/mcp/utils/safeHandlerWrapper.js.map +1 -0
  919. package/dist/services/mcp/utils/safeHandlerWrapper.mjs +27 -0
  920. package/dist/services/mcp/utils/safeHandlerWrapper.mjs.map +1 -0
  921. package/dist/services/mcp/utils/sendJsonRpcError.d.ts +4 -0
  922. package/dist/services/mcp/utils/sendJsonRpcError.d.ts.map +1 -0
  923. package/dist/services/mcp/utils/sendJsonRpcError.js +23 -0
  924. package/dist/services/mcp/utils/sendJsonRpcError.js.map +1 -0
  925. package/dist/services/mcp/utils/sendJsonRpcError.mjs +21 -0
  926. package/dist/services/mcp/utils/sendJsonRpcError.mjs.map +1 -0
  927. package/dist/services/mcp/utils/withTimeout.d.ts +7 -0
  928. package/dist/services/mcp/utils/withTimeout.d.ts.map +1 -0
  929. package/dist/services/mcp/utils/withTimeout.js +23 -0
  930. package/dist/services/mcp/utils/withTimeout.js.map +1 -0
  931. package/dist/services/mcp/utils/withTimeout.mjs +21 -0
  932. package/dist/services/mcp/utils/withTimeout.mjs.map +1 -0
  933. package/dist/services/metrics/admin-user-hash.d.ts.map +1 -1
  934. package/dist/services/metrics/admin-user-hash.js +17 -11
  935. package/dist/services/metrics/admin-user-hash.js.map +1 -1
  936. package/dist/services/metrics/admin-user-hash.mjs +12 -10
  937. package/dist/services/metrics/admin-user-hash.mjs.map +1 -1
  938. package/dist/services/metrics/index.d.ts +1 -1
  939. package/dist/services/metrics/index.d.ts.map +1 -1
  940. package/dist/services/metrics/index.js +51 -40
  941. package/dist/services/metrics/index.js.map +1 -1
  942. package/dist/services/metrics/index.mjs +50 -42
  943. package/dist/services/metrics/index.mjs.map +1 -1
  944. package/dist/services/metrics/is-truthy.d.ts.map +1 -1
  945. package/dist/services/metrics/is-truthy.js +17 -6
  946. package/dist/services/metrics/is-truthy.js.map +1 -1
  947. package/dist/services/metrics/is-truthy.mjs +12 -6
  948. package/dist/services/metrics/is-truthy.mjs.map +1 -1
  949. package/dist/services/metrics/middleware.d.ts +2 -1
  950. package/dist/services/metrics/middleware.d.ts.map +1 -1
  951. package/dist/services/metrics/middleware.js +55 -22
  952. package/dist/services/metrics/middleware.js.map +1 -1
  953. package/dist/services/metrics/middleware.mjs +54 -24
  954. package/dist/services/metrics/middleware.mjs.map +1 -1
  955. package/dist/services/metrics/rate-limiter.d.ts +2 -1
  956. package/dist/services/metrics/rate-limiter.d.ts.map +1 -1
  957. package/dist/services/metrics/rate-limiter.js +24 -19
  958. package/dist/services/metrics/rate-limiter.js.map +1 -1
  959. package/dist/services/metrics/rate-limiter.mjs +23 -21
  960. package/dist/services/metrics/rate-limiter.mjs.map +1 -1
  961. package/dist/services/metrics/sender.d.ts.map +1 -1
  962. package/dist/services/metrics/sender.js +102 -69
  963. package/dist/services/metrics/sender.js.map +1 -1
  964. package/dist/services/metrics/sender.mjs +93 -64
  965. package/dist/services/metrics/sender.mjs.map +1 -1
  966. package/dist/services/query-params.d.ts.map +1 -1
  967. package/dist/services/query-params.js +13 -10
  968. package/dist/services/query-params.js.map +1 -1
  969. package/dist/services/query-params.mjs +12 -12
  970. package/dist/services/query-params.mjs.map +1 -1
  971. package/dist/services/reloader.d.ts.map +1 -1
  972. package/dist/services/reloader.js +35 -32
  973. package/dist/services/reloader.js.map +1 -1
  974. package/dist/services/reloader.mjs +34 -33
  975. package/dist/services/reloader.mjs.map +1 -1
  976. package/dist/services/request-context.d.ts.map +1 -1
  977. package/dist/services/request-context.js +11 -8
  978. package/dist/services/request-context.js.map +1 -1
  979. package/dist/services/request-context.mjs +10 -10
  980. package/dist/services/request-context.mjs.map +1 -1
  981. package/dist/services/server/admin-api.d.ts +3 -5
  982. package/dist/services/server/admin-api.d.ts.map +1 -1
  983. package/dist/services/server/admin-api.js +11 -10
  984. package/dist/services/server/admin-api.js.map +1 -1
  985. package/dist/services/server/admin-api.mjs +10 -11
  986. package/dist/services/server/admin-api.mjs.map +1 -1
  987. package/dist/services/server/api.d.ts +3 -4
  988. package/dist/services/server/api.d.ts.map +1 -1
  989. package/dist/services/server/api.js +37 -27
  990. package/dist/services/server/api.js.map +1 -1
  991. package/dist/services/server/api.mjs +32 -26
  992. package/dist/services/server/api.mjs.map +1 -1
  993. package/dist/services/server/compose-endpoint.d.ts.map +1 -1
  994. package/dist/services/server/compose-endpoint.js +118 -105
  995. package/dist/services/server/compose-endpoint.js.map +1 -1
  996. package/dist/services/server/compose-endpoint.mjs +113 -105
  997. package/dist/services/server/compose-endpoint.mjs.map +1 -1
  998. package/dist/services/server/content-api.d.ts +3 -5
  999. package/dist/services/server/content-api.d.ts.map +1 -1
  1000. package/dist/services/server/content-api.js +11 -9
  1001. package/dist/services/server/content-api.js.map +1 -1
  1002. package/dist/services/server/content-api.mjs +10 -10
  1003. package/dist/services/server/content-api.mjs.map +1 -1
  1004. package/dist/services/server/http-server.d.ts +0 -1
  1005. package/dist/services/server/http-server.d.ts.map +1 -1
  1006. package/dist/services/server/http-server.js +52 -44
  1007. package/dist/services/server/http-server.js.map +1 -1
  1008. package/dist/services/server/http-server.mjs +47 -43
  1009. package/dist/services/server/http-server.mjs.map +1 -1
  1010. package/dist/services/server/index.d.ts.map +1 -1
  1011. package/dist/services/server/index.js +89 -82
  1012. package/dist/services/server/index.js.map +1 -1
  1013. package/dist/services/server/index.mjs +84 -81
  1014. package/dist/services/server/index.mjs.map +1 -1
  1015. package/dist/services/server/koa-methods.d.ts +107 -0
  1016. package/dist/services/server/koa-methods.d.ts.map +1 -0
  1017. package/dist/services/server/koa-methods.js +24 -0
  1018. package/dist/services/server/koa-methods.js.map +1 -0
  1019. package/dist/services/server/koa-methods.mjs +22 -0
  1020. package/dist/services/server/koa-methods.mjs.map +1 -0
  1021. package/dist/services/server/koa.d.ts +0 -9
  1022. package/dist/services/server/koa.d.ts.map +1 -1
  1023. package/dist/services/server/koa.js +53 -47
  1024. package/dist/services/server/koa.js.map +1 -1
  1025. package/dist/services/server/koa.mjs +46 -44
  1026. package/dist/services/server/koa.mjs.map +1 -1
  1027. package/dist/services/server/middleware.d.ts.map +1 -1
  1028. package/dist/services/server/middleware.js +90 -82
  1029. package/dist/services/server/middleware.js.map +1 -1
  1030. package/dist/services/server/middleware.mjs +85 -82
  1031. package/dist/services/server/middleware.mjs.map +1 -1
  1032. package/dist/services/server/openapi.d.ts +3 -0
  1033. package/dist/services/server/openapi.d.ts.map +1 -0
  1034. package/dist/services/server/openapi.js +214 -0
  1035. package/dist/services/server/openapi.js.map +1 -0
  1036. package/dist/services/server/openapi.mjs +188 -0
  1037. package/dist/services/server/openapi.mjs.map +1 -0
  1038. package/dist/services/server/policy.d.ts.map +1 -1
  1039. package/dist/services/server/policy.js +24 -17
  1040. package/dist/services/server/policy.js.map +1 -1
  1041. package/dist/services/server/policy.mjs +23 -18
  1042. package/dist/services/server/policy.mjs.map +1 -1
  1043. package/dist/services/server/register-middlewares.d.ts.map +1 -1
  1044. package/dist/services/server/register-middlewares.js +68 -61
  1045. package/dist/services/server/register-middlewares.js.map +1 -1
  1046. package/dist/services/server/register-middlewares.mjs +67 -63
  1047. package/dist/services/server/register-middlewares.mjs.map +1 -1
  1048. package/dist/services/server/register-routes.d.ts.map +1 -1
  1049. package/dist/services/server/register-routes.js +118 -66
  1050. package/dist/services/server/register-routes.js.map +1 -1
  1051. package/dist/services/server/register-routes.mjs +113 -66
  1052. package/dist/services/server/register-routes.mjs.map +1 -1
  1053. package/dist/services/server/routing.d.ts +10 -2
  1054. package/dist/services/server/routing.d.ts.map +1 -1
  1055. package/dist/services/server/routing.js +104 -81
  1056. package/dist/services/server/routing.js.map +1 -1
  1057. package/dist/services/server/routing.mjs +99 -81
  1058. package/dist/services/server/routing.mjs.map +1 -1
  1059. package/dist/services/session-manager.d.ts +187 -0
  1060. package/dist/services/session-manager.d.ts.map +1 -0
  1061. package/dist/services/session-manager.js +591 -0
  1062. package/dist/services/session-manager.js.map +1 -0
  1063. package/dist/services/session-manager.mjs +583 -0
  1064. package/dist/services/session-manager.mjs.map +1 -0
  1065. package/dist/services/utils/conditional-fields.d.ts +3 -0
  1066. package/dist/services/utils/conditional-fields.d.ts.map +1 -0
  1067. package/dist/services/utils/conditional-fields.js +22 -0
  1068. package/dist/services/utils/conditional-fields.js.map +1 -0
  1069. package/dist/services/utils/conditional-fields.mjs +20 -0
  1070. package/dist/services/utils/conditional-fields.mjs.map +1 -0
  1071. package/dist/services/utils/dynamic-zones.js +13 -14
  1072. package/dist/services/utils/dynamic-zones.js.map +1 -1
  1073. package/dist/services/utils/dynamic-zones.mjs +12 -16
  1074. package/dist/services/utils/dynamic-zones.mjs.map +1 -1
  1075. package/dist/services/webhook-runner.js +129 -122
  1076. package/dist/services/webhook-runner.js.map +1 -1
  1077. package/dist/services/webhook-runner.mjs +123 -121
  1078. package/dist/services/webhook-runner.mjs.map +1 -1
  1079. package/dist/services/webhook-store.d.ts.map +1 -1
  1080. package/dist/services/webhook-store.js +132 -99
  1081. package/dist/services/webhook-store.js.map +1 -1
  1082. package/dist/services/webhook-store.mjs +131 -101
  1083. package/dist/services/webhook-store.mjs.map +1 -1
  1084. package/dist/services/worker-queue.js +48 -49
  1085. package/dist/services/worker-queue.js.map +1 -1
  1086. package/dist/services/worker-queue.mjs +43 -49
  1087. package/dist/services/worker-queue.mjs.map +1 -1
  1088. package/dist/utils/convert-custom-field-type.d.ts.map +1 -1
  1089. package/dist/utils/convert-custom-field-type.js +17 -20
  1090. package/dist/utils/convert-custom-field-type.js.map +1 -1
  1091. package/dist/utils/convert-custom-field-type.mjs +16 -21
  1092. package/dist/utils/convert-custom-field-type.mjs.map +1 -1
  1093. package/dist/utils/cron.d.ts.map +1 -1
  1094. package/dist/utils/cron.js +64 -30
  1095. package/dist/utils/cron.js.map +1 -1
  1096. package/dist/utils/cron.mjs +63 -31
  1097. package/dist/utils/cron.mjs.map +1 -1
  1098. package/dist/utils/fetch.d.ts +5 -1
  1099. package/dist/utils/fetch.d.ts.map +1 -1
  1100. package/dist/utils/fetch.js +28 -17
  1101. package/dist/utils/fetch.js.map +1 -1
  1102. package/dist/utils/fetch.mjs +27 -18
  1103. package/dist/utils/fetch.mjs.map +1 -1
  1104. package/dist/utils/filepath-to-prop-path.d.ts +1 -1
  1105. package/dist/utils/filepath-to-prop-path.d.ts.map +1 -1
  1106. package/dist/utils/filepath-to-prop-path.js +27 -9
  1107. package/dist/utils/filepath-to-prop-path.js.map +1 -1
  1108. package/dist/utils/filepath-to-prop-path.mjs +20 -7
  1109. package/dist/utils/filepath-to-prop-path.mjs.map +1 -1
  1110. package/dist/utils/is-initialized.d.ts.map +1 -1
  1111. package/dist/utils/is-initialized.js +21 -12
  1112. package/dist/utils/is-initialized.js.map +1 -1
  1113. package/dist/utils/is-initialized.mjs +20 -13
  1114. package/dist/utils/is-initialized.mjs.map +1 -1
  1115. package/dist/utils/lifecycles.js +6 -5
  1116. package/dist/utils/lifecycles.js.map +1 -1
  1117. package/dist/utils/lifecycles.mjs +5 -6
  1118. package/dist/utils/lifecycles.mjs.map +1 -1
  1119. package/dist/utils/load-config-file.d.ts.map +1 -1
  1120. package/dist/utils/load-config-file.js +45 -38
  1121. package/dist/utils/load-config-file.js.map +1 -1
  1122. package/dist/utils/load-config-file.mjs +39 -36
  1123. package/dist/utils/load-config-file.mjs.map +1 -1
  1124. package/dist/utils/load-files.d.ts +1 -1
  1125. package/dist/utils/load-files.d.ts.map +1 -1
  1126. package/dist/utils/load-files.js +46 -35
  1127. package/dist/utils/load-files.js.map +1 -1
  1128. package/dist/utils/load-files.mjs +39 -32
  1129. package/dist/utils/load-files.mjs.map +1 -1
  1130. package/dist/utils/open-browser.d.ts +0 -1
  1131. package/dist/utils/open-browser.d.ts.map +1 -1
  1132. package/dist/utils/open-browser.js +12 -8
  1133. package/dist/utils/open-browser.js.map +1 -1
  1134. package/dist/utils/open-browser.mjs +7 -7
  1135. package/dist/utils/open-browser.mjs.map +1 -1
  1136. package/dist/utils/resolve-working-dirs.d.ts.map +1 -1
  1137. package/dist/utils/resolve-working-dirs.js +27 -10
  1138. package/dist/utils/resolve-working-dirs.js.map +1 -1
  1139. package/dist/utils/resolve-working-dirs.mjs +22 -9
  1140. package/dist/utils/resolve-working-dirs.mjs.map +1 -1
  1141. package/dist/utils/signals.d.ts.map +1 -1
  1142. package/dist/utils/signals.js +20 -14
  1143. package/dist/utils/signals.js.map +1 -1
  1144. package/dist/utils/signals.mjs +19 -15
  1145. package/dist/utils/signals.mjs.map +1 -1
  1146. package/dist/utils/startup-logger.d.ts.map +1 -1
  1147. package/dist/utils/startup-logger.js +125 -78
  1148. package/dist/utils/startup-logger.js.map +1 -1
  1149. package/dist/utils/startup-logger.mjs +117 -74
  1150. package/dist/utils/startup-logger.mjs.map +1 -1
  1151. package/dist/utils/transform-content-types-to-models.d.ts +553 -24
  1152. package/dist/utils/transform-content-types-to-models.d.ts.map +1 -1
  1153. package/dist/utils/transform-content-types-to-models.js +359 -248
  1154. package/dist/utils/transform-content-types-to-models.js.map +1 -1
  1155. package/dist/utils/transform-content-types-to-models.mjs +353 -256
  1156. package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
  1157. package/dist/utils/update-notifier/index.d.ts.map +1 -1
  1158. package/dist/utils/update-notifier/index.js +81 -73
  1159. package/dist/utils/update-notifier/index.js.map +1 -1
  1160. package/dist/utils/update-notifier/index.mjs +72 -67
  1161. package/dist/utils/update-notifier/index.mjs.map +1 -1
  1162. package/package.json +63 -53
@@ -1,50 +1,2578 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const strapiUtils = require("@strapi/utils");
4
- async function* getBatchToDiscard({
5
- db,
6
- trx,
7
- uid,
8
- batchSize = 1e3
9
- }) {
10
- let offset = 0;
11
- let hasMore = true;
12
- while (hasMore) {
13
- const batch = await db.queryBuilder(uid).select(["id", "documentId", "locale"]).where({ publishedAt: { $ne: null } }).limit(batchSize).offset(offset).orderBy("id").transacting(trx).execute();
14
- if (batch.length < batchSize) {
15
- hasMore = false;
16
- }
17
- offset += batchSize;
18
- yield batch;
19
- }
20
- }
21
- const migrateUp = async (trx, db) => {
22
- for (const meta of db.metadata.values()) {
1
+ 'use strict';
2
+
3
+ var cuid2 = require('@paralleldrive/cuid2');
4
+ var strapiUtils = require('@strapi/utils');
5
+ var createDebug = require('debug');
6
+ var transformContentTypesToModels = require('../../utils/transform-content-types-to-models.js');
7
+
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
+
10
+ var createDebug__default = /*#__PURE__*/_interopDefault(createDebug);
11
+
12
+ const resolveComponentMetadataUidCandidates = (componentUid)=>{
13
+ if (componentUid.startsWith('component::')) {
14
+ return [
15
+ componentUid,
16
+ componentUid.slice('component::'.length)
17
+ ];
18
+ }
19
+ return [
20
+ componentUid,
21
+ `component::${componentUid}`
22
+ ];
23
+ };
24
+ const getComponentMetadataByUid = (componentUid)=>{
25
+ for (const candidate of resolveComponentMetadataUidCandidates(componentUid)){
26
+ try {
27
+ const meta = strapi.db.metadata.get(candidate);
28
+ if (meta) {
29
+ return meta;
30
+ }
31
+ } catch {
32
+ continue;
33
+ }
34
+ }
35
+ return null;
36
+ };
37
+ const DEFAULT_PRIMARY_KEY_COLUMN = 'id';
38
+ /**
39
+ * Determines the primary-key column name for a schema, handling the various shapes
40
+ * metadata can take (string, object, attribute flag) and defaulting to `id`.
41
+ */ const resolvePrimaryKeyColumn = (meta)=>{
42
+ const { primaryKey } = meta;
43
+ if (typeof primaryKey === 'string' && primaryKey) {
44
+ return primaryKey;
45
+ }
46
+ if (primaryKey && typeof primaryKey === 'object') {
47
+ const pkObject = primaryKey;
48
+ const columnName = pkObject.columnName;
49
+ if (typeof columnName === 'string' && columnName) {
50
+ return columnName;
51
+ }
52
+ const name = pkObject.name;
53
+ if (typeof name === 'string' && name) {
54
+ return name;
55
+ }
56
+ }
57
+ const attributes = meta.attributes ?? {};
58
+ for (const [attributeName, attribute] of Object.entries(attributes)){
59
+ const normalizedAttribute = attribute;
60
+ if (!normalizedAttribute) {
61
+ continue;
62
+ }
63
+ const { column } = normalizedAttribute;
64
+ if (column?.primary === true) {
65
+ if (typeof normalizedAttribute.columnName === 'string' && normalizedAttribute.columnName) {
66
+ return normalizedAttribute.columnName;
67
+ }
68
+ return attributeName;
69
+ }
70
+ }
71
+ return DEFAULT_PRIMARY_KEY_COLUMN;
72
+ };
73
+ /**
74
+ * Check if the model has draft and publish enabled.
75
+ */ const hasDraftAndPublish = async (trx, meta)=>{
23
76
  const hasTable = await trx.schema.hasTable(meta.tableName);
24
77
  if (!hasTable) {
25
- continue;
78
+ return false;
26
79
  }
27
80
  const uid = meta.uid;
28
81
  const model = strapi.getModel(uid);
29
82
  const hasDP = strapiUtils.contentTypes.hasDraftAndPublish(model);
30
83
  if (!hasDP) {
31
- continue;
84
+ return false;
85
+ }
86
+ return true;
87
+ };
88
+ /**
89
+ * Join-column relations that are persisted on the row (e.g. createdBy), excluding virtual
90
+ * relations such as i18n `localizations` which reuse `document_id` and are not DB-owned.
91
+ */ const isPersistedJoinColumnRelation = (attribute)=>attribute?.type === 'relation' && !attribute.unstable_virtual && attribute.joinColumn && !attribute.joinTable;
92
+ /**
93
+ * Column names copied when cloning a published row into a draft (stage 1).
94
+ * Scalars plus persisted join-column FKs; deduped so virtual relations cannot repeat columns.
95
+ */ const getPublishedToDraftCloneColumns = (meta)=>{
96
+ const seen = new Set();
97
+ const columns = [];
98
+ const addColumn = (columnName)=>{
99
+ if (!columnName || columnName === 'id' || seen.has(columnName)) {
100
+ return;
101
+ }
102
+ seen.add(columnName);
103
+ columns.push(columnName);
104
+ };
105
+ for (const attribute of Object.values(meta.attributes)){
106
+ if (strapiUtils.contentTypes.isScalarAttribute(attribute)) {
107
+ addColumn(attribute.columnName);
108
+ continue;
109
+ }
110
+ if (isPersistedJoinColumnRelation(attribute)) {
111
+ addColumn(attribute.joinColumn.name);
112
+ }
113
+ }
114
+ return columns;
115
+ };
116
+ /**
117
+ * Copy published entries to draft rows, cloning scalar fields and join-column foreign keys.
118
+ * Components, dynamic zones, and join-table relations are handled in later stages.
119
+ */ async function copyPublishedEntriesToDraft({ db, trx, uid }) {
120
+ const meta = db.metadata.get(uid);
121
+ const columnsToCopy = getPublishedToDraftCloneColumns(meta);
122
+ /**
123
+ * Query to copy the published entries into draft entries.
124
+ *
125
+ * INSERT INTO tableName (columnName1, columnName2, columnName3, ...)
126
+ * SELECT columnName1, columnName2, columnName3, ...
127
+ * FROM tableName
128
+ */ await trx// INSERT INTO tableName (columnName1, columnName2, columnName3, ...)
129
+ .into(trx.raw(`?? (${columnsToCopy.map(()=>`??`).join(', ')})`, [
130
+ meta.tableName,
131
+ ...columnsToCopy
132
+ ])).insert((subQb)=>{
133
+ // SELECT columnName1, columnName2, columnName3, ...
134
+ subQb.select(...columnsToCopy.map((att)=>{
135
+ // NOTE: these literals reference Strapi's built-in system columns. They never get shortened by
136
+ // the identifier migration (5.0.0-01-convert-identifiers-long-than-max-length) so we can safely
137
+ // compare/use them directly here.
138
+ if (att === 'published_at') {
139
+ return trx.raw('NULL as ??', 'published_at');
140
+ }
141
+ return att;
142
+ })).from(meta.tableName)// Only select entries that were published
143
+ .whereNotNull('published_at');
144
+ });
145
+ }
146
+ /**
147
+ * Orchestrates the relation cloning pipeline for a single content type. We duplicate
148
+ * every category of relation (self, inbound, outbound, components) using direct SQL so
149
+ * the migration can scale without calling `discardDraft` entry by entry.
150
+ */ async function copyRelationsToDrafts({ db, trx, uid }) {
151
+ const meta = db.metadata.get(uid);
152
+ if (!meta) {
153
+ return;
154
+ }
155
+ // Create mapping from published entry ID to draft entry ID
156
+ const publishedToDraftMap = await buildPublishedToDraftMap({
157
+ trx,
158
+ uid,
159
+ meta
160
+ });
161
+ if (!publishedToDraftMap || publishedToDraftMap.size === 0) {
162
+ return;
163
+ }
164
+ // Copy relations for this content type
165
+ await copyRelationsForContentType({
166
+ trx,
167
+ uid,
168
+ publishedToDraftMap
169
+ });
170
+ // Copy relations from other content types that target this content type
171
+ await copyRelationsFromOtherContentTypes({
172
+ trx,
173
+ uid,
174
+ publishedToDraftMap
175
+ });
176
+ // Copy relations from this content type that target other content types (category 3)
177
+ await copyRelationsToOtherContentTypes({
178
+ trx,
179
+ uid,
180
+ publishedToDraftMap
181
+ });
182
+ // Copy component relations from published entries to draft entries
183
+ await copyComponentRelations({
184
+ trx,
185
+ uid,
186
+ publishedToDraftMap
187
+ });
188
+ // (1) Media: one shared table owned by upload plugin; we are the "related" side (related_id).
189
+ // Copy rows so draft entity ids get the same file links as their published pair.
190
+ await copyMediaMorphToDraftsForContentType({
191
+ trx,
192
+ uid,
193
+ publishedToDraftMap
194
+ });
195
+ // (2) Other morph: per-attribute tables where we are the "source" side (join column = our entity id).
196
+ // Copy rows so draft entity ids get the same polymorphic links. Skips upload table by name.
197
+ await copySourceSideMorphRelationsForContentType({
198
+ trx,
199
+ uid,
200
+ publishedToDraftMap
201
+ });
202
+ }
203
+ /**
204
+ * Returns the upload plugin's morph join table info (e.g. files_related_morphs) if present.
205
+ * This is the single table used by all media fields across content types and components.
206
+ */ function getUploadMorphTableInfo() {
207
+ const fileMeta = strapi.db.metadata.get('plugin::upload.file');
208
+ if (!fileMeta?.attributes) {
209
+ return null;
210
+ }
211
+ const relatedAttr = fileMeta.attributes.related;
212
+ const joinTable = relatedAttr?.joinTable;
213
+ const morphColumn = joinTable?.morphColumn ?? relatedAttr?.morphColumn;
214
+ if (!joinTable?.name || !joinTable?.joinColumn?.name || !morphColumn) {
215
+ return null;
216
+ }
217
+ return {
218
+ tableName: joinTable.name,
219
+ joinColumnName: joinTable.joinColumn.name,
220
+ relatedIdColumnName: morphColumn.idColumn.name,
221
+ relatedTypeColumnName: morphColumn.typeColumn.name
222
+ };
223
+ }
224
+ /**
225
+ * Unified morph copy: duplicate rows in a morph join table, rewriting one column from original ids to draft ids.
226
+ * Used for both (1) media: upload table, we are "related" side, filter by related_type; (2) other morph: we are "source" side, no filter.
227
+ * @param columnToRewrite - the column that holds our entity id (related_id in upload table, entity_id in source-side tables).
228
+ * @param filter - optional: only copy rows where filter.column = filter.value (e.g. related_type = uid for media).
229
+ */ async function copyMorphRowsByIdMap({ trx, tableName, columnToRewrite, idMap, filter, contextReason }) {
230
+ if (idMap.size === 0) return;
231
+ const hasTable = await ensureTableExists(trx, tableName);
232
+ if (!hasTable) return;
233
+ const originalIds = Array.from(idMap.keys());
234
+ const chunks = chunkArray(originalIds, getBatchSize(trx, 500));
235
+ for (const chunk of chunks){
236
+ let q = trx(tableName).select('*').whereIn(columnToRewrite, chunk);
237
+ if (filter) {
238
+ q = q.where(filter.column, filter.value);
239
+ }
240
+ const rows = await q;
241
+ if (rows.length === 0) continue;
242
+ const toInsert = [];
243
+ for (const row of rows){
244
+ const originalId = normalizeId(row[columnToRewrite]);
245
+ if (originalId == null) continue;
246
+ const newId = idMap.get(originalId);
247
+ if (newId == null) continue;
248
+ const { id, ...rest } = row;
249
+ toInsert.push({
250
+ ...rest,
251
+ [columnToRewrite]: newId
252
+ });
253
+ }
254
+ if (toInsert.length > 0) {
255
+ await insertRelationsWithDuplicateHandling({
256
+ trx,
257
+ tableName,
258
+ relations: toInsert,
259
+ context: {
260
+ reason: contextReason,
261
+ tableName
262
+ }
263
+ });
264
+ }
265
+ }
266
+ }
267
+ /**
268
+ * Same as copyMorphRowsByIdMap but for (originalId, draftId) pairs when one original can map to multiple drafts (e.g. cloned components).
269
+ */ async function copyMorphRowsByPairs({ trx, tableName, columnToRewrite, pairs, filter, contextReason }) {
270
+ if (pairs.length === 0) return;
271
+ const hasTable = await ensureTableExists(trx, tableName);
272
+ if (!hasTable) return;
273
+ const originalIds = [
274
+ ...new Set(pairs.map((p)=>p.originalId))
275
+ ];
276
+ const chunks = chunkArray(originalIds, getBatchSize(trx, 500));
277
+ for (const chunk of chunks){
278
+ let q = trx(tableName).select('*').whereIn(columnToRewrite, chunk);
279
+ if (filter) {
280
+ q = q.where(filter.column, filter.value);
281
+ }
282
+ const rows = await q;
283
+ if (rows.length === 0) continue;
284
+ const toInsert = [];
285
+ for (const row of rows){
286
+ const originalId = normalizeId(row[columnToRewrite]);
287
+ if (originalId == null) continue;
288
+ const draftIds = pairs.filter((p)=>p.originalId === originalId).map((p)=>p.draftId);
289
+ for (const draftId of draftIds){
290
+ const { id, ...rest } = row;
291
+ toInsert.push({
292
+ ...rest,
293
+ [columnToRewrite]: draftId
294
+ });
295
+ }
296
+ }
297
+ if (toInsert.length > 0) {
298
+ await insertRelationsWithDuplicateHandling({
299
+ trx,
300
+ tableName,
301
+ relations: toInsert,
302
+ context: {
303
+ reason: contextReason,
304
+ tableName
305
+ }
306
+ });
307
+ }
308
+ }
309
+ }
310
+ const recordClonedComponentPair = (clonedComponentPairsCache, componentUid, originalId, draftId)=>{
311
+ if (!clonedComponentPairsCache) {
312
+ return;
313
+ }
314
+ let pairMap = clonedComponentPairsCache.get(componentUid);
315
+ if (!pairMap) {
316
+ pairMap = new Map();
317
+ clonedComponentPairsCache.set(componentUid, pairMap);
318
+ }
319
+ pairMap.set(`${originalId}:${draftId}`, draftId);
320
+ };
321
+ /** Copy media morph rows for this content type (upload table; we are the "related" side). */ async function copyMediaMorphToDraftsForContentType({ trx, uid, publishedToDraftMap }) {
322
+ const morphInfo = getUploadMorphTableInfo();
323
+ if (!morphInfo) return;
324
+ await copyMorphRowsByIdMap({
325
+ trx,
326
+ tableName: morphInfo.tableName,
327
+ columnToRewrite: morphInfo.relatedIdColumnName,
328
+ idMap: publishedToDraftMap,
329
+ filter: {
330
+ column: morphInfo.relatedTypeColumnName,
331
+ value: uid
332
+ },
333
+ contextReason: 'media-morph-draft'
334
+ });
335
+ }
336
+ /** Copy source-side morph rows for this content type (per-attribute tables; we are the "source" side). */ async function copySourceSideMorphRelationsForContentType({ trx, uid, publishedToDraftMap }) {
337
+ const meta = strapi.db.metadata.get(uid);
338
+ if (!meta) return;
339
+ const uploadMorph = getUploadMorphTableInfo();
340
+ const uploadTableName = uploadMorph?.tableName ?? null;
341
+ for (const attribute of Object.values(meta.attributes)){
342
+ if (attribute.type !== 'relation' || !attribute.joinTable?.morphColumn) continue;
343
+ const joinTable = attribute.joinTable;
344
+ if (joinTable.name === uploadTableName) continue;
345
+ // Dynamic zones are represented as morph relations in DB metadata, but their rows live in
346
+ // the shared component join table (`*_cmps`) and are already handled by copyComponentRelations.
347
+ if (joinTable.name.includes('_cmps')) continue;
348
+ const sourceColumnName = joinTable.joinColumn?.name;
349
+ if (!sourceColumnName) continue;
350
+ await copyMorphRowsByIdMap({
351
+ trx,
352
+ tableName: joinTable.name,
353
+ columnToRewrite: sourceColumnName,
354
+ idMap: publishedToDraftMap,
355
+ contextReason: 'source-side-morph-draft'
356
+ });
357
+ }
358
+ }
359
+ /**
360
+ * Copy source-side morph relations for cloned components (each component type's morph attributes).
361
+ */ async function copySourceSideMorphRelationsForClonedComponents({ trx, clonedComponentPairsCache }) {
362
+ const uploadMorph = getUploadMorphTableInfo();
363
+ const uploadTableName = uploadMorph?.tableName ?? null;
364
+ for (const [componentType, cloneMap] of clonedComponentPairsCache.entries()){
365
+ let componentMeta;
366
+ try {
367
+ componentMeta = getComponentMetadataByUid(componentType);
368
+ } catch {
369
+ continue;
370
+ }
371
+ for (const attribute of Object.values(componentMeta.attributes || {})){
372
+ if (attribute.type !== 'relation' || !attribute.joinTable?.morphColumn) continue;
373
+ const joinTable = attribute.joinTable;
374
+ if (joinTable.name === uploadTableName) continue;
375
+ // Component dynamic zones also use `*_cmps` join tables and are cloned recursively.
376
+ // Copying them here would reinsert original component ids and create shared draft/published rows.
377
+ if (joinTable.name.includes('_cmps')) continue;
378
+ const sourceColumnName = joinTable.joinColumn?.name;
379
+ if (!sourceColumnName) continue;
380
+ const pairs = [];
381
+ for (const [key, newComponentId] of cloneMap.entries()){
382
+ const originalId = Number(key.split(':')[0]);
383
+ if (!Number.isNaN(originalId)) {
384
+ pairs.push({
385
+ originalId,
386
+ draftId: newComponentId
387
+ });
388
+ }
389
+ }
390
+ if (pairs.length > 0) {
391
+ await copyMorphRowsByPairs({
392
+ trx,
393
+ tableName: joinTable.name,
394
+ columnToRewrite: sourceColumnName,
395
+ pairs,
396
+ contextReason: 'source-side-morph-draft-pairs'
397
+ });
398
+ }
399
+ }
400
+ }
401
+ }
402
+ /**
403
+ * Splits large input arrays into smaller batches so we can run SQL queries without
404
+ * hitting parameter limits (SQLite) or payload limits (MySQL/Postgres).
405
+ */ function chunkArray(array, chunkSize) {
406
+ const chunks = [];
407
+ for(let i = 0; i < array.length; i += chunkSize){
408
+ chunks.push(array.slice(i, i + chunkSize));
409
+ }
410
+ return chunks;
411
+ }
412
+ /**
413
+ * Bulk-load existing relation rows for (sourceId, newTargetId) pairs so we can avoid
414
+ * per-row SELECTs when deciding update vs delete.
415
+ */ async function buildExistingRelationMap({ trx, tableName, sourceColumnName, targetColumnName, updates, batchSize }) {
416
+ const existingMap = new Map();
417
+ if (updates.length === 0) {
418
+ return existingMap;
419
+ }
420
+ const queryChunks = chunkArray(updates, batchSize);
421
+ for (const chunk of queryChunks){
422
+ const rows = await trx(tableName).select([
423
+ 'id',
424
+ sourceColumnName,
425
+ targetColumnName
426
+ ]).where((qb)=>{
427
+ for (const update of chunk){
428
+ qb.orWhere((subQb)=>{
429
+ subQb.where(sourceColumnName, update.sourceId).where(targetColumnName, update.newTargetId);
430
+ });
431
+ }
432
+ });
433
+ for (const row of rows){
434
+ const key = `${row[sourceColumnName]}_${row[targetColumnName]}`;
435
+ existingMap.set(key, row.id);
436
+ }
437
+ }
438
+ return existingMap;
439
+ }
440
+ /**
441
+ * Chooses a safe batch size for bulk operations depending on the database engine,
442
+ * falling back to smaller units on engines (notably SQLite) that have low limits.
443
+ */ function getBatchSize(trx, defaultSize = 1000) {
444
+ const client = trx.client.config.client;
445
+ const isSQLite = typeof client === 'string' && [
446
+ 'sqlite',
447
+ 'sqlite3',
448
+ 'better-sqlite3'
449
+ ].includes(client);
450
+ // SQLite documentation states that the maximum number of terms in a
451
+ // compound SELECT statement is 500 by default.
452
+ // See: https://www.sqlite.org/limits.html
453
+ // We use 250 to be safe and account for other query complexity.
454
+ return isSQLite ? Math.min(defaultSize, 250) : defaultSize;
455
+ }
456
+ /**
457
+ * Applies stable ordering to join-table queries so cloning work is deterministic and
458
+ * matches the ordering logic used by the entity service (important for tests and DZ order).
459
+ */ const applyJoinTableOrdering = (qb, joinTable, sourceColumnName)=>{
460
+ const seenColumns = new Set();
461
+ const enqueueColumn = (column, direction = 'asc')=>{
462
+ if (!column || seenColumns.has(column)) {
463
+ return;
464
+ }
465
+ seenColumns.add(column);
466
+ qb.orderBy(column, direction);
467
+ };
468
+ enqueueColumn(sourceColumnName, 'asc');
469
+ if (Array.isArray(joinTable?.orderBy)) {
470
+ for (const clause of joinTable.orderBy){
471
+ if (!clause || typeof clause !== 'object') {
472
+ continue;
473
+ }
474
+ const [column, direction] = Object.entries(clause)[0] ?? [];
475
+ if (!column) {
476
+ continue;
477
+ }
478
+ const normalizedDirection = typeof direction === 'string' && direction.toLowerCase() === 'desc' ? 'desc' : 'asc';
479
+ enqueueColumn(column, normalizedDirection);
480
+ }
481
+ }
482
+ enqueueColumn(joinTable?.orderColumnName, 'asc');
483
+ enqueueColumn(joinTable?.orderColumn, 'asc');
484
+ enqueueColumn('id', 'asc');
485
+ };
486
+ /**
487
+ * Builds a stable key for join-table relations to detect duplicates.
488
+ * Key format: sourceId::targetId::field::componentType
489
+ */ const buildRelationKey = (relation, sourceColumnName, targetId)=>{
490
+ const sourceId = normalizeId(relation[sourceColumnName]) ?? relation[sourceColumnName];
491
+ const fieldValue = 'field' in relation ? relation.field ?? '' : '';
492
+ const componentTypeValue = 'component_type' in relation ? relation.component_type ?? '' : '';
493
+ return `${sourceId ?? 'null'}::${targetId ?? 'null'}::${fieldValue}::${componentTypeValue}`;
494
+ };
495
+ /**
496
+ * Queries existing relations from a join table and builds a set of keys for duplicate detection.
497
+ */ async function getExistingRelationKeys({ trx, joinTable, sourceColumnName, targetColumnName, sourceIds }) {
498
+ const existingKeys = new Set();
499
+ if (sourceIds.length === 0) {
500
+ return existingKeys;
501
+ }
502
+ const idChunks = chunkArray(sourceIds, getBatchSize(trx, 1000));
503
+ for (const chunk of idChunks){
504
+ const existingRelationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, chunk);
505
+ applyJoinTableOrdering(existingRelationsQuery, joinTable, sourceColumnName);
506
+ const existingRelations = await existingRelationsQuery;
507
+ for (const relation of existingRelations){
508
+ const targetId = normalizeId(relation[targetColumnName]) ?? relation[targetColumnName];
509
+ const key = buildRelationKey(relation, sourceColumnName, targetId);
510
+ existingKeys.add(key);
511
+ }
512
+ }
513
+ return existingKeys;
514
+ }
515
+ /**
516
+ * Inserts relations into a join table with database-specific duplicate handling.
517
+ * Tries batch insert first, then falls back to individual inserts with conflict handling.
518
+ */ async function insertRelationsWithDuplicateHandling({ trx, tableName, relations, context = {} }) {
519
+ if (relations.length === 0) {
520
+ return;
521
+ }
522
+ try {
523
+ await trx.batchInsert(tableName, relations, getBatchSize(trx, 1000));
524
+ } catch (error) {
525
+ // If batch insert fails due to duplicates, try with conflict handling
526
+ if (!isDuplicateEntryError(error)) {
527
+ throw error;
528
+ }
529
+ const client = trx.client.config.client;
530
+ if (client === 'postgres' || client === 'pg') {
531
+ for (const relation of relations){
532
+ try {
533
+ await trx(tableName).insert(relation).onConflict().ignore();
534
+ } catch (err) {
535
+ if (err.code !== '23505' && !err.message?.includes('duplicate key')) {
536
+ throw err;
537
+ }
538
+ }
539
+ }
540
+ } else {
541
+ // MySQL and SQLite: use insertRowWithDuplicateHandling
542
+ for (const relation of relations){
543
+ await insertRowWithDuplicateHandling(trx, tableName, relation, context);
544
+ }
545
+ }
546
+ }
547
+ }
548
+ const componentParentSchemasCache = new Map();
549
+ const joinTableExistsCache = new Map();
550
+ const componentMetaCache = new Map();
551
+ const SKIPPED_RELATION_SAMPLE_LIMIT = 5;
552
+ const supportsReturning = (trx)=>{
553
+ const client = trx.client.config.client;
554
+ if (typeof client !== 'string') {
555
+ return false;
556
+ }
557
+ return [
558
+ 'postgres',
559
+ 'pg'
560
+ ].includes(client.toLowerCase());
561
+ };
562
+ const skippedRelationStats = new Map();
563
+ const DUPLICATE_ERROR_CODES = new Set([
564
+ '23505',
565
+ 'ER_DUP_ENTRY',
566
+ 'SQLITE_CONSTRAINT_UNIQUE'
567
+ ]);
568
+ const debug = createDebug__default.default('strapi::migration::discard-drafts');
569
+ /**
570
+ * Converts arbitrary id values into numbers when possible so we can safely index into
571
+ * mapping tables without worrying about string/number mismatches.
572
+ */ const normalizeId = (value)=>{
573
+ if (value == null) {
574
+ return null;
575
+ }
576
+ const num = Number(value);
577
+ if (Number.isNaN(num)) {
578
+ return null;
579
+ }
580
+ return num;
581
+ };
582
+ /**
583
+ * Wrapper around map lookups that first normalizes the provided identifier.
584
+ */ const getMappedValue = (map, key)=>{
585
+ if (!map) {
586
+ return undefined;
587
+ }
588
+ const normalized = normalizeId(key);
589
+ if (normalized == null) {
590
+ return undefined;
591
+ }
592
+ return map.get(normalized);
593
+ };
594
+ /**
595
+ * Extracts the inserted row identifier across the various shapes returned by different
596
+ * clients/drivers (numbers, objects, arrays). Falls back to `null` if nothing usable.
597
+ */ const resolveInsertedId = (insertResult)=>{
598
+ if (insertResult == null) {
599
+ return null;
600
+ }
601
+ if (typeof insertResult === 'number') {
602
+ return insertResult;
603
+ }
604
+ if (Array.isArray(insertResult)) {
605
+ if (insertResult.length === 0) {
606
+ return null;
607
+ }
608
+ const first = insertResult[0];
609
+ if (first == null) {
610
+ return null;
611
+ }
612
+ if (typeof first === 'number') {
613
+ return first;
614
+ }
615
+ if (typeof first === 'object') {
616
+ if ('id' in first) {
617
+ return Number(first.id);
618
+ }
619
+ const idKey = Object.keys(first).find((key)=>key.toLowerCase() === 'id');
620
+ if (idKey) {
621
+ return Number(first[idKey]);
622
+ }
623
+ }
624
+ }
625
+ if (typeof insertResult === 'object' && 'id' in insertResult) {
626
+ return Number(insertResult.id);
627
+ }
628
+ return null;
629
+ };
630
+ /**
631
+ * Detects vendor-specific duplicate key errors so we can safely ignore them when our
632
+ * goal is to insert-or-ignore without branching on the client everywhere.
633
+ */ const isDuplicateEntryError = (error)=>{
634
+ if (!error) {
635
+ return false;
32
636
  }
33
- const discardDraft = async (entry) => strapi.documents(uid).discardDraft({ documentId: entry.documentId, locale: entry.locale });
34
- for await (const batch of getBatchToDiscard({ db, trx, uid: meta.uid })) {
35
- await strapiUtils.async.map(batch, discardDraft, { concurrency: 10 });
637
+ if (DUPLICATE_ERROR_CODES.has(error.code)) {
638
+ return true;
36
639
  }
37
- }
640
+ const message = typeof error.message === 'string' ? error.message : '';
641
+ return message.includes('duplicate key') || message.includes('UNIQUE constraint failed');
38
642
  };
643
+ /**
644
+ * Inserts a row while tolerating duplicates across all supported clients. Used when
645
+ * bulk operations fall back to single inserts to resolve constraint conflicts.
646
+ */ const insertRowWithDuplicateHandling = async (trx, tableName, row, context = {})=>{
647
+ try {
648
+ const client = trx.client.config.client;
649
+ if (client === 'postgres' || client === 'pg' || client === 'sqlite3' || client === 'better-sqlite3') {
650
+ await trx(tableName).insert(row).onConflict().ignore();
651
+ return;
652
+ }
653
+ if (client === 'mysql' || client === 'mysql2') {
654
+ await trx.raw(`INSERT IGNORE INTO ?? SET ?`, [
655
+ tableName,
656
+ row
657
+ ]);
658
+ return;
659
+ }
660
+ await trx(tableName).insert(row);
661
+ } catch (error) {
662
+ if (!isDuplicateEntryError(error)) {
663
+ const details = JSON.stringify(context);
664
+ const wrapped = new Error(`Failed to insert row into ${tableName}: ${error.message} | context=${details}`);
665
+ wrapped.cause = error;
666
+ throw wrapped;
667
+ }
668
+ }
669
+ };
670
+ /**
671
+ * Normalizes identifiers into a comparable string so we can dedupe target ids
672
+ * regardless of whether they come in as numbers, strings, or objects.
673
+ */ const toComparisonKey = (value)=>{
674
+ if (value === null || value === undefined) {
675
+ return 'null';
676
+ }
677
+ if (typeof value === 'object') {
678
+ try {
679
+ return JSON.stringify(value);
680
+ } catch {
681
+ return String(value);
682
+ }
683
+ }
684
+ return String(value);
685
+ };
686
+ /**
687
+ * Formats ids for log output while keeping the log lightweight and JSON-safe.
688
+ */ const toDisplayValue = (value)=>{
689
+ if (value === null || value === undefined) {
690
+ return 'null';
691
+ }
692
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') {
693
+ return String(value);
694
+ }
695
+ try {
696
+ return JSON.stringify(value);
697
+ } catch {
698
+ return String(value);
699
+ }
700
+ };
701
+ /**
702
+ * Tracks how many relation rows we skipped because their targets are missing, so we
703
+ * can emit a consolidated warning once the migration finishes copying relations.
704
+ */ function recordSkippedRelations(context, skippedIds) {
705
+ if (!skippedIds.length) {
706
+ return;
707
+ }
708
+ const key = `${context.sourceUid}::${context.attributeName}::${context.joinTable ?? 'NO_JOIN_TABLE'}`;
709
+ let stats = skippedRelationStats.get(key);
710
+ if (!stats) {
711
+ stats = {
712
+ ...context,
713
+ count: 0,
714
+ samples: new Set()
715
+ };
716
+ }
717
+ stats.count += skippedIds.length;
718
+ for (const id of skippedIds){
719
+ if (stats.samples.size >= SKIPPED_RELATION_SAMPLE_LIMIT) {
720
+ break;
721
+ }
722
+ stats.samples.add(toDisplayValue(id));
723
+ }
724
+ skippedRelationStats.set(key, stats);
725
+ }
726
+ /**
727
+ * Emits aggregated warnings for all skipped relations and resets the counters.
728
+ * This keeps the log readable even when millions of orphaned rows exist.
729
+ */ function flushSkippedRelationLogs() {
730
+ if (skippedRelationStats.size === 0) {
731
+ return;
732
+ }
733
+ for (const stats of skippedRelationStats.values()){
734
+ const sampleArray = Array.from(stats.samples);
735
+ const sampleText = sampleArray.length > 0 ? sampleArray.join(', ') : 'n/a';
736
+ const targetInfo = stats.targetUid ? `target=${stats.targetUid}` : 'target=unknown';
737
+ const joinTableInfo = stats.joinTable ? `joinTable=${stats.joinTable}` : 'joinTable=n/a';
738
+ const ellipsis = stats.count > sampleArray.length ? ', ...' : '';
739
+ strapi.log.warn(`[discard-drafts] Skipped ${stats.count} relation(s) for ${stats.sourceUid}.${stats.attributeName} (${targetInfo}, ${joinTableInfo}). Example target ids: ${sampleText}${ellipsis}`);
740
+ }
741
+ strapi.log.warn('[discard-drafts] Some join-table relations referenced missing targets and were skipped. Review these warnings and clean up orphaned relations before rerunning the migration if needed.');
742
+ skippedRelationStats.clear();
743
+ }
744
+ /**
745
+ * Returns every schema (content type or component) that can embed the provided component.
746
+ * Cached because we consult it repeatedly while remapping nested components.
747
+ */ function listComponentParentSchemas(componentUid) {
748
+ if (!componentParentSchemasCache.has(componentUid)) {
749
+ const schemas = [
750
+ ...Object.values(strapi.contentTypes),
751
+ ...Object.values(strapi.components)
752
+ ];
753
+ const parents = schemas.filter((schema)=>{
754
+ if (!schema?.attributes) {
755
+ return false;
756
+ }
757
+ return Object.values(schema.attributes).some((attr)=>{
758
+ if (attr.type === 'component') {
759
+ return attr.component === componentUid;
760
+ }
761
+ if (attr.type === 'dynamiczone') {
762
+ return attr.components?.includes(componentUid);
763
+ }
764
+ return false;
765
+ });
766
+ }).map((schema)=>({
767
+ uid: schema.uid,
768
+ collectionName: schema.collectionName
769
+ }));
770
+ componentParentSchemasCache.set(componentUid, parents);
771
+ }
772
+ return componentParentSchemasCache.get(componentUid);
773
+ }
774
+ /**
775
+ * Memoized helper for checking whether a table exists. Avoids repeating expensive
776
+ * information_schema queries when we touch the same join table many times.
777
+ */ async function ensureTableExists(trx, tableName) {
778
+ if (!joinTableExistsCache.has(tableName)) {
779
+ const exists = await trx.schema.hasTable(tableName);
780
+ joinTableExistsCache.set(tableName, exists);
781
+ }
782
+ return joinTableExistsCache.get(tableName);
783
+ }
784
+ /**
785
+ * Filters out relation rows whose target entity no longer exists, returning the safe
786
+ * rows along with a list of skipped ids so we can log them later.
787
+ */ async function filterRelationsWithExistingTargets({ trx, targetUid, relations, getTargetId }) {
788
+ if (!relations.length) {
789
+ return {
790
+ relations,
791
+ skippedIds: []
792
+ };
793
+ }
794
+ if (!targetUid) {
795
+ return {
796
+ relations,
797
+ skippedIds: []
798
+ };
799
+ }
800
+ const targetMeta = strapi.db.metadata.get(targetUid);
801
+ if (!targetMeta) {
802
+ return {
803
+ relations,
804
+ skippedIds: []
805
+ };
806
+ }
807
+ const tableName = targetMeta.tableName;
808
+ const primaryKeyColumn = resolvePrimaryKeyColumn(targetMeta);
809
+ if (!tableName) {
810
+ return {
811
+ relations,
812
+ skippedIds: []
813
+ };
814
+ }
815
+ const uniqueIdMap = new Map();
816
+ for (const relation of relations){
817
+ const targetId = getTargetId(relation);
818
+ if (targetId == null) {
819
+ continue;
820
+ }
821
+ const key = toComparisonKey(targetId);
822
+ if (!uniqueIdMap.has(key)) {
823
+ uniqueIdMap.set(key, targetId);
824
+ }
825
+ }
826
+ if (uniqueIdMap.size === 0) {
827
+ return {
828
+ relations,
829
+ skippedIds: []
830
+ };
831
+ }
832
+ const hasTable = await ensureTableExists(trx, tableName);
833
+ if (!hasTable) {
834
+ return {
835
+ relations: [],
836
+ skippedIds: Array.from(uniqueIdMap.values())
837
+ };
838
+ }
839
+ const existingKeys = new Set();
840
+ const uniqueIds = Array.from(uniqueIdMap.values());
841
+ const idChunks = chunkArray(uniqueIds, getBatchSize(trx, 1000));
842
+ for (const chunk of idChunks){
843
+ const rows = await trx(tableName).select(primaryKeyColumn).whereIn(primaryKeyColumn, chunk);
844
+ for (const row of rows){
845
+ const value = row[primaryKeyColumn];
846
+ existingKeys.add(toComparisonKey(value));
847
+ }
848
+ }
849
+ const filteredRelations = [];
850
+ const skippedIds = [];
851
+ for (const relation of relations){
852
+ const targetId = getTargetId(relation);
853
+ if (targetId == null) {
854
+ skippedIds.push(targetId);
855
+ continue;
856
+ }
857
+ if (existingKeys.has(toComparisonKey(targetId))) {
858
+ filteredRelations.push(relation);
859
+ } else {
860
+ skippedIds.push(targetId);
861
+ }
862
+ }
863
+ return {
864
+ relations: filteredRelations,
865
+ skippedIds
866
+ };
867
+ }
868
+ /**
869
+ * Locates the owning entity (content type or component) for a given component instance.
870
+ * This mirrors the document service logic we need in order to decide whether a relation
871
+ * should propagate to drafts, and is cached for performance.
872
+ */ async function findComponentParentInstance(trx, identifiers, componentUid, componentId, excludeUid, caches) {
873
+ const cacheKey = `${componentUid}:${componentId}:${excludeUid ?? 'ALL'}`;
874
+ if (caches.parentInstanceCache.has(cacheKey)) {
875
+ return caches.parentInstanceCache.get(cacheKey);
876
+ }
877
+ const parentComponentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
878
+ const parentComponentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
879
+ const parentEntityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
880
+ const potentialParents = listComponentParentSchemas(componentUid).filter((schema)=>schema.uid !== excludeUid);
881
+ for (const parentSchema of potentialParents){
882
+ if (!parentSchema.collectionName) {
883
+ continue;
884
+ }
885
+ const parentJoinTableName = transformContentTypesToModels.getComponentJoinTableName(parentSchema.collectionName, identifiers);
886
+ try {
887
+ if (!await ensureTableExists(trx, parentJoinTableName)) {
888
+ continue;
889
+ }
890
+ const parentRow = await trx(parentJoinTableName).where({
891
+ [parentComponentIdColumn]: componentId,
892
+ [parentComponentTypeColumn]: componentUid
893
+ }).first(parentEntityIdColumn);
894
+ if (parentRow) {
895
+ const parentInstance = {
896
+ uid: parentSchema.uid,
897
+ parentId: parentRow[parentEntityIdColumn]
898
+ };
899
+ caches.parentInstanceCache.set(cacheKey, parentInstance);
900
+ return parentInstance;
901
+ }
902
+ } catch {
903
+ continue;
904
+ }
905
+ }
906
+ caches.parentInstanceCache.set(cacheKey, null);
907
+ return null;
908
+ }
909
+ /**
910
+ * Fetches and caches database metadata for a component uid. Saves repeated lookups while
911
+ * cloning the same component type thousands of times.
912
+ */ const getComponentMeta = (componentUid)=>{
913
+ if (!componentMetaCache.has(componentUid)) {
914
+ const meta = getComponentMetadataByUid(componentUid);
915
+ componentMetaCache.set(componentUid, meta ?? null);
916
+ }
917
+ return componentMetaCache.get(componentUid);
918
+ };
919
+ /**
920
+ * Determines whether a component's parent entity participates in draft/publish,
921
+ * short-circuiting a lot of recursion when deciding relation propagation rules.
922
+ */ async function hasDraftPublishAncestorForParent(trx, identifiers, parent, caches) {
923
+ const cacheKey = `${parent.uid}:${parent.parentId}`;
924
+ if (caches.parentDpCache.has(cacheKey)) {
925
+ return caches.parentDpCache.get(cacheKey);
926
+ }
927
+ const parentContentType = strapi.contentTypes[parent.uid];
928
+ if (parentContentType) {
929
+ const result = !!parentContentType?.options?.draftAndPublish;
930
+ caches.parentDpCache.set(cacheKey, result);
931
+ return result;
932
+ }
933
+ const parentComponent = strapi.components[parent.uid];
934
+ if (!parentComponent) {
935
+ caches.parentDpCache.set(cacheKey, false);
936
+ return false;
937
+ }
938
+ const result = await hasDraftPublishAncestorForComponent(trx, identifiers, parent.uid, parent.parentId, undefined, caches);
939
+ caches.parentDpCache.set(cacheKey, result);
940
+ return result;
941
+ }
942
+ /**
943
+ * Recursively checks whether a component lies beneath a draft/publish-enabled parent
944
+ * component or content type. We mirror discardDraft's propagation guard.
945
+ */ async function hasDraftPublishAncestorForComponent(trx, identifiers, componentUid, componentId, excludeUid, caches) {
946
+ const cacheKey = `${componentUid}:${componentId}:${'ALL'}`;
947
+ if (caches.ancestorDpCache.has(cacheKey)) {
948
+ return caches.ancestorDpCache.get(cacheKey);
949
+ }
950
+ const parent = await findComponentParentInstance(trx, identifiers, componentUid, componentId, excludeUid, caches);
951
+ if (!parent) {
952
+ caches.ancestorDpCache.set(cacheKey, false);
953
+ return false;
954
+ }
955
+ const result = await hasDraftPublishAncestorForParent(trx, identifiers, parent, caches);
956
+ caches.ancestorDpCache.set(cacheKey, result);
957
+ return result;
958
+ }
959
+ /**
960
+ * Abstracts `NOW()` handling so that timestamps stay consistent across databases—
961
+ * using Knex's native function when available and falling back to JS dates otherwise.
962
+ */ const resolveNowValue = (trx)=>{
963
+ if (typeof trx.fn?.now === 'function') {
964
+ return trx.fn.now();
965
+ }
966
+ return new Date();
967
+ };
968
+ /**
969
+ * Builds or retrieves the published→draft id map for a target content type, caching
970
+ * the result so nested relation remapping can reuse the work.
971
+ */ async function getDraftMapForTarget(trx, targetUid, draftMapCache) {
972
+ if (draftMapCache.has(targetUid)) {
973
+ return draftMapCache.get(targetUid) ?? null;
974
+ }
975
+ const targetMeta = strapi.db.metadata.get(targetUid);
976
+ if (!targetMeta) {
977
+ draftMapCache.set(targetUid, null);
978
+ return null;
979
+ }
980
+ const map = await buildPublishedToDraftMap({
981
+ trx,
982
+ uid: targetUid,
983
+ meta: targetMeta,
984
+ options: {
985
+ requireDraftAndPublish: true
986
+ }
987
+ });
988
+ draftMapCache.set(targetUid, map ?? null);
989
+ return map ?? null;
990
+ }
991
+ /**
992
+ * Builds a reverse map from draft IDs to published IDs for a target content type.
993
+ * This is needed to check if a target ID is already a draft and find its published version.
994
+ */ async function getDraftToPublishedMap(trx, targetUid, reverseMapCache, draftMapCache) {
995
+ if (reverseMapCache.has(targetUid)) {
996
+ return reverseMapCache.get(targetUid) ?? null;
997
+ }
998
+ const targetMeta = strapi.db.metadata.get(targetUid);
999
+ if (!targetMeta) {
1000
+ reverseMapCache.set(targetUid, null);
1001
+ return null;
1002
+ }
1003
+ const draftToPublishedMap = new Map();
1004
+ const draftMap = await getDraftMapForTarget(trx, targetUid, draftMapCache ?? new Map());
1005
+ if (draftMap) {
1006
+ // Reverse the published->draft map to get draft->published
1007
+ for (const [publishedId, draftId] of draftMap.entries()){
1008
+ draftToPublishedMap.set(draftId, publishedId);
1009
+ }
1010
+ debug(`[getDraftToPublishedMap] ${targetUid}: Built reverse map with ${draftToPublishedMap.size} entries (draft->published)`);
1011
+ } else {
1012
+ debug(`[getDraftToPublishedMap] ${targetUid}: No draft map found, returning null`);
1013
+ }
1014
+ reverseMapCache.set(targetUid, draftToPublishedMap.size > 0 ? draftToPublishedMap : null);
1015
+ return draftToPublishedMap.size > 0 ? draftToPublishedMap : null;
1016
+ }
1017
+ /**
1018
+ * Checks if a target ID is published or draft by querying the database.
1019
+ */ async function getTargetPublicationState(trx, targetId, targetUid) {
1020
+ const targetMeta = strapi.db.metadata.get(targetUid);
1021
+ if (!targetMeta) {
1022
+ return null;
1023
+ }
1024
+ const target = await trx(targetMeta.tableName).select('published_at').where('id', targetId).first();
1025
+ if (!target) {
1026
+ return null;
1027
+ }
1028
+ return target.published_at !== null ? 'published' : 'draft';
1029
+ }
1030
+ /**
1031
+ * Maps relation foreign keys so that draft entities reference draft targets when those
1032
+ * targets exist; otherwise we preserve the original reference (matching discardDraft).
1033
+ *
1034
+ * When mapping for a draft component: maps published targets → draft targets
1035
+ * When mapping for a published component: maps draft targets → published targets (if needed)
1036
+ */ async function mapTargetId(trx, originalId, targetUid, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity = true, reverseMapCache) {
1037
+ if (originalId == null || !targetUid) {
1038
+ return originalId;
1039
+ }
1040
+ if (targetUid === parentUid) {
1041
+ if (isForDraftEntity) {
1042
+ return parentPublishedToDraftMap.get(Number(originalId)) ?? originalId;
1043
+ }
1044
+ // For published entity, if we got a draft ID, find the published version
1045
+ const effectiveReverseCache = reverseMapCache ?? new Map();
1046
+ const reverseMap = await getDraftToPublishedMap(trx, targetUid, effectiveReverseCache, draftMapCache);
1047
+ if (reverseMap) {
1048
+ return reverseMap.get(Number(originalId)) ?? originalId;
1049
+ }
1050
+ return originalId;
1051
+ }
1052
+ const targetMap = await getDraftMapForTarget(trx, targetUid, draftMapCache);
1053
+ if (!targetMap) {
1054
+ return originalId;
1055
+ }
1056
+ // Check if the original ID is already a draft or published
1057
+ const targetState = await getTargetPublicationState(trx, Number(originalId), targetUid);
1058
+ if (isForDraftEntity) {
1059
+ // For draft entities: map published targets to draft targets
1060
+ if (targetState === 'published') {
1061
+ return targetMap.get(Number(originalId)) ?? originalId;
1062
+ }
1063
+ if (targetState === 'draft') {
1064
+ // Already a draft, keep it
1065
+ return originalId;
1066
+ }
1067
+ // If we can't determine state, try the map lookup
1068
+ return targetMap.get(Number(originalId)) ?? originalId;
1069
+ }
1070
+ // For published entities: map draft targets to published targets
1071
+ if (targetState === 'draft') {
1072
+ const effectiveReverseCache = reverseMapCache ?? new Map();
1073
+ const reverseMap = await getDraftToPublishedMap(trx, targetUid, effectiveReverseCache, draftMapCache);
1074
+ if (reverseMap) {
1075
+ return reverseMap.get(Number(originalId)) ?? originalId;
1076
+ }
1077
+ return originalId;
1078
+ }
1079
+ if (targetState === 'published') {
1080
+ // Already published, keep it
1081
+ return originalId;
1082
+ }
1083
+ // If we can't determine state, assume it's published
1084
+ return originalId;
1085
+ }
1086
+ /**
1087
+ * Clones a database row and strips the `id` column so it can be reinserted as a new row.
1088
+ */ const ensureObjectWithoutId = (row)=>{
1089
+ const cloned = {
1090
+ ...row
1091
+ };
1092
+ if ('id' in cloned) {
1093
+ delete cloned.id;
1094
+ }
1095
+ return cloned;
1096
+ };
1097
+ /**
1098
+ * Duplicates join-table relations for a component instance while remapping any foreign
1099
+ * keys to draft targets. Mirrors the runtime clone logic but operates entirely in SQL.
1100
+ */ async function cloneComponentRelationJoinTables(trx, componentMeta, componentUid, originalComponentId, newComponentId, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity = true, reverseMapCache) {
1101
+ for (const [attributeName, attribute] of Object.entries(componentMeta.attributes)){
1102
+ if (attribute.type !== 'relation' || !attribute.joinTable) {
1103
+ continue;
1104
+ }
1105
+ const rawComponentAttribute = strapi.components[componentUid]?.attributes?.[attributeName];
1106
+ // Component and dynamic zone links need deep cloning of target component rows.
1107
+ // Skip the generic join-table copier so the recursive clone path can handle them.
1108
+ if (rawComponentAttribute?.type === 'component' || rawComponentAttribute?.type === 'dynamiczone') {
1109
+ continue;
1110
+ }
1111
+ const joinTable = attribute.joinTable;
1112
+ const sourceColumnName = joinTable.joinColumn.name;
1113
+ // Morph join tables use morphColumn instead of inverseJoinColumn — skip them
1114
+ if (!joinTable.inverseJoinColumn) {
1115
+ continue;
1116
+ }
1117
+ const targetColumnName = joinTable.inverseJoinColumn.name;
1118
+ if (!componentMeta.relationsLogPrinted) {
1119
+ debug(`[cloneComponentRelationJoinTables] Inspecting join table ${joinTable.name} for component ${componentUid}`);
1120
+ componentMeta.relationsLogPrinted = true;
1121
+ }
1122
+ const relations = await trx(joinTable.name).select('*').where(sourceColumnName, originalComponentId);
1123
+ if (relations.length === 0) {
1124
+ continue;
1125
+ }
1126
+ const preparedRelations = [];
1127
+ for (const relation of relations){
1128
+ const clonedRelation = ensureObjectWithoutId(relation);
1129
+ clonedRelation[sourceColumnName] = newComponentId;
1130
+ if (targetColumnName in clonedRelation) {
1131
+ const originalTargetId = clonedRelation[targetColumnName];
1132
+ clonedRelation[targetColumnName] = await mapTargetId(trx, clonedRelation[targetColumnName], attribute.target, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity, reverseMapCache);
1133
+ debug(`[cloneComponentRelationJoinTables] ${componentUid} join ${joinTable.name}: mapped ${targetColumnName} from ${originalTargetId} to ${clonedRelation[targetColumnName]} (target=${attribute.target})`);
1134
+ }
1135
+ preparedRelations.push(clonedRelation);
1136
+ }
1137
+ let relationsToInsert = preparedRelations;
1138
+ if (preparedRelations.some((relation)=>targetColumnName in relation)) {
1139
+ const { relations: safeRelations, skippedIds } = await filterRelationsWithExistingTargets({
1140
+ trx,
1141
+ targetUid: attribute.target,
1142
+ relations: preparedRelations,
1143
+ getTargetId: (relation)=>relation[targetColumnName]
1144
+ });
1145
+ recordSkippedRelations({
1146
+ sourceUid: componentUid,
1147
+ attributeName,
1148
+ targetUid: attribute.target,
1149
+ joinTable: joinTable.name
1150
+ }, skippedIds);
1151
+ relationsToInsert = safeRelations;
1152
+ }
1153
+ if (relationsToInsert.length === 0) {
1154
+ continue;
1155
+ }
1156
+ for (const relation of relationsToInsert){
1157
+ // Ensure we're only creating relations for the NEW component, not the original
1158
+ // The sourceColumnName must be newComponentId to ensure we don't accidentally modify
1159
+ // the original published component's relations
1160
+ if (relation[sourceColumnName] !== newComponentId) {
1161
+ debug(`[cloneComponentRelationJoinTables] ERROR: Relation source ${relation[sourceColumnName]} does not match newComponentId ${newComponentId} - skipping to prevent modifying original component relations`);
1162
+ continue;
1163
+ }
1164
+ debug(`[cloneComponentRelationJoinTables] inserting relation into ${joinTable.name} (component=${componentUid}, source=${relation[sourceColumnName]}, target=${relation[targetColumnName]})`);
1165
+ await insertRowWithDuplicateHandling(trx, joinTable.name, relation, {
1166
+ componentUid,
1167
+ originalComponentId,
1168
+ newComponentId,
1169
+ joinTable: joinTable.name,
1170
+ sourceColumnName,
1171
+ targetColumnName,
1172
+ targetUid: attribute.target,
1173
+ parentUid
1174
+ });
1175
+ }
1176
+ }
1177
+ }
1178
+ /**
1179
+ * Clones a component row (including nested relations) so the newly created draft entity
1180
+ * owns its own copy, matching what the document service would have produced.
1181
+ */ async function cloneComponentInstance({ trx, componentUid, componentId, parentUid, parentPublishedToDraftMap, draftMapCache, clonedComponentPairsCache, isForDraftEntity = true, reverseMapCache }) {
1182
+ const componentMeta = getComponentMeta(componentUid);
1183
+ if (!componentMeta) {
1184
+ return componentId;
1185
+ }
1186
+ const componentTableName = componentMeta.tableName;
1187
+ const componentPrimaryKey = Number.isNaN(Number(componentId)) ? componentId : Number(componentId);
1188
+ const componentRow = await trx(componentTableName).select('*').where('id', componentPrimaryKey).first();
1189
+ if (!componentRow) {
1190
+ return componentId;
1191
+ }
1192
+ const newComponentRow = ensureObjectWithoutId(componentRow);
1193
+ // `document_id`, `created_at`, `updated_at` are Strapi system columns whose names remain stable across the
1194
+ // identifier-shortening migration, so it’s safe to check them directly here.
1195
+ if ('document_id' in newComponentRow) {
1196
+ newComponentRow.document_id = cuid2.createId();
1197
+ }
1198
+ if ('updated_at' in newComponentRow) {
1199
+ newComponentRow.updated_at = resolveNowValue(trx);
1200
+ }
1201
+ if ('created_at' in newComponentRow && newComponentRow.created_at == null) {
1202
+ newComponentRow.created_at = resolveNowValue(trx);
1203
+ }
1204
+ for (const attribute of Object.values(componentMeta.attributes)){
1205
+ if (!isPersistedJoinColumnRelation(attribute)) {
1206
+ continue;
1207
+ }
1208
+ const joinColumn = attribute.joinColumn;
1209
+ if (!joinColumn) {
1210
+ continue;
1211
+ }
1212
+ const columnName = joinColumn.name;
1213
+ if (!columnName || !(columnName in newComponentRow)) {
1214
+ continue;
1215
+ }
1216
+ newComponentRow[columnName] = await mapTargetId(trx, newComponentRow[columnName], attribute.target, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity, reverseMapCache);
1217
+ }
1218
+ let insertResult;
1219
+ if (supportsReturning(trx)) {
1220
+ try {
1221
+ insertResult = await trx(componentTableName).insert(newComponentRow, [
1222
+ 'id'
1223
+ ]);
1224
+ } catch (error) {
1225
+ insertResult = await trx(componentTableName).insert(newComponentRow);
1226
+ }
1227
+ } else {
1228
+ insertResult = await trx(componentTableName).insert(newComponentRow);
1229
+ }
1230
+ let newComponentId = resolveInsertedId(insertResult);
1231
+ if (!newComponentId) {
1232
+ if ('document_id' in newComponentRow && newComponentRow.document_id) {
1233
+ const insertedRow = await trx(componentTableName).select('id').where('document_id', newComponentRow.document_id).orderBy('id', 'desc').first();
1234
+ newComponentId = insertedRow?.id ?? null;
1235
+ }
1236
+ if (!newComponentId) {
1237
+ const insertedRow = await trx(componentTableName).select('id').orderBy('id', 'desc').first();
1238
+ newComponentId = insertedRow?.id ?? null;
1239
+ }
1240
+ }
1241
+ if (!newComponentId) {
1242
+ throw new Error(`Failed to clone component ${componentUid} (id: ${componentId})`);
1243
+ }
1244
+ newComponentId = Number(newComponentId);
1245
+ if (Number.isNaN(newComponentId)) {
1246
+ throw new Error(`Invalid cloned component identifier for ${componentUid} (id: ${componentId})`);
1247
+ }
1248
+ recordClonedComponentPair(clonedComponentPairsCache, componentUid, Number(componentPrimaryKey), newComponentId);
1249
+ await cloneComponentRelationJoinTables(trx, componentMeta, componentUid, Number(componentPrimaryKey), newComponentId, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity, reverseMapCache);
1250
+ // Clone nested components (component and dynamiczone attributes) so draft has its own copy
1251
+ const componentSchema = strapi.components[componentUid];
1252
+ const collectionName = componentSchema?.collectionName;
1253
+ if (collectionName && componentSchema?.attributes) {
1254
+ const identifiers = strapi.db.metadata.identifiers;
1255
+ const entityIdCol = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
1256
+ const componentIdCol = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
1257
+ const componentTypeCol = transformContentTypesToModels.getComponentTypeColumn(identifiers);
1258
+ const fieldCol = identifiers.FIELD_COLUMN;
1259
+ // Use the raw component schema here: DB metadata transforms component/DZ attrs into relations,
1260
+ // so their original `type` values are only available on the schema definition.
1261
+ for (const [attrName, attr] of Object.entries(componentSchema.attributes || {})){
1262
+ if (attr.type === 'component') {
1263
+ const nestedJoinTableName = transformContentTypesToModels.getComponentJoinTableName(collectionName, identifiers);
1264
+ if (!await ensureTableExists(trx, nestedJoinTableName)) continue;
1265
+ const nestedRows = await trx(nestedJoinTableName).select('*').where(entityIdCol, componentPrimaryKey).where(componentTypeCol, attr.component).where(fieldCol, attrName);
1266
+ for (const row of nestedRows){
1267
+ const nestedId = Number(row[componentIdCol]);
1268
+ if (Number.isNaN(nestedId)) continue;
1269
+ const newNestedId = await cloneComponentInstance({
1270
+ trx,
1271
+ componentUid: attr.component,
1272
+ componentId: nestedId,
1273
+ parentUid: componentUid,
1274
+ parentPublishedToDraftMap,
1275
+ draftMapCache,
1276
+ clonedComponentPairsCache,
1277
+ isForDraftEntity,
1278
+ reverseMapCache
1279
+ });
1280
+ const { id, ...rest } = row;
1281
+ await insertRowWithDuplicateHandling(trx, nestedJoinTableName, {
1282
+ ...rest,
1283
+ [entityIdCol]: newComponentId,
1284
+ [componentIdCol]: newNestedId
1285
+ });
1286
+ }
1287
+ } else if (attr.type === 'dynamiczone' && Array.isArray(attr.components)) {
1288
+ const dzJoinTableName = transformContentTypesToModels.getDzJoinTableName(collectionName, identifiers);
1289
+ if (!await ensureTableExists(trx, dzJoinTableName)) continue;
1290
+ const dzRows = await trx(dzJoinTableName).select('*').where(entityIdCol, componentPrimaryKey).where(fieldCol, attrName);
1291
+ for (const row of dzRows){
1292
+ const nestedType = row[componentTypeCol];
1293
+ const nestedId = Number(row[componentIdCol]);
1294
+ if (!nestedType || Number.isNaN(nestedId)) continue;
1295
+ const newNestedId = await cloneComponentInstance({
1296
+ trx,
1297
+ componentUid: nestedType,
1298
+ componentId: nestedId,
1299
+ parentUid: componentUid,
1300
+ parentPublishedToDraftMap,
1301
+ draftMapCache,
1302
+ clonedComponentPairsCache,
1303
+ isForDraftEntity,
1304
+ reverseMapCache
1305
+ });
1306
+ const { id, ...rest } = row;
1307
+ await insertRowWithDuplicateHandling(trx, dzJoinTableName, {
1308
+ ...rest,
1309
+ [entityIdCol]: newComponentId,
1310
+ [componentIdCol]: newNestedId
1311
+ });
1312
+ }
1313
+ }
1314
+ }
1315
+ }
1316
+ return newComponentId;
1317
+ }
1318
+ /**
1319
+ * Generates a map between published row ids and their corresponding draft ids so we can
1320
+ * rewire relations in bulk. Handles localization nuances and caches the newest draft.
1321
+ */ async function buildPublishedToDraftMap({ trx, uid, meta, options = {} }) {
1322
+ if (!meta) {
1323
+ return null;
1324
+ }
1325
+ const model = strapi.getModel(uid);
1326
+ const hasDraftAndPublishEnabled = strapiUtils.contentTypes.hasDraftAndPublish(model);
1327
+ if (options.requireDraftAndPublish && !hasDraftAndPublishEnabled) {
1328
+ return null;
1329
+ }
1330
+ const [publishedEntries, draftEntries] = await Promise.all([
1331
+ // `document_id`, `locale`, and `published_at` are core columns that keep their exact names after the
1332
+ // identifier-shortening migration, so selecting them by literal is safe.
1333
+ trx(meta.tableName).select([
1334
+ 'id',
1335
+ 'document_id',
1336
+ 'locale'
1337
+ ]).whereNotNull('published_at'),
1338
+ trx(meta.tableName).select([
1339
+ 'id',
1340
+ 'document_id',
1341
+ 'locale'
1342
+ ]).whereNull('published_at')
1343
+ ]);
1344
+ if (publishedEntries.length === 0 || draftEntries.length === 0) {
1345
+ return null;
1346
+ }
1347
+ const i18nService = strapi.plugin('i18n')?.service('content-types');
1348
+ const contentType = strapi.contentTypes[uid];
1349
+ const isLocalized = i18nService?.isLocalizedContentType(contentType) ?? false;
1350
+ const draftByDocumentId = new Map();
1351
+ for (const draft of draftEntries){
1352
+ if (!draft.document_id) {
1353
+ continue;
1354
+ }
1355
+ const key = isLocalized ? `${draft.document_id}:${draft.locale || ''}` : draft.document_id;
1356
+ const existing = draftByDocumentId.get(key);
1357
+ if (!existing) {
1358
+ draftByDocumentId.set(key, draft);
1359
+ continue;
1360
+ }
1361
+ const existingId = Number(existing.id);
1362
+ const draftId = Number(draft.id);
1363
+ if (Number.isNaN(existingId) || Number.isNaN(draftId)) {
1364
+ draftByDocumentId.set(key, draft);
1365
+ continue;
1366
+ }
1367
+ if (draftId > existingId) {
1368
+ draftByDocumentId.set(key, draft);
1369
+ }
1370
+ }
1371
+ const publishedToDraftMap = new Map();
1372
+ for (const published of publishedEntries){
1373
+ if (!published.document_id) {
1374
+ continue;
1375
+ }
1376
+ const key = isLocalized ? `${published.document_id}:${published.locale || ''}` : published.document_id;
1377
+ const draft = draftByDocumentId.get(key);
1378
+ if (draft) {
1379
+ const publishedId = normalizeId(published.id);
1380
+ const draftId = normalizeId(draft.id);
1381
+ if (publishedId == null || draftId == null) {
1382
+ continue;
1383
+ }
1384
+ publishedToDraftMap.set(publishedId, draftId);
1385
+ }
1386
+ }
1387
+ return publishedToDraftMap.size > 0 ? publishedToDraftMap : null;
1388
+ }
1389
+ /**
1390
+ * Copy relations within the same content type (self-referential relations)
1391
+ */ async function copyRelationsForContentType({ trx, uid, publishedToDraftMap }) {
1392
+ const meta = strapi.db.metadata.get(uid);
1393
+ if (!meta) return;
1394
+ const publishedIds = Array.from(publishedToDraftMap.keys());
1395
+ for (const attribute of Object.values(meta.attributes)){
1396
+ if (attribute.type !== 'relation' || attribute.target !== uid) {
1397
+ continue;
1398
+ }
1399
+ const joinTable = attribute.joinTable;
1400
+ if (!joinTable) {
1401
+ continue;
1402
+ }
1403
+ // Skip component join tables - they are handled by copyComponentRelations
1404
+ if (joinTable.name.includes('_cmps')) {
1405
+ continue;
1406
+ }
1407
+ const { name: sourceColumnName } = joinTable.joinColumn;
1408
+ // Morph join tables use morphColumn instead of inverseJoinColumn — skip them
1409
+ if (!joinTable.inverseJoinColumn) {
1410
+ continue;
1411
+ }
1412
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1413
+ // Process in batches to avoid MySQL query size limits and SQLite expression tree limits
1414
+ const publishedIdsChunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
1415
+ for (const publishedIdsChunk of publishedIdsChunks){
1416
+ const draftSourceIds = publishedIdsChunk.map((value)=>getMappedValue(publishedToDraftMap, value)).filter((value)=>value != null);
1417
+ // Get relations where the source is a published entry (in batches)
1418
+ const relationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, publishedIdsChunk);
1419
+ applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
1420
+ const relations = await relationsQuery;
1421
+ if (relations.length === 0) {
1422
+ continue;
1423
+ }
1424
+ // Create new relations pointing to draft entries
1425
+ // Remove the 'id' field to avoid duplicate key errors
1426
+ const newRelations = relations.map((relation)=>{
1427
+ const newSourceId = getMappedValue(publishedToDraftMap, relation[sourceColumnName]);
1428
+ const newTargetId = getMappedValue(publishedToDraftMap, relation[targetColumnName]);
1429
+ if (!newSourceId || !newTargetId) {
1430
+ // Skip if no mapping found
1431
+ return null;
1432
+ }
1433
+ // Create new relation object without the 'id' field
1434
+ const { id, ...relationWithoutId } = relation;
1435
+ return {
1436
+ ...relationWithoutId,
1437
+ [sourceColumnName]: newSourceId,
1438
+ [targetColumnName]: newTargetId
1439
+ };
1440
+ }).filter(Boolean);
1441
+ if (newRelations.length === 0) {
1442
+ continue;
1443
+ }
1444
+ const existingKeys = await getExistingRelationKeys({
1445
+ trx,
1446
+ joinTable,
1447
+ sourceColumnName,
1448
+ targetColumnName,
1449
+ sourceIds: draftSourceIds
1450
+ });
1451
+ const relationsToInsert = newRelations.filter((relation)=>{
1452
+ const targetId = normalizeId(relation[targetColumnName]) ?? relation[targetColumnName];
1453
+ const key = buildRelationKey(relation, sourceColumnName, targetId);
1454
+ return !existingKeys.has(key);
1455
+ });
1456
+ if (relationsToInsert.length === 0) {
1457
+ continue;
1458
+ }
1459
+ await insertRelationsWithDuplicateHandling({
1460
+ trx,
1461
+ tableName: joinTable.name,
1462
+ relations: relationsToInsert,
1463
+ context: {
1464
+ reason: 'duplicate-self-relation-check',
1465
+ sourceUid: uid,
1466
+ targetUid: uid
1467
+ }
1468
+ });
1469
+ }
1470
+ }
1471
+ }
1472
+ /**
1473
+ * Copy relations from other content types that target this content type
1474
+ */ async function copyRelationsFromOtherContentTypes({ trx, uid, publishedToDraftMap }) {
1475
+ const targetMeta = strapi.db.metadata.get(uid);
1476
+ if (!targetMeta) {
1477
+ return;
1478
+ }
1479
+ const publishedTargetIds = Array.from(publishedToDraftMap.keys()).map((value)=>normalizeId(value)).filter((value)=>value != null);
1480
+ if (publishedTargetIds.length === 0) {
1481
+ return;
1482
+ }
1483
+ const draftTargetIds = Array.from(publishedToDraftMap.values()).map((value)=>normalizeId(value)).filter((value)=>value != null);
1484
+ const models = [
1485
+ ...Object.values(strapi.contentTypes),
1486
+ ...Object.values(strapi.components)
1487
+ ];
1488
+ for (const model of models){
1489
+ const dbModel = strapi.db.metadata.get(model.uid);
1490
+ if (!dbModel) {
1491
+ continue;
1492
+ }
1493
+ const sourceHasDraftAndPublish = Boolean(model.options?.draftAndPublish);
1494
+ for (const attribute of Object.values(dbModel.attributes)){
1495
+ if (attribute.type !== 'relation' || attribute.target !== uid) {
1496
+ continue;
1497
+ }
1498
+ const joinTable = attribute.joinTable;
1499
+ if (!joinTable) {
1500
+ continue;
1501
+ }
1502
+ // Component join tables are handled separately when cloning components.
1503
+ if (joinTable.name.includes('_cmps')) {
1504
+ continue;
1505
+ }
1506
+ // If the source content type also has draft/publish, its own cloning routine will recreate its relations.
1507
+ if (sourceHasDraftAndPublish) {
1508
+ continue;
1509
+ }
1510
+ const { name: sourceColumnName } = joinTable.joinColumn;
1511
+ if (!joinTable.inverseJoinColumn) {
1512
+ continue;
1513
+ }
1514
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1515
+ // Query existing relations by target IDs to avoid duplicates
1516
+ const existingKeys = await getExistingRelationKeys({
1517
+ trx,
1518
+ joinTable,
1519
+ sourceColumnName,
1520
+ targetColumnName,
1521
+ sourceIds: draftTargetIds
1522
+ });
1523
+ const publishedIdChunks = chunkArray(publishedTargetIds, getBatchSize(trx, 1000));
1524
+ for (const chunk of publishedIdChunks){
1525
+ const relationsQuery = trx(joinTable.name).select('*').whereIn(targetColumnName, chunk);
1526
+ applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
1527
+ const relations = await relationsQuery;
1528
+ if (relations.length === 0) {
1529
+ continue;
1530
+ }
1531
+ const newRelations = [];
1532
+ for (const relation of relations){
1533
+ const newTargetId = getMappedValue(publishedToDraftMap, relation[targetColumnName]);
1534
+ if (!newTargetId) {
1535
+ continue;
1536
+ }
1537
+ const key = buildRelationKey(relation, sourceColumnName, newTargetId);
1538
+ if (existingKeys.has(key)) {
1539
+ continue;
1540
+ }
1541
+ existingKeys.add(key);
1542
+ const { id, ...relationWithoutId } = relation;
1543
+ newRelations.push({
1544
+ ...relationWithoutId,
1545
+ [targetColumnName]: newTargetId
1546
+ });
1547
+ }
1548
+ if (newRelations.length === 0) {
1549
+ continue;
1550
+ }
1551
+ await insertRelationsWithDuplicateHandling({
1552
+ trx,
1553
+ tableName: joinTable.name,
1554
+ relations: newRelations,
1555
+ context: {
1556
+ reason: 'duplicate-draft-target-relation',
1557
+ sourceUid: model.uid,
1558
+ targetUid: uid
1559
+ }
1560
+ });
1561
+ }
1562
+ }
1563
+ }
1564
+ }
1565
+ /**
1566
+ * Copy relations from this content type that target other content types (category 3)
1567
+ * Example: Article -> Categories/Tags
1568
+ */ async function copyRelationsToOtherContentTypes({ trx, uid, publishedToDraftMap }) {
1569
+ const meta = strapi.db.metadata.get(uid);
1570
+ if (!meta) return;
1571
+ const publishedIds = Array.from(publishedToDraftMap.keys());
1572
+ // Cache target publishedToDraftMap to avoid duplicate calls for same target
1573
+ const targetMapCache = new Map();
1574
+ for (const [attributeName, attribute] of Object.entries(meta.attributes)){
1575
+ if (attribute.type !== 'relation' || attribute.target === uid) {
1576
+ continue;
1577
+ }
1578
+ const joinTable = attribute.joinTable;
1579
+ if (!joinTable) {
1580
+ continue;
1581
+ }
1582
+ // Skip component join tables - they are handled by copyComponentRelations
1583
+ if (joinTable.name.includes('_cmps')) {
1584
+ continue;
1585
+ }
1586
+ const { name: sourceColumnName } = joinTable.joinColumn;
1587
+ if (!joinTable.inverseJoinColumn) {
1588
+ continue;
1589
+ }
1590
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1591
+ // Get target content type's publishedToDraftMap if it has draft/publish (cached)
1592
+ const targetUid = attribute.target;
1593
+ if (!targetMapCache.has(targetUid)) {
1594
+ const targetMeta = strapi.db.metadata.get(targetUid);
1595
+ const targetMap = await buildPublishedToDraftMap({
1596
+ trx,
1597
+ uid: targetUid,
1598
+ meta: targetMeta,
1599
+ options: {
1600
+ requireDraftAndPublish: true
1601
+ }
1602
+ });
1603
+ targetMapCache.set(targetUid, targetMap);
1604
+ }
1605
+ const targetPublishedToDraftMap = targetMapCache.get(targetUid);
1606
+ // Process in batches to avoid MySQL query size limits and SQLite expression tree limits
1607
+ const publishedIdsChunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
1608
+ for (const publishedIdsChunk of publishedIdsChunks){
1609
+ // Get relations where the source is a published entry of our content type (in batches)
1610
+ const relationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, publishedIdsChunk);
1611
+ applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
1612
+ const relations = await relationsQuery;
1613
+ if (relations.length === 0) {
1614
+ continue;
1615
+ }
1616
+ // Create new relations pointing to draft entries
1617
+ // Remove the 'id' field to avoid duplicate key errors
1618
+ const newRelations = relations.map((relation)=>{
1619
+ const newSourceId = getMappedValue(publishedToDraftMap, relation[sourceColumnName]);
1620
+ if (!newSourceId) {
1621
+ return null;
1622
+ }
1623
+ // Map target ID to draft if target has draft/publish enabled
1624
+ // This matches discard() behavior: drafts relate to drafts
1625
+ let newTargetId = relation[targetColumnName];
1626
+ if (targetPublishedToDraftMap) {
1627
+ const mappedTargetId = getMappedValue(targetPublishedToDraftMap, relation[targetColumnName]);
1628
+ if (mappedTargetId !== undefined) {
1629
+ newTargetId = mappedTargetId;
1630
+ }
1631
+ // If no draft mapping, keep published target (target might not have DP or was deleted)
1632
+ // This will be fixed by fixExistingDraftRelations if needed
1633
+ }
1634
+ // Create new relation object without the 'id' field
1635
+ const { id, ...relationWithoutId } = relation;
1636
+ return {
1637
+ ...relationWithoutId,
1638
+ [sourceColumnName]: newSourceId,
1639
+ [targetColumnName]: newTargetId
1640
+ };
1641
+ }).filter(Boolean);
1642
+ const { relations: safeRelations, skippedIds } = await filterRelationsWithExistingTargets({
1643
+ trx,
1644
+ targetUid,
1645
+ relations: newRelations,
1646
+ getTargetId: (relation)=>relation[targetColumnName]
1647
+ });
1648
+ recordSkippedRelations({
1649
+ sourceUid: uid,
1650
+ attributeName,
1651
+ targetUid,
1652
+ joinTable: joinTable.name
1653
+ }, skippedIds);
1654
+ if (safeRelations.length === 0) {
1655
+ continue;
1656
+ }
1657
+ // Check for existing relations to avoid duplicates (similar to copyRelationsFromOtherContentTypes)
1658
+ // This is important when the target doesn't have D&P, as copyRelationsFromOtherContentTypes
1659
+ // may have already created some relations
1660
+ const draftSourceIds = Array.from(publishedToDraftMap.values()).map((value)=>normalizeId(value)).filter((value)=>value != null);
1661
+ const existingKeys = await getExistingRelationKeys({
1662
+ trx,
1663
+ joinTable,
1664
+ sourceColumnName,
1665
+ targetColumnName,
1666
+ sourceIds: draftSourceIds
1667
+ });
1668
+ // Filter out relations that already exist
1669
+ const relationsToInsert = safeRelations.filter((relation)=>{
1670
+ const targetId = normalizeId(relation[targetColumnName]) ?? relation[targetColumnName];
1671
+ const key = buildRelationKey(relation, sourceColumnName, targetId);
1672
+ return !existingKeys.has(key);
1673
+ });
1674
+ if (relationsToInsert.length > 0) {
1675
+ await insertRelationsWithDuplicateHandling({
1676
+ trx,
1677
+ tableName: joinTable.name,
1678
+ relations: relationsToInsert,
1679
+ context: {
1680
+ reason: 'duplicate-relation-check',
1681
+ sourceUid: uid,
1682
+ targetUid
1683
+ }
1684
+ });
1685
+ }
1686
+ }
1687
+ }
1688
+ }
1689
+ /**
1690
+ * Update JoinColumn relations (oneToOne, manyToOne foreign keys) to point to draft versions
1691
+ * This matches discard() behavior: when creating drafts, foreign keys should point to draft targets
1692
+ */ async function updateJoinColumnRelations({ db, trx, uid }) {
1693
+ const meta = db.metadata.get(uid);
1694
+ if (!meta) {
1695
+ return;
1696
+ }
1697
+ // Create mapping from published entry ID to draft entry ID
1698
+ const publishedToDraftMap = await buildPublishedToDraftMap({
1699
+ trx,
1700
+ uid,
1701
+ meta
1702
+ });
1703
+ if (!publishedToDraftMap || publishedToDraftMap.size === 0) {
1704
+ return;
1705
+ }
1706
+ // Cache target publishedToDraftMap to avoid duplicate calls for same target
1707
+ const targetMapCache = new Map();
1708
+ // Find all JoinColumn relations (oneToOne, manyToOne without joinTable)
1709
+ for (const attribute of Object.values(meta.attributes)){
1710
+ if (!isPersistedJoinColumnRelation(attribute)) {
1711
+ continue;
1712
+ }
1713
+ const joinColumn = attribute.joinColumn;
1714
+ if (!joinColumn) {
1715
+ continue;
1716
+ }
1717
+ const targetUid = attribute.target;
1718
+ const foreignKeyColumn = joinColumn.name;
1719
+ // Get target content type's publishedToDraftMap if it has draft/publish (cached)
1720
+ if (!targetMapCache.has(targetUid)) {
1721
+ const targetMeta = strapi.db.metadata.get(targetUid);
1722
+ const targetMap = await buildPublishedToDraftMap({
1723
+ trx,
1724
+ uid: targetUid,
1725
+ meta: targetMeta,
1726
+ options: {
1727
+ requireDraftAndPublish: true
1728
+ }
1729
+ });
1730
+ targetMapCache.set(targetUid, targetMap);
1731
+ }
1732
+ const targetPublishedToDraftMap = targetMapCache.get(targetUid);
1733
+ if (!targetPublishedToDraftMap) {
1734
+ continue;
1735
+ }
1736
+ const draftIds = Array.from(publishedToDraftMap.values());
1737
+ if (draftIds.length === 0) {
1738
+ continue;
1739
+ }
1740
+ const draftIdsChunks = chunkArray(draftIds, getBatchSize(trx, 1000));
1741
+ for (const draftIdsChunk of draftIdsChunks){
1742
+ // Get draft entries with their foreign key values
1743
+ const draftEntriesWithFk = await trx(meta.tableName).select([
1744
+ 'id',
1745
+ foreignKeyColumn
1746
+ ]).whereIn('id', draftIdsChunk).whereNotNull(foreignKeyColumn);
1747
+ const updates = draftEntriesWithFk.reduce((acc, draftEntry)=>{
1748
+ const publishedTargetIdRaw = draftEntry[foreignKeyColumn];
1749
+ const normalizedPublishedTargetId = normalizeId(publishedTargetIdRaw);
1750
+ const draftTargetId = normalizedPublishedTargetId == null ? undefined : targetPublishedToDraftMap.get(normalizedPublishedTargetId);
1751
+ if (draftTargetId != null && normalizeId(draftTargetId) !== normalizedPublishedTargetId) {
1752
+ acc.push({
1753
+ id: draftEntry.id,
1754
+ draftTargetId
1755
+ });
1756
+ }
1757
+ return acc;
1758
+ }, []);
1759
+ if (updates.length === 0) {
1760
+ continue;
1761
+ }
1762
+ const caseFragments = updates.map(()=>'WHEN ? THEN ?').join(' ');
1763
+ const idsPlaceholders = updates.map(()=>'?').join(', ');
1764
+ await trx.raw(`UPDATE ?? SET ?? = CASE ?? ${caseFragments} ELSE ?? END WHERE ?? IN (${idsPlaceholders})`, [
1765
+ meta.tableName,
1766
+ foreignKeyColumn,
1767
+ 'id',
1768
+ ...updates.flatMap(({ id, draftTargetId })=>[
1769
+ id,
1770
+ draftTargetId
1771
+ ]),
1772
+ foreignKeyColumn,
1773
+ 'id',
1774
+ ...updates.map(({ id })=>id)
1775
+ ]);
1776
+ }
1777
+ }
1778
+ }
1779
+ /**
1780
+ * Fixes existing v4 draft entries' join table relations by converting published targets to draft targets.
1781
+ * This ensures that draft entries point to draft targets, not published ones.
1782
+ */ async function fixExistingDraftRelations({ trx, uid }) {
1783
+ const meta = strapi.db.metadata.get(uid);
1784
+ if (!meta) {
1785
+ return;
1786
+ }
1787
+ // Get all draft entity IDs (including existing v4 drafts, not just newly created ones)
1788
+ const draftEntities = await trx(meta.tableName).select('id').whereNull('published_at');
1789
+ if (draftEntities.length === 0) {
1790
+ return;
1791
+ }
1792
+ const draftIds = draftEntities.map((e)=>Number(e.id));
1793
+ const draftIdsChunks = chunkArray(draftIds, getBatchSize(trx, 1000));
1794
+ const draftMapCache = new Map();
1795
+ for (const [attributeName, attribute] of Object.entries(meta.attributes)){
1796
+ if (attribute.type !== 'relation') {
1797
+ continue;
1798
+ }
1799
+ const joinTable = attribute.joinTable;
1800
+ if (!joinTable) {
1801
+ continue;
1802
+ }
1803
+ // Skip component join tables - they are handled by fixExistingDraftComponentRelations
1804
+ if (joinTable.name.includes('_cmps')) {
1805
+ continue;
1806
+ }
1807
+ // Skip self-referential relations - they're handled by copyRelationsForContentType
1808
+ if (attribute.target === uid) {
1809
+ continue;
1810
+ }
1811
+ const targetUid = attribute.target;
1812
+ if (!targetUid) {
1813
+ continue;
1814
+ }
1815
+ const targetContentType = strapi.contentTypes[targetUid];
1816
+ const targetHasDP = targetContentType?.options?.draftAndPublish;
1817
+ if (!targetHasDP) {
1818
+ continue;
1819
+ }
1820
+ const { name: sourceColumnName } = joinTable.joinColumn;
1821
+ if (!joinTable.inverseJoinColumn) {
1822
+ continue;
1823
+ }
1824
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1825
+ // Get draft map for target to convert published targets to draft targets
1826
+ const targetDraftMap = await getDraftMapForTarget(trx, targetUid, draftMapCache);
1827
+ if (!targetDraftMap || targetDraftMap.size === 0) {
1828
+ continue;
1829
+ }
1830
+ // Get target publication states
1831
+ const targetMeta = strapi.db.metadata.get(targetUid);
1832
+ if (!targetMeta) {
1833
+ continue;
1834
+ }
1835
+ for (const draftIdsChunk of draftIdsChunks){
1836
+ // Get all relations for these draft entries
1837
+ const relations = await trx(joinTable.name).whereIn(sourceColumnName, draftIdsChunk).select('id', sourceColumnName, targetColumnName);
1838
+ if (relations.length === 0) {
1839
+ continue;
1840
+ }
1841
+ const targetIds = [
1842
+ ...new Set(relations.map((r)=>r[targetColumnName]).filter(Boolean))
1843
+ ];
1844
+ if (targetIds.length === 0) {
1845
+ continue;
1846
+ }
1847
+ const targets = await trx(targetMeta.tableName).whereIn('id', targetIds).select('id', 'published_at');
1848
+ const targetPublicationState = new Map(targets.map((t)=>[
1849
+ Number(t.id),
1850
+ t.published_at !== null ? 'published' : 'draft'
1851
+ ]));
1852
+ // Find relations from draft entries to published targets and convert them
1853
+ const relationsToUpdate = [];
1854
+ for (const relation of relations){
1855
+ const targetId = Number(relation[targetColumnName]);
1856
+ const targetState = targetPublicationState.get(targetId);
1857
+ if (targetState === 'published') {
1858
+ // This is a relation from a draft entry to a published target - convert to draft target
1859
+ const draftTargetId = targetDraftMap.get(targetId);
1860
+ if (draftTargetId != null) {
1861
+ relationsToUpdate.push({
1862
+ relationId: relation.id,
1863
+ sourceId: Number(relation[sourceColumnName]),
1864
+ oldTargetId: targetId,
1865
+ newTargetId: draftTargetId
1866
+ });
1867
+ }
1868
+ }
1869
+ }
1870
+ if (relationsToUpdate.length > 0) {
1871
+ debug(`[fixExistingDraftRelations] ${uid}: Converting ${relationsToUpdate.length} relations from draft entries to published targets -> draft targets (attribute: ${attributeName}, target: ${targetUid})`);
1872
+ const updateChunks = chunkArray(relationsToUpdate, getBatchSize(trx, 1000));
1873
+ for (const updateChunk of updateChunks){
1874
+ // Preload existing relations for this chunk to avoid N+1 lookups.
1875
+ const existingRelationMap = await buildExistingRelationMap({
1876
+ trx,
1877
+ tableName: joinTable.name,
1878
+ sourceColumnName,
1879
+ targetColumnName,
1880
+ updates: updateChunk.map((update)=>({
1881
+ sourceId: update.sourceId,
1882
+ newTargetId: update.newTargetId
1883
+ })),
1884
+ batchSize: getBatchSize(trx, 100)
1885
+ });
1886
+ for (const update of updateChunk){
1887
+ try {
1888
+ // Check if relation to draft target already exists
1889
+ const key = `${update.sourceId}_${update.newTargetId}`;
1890
+ const existingRelationId = existingRelationMap.get(key);
1891
+ if (existingRelationId && existingRelationId !== update.relationId) {
1892
+ // If relation to draft target already exists, delete the published target relation
1893
+ await trx(joinTable.name).where('id', update.relationId).delete();
1894
+ debug(`[fixExistingDraftRelations] ${uid}: Deleted relation ${update.relationId} (entry ${update.sourceId} -> published target ${update.oldTargetId}), draft relation already exists (-> ${update.newTargetId})`);
1895
+ } else {
1896
+ // Update the relation to point to draft target
1897
+ const updated = await trx(joinTable.name).where('id', update.relationId).update({
1898
+ [targetColumnName]: update.newTargetId
1899
+ });
1900
+ if (updated > 0) {
1901
+ debug(`[fixExistingDraftRelations] ${uid}: Updated relation ${update.relationId} (entry ${update.sourceId} -> published target ${update.oldTargetId} -> draft target ${update.newTargetId})`);
1902
+ }
1903
+ }
1904
+ } catch (error) {
1905
+ // If update fails due to duplicate key, try deleting the published target relation instead
1906
+ if (isDuplicateEntryError(error)) {
1907
+ await trx(joinTable.name).where('id', update.relationId).delete();
1908
+ debug(`[fixExistingDraftRelations] ${uid}: Deleted relation ${update.relationId} due to duplicate key error (entry ${update.sourceId})`);
1909
+ } else {
1910
+ throw error;
1911
+ }
1912
+ }
1913
+ }
1914
+ }
1915
+ }
1916
+ }
1917
+ }
1918
+ }
1919
+ /**
1920
+ * Fixes existing v4 draft entries' component relations by converting published targets to draft targets.
1921
+ * This ensures that draft components point to draft targets, not published ones.
1922
+ */ async function fixExistingDraftComponentRelations({ trx, uid }) {
1923
+ const meta = strapi.db.metadata.get(uid);
1924
+ if (!meta) {
1925
+ return;
1926
+ }
1927
+ const contentType = strapi.contentTypes[uid];
1928
+ const collectionName = contentType?.collectionName;
1929
+ if (!collectionName) {
1930
+ return;
1931
+ }
1932
+ const identifiers = strapi.db.metadata.identifiers;
1933
+ const joinTableName = transformContentTypesToModels.getComponentJoinTableName(collectionName, identifiers);
1934
+ const entityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
1935
+ const componentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
1936
+ const componentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
1937
+ const hasTable = await trx.schema.hasTable(joinTableName);
1938
+ if (!hasTable) {
1939
+ return;
1940
+ }
1941
+ // Get all draft entity IDs (including existing v4 drafts, not just newly created ones)
1942
+ const draftEntities = await trx(meta.tableName).select('id').whereNull('published_at');
1943
+ if (draftEntities.length === 0) {
1944
+ return;
1945
+ }
1946
+ const draftIds = draftEntities.map((e)=>Number(e.id));
1947
+ const draftIdsChunks = chunkArray(draftIds, getBatchSize(trx, 1000));
1948
+ for (const draftIdsChunk of draftIdsChunks){
1949
+ // Get components that belong to draft entities
1950
+ const componentRelations = await trx(joinTableName).select('*').whereIn(entityIdColumn, draftIdsChunk);
1951
+ if (componentRelations.length === 0) {
1952
+ continue;
1953
+ }
1954
+ const componentTypes = [
1955
+ ...new Set(componentRelations.map((r)=>r[componentTypeColumn]))
1956
+ ];
1957
+ const draftMapCache = new Map();
1958
+ for (const componentType of componentTypes){
1959
+ const componentMeta = getComponentMetadataByUid(componentType);
1960
+ if (!componentMeta) continue;
1961
+ for (const [, attr] of Object.entries(componentMeta.attributes || {})){
1962
+ if (attr.type !== 'relation' || !attr.joinTable) continue;
1963
+ const targetUid = attr.target;
1964
+ if (!targetUid) continue;
1965
+ const targetContentType = strapi.contentTypes[targetUid];
1966
+ const targetHasDP = targetContentType?.options?.draftAndPublish;
1967
+ if (!targetHasDP) continue;
1968
+ const relationJoinTable = attr.joinTable.name;
1969
+ const sourceColumn = attr.joinTable.joinColumn.name;
1970
+ if (!attr.joinTable.inverseJoinColumn) {
1971
+ continue;
1972
+ }
1973
+ const targetColumn = attr.joinTable.inverseJoinColumn.name;
1974
+ const hasRelationTable = await trx.schema.hasTable(relationJoinTable);
1975
+ if (!hasRelationTable) continue;
1976
+ // Get component IDs that belong to draft entities
1977
+ const componentIds = componentRelations.filter((r)=>r[componentTypeColumn] === componentType).map((r)=>Number(r[componentIdColumn]));
1978
+ if (componentIds.length === 0) continue;
1979
+ // Get all relations for these components
1980
+ const relations = await trx(relationJoinTable).whereIn(sourceColumn, componentIds).select('id', sourceColumn, targetColumn);
1981
+ if (relations.length === 0) continue;
1982
+ // Get target publication states
1983
+ const targetMeta = strapi.db.metadata.get(targetUid);
1984
+ if (!targetMeta) continue;
1985
+ const targetIds = [
1986
+ ...new Set(relations.map((r)=>r[targetColumn]).filter(Boolean))
1987
+ ];
1988
+ if (targetIds.length === 0) continue;
1989
+ const targets = await trx(targetMeta.tableName).whereIn('id', targetIds).select('id', 'published_at');
1990
+ const targetPublicationState = new Map(targets.map((t)=>[
1991
+ Number(t.id),
1992
+ t.published_at !== null ? 'published' : 'draft'
1993
+ ]));
1994
+ // Get draft map for target to convert published targets to draft targets
1995
+ const targetDraftMap = await getDraftMapForTarget(trx, targetUid, draftMapCache);
1996
+ if (!targetDraftMap || targetDraftMap.size === 0) continue;
1997
+ // Find relations from draft components to published targets and convert them
1998
+ const relationsToUpdate = [];
1999
+ for (const relation of relations){
2000
+ const targetId = Number(relation[targetColumn]);
2001
+ const targetState = targetPublicationState.get(targetId);
2002
+ if (targetState === 'published') {
2003
+ // This is a relation from a draft component to a published target - convert to draft target
2004
+ const draftTargetId = targetDraftMap.get(targetId);
2005
+ if (draftTargetId != null) {
2006
+ relationsToUpdate.push({
2007
+ relationId: relation.id,
2008
+ componentId: Number(relation[sourceColumn]),
2009
+ oldTargetId: targetId,
2010
+ newTargetId: draftTargetId
2011
+ });
2012
+ }
2013
+ }
2014
+ }
2015
+ if (relationsToUpdate.length > 0) {
2016
+ debug(`[fixExistingDraftComponentRelations] ${uid}: Converting ${relationsToUpdate.length} relations from draft components to published targets -> draft targets (component type: ${componentType}, target: ${targetUid})`);
2017
+ const updateChunks = chunkArray(relationsToUpdate, getBatchSize(trx, 1000));
2018
+ for (const updateChunk of updateChunks){
2019
+ // Preload existing relations for this chunk to avoid N+1 lookups.
2020
+ const existingRelationMap = await buildExistingRelationMap({
2021
+ trx,
2022
+ tableName: relationJoinTable,
2023
+ sourceColumnName: sourceColumn,
2024
+ targetColumnName: targetColumn,
2025
+ updates: updateChunk.map((update)=>({
2026
+ sourceId: update.componentId,
2027
+ newTargetId: update.newTargetId
2028
+ })),
2029
+ batchSize: getBatchSize(trx, 100)
2030
+ });
2031
+ for (const update of updateChunk){
2032
+ try {
2033
+ // Check if relation to draft target already exists
2034
+ const key = `${update.componentId}_${update.newTargetId}`;
2035
+ const existingRelationId = existingRelationMap.get(key);
2036
+ if (existingRelationId && existingRelationId !== update.relationId) {
2037
+ // If relation to draft target already exists, delete the published target relation
2038
+ await trx(relationJoinTable).where('id', update.relationId).delete();
2039
+ debug(`[fixExistingDraftComponentRelations] ${uid}: Deleted relation ${update.relationId} (component ${update.componentId} -> published target ${update.oldTargetId}), draft relation already exists (-> ${update.newTargetId})`);
2040
+ } else {
2041
+ // Update the relation to point to draft target
2042
+ const updated = await trx(relationJoinTable).where('id', update.relationId).update({
2043
+ [targetColumn]: update.newTargetId
2044
+ });
2045
+ if (updated > 0) {
2046
+ debug(`[fixExistingDraftComponentRelations] ${uid}: Updated relation ${update.relationId} (component ${update.componentId} -> published target ${update.oldTargetId} -> draft target ${update.newTargetId})`);
2047
+ }
2048
+ }
2049
+ } catch (error) {
2050
+ // If update fails due to duplicate key, try deleting the published target relation instead
2051
+ if (isDuplicateEntryError(error)) {
2052
+ await trx(relationJoinTable).where('id', update.relationId).delete();
2053
+ debug(`[fixExistingDraftComponentRelations] ${uid}: Deleted relation ${update.relationId} due to duplicate key error (component ${update.componentId})`);
2054
+ } else {
2055
+ throw error;
2056
+ }
2057
+ }
2058
+ }
2059
+ }
2060
+ }
2061
+ }
2062
+ }
2063
+ }
2064
+ }
2065
+ /**
2066
+ * Fix published entities' component relations so they point to published targets (not draft).
2067
+ * After duplicating nested components, the published tree keeps the original components;
2068
+ * their relation _lnk rows must point to published targets so the published view resolves them.
2069
+ */ async function fixPublishedComponentRelationTargets({ trx, uid }) {
2070
+ const meta = strapi.db.metadata.get(uid);
2071
+ if (!meta) return;
2072
+ const contentType = strapi.contentTypes[uid];
2073
+ const collectionName = contentType?.collectionName;
2074
+ if (!collectionName) return;
2075
+ const identifiers = strapi.db.metadata.identifiers;
2076
+ const joinTableName = transformContentTypesToModels.getComponentJoinTableName(collectionName, identifiers);
2077
+ const entityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
2078
+ const componentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
2079
+ const componentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
2080
+ if (!await ensureTableExists(trx, joinTableName)) return;
2081
+ const publishedIds = (await trx(meta.tableName).select('id').whereNotNull('published_at')).map((r)=>Number(r.id));
2082
+ if (publishedIds.length === 0) return;
2083
+ const reverseMapCache = new Map();
2084
+ const typeToIds = new Map();
2085
+ let currentLevelByType = new Map();
2086
+ currentLevelByType.set(uid, publishedIds);
2087
+ const maxLevels = 10;
2088
+ for(let level = 0; level < maxLevels; level += 1){
2089
+ const nextLevelByType = new Map();
2090
+ if (level === 0) {
2091
+ const chunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
2092
+ for (const chunk of chunks){
2093
+ const rows = await trx(joinTableName).select(componentIdColumn, componentTypeColumn).whereIn(entityIdColumn, chunk);
2094
+ for (const row of rows){
2095
+ const type = row[componentTypeColumn];
2096
+ const id = Number(row[componentIdColumn]);
2097
+ if (!type || Number.isNaN(id)) continue;
2098
+ if (!typeToIds.has(type)) typeToIds.set(type, new Set());
2099
+ typeToIds.get(type).add(id);
2100
+ if (!nextLevelByType.has(type)) nextLevelByType.set(type, []);
2101
+ nextLevelByType.get(type).push(id);
2102
+ }
2103
+ }
2104
+ } else {
2105
+ for (const [compType, ids] of currentLevelByType.entries()){
2106
+ if (compType === uid) continue;
2107
+ const compSchema = strapi.components[compType];
2108
+ if (!compSchema?.collectionName) continue;
2109
+ const nestedTable = transformContentTypesToModels.getComponentJoinTableName(compSchema.collectionName, identifiers);
2110
+ if (!await ensureTableExists(trx, nestedTable)) continue;
2111
+ const idChunks = chunkArray(ids, getBatchSize(trx, 1000));
2112
+ for (const idChunk of idChunks){
2113
+ const rows = await trx(nestedTable).select(componentIdColumn, componentTypeColumn).whereIn(entityIdColumn, idChunk);
2114
+ for (const row of rows){
2115
+ const type = row[componentTypeColumn];
2116
+ const id = Number(row[componentIdColumn]);
2117
+ if (!type || Number.isNaN(id)) continue;
2118
+ if (!typeToIds.has(type)) typeToIds.set(type, new Set());
2119
+ typeToIds.get(type).add(id);
2120
+ if (!nextLevelByType.has(type)) nextLevelByType.set(type, []);
2121
+ nextLevelByType.get(type).push(id);
2122
+ }
2123
+ }
2124
+ }
2125
+ }
2126
+ if (nextLevelByType.size === 0) break;
2127
+ currentLevelByType = nextLevelByType;
2128
+ }
2129
+ for (const [componentType, componentIds] of typeToIds.entries()){
2130
+ const componentMeta = getComponentMetadataByUid(componentType);
2131
+ if (!componentMeta) continue;
2132
+ const ids = Array.from(componentIds);
2133
+ if (ids.length === 0) continue;
2134
+ for (const [, attr] of Object.entries(componentMeta.attributes || {})){
2135
+ if (attr.type !== 'relation' || !attr.joinTable) continue;
2136
+ const targetUid = attr.target;
2137
+ if (!targetUid) continue;
2138
+ const targetContentType = strapi.contentTypes[targetUid];
2139
+ if (!targetContentType?.options?.draftAndPublish) continue;
2140
+ const relationJoinTable = attr.joinTable.name;
2141
+ const sourceColumn = attr.joinTable.joinColumn.name;
2142
+ if (!attr.joinTable.inverseJoinColumn) {
2143
+ continue;
2144
+ }
2145
+ const targetColumn = attr.joinTable.inverseJoinColumn.name;
2146
+ if (!await ensureTableExists(trx, relationJoinTable)) continue;
2147
+ const relations = await trx(relationJoinTable).whereIn(sourceColumn, ids).select('id', sourceColumn, targetColumn);
2148
+ if (relations.length === 0) continue;
2149
+ const targetMeta = strapi.db.metadata.get(targetUid);
2150
+ if (!targetMeta) continue;
2151
+ const targetIdList = [
2152
+ ...new Set(relations.map((r)=>r[targetColumn]).filter(Boolean))
2153
+ ];
2154
+ if (targetIdList.length === 0) continue;
2155
+ const targets = await trx(targetMeta.tableName).whereIn('id', targetIdList).select('id', 'published_at');
2156
+ const targetState = new Map(targets.map((t)=>[
2157
+ Number(t.id),
2158
+ t.published_at !== null ? 'published' : 'draft'
2159
+ ]));
2160
+ const draftToPublished = await getDraftToPublishedMap(trx, targetUid, reverseMapCache);
2161
+ if (!draftToPublished || draftToPublished.size === 0) continue;
2162
+ const relationsToUpdate = [];
2163
+ for (const relation of relations){
2164
+ const targetId = Number(relation[targetColumn]);
2165
+ if (targetState.get(targetId) !== 'draft') continue;
2166
+ const publishedId = draftToPublished.get(targetId);
2167
+ if (publishedId == null) continue;
2168
+ relationsToUpdate.push({
2169
+ relationId: relation.id,
2170
+ sourceId: Number(relation[sourceColumn]),
2171
+ oldTargetId: targetId,
2172
+ newTargetId: publishedId
2173
+ });
2174
+ }
2175
+ if (relationsToUpdate.length > 0) {
2176
+ const updateChunks = chunkArray(relationsToUpdate, getBatchSize(trx, 100));
2177
+ for (const updateChunk of updateChunks){
2178
+ const existingRelationMap = await buildExistingRelationMap({
2179
+ trx,
2180
+ tableName: relationJoinTable,
2181
+ sourceColumnName: sourceColumn,
2182
+ targetColumnName: targetColumn,
2183
+ updates: updateChunk.map((u)=>({
2184
+ sourceId: u.sourceId,
2185
+ newTargetId: u.newTargetId
2186
+ })),
2187
+ batchSize: getBatchSize(trx, 100)
2188
+ });
2189
+ for (const update of updateChunk){
2190
+ const key = `${update.sourceId}_${update.newTargetId}`;
2191
+ const existingRelationId = existingRelationMap.get(key);
2192
+ if (existingRelationId != null && existingRelationId !== update.relationId) {
2193
+ await trx(relationJoinTable).where('id', update.relationId).delete();
2194
+ continue;
2195
+ }
2196
+ try {
2197
+ await trx(relationJoinTable).where('id', update.relationId).update({
2198
+ [targetColumn]: update.newTargetId
2199
+ });
2200
+ existingRelationMap.set(key, update.relationId);
2201
+ } catch (error) {
2202
+ if (isDuplicateEntryError(error)) {
2203
+ await trx(relationJoinTable).where('id', update.relationId).delete();
2204
+ } else {
2205
+ throw error;
2206
+ }
2207
+ }
2208
+ }
2209
+ }
2210
+ }
2211
+ }
2212
+ }
2213
+ }
2214
+ /**
2215
+ * Copy component relations from published entries to draft entries
2216
+ */ async function copyComponentRelations({ trx, uid, publishedToDraftMap }) {
2217
+ const meta = strapi.db.metadata.get(uid);
2218
+ if (!meta) {
2219
+ return;
2220
+ }
2221
+ // Get collectionName from content type schema (Meta only has tableName which may be shortened)
2222
+ const contentType = strapi.contentTypes[uid];
2223
+ const collectionName = contentType?.collectionName;
2224
+ if (!collectionName) {
2225
+ return;
2226
+ }
2227
+ const identifiers = strapi.db.metadata.identifiers;
2228
+ const joinTableName = transformContentTypesToModels.getComponentJoinTableName(collectionName, identifiers);
2229
+ const entityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
2230
+ const componentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
2231
+ const componentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
2232
+ const fieldColumn = identifiers.FIELD_COLUMN;
2233
+ // Check if component join table exists
2234
+ const hasTable = await trx.schema.hasTable(joinTableName);
2235
+ if (!hasTable) {
2236
+ return;
2237
+ }
2238
+ const publishedIds = Array.from(publishedToDraftMap.keys());
2239
+ // Process in batches to avoid MySQL query size limits and SQLite expression tree limits
2240
+ const publishedIdsChunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
2241
+ const componentTargetDraftMapCache = new Map();
2242
+ const componentTargetReverseMapCache = new Map();
2243
+ for (const publishedIdsChunk of publishedIdsChunks){
2244
+ // Get component relations for published entries
2245
+ const componentRelations = await trx(joinTableName).select('*').whereIn(entityIdColumn, publishedIdsChunk);
2246
+ if (componentRelations.length === 0) {
2247
+ continue;
2248
+ }
2249
+ const componentCloneCache = new Map();
2250
+ const clonedComponentPairsCache = new Map();
2251
+ const componentHierarchyCaches = {
2252
+ parentInstanceCache: new Map(),
2253
+ ancestorDpCache: new Map(),
2254
+ parentDpCache: new Map()
2255
+ };
2256
+ // Filter component relations: only propagate if component's parent in the component hierarchy doesn't have draft/publish
2257
+ // This matches discardDraft() behavior via shouldPropagateComponentRelationToNewVersion
2258
+ //
2259
+ // The logic: find what contains this component instance (could be a content type or another component).
2260
+ // If it's a component, recursively check its parents. If any parent in the chain has DP, filter out the relation.
2261
+ // Filter in batches to cap memory use and DB fan-out when relations are large.
2262
+ const filteredComponentRelations = [];
2263
+ const filterBatches = chunkArray(componentRelations, getBatchSize(trx, 100));
2264
+ for (const batch of filterBatches){
2265
+ const batchResults = await Promise.all(batch.map(async (relation)=>{
2266
+ const componentId = relation[componentIdColumn];
2267
+ const componentType = relation[componentTypeColumn];
2268
+ const entityId = relation[entityIdColumn];
2269
+ const componentSchema = strapi.components[componentType];
2270
+ if (!componentSchema) {
2271
+ debug(`[copyComponentRelations] ${uid}: Keeping relation - unknown component type ${componentType} (entity: ${entityId}, componentId: ${componentId})`);
2272
+ return relation;
2273
+ }
2274
+ const componentParent = await findComponentParentInstance(trx, identifiers, componentSchema.uid, componentId, uid, componentHierarchyCaches);
2275
+ if (!componentParent) {
2276
+ debug(`[copyComponentRelations] ${uid}: Keeping relation - component ${componentType} (id: ${componentId}) is directly on entity ${entityId} (no nested parent found)`);
2277
+ return relation;
2278
+ }
2279
+ debug(`[copyComponentRelations] ${uid}: Component ${componentType} (id: ${componentId}, entity: ${entityId}) has parent in hierarchy: ${componentParent.uid} (parentId: ${componentParent.parentId})`);
2280
+ const hasDPParent = await hasDraftPublishAncestorForParent(trx, identifiers, componentParent, componentHierarchyCaches);
2281
+ if (hasDPParent) {
2282
+ debug(`[copyComponentRelations] Filtering: component ${componentType} (id: ${componentId}, entity: ${entityId}) has DP parent in hierarchy (${componentParent.uid})`);
2283
+ return null;
2284
+ }
2285
+ debug(`[copyComponentRelations] ${uid}: Keeping relation - component ${componentType} (id: ${componentId}, entity: ${entityId}) has no DP parent in hierarchy`);
2286
+ return relation;
2287
+ }));
2288
+ filteredComponentRelations.push(...batchResults);
2289
+ }
2290
+ // Filter out null values (filtered relations)
2291
+ const relationsToProcess = filteredComponentRelations.filter(Boolean);
2292
+ const filteredCount = componentRelations.length - relationsToProcess.length;
2293
+ if (filteredCount > 0) {
2294
+ debug(`[copyComponentRelations] ${uid}: Filtered ${filteredCount} of ${componentRelations.length} component relations (removed ${filteredCount} with DP parents)`);
2295
+ }
2296
+ // Create new component relations for draft entries
2297
+ // Remove the 'id' field to avoid duplicate key errors
2298
+ const mappedRelations = (await Promise.all(relationsToProcess.map(async (relation)=>{
2299
+ const newEntityId = getMappedValue(publishedToDraftMap, relation[entityIdColumn]);
2300
+ if (!newEntityId) {
2301
+ return null;
2302
+ }
2303
+ const componentId = relation[componentIdColumn];
2304
+ const componentType = relation[componentTypeColumn];
2305
+ const componentKey = `${componentId}:${newEntityId}`;
2306
+ let cloneMap = componentCloneCache.get(componentType);
2307
+ if (!cloneMap) {
2308
+ cloneMap = new Map();
2309
+ componentCloneCache.set(componentType, cloneMap);
2310
+ }
2311
+ let newComponentId = cloneMap.get(componentKey);
2312
+ if (!newComponentId) {
2313
+ newComponentId = await cloneComponentInstance({
2314
+ trx,
2315
+ componentUid: componentType,
2316
+ componentId: Number(componentId),
2317
+ parentUid: uid,
2318
+ parentPublishedToDraftMap: publishedToDraftMap,
2319
+ draftMapCache: componentTargetDraftMapCache,
2320
+ clonedComponentPairsCache,
2321
+ isForDraftEntity: true,
2322
+ reverseMapCache: componentTargetReverseMapCache
2323
+ });
2324
+ cloneMap.set(componentKey, newComponentId);
2325
+ }
2326
+ const { id, ...relationWithoutId } = relation;
2327
+ return {
2328
+ ...relationWithoutId,
2329
+ [entityIdColumn]: newEntityId,
2330
+ [componentIdColumn]: newComponentId
2331
+ };
2332
+ }))).filter(Boolean);
2333
+ // Deduplicate relations based on the unique constraint columns
2334
+ // This prevents duplicates within the same batch that could cause conflicts
2335
+ const uniqueKeyMap = new Map();
2336
+ for (const relation of mappedRelations){
2337
+ const uniqueKey = `${relation[entityIdColumn]}_${relation[componentIdColumn]}_${relation[fieldColumn]}_${relation[componentTypeColumn]}`;
2338
+ if (!uniqueKeyMap.has(uniqueKey)) {
2339
+ uniqueKeyMap.set(uniqueKey, relation);
2340
+ }
2341
+ }
2342
+ const deduplicatedRelations = Array.from(uniqueKeyMap.values());
2343
+ if (deduplicatedRelations.length === 0) {
2344
+ continue;
2345
+ }
2346
+ // Check which relations already exist in the database to avoid conflicts
2347
+ // We need to check all unique constraint columns (entity_id, cmp_id, field, component_type)
2348
+ // Batch the check to avoid SQLite expression tree depth limits
2349
+ // Use smaller batches for OR queries (50 for SQLite, 100 for others)
2350
+ const batchSize = getBatchSize(trx, 50);
2351
+ const relationChunks = chunkArray(deduplicatedRelations, batchSize);
2352
+ const existingKeys = new Set();
2353
+ for (const relationChunk of relationChunks){
2354
+ const existingRelations = await trx(joinTableName).select([
2355
+ entityIdColumn,
2356
+ componentIdColumn,
2357
+ fieldColumn,
2358
+ componentTypeColumn
2359
+ ]).where((qb)=>{
2360
+ // Build OR conditions for each relation in this chunk
2361
+ for (const relation of relationChunk){
2362
+ qb.orWhere((subQb)=>{
2363
+ subQb.where(entityIdColumn, relation[entityIdColumn]).where(componentIdColumn, relation[componentIdColumn]).where(fieldColumn, relation[fieldColumn]).where(componentTypeColumn, relation[componentTypeColumn]);
2364
+ });
2365
+ }
2366
+ });
2367
+ // Add existing relation keys to the set
2368
+ for (const existing of existingRelations){
2369
+ const key = `${existing[entityIdColumn]}_${existing[componentIdColumn]}_${existing[fieldColumn]}_${existing[componentTypeColumn]}`;
2370
+ existingKeys.add(key);
2371
+ }
2372
+ }
2373
+ // Filter out relations that already exist
2374
+ const newComponentRelations = deduplicatedRelations.filter((relation)=>{
2375
+ const key = `${relation[entityIdColumn]}_${relation[componentIdColumn]}_${relation[fieldColumn]}_${relation[componentTypeColumn]}`;
2376
+ return !existingKeys.has(key);
2377
+ });
2378
+ if (newComponentRelations.length > 0) {
2379
+ // Insert component relations with PostgreSQL-specific ON CONFLICT handling
2380
+ // Component relations use a different conflict resolution than regular relations
2381
+ const client = trx.client.config.client;
2382
+ if (client === 'postgres' || client === 'pg') {
2383
+ // PostgreSQL: Batch insert with ON CONFLICT DO NOTHING for better throughput.
2384
+ const relationChunks = chunkArray(newComponentRelations, getBatchSize(trx, 500));
2385
+ let insertedCount = 0;
2386
+ for (const relationChunk of relationChunks){
2387
+ await trx(joinTableName).insert(relationChunk).onConflict([
2388
+ entityIdColumn,
2389
+ componentIdColumn,
2390
+ fieldColumn,
2391
+ componentTypeColumn
2392
+ ]).ignore();
2393
+ insertedCount += relationChunk.length;
2394
+ }
2395
+ if (insertedCount > 0) {
2396
+ debug(`[copyComponentRelations] ${uid}: Attempted to insert ${insertedCount} component relations (duplicates ignored)`);
2397
+ }
2398
+ } else {
2399
+ // MySQL and SQLite: use standard insert with duplicate handling
2400
+ await insertRelationsWithDuplicateHandling({
2401
+ trx,
2402
+ tableName: joinTableName,
2403
+ relations: newComponentRelations,
2404
+ context: {
2405
+ reason: 'component-relation-insert',
2406
+ sourceUid: uid
2407
+ }
2408
+ });
2409
+ }
2410
+ }
2411
+ // Copy media morph rows for cloned components so draft components have the same media as published
2412
+ const morphInfo = getUploadMorphTableInfo();
2413
+ if (morphInfo) {
2414
+ for (const [componentType, cloneMap] of clonedComponentPairsCache.entries()){
2415
+ const pairs = [];
2416
+ for (const [key, newComponentId] of cloneMap.entries()){
2417
+ const originalId = Number(key.split(':')[0]);
2418
+ if (!Number.isNaN(originalId)) {
2419
+ pairs.push({
2420
+ originalId,
2421
+ draftId: newComponentId
2422
+ });
2423
+ }
2424
+ }
2425
+ if (pairs.length > 0) {
2426
+ await copyMorphRowsByPairs({
2427
+ trx,
2428
+ tableName: morphInfo.tableName,
2429
+ columnToRewrite: morphInfo.relatedIdColumnName,
2430
+ pairs,
2431
+ filter: {
2432
+ column: morphInfo.relatedTypeColumnName,
2433
+ value: componentType
2434
+ },
2435
+ contextReason: 'media-morph-draft-components'
2436
+ });
2437
+ }
2438
+ }
2439
+ }
2440
+ // Copy any other morph relations where cloned components are the source (morphToOne/morphToMany)
2441
+ await copySourceSideMorphRelationsForClonedComponents({
2442
+ trx,
2443
+ clonedComponentPairsCache
2444
+ });
2445
+ }
2446
+ }
2447
+ /**
2448
+ * 2 pass migration to create the draft entries for all the published entries.
2449
+ * And then copy relations directly using database queries.
2450
+ */ const migrateUp = async (trx, db)=>{
2451
+ strapi.log.info('[discard-drafts] Migration started');
2452
+ const dpModels = [];
2453
+ for (const meta of db.metadata.values()){
2454
+ const hasDP = await hasDraftAndPublish(trx, meta);
2455
+ if (hasDP) {
2456
+ dpModels.push(meta);
2457
+ }
2458
+ }
2459
+ debug(`Found ${dpModels.length} draft/publish content types to process`);
2460
+ /**
2461
+ * Create plain draft entries for all the entries that were published.
2462
+ */ strapi.log.info('[discard-drafts] Stage 1/5 – cloning published entries into draft rows');
2463
+ for (const model of dpModels){
2464
+ debug(` • cloning scalars for ${model.uid}`);
2465
+ await copyPublishedEntriesToDraft({
2466
+ db,
2467
+ trx,
2468
+ uid: model.uid
2469
+ });
2470
+ }
2471
+ strapi.log.info('[discard-drafts] Stage 1/5 complete');
2472
+ /**
2473
+ * Copy relations from published entries to draft entries using direct database queries.
2474
+ * This is much more efficient than calling discardDraft for each entry.
2475
+ */ strapi.log.info('[discard-drafts] Stage 2/5 – copying relations and components to drafts');
2476
+ for (const model of dpModels){
2477
+ debug(` • copying relations for ${model.uid}`);
2478
+ await copyRelationsToDrafts({
2479
+ db,
2480
+ trx,
2481
+ uid: model.uid
2482
+ });
2483
+ }
2484
+ flushSkippedRelationLogs();
2485
+ strapi.log.info('[discard-drafts] Stage 2/5 complete');
2486
+ /**
2487
+ * Fix existing v4 draft entries' join table relations to ensure they point to draft targets.
2488
+ * In v4, draft entries might have had relations pointing to published targets. These need
2489
+ * to be converted to point to the draft versions of those targets.
2490
+ */ strapi.log.info('[discard-drafts] Stage 3/5 – fixing existing draft relations');
2491
+ for (const model of dpModels){
2492
+ debug(` • fixing existing draft relations for ${model.uid}`);
2493
+ await fixExistingDraftRelations({
2494
+ trx,
2495
+ uid: model.uid
2496
+ });
2497
+ }
2498
+ strapi.log.info('[discard-drafts] Stage 3/5 complete');
2499
+ /**
2500
+ * Fix existing v4 draft entries' component relations to ensure they point to draft targets.
2501
+ * In v4, draft entries might have had components pointing to published targets. These need
2502
+ * to be converted to point to the draft versions of those targets.
2503
+ */ strapi.log.info('[discard-drafts] Stage 4/5 – fixing existing draft component relations');
2504
+ for (const model of dpModels){
2505
+ debug(` • fixing existing draft component relations for ${model.uid}`);
2506
+ await fixExistingDraftComponentRelations({
2507
+ trx,
2508
+ uid: model.uid
2509
+ });
2510
+ }
2511
+ strapi.log.info('[discard-drafts] Stage 4/5 complete');
2512
+ /**
2513
+ * Fix published entities' component relations to point to published targets (not draft).
2514
+ * Ensures the published view can resolve nested component relations after duplication.
2515
+ */ strapi.log.info('[discard-drafts] Stage 4b/5 – fixing published component relations to published targets');
2516
+ for (const model of dpModels){
2517
+ debug(` • fixing published component relations for ${model.uid}`);
2518
+ await fixPublishedComponentRelationTargets({
2519
+ trx,
2520
+ uid: model.uid
2521
+ });
2522
+ }
2523
+ strapi.log.info('[discard-drafts] Stage 4b/5 complete');
2524
+ /**
2525
+ * Update JoinColumn relations (foreign keys) to point to draft versions
2526
+ * This matches discard() behavior: drafts relate to drafts
2527
+ */ strapi.log.info('[discard-drafts] Stage 5/5 – updating foreign key references to draft targets');
2528
+ for (const model of dpModels){
2529
+ debug(` • updating join columns for ${model.uid}`);
2530
+ await updateJoinColumnRelations({
2531
+ db,
2532
+ trx,
2533
+ uid: model.uid
2534
+ });
2535
+ }
2536
+ strapi.log.info('[discard-drafts] Stage 5/5 complete');
2537
+ strapi.log.info('[discard-drafts] Migration completed successfully');
2538
+ };
2539
+ /**
2540
+ * Load a batch of versions to discard.
2541
+ *
2542
+ * Versions with only a draft version will be ignored.
2543
+ * Only versions with a published version (which always have a draft version) will be discarded.
2544
+ */ async function* getBatchToDiscard({ db, trx, uid, defaultBatchSize = 1000 }) {
2545
+ const batchSize = Math.min(defaultBatchSize, db.dialect.getBatchInsertSize());
2546
+ let offset = 0;
2547
+ let hasMore = true;
2548
+ while(hasMore){
2549
+ // Look for the published entries to discard
2550
+ const batch = await db.queryBuilder(uid).select([
2551
+ 'id',
2552
+ 'documentId',
2553
+ 'locale'
2554
+ ]).where({
2555
+ publishedAt: {
2556
+ $ne: null
2557
+ }
2558
+ }).limit(batchSize).offset(offset).orderBy('id').transacting(trx).execute();
2559
+ if (batch.length < batchSize) {
2560
+ hasMore = false;
2561
+ }
2562
+ offset += batchSize;
2563
+ yield batch;
2564
+ }
2565
+ }
39
2566
  const discardDocumentDrafts = {
40
- name: "core::5.0.0-discard-drafts",
41
- async up(trx, db) {
42
- await migrateUp(trx, db);
43
- },
44
- async down() {
45
- throw new Error("not implemented");
46
- }
2567
+ name: 'core::5.0.0-discard-drafts',
2568
+ async up (trx, db) {
2569
+ await migrateUp(trx, db);
2570
+ },
2571
+ async down () {
2572
+ throw new Error('not implemented');
2573
+ }
47
2574
  };
2575
+
48
2576
  exports.discardDocumentDrafts = discardDocumentDrafts;
49
2577
  exports.getBatchToDiscard = getBatchToDiscard;
50
2578
  //# sourceMappingURL=5.0.0-discard-drafts.js.map