@strapi/core 0.0.0-next.f5312617ca16b870c2bf1adcea2c69b676979e29 → 0.0.0-next.f698d55751345c4ca87477ef683475c1a68f310a

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 (345) hide show
  1. package/dist/Strapi.d.ts.map +1 -1
  2. package/dist/Strapi.js +11 -8
  3. package/dist/Strapi.js.map +1 -1
  4. package/dist/Strapi.mjs +9 -6
  5. package/dist/Strapi.mjs.map +1 -1
  6. package/dist/compile.js.map +1 -1
  7. package/dist/compile.mjs.map +1 -1
  8. package/dist/configuration/config-loader.js +1 -2
  9. package/dist/configuration/config-loader.js.map +1 -1
  10. package/dist/configuration/config-loader.mjs +1 -2
  11. package/dist/configuration/config-loader.mjs.map +1 -1
  12. package/dist/configuration/get-dirs.js.map +1 -1
  13. package/dist/configuration/get-dirs.mjs.map +1 -1
  14. package/dist/configuration/index.d.ts.map +1 -1
  15. package/dist/configuration/index.js +8 -3
  16. package/dist/configuration/index.js.map +1 -1
  17. package/dist/configuration/index.mjs +8 -3
  18. package/dist/configuration/index.mjs.map +1 -1
  19. package/dist/configuration/urls.js.map +1 -1
  20. package/dist/configuration/urls.mjs.map +1 -1
  21. package/dist/container.js.map +1 -1
  22. package/dist/container.mjs.map +1 -1
  23. package/dist/core-api/controller/collection-type.js.map +1 -1
  24. package/dist/core-api/controller/collection-type.mjs.map +1 -1
  25. package/dist/core-api/controller/index.js.map +1 -1
  26. package/dist/core-api/controller/index.mjs.map +1 -1
  27. package/dist/core-api/controller/single-type.js.map +1 -1
  28. package/dist/core-api/controller/single-type.mjs.map +1 -1
  29. package/dist/core-api/controller/transform.js.map +1 -1
  30. package/dist/core-api/controller/transform.mjs.map +1 -1
  31. package/dist/core-api/routes/index.js.map +1 -1
  32. package/dist/core-api/routes/index.mjs.map +1 -1
  33. package/dist/core-api/service/collection-type.js.map +1 -1
  34. package/dist/core-api/service/collection-type.mjs.map +1 -1
  35. package/dist/core-api/service/core-service.js.map +1 -1
  36. package/dist/core-api/service/core-service.mjs.map +1 -1
  37. package/dist/core-api/service/index.js.map +1 -1
  38. package/dist/core-api/service/index.mjs.map +1 -1
  39. package/dist/core-api/service/pagination.js.map +1 -1
  40. package/dist/core-api/service/pagination.mjs.map +1 -1
  41. package/dist/core-api/service/single-type.js +1 -2
  42. package/dist/core-api/service/single-type.js.map +1 -1
  43. package/dist/core-api/service/single-type.mjs +1 -2
  44. package/dist/core-api/service/single-type.mjs.map +1 -1
  45. package/dist/domain/content-type/index.js.map +1 -1
  46. package/dist/domain/content-type/index.mjs.map +1 -1
  47. package/dist/domain/content-type/validator.js.map +1 -1
  48. package/dist/domain/content-type/validator.mjs.map +1 -1
  49. package/dist/domain/module/index.js.map +1 -1
  50. package/dist/domain/module/index.mjs.map +1 -1
  51. package/dist/domain/module/validation.js.map +1 -1
  52. package/dist/domain/module/validation.mjs.map +1 -1
  53. package/dist/ee/index.js.map +1 -1
  54. package/dist/ee/index.mjs.map +1 -1
  55. package/dist/ee/license.js.map +1 -1
  56. package/dist/ee/license.mjs.map +1 -1
  57. package/dist/factories.js.map +1 -1
  58. package/dist/factories.mjs.map +1 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/loaders/admin.js.map +1 -1
  61. package/dist/loaders/admin.mjs.map +1 -1
  62. package/dist/loaders/apis.js.map +1 -1
  63. package/dist/loaders/apis.mjs.map +1 -1
  64. package/dist/loaders/components.js.map +1 -1
  65. package/dist/loaders/components.mjs.map +1 -1
  66. package/dist/loaders/middlewares.js.map +1 -1
  67. package/dist/loaders/middlewares.mjs.map +1 -1
  68. package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
  69. package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
  70. package/dist/loaders/plugins/get-user-plugins-config.js.map +1 -1
  71. package/dist/loaders/plugins/get-user-plugins-config.mjs.map +1 -1
  72. package/dist/loaders/plugins/index.js +1 -2
  73. package/dist/loaders/plugins/index.js.map +1 -1
  74. package/dist/loaders/plugins/index.mjs.map +1 -1
  75. package/dist/loaders/policies.js.map +1 -1
  76. package/dist/loaders/policies.mjs.map +1 -1
  77. package/dist/loaders/sanitizers.js.map +1 -1
  78. package/dist/loaders/sanitizers.mjs.map +1 -1
  79. package/dist/loaders/src-index.js.map +1 -1
  80. package/dist/loaders/src-index.mjs.map +1 -1
  81. package/dist/loaders/validators.js.map +1 -1
  82. package/dist/loaders/validators.mjs.map +1 -1
  83. package/dist/middlewares/body.js.map +1 -1
  84. package/dist/middlewares/body.mjs.map +1 -1
  85. package/dist/middlewares/cors.js.map +1 -1
  86. package/dist/middlewares/cors.mjs.map +1 -1
  87. package/dist/middlewares/errors.js.map +1 -1
  88. package/dist/middlewares/errors.mjs.map +1 -1
  89. package/dist/middlewares/favicon.js.map +1 -1
  90. package/dist/middlewares/favicon.mjs.map +1 -1
  91. package/dist/middlewares/index.js.map +1 -1
  92. package/dist/middlewares/logger.js.map +1 -1
  93. package/dist/middlewares/logger.mjs.map +1 -1
  94. package/dist/middlewares/powered-by.js.map +1 -1
  95. package/dist/middlewares/powered-by.mjs.map +1 -1
  96. package/dist/middlewares/public.js.map +1 -1
  97. package/dist/middlewares/public.mjs.map +1 -1
  98. package/dist/middlewares/query.js.map +1 -1
  99. package/dist/middlewares/query.mjs.map +1 -1
  100. package/dist/middlewares/response-time.js.map +1 -1
  101. package/dist/middlewares/response-time.mjs.map +1 -1
  102. package/dist/middlewares/responses.js.map +1 -1
  103. package/dist/middlewares/responses.mjs.map +1 -1
  104. package/dist/middlewares/security.js.map +1 -1
  105. package/dist/middlewares/security.mjs.map +1 -1
  106. package/dist/middlewares/session.js.map +1 -1
  107. package/dist/middlewares/session.mjs.map +1 -1
  108. package/dist/migrations/database/5.0.0-discard-drafts.d.ts.map +1 -1
  109. package/dist/migrations/database/5.0.0-discard-drafts.js +1 -1
  110. package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
  111. package/dist/migrations/database/5.0.0-discard-drafts.mjs +1 -1
  112. package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
  113. package/dist/migrations/draft-publish.js.map +1 -1
  114. package/dist/migrations/draft-publish.mjs.map +1 -1
  115. package/dist/migrations/i18n.js.map +1 -1
  116. package/dist/migrations/i18n.mjs.map +1 -1
  117. package/dist/migrations/index.js.map +1 -1
  118. package/dist/migrations/index.mjs.map +1 -1
  119. package/dist/providers/admin.js.map +1 -1
  120. package/dist/providers/admin.mjs.map +1 -1
  121. package/dist/providers/coreStore.js.map +1 -1
  122. package/dist/providers/coreStore.mjs.map +1 -1
  123. package/dist/providers/cron.js.map +1 -1
  124. package/dist/providers/cron.mjs.map +1 -1
  125. package/dist/providers/registries.js.map +1 -1
  126. package/dist/providers/registries.mjs.map +1 -1
  127. package/dist/providers/telemetry.js.map +1 -1
  128. package/dist/providers/telemetry.mjs.map +1 -1
  129. package/dist/providers/webhooks.js.map +1 -1
  130. package/dist/providers/webhooks.mjs.map +1 -1
  131. package/dist/registries/apis.js.map +1 -1
  132. package/dist/registries/apis.mjs.map +1 -1
  133. package/dist/registries/components.js.map +1 -1
  134. package/dist/registries/components.mjs.map +1 -1
  135. package/dist/registries/content-types.js.map +1 -1
  136. package/dist/registries/content-types.mjs.map +1 -1
  137. package/dist/registries/controllers.js.map +1 -1
  138. package/dist/registries/controllers.mjs.map +1 -1
  139. package/dist/registries/custom-fields.js.map +1 -1
  140. package/dist/registries/custom-fields.mjs.map +1 -1
  141. package/dist/registries/hooks.js.map +1 -1
  142. package/dist/registries/hooks.mjs.map +1 -1
  143. package/dist/registries/middlewares.js.map +1 -1
  144. package/dist/registries/middlewares.mjs.map +1 -1
  145. package/dist/registries/models.js.map +1 -1
  146. package/dist/registries/models.mjs.map +1 -1
  147. package/dist/registries/modules.js.map +1 -1
  148. package/dist/registries/modules.mjs.map +1 -1
  149. package/dist/registries/namespace.js.map +1 -1
  150. package/dist/registries/namespace.mjs.map +1 -1
  151. package/dist/registries/plugins.js.map +1 -1
  152. package/dist/registries/plugins.mjs.map +1 -1
  153. package/dist/registries/policies.js.map +1 -1
  154. package/dist/registries/policies.mjs.map +1 -1
  155. package/dist/registries/sanitizers.js.map +1 -1
  156. package/dist/registries/sanitizers.mjs.map +1 -1
  157. package/dist/registries/services.js.map +1 -1
  158. package/dist/registries/services.mjs.map +1 -1
  159. package/dist/registries/validators.js.map +1 -1
  160. package/dist/registries/validators.mjs.map +1 -1
  161. package/dist/services/auth/index.js.map +1 -1
  162. package/dist/services/auth/index.mjs.map +1 -1
  163. package/dist/services/config.js.map +1 -1
  164. package/dist/services/config.mjs.map +1 -1
  165. package/dist/services/content-api/index.js.map +1 -1
  166. package/dist/services/content-api/index.mjs.map +1 -1
  167. package/dist/services/content-api/permissions/index.js.map +1 -1
  168. package/dist/services/content-api/permissions/index.mjs.map +1 -1
  169. package/dist/services/content-api/permissions/providers/action.js.map +1 -1
  170. package/dist/services/content-api/permissions/providers/action.mjs.map +1 -1
  171. package/dist/services/content-api/permissions/providers/condition.js.map +1 -1
  172. package/dist/services/content-api/permissions/providers/condition.mjs.map +1 -1
  173. package/dist/services/core-store.js.map +1 -1
  174. package/dist/services/core-store.mjs.map +1 -1
  175. package/dist/services/cron.js +1 -2
  176. package/dist/services/cron.js.map +1 -1
  177. package/dist/services/cron.mjs +1 -2
  178. package/dist/services/cron.mjs.map +1 -1
  179. package/dist/services/custom-fields.js.map +1 -1
  180. package/dist/services/custom-fields.mjs.map +1 -1
  181. package/dist/services/document-service/attributes/index.js.map +1 -1
  182. package/dist/services/document-service/attributes/index.mjs.map +1 -1
  183. package/dist/services/document-service/attributes/transforms.js.map +1 -1
  184. package/dist/services/document-service/attributes/transforms.mjs.map +1 -1
  185. package/dist/services/document-service/components.js.map +1 -1
  186. package/dist/services/document-service/components.mjs.map +1 -1
  187. package/dist/services/document-service/draft-and-publish.js.map +1 -1
  188. package/dist/services/document-service/draft-and-publish.mjs.map +1 -1
  189. package/dist/services/document-service/entries.js.map +1 -1
  190. package/dist/services/document-service/entries.mjs.map +1 -1
  191. package/dist/services/document-service/events.js.map +1 -1
  192. package/dist/services/document-service/events.mjs.map +1 -1
  193. package/dist/services/document-service/index.js.map +1 -1
  194. package/dist/services/document-service/index.mjs.map +1 -1
  195. package/dist/services/document-service/internationalization.js.map +1 -1
  196. package/dist/services/document-service/internationalization.mjs.map +1 -1
  197. package/dist/services/document-service/middlewares/errors.js.map +1 -1
  198. package/dist/services/document-service/middlewares/errors.mjs.map +1 -1
  199. package/dist/services/document-service/middlewares/middleware-manager.js.map +1 -1
  200. package/dist/services/document-service/middlewares/middleware-manager.mjs.map +1 -1
  201. package/dist/services/document-service/repository.js +1 -1
  202. package/dist/services/document-service/repository.js.map +1 -1
  203. package/dist/services/document-service/repository.mjs +1 -1
  204. package/dist/services/document-service/repository.mjs.map +1 -1
  205. package/dist/services/document-service/transform/data.js.map +1 -1
  206. package/dist/services/document-service/transform/data.mjs.map +1 -1
  207. package/dist/services/document-service/transform/fields.js.map +1 -1
  208. package/dist/services/document-service/transform/fields.mjs.map +1 -1
  209. package/dist/services/document-service/transform/id-map.js +2 -4
  210. package/dist/services/document-service/transform/id-map.js.map +1 -1
  211. package/dist/services/document-service/transform/id-map.mjs +2 -4
  212. package/dist/services/document-service/transform/id-map.mjs.map +1 -1
  213. package/dist/services/document-service/transform/id-transform.js.map +1 -1
  214. package/dist/services/document-service/transform/id-transform.mjs.map +1 -1
  215. package/dist/services/document-service/transform/populate.js.map +1 -1
  216. package/dist/services/document-service/transform/populate.mjs.map +1 -1
  217. package/dist/services/document-service/transform/query.js.map +1 -1
  218. package/dist/services/document-service/transform/query.mjs.map +1 -1
  219. package/dist/services/document-service/transform/relations/extract/data-ids.d.ts.map +1 -1
  220. package/dist/services/document-service/transform/relations/extract/data-ids.js +13 -6
  221. package/dist/services/document-service/transform/relations/extract/data-ids.js.map +1 -1
  222. package/dist/services/document-service/transform/relations/extract/data-ids.mjs +13 -6
  223. package/dist/services/document-service/transform/relations/extract/data-ids.mjs.map +1 -1
  224. package/dist/services/document-service/transform/relations/transform/data-ids.d.ts.map +1 -1
  225. package/dist/services/document-service/transform/relations/transform/data-ids.js +17 -8
  226. package/dist/services/document-service/transform/relations/transform/data-ids.js.map +1 -1
  227. package/dist/services/document-service/transform/relations/transform/data-ids.mjs +18 -9
  228. package/dist/services/document-service/transform/relations/transform/data-ids.mjs.map +1 -1
  229. package/dist/services/document-service/transform/relations/transform/default-locale.js.map +1 -1
  230. package/dist/services/document-service/transform/relations/transform/default-locale.mjs.map +1 -1
  231. package/dist/services/document-service/transform/relations/utils/dp.js.map +1 -1
  232. package/dist/services/document-service/transform/relations/utils/dp.mjs.map +1 -1
  233. package/dist/services/document-service/transform/relations/utils/i18n.js.map +1 -1
  234. package/dist/services/document-service/transform/relations/utils/i18n.mjs.map +1 -1
  235. package/dist/services/document-service/transform/relations/utils/map-relation.d.ts.map +1 -1
  236. package/dist/services/document-service/transform/relations/utils/map-relation.js +3 -10
  237. package/dist/services/document-service/transform/relations/utils/map-relation.js.map +1 -1
  238. package/dist/services/document-service/transform/relations/utils/map-relation.mjs +3 -10
  239. package/dist/services/document-service/transform/relations/utils/map-relation.mjs.map +1 -1
  240. package/dist/services/document-service/utils/populate.d.ts.map +1 -1
  241. package/dist/services/document-service/utils/populate.js +1 -1
  242. package/dist/services/document-service/utils/populate.js.map +1 -1
  243. package/dist/services/document-service/utils/populate.mjs +1 -1
  244. package/dist/services/document-service/utils/populate.mjs.map +1 -1
  245. package/dist/services/document-service/utils/unidirectional-relations.js +1 -2
  246. package/dist/services/document-service/utils/unidirectional-relations.js.map +1 -1
  247. package/dist/services/document-service/utils/unidirectional-relations.mjs +1 -2
  248. package/dist/services/document-service/utils/unidirectional-relations.mjs.map +1 -1
  249. package/dist/services/entity-service/index.js.map +1 -1
  250. package/dist/services/entity-service/index.mjs.map +1 -1
  251. package/dist/services/entity-validator/blocks-validator.js.map +1 -1
  252. package/dist/services/entity-validator/blocks-validator.mjs.map +1 -1
  253. package/dist/services/entity-validator/index.js.map +1 -1
  254. package/dist/services/entity-validator/index.mjs.map +1 -1
  255. package/dist/services/entity-validator/validators.js.map +1 -1
  256. package/dist/services/entity-validator/validators.mjs.map +1 -1
  257. package/dist/services/errors.js.map +1 -1
  258. package/dist/services/errors.mjs.map +1 -1
  259. package/dist/services/event-hub.js.map +1 -1
  260. package/dist/services/event-hub.mjs.map +1 -1
  261. package/dist/services/features.js.map +1 -1
  262. package/dist/services/features.mjs.map +1 -1
  263. package/dist/services/fs.js.map +1 -1
  264. package/dist/services/fs.mjs.map +1 -1
  265. package/dist/services/metrics/admin-user-hash.js.map +1 -1
  266. package/dist/services/metrics/admin-user-hash.mjs.map +1 -1
  267. package/dist/services/metrics/index.js +1 -2
  268. package/dist/services/metrics/index.js.map +1 -1
  269. package/dist/services/metrics/index.mjs +1 -2
  270. package/dist/services/metrics/index.mjs.map +1 -1
  271. package/dist/services/metrics/is-truthy.js.map +1 -1
  272. package/dist/services/metrics/middleware.js.map +1 -1
  273. package/dist/services/metrics/middleware.mjs.map +1 -1
  274. package/dist/services/metrics/rate-limiter.js.map +1 -1
  275. package/dist/services/metrics/rate-limiter.mjs.map +1 -1
  276. package/dist/services/metrics/sender.js.map +1 -1
  277. package/dist/services/metrics/sender.mjs.map +1 -1
  278. package/dist/services/query-params.js.map +1 -1
  279. package/dist/services/query-params.mjs.map +1 -1
  280. package/dist/services/reloader.js.map +1 -1
  281. package/dist/services/reloader.mjs.map +1 -1
  282. package/dist/services/request-context.js.map +1 -1
  283. package/dist/services/request-context.mjs.map +1 -1
  284. package/dist/services/server/admin-api.js.map +1 -1
  285. package/dist/services/server/admin-api.mjs.map +1 -1
  286. package/dist/services/server/api.js.map +1 -1
  287. package/dist/services/server/api.mjs.map +1 -1
  288. package/dist/services/server/compose-endpoint.js.map +1 -1
  289. package/dist/services/server/compose-endpoint.mjs.map +1 -1
  290. package/dist/services/server/content-api.js.map +1 -1
  291. package/dist/services/server/content-api.mjs.map +1 -1
  292. package/dist/services/server/http-server.js.map +1 -1
  293. package/dist/services/server/http-server.mjs.map +1 -1
  294. package/dist/services/server/index.js.map +1 -1
  295. package/dist/services/server/index.mjs.map +1 -1
  296. package/dist/services/server/koa.js.map +1 -1
  297. package/dist/services/server/koa.mjs.map +1 -1
  298. package/dist/services/server/middleware.js.map +1 -1
  299. package/dist/services/server/middleware.mjs.map +1 -1
  300. package/dist/services/server/policy.js.map +1 -1
  301. package/dist/services/server/policy.mjs.map +1 -1
  302. package/dist/services/server/register-middlewares.js.map +1 -1
  303. package/dist/services/server/register-middlewares.mjs.map +1 -1
  304. package/dist/services/server/register-routes.js.map +1 -1
  305. package/dist/services/server/register-routes.mjs.map +1 -1
  306. package/dist/services/server/routing.js.map +1 -1
  307. package/dist/services/server/routing.mjs.map +1 -1
  308. package/dist/services/utils/dynamic-zones.js.map +1 -1
  309. package/dist/services/utils/dynamic-zones.mjs.map +1 -1
  310. package/dist/services/webhook-runner.js.map +1 -1
  311. package/dist/services/webhook-runner.mjs.map +1 -1
  312. package/dist/services/webhook-store.js.map +1 -1
  313. package/dist/services/webhook-store.mjs.map +1 -1
  314. package/dist/services/worker-queue.js.map +1 -1
  315. package/dist/services/worker-queue.mjs.map +1 -1
  316. package/dist/utils/convert-custom-field-type.js.map +1 -1
  317. package/dist/utils/convert-custom-field-type.mjs.map +1 -1
  318. package/dist/utils/cron.js.map +1 -1
  319. package/dist/utils/cron.mjs.map +1 -1
  320. package/dist/utils/fetch.js.map +1 -1
  321. package/dist/utils/fetch.mjs.map +1 -1
  322. package/dist/utils/filepath-to-prop-path.js.map +1 -1
  323. package/dist/utils/filepath-to-prop-path.mjs.map +1 -1
  324. package/dist/utils/is-initialized.js.map +1 -1
  325. package/dist/utils/is-initialized.mjs.map +1 -1
  326. package/dist/utils/load-config-file.js.map +1 -1
  327. package/dist/utils/load-config-file.mjs.map +1 -1
  328. package/dist/utils/load-files.js +1 -2
  329. package/dist/utils/load-files.js.map +1 -1
  330. package/dist/utils/load-files.mjs +1 -2
  331. package/dist/utils/load-files.mjs.map +1 -1
  332. package/dist/utils/resolve-working-dirs.js.map +1 -1
  333. package/dist/utils/resolve-working-dirs.mjs.map +1 -1
  334. package/dist/utils/signals.js.map +1 -1
  335. package/dist/utils/signals.mjs.map +1 -1
  336. package/dist/utils/startup-logger.d.ts.map +1 -1
  337. package/dist/utils/startup-logger.js +6 -1
  338. package/dist/utils/startup-logger.js.map +1 -1
  339. package/dist/utils/startup-logger.mjs +6 -1
  340. package/dist/utils/startup-logger.mjs.map +1 -1
  341. package/dist/utils/transform-content-types-to-models.js.map +1 -1
  342. package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
  343. package/dist/utils/update-notifier/index.js.map +1 -1
  344. package/dist/utils/update-notifier/index.mjs.map +1 -1
  345. package/package.json +14 -14
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../../src/services/entity-service/index.ts"],"sourcesContent":["import _ from 'lodash';\nimport delegate from 'delegates';\nimport { errors as databaseErrors } from '@strapi/database';\nimport {\n contentTypes as contentTypesUtils,\n errors,\n relations as relationUtils,\n} from '@strapi/utils';\nimport type { Database } from '@strapi/database';\nimport type { Core, Modules, Utils } from '@strapi/types';\n\ntype Decoratable<T> = T & {\n decorate(\n decorator: (old: Modules.EntityService.EntityService) => Modules.EntityService.EntityService & {\n [key: string]: unknown;\n }\n ): void;\n};\n\nconst transformLoadParamsToQuery = (\n uid: string,\n field: string,\n params: Record<string, unknown>,\n pagination = {}\n) => {\n const query = strapi\n .get('query-params')\n .transform(uid, { populate: { [field]: params } as any }) as any;\n\n const res = {\n ...query.populate[field],\n ...pagination,\n };\n\n return res;\n};\n\nconst databaseErrorsToTransform = [\n databaseErrors.InvalidTimeError,\n databaseErrors.InvalidDateTimeError,\n databaseErrors.InvalidDateError,\n databaseErrors.InvalidRelationError,\n];\n\nconst createDefaultImplementation = ({\n strapi,\n db,\n}: {\n strapi: Core.Strapi;\n db: Database;\n}): Modules.EntityService.EntityService => ({\n async wrapParams(options: any = {}) {\n return options;\n },\n\n async wrapResult(result: any = {}) {\n return result;\n },\n\n async findMany(uid, opts) {\n const { kind } = strapi.getModel(uid);\n\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findMany' });\n\n if (kind === 'singleType') {\n const entity = strapi.documents!(uid).findFirst(wrappedParams);\n return this.wrapResult(entity, { uid, action: 'findOne' });\n }\n\n const entities = await strapi.documents!(uid).findMany(wrappedParams);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findPage(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findPage' });\n\n const query = strapi.get('query-params').transform(uid, wrappedParams);\n\n const entities = await db.query(uid).findPage(query);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findOne(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findOne' });\n\n const res = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!res) {\n return this.wrapResult(null, { uid, action: 'findOne' });\n }\n\n const entity = await strapi.documents!(uid).findOne({\n ...wrappedParams,\n documentId: res.documentId,\n });\n return this.wrapResult(entity, { uid, action: 'findOne' });\n },\n\n async count(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'count' });\n\n return strapi.documents!(uid).count(wrappedParams);\n },\n\n async create(uid, params) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data' | 'fields' | 'populate'>\n >(params, { uid, action: 'create' });\n const { data } = wrappedParams;\n\n if (!data) {\n throw new Error('cannot create');\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(data, strapi.getModel(uid));\n\n const entity = await strapi.documents!(uid).create({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n });\n\n return this.wrapResult(entity, { uid, action: 'create' });\n },\n\n async update(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data:partial' | 'fields' | 'populate'>\n >(opts, {\n uid,\n action: 'update',\n });\n const entityToUpdate = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToUpdate) {\n return this.wrapResult(null, { uid, action: 'update' });\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(entityToUpdate, strapi.getModel(uid));\n\n const entity = strapi.documents!(uid).update({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n documentId: entityToUpdate.documentId,\n });\n\n return this.wrapResult(entity, { uid, action: 'update' });\n },\n\n async delete(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'delete' });\n\n const entityToDelete = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToDelete) {\n return this.wrapResult(null, { uid, action: 'delete' });\n }\n\n await strapi.documents!(uid).delete({\n ...wrappedParams,\n documentId: entityToDelete.documentId,\n });\n\n return this.wrapResult(entityToDelete, { uid, action: 'delete' });\n },\n\n async load(uid, entity, field, params) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const loadedEntity = await db\n .query(uid)\n .load(entity, field, transformLoadParamsToQuery(uid, field, params ?? {}));\n\n return this.wrapResult(loadedEntity, { uid, field, action: 'load' });\n },\n\n async loadPages(uid, entity, field, params, pagination = {}) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const { attributes } = strapi.getModel(uid);\n const attribute = attributes[field];\n\n if (!relationUtils.isAnyToMany(attribute)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be an anyToMany relational attribute`);\n }\n\n const query = transformLoadParamsToQuery(uid, field, params ?? {}, pagination);\n\n const loadedPage = await db.query(uid).loadPages(entity, field, query);\n\n return {\n ...loadedPage,\n results: await this.wrapResult(loadedPage.results, { uid, field, action: 'load' }),\n };\n },\n});\n\nexport default (ctx: {\n strapi: Core.Strapi;\n db: Database;\n}): Decoratable<Modules.EntityService.EntityService> => {\n const implementation = createDefaultImplementation(ctx);\n\n const service = {\n implementation,\n decorate<T extends object>(decorator: (current: typeof implementation) => T) {\n if (typeof decorator !== 'function') {\n throw new Error(`Decorator must be a function, received ${typeof decorator}`);\n }\n\n this.implementation = { ...this.implementation, ...decorator(this.implementation) };\n return this;\n },\n };\n\n const delegator = delegate(service, 'implementation');\n\n // delegate every method in implementation\n Object.keys(service.implementation).forEach((key) => delegator.method(key));\n\n // wrap methods to handle Database Errors\n service.decorate((oldService: Modules.EntityService.EntityService) => {\n const newService = _.mapValues(\n oldService,\n (method, methodName: keyof Modules.EntityService.EntityService) =>\n async function (this: Modules.EntityService.EntityService, ...args: []) {\n try {\n return await (oldService[methodName] as Utils.Function.AnyPromise).call(this, ...args);\n } catch (error) {\n if (\n databaseErrorsToTransform.some(\n (errorToTransform) => error instanceof errorToTransform\n )\n ) {\n if (error instanceof Error) {\n throw new errors.ValidationError(error.message);\n }\n\n throw error;\n }\n throw error;\n }\n }\n );\n\n return newService;\n });\n\n return service as unknown as Decoratable<Modules.EntityService.EntityService>;\n};\n"],"names":["databaseErrors","strapi","contentTypesUtils","relationUtils","errors"],"mappings":";;;;AAmBA,MAAM,6BAA6B,CACjC,KACA,OACA,QACA,aAAa,CAAA,MACV;AACH,QAAM,QAAQ,OACX,IAAI,cAAc,EAClB,UAAU,KAAK,EAAE,UAAU,EAAE,CAAC,KAAK,GAAG,OAAA,EAAiB,CAAA;AAE1D,QAAM,MAAM;AAAA,IACV,GAAG,MAAM,SAAS,KAAK;AAAA,IACvB,GAAG;AAAA,EAAA;AAGE,SAAA;AACT;AAEA,MAAM,4BAA4B;AAAA,EAChCA,OAAe;AAAA,EACfA,OAAe;AAAA,EACfA,OAAe;AAAA,EACfA,OAAe;AACjB;AAEA,MAAM,8BAA8B,CAAC;AAAA,EACnC,QAAAC;AAAAA,EACA;AACF,OAG4C;AAAA,EAC1C,MAAM,WAAW,UAAe,IAAI;AAC3B,WAAA;AAAA,EACT;AAAA,EAEA,MAAM,WAAW,SAAc,IAAI;AAC1B,WAAA;AAAA,EACT;AAAA,EAEA,MAAM,SAA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 from 'lodash';\nimport delegate from 'delegates';\nimport { errors as databaseErrors } from '@strapi/database';\nimport {\n contentTypes as contentTypesUtils,\n errors,\n relations as relationUtils,\n} from '@strapi/utils';\nimport type { Database } from '@strapi/database';\nimport type { Core, Modules, Utils } from '@strapi/types';\n\ntype Decoratable<T> = T & {\n decorate(\n decorator: (old: Modules.EntityService.EntityService) => Modules.EntityService.EntityService & {\n [key: string]: unknown;\n }\n ): void;\n};\n\nconst transformLoadParamsToQuery = (\n uid: string,\n field: string,\n params: Record<string, unknown>,\n pagination = {}\n) => {\n const query = strapi\n .get('query-params')\n .transform(uid, { populate: { [field]: params } as any }) as any;\n\n const res = {\n ...query.populate[field],\n ...pagination,\n };\n\n return res;\n};\n\nconst databaseErrorsToTransform = [\n databaseErrors.InvalidTimeError,\n databaseErrors.InvalidDateTimeError,\n databaseErrors.InvalidDateError,\n databaseErrors.InvalidRelationError,\n];\n\nconst createDefaultImplementation = ({\n strapi,\n db,\n}: {\n strapi: Core.Strapi;\n db: Database;\n}): Modules.EntityService.EntityService => ({\n async wrapParams(options: any = {}) {\n return options;\n },\n\n async wrapResult(result: any = {}) {\n return result;\n },\n\n async findMany(uid, opts) {\n const { kind } = strapi.getModel(uid);\n\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findMany' });\n\n if (kind === 'singleType') {\n const entity = strapi.documents!(uid).findFirst(wrappedParams);\n return this.wrapResult(entity, { uid, action: 'findOne' });\n }\n\n const entities = await strapi.documents!(uid).findMany(wrappedParams);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findPage(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findPage' });\n\n const query = strapi.get('query-params').transform(uid, wrappedParams);\n\n const entities = await db.query(uid).findPage(query);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findOne(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findOne' });\n\n const res = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!res) {\n return this.wrapResult(null, { uid, action: 'findOne' });\n }\n\n const entity = await strapi.documents!(uid).findOne({\n ...wrappedParams,\n documentId: res.documentId,\n });\n return this.wrapResult(entity, { uid, action: 'findOne' });\n },\n\n async count(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'count' });\n\n return strapi.documents!(uid).count(wrappedParams);\n },\n\n async create(uid, params) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data' | 'fields' | 'populate'>\n >(params, { uid, action: 'create' });\n const { data } = wrappedParams;\n\n if (!data) {\n throw new Error('cannot create');\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(data, strapi.getModel(uid));\n\n const entity = await strapi.documents!(uid).create({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n });\n\n return this.wrapResult(entity, { uid, action: 'create' });\n },\n\n async update(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data:partial' | 'fields' | 'populate'>\n >(opts, {\n uid,\n action: 'update',\n });\n const entityToUpdate = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToUpdate) {\n return this.wrapResult(null, { uid, action: 'update' });\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(entityToUpdate, strapi.getModel(uid));\n\n const entity = strapi.documents!(uid).update({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n documentId: entityToUpdate.documentId,\n });\n\n return this.wrapResult(entity, { uid, action: 'update' });\n },\n\n async delete(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'delete' });\n\n const entityToDelete = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToDelete) {\n return this.wrapResult(null, { uid, action: 'delete' });\n }\n\n await strapi.documents!(uid).delete({\n ...wrappedParams,\n documentId: entityToDelete.documentId,\n });\n\n return this.wrapResult(entityToDelete, { uid, action: 'delete' });\n },\n\n async load(uid, entity, field, params) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const loadedEntity = await db\n .query(uid)\n .load(entity, field, transformLoadParamsToQuery(uid, field, params ?? {}));\n\n return this.wrapResult(loadedEntity, { uid, field, action: 'load' });\n },\n\n async loadPages(uid, entity, field, params, pagination = {}) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const { attributes } = strapi.getModel(uid);\n const attribute = attributes[field];\n\n if (!relationUtils.isAnyToMany(attribute)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be an anyToMany relational attribute`);\n }\n\n const query = transformLoadParamsToQuery(uid, field, params ?? {}, pagination);\n\n const loadedPage = await db.query(uid).loadPages(entity, field, query);\n\n return {\n ...loadedPage,\n results: await this.wrapResult(loadedPage.results, { uid, field, action: 'load' }),\n };\n },\n});\n\nexport default (ctx: {\n strapi: Core.Strapi;\n db: Database;\n}): Decoratable<Modules.EntityService.EntityService> => {\n const implementation = createDefaultImplementation(ctx);\n\n const service = {\n implementation,\n decorate<T extends object>(decorator: (current: typeof implementation) => T) {\n if (typeof decorator !== 'function') {\n throw new Error(`Decorator must be a function, received ${typeof decorator}`);\n }\n\n this.implementation = { ...this.implementation, ...decorator(this.implementation) };\n return this;\n },\n };\n\n const delegator = delegate(service, 'implementation');\n\n // delegate every method in implementation\n Object.keys(service.implementation).forEach((key) => delegator.method(key));\n\n // wrap methods to handle Database Errors\n service.decorate((oldService: Modules.EntityService.EntityService) => {\n const newService = _.mapValues(\n oldService,\n (method, methodName: keyof Modules.EntityService.EntityService) =>\n async function (this: Modules.EntityService.EntityService, ...args: []) {\n try {\n return await (oldService[methodName] as Utils.Function.AnyPromise).call(this, ...args);\n } catch (error) {\n if (\n databaseErrorsToTransform.some(\n (errorToTransform) => error instanceof errorToTransform\n )\n ) {\n if (error instanceof Error) {\n throw new errors.ValidationError(error.message);\n }\n\n throw error;\n }\n throw error;\n }\n }\n );\n\n return newService;\n });\n\n return service as unknown as Decoratable<Modules.EntityService.EntityService>;\n};\n"],"names":["databaseErrors","strapi","contentTypesUtils","relationUtils","errors"],"mappings":";;;;AAmBA,MAAM,6BAA6B,CACjC,KACA,OACA,QACA,aAAa,CAAA,MACV;AACH,QAAM,QAAQ,OACX,IAAI,cAAc,EAClB,UAAU,KAAK,EAAE,UAAU,EAAE,CAAC,KAAK,GAAG,UAAiB;AAE1D,QAAM,MAAM;AAAA,IACV,GAAG,MAAM,SAAS,KAAK;AAAA,IACvB,GAAG;AAAA,EACL;AAEO,SAAA;AACT;AAEA,MAAM,4BAA4B;AAAA,EAChCA,OAAe;AAAA,EACfA,OAAe;AAAA,EACfA,OAAe;AAAA,EACfA,OAAe;AACjB;AAEA,MAAM,8BAA8B,CAAC;AAAA,EACnC,QAAAC;AAAAA,EACA;AACF,OAG4C;AAAA,EAC1C,MAAM,WAAW,UAAe,IAAI;AAC3B,WAAA;AAAA,EACT;AAAA,EAEA,MAAM,WAAW,SAAc,IAAI;AAC1B,WAAA;AAAA,EACT;AAAA,EAEA,MAAM,SAAS,KAAK,MAAM;AACxB,UAAM,EAAE,KAASA,IAAAA,QAAO,SAAS,GAAG;AAE9B,UAAA,gBAAgB,MAAM,KAAK,WAAW,MAAM,EAAE,KAAK,QAAQ,YAAY;AAE7E,QAAI,SAAS,cAAc;AACzB,YAAM,SAASA,QAAO,UAAW,GAAG,EAAE,UAAU,aAAa;AAC7D,aAAO,KAAK,WAAW,QAAQ,EAAE,KAAK,QAAQ,WAAW;AAAA,IAAA;AAG3D,UAAM,WAAW,MAAMA,QAAO,UAAW,GAAG,EAAE,SAAS,aAAa;AACpE,WAAO,KAAK,WAAW,UAAU,EAAE,KAAK,QAAQ,YAAY;AAAA,EAC9D;AAAA,EAEA,MAAM,SAAS,KAAK,MAAM;AAClB,UAAA,gBAAgB,MAAM,KAAK,WAAW,MAAM,EAAE,KAAK,QAAQ,YAAY;AAE7E,UAAM,QAAQA,QAAO,IAAI,cAAc,EAAE,UAAU,K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,EAAE,QAAQ,CAAC,QAAQ,UAAU,OAAO,GAAG,CAAC;AAGlE,UAAA,SAAS,CAAC,eAAoD;AACpE,UAAM,aAAa,EAAE;AAAA,MACnB;AAAA,MACA,CAAC,QAAQ,eACP,kBAA8D,MAAU;AAClE,YAAA;AACF,iBAAO,MAAO,WAAW,UAAU,EAAgC,KAAK,MAAM,GAAG,IAAI;AAAA,iBAC9E,OAAO;AACd,cACE,0BAA0B;AAAA,YACxB,CAAC,qBAAqB,iBAAiB;AAAA,UAAA,GAEzC;AACA,gBAAI,iBAAiB,OAAO;AAC1B,oBAAM,IAAIC,SAAO,gBAAgB,MAAM,OAAO;AAAA,YAAA;AAG1C,kBAAA;AAAA,UAAA;AAEF,gBAAA;AAAA,QAAA;AAAA,MACR;AAAA,IAEN;AAEO,WAAA;AAAA,EAAA,CACR;AAEM,SAAA;AACT;"}
@@ -1 +1 @@
1
- {"version":3,"file":"blocks-validator.js","sources":["../../../src/services/entity-validator/blocks-validator.ts"],"sourcesContent":["import { yup } from '@strapi/utils';\n\nconst textNodeValidator = yup.object().shape({\n type: yup.string().equals(['text']).required(),\n text: yup\n .string()\n .test(\n 'is-valid-text',\n 'Text must be defined with at least an empty string',\n (text: unknown) => {\n return typeof text === 'string' || text === '';\n }\n ),\n bold: yup.boolean(),\n italic: yup.boolean(),\n underline: yup.boolean(),\n strikethrough: yup.boolean(),\n code: yup.boolean(),\n});\n\nconst checkValidLink = (link: string) => {\n try {\n // eslint-disable-next-line no-new\n new URL(link.startsWith('/') ? `https://strapi.io${link}` : link);\n } catch (error) {\n return false;\n }\n return true;\n};\n\nconst linkNodeValidator = yup.object().shape({\n type: yup.string().equals(['link']).required(),\n url: yup\n .string()\n .test('invalid-url', 'Please specify a valid link.', (value) => checkValidLink(value ?? '')),\n children: yup.array().of(textNodeValidator).required(),\n});\n\n// TODO: remove any with a correct Type\nconst inlineNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'text':\n return textNodeValidator;\n case 'link':\n return linkNodeValidator;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be Text or Link', () => {\n return false;\n });\n }\n});\n\nconst paragraphNodeValidator = yup.object().shape({\n type: yup.string().equals(['paragraph']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Paragraph node children must have at least one Text or Link node')\n .required(),\n});\n\nconst headingNodeValidator = yup.object().shape({\n type: yup.string().equals(['heading']).required(),\n level: yup.number().oneOf([1, 2, 3, 4, 5, 6]).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Heading node children must have at least one Text or Link node')\n .required(),\n});\n\nconst quoteNodeValidator = yup.object().shape({\n type: yup.string().equals(['quote']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst codeBlockValidator = yup.object().shape({\n type: yup.string().equals(['code']).required(),\n syntax: yup.string().nullable(),\n children: yup\n .array()\n .of(textNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst listItemNode = yup.object().shape({\n type: yup.string().equals(['list-item']).required(),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// Allow children to be either a listItemNode or a listNode itself\n// @ts-expect-error - listChildrenValidator needs a type\nconst listChildrenValidator = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'list':\n return listNodeValidator;\n case 'list-item':\n return listItemNode;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be list-item or list', () => {\n return false;\n });\n }\n});\n\n// @ts-expect-error - listNodeValidator needs a type\nconst listNodeValidator = yup.object().shape({\n type: yup.string().equals(['list']).required(),\n format: yup.string().equals(['ordered', 'unordered']).required(),\n children: yup\n .array()\n .of(listChildrenValidator)\n .min(1, 'List node children must have at least one ListItem or ListNode')\n .required(),\n});\n\nconst imageNodeValidator = yup.object().shape({\n type: yup.string().equals(['image']).required(),\n image: yup.object().shape({\n name: yup.string().required(),\n alternativeText: yup.string().nullable(),\n url: yup.string().required(),\n caption: yup.string().nullable(),\n width: yup.number().required(),\n height: yup.number().required(),\n formats: yup.object().required(),\n hash: yup.string().required(),\n ext: yup.string().required(),\n mime: yup.string().required(),\n size: yup.number().required(),\n previewUrl: yup.string().nullable(),\n provider: yup.string().required(),\n provider_metadata: yup.mixed().nullable(),\n createdAt: yup.string().required(),\n updatedAt: yup.string().required(),\n }),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// TODO: remove the any and replace with a correct Type\nconst blockNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'paragraph':\n return paragraphNodeValidator;\n case 'heading':\n return headingNodeValidator;\n case 'quote':\n return quoteNodeValidator;\n case 'list':\n return listNodeValidator;\n case 'image':\n return imageNodeValidator;\n case 'code':\n return codeBlockValidator;\n default:\n return yup.mixed().test('invalid-type', 'Block node is of invalid type', () => {\n return false;\n });\n }\n});\n\nconst blocksValidatorSchema = yup.array().of(blockNodeValidator);\n\nexport const blocksValidator = () => blocksValidatorSchema;\n"],"names":["yup"],"mappings":";;;AAEA,MAAM,oBAAoBA,YAAA,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAMA,gBAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,MAAMA,YAAAA,IACH,OAAA,EACA;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,SAAkB;AACV,aAAA,OAAO,SAAS,YAAY,SAAS;AAAA,IAC9C;AAAA,EACF;AAAA,EACF,MAAMA,gBAAI,QAAQ;AAAA,EAClB,QAAQA,gBAAI,QAAQ;AAAA,EACpB,WAAWA,gBAAI,QAAQ;AAAA,EACvB,eAAeA,gBAAI,QAAQ;AAAA,EAC3B,MAAMA,gBAAI,QAAQ;AACpB,CAAC;AAED,MAAM,iBAAiB,CAAC,SAAiB;AACnC,MAAA;AAEE,QAAA,IAAI,KAAK,WAAW,GAAG,IAAI,oBAAoB,IAAI,KAAK,IAAI;AAAA,WACz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;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT;AACE,aAAOA,YAAAA,IAAI,MAAM,EAAE,KAAK,gBAAgB,iCAAiC,MAAM;AACtE,eAAA;AAAA,MAAA,CACR;AAAA,EACL;AACF,CAAC;AAED,MAAM,wBAAwBA,YAAAA,IAAI,MAAM,EAAE,GAAG,kBAAkB;AAExD,MAAM,kBAAkB,MAAM;;"}
1
+ {"version":3,"file":"blocks-validator.js","sources":["../../../src/services/entity-validator/blocks-validator.ts"],"sourcesContent":["import { yup } from '@strapi/utils';\n\nconst textNodeValidator = yup.object().shape({\n type: yup.string().equals(['text']).required(),\n text: yup\n .string()\n .test(\n 'is-valid-text',\n 'Text must be defined with at least an empty string',\n (text: unknown) => {\n return typeof text === 'string' || text === '';\n }\n ),\n bold: yup.boolean(),\n italic: yup.boolean(),\n underline: yup.boolean(),\n strikethrough: yup.boolean(),\n code: yup.boolean(),\n});\n\nconst checkValidLink = (link: string) => {\n try {\n // eslint-disable-next-line no-new\n new URL(link.startsWith('/') ? `https://strapi.io${link}` : link);\n } catch (error) {\n return false;\n }\n return true;\n};\n\nconst linkNodeValidator = yup.object().shape({\n type: yup.string().equals(['link']).required(),\n url: yup\n .string()\n .test('invalid-url', 'Please specify a valid link.', (value) => checkValidLink(value ?? '')),\n children: yup.array().of(textNodeValidator).required(),\n});\n\n// TODO: remove any with a correct Type\nconst inlineNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'text':\n return textNodeValidator;\n case 'link':\n return linkNodeValidator;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be Text or Link', () => {\n return false;\n });\n }\n});\n\nconst paragraphNodeValidator = yup.object().shape({\n type: yup.string().equals(['paragraph']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Paragraph node children must have at least one Text or Link node')\n .required(),\n});\n\nconst headingNodeValidator = yup.object().shape({\n type: yup.string().equals(['heading']).required(),\n level: yup.number().oneOf([1, 2, 3, 4, 5, 6]).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Heading node children must have at least one Text or Link node')\n .required(),\n});\n\nconst quoteNodeValidator = yup.object().shape({\n type: yup.string().equals(['quote']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst codeBlockValidator = yup.object().shape({\n type: yup.string().equals(['code']).required(),\n syntax: yup.string().nullable(),\n children: yup\n .array()\n .of(textNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst listItemNode = yup.object().shape({\n type: yup.string().equals(['list-item']).required(),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// Allow children to be either a listItemNode or a listNode itself\n// @ts-expect-error - listChildrenValidator needs a type\nconst listChildrenValidator = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'list':\n return listNodeValidator;\n case 'list-item':\n return listItemNode;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be list-item or list', () => {\n return false;\n });\n }\n});\n\n// @ts-expect-error - listNodeValidator needs a type\nconst listNodeValidator = yup.object().shape({\n type: yup.string().equals(['list']).required(),\n format: yup.string().equals(['ordered', 'unordered']).required(),\n children: yup\n .array()\n .of(listChildrenValidator)\n .min(1, 'List node children must have at least one ListItem or ListNode')\n .required(),\n});\n\nconst imageNodeValidator = yup.object().shape({\n type: yup.string().equals(['image']).required(),\n image: yup.object().shape({\n name: yup.string().required(),\n alternativeText: yup.string().nullable(),\n url: yup.string().required(),\n caption: yup.string().nullable(),\n width: yup.number().required(),\n height: yup.number().required(),\n formats: yup.object().required(),\n hash: yup.string().required(),\n ext: yup.string().required(),\n mime: yup.string().required(),\n size: yup.number().required(),\n previewUrl: yup.string().nullable(),\n provider: yup.string().required(),\n provider_metadata: yup.mixed().nullable(),\n createdAt: yup.string().required(),\n updatedAt: yup.string().required(),\n }),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// TODO: remove the any and replace with a correct Type\nconst blockNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'paragraph':\n return paragraphNodeValidator;\n case 'heading':\n return headingNodeValidator;\n case 'quote':\n return quoteNodeValidator;\n case 'list':\n return listNodeValidator;\n case 'image':\n return imageNodeValidator;\n case 'code':\n return codeBlockValidator;\n default:\n return yup.mixed().test('invalid-type', 'Block node is of invalid type', () => {\n return false;\n });\n }\n});\n\nconst blocksValidatorSchema = yup.array().of(blockNodeValidator);\n\nexport const blocksValidator = () => blocksValidatorSchema;\n"],"names":["yup"],"mappings":";;;AAEA,MAAM,oBAAoBA,YAAA,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAMA,gBAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,MAAMA,YAAAA,IACH,OAAA,EACA;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,SAAkB;AACV,aAAA,OAAO,SAAS,YAAY,SAAS;AAAA,IAAA;AAAA,EAEhD;AAAA,EACF,MAAMA,gBAAI,QAAQ;AAAA,EAClB,QAAQA,gBAAI,QAAQ;AAAA,EACpB,WAAWA,gBAAI,QAAQ;AAAA,EACvB,eAAeA,gBAAI,QAAQ;AAAA,EAC3B,MAAMA,gBAAI,QAAQ;AACpB,CAAC;AAED,MAAM,iBAAiB,CAAC,SAAiB;AACnC,MAAA;AAEE,QAAA,IAAI,KAAK,WAAW,GAAG,IAAI,oBAAoB,IAAI,KAAK,IAAI;AAAA,WACzD,OAAO;AACP,WAAA;AAAA,EAAA;AAEF,SAAA;AACT;AAEA,MAAM,oBAAoBA,YAAA,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAMA,gBAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,KAAKA,YAAA,IACF,OAAO,EACP,KAA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MAAA,CACR;AAAA,EAAA;AAEP,CAAC;AAED,MAAM,wBAAwBA,YAAAA,IAAI,QAAQ,GAAG,kBAAkB;AAExD,MAAM,kBAAkB,MAAM;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"blocks-validator.mjs","sources":["../../../src/services/entity-validator/blocks-validator.ts"],"sourcesContent":["import { yup } from '@strapi/utils';\n\nconst textNodeValidator = yup.object().shape({\n type: yup.string().equals(['text']).required(),\n text: yup\n .string()\n .test(\n 'is-valid-text',\n 'Text must be defined with at least an empty string',\n (text: unknown) => {\n return typeof text === 'string' || text === '';\n }\n ),\n bold: yup.boolean(),\n italic: yup.boolean(),\n underline: yup.boolean(),\n strikethrough: yup.boolean(),\n code: yup.boolean(),\n});\n\nconst checkValidLink = (link: string) => {\n try {\n // eslint-disable-next-line no-new\n new URL(link.startsWith('/') ? `https://strapi.io${link}` : link);\n } catch (error) {\n return false;\n }\n return true;\n};\n\nconst linkNodeValidator = yup.object().shape({\n type: yup.string().equals(['link']).required(),\n url: yup\n .string()\n .test('invalid-url', 'Please specify a valid link.', (value) => checkValidLink(value ?? '')),\n children: yup.array().of(textNodeValidator).required(),\n});\n\n// TODO: remove any with a correct Type\nconst inlineNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'text':\n return textNodeValidator;\n case 'link':\n return linkNodeValidator;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be Text or Link', () => {\n return false;\n });\n }\n});\n\nconst paragraphNodeValidator = yup.object().shape({\n type: yup.string().equals(['paragraph']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Paragraph node children must have at least one Text or Link node')\n .required(),\n});\n\nconst headingNodeValidator = yup.object().shape({\n type: yup.string().equals(['heading']).required(),\n level: yup.number().oneOf([1, 2, 3, 4, 5, 6]).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Heading node children must have at least one Text or Link node')\n .required(),\n});\n\nconst quoteNodeValidator = yup.object().shape({\n type: yup.string().equals(['quote']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst codeBlockValidator = yup.object().shape({\n type: yup.string().equals(['code']).required(),\n syntax: yup.string().nullable(),\n children: yup\n .array()\n .of(textNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst listItemNode = yup.object().shape({\n type: yup.string().equals(['list-item']).required(),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// Allow children to be either a listItemNode or a listNode itself\n// @ts-expect-error - listChildrenValidator needs a type\nconst listChildrenValidator = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'list':\n return listNodeValidator;\n case 'list-item':\n return listItemNode;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be list-item or list', () => {\n return false;\n });\n }\n});\n\n// @ts-expect-error - listNodeValidator needs a type\nconst listNodeValidator = yup.object().shape({\n type: yup.string().equals(['list']).required(),\n format: yup.string().equals(['ordered', 'unordered']).required(),\n children: yup\n .array()\n .of(listChildrenValidator)\n .min(1, 'List node children must have at least one ListItem or ListNode')\n .required(),\n});\n\nconst imageNodeValidator = yup.object().shape({\n type: yup.string().equals(['image']).required(),\n image: yup.object().shape({\n name: yup.string().required(),\n alternativeText: yup.string().nullable(),\n url: yup.string().required(),\n caption: yup.string().nullable(),\n width: yup.number().required(),\n height: yup.number().required(),\n formats: yup.object().required(),\n hash: yup.string().required(),\n ext: yup.string().required(),\n mime: yup.string().required(),\n size: yup.number().required(),\n previewUrl: yup.string().nullable(),\n provider: yup.string().required(),\n provider_metadata: yup.mixed().nullable(),\n createdAt: yup.string().required(),\n updatedAt: yup.string().required(),\n }),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// TODO: remove the any and replace with a correct Type\nconst blockNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'paragraph':\n return paragraphNodeValidator;\n case 'heading':\n return headingNodeValidator;\n case 'quote':\n return quoteNodeValidator;\n case 'list':\n return listNodeValidator;\n case 'image':\n return imageNodeValidator;\n case 'code':\n return codeBlockValidator;\n default:\n return yup.mixed().test('invalid-type', 'Block node is of invalid type', () => {\n return false;\n });\n }\n});\n\nconst blocksValidatorSchema = yup.array().of(blockNodeValidator);\n\nexport const blocksValidator = () => blocksValidatorSchema;\n"],"names":[],"mappings":";AAEA,MAAM,oBAAoB,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAM,IAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,MAAM,IACH,OAAA,EACA;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,SAAkB;AACV,aAAA,OAAO,SAAS,YAAY,SAAS;AAAA,IAC9C;AAAA,EACF;AAAA,EACF,MAAM,IAAI,QAAQ;AAAA,EAClB,QAAQ,IAAI,QAAQ;AAAA,EACpB,WAAW,IAAI,QAAQ;AAAA,EACvB,eAAe,IAAI,QAAQ;AAAA,EAC3B,MAAM,IAAI,QAAQ;AACpB,CAAC;AAED,MAAM,iBAAiB,CAAC,SAAiB;AACnC,MAAA;AAEE,QAAA,IAAI,KAAK,WAAW,GAAG,IAAI,oBAAoB,IAAI,KAAK,IAAI;AAAA,WACzD,OAAO;AACP,WAAA;AAAA,EACT;AACO,SAAA;AACT;AAEA,MAAM,oBAAoB,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAM,IAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,KAAK,IACF,OAAO,EACP,KAAK,eAAe,gCAAgC,CAAC,UAAU,eAAe,SAAS,EAAE,CAAC;AAAA,EAC7F,UAAU,IAAI,MAAA,EAAQ,GAAG,iBAAiB,EAAE,SAAS;AACvD,CAAC;AAGD,MAAM,sBAA2B,IAAI,KAAK,CAAC,UAA4B;AACrE,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AAC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M,IAAI,OAAO,EAAE,SAAS;AAAA,IAC5B,YAAY,IAAI,OAAO,EAAE,SAAS;AAAA,IAClC,UAAU,IAAI,OAAO,EAAE,SAAS;AAAA,IAChC,mBAAmB,IAAI,MAAM,EAAE,SAAS;AAAA,IACxC,WAAW,IAAI,OAAO,EAAE,SAAS;AAAA,IACjC,WAAW,IAAI,OAAO,EAAE,SAAS;AAAA,EAAA,CAClC;AAAA,EACD,UAAU,IAAI,MAAA,EAAQ,GAAG,mBAAmB,EAAE,SAAS;AACzD,CAAC;AAGD,MAAM,qBAA0B,IAAI,KAAK,CAAC,UAA4B;AACpE,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT;AACE,aAAO,IAAI,MAAM,EAAE,KAAK,gBAAgB,iCAAiC,MAAM;AACtE,eAAA;AAAA,MAAA,CACR;AAAA,EACL;AACF,CAAC;AAED,MAAM,wBAAwB,IAAI,MAAM,EAAE,GAAG,kBAAkB;AAExD,MAAM,kBAAkB,MAAM;"}
1
+ {"version":3,"file":"blocks-validator.mjs","sources":["../../../src/services/entity-validator/blocks-validator.ts"],"sourcesContent":["import { yup } from '@strapi/utils';\n\nconst textNodeValidator = yup.object().shape({\n type: yup.string().equals(['text']).required(),\n text: yup\n .string()\n .test(\n 'is-valid-text',\n 'Text must be defined with at least an empty string',\n (text: unknown) => {\n return typeof text === 'string' || text === '';\n }\n ),\n bold: yup.boolean(),\n italic: yup.boolean(),\n underline: yup.boolean(),\n strikethrough: yup.boolean(),\n code: yup.boolean(),\n});\n\nconst checkValidLink = (link: string) => {\n try {\n // eslint-disable-next-line no-new\n new URL(link.startsWith('/') ? `https://strapi.io${link}` : link);\n } catch (error) {\n return false;\n }\n return true;\n};\n\nconst linkNodeValidator = yup.object().shape({\n type: yup.string().equals(['link']).required(),\n url: yup\n .string()\n .test('invalid-url', 'Please specify a valid link.', (value) => checkValidLink(value ?? '')),\n children: yup.array().of(textNodeValidator).required(),\n});\n\n// TODO: remove any with a correct Type\nconst inlineNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'text':\n return textNodeValidator;\n case 'link':\n return linkNodeValidator;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be Text or Link', () => {\n return false;\n });\n }\n});\n\nconst paragraphNodeValidator = yup.object().shape({\n type: yup.string().equals(['paragraph']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Paragraph node children must have at least one Text or Link node')\n .required(),\n});\n\nconst headingNodeValidator = yup.object().shape({\n type: yup.string().equals(['heading']).required(),\n level: yup.number().oneOf([1, 2, 3, 4, 5, 6]).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Heading node children must have at least one Text or Link node')\n .required(),\n});\n\nconst quoteNodeValidator = yup.object().shape({\n type: yup.string().equals(['quote']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst codeBlockValidator = yup.object().shape({\n type: yup.string().equals(['code']).required(),\n syntax: yup.string().nullable(),\n children: yup\n .array()\n .of(textNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst listItemNode = yup.object().shape({\n type: yup.string().equals(['list-item']).required(),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// Allow children to be either a listItemNode or a listNode itself\n// @ts-expect-error - listChildrenValidator needs a type\nconst listChildrenValidator = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'list':\n return listNodeValidator;\n case 'list-item':\n return listItemNode;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be list-item or list', () => {\n return false;\n });\n }\n});\n\n// @ts-expect-error - listNodeValidator needs a type\nconst listNodeValidator = yup.object().shape({\n type: yup.string().equals(['list']).required(),\n format: yup.string().equals(['ordered', 'unordered']).required(),\n children: yup\n .array()\n .of(listChildrenValidator)\n .min(1, 'List node children must have at least one ListItem or ListNode')\n .required(),\n});\n\nconst imageNodeValidator = yup.object().shape({\n type: yup.string().equals(['image']).required(),\n image: yup.object().shape({\n name: yup.string().required(),\n alternativeText: yup.string().nullable(),\n url: yup.string().required(),\n caption: yup.string().nullable(),\n width: yup.number().required(),\n height: yup.number().required(),\n formats: yup.object().required(),\n hash: yup.string().required(),\n ext: yup.string().required(),\n mime: yup.string().required(),\n size: yup.number().required(),\n previewUrl: yup.string().nullable(),\n provider: yup.string().required(),\n provider_metadata: yup.mixed().nullable(),\n createdAt: yup.string().required(),\n updatedAt: yup.string().required(),\n }),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// TODO: remove the any and replace with a correct Type\nconst blockNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'paragraph':\n return paragraphNodeValidator;\n case 'heading':\n return headingNodeValidator;\n case 'quote':\n return quoteNodeValidator;\n case 'list':\n return listNodeValidator;\n case 'image':\n return imageNodeValidator;\n case 'code':\n return codeBlockValidator;\n default:\n return yup.mixed().test('invalid-type', 'Block node is of invalid type', () => {\n return false;\n });\n }\n});\n\nconst blocksValidatorSchema = yup.array().of(blockNodeValidator);\n\nexport const blocksValidator = () => blocksValidatorSchema;\n"],"names":[],"mappings":";AAEA,MAAM,oBAAoB,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAM,IAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,MAAM,IACH,OAAA,EACA;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,SAAkB;AACV,aAAA,OAAO,SAAS,YAAY,SAAS;AAAA,IAAA;AAAA,EAEhD;AAAA,EACF,MAAM,IAAI,QAAQ;AAAA,EAClB,QAAQ,IAAI,QAAQ;AAAA,EACpB,WAAW,IAAI,QAAQ;AAAA,EACvB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,aAAO,IAAI,MAAM,EAAE,KAAK,gBAAgB,iCAAiC,MAAM;AACtE,eAAA;AAAA,MAAA,CACR;AAAA,EAAA;AAEP,CAAC;AAED,MAAM,wBAAwB,IAAI,QAAQ,GAAG,kBAAkB;AAExD,MAAM,kBAAkB,MAAM;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, Validators)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["strapiUtils","validator","prop","has","Validators","validators","isObject","data","isEmpty","isNil","castArray","mergeWith","isArray","value","uniqBy"],"mappings":";;;;;;;AAaA,MAAM,EAAE,KAAK,kBAAsB,IAAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,sBAAA,IAA0BA,qBAAAA,QAAY;AACnF,MAAM,EAAE,gBAAgB,IAAIA,qBAAY,QAAA;AA4CxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,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AsB,OAAO,iBAAuC,OAAO;AAC/E,QAAM,WAA4B,CAAA;AAElC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,cAAc,GAAG;AACzD,UAAM,WAAW,YAAY;AACrB,YAAA,eAAeE,EAAO,OAAA,OAAO,IAAI;AACvC,YAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,GAAiB,EAAE,MAAM;AAAA,QAC3D,OAAO;AAAA,UACL,IAAI;AAAA,YACF,KAAK,aAAa,IAAI,CAAC,MAAM,EAAE,EAAE;AAAA,UACnC;AAAA,QACF;AAAA,MAAA,CACD;AAEG,UAAA,UAAU,aAAa,QAAQ;AACjC,cAAM,IAAI;AAAA,UACR,GACE,aAAa,SAAS,KACxB,wBAAwB,GAAG;AAAA,QAAA;AAAA,MAE/B;AAAA,IAAA;AAEO,aAAA,KAAK,UAAU;AAAA,EAC1B;AAEO,SAAA,QAAQ,IAAI,QAAQ;AAC7B;AAEA,MAAM,kBAA2D;AAAA,EAC/D,wBAAwB,qBAAqB,UAAU;AAAA,EACvD,sBAAsB,qBAAqB,QAAQ;AACrD;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, Validators)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["strapiUtils","validator","prop","has","Validators","validators","isObject","data","isEmpty","isNil","castArray","mergeWith","isArray","value","uniqBy"],"mappings":";;;;;;;AAaA,MAAM,EAAE,KAAK,kBAAA,IAAsBA,qBAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,0BAA0BA,qBAAY,QAAA;AACnF,MAAM,EAAE,gBAAgB,IAAIA,qBAAAA,QAAY;AA4CxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AACF,MACM;AACN,MAAI,gBAAmB;AAEvB,MACE,UAAU,KAAK,GAAG,MAChB,cAAc,QAAQ,KAAK,YAC1B,MAAM,QAAQ,iBAAiB,KAAK,KAAK,iBAAiB,MAAM,SAAS,IAC5E;AACgB,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAAA;AAExC,MAAA,UAAU,KAAK,GAAG,GAAG;AACP,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAAA;AAErC,SAAA;AACT;AAEA,MAAM,wBAAwB,CAAC,mBAAmC;AAChE,SAAO,CACL,WACA;AAAA,IACE,MAAM,EAAE,SAAS;AAAA,EAAA,MAEb;AACN,QAAI,gBAAgB;AAEpB,QAAI,UAAU;AACZ,UAAI,mBAAmB,YAAY;AACjC,wBAAgB,cAAc,OAAO;AAAA,MAAA,WAC5B,mBAAmB,UAAU;AACtC,wBAAgB,cAAc,QAAQ;AAAA,MAAA;AAAA,IACxC,OACK;AACL,sBAAgB,cAAc,SAAS;AAAA,IAAA;AAElC,WAAA;AAAA,EACT;AACF;AAEA,MAAM,aAAa,CAAC,mBAAmC;AACrD,SAA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AQ;AACrD;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, Validators)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["validator","data","value"],"mappings":";;;;AAaA,MAAM,EAAE,KAAK,kBAAsB,IAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,sBAAA,IAA0B,YAAY;AACnF,MAAM,EAAE,gBAAgB,IAAI,YAAY;AA4CxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AACF,MACM;AACN,MAAI,gBAAmB;AAEvB,MACE,UAAU,KAAK,GAAG,MAChB,cAAc,QAAQ,KAAK,YAC1B,MAAM,QAAQ,iBAAiB,KAAK,KAAK,iBAAiB,MAAM,SAAS,IAC5E;AACgB,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACI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Aa,QAAQ;AACjC,cAAM,IAAI;AAAA,UACR,GACE,aAAa,SAAS,KACxB,wBAAwB,GAAG;AAAA,QAAA;AAAA,MAE/B;AAAA,IAAA;AAEO,aAAA,KAAK,UAAU;AAAA,EAC1B;AAEO,SAAA,QAAQ,IAAI,QAAQ;AAC7B;AAEA,MAAM,kBAA2D;AAAA,EAC/D,wBAAwB,qBAAqB,UAAU;AAAA,EACvD,sBAAsB,qBAAqB,QAAQ;AACrD;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, Validators)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["validator","data","value"],"mappings":";;;;AAaA,MAAM,EAAE,KAAK,kBAAA,IAAsB;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,0BAA0B,YAAY;AACnF,MAAM,EAAE,gBAAgB,IAAI,YAAY;AA4CxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;A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AAEnC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,cAAc,GAAG;AACzD,UAAM,WAAW,YAAY;AACrB,YAAA,eAAe,OAAO,OAAO,IAAI;AACvC,YAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,GAAiB,EAAE,MAAM;AAAA,QAC3D,OAAO;AAAA,UACL,IAAI;AAAA,YACF,KAAK,aAAa,IAAI,CAAC,MAAM,EAAE,EAAE;AAAA,UAAA;AAAA,QACnC;AAAA,MACF,CACD;AAEG,UAAA,UAAU,aAAa,QAAQ;AACjC,cAAM,IAAI;AAAA,UACR,GACE,aAAa,SAAS,KACxB,wBAAwB,GAAG;AAAA,QAC7B;AAAA,MAAA;AAAA,IAEJ;AACS,aAAA,KAAK,UAAU;AAAA,EAAA;AAGnB,SAAA,QAAQ,IAAI,QAAQ;AAC7B;AAEA,MAAM,kBAA2D;AAAA,EAC/D,wBAAwB,qBAAqB,UAAU;AAAA,EACvD,sBAAsB,qBAAqB,QAAQ;AACrD;"}
@@ -1 +1 @@
1
- {"version":3,"file":"validators.js","sources":["../../../src/services/entity-validator/validators.ts"],"sourcesContent":["/**\n * Validators check if the entry data meets specific criteria before saving or publishing.\n * (e.g., length, range, format).\n *\n * Drafts have limited validations (mainly max constraints),\n * while published content undergoes full validation.\n *\n * The system also takes locales into account when validating data.\n * E.g, unique fields must be unique within the same locale.\n */\nimport _ from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Schema, Struct, Modules } from '@strapi/types';\nimport { blocksValidator } from './blocks-validator';\n\nimport type { ComponentContext } from '.';\n\nexport interface ValidatorMetas<\n TAttribute extends Schema.Attribute.AnyAttribute = Schema.Attribute.AnyAttribute,\n TValue extends Schema.Attribute.Value<TAttribute> = Schema.Attribute.Value<TAttribute>,\n> {\n attr: TAttribute;\n model: Struct.Schema;\n updatedAttribute: {\n name: string;\n value: TValue;\n };\n componentContext?: ComponentContext;\n entity?: Modules.EntityValidator.Entity;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n },\n { isDraft }: ValidatorOptions\n) => (_.isNumber(attr.min) && !isDraft ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n },\n { isDraft }: ValidatorOptions\n) => (_.isNumber(attr.min) && !isDraft ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex) && !isDraft\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\nconst addUniqueValidator = <T extends yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n componentContext,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n const validateUniqueFieldWithinComponent = async (value: any): Promise<boolean> => {\n if (!componentContext) {\n return false;\n }\n\n // If we are validating a unique field within a repeatable component,\n // we first need to ensure that the repeatable in the current entity is\n // valid against itself.\n const hasRepeatableData = componentContext.repeatableData.length > 0;\n if (hasRepeatableData) {\n const { name: updatedName, value: updatedValue } = updatedAttribute;\n // Construct the full path to the unique field within the component.\n const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join('.');\n\n // Extract the values from the repeatable data using the constructed path\n const values = componentContext.repeatableData.map((item) => {\n return pathToCheck.split('.').reduce((acc, key) => acc[key], item as any);\n });\n\n // Check if the value is repeated in the current entity\n const isUpdatedAttributeRepeatedInThisEntity =\n values.filter((value) => value === updatedValue).length > 1;\n\n if (isUpdatedAttributeRepeatedInThisEntity) {\n return false;\n }\n }\n\n /**\n * When `componentContext` is present it means we are dealing with a unique\n * field within a component.\n *\n * The unique validation must consider the specific context of the\n * component, which will always be contained within a parent content type\n * and may also be nested within another component.\n *\n * We construct a query that takes into account the parent's model UID,\n * dimensions (such as draft and publish state/locale) and excludes the current\n * content type entity by its ID if provided.\n */\n const {\n model: parentModel,\n options: parentOptions,\n id: excludeId,\n } = componentContext.parentContent;\n\n const whereConditions: Record<string, any> = {};\n const isParentDraft = parentOptions && parentOptions.isDraft;\n\n whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };\n\n if (parentOptions?.locale) {\n whereConditions.locale = parentOptions.locale;\n }\n\n if (excludeId && !Number.isNaN(excludeId)) {\n whereConditions.id = { $ne: excludeId };\n }\n\n const queryUid = parentModel.uid;\n const queryWhere = {\n ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {\n [updatedAttribute.name]: value,\n }),\n\n ...whereConditions,\n };\n\n // The validation should pass if there is no other record found from the query\n return !(await strapi.db.query(queryUid).findOne({ where: queryWhere }));\n };\n\n const validateUniqueFieldWithinDynamicZoneComponent = async (\n startOfPath: string\n ): Promise<boolean> => {\n if (!componentContext) {\n return false;\n }\n\n const targetComponentUID = model.uid;\n // Ensure that the value is unique within the dynamic zone in this entity.\n const countOfValueInThisEntity = (componentContext?.fullDynamicZoneContent ?? []).reduce(\n (acc, component) => {\n if (component.__component !== targetComponentUID) {\n return acc;\n }\n\n const updatedValue = component[updatedAttribute.name];\n return updatedValue === updatedAttribute.value ? acc + 1 : acc;\n },\n 0\n );\n\n if (countOfValueInThisEntity > 1) {\n // If the value is repeated in the current entity, the validation fails.\n return false;\n }\n\n // Build a query for the parent content type to find all entities in the\n // same locale and publication state\n type QueryType = {\n select: string[];\n where: {\n published_at?: { $eq: null } | { $ne: null };\n id?: { $ne: number };\n locale?: string;\n };\n populate: {\n [key: string]: {\n on: {\n [key: string]: {\n select: string[];\n where: { [key: string]: string | number | boolean };\n };\n };\n };\n };\n };\n\n // Populate the dynamic zone for any components that share the same value\n // as the updated attribute.\n const query: QueryType = {\n select: ['id'],\n where: {},\n populate: {\n [startOfPath]: {\n on: {\n [targetComponentUID]: {\n select: ['id'],\n where: { [updatedAttribute.name]: updatedAttribute.value },\n },\n },\n },\n },\n };\n\n const { options, id } = componentContext.parentContent;\n\n if (options?.isDraft !== undefined) {\n query.where.published_at = options.isDraft ? { $eq: null } : { $ne: null };\n }\n\n if (id) {\n query.where.id = { $ne: id };\n }\n\n if (options?.locale) {\n query.where.locale = options.locale;\n }\n\n const parentModelQueryResult = await strapi.db\n .query(componentContext.parentContent.model.uid)\n .findMany(query);\n\n // Filter the results to only include results that have components in the\n // dynamic zone that match the target component type.\n const filteredResults = parentModelQueryResult\n .filter((result) => Array.isArray(result[startOfPath]) && result[startOfPath].length)\n .flatMap((result) => result[startOfPath])\n .filter((dynamicZoneComponent) => dynamicZoneComponent.__component === targetComponentUID);\n\n if (filteredResults.length >= 1) {\n return false;\n }\n\n return true;\n };\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n /**\n * If the attribute value is `null` or an empty string we want to skip the unique validation.\n * Otherwise it'll only accept a single entry with that value in the database.\n */\n if (_.isNil(value) || value === '') {\n return true;\n }\n\n /**\n * We don't validate any unique constraint for draft entries.\n */\n if (options.isDraft) {\n return true;\n }\n\n const hasPathToComponent = componentContext && componentContext.pathToComponent.length > 0;\n if (hasPathToComponent) {\n // Detect if we are validating within a dynamiczone by checking if the first\n // path is a dynamiczone attribute in the parent content type.\n const startOfPath = componentContext.pathToComponent[0];\n const testingDZ =\n componentContext.parentContent.model.attributes[startOfPath].type === 'dynamiczone';\n\n if (testingDZ) {\n return validateUniqueFieldWithinDynamicZoneComponent(startOfPath);\n }\n\n return validateUniqueFieldWithinComponent(value);\n }\n\n /**\n * Here we are validating a scalar unique field from the content type's schema.\n * We construct a query to check if the value is unique\n * considering dimensions (e.g. locale, publication state) and excluding the current entity by its ID if available.\n */\n const scalarAttributeWhere: Record<string, any> = {\n [updatedAttribute.name]: value,\n publishedAt: { $notNull: true },\n };\n\n if (options?.locale) {\n scalarAttributeWhere.locale = options.locale;\n }\n\n if (entity?.id) {\n scalarAttributeWhere.id = { $ne: entity.id };\n }\n\n // The validation should pass if there is no other record found from the query\n return !(await strapi.db\n .query(model.uid)\n .findOne({ where: scalarAttributeWhere, select: ['id'] }));\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas, options);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n\n if (options.isDraft) {\n return schema;\n }\n\n return schema.email().min(\n 1,\n // eslint-disable-next-line no-template-curly-in-string\n '${path} cannot be empty'\n );\n};\n\nexport const uidValidator = (\n metas: ValidatorMetas<Schema.Attribute.UID>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n\n if (options.isDraft) {\n return schema;\n }\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nexport const enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nexport const integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas, options);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n\n schema = addMinFloatValidator(schema, metas, options);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport const datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport const Validators = {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":["_","value","options","yup","blocksValidator"],"mappings":";;;;;;;AAyCA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,GASA,EAAE,cACC;AACH,SAAO,KAAK,aAAaA,WAAE,QAAA,UAAU,KAAK,SAAS,KAAK,CAAC,UACrD,UAAU,IAAI,KAAK,SAAS,IAC5B;AACN;AAMA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,MASG;AACI,SAAA,KAAK,aAAaA,mBAAE,UAAU,KAAK,SAAS,IAAI,UAAU,IAAI,KAAK,SAAS,IAAI;AACzF;AAMA,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,GAGA,EAAE,QAAQ,MACNA,WAAE,QAAA,SAAS,KAAK,GAAG,KAAK,CAAC,UAAU,UAAU,IAAIA,WAAAA,QAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKhF,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGIA,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/services/entity-validator/validators.ts"],"sourcesContent":["/**\n * Validators check if the entry data meets specific criteria before saving or publishing.\n * (e.g., length, range, format).\n *\n * Drafts have limited validations (mainly max constraints),\n * while published content undergoes full validation.\n *\n * The system also takes locales into account when validating data.\n * E.g, unique fields must be unique within the same locale.\n */\nimport _ from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Schema, Struct, Modules } from '@strapi/types';\nimport { blocksValidator } from './blocks-validator';\n\nimport type { ComponentContext } from '.';\n\nexport interface ValidatorMetas<\n TAttribute extends Schema.Attribute.AnyAttribute = Schema.Attribute.AnyAttribute,\n TValue extends Schema.Attribute.Value<TAttribute> = Schema.Attribute.Value<TAttribute>,\n> {\n attr: TAttribute;\n model: Struct.Schema;\n updatedAttribute: {\n name: string;\n value: TValue;\n };\n componentContext?: ComponentContext;\n entity?: Modules.EntityValidator.Entity;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n },\n { isDraft }: ValidatorOptions\n) => (_.isNumber(attr.min) && !isDraft ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n },\n { isDraft }: ValidatorOptions\n) => (_.isNumber(attr.min) && !isDraft ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex) && !isDraft\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\nconst addUniqueValidator = <T extends yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n componentContext,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n const validateUniqueFieldWithinComponent = async (value: any): Promise<boolean> => {\n if (!componentContext) {\n return false;\n }\n\n // If we are validating a unique field within a repeatable component,\n // we first need to ensure that the repeatable in the current entity is\n // valid against itself.\n const hasRepeatableData = componentContext.repeatableData.length > 0;\n if (hasRepeatableData) {\n const { name: updatedName, value: updatedValue } = updatedAttribute;\n // Construct the full path to the unique field within the component.\n const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join('.');\n\n // Extract the values from the repeatable data using the constructed path\n const values = componentContext.repeatableData.map((item) => {\n return pathToCheck.split('.').reduce((acc, key) => acc[key], item as any);\n });\n\n // Check if the value is repeated in the current entity\n const isUpdatedAttributeRepeatedInThisEntity =\n values.filter((value) => value === updatedValue).length > 1;\n\n if (isUpdatedAttributeRepeatedInThisEntity) {\n return false;\n }\n }\n\n /**\n * When `componentContext` is present it means we are dealing with a unique\n * field within a component.\n *\n * The unique validation must consider the specific context of the\n * component, which will always be contained within a parent content type\n * and may also be nested within another component.\n *\n * We construct a query that takes into account the parent's model UID,\n * dimensions (such as draft and publish state/locale) and excludes the current\n * content type entity by its ID if provided.\n */\n const {\n model: parentModel,\n options: parentOptions,\n id: excludeId,\n } = componentContext.parentContent;\n\n const whereConditions: Record<string, any> = {};\n const isParentDraft = parentOptions && parentOptions.isDraft;\n\n whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };\n\n if (parentOptions?.locale) {\n whereConditions.locale = parentOptions.locale;\n }\n\n if (excludeId && !Number.isNaN(excludeId)) {\n whereConditions.id = { $ne: excludeId };\n }\n\n const queryUid = parentModel.uid;\n const queryWhere = {\n ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {\n [updatedAttribute.name]: value,\n }),\n\n ...whereConditions,\n };\n\n // The validation should pass if there is no other record found from the query\n return !(await strapi.db.query(queryUid).findOne({ where: queryWhere }));\n };\n\n const validateUniqueFieldWithinDynamicZoneComponent = async (\n startOfPath: string\n ): Promise<boolean> => {\n if (!componentContext) {\n return false;\n }\n\n const targetComponentUID = model.uid;\n // Ensure that the value is unique within the dynamic zone in this entity.\n const countOfValueInThisEntity = (componentContext?.fullDynamicZoneContent ?? []).reduce(\n (acc, component) => {\n if (component.__component !== targetComponentUID) {\n return acc;\n }\n\n const updatedValue = component[updatedAttribute.name];\n return updatedValue === updatedAttribute.value ? acc + 1 : acc;\n },\n 0\n );\n\n if (countOfValueInThisEntity > 1) {\n // If the value is repeated in the current entity, the validation fails.\n return false;\n }\n\n // Build a query for the parent content type to find all entities in the\n // same locale and publication state\n type QueryType = {\n select: string[];\n where: {\n published_at?: { $eq: null } | { $ne: null };\n id?: { $ne: number };\n locale?: string;\n };\n populate: {\n [key: string]: {\n on: {\n [key: string]: {\n select: string[];\n where: { [key: string]: string | number | boolean };\n };\n };\n };\n };\n };\n\n // Populate the dynamic zone for any components that share the same value\n // as the updated attribute.\n const query: QueryType = {\n select: ['id'],\n where: {},\n populate: {\n [startOfPath]: {\n on: {\n [targetComponentUID]: {\n select: ['id'],\n where: { [updatedAttribute.name]: updatedAttribute.value },\n },\n },\n },\n },\n };\n\n const { options, id } = componentContext.parentContent;\n\n if (options?.isDraft !== undefined) {\n query.where.published_at = options.isDraft ? { $eq: null } : { $ne: null };\n }\n\n if (id) {\n query.where.id = { $ne: id };\n }\n\n if (options?.locale) {\n query.where.locale = options.locale;\n }\n\n const parentModelQueryResult = await strapi.db\n .query(componentContext.parentContent.model.uid)\n .findMany(query);\n\n // Filter the results to only include results that have components in the\n // dynamic zone that match the target component type.\n const filteredResults = parentModelQueryResult\n .filter((result) => Array.isArray(result[startOfPath]) && result[startOfPath].length)\n .flatMap((result) => result[startOfPath])\n .filter((dynamicZoneComponent) => dynamicZoneComponent.__component === targetComponentUID);\n\n if (filteredResults.length >= 1) {\n return false;\n }\n\n return true;\n };\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n /**\n * If the attribute value is `null` or an empty string we want to skip the unique validation.\n * Otherwise it'll only accept a single entry with that value in the database.\n */\n if (_.isNil(value) || value === '') {\n return true;\n }\n\n /**\n * We don't validate any unique constraint for draft entries.\n */\n if (options.isDraft) {\n return true;\n }\n\n const hasPathToComponent = componentContext && componentContext.pathToComponent.length > 0;\n if (hasPathToComponent) {\n // Detect if we are validating within a dynamiczone by checking if the first\n // path is a dynamiczone attribute in the parent content type.\n const startOfPath = componentContext.pathToComponent[0];\n const testingDZ =\n componentContext.parentContent.model.attributes[startOfPath].type === 'dynamiczone';\n\n if (testingDZ) {\n return validateUniqueFieldWithinDynamicZoneComponent(startOfPath);\n }\n\n return validateUniqueFieldWithinComponent(value);\n }\n\n /**\n * Here we are validating a scalar unique field from the content type's schema.\n * We construct a query to check if the value is unique\n * considering dimensions (e.g. locale, publication state) and excluding the current entity by its ID if available.\n */\n const scalarAttributeWhere: Record<string, any> = {\n [updatedAttribute.name]: value,\n publishedAt: { $notNull: true },\n };\n\n if (options?.locale) {\n scalarAttributeWhere.locale = options.locale;\n }\n\n if (entity?.id) {\n scalarAttributeWhere.id = { $ne: entity.id };\n }\n\n // The validation should pass if there is no other record found from the query\n return !(await strapi.db\n .query(model.uid)\n .findOne({ where: scalarAttributeWhere, select: ['id'] }));\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas, options);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n\n if (options.isDraft) {\n return schema;\n }\n\n return schema.email().min(\n 1,\n // eslint-disable-next-line no-template-curly-in-string\n '${path} cannot be empty'\n );\n};\n\nexport const uidValidator = (\n metas: ValidatorMetas<Schema.Attribute.UID>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n\n if (options.isDraft) {\n return schema;\n }\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nexport const enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nexport const integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas, options);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n\n schema = addMinFloatValidator(schema, metas, options);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport const datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport const Validators = {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":["_","value","options","yup","blocksValidator"],"mappings":";;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