@strapi/core 5.59.0 → 5.61.0

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 (97) hide show
  1. package/dist/core-api/routes/index.js +10 -45
  2. package/dist/core-api/routes/index.js.map +1 -1
  3. package/dist/core-api/routes/index.mjs +10 -25
  4. package/dist/core-api/routes/index.mjs.map +1 -1
  5. package/dist/core-api/routes/response.d.ts +28 -0
  6. package/dist/core-api/routes/response.d.ts.map +1 -0
  7. package/dist/core-api/routes/response.js +63 -0
  8. package/dist/core-api/routes/response.js.map +1 -0
  9. package/dist/core-api/routes/response.mjs +40 -0
  10. package/dist/core-api/routes/response.mjs.map +1 -0
  11. package/dist/package.json.js +17 -21
  12. package/dist/package.json.js.map +1 -1
  13. package/dist/package.json.mjs +17 -21
  14. package/dist/package.json.mjs.map +1 -1
  15. package/dist/providers/admin.d.ts.map +1 -1
  16. package/dist/providers/admin.js +8 -0
  17. package/dist/providers/admin.js.map +1 -1
  18. package/dist/providers/admin.mjs +8 -0
  19. package/dist/providers/admin.mjs.map +1 -1
  20. package/dist/providers/webhooks.d.ts.map +1 -1
  21. package/dist/providers/webhooks.js +1 -0
  22. package/dist/providers/webhooks.js.map +1 -1
  23. package/dist/providers/webhooks.mjs +1 -0
  24. package/dist/providers/webhooks.mjs.map +1 -1
  25. package/dist/services/config.js +1 -1
  26. package/dist/services/config.js.map +1 -1
  27. package/dist/services/config.mjs +2 -2
  28. package/dist/services/config.mjs.map +1 -1
  29. package/dist/services/document-service/components.d.ts +14 -1
  30. package/dist/services/document-service/components.d.ts.map +1 -1
  31. package/dist/services/document-service/components.js +413 -18
  32. package/dist/services/document-service/components.js.map +1 -1
  33. package/dist/services/document-service/components.mjs +414 -20
  34. package/dist/services/document-service/components.mjs.map +1 -1
  35. package/dist/services/document-service/events.d.ts.map +1 -1
  36. package/dist/services/document-service/events.js +8 -2
  37. package/dist/services/document-service/events.js.map +1 -1
  38. package/dist/services/document-service/events.mjs +8 -2
  39. package/dist/services/document-service/events.mjs.map +1 -1
  40. package/dist/services/document-service/middlewares/middleware-manager.d.ts +1 -1
  41. package/dist/services/document-service/middlewares/middleware-manager.d.ts.map +1 -1
  42. package/dist/services/document-service/middlewares/middleware-manager.js +6 -1
  43. package/dist/services/document-service/middlewares/middleware-manager.js.map +1 -1
  44. package/dist/services/document-service/middlewares/middleware-manager.mjs +6 -1
  45. package/dist/services/document-service/middlewares/middleware-manager.mjs.map +1 -1
  46. package/dist/services/entity-validator/index.d.ts.map +1 -1
  47. package/dist/services/entity-validator/index.js +41 -6
  48. package/dist/services/entity-validator/index.js.map +1 -1
  49. package/dist/services/entity-validator/index.mjs +42 -7
  50. package/dist/services/entity-validator/index.mjs.map +1 -1
  51. package/dist/services/event-hub.d.ts +1 -0
  52. package/dist/services/event-hub.d.ts.map +1 -1
  53. package/dist/services/event-hub.js +7 -0
  54. package/dist/services/event-hub.js.map +1 -1
  55. package/dist/services/event-hub.mjs +7 -0
  56. package/dist/services/event-hub.mjs.map +1 -1
  57. package/dist/services/mcp/handlers/handlePost.d.ts.map +1 -1
  58. package/dist/services/mcp/handlers/handlePost.js +5 -2
  59. package/dist/services/mcp/handlers/handlePost.js.map +1 -1
  60. package/dist/services/mcp/handlers/handlePost.mjs +5 -2
  61. package/dist/services/mcp/handlers/handlePost.mjs.map +1 -1
  62. package/dist/services/mcp/internal/McpConfiguration.d.ts +2 -0
  63. package/dist/services/mcp/internal/McpConfiguration.d.ts.map +1 -1
  64. package/dist/services/mcp/internal/McpConfiguration.js +17 -0
  65. package/dist/services/mcp/internal/McpConfiguration.js.map +1 -1
  66. package/dist/services/mcp/internal/McpConfiguration.mjs +17 -1
  67. package/dist/services/mcp/internal/McpConfiguration.mjs.map +1 -1
  68. package/dist/services/mcp/internal/McpServerFactory.d.ts +6 -1
  69. package/dist/services/mcp/internal/McpServerFactory.d.ts.map +1 -1
  70. package/dist/services/mcp/internal/McpServerFactory.js +11 -3
  71. package/dist/services/mcp/internal/McpServerFactory.js.map +1 -1
  72. package/dist/services/mcp/internal/McpServerFactory.mjs +12 -4
  73. package/dist/services/mcp/internal/McpServerFactory.mjs.map +1 -1
  74. package/dist/services/mcp/internal/resolveToolSchemaScope.d.ts +16 -0
  75. package/dist/services/mcp/internal/resolveToolSchemaScope.d.ts.map +1 -0
  76. package/dist/services/mcp/internal/resolveToolSchemaScope.js +40 -0
  77. package/dist/services/mcp/internal/resolveToolSchemaScope.js.map +1 -0
  78. package/dist/services/mcp/internal/resolveToolSchemaScope.mjs +38 -0
  79. package/dist/services/mcp/internal/resolveToolSchemaScope.mjs.map +1 -0
  80. package/dist/services/mcp/tool-registry.d.ts +5 -0
  81. package/dist/services/mcp/tool-registry.d.ts.map +1 -1
  82. package/dist/services/mcp/tool-registry.js +30 -1
  83. package/dist/services/mcp/tool-registry.js.map +1 -1
  84. package/dist/services/mcp/tool-registry.mjs +30 -1
  85. package/dist/services/mcp/tool-registry.mjs.map +1 -1
  86. package/dist/services/webhook-runner.d.ts +5 -6
  87. package/dist/services/webhook-runner.d.ts.map +1 -1
  88. package/dist/services/webhook-runner.js +45 -8
  89. package/dist/services/webhook-runner.js.map +1 -1
  90. package/dist/services/webhook-runner.mjs +45 -8
  91. package/dist/services/webhook-runner.mjs.map +1 -1
  92. package/dist/services/webhook-store.d.ts.map +1 -1
  93. package/dist/services/webhook-store.js +21 -2
  94. package/dist/services/webhook-store.js.map +1 -1
  95. package/dist/services/webhook-store.mjs +21 -2
  96. package/dist/services/webhook-store.mjs.map +1 -1
  97. package/package.json +17 -21
@@ -74,6 +74,16 @@ const addDefault = (createOrUpdate)=>{
74
74
  };
75
75
  };
76
76
  const preventCast = (validator)=>validator.transform((val, originalVal)=>originalVal);
77
+ /**
78
+ * On update, a component sent without an `id` is created, not updated (see
79
+ * `updateOrCreateComponent` in the document service). Its fields have no previous value to keep,
80
+ * so in a non-draft write they are validated as on creation.
81
+ */ const getComponentCreateOrUpdate = (createOrUpdate, componentData, options)=>{
82
+ if (createOrUpdate === 'update' && options.isDraft !== true && _.isObject(componentData) && _.get(componentData, 'id') === undefined) {
83
+ return 'creation';
84
+ }
85
+ return createOrUpdate;
86
+ };
77
87
  const createComponentValidator = (createOrUpdate)=>({ attr, updatedAttribute, componentContext }, options)=>{
78
88
  const model = strapi.getModel(attr.component);
79
89
  if (!model) {
@@ -81,7 +91,7 @@ const createComponentValidator = (createOrUpdate)=>({ attr, updatedAttribute, co
81
91
  }
82
92
  if (attr?.repeatable) {
83
93
  // FIXME: yup v1
84
- let validator = yup.array().of(yup.lazy((item)=>createModelValidator(createOrUpdate)({
94
+ let validator = yup.array().of(yup.lazy((item)=>createModelValidator(getComponentCreateOrUpdate(createOrUpdate, item, options))({
85
95
  componentContext,
86
96
  model,
87
97
  data: item
@@ -100,7 +110,7 @@ const createComponentValidator = (createOrUpdate)=>({ attr, updatedAttribute, co
100
110
  }
101
111
  return validator;
102
112
  }
103
- let validator = createModelValidator(createOrUpdate)({
113
+ let validator = createModelValidator(getComponentCreateOrUpdate(createOrUpdate, updatedAttribute.value, options))({
104
114
  model,
105
115
  data: updatedAttribute.value,
106
116
  componentContext
@@ -120,7 +130,7 @@ const createDzValidator = (createOrUpdate)=>({ attr, updatedAttribute, component
120
130
  const schema = yup.object().shape({
121
131
  __component: yup.string().required().oneOf(Object.keys(strapi.components))
122
132
  }).notNull();
123
- return model ? schema.concat(createModelValidator(createOrUpdate)({
133
+ return model ? schema.concat(createModelValidator(getComponentCreateOrUpdate(createOrUpdate, item, options))({
124
134
  model,
125
135
  data: item,
126
136
  componentContext
@@ -357,8 +367,29 @@ const createAttributeValidator = (createOrUpdate)=>(metas, options)=>{
357
367
  validator = addDefault(createOrUpdate)(validator, metas);
358
368
  return validator;
359
369
  };
370
+ /**
371
+ * Conditional visibility is evaluated against the written data. On creation, an attribute
372
+ * missing from the payload is stored with its schema default, so the condition must see that
373
+ * default. On update, a missing attribute keeps its stored value, which is not known here.
374
+ * Only used to evaluate conditions: the validated payload is left untouched.
375
+ */ const getVisibilityData = (createOrUpdate, model, data)=>{
376
+ if (createOrUpdate !== 'creation' || _.isObject(data) === false) {
377
+ return data;
378
+ }
379
+ return Object.entries(model.attributes).reduce((visibilityData, [attributeName, attribute])=>{
380
+ if (visibilityData[attributeName] !== undefined || 'default' in attribute === false || attribute.default === undefined) {
381
+ return visibilityData;
382
+ }
383
+ const defaultValue = typeof attribute.default === 'function' ? attribute.default() : attribute.default;
384
+ return {
385
+ ...visibilityData,
386
+ [attributeName]: defaultValue
387
+ };
388
+ }, data);
389
+ };
360
390
  const createModelValidator = (createOrUpdate)=>({ componentContext, model, data, entity }, options)=>{
361
391
  const writableAttributes = model ? getWritableAttributes(model) : [];
392
+ const visibilityData = model ? getVisibilityData(createOrUpdate, model, data) : data;
362
393
  const schema = writableAttributes.reduce((validators, attributeName)=>{
363
394
  const metas = {
364
395
  attr: model.attributes[attributeName],
@@ -366,7 +397,7 @@ const createModelValidator = (createOrUpdate)=>({ componentContext, model, data,
366
397
  name: attributeName,
367
398
  value: _.get(data, attributeName)
368
399
  },
369
- data,
400
+ data: visibilityData,
370
401
  model,
371
402
  entity,
372
403
  componentContext
@@ -483,7 +514,7 @@ const createValidateEntity = (createOrUpdate)=>{
483
514
  uid: attribute.component,
484
515
  data: componentValue
485
516
  }), (objValue, srcValue)=>{
486
- if (_.isArray(objValue)) {
517
+ if (Array.isArray(objValue)) {
487
518
  return objValue.concat(srcValue);
488
519
  }
489
520
  });
@@ -500,7 +531,7 @@ const createValidateEntity = (createOrUpdate)=>{
500
531
  uid: value.__component,
501
532
  data: value
502
533
  }), (objValue, srcValue)=>{
503
- if (_.isArray(objValue)) {
534
+ if (Array.isArray(objValue)) {
504
535
  return objValue.concat(srcValue);
505
536
  }
506
537
  });
@@ -518,6 +549,10 @@ const createValidateEntity = (createOrUpdate)=>{
518
549
  for (const [key, value] of Object.entries(relationsStore)){
519
550
  const evaluate = async ()=>{
520
551
  const uniqueValues = _.uniqBy(value, `id`);
552
+ // Relations sent with empty connect and disconnect lists leave nothing to look up
553
+ if (uniqueValues.length === 0) {
554
+ return;
555
+ }
521
556
  const count = await strapi.db.query(key).count({
522
557
  where: {
523
558
  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, get, has, isEmpty, isObject } from 'lodash';\nimport jsonLogic from 'json-logic-js';\nimport * as strapiUtils from '@strapi/utils';\nimport type { 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 { isAnyToOne } = strapiUtils.relations;\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 strictRelations?: boolean;\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 options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\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 options\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!options.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 options\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute, componentContext }: ValidatorMeta,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(get(item, '__component'));\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)({ model, data: item, componentContext }, options)\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 (!options.isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\n/**\n * A relation/media value can be supplied in several shapes: a bare id, an array of ids,\n * or a connect/set object (`{ connect: [...] }` / `{ set: [...] }`). This normalises all\n * of them to \"does this attach at least one entry?\" so required validation is consistent\n * regardless of the input shape (mirrors `buildRelationsStore`'s source extraction).\n */\nconst hasRelationValue = (value: unknown): boolean => {\n if (isNil(value)) {\n return false;\n }\n\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n\n if (isObject(value)) {\n const connect = (value as { connect?: unknown }).connect;\n const set = (value as { set?: unknown }).set;\n\n if (!isNil(connect)) {\n return Array.isArray(connect) ? connect.length > 0 : true;\n }\n if (!isNil(set)) {\n return Array.isArray(set) ? set.length > 0 : true;\n }\n\n // Any other object shape (e.g. a bare `{ id }`) counts as a value.\n return true;\n }\n\n return true;\n};\n\n/**\n * A disconnect-only update payload removes entries without adding or replacing any:\n * actual removals in `disconnect`, no `set`, and no effective additions in `connect`.\n * `connect` counts as \"no additions\" when absent OR an empty array — the Content Manager\n * initializes every relation as `{ connect: [], disconnect: [] }` and keeps `connect: []`\n * in place when the user only removes entries, so `{ connect: [], disconnect: [id] }`\n * is the shape real admin saves produce. A payload with empty `disconnect` (nothing\n * removed) is NOT disconnect-only — it's the CM's untouched-relation no-op.\n */\nconst isDisconnectOnly = (value: unknown): boolean => {\n if (!isObject(value)) {\n return false;\n }\n\n const { connect, set, disconnect } = value as {\n connect?: unknown;\n set?: unknown;\n disconnect?: unknown;\n };\n\n if (!isNil(set)) {\n return false;\n }\n\n const hasAdditions = !isNil(connect) && (!Array.isArray(connect) || connect.length > 0);\n if (hasAdditions) {\n return false;\n }\n\n return !isNil(disconnect) && (!Array.isArray(disconnect) || disconnect.length > 0);\n};\n\n/**\n * Decides whether a required media/relation value should be rejected as empty,\n * mirroring the scalar `required` semantics:\n *\n * - creation (`notNil` analogue): an absent key is a failure — the field must be\n * populated, so anything without a value (`undefined`/`null`/`[]`/empty `set`/`connect`)\n * is rejected.\n * - update (`notNull` analogue): an absent key keeps the existing value, so it passes.\n * Only reject when the request is present AND leaves the field empty. A bare\n * `{ connect: [] }` (no `set`) neither adds nor removes anything → treated as a no-op\n * that passes; `{ set: [] }` / `null` / `[]` explicitly empty the field → rejected.\n *\n * `isToOne` marks a to-one relation / single media, which can hold at most one entry.\n * For those, a disconnect-only update (`{ disconnect: [...] }` with no `connect`/`set`)\n * always leaves the field empty — no DB read needed — so it is rejected on non-draft\n * updates. To-many fields can still hold other entries after a disconnect, so their\n * resulting state can't be known without a DB read and they fall through to a pass\n * (publish re-validates the populated draft for D&P types; documented limitation for\n * non-D&P, tied to the null→[] follow-up).\n *\n * On creation there are no existing rows, so a disconnect-only payload attaches nothing\n * and always leaves the field empty — for both to-one and to-many — so it is rejected\n * regardless of `isToOne`.\n */\nconst relationRequiredFails = (\n createOrUpdate: CreateOrUpdate,\n value: unknown,\n isToOne: boolean\n): boolean => {\n if (createOrUpdate === 'creation') {\n // No existing rows on create, so a disconnect attaches nothing and the field stays\n // empty for both to-one and to-many — reject it before the generic value check, which\n // would otherwise treat the bare `{ disconnect: [...] }` object as a present value.\n if (isDisconnectOnly(value)) {\n return true;\n }\n }\n\n if (createOrUpdate === 'update') {\n // Absent key on update = keep the existing value.\n if (value === undefined) {\n return false;\n }\n\n if (isDisconnectOnly(value)) {\n // A disconnect on a to-one/single field deterministically empties it; on a to-many\n // field the resulting state depends on the current DB rows, so we can't reject here.\n return isToOne;\n }\n\n // A connect-only empty is a no-op, not an emptying operation.\n if (isObject(value) && !isNil((value as { connect?: unknown }).connect)) {\n const connect = (value as { connect?: unknown }).connect;\n const hasSet = !isNil((value as { set?: unknown }).set);\n if (!hasSet && Array.isArray(connect) && connect.length === 0) {\n return false;\n }\n }\n }\n\n return !hasRelationValue(value);\n};\n\nconst createMediaAttributeValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Media>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n // Media values arrive in several shapes (a bare id, an array of ids, or a\n // `{ connect }` / `{ set }` object on update). `yup.mixed()` accepts all of them;\n // coercing `multiple` media to `yup.array()` would reject the connect/set object\n // syntax that update requests legitimately send. Required-ness is asserted below\n // via `relationRequiredFails`, which understands every shape.\n let validator: strapiUtils.yup.AnySchema = yup.mixed();\n\n // Relational required constraints are only enforced under the strictRelations flag,\n // and never for drafts (mirrors scalar `required` handling via `!isDraft`).\n if (options.strictRelations && !options.isDraft && attr.required) {\n // A media value can arrive as an id, an array, or a connect/set object, so a simple\n // `.notNil()`/`.min()` is not enough — normalise the shape before asserting.\n // Single media holds at most one file, so a disconnect-only update always empties it.\n const isToOne = !attr.multiple;\n validator = validator.test(\n 'required-media',\n `${updatedAttribute.name} must be defined.`,\n () => !relationRequiredFails(createOrUpdate, updatedAttribute.value, isToOne)\n );\n }\n\n return validator;\n };\n\nconst createRelationValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Relation>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n let validator: strapiUtils.yup.AnySchema;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n // Relational required constraints are only enforced under the strictRelations flag,\n // and never for drafts (mirrors scalar `required` handling via `!isDraft`).\n if (options.strictRelations && !options.isDraft && attr.required) {\n // A relation value can arrive as an id, an array, or a connect/set object, so a\n // simple `.notNil()`/`.min()` is not enough — normalise the shape before asserting.\n // A to-one relation holds at most one target, so a disconnect-only update always empties it.\n const isToOne = isAnyToOne(attr);\n validator = validator.test(\n 'required-relation',\n `${updatedAttribute.name} must be defined.`,\n () => !relationRequiredFails(createOrUpdate, updatedAttribute.value, isToOne)\n );\n }\n\n return validator;\n };\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(Validators, metas.attr.type)) {\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: ValidatorMetas, options: ValidatorContext): strapiUtils.yup.AnySchema => {\n let validator = yup.mixed();\n\n // If field is conditionally invisible, skip all validation for it\n if (metas.attr.conditions?.visible) {\n const isVisible = jsonLogic.apply(metas.attr.conditions.visible, metas.data);\n\n if (!isVisible) {\n return yup.mixed().notRequired(); // Completely skip validation\n }\n }\n\n if (isMediaAttribute(metas.attr)) {\n validator = createMediaAttributeValidator(createOrUpdate)(\n {\n attr: metas.attr as Schema.Attribute.Media,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\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(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 (\n { componentContext, model, data, entity }: ModelValidatorMetas,\n options: ValidatorContext\n ): strapiUtils.yup.AnyObjectSchema => {\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: get(data, attributeName) },\n 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 strictRelations: options?.strictRelations ?? false,\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":["yup","validateYupSchema","strapiUtils","isMediaAttribute","isScalarAttribute","getWritableAttributes","contentTypes","isAnyToOne","relations","ValidationError","errors","isInteger","value","Number","addMinMax","validator","attr","updatedAttribute","nextValidator","min","required","Array","isArray","length","max","addRequiredValidation","createOrUpdate","notNil","notNull","nullable","addDefault","type","repeatable","default","undefined","preventCast","transform","val","originalVal","createComponentValidator","componentContext","options","model","strapi","getModel","component","Error","array","of","lazy","item","createModelValidator","data","isDraft","createDzValidator","get","schema","object","shape","__component","string","oneOf","Object","keys","components","concat","hasRelationValue","isNil","isObject","connect","set","isDisconnectOnly","disconnect","hasAdditions","relationRequiredFails","isToOne","hasSet","createMediaAttributeValidator","mixed","strictRelations","multiple","test","name","createRelationValidator","createScalarAttributeValidator","metas","has","Validators","createAttributeValidator","conditions","visible","isVisible","jsonLogic","apply","notRequired","pathToComponent","repeatableData","newComponentContext","fullDynamicZoneContent","assign","entity","writableAttributes","reduce","validators","attributeName","attributes","createValidateEntity","displayName","info","parentContent","id","locale","relationsValidation","checkRelationsExist","buildRelationsStore","uid","e","createError","path","message","strict","abortEarly","isEmpty","currentModel","result","attribute","relation","target","source","castArray","idArray","map","v","push","relationsStore","componentValue","mergeWith","objValue","srcValue","dzValue","promises","key","entries","evaluate","uniqueValues","uniqBy","count","db","query","where","$in","Promise","all","entityValidator","validateEntityCreation","validateEntityUpdate"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,EAAEA,GAAG,EAAEC,iBAAiB,EAAE,GAAGC,sBAAAA;AACnC,MAAM,EAAEC,gBAAgB,EAAEC,iBAAiB,EAAEC,qBAAqB,EAAE,GAAGH,sBAAAA,CAAYI,YAAY;AAC/F,MAAM,EAAEC,UAAU,EAAE,GAAGL,uBAAYM,SAAS;AAC5C,MAAM,EAAEC,eAAe,EAAE,GAAGP,uBAAYQ,MAAM;AA6C9C,MAAMC,SAAAA,GAAY,CAACC,KAAAA,GAAoCC,MAAAA,CAAOF,SAAS,CAACC,KAAAA,CAAAA;AAExE,MAAME,YAAY,CAMhBC,SAAAA,EACA,EACEC,IAAI,EACJC,gBAAgB,EAC8E,GAAA;AAEhG,IAAA,IAAIC,aAAAA,GAAmBH,SAAAA;IAEvB,IACEJ,SAAAA,CAAUK,KAAKG,GAAG,CAAA,KACjB,UAAC,IAAcH,IAAAA,IAAQA,IAAAA,CAAKI,QAAQ,IAClCC,MAAMC,OAAO,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ChB,IAAA;IAEA,OAAOQ,OAAAA,CAAQC,GAAG,CAACZ,QAAAA,CAAAA;AACrB,CAAA;AAEA,MAAMa,eAAAA,GAA2D;AAC/DC,IAAAA,sBAAAA,EAAwBhD,oBAAAA,CAAqB,UAAA,CAAA;AAC7CiD,IAAAA,oBAAAA,EAAsBjD,oBAAAA,CAAqB,QAAA;AAC7C;;;;"}
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, mergeWith, get, has, isEmpty, isObject } from 'lodash';\nimport jsonLogic from 'json-logic-js';\nimport * as strapiUtils from '@strapi/utils';\nimport type { 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 { isAnyToOne } = strapiUtils.relations;\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 strictRelations?: boolean;\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\n/**\n * On update, a component sent without an `id` is created, not updated (see\n * `updateOrCreateComponent` in the document service). Its fields have no previous value to keep,\n * so in a non-draft write they are validated as on creation.\n */\nconst getComponentCreateOrUpdate = (\n createOrUpdate: CreateOrUpdate,\n componentData: unknown,\n options: ValidatorContext\n): CreateOrUpdate => {\n if (\n createOrUpdate === 'update' &&\n options.isDraft !== true &&\n isObject(componentData) &&\n get(componentData, 'id') === undefined\n ) {\n return 'creation';\n }\n\n return createOrUpdate;\n};\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\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(getComponentCreateOrUpdate(createOrUpdate, item, options))(\n { componentContext, model, data: item },\n options\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!options.isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(\n getComponentCreateOrUpdate(createOrUpdate, updatedAttribute.value, options)\n )(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n options\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute, componentContext }: ValidatorMeta,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(get(item, '__component'));\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(getComponentCreateOrUpdate(createOrUpdate, item, options))(\n { model, data: item, componentContext },\n options\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 (!options.isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\n/**\n * A relation/media value can be supplied in several shapes: a bare id, an array of ids,\n * or a connect/set object (`{ connect: [...] }` / `{ set: [...] }`). This normalises all\n * of them to \"does this attach at least one entry?\" so required validation is consistent\n * regardless of the input shape (mirrors `buildRelationsStore`'s source extraction).\n */\nconst hasRelationValue = (value: unknown): boolean => {\n if (isNil(value)) {\n return false;\n }\n\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n\n if (isObject(value)) {\n const connect = (value as { connect?: unknown }).connect;\n const set = (value as { set?: unknown }).set;\n\n if (!isNil(connect)) {\n return Array.isArray(connect) ? connect.length > 0 : true;\n }\n if (!isNil(set)) {\n return Array.isArray(set) ? set.length > 0 : true;\n }\n\n // Any other object shape (e.g. a bare `{ id }`) counts as a value.\n return true;\n }\n\n return true;\n};\n\n/**\n * A disconnect-only update payload removes entries without adding or replacing any:\n * actual removals in `disconnect`, no `set`, and no effective additions in `connect`.\n * `connect` counts as \"no additions\" when absent OR an empty array — the Content Manager\n * initializes every relation as `{ connect: [], disconnect: [] }` and keeps `connect: []`\n * in place when the user only removes entries, so `{ connect: [], disconnect: [id] }`\n * is the shape real admin saves produce. A payload with empty `disconnect` (nothing\n * removed) is NOT disconnect-only — it's the CM's untouched-relation no-op.\n */\nconst isDisconnectOnly = (value: unknown): boolean => {\n if (!isObject(value)) {\n return false;\n }\n\n const { connect, set, disconnect } = value as {\n connect?: unknown;\n set?: unknown;\n disconnect?: unknown;\n };\n\n if (!isNil(set)) {\n return false;\n }\n\n const hasAdditions = !isNil(connect) && (!Array.isArray(connect) || connect.length > 0);\n if (hasAdditions) {\n return false;\n }\n\n return !isNil(disconnect) && (!Array.isArray(disconnect) || disconnect.length > 0);\n};\n\n/**\n * Decides whether a required media/relation value should be rejected as empty,\n * mirroring the scalar `required` semantics:\n *\n * - creation (`notNil` analogue): an absent key is a failure — the field must be\n * populated, so anything without a value (`undefined`/`null`/`[]`/empty `set`/`connect`)\n * is rejected.\n * - update (`notNull` analogue): an absent key keeps the existing value, so it passes.\n * Only reject when the request is present AND leaves the field empty. A bare\n * `{ connect: [] }` (no `set`) neither adds nor removes anything → treated as a no-op\n * that passes; `{ set: [] }` / `null` / `[]` explicitly empty the field → rejected.\n *\n * `isToOne` marks a to-one relation / single media, which can hold at most one entry.\n * For those, a disconnect-only update (`{ disconnect: [...] }` with no `connect`/`set`)\n * always leaves the field empty — no DB read needed — so it is rejected on non-draft\n * updates. To-many fields can still hold other entries after a disconnect, so their\n * resulting state can't be known without a DB read and they fall through to a pass\n * (publish re-validates the populated draft for D&P types; documented limitation for\n * non-D&P, tied to the null→[] follow-up).\n *\n * On creation there are no existing rows, so a disconnect-only payload attaches nothing\n * and always leaves the field empty — for both to-one and to-many — so it is rejected\n * regardless of `isToOne`.\n */\nconst relationRequiredFails = (\n createOrUpdate: CreateOrUpdate,\n value: unknown,\n isToOne: boolean\n): boolean => {\n if (createOrUpdate === 'creation') {\n // No existing rows on create, so a disconnect attaches nothing and the field stays\n // empty for both to-one and to-many — reject it before the generic value check, which\n // would otherwise treat the bare `{ disconnect: [...] }` object as a present value.\n if (isDisconnectOnly(value)) {\n return true;\n }\n }\n\n if (createOrUpdate === 'update') {\n // Absent key on update = keep the existing value.\n if (value === undefined) {\n return false;\n }\n\n if (isDisconnectOnly(value)) {\n // A disconnect on a to-one/single field deterministically empties it; on a to-many\n // field the resulting state depends on the current DB rows, so we can't reject here.\n return isToOne;\n }\n\n // A connect-only empty is a no-op, not an emptying operation.\n if (isObject(value) && !isNil((value as { connect?: unknown }).connect)) {\n const connect = (value as { connect?: unknown }).connect;\n const hasSet = !isNil((value as { set?: unknown }).set);\n if (!hasSet && Array.isArray(connect) && connect.length === 0) {\n return false;\n }\n }\n }\n\n return !hasRelationValue(value);\n};\n\nconst createMediaAttributeValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Media>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n // Media values arrive in several shapes (a bare id, an array of ids, or a\n // `{ connect }` / `{ set }` object on update). `yup.mixed()` accepts all of them;\n // coercing `multiple` media to `yup.array()` would reject the connect/set object\n // syntax that update requests legitimately send. Required-ness is asserted below\n // via `relationRequiredFails`, which understands every shape.\n let validator: strapiUtils.yup.AnySchema = yup.mixed();\n\n // Relational required constraints are only enforced under the strictRelations flag,\n // and never for drafts (mirrors scalar `required` handling via `!isDraft`).\n if (options.strictRelations && !options.isDraft && attr.required) {\n // A media value can arrive as an id, an array, or a connect/set object, so a simple\n // `.notNil()`/`.min()` is not enough — normalise the shape before asserting.\n // Single media holds at most one file, so a disconnect-only update always empties it.\n const isToOne = !attr.multiple;\n validator = validator.test(\n 'required-media',\n `${updatedAttribute.name} must be defined.`,\n () => !relationRequiredFails(createOrUpdate, updatedAttribute.value, isToOne)\n );\n }\n\n return validator;\n };\n\nconst createRelationValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Relation>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n let validator: strapiUtils.yup.AnySchema;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n // Relational required constraints are only enforced under the strictRelations flag,\n // and never for drafts (mirrors scalar `required` handling via `!isDraft`).\n if (options.strictRelations && !options.isDraft && attr.required) {\n // A relation value can arrive as an id, an array, or a connect/set object, so a\n // simple `.notNil()`/`.min()` is not enough — normalise the shape before asserting.\n // A to-one relation holds at most one target, so a disconnect-only update always empties it.\n const isToOne = isAnyToOne(attr);\n validator = validator.test(\n 'required-relation',\n `${updatedAttribute.name} must be defined.`,\n () => !relationRequiredFails(createOrUpdate, updatedAttribute.value, isToOne)\n );\n }\n\n return validator;\n };\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(Validators, metas.attr.type)) {\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: ValidatorMetas, options: ValidatorContext): strapiUtils.yup.AnySchema => {\n let validator = yup.mixed();\n\n // If field is conditionally invisible, skip all validation for it\n if (metas.attr.conditions?.visible) {\n const isVisible = jsonLogic.apply(metas.attr.conditions.visible, metas.data);\n\n if (!isVisible) {\n return yup.mixed().notRequired(); // Completely skip validation\n }\n }\n\n if (isMediaAttribute(metas.attr)) {\n validator = createMediaAttributeValidator(createOrUpdate)(\n {\n attr: metas.attr as Schema.Attribute.Media,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\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(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\n/**\n * Conditional visibility is evaluated against the written data. On creation, an attribute\n * missing from the payload is stored with its schema default, so the condition must see that\n * default. On update, a missing attribute keeps its stored value, which is not known here.\n * Only used to evaluate conditions: the validated payload is left untouched.\n */\nconst getVisibilityData = (\n createOrUpdate: CreateOrUpdate,\n model: Struct.Schema,\n data: Record<string, unknown>\n): Record<string, unknown> => {\n if (createOrUpdate !== 'creation' || isObject(data) === false) {\n return data;\n }\n\n return Object.entries(model.attributes).reduce((visibilityData, [attributeName, attribute]) => {\n if (\n visibilityData[attributeName] !== undefined ||\n 'default' in attribute === false ||\n attribute.default === undefined\n ) {\n return visibilityData;\n }\n\n const defaultValue =\n typeof attribute.default === 'function' ? attribute.default() : attribute.default;\n\n return { ...visibilityData, [attributeName]: defaultValue };\n }, data);\n};\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { componentContext, model, data, entity }: ModelValidatorMetas,\n options: ValidatorContext\n ): strapiUtils.yup.AnyObjectSchema => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n const visibilityData = model ? getVisibilityData(createOrUpdate, model, data) : data;\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: get(data, attributeName) },\n data: visibilityData,\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 strictRelations: options?.strictRelations ?? false,\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 (Array.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 (Array.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\n // Relations sent with empty connect and disconnect lists leave nothing to look up\n if (uniqueValues.length === 0) {\n return;\n }\n\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":["yup","validateYupSchema","strapiUtils","isMediaAttribute","isScalarAttribute","getWritableAttributes","contentTypes","isAnyToOne","relations","ValidationError","errors","isInteger","value","Number","addMinMax","validator","attr","updatedAttribute","nextValidator","min","required","Array","isArray","length","max","addRequiredValidation","createOrUpdate","notNil","notNull","nullable","addDefault","type","repeatable","default","undefined","preventCast","transform","val","originalVal","getComponentCreateOrUpdate","componentData","options","isDraft","isObject","get","createComponentValidator","componentContext","model","strapi","getModel","component","Error","array","of","lazy","item","createModelValidator","data","createDzValidator","schema","object","shape","__component","string","oneOf","Object","keys","components","concat","hasRelationValue","isNil","connect","set","isDisconnectOnly","disconnect","hasAdditions","relationRequiredFails","isToOne","hasSet","createMediaAttributeValidator","mixed","strictRelations","multiple","test","name","createRelationValidator","createScalarAttributeValidator","metas","has","Validators","createAttributeValidator","conditions","visible","isVisible","jsonLogic","apply","notRequired","pathToComponent","repeatableData","newComponentContext","fullDynamicZoneContent","assign","getVisibilityData","entries","attributes","reduce","visibilityData","attributeName","attribute","defaultValue","entity","writableAttributes","validators","createValidateEntity","displayName","info","parentContent","id","locale","relationsValidation","checkRelationsExist","buildRelationsStore","uid","e","createError","path","message","strict","abortEarly","isEmpty","currentModel","result","relation","target","source","castArray","idArray","map","v","push","relationsStore","componentValue","mergeWith","objValue","srcValue","dzValue","promises","key","evaluate","uniqueValues","uniqBy","count","db","query","where","$in","Promise","all","entityValidator","validateEntityCreation","validateEntityUpdate"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,EAAEA,GAAG,EAAEC,iBAAiB,EAAE,GAAGC,sBAAAA;AACnC,MAAM,EAAEC,gBAAgB,EAAEC,iBAAiB,EAAEC,qBAAqB,EAAE,GAAGH,sBAAAA,CAAYI,YAAY;AAC/F,MAAM,EAAEC,UAAU,EAAE,GAAGL,uBAAYM,SAAS;AAC5C,MAAM,EAAEC,eAAe,EAAE,GAAGP,uBAAYQ,MAAM;AA6C9C,MAAMC,SAAAA,GAAY,CAACC,KAAAA,GAAoCC,MAAAA,CAAOF,SAAS,CAACC,KAAAA,CAAAA;AAExE,MAAME,YAAY,CAMhBC,SAAAA,EACA,EACEC,IAAI,EACJC,gBAAgB,EAC8E,GAAA;AAEhG,IAAA,IAAIC,aAAAA,GAAmBH,SAAAA;IAEvB,IACEJ,SAAAA,CAAUK,KAAKG,GAAG,CAAA,KACjB,UAAC,IAAcH,IAAAA,IAAQA,IAAAA,CAAKI,QAAQ,IAClCC,MAAMC,OAAO,CAACL,gBAAAA,CAAiBL,KAAK,CAAA,IAAKK,gBAAAA,CAAiBL,KAAK,CAACW,MAAM,G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AUF,YAAAA,CAAa9H,MAAM,EAAE;gBACjC,MAAM,IAAId,eAAAA,CACR,CAAA,EACE4I,YAAAA,CAAa9H,MAAM,GAAGgI,KAAAA,CACvB,qBAAqB,EAAEJ,GAAAA,CAAI,yCAAyC,CAAC,CAAA;AAE1E,YAAA;AACF,QAAA,CAAA;AACAD,QAAAA,QAAAA,CAASP,IAAI,CAACS,QAAAA,EAAAA,CAAAA;AAChB,IAAA;IAEA,OAAOQ,OAAAA,CAAQC,GAAG,CAACX,QAAAA,CAAAA;AACrB,CAAA;AAEA,MAAMY,eAAAA,GAA2D;AAC/DC,IAAAA,sBAAAA,EAAwB9C,oBAAAA,CAAqB,UAAA,CAAA;AAC7C+C,IAAAA,oBAAAA,EAAsB/C,oBAAAA,CAAqB,QAAA;AAC7C;;;;"}
@@ -1,4 +1,4 @@
1
- import { isObject, get, isEmpty, isNil, castArray, mergeWith, isArray, uniqBy, has } from 'lodash';
1
+ import { isObject, get, isEmpty, isNil, castArray, mergeWith, uniqBy, has } from 'lodash';
2
2
  import jsonLogic from 'json-logic-js';
3
3
  import * as strapiUtils from '@strapi/utils';
4
4
  import { Validators } from './validators.mjs';
@@ -49,6 +49,16 @@ const addDefault = (createOrUpdate)=>{
49
49
  };
50
50
  };
51
51
  const preventCast = (validator)=>validator.transform((val, originalVal)=>originalVal);
52
+ /**
53
+ * On update, a component sent without an `id` is created, not updated (see
54
+ * `updateOrCreateComponent` in the document service). Its fields have no previous value to keep,
55
+ * so in a non-draft write they are validated as on creation.
56
+ */ const getComponentCreateOrUpdate = (createOrUpdate, componentData, options)=>{
57
+ if (createOrUpdate === 'update' && options.isDraft !== true && isObject(componentData) && get(componentData, 'id') === undefined) {
58
+ return 'creation';
59
+ }
60
+ return createOrUpdate;
61
+ };
52
62
  const createComponentValidator = (createOrUpdate)=>({ attr, updatedAttribute, componentContext }, options)=>{
53
63
  const model = strapi.getModel(attr.component);
54
64
  if (!model) {
@@ -56,7 +66,7 @@ const createComponentValidator = (createOrUpdate)=>({ attr, updatedAttribute, co
56
66
  }
57
67
  if (attr?.repeatable) {
58
68
  // FIXME: yup v1
59
- let validator = yup.array().of(yup.lazy((item)=>createModelValidator(createOrUpdate)({
69
+ let validator = yup.array().of(yup.lazy((item)=>createModelValidator(getComponentCreateOrUpdate(createOrUpdate, item, options))({
60
70
  componentContext,
61
71
  model,
62
72
  data: item
@@ -75,7 +85,7 @@ const createComponentValidator = (createOrUpdate)=>({ attr, updatedAttribute, co
75
85
  }
76
86
  return validator;
77
87
  }
78
- let validator = createModelValidator(createOrUpdate)({
88
+ let validator = createModelValidator(getComponentCreateOrUpdate(createOrUpdate, updatedAttribute.value, options))({
79
89
  model,
80
90
  data: updatedAttribute.value,
81
91
  componentContext
@@ -95,7 +105,7 @@ const createDzValidator = (createOrUpdate)=>({ attr, updatedAttribute, component
95
105
  const schema = yup.object().shape({
96
106
  __component: yup.string().required().oneOf(Object.keys(strapi.components))
97
107
  }).notNull();
98
- return model ? schema.concat(createModelValidator(createOrUpdate)({
108
+ return model ? schema.concat(createModelValidator(getComponentCreateOrUpdate(createOrUpdate, item, options))({
99
109
  model,
100
110
  data: item,
101
111
  componentContext
@@ -332,8 +342,29 @@ const createAttributeValidator = (createOrUpdate)=>(metas, options)=>{
332
342
  validator = addDefault(createOrUpdate)(validator, metas);
333
343
  return validator;
334
344
  };
345
+ /**
346
+ * Conditional visibility is evaluated against the written data. On creation, an attribute
347
+ * missing from the payload is stored with its schema default, so the condition must see that
348
+ * default. On update, a missing attribute keeps its stored value, which is not known here.
349
+ * Only used to evaluate conditions: the validated payload is left untouched.
350
+ */ const getVisibilityData = (createOrUpdate, model, data)=>{
351
+ if (createOrUpdate !== 'creation' || isObject(data) === false) {
352
+ return data;
353
+ }
354
+ return Object.entries(model.attributes).reduce((visibilityData, [attributeName, attribute])=>{
355
+ if (visibilityData[attributeName] !== undefined || 'default' in attribute === false || attribute.default === undefined) {
356
+ return visibilityData;
357
+ }
358
+ const defaultValue = typeof attribute.default === 'function' ? attribute.default() : attribute.default;
359
+ return {
360
+ ...visibilityData,
361
+ [attributeName]: defaultValue
362
+ };
363
+ }, data);
364
+ };
335
365
  const createModelValidator = (createOrUpdate)=>({ componentContext, model, data, entity }, options)=>{
336
366
  const writableAttributes = model ? getWritableAttributes(model) : [];
367
+ const visibilityData = model ? getVisibilityData(createOrUpdate, model, data) : data;
337
368
  const schema = writableAttributes.reduce((validators, attributeName)=>{
338
369
  const metas = {
339
370
  attr: model.attributes[attributeName],
@@ -341,7 +372,7 @@ const createModelValidator = (createOrUpdate)=>({ componentContext, model, data,
341
372
  name: attributeName,
342
373
  value: get(data, attributeName)
343
374
  },
344
- data,
375
+ data: visibilityData,
345
376
  model,
346
377
  entity,
347
378
  componentContext
@@ -458,7 +489,7 @@ const createValidateEntity = (createOrUpdate)=>{
458
489
  uid: attribute.component,
459
490
  data: componentValue
460
491
  }), (objValue, srcValue)=>{
461
- if (isArray(objValue)) {
492
+ if (Array.isArray(objValue)) {
462
493
  return objValue.concat(srcValue);
463
494
  }
464
495
  });
@@ -475,7 +506,7 @@ const createValidateEntity = (createOrUpdate)=>{
475
506
  uid: value.__component,
476
507
  data: value
477
508
  }), (objValue, srcValue)=>{
478
- if (isArray(objValue)) {
509
+ if (Array.isArray(objValue)) {
479
510
  return objValue.concat(srcValue);
480
511
  }
481
512
  });
@@ -493,6 +524,10 @@ const createValidateEntity = (createOrUpdate)=>{
493
524
  for (const [key, value] of Object.entries(relationsStore)){
494
525
  const evaluate = async ()=>{
495
526
  const uniqueValues = uniqBy(value, `id`);
527
+ // Relations sent with empty connect and disconnect lists leave nothing to look up
528
+ if (uniqueValues.length === 0) {
529
+ return;
530
+ }
496
531
  const count = await strapi.db.query(key).count({
497
532
  where: {
498
533
  id: {