@strapi/core 0.0.0-experimental.e60ec1829240dae21c1e1d29076681c322288813 → 0.0.0-experimental.edc24aaa3bb5a90fa5fd4fee208167dd4e2e38d4

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 (225) hide show
  1. package/LICENSE +18 -3
  2. package/dist/Strapi.d.ts +3 -1
  3. package/dist/Strapi.d.ts.map +1 -1
  4. package/dist/Strapi.js +59 -15
  5. package/dist/Strapi.js.map +1 -1
  6. package/dist/Strapi.mjs +38 -13
  7. package/dist/Strapi.mjs.map +1 -1
  8. package/dist/configuration/get-dirs.js +2 -2
  9. package/dist/configuration/get-dirs.js.map +1 -1
  10. package/dist/configuration/index.js +2 -2
  11. package/dist/configuration/index.js.map +1 -1
  12. package/dist/core-api/controller/collection-type.d.ts.map +1 -1
  13. package/dist/core-api/controller/collection-type.js +5 -3
  14. package/dist/core-api/controller/collection-type.js.map +1 -1
  15. package/dist/core-api/controller/collection-type.mjs +2 -0
  16. package/dist/core-api/controller/collection-type.mjs.map +1 -1
  17. package/dist/core-api/controller/index.js +2 -2
  18. package/dist/core-api/controller/index.js.map +1 -1
  19. package/dist/core-api/controller/single-type.d.ts.map +1 -1
  20. package/dist/core-api/controller/single-type.js +3 -2
  21. package/dist/core-api/controller/single-type.js.map +1 -1
  22. package/dist/core-api/controller/single-type.mjs +1 -0
  23. package/dist/core-api/controller/single-type.mjs.map +1 -1
  24. package/dist/core-api/controller/transform.js +8 -8
  25. package/dist/core-api/controller/transform.js.map +1 -1
  26. package/dist/core-api/service/collection-type.d.ts +1 -7
  27. package/dist/core-api/service/collection-type.d.ts.map +1 -1
  28. package/dist/core-api/service/collection-type.js +3 -2
  29. package/dist/core-api/service/collection-type.js.map +1 -1
  30. package/dist/core-api/service/collection-type.mjs +4 -3
  31. package/dist/core-api/service/collection-type.mjs.map +1 -1
  32. package/dist/core-api/service/pagination.d.ts +4 -11
  33. package/dist/core-api/service/pagination.d.ts.map +1 -1
  34. package/dist/core-api/service/pagination.js +18 -44
  35. package/dist/core-api/service/pagination.js.map +1 -1
  36. package/dist/core-api/service/pagination.mjs +16 -42
  37. package/dist/core-api/service/pagination.mjs.map +1 -1
  38. package/dist/domain/content-type/index.js +4 -4
  39. package/dist/domain/content-type/index.js.map +1 -1
  40. package/dist/ee/index.js +3 -3
  41. package/dist/ee/index.js.map +1 -1
  42. package/dist/factories.js +4 -4
  43. package/dist/factories.js.map +1 -1
  44. package/dist/index.d.ts +14 -0
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js.map +1 -1
  47. package/dist/index.mjs.map +1 -1
  48. package/dist/loaders/apis.js +2 -2
  49. package/dist/loaders/apis.js.map +1 -1
  50. package/dist/loaders/plugins/get-enabled-plugins.d.ts.map +1 -1
  51. package/dist/loaders/plugins/get-enabled-plugins.js +8 -8
  52. package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
  53. package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
  54. package/dist/loaders/plugins/get-user-plugins-config.js +2 -2
  55. package/dist/loaders/plugins/get-user-plugins-config.js.map +1 -1
  56. package/dist/loaders/plugins/index.js +6 -6
  57. package/dist/loaders/plugins/index.js.map +1 -1
  58. package/dist/middlewares/body.js +2 -2
  59. package/dist/middlewares/body.js.map +1 -1
  60. package/dist/middlewares/cors.d.ts.map +1 -1
  61. package/dist/middlewares/cors.js +9 -7
  62. package/dist/middlewares/cors.js.map +1 -1
  63. package/dist/middlewares/cors.mjs +9 -7
  64. package/dist/middlewares/cors.mjs.map +1 -1
  65. package/dist/middlewares/public.js +2 -2
  66. package/dist/middlewares/public.js.map +1 -1
  67. package/dist/middlewares/query.d.ts.map +1 -1
  68. package/dist/middlewares/query.js.map +1 -1
  69. package/dist/middlewares/query.mjs.map +1 -1
  70. package/dist/middlewares/responses.js +2 -2
  71. package/dist/middlewares/responses.js.map +1 -1
  72. package/dist/middlewares/security.d.ts.map +1 -1
  73. package/dist/middlewares/security.js +12 -5
  74. package/dist/middlewares/security.js.map +1 -1
  75. package/dist/middlewares/security.mjs +11 -4
  76. package/dist/middlewares/security.mjs.map +1 -1
  77. package/dist/middlewares/session.js +2 -2
  78. package/dist/middlewares/session.js.map +1 -1
  79. package/dist/migrations/database/5.0.0-discard-drafts.d.ts +19 -1
  80. package/dist/migrations/database/5.0.0-discard-drafts.d.ts.map +1 -1
  81. package/dist/migrations/database/5.0.0-discard-drafts.js +1 -0
  82. package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
  83. package/dist/migrations/database/5.0.0-discard-drafts.mjs +2 -1
  84. package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
  85. package/dist/migrations/draft-publish.d.ts.map +1 -1
  86. package/dist/migrations/draft-publish.js +14 -31
  87. package/dist/migrations/draft-publish.js.map +1 -1
  88. package/dist/migrations/draft-publish.mjs +15 -32
  89. package/dist/migrations/draft-publish.mjs.map +1 -1
  90. package/dist/registries/apis.js +2 -2
  91. package/dist/registries/apis.js.map +1 -1
  92. package/dist/registries/components.js +2 -2
  93. package/dist/registries/components.js.map +1 -1
  94. package/dist/registries/content-types.js +3 -3
  95. package/dist/registries/content-types.js.map +1 -1
  96. package/dist/registries/controllers.js +3 -3
  97. package/dist/registries/controllers.js.map +1 -1
  98. package/dist/registries/custom-fields.js +4 -4
  99. package/dist/registries/custom-fields.js.map +1 -1
  100. package/dist/registries/hooks.js +2 -2
  101. package/dist/registries/hooks.js.map +1 -1
  102. package/dist/registries/middlewares.js +3 -3
  103. package/dist/registries/middlewares.js.map +1 -1
  104. package/dist/registries/modules.js +3 -3
  105. package/dist/registries/modules.js.map +1 -1
  106. package/dist/registries/plugins.js +2 -2
  107. package/dist/registries/plugins.js.map +1 -1
  108. package/dist/registries/policies.js +4 -4
  109. package/dist/registries/policies.js.map +1 -1
  110. package/dist/registries/services.js +3 -3
  111. package/dist/registries/services.js.map +1 -1
  112. package/dist/services/auth/index.js +3 -3
  113. package/dist/services/auth/index.js.map +1 -1
  114. package/dist/services/core-store.js +3 -3
  115. package/dist/services/core-store.js.map +1 -1
  116. package/dist/services/cron.js +3 -3
  117. package/dist/services/cron.js.map +1 -1
  118. package/dist/services/document-service/attributes/index.js +2 -2
  119. package/dist/services/document-service/attributes/index.js.map +1 -1
  120. package/dist/services/document-service/attributes/transforms.js +3 -3
  121. package/dist/services/document-service/attributes/transforms.js.map +1 -1
  122. package/dist/services/document-service/components.js +15 -15
  123. package/dist/services/document-service/components.js.map +1 -1
  124. package/dist/services/document-service/draft-and-publish.js +16 -16
  125. package/dist/services/document-service/draft-and-publish.js.map +1 -1
  126. package/dist/services/document-service/entries.js +5 -5
  127. package/dist/services/document-service/entries.js.map +1 -1
  128. package/dist/services/document-service/internationalization.d.ts.map +1 -1
  129. package/dist/services/document-service/internationalization.js +21 -12
  130. package/dist/services/document-service/internationalization.js.map +1 -1
  131. package/dist/services/document-service/internationalization.mjs +14 -5
  132. package/dist/services/document-service/internationalization.mjs.map +1 -1
  133. package/dist/services/document-service/params.js +2 -2
  134. package/dist/services/document-service/params.js.map +1 -1
  135. package/dist/services/document-service/repository.js +10 -10
  136. package/dist/services/document-service/repository.js.map +1 -1
  137. package/dist/services/document-service/repository.mjs +2 -2
  138. package/dist/services/document-service/repository.mjs.map +1 -1
  139. package/dist/services/document-service/transform/id-transform.js +2 -2
  140. package/dist/services/document-service/transform/id-transform.js.map +1 -1
  141. package/dist/services/document-service/transform/query.js +3 -3
  142. package/dist/services/document-service/transform/query.js.map +1 -1
  143. package/dist/services/document-service/transform/relations/extract/data-ids.d.ts.map +1 -1
  144. package/dist/services/document-service/transform/relations/extract/data-ids.js +5 -2
  145. package/dist/services/document-service/transform/relations/extract/data-ids.js.map +1 -1
  146. package/dist/services/document-service/transform/relations/extract/data-ids.mjs +3 -0
  147. package/dist/services/document-service/transform/relations/extract/data-ids.mjs.map +1 -1
  148. package/dist/services/document-service/transform/relations/transform/data-ids.d.ts.map +1 -1
  149. package/dist/services/document-service/transform/relations/transform/data-ids.js +5 -2
  150. package/dist/services/document-service/transform/relations/transform/data-ids.js.map +1 -1
  151. package/dist/services/document-service/transform/relations/transform/data-ids.mjs +3 -0
  152. package/dist/services/document-service/transform/relations/transform/data-ids.mjs.map +1 -1
  153. package/dist/services/document-service/transform/relations/utils/dp.js +2 -2
  154. package/dist/services/document-service/transform/relations/utils/dp.js.map +1 -1
  155. package/dist/services/document-service/transform/relations/utils/map-relation.d.ts.map +1 -1
  156. package/dist/services/document-service/transform/relations/utils/map-relation.js +13 -9
  157. package/dist/services/document-service/transform/relations/utils/map-relation.js.map +1 -1
  158. package/dist/services/document-service/transform/relations/utils/map-relation.mjs +7 -3
  159. package/dist/services/document-service/transform/relations/utils/map-relation.mjs.map +1 -1
  160. package/dist/services/document-service/utils/populate.d.ts.map +1 -1
  161. package/dist/services/document-service/utils/populate.js +4 -0
  162. package/dist/services/document-service/utils/populate.js.map +1 -1
  163. package/dist/services/document-service/utils/populate.mjs +4 -0
  164. package/dist/services/document-service/utils/populate.mjs.map +1 -1
  165. package/dist/services/entity-validator/index.d.ts +14 -1
  166. package/dist/services/entity-validator/index.d.ts.map +1 -1
  167. package/dist/services/entity-validator/index.js +106 -49
  168. package/dist/services/entity-validator/index.js.map +1 -1
  169. package/dist/services/entity-validator/index.mjs +87 -30
  170. package/dist/services/entity-validator/index.mjs.map +1 -1
  171. package/dist/services/entity-validator/validators.d.ts +10 -8
  172. package/dist/services/entity-validator/validators.d.ts.map +1 -1
  173. package/dist/services/entity-validator/validators.js +61 -19
  174. package/dist/services/entity-validator/validators.js.map +1 -1
  175. package/dist/services/entity-validator/validators.mjs +54 -11
  176. package/dist/services/entity-validator/validators.mjs.map +1 -1
  177. package/dist/services/server/compose-endpoint.js +7 -7
  178. package/dist/services/server/compose-endpoint.js.map +1 -1
  179. package/dist/services/server/index.js +1 -1
  180. package/dist/services/server/index.js.map +1 -1
  181. package/dist/services/server/index.mjs +1 -1
  182. package/dist/services/server/index.mjs.map +1 -1
  183. package/dist/services/server/koa.js +3 -3
  184. package/dist/services/server/koa.js.map +1 -1
  185. package/dist/services/server/middleware.js +3 -3
  186. package/dist/services/server/middleware.js.map +1 -1
  187. package/dist/services/server/routing.js +2 -2
  188. package/dist/services/server/routing.js.map +1 -1
  189. package/dist/services/utils/dynamic-zones.js +5 -5
  190. package/dist/services/utils/dynamic-zones.js.map +1 -1
  191. package/dist/services/webhook-runner.d.ts +2 -1
  192. package/dist/services/webhook-runner.d.ts.map +1 -1
  193. package/dist/services/webhook-runner.js.map +1 -1
  194. package/dist/services/webhook-runner.mjs.map +1 -1
  195. package/dist/services/webhook-store.d.ts +2 -8
  196. package/dist/services/webhook-store.d.ts.map +1 -1
  197. package/dist/services/webhook-store.js +1 -1
  198. package/dist/services/webhook-store.js.map +1 -1
  199. package/dist/services/webhook-store.mjs +1 -1
  200. package/dist/services/webhook-store.mjs.map +1 -1
  201. package/dist/utils/cron.js +3 -3
  202. package/dist/utils/cron.js.map +1 -1
  203. package/dist/utils/fetch.d.ts.map +1 -1
  204. package/dist/utils/fetch.js +4 -3
  205. package/dist/utils/fetch.js.map +1 -1
  206. package/dist/utils/fetch.mjs +4 -3
  207. package/dist/utils/fetch.mjs.map +1 -1
  208. package/dist/utils/filepath-to-prop-path.d.ts +1 -1
  209. package/dist/utils/filepath-to-prop-path.d.ts.map +1 -1
  210. package/dist/utils/filepath-to-prop-path.js +27 -6
  211. package/dist/utils/filepath-to-prop-path.js.map +1 -1
  212. package/dist/utils/filepath-to-prop-path.mjs +25 -5
  213. package/dist/utils/filepath-to-prop-path.mjs.map +1 -1
  214. package/dist/utils/is-initialized.js +3 -3
  215. package/dist/utils/is-initialized.js.map +1 -1
  216. package/dist/utils/startup-logger.js +4 -4
  217. package/dist/utils/startup-logger.js.map +1 -1
  218. package/dist/utils/startup-logger.mjs +3 -3
  219. package/dist/utils/startup-logger.mjs.map +1 -1
  220. package/dist/utils/transform-content-types-to-models.d.ts.map +1 -1
  221. package/dist/utils/transform-content-types-to-models.js +16 -4
  222. package/dist/utils/transform-content-types-to-models.js.map +1 -1
  223. package/dist/utils/transform-content-types-to-models.mjs +15 -3
  224. package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
  225. package/package.json +16 -14
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
- const _$1 = require("lodash");
3
- const _ = require("lodash/fp");
2
+ const _ = require("lodash");
3
+ const fp = require("lodash/fp");
4
4
  const strapiUtils = require("@strapi/utils");
5
5
  const validators = require("./validators.js");
6
6
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
@@ -55,7 +55,11 @@ const addDefault = (createOrUpdate) => {
55
55
  };
56
56
  };
57
57
  const preventCast = (validator) => validator.transform((val, originalVal) => originalVal);
58
- const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isDraft }) => {
58
+ const createComponentValidator = (createOrUpdate) => ({
59
+ attr,
60
+ updatedAttribute,
61
+ componentContext
62
+ }, { isDraft }) => {
59
63
  const model = strapi.getModel(attr.component);
60
64
  if (!model) {
61
65
  throw new Error("Validation failed: Model not found");
@@ -63,7 +67,10 @@ const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }
63
67
  if (attr?.repeatable) {
64
68
  let validator2 = yup.array().of(
65
69
  yup.lazy(
66
- (item) => createModelValidator(createOrUpdate)({ model, data: item }, { isDraft }).notNull()
70
+ (item) => createModelValidator(createOrUpdate)(
71
+ { componentContext, model, data: item },
72
+ { isDraft }
73
+ ).notNull()
67
74
  )
68
75
  );
69
76
  validator2 = addRequiredValidation(createOrUpdate)(validator2, {
@@ -74,7 +81,11 @@ const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }
74
81
  return validator2;
75
82
  }
76
83
  let validator = createModelValidator(createOrUpdate)(
77
- { model, data: updatedAttribute.value },
84
+ {
85
+ model,
86
+ data: updatedAttribute.value,
87
+ componentContext
88
+ },
78
89
  { isDraft }
79
90
  );
80
91
  validator = addRequiredValidation(createOrUpdate)(validator, {
@@ -83,15 +94,20 @@ const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }
83
94
  });
84
95
  return validator;
85
96
  };
86
- const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isDraft }) => {
97
+ const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute, componentContext }, { isDraft }) => {
87
98
  let validator;
88
99
  validator = yup.array().of(
89
100
  yup.lazy((item) => {
90
- const model = strapi.getModel(_.prop("__component", item));
101
+ const model = strapi.getModel(fp.prop("__component", item));
91
102
  const schema = yup.object().shape({
92
103
  __component: yup.string().required().oneOf(Object.keys(strapi.components))
93
104
  }).notNull();
94
- return model ? schema.concat(createModelValidator(createOrUpdate)({ model, data: item }, { isDraft })) : schema;
105
+ return model ? schema.concat(
106
+ createModelValidator(createOrUpdate)(
107
+ { model, data: item, componentContext },
108
+ { isDraft }
109
+ )
110
+ ) : schema;
95
111
  })
96
112
  // FIXME: yup v1
97
113
  );
@@ -102,22 +118,20 @@ const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isD
102
118
  validator = addMinMax(validator, { attr, updatedAttribute });
103
119
  return validator;
104
120
  };
105
- const createRelationValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isDraft }) => {
121
+ const createRelationValidator = ({
122
+ updatedAttribute
123
+ }) => {
106
124
  let validator;
107
125
  if (Array.isArray(updatedAttribute.value)) {
108
126
  validator = yup.array().of(yup.mixed());
109
127
  } else {
110
128
  validator = yup.mixed();
111
129
  }
112
- validator = addRequiredValidation(createOrUpdate)(validator, {
113
- attr: { required: !isDraft && attr.required },
114
- updatedAttribute
115
- });
116
130
  return validator;
117
131
  };
118
132
  const createScalarAttributeValidator = (createOrUpdate) => (metas, options) => {
119
133
  let validator;
120
- if (_.has(metas.attr.type, validators)) {
134
+ if (fp.has(metas.attr.type, validators)) {
121
135
  validator = validators[metas.attr.type](metas, options);
122
136
  } else {
123
137
  validator = yup.mixed();
@@ -136,35 +150,58 @@ const createAttributeValidator = (createOrUpdate) => (metas, options) => {
136
150
  validator = createScalarAttributeValidator(createOrUpdate)(metas, options);
137
151
  } else {
138
152
  if (metas.attr.type === "component") {
153
+ const pathToComponent = [
154
+ ...metas?.componentContext?.pathToComponent ?? [],
155
+ metas.updatedAttribute.name
156
+ ];
157
+ const repeatableData = metas.attr.repeatable && pathToComponent.length === 1 ? metas.updatedAttribute.value : metas.componentContext?.repeatableData;
158
+ const newComponentContext = {
159
+ ...metas?.componentContext ?? {},
160
+ pathToComponent,
161
+ repeatableData
162
+ };
139
163
  validator = createComponentValidator(createOrUpdate)(
140
- { attr: metas.attr, updatedAttribute: metas.updatedAttribute },
141
- options
142
- );
143
- } else if (metas.attr.type === "dynamiczone") {
144
- validator = createDzValidator(createOrUpdate)(metas, options);
145
- } else if (metas.attr.type === "relation") {
146
- validator = createRelationValidator(createOrUpdate)(
147
164
  {
165
+ componentContext: newComponentContext,
148
166
  attr: metas.attr,
149
167
  updatedAttribute: metas.updatedAttribute
150
168
  },
151
169
  options
152
170
  );
171
+ } else if (metas.attr.type === "dynamiczone") {
172
+ const pathToComponent = [
173
+ ...metas?.componentContext?.pathToComponent ?? [],
174
+ metas.updatedAttribute.name
175
+ ];
176
+ const newComponentContext = {
177
+ ...metas?.componentContext ?? {},
178
+ pathToComponent
179
+ };
180
+ validator = createDzValidator(createOrUpdate)(
181
+ { ...metas, componentContext: newComponentContext },
182
+ options
183
+ );
184
+ } else if (metas.attr.type === "relation") {
185
+ validator = createRelationValidator({
186
+ attr: metas.attr,
187
+ updatedAttribute: metas.updatedAttribute
188
+ });
153
189
  }
154
190
  validator = preventCast(validator);
155
191
  }
156
192
  validator = addDefault(createOrUpdate)(validator, metas);
157
193
  return validator;
158
194
  };
159
- const createModelValidator = (createOrUpdate) => ({ model, data, entity }, options) => {
195
+ const createModelValidator = (createOrUpdate) => ({ componentContext, model, data, entity }, options) => {
160
196
  const writableAttributes = model ? getWritableAttributes(model) : [];
161
197
  const schema = writableAttributes.reduce(
162
198
  (validators2, attributeName) => {
163
199
  const metas = {
164
200
  attr: model.attributes[attributeName],
165
- updatedAttribute: { name: attributeName, value: _.prop(attributeName, data) },
201
+ updatedAttribute: { name: attributeName, value: fp.prop(attributeName, data) },
166
202
  model,
167
- entity
203
+ entity,
204
+ componentContext
168
205
  };
169
206
  const validator = createAttributeValidator(createOrUpdate)(metas, options);
170
207
  validators2[attributeName] = validator;
@@ -176,29 +213,49 @@ const createModelValidator = (createOrUpdate) => ({ model, data, entity }, optio
176
213
  };
177
214
  const createValidateEntity = (createOrUpdate) => {
178
215
  return async (model, data, options, entity) => {
179
- if (!_.isObject(data)) {
216
+ if (!fp.isObject(data)) {
180
217
  const { displayName } = model.info;
181
218
  throw new ValidationError(
182
219
  `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`
183
220
  );
184
221
  }
185
222
  const validator = createModelValidator(createOrUpdate)(
186
- { model, data, entity },
223
+ {
224
+ model,
225
+ data,
226
+ entity,
227
+ componentContext: {
228
+ // Set up the initial component context.
229
+ // Keeping track of parent content type context in which a component will be used.
230
+ // This is necessary to validate component field constraints such as uniqueness.
231
+ parentContent: {
232
+ id: entity?.id,
233
+ model,
234
+ options
235
+ },
236
+ pathToComponent: [],
237
+ repeatableData: []
238
+ }
239
+ },
187
240
  {
188
241
  isDraft: options?.isDraft ?? false,
189
242
  locale: options?.locale ?? null
190
243
  }
191
- ).test("relations-test", "check that all relations exist", async function(data2) {
192
- try {
193
- await checkRelationsExist(buildRelationsStore({ uid: model.uid, data: data2 }));
194
- } catch (e) {
195
- return this.createError({
196
- path: this.path,
197
- message: e instanceof ValidationError && e.message || "Invalid relations"
198
- });
244
+ ).test(
245
+ "relations-test",
246
+ "check that all relations exist",
247
+ async function relationsValidation(data2) {
248
+ try {
249
+ await checkRelationsExist(buildRelationsStore({ uid: model.uid, data: data2 }));
250
+ } catch (e) {
251
+ return this.createError({
252
+ path: this.path,
253
+ message: e instanceof ValidationError && e.message || "Invalid relations"
254
+ });
255
+ }
256
+ return true;
199
257
  }
200
- return true;
201
- }).required();
258
+ ).required();
202
259
  return validateYupSchema(validator, {
203
260
  strict: false,
204
261
  abortEarly: false
@@ -212,7 +269,7 @@ const buildRelationsStore = ({
212
269
  if (!uid) {
213
270
  throw new ValidationError(`Cannot build relations store: "uid" is undefined`);
214
271
  }
215
- if (_.isEmpty(data)) {
272
+ if (fp.isEmpty(data)) {
216
273
  return {};
217
274
  }
218
275
  const currentModel = strapi.getModel(uid);
@@ -220,7 +277,7 @@ const buildRelationsStore = ({
220
277
  (result, attributeName) => {
221
278
  const attribute = currentModel.attributes[attributeName];
222
279
  const value = data[attributeName];
223
- if (_$1.isNil(value)) {
280
+ if (_.isNil(value)) {
224
281
  return result;
225
282
  }
226
283
  switch (attribute.type) {
@@ -236,16 +293,16 @@ const buildRelationsStore = ({
236
293
  let source;
237
294
  if (Array.isArray(value)) {
238
295
  source = value;
239
- } else if (_.isObject(value)) {
240
- if ("connect" in value && !_$1.isNil(value.connect)) {
296
+ } else if (fp.isObject(value)) {
297
+ if ("connect" in value && !_.isNil(value.connect)) {
241
298
  source = value.connect;
242
- } else if ("set" in value && !_$1.isNil(value.set)) {
299
+ } else if ("set" in value && !_.isNil(value.set)) {
243
300
  source = value.set;
244
301
  } else {
245
302
  source = [];
246
303
  }
247
304
  } else {
248
- source = _$1.castArray(value);
305
+ source = _.castArray(value);
249
306
  }
250
307
  const idArray = source.map((v) => ({
251
308
  id: typeof v === "object" ? v.id : v
@@ -255,20 +312,20 @@ const buildRelationsStore = ({
255
312
  break;
256
313
  }
257
314
  case "component": {
258
- return _$1.castArray(value).reduce((relationsStore, componentValue) => {
315
+ return _.castArray(value).reduce((relationsStore, componentValue) => {
259
316
  if (!attribute.component) {
260
317
  throw new ValidationError(
261
318
  `Cannot build relations store from component, component identifier is undefined`
262
319
  );
263
320
  }
264
- return _$1.mergeWith(
321
+ return _.mergeWith(
265
322
  relationsStore,
266
323
  buildRelationsStore({
267
324
  uid: attribute.component,
268
325
  data: componentValue
269
326
  }),
270
327
  (objValue, srcValue) => {
271
- if (_$1.isArray(objValue)) {
328
+ if (_.isArray(objValue)) {
272
329
  return objValue.concat(srcValue);
273
330
  }
274
331
  }
@@ -276,21 +333,21 @@ const buildRelationsStore = ({
276
333
  }, result);
277
334
  }
278
335
  case "dynamiczone": {
279
- return _$1.castArray(value).reduce((relationsStore, dzValue) => {
336
+ return _.castArray(value).reduce((relationsStore, dzValue) => {
280
337
  const value2 = dzValue;
281
338
  if (!value2.__component) {
282
339
  throw new ValidationError(
283
340
  `Cannot build relations store from dynamiczone, component identifier is undefined`
284
341
  );
285
342
  }
286
- return _$1.mergeWith(
343
+ return _.mergeWith(
287
344
  relationsStore,
288
345
  buildRelationsStore({
289
346
  uid: value2.__component,
290
347
  data: value2
291
348
  }),
292
349
  (objValue, srcValue) => {
293
- if (_$1.isArray(objValue)) {
350
+ if (_.isArray(objValue)) {
294
351
  return objValue.concat(srcValue);
295
352
  }
296
353
  }
@@ -307,7 +364,7 @@ const checkRelationsExist = async (relationsStore = {}) => {
307
364
  const promises = [];
308
365
  for (const [key, value] of Object.entries(relationsStore)) {
309
366
  const evaluate = async () => {
310
- const uniqueValues = _$1.uniqBy(value, `id`);
367
+ const uniqueValues = _.uniqBy(value, `id`);
311
368
  const count = await strapi.db.query(key).count({
312
369
  where: {
313
370
  id: {
@@ -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 from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype Entity = {\n id: ID;\n [key: string]: unknown;\n} | null;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface AttributeValidatorMetas {\n attr: Schema.Attribute.AnyAttribute;\n updatedAttribute: { name: string; value: unknown };\n model: Struct.Schema;\n entity?: Entity;\n}\n\ninterface ModelValidatorMetas {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: 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 { attr, updatedAttribute }: 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)({ model, data: item }, { isDraft }).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n validator = addMinMax(validator, { attr, updatedAttribute });\n\n return validator;\n }\n\n // FIXME: v4 was broken\n let validator = createModelValidator(createOrUpdate)(\n { model, data: updatedAttribute.value },\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 }: 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(createModelValidator(createOrUpdate)({ model, data: item }, { isDraft }))\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n validator = addMinMax(validator, { attr, updatedAttribute });\n\n return validator;\n };\n\nconst createRelationValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Relation>,\n { isDraft }: ValidatorContext\n ) => {\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 validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\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) =>\n (metas: AttributeValidatorMetas, 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') {\n validator = createComponentValidator(createOrUpdate)(\n { attr: metas.attr, updatedAttribute: metas.updatedAttribute },\n options\n );\n } else if (metas.attr.type === 'dynamiczone') {\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator(createOrUpdate)(\n {\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\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 ({ 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 };\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?: 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 { model, data, entity },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test('relations-test', 'check that all relations exist', async function (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 .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","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;AAkCxC,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,MAAA,UAAU,KAAK,GAAG,GAAG;AACP,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACO,SAAA;AACT;AAEA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ACT;AAAA,IACA,CAAC;AAAA,EAAA;AAEL;AAMA,MAAM,sBAAsB,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,IAAO,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 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};\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 AttributeValidatorMetas extends WithComponentContext {\n attr: Schema.Attribute.AnyAttribute;\n updatedAttribute: { name: string; value: unknown };\n model: Struct.Schema;\n entity?: Modules.EntityValidator.Entity;\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 validator = addMinMax(validator, { attr, updatedAttribute });\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 validator = addMinMax(validator, { attr, updatedAttribute });\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) =>\n (metas: AttributeValidatorMetas, 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') {\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 = {\n ...(metas?.componentContext ?? {}),\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext as ComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone') {\n // TODO: fix! query layer fails when building a where for dynamic\n // zones\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n const newComponentContext = {\n ...(metas?.componentContext ?? {}),\n pathToComponent,\n };\n\n validator = createDzValidator(createOrUpdate)(\n { ...metas, componentContext: newComponentContext as ComponentContext },\n options\n );\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","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;AAkDxC,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,MAAA,UAAU,KAAK,GAAG,GAAG;AACP,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACO,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;MAAO,WAC5B,mBAAmB,UAAU;AACtC,wBAAgB,cAAc;MAChC;AAAA,IAAA,OACK;AACL,sBAAgB,cAAc;IAChC;A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ault = (createOrUpdate) => {
52
52
  };
53
53
  };
54
54
  const preventCast = (validator) => validator.transform((val, originalVal) => originalVal);
55
- const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isDraft }) => {
55
+ const createComponentValidator = (createOrUpdate) => ({
56
+ attr,
57
+ updatedAttribute,
58
+ componentContext
59
+ }, { isDraft }) => {
56
60
  const model = strapi.getModel(attr.component);
57
61
  if (!model) {
58
62
  throw new Error("Validation failed: Model not found");
@@ -60,7 +64,10 @@ const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }
60
64
  if (attr?.repeatable) {
61
65
  let validator2 = yup.array().of(
62
66
  yup.lazy(
63
- (item) => createModelValidator(createOrUpdate)({ model, data: item }, { isDraft }).notNull()
67
+ (item) => createModelValidator(createOrUpdate)(
68
+ { componentContext, model, data: item },
69
+ { isDraft }
70
+ ).notNull()
64
71
  )
65
72
  );
66
73
  validator2 = addRequiredValidation(createOrUpdate)(validator2, {
@@ -71,7 +78,11 @@ const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }
71
78
  return validator2;
72
79
  }
73
80
  let validator = createModelValidator(createOrUpdate)(
74
- { model, data: updatedAttribute.value },
81
+ {
82
+ model,
83
+ data: updatedAttribute.value,
84
+ componentContext
85
+ },
75
86
  { isDraft }
76
87
  );
77
88
  validator = addRequiredValidation(createOrUpdate)(validator, {
@@ -80,7 +91,7 @@ const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }
80
91
  });
81
92
  return validator;
82
93
  };
83
- const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isDraft }) => {
94
+ const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute, componentContext }, { isDraft }) => {
84
95
  let validator;
85
96
  validator = yup.array().of(
86
97
  yup.lazy((item) => {
@@ -88,7 +99,12 @@ const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isD
88
99
  const schema = yup.object().shape({
89
100
  __component: yup.string().required().oneOf(Object.keys(strapi.components))
90
101
  }).notNull();
91
- return model ? schema.concat(createModelValidator(createOrUpdate)({ model, data: item }, { isDraft })) : schema;
102
+ return model ? schema.concat(
103
+ createModelValidator(createOrUpdate)(
104
+ { model, data: item, componentContext },
105
+ { isDraft }
106
+ )
107
+ ) : schema;
92
108
  })
93
109
  // FIXME: yup v1
94
110
  );
@@ -99,17 +115,15 @@ const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isD
99
115
  validator = addMinMax(validator, { attr, updatedAttribute });
100
116
  return validator;
101
117
  };
102
- const createRelationValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isDraft }) => {
118
+ const createRelationValidator = ({
119
+ updatedAttribute
120
+ }) => {
103
121
  let validator;
104
122
  if (Array.isArray(updatedAttribute.value)) {
105
123
  validator = yup.array().of(yup.mixed());
106
124
  } else {
107
125
  validator = yup.mixed();
108
126
  }
109
- validator = addRequiredValidation(createOrUpdate)(validator, {
110
- attr: { required: !isDraft && attr.required },
111
- updatedAttribute
112
- });
113
127
  return validator;
114
128
  };
115
129
  const createScalarAttributeValidator = (createOrUpdate) => (metas, options) => {
@@ -133,27 +147,49 @@ const createAttributeValidator = (createOrUpdate) => (metas, options) => {
133
147
  validator = createScalarAttributeValidator(createOrUpdate)(metas, options);
134
148
  } else {
135
149
  if (metas.attr.type === "component") {
150
+ const pathToComponent = [
151
+ ...metas?.componentContext?.pathToComponent ?? [],
152
+ metas.updatedAttribute.name
153
+ ];
154
+ const repeatableData = metas.attr.repeatable && pathToComponent.length === 1 ? metas.updatedAttribute.value : metas.componentContext?.repeatableData;
155
+ const newComponentContext = {
156
+ ...metas?.componentContext ?? {},
157
+ pathToComponent,
158
+ repeatableData
159
+ };
136
160
  validator = createComponentValidator(createOrUpdate)(
137
- { attr: metas.attr, updatedAttribute: metas.updatedAttribute },
138
- options
139
- );
140
- } else if (metas.attr.type === "dynamiczone") {
141
- validator = createDzValidator(createOrUpdate)(metas, options);
142
- } else if (metas.attr.type === "relation") {
143
- validator = createRelationValidator(createOrUpdate)(
144
161
  {
162
+ componentContext: newComponentContext,
145
163
  attr: metas.attr,
146
164
  updatedAttribute: metas.updatedAttribute
147
165
  },
148
166
  options
149
167
  );
168
+ } else if (metas.attr.type === "dynamiczone") {
169
+ const pathToComponent = [
170
+ ...metas?.componentContext?.pathToComponent ?? [],
171
+ metas.updatedAttribute.name
172
+ ];
173
+ const newComponentContext = {
174
+ ...metas?.componentContext ?? {},
175
+ pathToComponent
176
+ };
177
+ validator = createDzValidator(createOrUpdate)(
178
+ { ...metas, componentContext: newComponentContext },
179
+ options
180
+ );
181
+ } else if (metas.attr.type === "relation") {
182
+ validator = createRelationValidator({
183
+ attr: metas.attr,
184
+ updatedAttribute: metas.updatedAttribute
185
+ });
150
186
  }
151
187
  validator = preventCast(validator);
152
188
  }
153
189
  validator = addDefault(createOrUpdate)(validator, metas);
154
190
  return validator;
155
191
  };
156
- const createModelValidator = (createOrUpdate) => ({ model, data, entity }, options) => {
192
+ const createModelValidator = (createOrUpdate) => ({ componentContext, model, data, entity }, options) => {
157
193
  const writableAttributes = model ? getWritableAttributes(model) : [];
158
194
  const schema = writableAttributes.reduce(
159
195
  (validators2, attributeName) => {
@@ -161,7 +197,8 @@ const createModelValidator = (createOrUpdate) => ({ model, data, entity }, optio
161
197
  attr: model.attributes[attributeName],
162
198
  updatedAttribute: { name: attributeName, value: prop(attributeName, data) },
163
199
  model,
164
- entity
200
+ entity,
201
+ componentContext
165
202
  };
166
203
  const validator = createAttributeValidator(createOrUpdate)(metas, options);
167
204
  validators2[attributeName] = validator;
@@ -180,22 +217,42 @@ const createValidateEntity = (createOrUpdate) => {
180
217
  );
181
218
  }
182
219
  const validator = createModelValidator(createOrUpdate)(
183
- { model, data, entity },
220
+ {
221
+ model,
222
+ data,
223
+ entity,
224
+ componentContext: {
225
+ // Set up the initial component context.
226
+ // Keeping track of parent content type context in which a component will be used.
227
+ // This is necessary to validate component field constraints such as uniqueness.
228
+ parentContent: {
229
+ id: entity?.id,
230
+ model,
231
+ options
232
+ },
233
+ pathToComponent: [],
234
+ repeatableData: []
235
+ }
236
+ },
184
237
  {
185
238
  isDraft: options?.isDraft ?? false,
186
239
  locale: options?.locale ?? null
187
240
  }
188
- ).test("relations-test", "check that all relations exist", async function(data2) {
189
- try {
190
- await checkRelationsExist(buildRelationsStore({ uid: model.uid, data: data2 }));
191
- } catch (e) {
192
- return this.createError({
193
- path: this.path,
194
- message: e instanceof ValidationError && e.message || "Invalid relations"
195
- });
241
+ ).test(
242
+ "relations-test",
243
+ "check that all relations exist",
244
+ async function relationsValidation(data2) {
245
+ try {
246
+ await checkRelationsExist(buildRelationsStore({ uid: model.uid, data: data2 }));
247
+ } catch (e) {
248
+ return this.createError({
249
+ path: this.path,
250
+ message: e instanceof ValidationError && e.message || "Invalid relations"
251
+ });
252
+ }
253
+ return true;
196
254
  }
197
- return true;
198
- }).required();
255
+ ).required();
199
256
  return validateYupSchema(validator, {
200
257
  strict: false,
201
258
  abortEarly: false