@strapi/content-manager 5.16.1 → 5.17.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 (44) hide show
  1. package/dist/admin/history/components/VersionContent.js +24 -3
  2. package/dist/admin/history/components/VersionContent.js.map +1 -1
  3. package/dist/admin/history/components/VersionContent.mjs +25 -4
  4. package/dist/admin/history/components/VersionContent.mjs.map +1 -1
  5. package/dist/admin/pages/EditView/EditViewPage.js +11 -1
  6. package/dist/admin/pages/EditView/EditViewPage.js.map +1 -1
  7. package/dist/admin/pages/EditView/EditViewPage.mjs +11 -1
  8. package/dist/admin/pages/EditView/EditViewPage.mjs.map +1 -1
  9. package/dist/admin/pages/EditView/components/DocumentActions.js +28 -4
  10. package/dist/admin/pages/EditView/components/DocumentActions.js.map +1 -1
  11. package/dist/admin/pages/EditView/components/DocumentActions.mjs +28 -4
  12. package/dist/admin/pages/EditView/components/DocumentActions.mjs.map +1 -1
  13. package/dist/admin/pages/EditView/components/FormInputs/Component/NonRepeatable.js +12 -1
  14. package/dist/admin/pages/EditView/components/FormInputs/Component/NonRepeatable.js.map +1 -1
  15. package/dist/admin/pages/EditView/components/FormInputs/Component/NonRepeatable.mjs +13 -2
  16. package/dist/admin/pages/EditView/components/FormInputs/Component/NonRepeatable.mjs.map +1 -1
  17. package/dist/admin/pages/EditView/components/FormInputs/Component/Repeatable.js +13 -2
  18. package/dist/admin/pages/EditView/components/FormInputs/Component/Repeatable.js.map +1 -1
  19. package/dist/admin/pages/EditView/components/FormInputs/Component/Repeatable.mjs +14 -3
  20. package/dist/admin/pages/EditView/components/FormInputs/Component/Repeatable.mjs.map +1 -1
  21. package/dist/admin/pages/EditView/components/FormInputs/DynamicZone/DynamicComponent.js +16 -3
  22. package/dist/admin/pages/EditView/components/FormInputs/DynamicZone/DynamicComponent.js.map +1 -1
  23. package/dist/admin/pages/EditView/components/FormInputs/DynamicZone/DynamicComponent.mjs +17 -4
  24. package/dist/admin/pages/EditView/components/FormInputs/DynamicZone/DynamicComponent.mjs.map +1 -1
  25. package/dist/admin/pages/EditView/components/FormLayout.js +27 -3
  26. package/dist/admin/pages/EditView/components/FormLayout.js.map +1 -1
  27. package/dist/admin/pages/EditView/components/FormLayout.mjs +27 -3
  28. package/dist/admin/pages/EditView/components/FormLayout.mjs.map +1 -1
  29. package/dist/admin/pages/EditView/utils/data.js +103 -0
  30. package/dist/admin/pages/EditView/utils/data.js.map +1 -1
  31. package/dist/admin/pages/EditView/utils/data.mjs +103 -1
  32. package/dist/admin/pages/EditView/utils/data.mjs.map +1 -1
  33. package/dist/admin/src/pages/EditView/utils/data.d.ts +19 -1
  34. package/dist/admin/src/utils/validation.d.ts +1 -0
  35. package/dist/admin/utils/validation.js +16 -5
  36. package/dist/admin/utils/validation.js.map +1 -1
  37. package/dist/admin/utils/validation.mjs +16 -5
  38. package/dist/admin/utils/validation.mjs.map +1 -1
  39. package/dist/server/services/document-metadata.js +1 -1
  40. package/dist/server/services/document-metadata.js.map +1 -1
  41. package/dist/server/services/document-metadata.mjs +1 -1
  42. package/dist/server/services/document-metadata.mjs.map +1 -1
  43. package/dist/server/src/services/document-metadata.d.ts.map +1 -1
  44. package/package.json +5 -5
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var strapiAdmin = require('@strapi/admin/strapi-admin');
3
4
  var fractionalIndexing = require('fractional-indexing');
4
5
  var pipe = require('lodash/fp/pipe');
5
6
  var attributes = require('../../../constants/attributes.js');
@@ -126,7 +127,109 @@ const BLOCK_LIST_ATTRIBUTE_KEYS = [
126
127
  ])(schema, components), removeNullValues, prepareRelations(schema, components), prepareTempKeys(schema, components));
127
128
  return transformations(document);
128
129
  };
130
+ /**
131
+ * Removes values from the data object if their corresponding attribute has a
132
+ * visibility condition that evaluates to false.
133
+ *
134
+ * @param {object} schema - The content type schema (with attributes).
135
+ * @param {object} data - The data object to filter based on visibility.
136
+ * @returns {object} A new data object with only visible fields retained.
137
+ */ const handleInvisibleAttributes = (data, { schema, initialValues = {}, components = {} }, path = [], removedAttributes = [])=>{
138
+ if (!schema?.attributes) return {
139
+ data,
140
+ removedAttributes
141
+ };
142
+ const rulesEngine = strapiAdmin.createRulesEngine();
143
+ const result = {};
144
+ for (const [attrName, attrDef] of Object.entries(schema.attributes)){
145
+ const fullPath = [
146
+ ...path,
147
+ attrName
148
+ ].join('.');
149
+ const condition = attrDef?.conditions?.visible;
150
+ const isVisible = condition ? rulesEngine.evaluate(condition, {
151
+ ...data,
152
+ ...result
153
+ }) : true;
154
+ if (!isVisible) {
155
+ removedAttributes.push(fullPath);
156
+ continue;
157
+ }
158
+ const userProvided = Object.prototype.hasOwnProperty.call(data, attrName);
159
+ const currentValue = userProvided ? data[attrName] : undefined;
160
+ const initialValue = initialValues?.[attrName];
161
+ // 🔹 Handle components
162
+ if (attrDef.type === 'component') {
163
+ const compSchema = components[attrDef.component];
164
+ const value = currentValue ?? initialValue;
165
+ if (!value) {
166
+ result[attrName] = attrDef.repeatable ? [] : null;
167
+ continue;
168
+ }
169
+ if (attrDef.repeatable && Array.isArray(value)) {
170
+ result[attrName] = value.map((item, index)=>handleInvisibleAttributes(item, {
171
+ schema: compSchema,
172
+ initialValues: initialValue?.[index] ?? {},
173
+ components
174
+ }, [
175
+ ...path,
176
+ `${attrName}[${index}]`
177
+ ], removedAttributes).data);
178
+ } else {
179
+ result[attrName] = handleInvisibleAttributes(value, {
180
+ schema: compSchema,
181
+ initialValues: initialValue ?? {},
182
+ components
183
+ }, [
184
+ ...path,
185
+ attrName
186
+ ], removedAttributes).data;
187
+ }
188
+ continue;
189
+ }
190
+ // 🔸 Handle dynamic zones
191
+ if (attrDef.type === 'dynamiczone') {
192
+ if (!Array.isArray(currentValue)) {
193
+ result[attrName] = [];
194
+ continue;
195
+ }
196
+ result[attrName] = currentValue.map((dzItem, index)=>{
197
+ const compUID = dzItem?.__component;
198
+ const compSchema = components[compUID];
199
+ const cleaned = handleInvisibleAttributes(dzItem, {
200
+ schema: compSchema,
201
+ initialValues: initialValue?.[index] ?? {},
202
+ components
203
+ }, [
204
+ ...path,
205
+ `${attrName}[${index}]`
206
+ ], removedAttributes).data;
207
+ return {
208
+ __component: compUID,
209
+ ...cleaned
210
+ };
211
+ });
212
+ continue;
213
+ }
214
+ // 🟡 Handle scalar/primitive
215
+ if (currentValue !== undefined) {
216
+ result[attrName] = currentValue;
217
+ } else if (initialValue !== undefined) {
218
+ result[attrName] = initialValue;
219
+ } else {
220
+ if (attrName === 'id' || attrName === 'documentId') {
221
+ continue;
222
+ }
223
+ result[attrName] = null;
224
+ }
225
+ }
226
+ return {
227
+ data: result,
228
+ removedAttributes
229
+ };
230
+ };
129
231
 
232
+ exports.handleInvisibleAttributes = handleInvisibleAttributes;
130
233
  exports.prepareRelations = prepareRelations;
131
234
  exports.prepareTempKeys = prepareTempKeys;
132
235
  exports.removeFieldsThatDontExistOnSchema = removeFieldsThatDontExistOnSchema;
@@ -1 +1 @@
1
- {"version":3,"file":"data.js","sources":["../../../../../admin/src/pages/EditView/utils/data.ts"],"sourcesContent":["import { generateNKeysBetween } from 'fractional-indexing';\nimport pipe from 'lodash/fp/pipe';\n\nimport { DOCUMENT_META_FIELDS } from '../../../constants/attributes';\n\nimport type { ComponentsDictionary, Document } from '../../../hooks/useDocument';\nimport type { Schema, UID } from '@strapi/types';\n\n/* -------------------------------------------------------------------------------------------------\n * traverseData\n * -----------------------------------------------------------------------------------------------*/\n\n// Make only attributes required since it's the only one Content History has\ntype PartialSchema = Partial<Schema.Schema> & Pick<Schema.Schema, 'attributes'>;\n\ntype Predicate = <TAttribute extends Schema.Attribute.AnyAttribute>(\n attribute: TAttribute,\n value: Schema.Attribute.Value<TAttribute>\n) => boolean;\ntype Transform = <TAttribute extends Schema.Attribute.AnyAttribute>(\n value: any,\n attribute: TAttribute\n) => any;\ntype AnyData = Omit<Document, 'id'>;\n\nconst BLOCK_LIST_ATTRIBUTE_KEYS = ['__component', '__temp_key__'];\n\n/**\n * @internal This function is used to traverse the data and transform the values.\n * Given a predicate function, it will transform the value (using the given transform function)\n * if the predicate returns true. If it finds that the attribute is a component or dynamiczone,\n * it will recursively traverse those data structures as well.\n *\n * It is possible to break the ContentManager by using this function incorrectly, for example,\n * if you transform a number into a string but the attribute type is a number, the ContentManager\n * will not be able to save the data and the Form will likely crash because the component it's\n * passing the data too won't succesfully be able to handle the value.\n */\nconst traverseData =\n (predicate: Predicate, transform: Transform) =>\n (schema: PartialSchema, components: ComponentsDictionary = {}) =>\n (data: AnyData = {}) => {\n const traverse = (datum: AnyData, attributes: Schema.Schema['attributes']) => {\n return Object.entries(datum).reduce<AnyData>((acc, [key, value]) => {\n const attribute = attributes[key];\n\n /**\n * If the attribute is a block list attribute, we don't want to transform it.\n * We also don't want to transform null or undefined values.\n */\n if (BLOCK_LIST_ATTRIBUTE_KEYS.includes(key) || value === null || value === undefined) {\n acc[key] = value;\n return acc;\n }\n\n if (attribute.type === 'component') {\n if (attribute.repeatable) {\n const componentValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n acc[key] = componentValue.map((componentData) =>\n traverse(componentData, components[attribute.component]?.attributes ?? {})\n );\n } else {\n const componentValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, false>>;\n\n acc[key] = traverse(componentValue, components[attribute.component]?.attributes ?? {});\n }\n } else if (attribute.type === 'dynamiczone') {\n const dynamicZoneValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n acc[key] = dynamicZoneValue.map((componentData) =>\n traverse(componentData, components[componentData.__component]?.attributes ?? {})\n );\n } else if (predicate(attribute, value)) {\n acc[key] = transform(value, attribute);\n } else {\n acc[key] = value;\n }\n\n return acc;\n }, {});\n };\n\n return traverse(data, schema.attributes);\n };\n\n/* -------------------------------------------------------------------------------------------------\n * removeProhibitedFields\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal Removes all the fields that are not allowed.\n */\nconst removeProhibitedFields = (prohibitedFields: Schema.Attribute.Kind[]) =>\n traverseData(\n (attribute) => prohibitedFields.includes(attribute.type),\n () => ''\n );\n\n/* -------------------------------------------------------------------------------------------------\n * prepareRelations\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Sets all relation values to an empty array.\n */\nconst prepareRelations = traverseData(\n (attribute) => attribute.type === 'relation',\n () => ({\n connect: [],\n disconnect: [],\n })\n);\n\n/* -------------------------------------------------------------------------------------------------\n * prepareTempKeys\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Adds a `__temp_key__` to each component and dynamiczone item. This gives us\n * a stable identifier regardless of its ids etc. that we can then use for drag and drop.\n */\nconst prepareTempKeys = traverseData(\n (attribute) =>\n (attribute.type === 'component' && attribute.repeatable) || attribute.type === 'dynamiczone',\n (data) => {\n if (Array.isArray(data) && data.length > 0) {\n const keys = generateNKeysBetween(undefined, undefined, data.length);\n\n return data.map((datum, index) => ({\n ...datum,\n __temp_key__: keys[index],\n }));\n }\n\n return data;\n }\n);\n\n/* -------------------------------------------------------------------------------------------------\n * removeFieldsThatDontExistOnSchema\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Fields that don't exist in the schema like createdAt etc. are only on the first level (not nested),\n * as such we don't need to traverse the components to remove them.\n */\nconst removeFieldsThatDontExistOnSchema = (schema: PartialSchema) => (data: AnyData) => {\n const schemaKeys = Object.keys(schema.attributes);\n const dataKeys = Object.keys(data);\n\n const keysToRemove = dataKeys.filter((key) => !schemaKeys.includes(key));\n\n const revisedData = [...keysToRemove, ...DOCUMENT_META_FIELDS].reduce((acc, key) => {\n delete acc[key];\n\n return acc;\n }, structuredClone(data));\n\n return revisedData;\n};\n\n/**\n * @internal\n * @description We need to remove null fields from the data-structure because it will pass it\n * to the specific inputs breaking them as most would prefer empty strings or `undefined` if\n * they're controlled / uncontrolled.\n */\nconst removeNullValues = (data: AnyData) => {\n return Object.entries(data).reduce<AnyData>((acc, [key, value]) => {\n if (value === null) {\n return acc;\n }\n\n acc[key] = value;\n\n return acc;\n }, {});\n};\n\n/* -------------------------------------------------------------------------------------------------\n * transformDocuments\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Takes a document data structure (this could be from the API or a default form structure)\n * and applies consistent data transformations to it. This is also used when we add new components to the\n * form to ensure the data is correctly prepared from their default state e.g. relations are set to an empty array.\n */\nconst transformDocument =\n (schema: PartialSchema, components: ComponentsDictionary = {}) =>\n (document: AnyData) => {\n const transformations = pipe(\n removeFieldsThatDontExistOnSchema(schema),\n removeProhibitedFields(['password'])(schema, components),\n removeNullValues,\n prepareRelations(schema, components),\n prepareTempKeys(schema, components)\n );\n\n return transformations(document);\n };\n\nexport {\n removeProhibitedFields,\n prepareRelations,\n prepareTempKeys,\n removeFieldsThatDontExistOnSchema,\n transformDocument,\n};\nexport type { AnyData };\n"],"names":["BLOCK_LIST_ATTRIBUTE_KEYS","traverseData","predicate","transform","schema","components","data","traverse","datum","attributes","Object","entries","reduce","acc","key","value","attribute","includes","undefined","type","repeatable","componentValue","map","componentData","component","dynamicZoneValue","__component","removeProhibitedFields","prohibitedFields","prepareRelations","connect","disconnect","prepareTempKeys","Array","isArray","length","keys","generateNKeysBetween","index","__temp_key__","removeFieldsThatDontExistOnSchema","schemaKeys","dataKeys","keysToRemove","filter","revisedData","DOCUMENT_META_FIELDS","structuredClone","removeNullValues","transformDocument","document","transformations","pipe"],"mappings":";;;;;;AAyBA,MAAMA,yBAA4B,GAAA;AAAC,IAAA,aAAA;AAAe,IAAA;AAAe,CAAA;AAEjE;;;;;;;;;;AAUC,IACD,MAAMC,YAAAA,GACJ,CAACC,SAAAA,EAAsBC,YACvB,CAACC,MAAAA,EAAuBC,UAAmC,GAAA,EAAE,GAC7D,CAACC,IAAAA,GAAgB,EAAE,GAAA;YACjB,MAAMC,QAAAA,GAAW,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T;QAEAA,GAAG,CAACC,IAAI,GAAGC,KAAAA;QAEX,OAAOF,GAAAA;AACT,KAAA,EAAG,EAAC,CAAA;AACN,CAAA;AAEA;;;;;;;IAUA,MAAMoC,oBACJ,CAAC7C,MAAAA,EAAuBC,aAAmC,EAAE,GAC7D,CAAC6C,QAAAA,GAAAA;AACC,QAAA,MAAMC,eAAkBC,GAAAA,IAAAA,CACtBZ,iCAAkCpC,CAAAA,MAAAA,CAAAA,EAClCuB,sBAAuB,CAAA;AAAC,YAAA;AAAW,SAAA,CAAA,CAAEvB,QAAQC,UAC7C2C,CAAAA,EAAAA,gBAAAA,EACAnB,iBAAiBzB,MAAQC,EAAAA,UAAAA,CAAAA,EACzB2B,gBAAgB5B,MAAQC,EAAAA,UAAAA,CAAAA,CAAAA;AAG1B,QAAA,OAAO8C,eAAgBD,CAAAA,QAAAA,CAAAA;AACzB;;;;;;;;"}
1
+ {"version":3,"file":"data.js","sources":["../../../../../admin/src/pages/EditView/utils/data.ts"],"sourcesContent":["import { createRulesEngine } from '@strapi/admin/strapi-admin';\nimport { generateNKeysBetween } from 'fractional-indexing';\nimport pipe from 'lodash/fp/pipe';\n\nimport { DOCUMENT_META_FIELDS } from '../../../constants/attributes';\n\nimport type { ComponentsDictionary, Document } from '../../../hooks/useDocument';\nimport type { Schema, UID } from '@strapi/types';\n\n/* -------------------------------------------------------------------------------------------------\n * traverseData\n * -----------------------------------------------------------------------------------------------*/\n\n// Make only attributes required since it's the only one Content History has\ntype PartialSchema = Partial<Schema.Schema> & Pick<Schema.Schema, 'attributes'>;\n\ntype Predicate = <TAttribute extends Schema.Attribute.AnyAttribute>(\n attribute: TAttribute,\n value: Schema.Attribute.Value<TAttribute>\n) => boolean;\ntype Transform = <TAttribute extends Schema.Attribute.AnyAttribute>(\n value: any,\n attribute: TAttribute\n) => any;\ntype AnyData = Omit<Document, 'id'>;\n\nconst BLOCK_LIST_ATTRIBUTE_KEYS = ['__component', '__temp_key__'];\n\n/**\n * @internal This function is used to traverse the data and transform the values.\n * Given a predicate function, it will transform the value (using the given transform function)\n * if the predicate returns true. If it finds that the attribute is a component or dynamiczone,\n * it will recursively traverse those data structures as well.\n *\n * It is possible to break the ContentManager by using this function incorrectly, for example,\n * if you transform a number into a string but the attribute type is a number, the ContentManager\n * will not be able to save the data and the Form will likely crash because the component it's\n * passing the data too won't succesfully be able to handle the value.\n */\nconst traverseData =\n (predicate: Predicate, transform: Transform) =>\n (schema: PartialSchema, components: ComponentsDictionary = {}) =>\n (data: AnyData = {}) => {\n const traverse = (datum: AnyData, attributes: Schema.Schema['attributes']) => {\n return Object.entries(datum).reduce<AnyData>((acc, [key, value]) => {\n const attribute = attributes[key];\n\n /**\n * If the attribute is a block list attribute, we don't want to transform it.\n * We also don't want to transform null or undefined values.\n */\n if (BLOCK_LIST_ATTRIBUTE_KEYS.includes(key) || value === null || value === undefined) {\n acc[key] = value;\n return acc;\n }\n\n if (attribute.type === 'component') {\n if (attribute.repeatable) {\n const componentValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n acc[key] = componentValue.map((componentData) =>\n traverse(componentData, components[attribute.component]?.attributes ?? {})\n );\n } else {\n const componentValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, false>>;\n\n acc[key] = traverse(componentValue, components[attribute.component]?.attributes ?? {});\n }\n } else if (attribute.type === 'dynamiczone') {\n const dynamicZoneValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n acc[key] = dynamicZoneValue.map((componentData) =>\n traverse(componentData, components[componentData.__component]?.attributes ?? {})\n );\n } else if (predicate(attribute, value)) {\n acc[key] = transform(value, attribute);\n } else {\n acc[key] = value;\n }\n\n return acc;\n }, {});\n };\n\n return traverse(data, schema.attributes);\n };\n\n/* -------------------------------------------------------------------------------------------------\n * removeProhibitedFields\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal Removes all the fields that are not allowed.\n */\nconst removeProhibitedFields = (prohibitedFields: Schema.Attribute.Kind[]) =>\n traverseData(\n (attribute) => prohibitedFields.includes(attribute.type),\n () => ''\n );\n\n/* -------------------------------------------------------------------------------------------------\n * prepareRelations\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Sets all relation values to an empty array.\n */\nconst prepareRelations = traverseData(\n (attribute) => attribute.type === 'relation',\n () => ({\n connect: [],\n disconnect: [],\n })\n);\n\n/* -------------------------------------------------------------------------------------------------\n * prepareTempKeys\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Adds a `__temp_key__` to each component and dynamiczone item. This gives us\n * a stable identifier regardless of its ids etc. that we can then use for drag and drop.\n */\nconst prepareTempKeys = traverseData(\n (attribute) =>\n (attribute.type === 'component' && attribute.repeatable) || attribute.type === 'dynamiczone',\n (data) => {\n if (Array.isArray(data) && data.length > 0) {\n const keys = generateNKeysBetween(undefined, undefined, data.length);\n\n return data.map((datum, index) => ({\n ...datum,\n __temp_key__: keys[index],\n }));\n }\n\n return data;\n }\n);\n\n/* -------------------------------------------------------------------------------------------------\n * removeFieldsThatDontExistOnSchema\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Fields that don't exist in the schema like createdAt etc. are only on the first level (not nested),\n * as such we don't need to traverse the components to remove them.\n */\nconst removeFieldsThatDontExistOnSchema = (schema: PartialSchema) => (data: AnyData) => {\n const schemaKeys = Object.keys(schema.attributes);\n const dataKeys = Object.keys(data);\n\n const keysToRemove = dataKeys.filter((key) => !schemaKeys.includes(key));\n\n const revisedData = [...keysToRemove, ...DOCUMENT_META_FIELDS].reduce((acc, key) => {\n delete acc[key];\n\n return acc;\n }, structuredClone(data));\n\n return revisedData;\n};\n\n/**\n * @internal\n * @description We need to remove null fields from the data-structure because it will pass it\n * to the specific inputs breaking them as most would prefer empty strings or `undefined` if\n * they're controlled / uncontrolled.\n */\nconst removeNullValues = (data: AnyData) => {\n return Object.entries(data).reduce<AnyData>((acc, [key, value]) => {\n if (value === null) {\n return acc;\n }\n\n acc[key] = value;\n\n return acc;\n }, {});\n};\n\n/* -------------------------------------------------------------------------------------------------\n * transformDocuments\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Takes a document data structure (this could be from the API or a default form structure)\n * and applies consistent data transformations to it. This is also used when we add new components to the\n * form to ensure the data is correctly prepared from their default state e.g. relations are set to an empty array.\n */\nconst transformDocument =\n (schema: PartialSchema, components: ComponentsDictionary = {}) =>\n (document: AnyData) => {\n const transformations = pipe(\n removeFieldsThatDontExistOnSchema(schema),\n removeProhibitedFields(['password'])(schema, components),\n removeNullValues,\n prepareRelations(schema, components),\n prepareTempKeys(schema, components)\n );\n\n return transformations(document);\n };\n\ntype HandleOptions = {\n schema?: Schema.ContentType | Schema.Component;\n initialValues?: AnyData;\n components?: Record<string, Schema.Component>;\n};\n\ntype RemovedFieldPath = string;\n\n/**\n * Removes values from the data object if their corresponding attribute has a\n * visibility condition that evaluates to false.\n *\n * @param {object} schema - The content type schema (with attributes).\n * @param {object} data - The data object to filter based on visibility.\n * @returns {object} A new data object with only visible fields retained.\n */\nconst handleInvisibleAttributes = (\n data: AnyData,\n { schema, initialValues = {}, components = {} }: HandleOptions,\n path: string[] = [],\n removedAttributes: RemovedFieldPath[] = []\n): {\n data: AnyData;\n removedAttributes: RemovedFieldPath[];\n} => {\n if (!schema?.attributes) return { data, removedAttributes };\n\n const rulesEngine = createRulesEngine();\n const result: AnyData = {};\n\n for (const [attrName, attrDef] of Object.entries(schema.attributes)) {\n const fullPath = [...path, attrName].join('.');\n const condition = attrDef?.conditions?.visible;\n const isVisible = condition ? rulesEngine.evaluate(condition, { ...data, ...result }) : true;\n\n if (!isVisible) {\n removedAttributes.push(fullPath);\n continue;\n }\n\n const userProvided = Object.prototype.hasOwnProperty.call(data, attrName);\n const currentValue = userProvided ? data[attrName] : undefined;\n const initialValue = initialValues?.[attrName];\n\n // 🔹 Handle components\n if (attrDef.type === 'component') {\n const compSchema = components[attrDef.component];\n const value = currentValue ?? initialValue;\n\n if (!value) {\n result[attrName] = attrDef.repeatable ? [] : null;\n continue;\n }\n\n if (attrDef.repeatable && Array.isArray(value)) {\n result[attrName] = value.map(\n (item, index) =>\n handleInvisibleAttributes(\n item,\n {\n schema: compSchema,\n initialValues: initialValue?.[index] ?? {},\n components,\n },\n [...path, `${attrName}[${index}]`],\n removedAttributes\n ).data\n );\n } else {\n result[attrName] = handleInvisibleAttributes(\n value,\n {\n schema: compSchema,\n initialValues: initialValue ?? {},\n components,\n },\n [...path, attrName],\n removedAttributes\n ).data;\n }\n\n continue;\n }\n\n // 🔸 Handle dynamic zones\n if (attrDef.type === 'dynamiczone') {\n if (!Array.isArray(currentValue)) {\n result[attrName] = [];\n continue;\n }\n\n result[attrName] = currentValue.map((dzItem, index) => {\n const compUID = dzItem?.__component;\n const compSchema = components[compUID];\n\n const cleaned = handleInvisibleAttributes(\n dzItem,\n {\n schema: compSchema,\n initialValues: initialValue?.[index] ?? {},\n components,\n },\n [...path, `${attrName}[${index}]`],\n removedAttributes\n ).data;\n\n return {\n __component: compUID,\n ...cleaned,\n };\n });\n\n continue;\n }\n\n // 🟡 Handle scalar/primitive\n if (currentValue !== undefined) {\n result[attrName] = currentValue;\n } else if (initialValue !== undefined) {\n result[attrName] = initialValue;\n } else {\n if (attrName === 'id' || attrName === 'documentId') {\n // If the attribute is 'id', we don't want to set it to null, as it should not be removed.\n continue;\n }\n result[attrName] = null;\n }\n }\n\n return {\n data: result,\n removedAttributes,\n };\n};\n\nexport {\n removeProhibitedFields,\n prepareRelations,\n prepareTempKeys,\n removeFieldsThatDontExistOnSchema,\n transformDocument,\n handleInvisibleAttributes,\n};\nexport type { AnyData };\n"],"names":["BLOCK_LIST_ATTRIBUTE_KEYS","traverseData","predicate","transform","schema","components","data","traverse","datum","attributes","Object","entries","reduce","acc","key","value","attribute","includes","undefined","type","repeatable","componentValue","map","componentData","component","dynamicZoneValue","__component","removeProhibitedFields","prohibitedFields","prepareRelations","connect","disconnect","prepareTempKeys","Array","isArray","length","keys","generateNKeysBetween","index","__temp_key__","removeFieldsThatDontExistOnSchema","schemaKeys","dataKeys","keysToRemove","filter","revisedData","DOCUMENT_META_FIELDS","structuredClone","removeNullValues","transformDocument","document","transformations","pipe","handleInvisibleAttributes","initialValues","path","removedAttributes","rulesEngine","createRulesEngine","result","attrName","attrDef","fullPath","join","condition","conditions","visible","isVisible","evaluate","push","userProvided","prototype","hasOwnProperty","call","currentValue","initialValue","compSchema","item","dzItem","compUID","cleaned"],"mappings":";;;;;;;AA0BA,MAAMA,yBAA4B,GAAA;AAAC,IAAA,aAAA;AAAe,IAAA;AAAe,CAAA;AAEjE;;;;;;;;;;AAUC,IACD,MAAMC,YAAAA,GACJ,CAACC,SAAAA,EAAsBC,YACvB,CAACC,MAAAA,EAAuBC,UAAmC,GAAA,EAAE,GAC7D,CAACC,IAAAA,GAAgB,EAAE,GAAA;YACjB,MAAMC,QAAAA,GAAW,CAACC,KAAgBC,EAAAA,UAAAA,GAAAA;gBAChC,OAAOC,MAAAA,CAAOC,OAAO,CAACH,KAAOI,CAAAA,CAAAA,MAAM,CAAU,CAACC,GAAAA,EAAK,CAACC,GAAAA,EAAKC,KAAM,CAAA,GAAA;oBAC7D,MAAMC,SAAAA,GAAYP,UAAU,CAACK,GAAI,CAAA;AAEjC;;;YAIA,IAAId,0BAA0BiB,QAAQ,CAACH,QAAQC,KAAU,KAAA,IAAA,IAAQA,UAAUG,SAAW,EAAA;wBACpFL,GAAG,CAACC,IAAI,GAAGC,KAAAA;wBACX,OAAOF,GAAAA;AACT;oBAEA,IAAIG,SAAAA,CAAUG,IAAI,KAAK,WAAa,EAAA;wBAClC,IAAIH,SAAAA,CAAUI,UAAU,EAAE;AACxB,4BAAA,MAAMC,iBACJnB,SAAUc,CAAAA,SAAAA,EAAWD,KAASZ,CAAAA,GAAAA,SA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AEAD,YAAAA,MAAM,CAACC,QAAS,CAAA,GAAGc,aAAapD,GAAG,CAAC,CAACwD,MAAQxC,EAAAA,KAAAA,GAAAA;AAC3C,gBAAA,MAAMyC,UAAUD,MAAQpD,EAAAA,WAAAA;gBACxB,MAAMkD,UAAAA,GAAavE,UAAU,CAAC0E,OAAQ,CAAA;gBAEtC,MAAMC,OAAAA,GAAU3B,0BACdyB,MACA,EAAA;oBACE1E,MAAQwE,EAAAA,UAAAA;AACRtB,oBAAAA,aAAAA,EAAeqB,YAAc,GAACrC,KAAM,CAAA,IAAI,EAAC;AACzCjC,oBAAAA;iBAEF,EAAA;AAAIkD,oBAAAA,GAAAA,IAAAA;AAAM,oBAAA,CAAC,EAAEK,QAAS,CAAA,CAAC,EAAEtB,KAAAA,CAAM,CAAC;AAAE,iBAAA,EAClCkB,mBACAlD,IAAI;gBAEN,OAAO;oBACLoB,WAAaqD,EAAAA,OAAAA;AACb,oBAAA,GAAGC;AACL,iBAAA;AACF,aAAA,CAAA;AAEA,YAAA;AACF;;AAGA,QAAA,IAAIN,iBAAiBxD,SAAW,EAAA;YAC9ByC,MAAM,CAACC,SAAS,GAAGc,YAAAA;SACd,MAAA,IAAIC,iBAAiBzD,SAAW,EAAA;YACrCyC,MAAM,CAACC,SAAS,GAAGe,YAAAA;SACd,MAAA;YACL,IAAIf,QAAAA,KAAa,IAAQA,IAAAA,QAAAA,KAAa,YAAc,EAAA;AAElD,gBAAA;AACF;YACAD,MAAM,CAACC,SAAS,GAAG,IAAA;AACrB;AACF;IAEA,OAAO;QACLtD,IAAMqD,EAAAA,MAAAA;AACNH,QAAAA;AACF,KAAA;AACF;;;;;;;;;"}
@@ -1,3 +1,4 @@
1
+ import { createRulesEngine } from '@strapi/admin/strapi-admin';
1
2
  import { generateNKeysBetween } from 'fractional-indexing';
2
3
  import pipe from 'lodash/fp/pipe';
3
4
  import { DOCUMENT_META_FIELDS } from '../../../constants/attributes.mjs';
@@ -124,6 +125,107 @@ const BLOCK_LIST_ATTRIBUTE_KEYS = [
124
125
  ])(schema, components), removeNullValues, prepareRelations(schema, components), prepareTempKeys(schema, components));
125
126
  return transformations(document);
126
127
  };
128
+ /**
129
+ * Removes values from the data object if their corresponding attribute has a
130
+ * visibility condition that evaluates to false.
131
+ *
132
+ * @param {object} schema - The content type schema (with attributes).
133
+ * @param {object} data - The data object to filter based on visibility.
134
+ * @returns {object} A new data object with only visible fields retained.
135
+ */ const handleInvisibleAttributes = (data, { schema, initialValues = {}, components = {} }, path = [], removedAttributes = [])=>{
136
+ if (!schema?.attributes) return {
137
+ data,
138
+ removedAttributes
139
+ };
140
+ const rulesEngine = createRulesEngine();
141
+ const result = {};
142
+ for (const [attrName, attrDef] of Object.entries(schema.attributes)){
143
+ const fullPath = [
144
+ ...path,
145
+ attrName
146
+ ].join('.');
147
+ const condition = attrDef?.conditions?.visible;
148
+ const isVisible = condition ? rulesEngine.evaluate(condition, {
149
+ ...data,
150
+ ...result
151
+ }) : true;
152
+ if (!isVisible) {
153
+ removedAttributes.push(fullPath);
154
+ continue;
155
+ }
156
+ const userProvided = Object.prototype.hasOwnProperty.call(data, attrName);
157
+ const currentValue = userProvided ? data[attrName] : undefined;
158
+ const initialValue = initialValues?.[attrName];
159
+ // 🔹 Handle components
160
+ if (attrDef.type === 'component') {
161
+ const compSchema = components[attrDef.component];
162
+ const value = currentValue ?? initialValue;
163
+ if (!value) {
164
+ result[attrName] = attrDef.repeatable ? [] : null;
165
+ continue;
166
+ }
167
+ if (attrDef.repeatable && Array.isArray(value)) {
168
+ result[attrName] = value.map((item, index)=>handleInvisibleAttributes(item, {
169
+ schema: compSchema,
170
+ initialValues: initialValue?.[index] ?? {},
171
+ components
172
+ }, [
173
+ ...path,
174
+ `${attrName}[${index}]`
175
+ ], removedAttributes).data);
176
+ } else {
177
+ result[attrName] = handleInvisibleAttributes(value, {
178
+ schema: compSchema,
179
+ initialValues: initialValue ?? {},
180
+ components
181
+ }, [
182
+ ...path,
183
+ attrName
184
+ ], removedAttributes).data;
185
+ }
186
+ continue;
187
+ }
188
+ // 🔸 Handle dynamic zones
189
+ if (attrDef.type === 'dynamiczone') {
190
+ if (!Array.isArray(currentValue)) {
191
+ result[attrName] = [];
192
+ continue;
193
+ }
194
+ result[attrName] = currentValue.map((dzItem, index)=>{
195
+ const compUID = dzItem?.__component;
196
+ const compSchema = components[compUID];
197
+ const cleaned = handleInvisibleAttributes(dzItem, {
198
+ schema: compSchema,
199
+ initialValues: initialValue?.[index] ?? {},
200
+ components
201
+ }, [
202
+ ...path,
203
+ `${attrName}[${index}]`
204
+ ], removedAttributes).data;
205
+ return {
206
+ __component: compUID,
207
+ ...cleaned
208
+ };
209
+ });
210
+ continue;
211
+ }
212
+ // 🟡 Handle scalar/primitive
213
+ if (currentValue !== undefined) {
214
+ result[attrName] = currentValue;
215
+ } else if (initialValue !== undefined) {
216
+ result[attrName] = initialValue;
217
+ } else {
218
+ if (attrName === 'id' || attrName === 'documentId') {
219
+ continue;
220
+ }
221
+ result[attrName] = null;
222
+ }
223
+ }
224
+ return {
225
+ data: result,
226
+ removedAttributes
227
+ };
228
+ };
127
229
 
128
- export { prepareRelations, prepareTempKeys, removeFieldsThatDontExistOnSchema, removeProhibitedFields, transformDocument };
230
+ export { handleInvisibleAttributes, prepareRelations, prepareTempKeys, removeFieldsThatDontExistOnSchema, removeProhibitedFields, transformDocument };
129
231
  //# sourceMappingURL=data.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"data.mjs","sources":["../../../../../admin/src/pages/EditView/utils/data.ts"],"sourcesContent":["import { generateNKeysBetween } from 'fractional-indexing';\nimport pipe from 'lodash/fp/pipe';\n\nimport { DOCUMENT_META_FIELDS } from '../../../constants/attributes';\n\nimport type { ComponentsDictionary, Document } from '../../../hooks/useDocument';\nimport type { Schema, UID } from '@strapi/types';\n\n/* -------------------------------------------------------------------------------------------------\n * traverseData\n * -----------------------------------------------------------------------------------------------*/\n\n// Make only attributes required since it's the only one Content History has\ntype PartialSchema = Partial<Schema.Schema> & Pick<Schema.Schema, 'attributes'>;\n\ntype Predicate = <TAttribute extends Schema.Attribute.AnyAttribute>(\n attribute: TAttribute,\n value: Schema.Attribute.Value<TAttribute>\n) => boolean;\ntype Transform = <TAttribute extends Schema.Attribute.AnyAttribute>(\n value: any,\n attribute: TAttribute\n) => any;\ntype AnyData = Omit<Document, 'id'>;\n\nconst BLOCK_LIST_ATTRIBUTE_KEYS = ['__component', '__temp_key__'];\n\n/**\n * @internal This function is used to traverse the data and transform the values.\n * Given a predicate function, it will transform the value (using the given transform function)\n * if the predicate returns true. If it finds that the attribute is a component or dynamiczone,\n * it will recursively traverse those data structures as well.\n *\n * It is possible to break the ContentManager by using this function incorrectly, for example,\n * if you transform a number into a string but the attribute type is a number, the ContentManager\n * will not be able to save the data and the Form will likely crash because the component it's\n * passing the data too won't succesfully be able to handle the value.\n */\nconst traverseData =\n (predicate: Predicate, transform: Transform) =>\n (schema: PartialSchema, components: ComponentsDictionary = {}) =>\n (data: AnyData = {}) => {\n const traverse = (datum: AnyData, attributes: Schema.Schema['attributes']) => {\n return Object.entries(datum).reduce<AnyData>((acc, [key, value]) => {\n const attribute = attributes[key];\n\n /**\n * If the attribute is a block list attribute, we don't want to transform it.\n * We also don't want to transform null or undefined values.\n */\n if (BLOCK_LIST_ATTRIBUTE_KEYS.includes(key) || value === null || value === undefined) {\n acc[key] = value;\n return acc;\n }\n\n if (attribute.type === 'component') {\n if (attribute.repeatable) {\n const componentValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n acc[key] = componentValue.map((componentData) =>\n traverse(componentData, components[attribute.component]?.attributes ?? {})\n );\n } else {\n const componentValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, false>>;\n\n acc[key] = traverse(componentValue, components[attribute.component]?.attributes ?? {});\n }\n } else if (attribute.type === 'dynamiczone') {\n const dynamicZoneValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n acc[key] = dynamicZoneValue.map((componentData) =>\n traverse(componentData, components[componentData.__component]?.attributes ?? {})\n );\n } else if (predicate(attribute, value)) {\n acc[key] = transform(value, attribute);\n } else {\n acc[key] = value;\n }\n\n return acc;\n }, {});\n };\n\n return traverse(data, schema.attributes);\n };\n\n/* -------------------------------------------------------------------------------------------------\n * removeProhibitedFields\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal Removes all the fields that are not allowed.\n */\nconst removeProhibitedFields = (prohibitedFields: Schema.Attribute.Kind[]) =>\n traverseData(\n (attribute) => prohibitedFields.includes(attribute.type),\n () => ''\n );\n\n/* -------------------------------------------------------------------------------------------------\n * prepareRelations\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Sets all relation values to an empty array.\n */\nconst prepareRelations = traverseData(\n (attribute) => attribute.type === 'relation',\n () => ({\n connect: [],\n disconnect: [],\n })\n);\n\n/* -------------------------------------------------------------------------------------------------\n * prepareTempKeys\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Adds a `__temp_key__` to each component and dynamiczone item. This gives us\n * a stable identifier regardless of its ids etc. that we can then use for drag and drop.\n */\nconst prepareTempKeys = traverseData(\n (attribute) =>\n (attribute.type === 'component' && attribute.repeatable) || attribute.type === 'dynamiczone',\n (data) => {\n if (Array.isArray(data) && data.length > 0) {\n const keys = generateNKeysBetween(undefined, undefined, data.length);\n\n return data.map((datum, index) => ({\n ...datum,\n __temp_key__: keys[index],\n }));\n }\n\n return data;\n }\n);\n\n/* -------------------------------------------------------------------------------------------------\n * removeFieldsThatDontExistOnSchema\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Fields that don't exist in the schema like createdAt etc. are only on the first level (not nested),\n * as such we don't need to traverse the components to remove them.\n */\nconst removeFieldsThatDontExistOnSchema = (schema: PartialSchema) => (data: AnyData) => {\n const schemaKeys = Object.keys(schema.attributes);\n const dataKeys = Object.keys(data);\n\n const keysToRemove = dataKeys.filter((key) => !schemaKeys.includes(key));\n\n const revisedData = [...keysToRemove, ...DOCUMENT_META_FIELDS].reduce((acc, key) => {\n delete acc[key];\n\n return acc;\n }, structuredClone(data));\n\n return revisedData;\n};\n\n/**\n * @internal\n * @description We need to remove null fields from the data-structure because it will pass it\n * to the specific inputs breaking them as most would prefer empty strings or `undefined` if\n * they're controlled / uncontrolled.\n */\nconst removeNullValues = (data: AnyData) => {\n return Object.entries(data).reduce<AnyData>((acc, [key, value]) => {\n if (value === null) {\n return acc;\n }\n\n acc[key] = value;\n\n return acc;\n }, {});\n};\n\n/* -------------------------------------------------------------------------------------------------\n * transformDocuments\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Takes a document data structure (this could be from the API or a default form structure)\n * and applies consistent data transformations to it. This is also used when we add new components to the\n * form to ensure the data is correctly prepared from their default state e.g. relations are set to an empty array.\n */\nconst transformDocument =\n (schema: PartialSchema, components: ComponentsDictionary = {}) =>\n (document: AnyData) => {\n const transformations = pipe(\n removeFieldsThatDontExistOnSchema(schema),\n removeProhibitedFields(['password'])(schema, components),\n removeNullValues,\n prepareRelations(schema, components),\n prepareTempKeys(schema, components)\n );\n\n return transformations(document);\n };\n\nexport {\n removeProhibitedFields,\n prepareRelations,\n prepareTempKeys,\n removeFieldsThatDontExistOnSchema,\n transformDocument,\n};\nexport type { AnyData };\n"],"names":["BLOCK_LIST_ATTRIBUTE_KEYS","traverseData","predicate","transform","schema","components","data","traverse","datum","attributes","Object","entries","reduce","acc","key","value","attribute","includes","undefined","type","repeatable","componentValue","map","componentData","component","dynamicZoneValue","__component","removeProhibitedFields","prohibitedFields","prepareRelations","connect","disconnect","prepareTempKeys","Array","isArray","length","keys","generateNKeysBetween","index","__temp_key__","removeFieldsThatDontExistOnSchema","schemaKeys","dataKeys","keysToRemove","filter","revisedData","DOCUMENT_META_FIELDS","structuredClone","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AAA,CAAAA,CAAAA;QAEnB,OAAOuC,WAAAA;AACT;AAEA;;;;;IAMA,MAAMG,mBAAmB,CAAC1C,IAAAA,GAAAA;IACxB,OAAOI,MAAAA,CAAOC,OAAO,CAACL,IAAMM,CAAAA,CAAAA,MAAM,CAAU,CAACC,GAAAA,EAAK,CAACC,GAAAA,EAAKC,KAAM,CAAA,GAAA;AAC5D,QAAA,IAAIA,UAAU,IAAM,EAAA;YAClB,OAAOF,GAAAA;AACT;QAEAA,GAAG,CAACC,IAAI,GAAGC,KAAAA;QAEX,OAAOF,GAAAA;AACT,KAAA,EAAG,EAAC,CAAA;AACN,CAAA;AAEA;;;;;;;IAUA,MAAMoC,oBACJ,CAAC7C,MAAAA,EAAuBC,aAAmC,EAAE,GAC7D,CAAC6C,QAAAA,GAAAA;AACC,QAAA,MAAMC,eAAkBC,GAAAA,IAAAA,CACtBZ,iCAAkCpC,CAAAA,MAAAA,CAAAA,EAClCuB,sBAAuB,CAAA;AAAC,YAAA;AAAW,SAAA,CAAA,CAAEvB,QAAQC,UAC7C2C,CAAAA,EAAAA,gBAAAA,EACAnB,iBAAiBzB,MAAQC,EAAAA,UAAAA,CAAAA,EACzB2B,gBAAgB5B,MAAQC,EAAAA,UAAAA,CAAAA,CAAAA;AAG1B,QAAA,OAAO8C,eAAgBD,CAAAA,QAAAA,CAAAA;AACzB;;;;"}
1
+ {"version":3,"file":"data.mjs","sources":["../../../../../admin/src/pages/EditView/utils/data.ts"],"sourcesContent":["import { createRulesEngine } from '@strapi/admin/strapi-admin';\nimport { generateNKeysBetween } from 'fractional-indexing';\nimport pipe from 'lodash/fp/pipe';\n\nimport { DOCUMENT_META_FIELDS } from '../../../constants/attributes';\n\nimport type { ComponentsDictionary, Document } from '../../../hooks/useDocument';\nimport type { Schema, UID } from '@strapi/types';\n\n/* -------------------------------------------------------------------------------------------------\n * traverseData\n * -----------------------------------------------------------------------------------------------*/\n\n// Make only attributes required since it's the only one Content History has\ntype PartialSchema = Partial<Schema.Schema> & Pick<Schema.Schema, 'attributes'>;\n\ntype Predicate = <TAttribute extends Schema.Attribute.AnyAttribute>(\n attribute: TAttribute,\n value: Schema.Attribute.Value<TAttribute>\n) => boolean;\ntype Transform = <TAttribute extends Schema.Attribute.AnyAttribute>(\n value: any,\n attribute: TAttribute\n) => any;\ntype AnyData = Omit<Document, 'id'>;\n\nconst BLOCK_LIST_ATTRIBUTE_KEYS = ['__component', '__temp_key__'];\n\n/**\n * @internal This function is used to traverse the data and transform the values.\n * Given a predicate function, it will transform the value (using the given transform function)\n * if the predicate returns true. If it finds that the attribute is a component or dynamiczone,\n * it will recursively traverse those data structures as well.\n *\n * It is possible to break the ContentManager by using this function incorrectly, for example,\n * if you transform a number into a string but the attribute type is a number, the ContentManager\n * will not be able to save the data and the Form will likely crash because the component it's\n * passing the data too won't succesfully be able to handle the value.\n */\nconst traverseData =\n (predicate: Predicate, transform: Transform) =>\n (schema: PartialSchema, components: ComponentsDictionary = {}) =>\n (data: AnyData = {}) => {\n const traverse = (datum: AnyData, attributes: Schema.Schema['attributes']) => {\n return Object.entries(datum).reduce<AnyData>((acc, [key, value]) => {\n const attribute = attributes[key];\n\n /**\n * If the attribute is a block list attribute, we don't want to transform it.\n * We also don't want to transform null or undefined values.\n */\n if (BLOCK_LIST_ATTRIBUTE_KEYS.includes(key) || value === null || value === undefined) {\n acc[key] = value;\n return acc;\n }\n\n if (attribute.type === 'component') {\n if (attribute.repeatable) {\n const componentValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n acc[key] = componentValue.map((componentData) =>\n traverse(componentData, components[attribute.component]?.attributes ?? {})\n );\n } else {\n const componentValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, false>>;\n\n acc[key] = traverse(componentValue, components[attribute.component]?.attributes ?? {});\n }\n } else if (attribute.type === 'dynamiczone') {\n const dynamicZoneValue = (\n predicate(attribute, value) ? transform(value, attribute) : value\n ) as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n acc[key] = dynamicZoneValue.map((componentData) =>\n traverse(componentData, components[componentData.__component]?.attributes ?? {})\n );\n } else if (predicate(attribute, value)) {\n acc[key] = transform(value, attribute);\n } else {\n acc[key] = value;\n }\n\n return acc;\n }, {});\n };\n\n return traverse(data, schema.attributes);\n };\n\n/* -------------------------------------------------------------------------------------------------\n * removeProhibitedFields\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal Removes all the fields that are not allowed.\n */\nconst removeProhibitedFields = (prohibitedFields: Schema.Attribute.Kind[]) =>\n traverseData(\n (attribute) => prohibitedFields.includes(attribute.type),\n () => ''\n );\n\n/* -------------------------------------------------------------------------------------------------\n * prepareRelations\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Sets all relation values to an empty array.\n */\nconst prepareRelations = traverseData(\n (attribute) => attribute.type === 'relation',\n () => ({\n connect: [],\n disconnect: [],\n })\n);\n\n/* -------------------------------------------------------------------------------------------------\n * prepareTempKeys\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Adds a `__temp_key__` to each component and dynamiczone item. This gives us\n * a stable identifier regardless of its ids etc. that we can then use for drag and drop.\n */\nconst prepareTempKeys = traverseData(\n (attribute) =>\n (attribute.type === 'component' && attribute.repeatable) || attribute.type === 'dynamiczone',\n (data) => {\n if (Array.isArray(data) && data.length > 0) {\n const keys = generateNKeysBetween(undefined, undefined, data.length);\n\n return data.map((datum, index) => ({\n ...datum,\n __temp_key__: keys[index],\n }));\n }\n\n return data;\n }\n);\n\n/* -------------------------------------------------------------------------------------------------\n * removeFieldsThatDontExistOnSchema\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Fields that don't exist in the schema like createdAt etc. are only on the first level (not nested),\n * as such we don't need to traverse the components to remove them.\n */\nconst removeFieldsThatDontExistOnSchema = (schema: PartialSchema) => (data: AnyData) => {\n const schemaKeys = Object.keys(schema.attributes);\n const dataKeys = Object.keys(data);\n\n const keysToRemove = dataKeys.filter((key) => !schemaKeys.includes(key));\n\n const revisedData = [...keysToRemove, ...DOCUMENT_META_FIELDS].reduce((acc, key) => {\n delete acc[key];\n\n return acc;\n }, structuredClone(data));\n\n return revisedData;\n};\n\n/**\n * @internal\n * @description We need to remove null fields from the data-structure because it will pass it\n * to the specific inputs breaking them as most would prefer empty strings or `undefined` if\n * they're controlled / uncontrolled.\n */\nconst removeNullValues = (data: AnyData) => {\n return Object.entries(data).reduce<AnyData>((acc, [key, value]) => {\n if (value === null) {\n return acc;\n }\n\n acc[key] = value;\n\n return acc;\n }, {});\n};\n\n/* -------------------------------------------------------------------------------------------------\n * transformDocuments\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * @internal\n * @description Takes a document data structure (this could be from the API or a default form structure)\n * and applies consistent data transformations to it. This is also used when we add new components to the\n * form to ensure the data is correctly prepared from their default state e.g. relations are set to an empty array.\n */\nconst transformDocument =\n (schema: PartialSchema, components: ComponentsDictionary = {}) =>\n (document: AnyData) => {\n const transformations = pipe(\n removeFieldsThatDontExistOnSchema(schema),\n removeProhibitedFields(['password'])(schema, components),\n removeNullValues,\n prepareRelations(schema, components),\n prepareTempKeys(schema, components)\n );\n\n return transformations(document);\n };\n\ntype HandleOptions = {\n schema?: Schema.ContentType | Schema.Component;\n initialValues?: AnyData;\n components?: Record<string, Schema.Component>;\n};\n\ntype RemovedFieldPath = string;\n\n/**\n * Removes values from the data object if their corresponding attribute has a\n * visibility condition that evaluates to false.\n *\n * @param {object} schema - The content type schema (with attributes).\n * @param {object} data - The data object to filter based on visibility.\n * @returns {object} A new data object with only visible fields retained.\n */\nconst handleInvisibleAttributes = (\n data: AnyData,\n { schema, initialValues = {}, components = {} }: HandleOptions,\n path: string[] = [],\n removedAttributes: RemovedFieldPath[] = []\n): {\n data: AnyData;\n removedAttributes: RemovedFieldPath[];\n} => {\n if (!schema?.attributes) return { data, removedAttributes };\n\n const rulesEngine = createRulesEngine();\n const result: AnyData = {};\n\n for (const [attrName, attrDef] of Object.entries(schema.attributes)) {\n const fullPath = [...path, attrName].join('.');\n const condition = attrDef?.conditions?.visible;\n const isVisible = condition ? rulesEngine.evaluate(condition, { ...data, ...result }) : true;\n\n if (!isVisible) {\n removedAttributes.push(fullPath);\n continue;\n }\n\n const userProvided = Object.prototype.hasOwnProperty.call(data, attrName);\n const currentValue = userProvided ? data[attrName] : undefined;\n const initialValue = initialValues?.[attrName];\n\n // 🔹 Handle components\n if (attrDef.type === 'component') {\n const compSchema = components[attrDef.component];\n const value = currentValue ?? initialValue;\n\n if (!value) {\n result[attrName] = attrDef.repeatable ? [] : null;\n continue;\n }\n\n if (attrDef.repeatable && Array.isArray(value)) {\n result[attrName] = value.map(\n (item, index) =>\n handleInvisibleAttributes(\n item,\n {\n schema: compSchema,\n initialValues: initialValue?.[index] ?? {},\n components,\n },\n [...path, `${attrName}[${index}]`],\n removedAttributes\n ).data\n );\n } else {\n result[attrName] = handleInvisibleAttributes(\n value,\n {\n schema: compSchema,\n initialValues: initialValue ?? {},\n components,\n },\n [...path, attrName],\n removedAttributes\n ).data;\n }\n\n continue;\n }\n\n // 🔸 Handle dynamic zones\n if (attrDef.type === 'dynamiczone') {\n if (!Array.isArray(currentValue)) {\n result[attrName] = [];\n continue;\n }\n\n result[attrName] = currentValue.map((dzItem, index) => {\n const compUID = dzItem?.__component;\n const compSchema = components[compUID];\n\n const cleaned = handleInvisibleAttributes(\n dzItem,\n {\n schema: compSchema,\n initialValues: initialValue?.[index] ?? {},\n components,\n },\n [...path, `${attrName}[${index}]`],\n removedAttributes\n ).data;\n\n return {\n __component: compUID,\n ...cleaned,\n };\n });\n\n continue;\n }\n\n // 🟡 Handle scalar/primitive\n if (currentValue !== undefined) {\n result[attrName] = currentValue;\n } else if (initialValue !== undefined) {\n result[attrName] = initialValue;\n } else {\n if (attrName === 'id' || attrName === 'documentId') {\n // If the attribute is 'id', we don't want to set it to null, as it should not be removed.\n continue;\n }\n result[attrName] = null;\n }\n }\n\n return {\n data: result,\n removedAttributes,\n };\n};\n\nexport {\n removeProhibitedFields,\n prepareRelations,\n prepareTempKeys,\n removeFieldsThatDontExistOnSchema,\n transformDocument,\n handleInvisibleAttributes,\n};\nexport type { AnyData };\n"],"names":["BLOCK_LIST_ATTRIBUTE_KEYS","traverseData","predicate","transform","schema","components","data","traverse","datum","attributes","Object","entries","reduce","acc","key","value","attribute","includes","undefined","type","repeatable","componentValue","map","componentData","component","dynamicZoneValue","__component","removeProhibitedFields","prohibitedFields","prepareRelations","connect","disconnect","prepareTempKeys","Array","isArray","length","keys","generateNKeysBetween","index","__temp_key__","removeFieldsThatDontExistOnSchema","schemaKeys","dataKeys","keysToRemove","filter","revisedData","DOCUMENT_META_FIELDS","structuredClone","removeNullValues","transformDocument","document","transformations","pipe","handleInvisibleAttributes","initialValues","path","removedAttributes","rulesEngine","createRulesEngine","result","attrName","attrDef","fullPath","join","condition","conditions","visible","isVisible","evaluate","push","userProvided","prototype","hasOwnProperty","call","currentValue","initialValue","compSchema","item","dzItem","compUID","cleaned"],"mappings":";;;;;AA0BA,MAAMA,yBAA4B,GAAA;AAAC,IAAA,aAAA;AAAe,IAAA;AAAe,CAAA;AAEjE;;;;;;;;;;AAUC,IACD,MAAMC,YAAAA,GACJ,CAACC,SAAAA,EAAsBC,YACvB,CAACC,MAAAA,EAAuBC,UAAmC,GAAA,EAAE,GAC7D,CAACC,IAAAA,GAAgB,EAAE,GAAA;YACjB,MAAMC,QAAAA,GAAW,CAACC,KAAgBC,EAAAA,UAAAA,GAAAA;gBAChC,OAAOC,MAAAA,CAAOC,OAAO,CAACH,KAAOI,CAAAA,CAAAA,MAAM,CAAU,CAACC,GAAAA,EAAK,CAACC,GAAAA,EAAKC,KAAM,CAAA,GAAA;oBAC7D,MAAMC,SAAAA,GAAYP,UAAU,CAACK,GAAI,CAAA;AAEjC;;;YAIA,IAAId,0BAA0BiB,QAAQ,CAACH,QAA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B;AACF;IAEA,OAAO;QACLtD,IAAMqD,EAAAA,MAAAA;AACNH,QAAAA;AACF,KAAA;AACF;;;;"}
@@ -30,5 +30,23 @@ declare const removeFieldsThatDontExistOnSchema: (schema: PartialSchema) => (dat
30
30
  * form to ensure the data is correctly prepared from their default state e.g. relations are set to an empty array.
31
31
  */
32
32
  declare const transformDocument: (schema: PartialSchema, components?: ComponentsDictionary) => (document: AnyData) => AnyData;
33
- export { removeProhibitedFields, prepareRelations, prepareTempKeys, removeFieldsThatDontExistOnSchema, transformDocument, };
33
+ type HandleOptions = {
34
+ schema?: Schema.ContentType | Schema.Component;
35
+ initialValues?: AnyData;
36
+ components?: Record<string, Schema.Component>;
37
+ };
38
+ type RemovedFieldPath = string;
39
+ /**
40
+ * Removes values from the data object if their corresponding attribute has a
41
+ * visibility condition that evaluates to false.
42
+ *
43
+ * @param {object} schema - The content type schema (with attributes).
44
+ * @param {object} data - The data object to filter based on visibility.
45
+ * @returns {object} A new data object with only visible fields retained.
46
+ */
47
+ declare const handleInvisibleAttributes: (data: AnyData, { schema, initialValues, components }: HandleOptions, path?: string[], removedAttributes?: RemovedFieldPath[]) => {
48
+ data: AnyData;
49
+ removedAttributes: RemovedFieldPath[];
50
+ };
51
+ export { removeProhibitedFields, prepareRelations, prepareTempKeys, removeFieldsThatDontExistOnSchema, transformDocument, handleInvisibleAttributes, };
34
52
  export type { AnyData };
@@ -2,6 +2,7 @@ import * as yup from 'yup';
2
2
  import type { ComponentsDictionary, Schema } from '../hooks/useDocument';
3
3
  interface ValidationOptions {
4
4
  status: 'draft' | 'published' | null;
5
+ removedAttributes?: string[];
5
6
  }
6
7
  /**
7
8
  * TODO: should we create a Map to store these based on the hash of the schema?
@@ -42,15 +42,26 @@ const arrayValidator = (attribute, options)=>({
42
42
  return true;
43
43
  }
44
44
  });
45
+ const escapeRegex = (str)=>str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
45
46
  /**
46
47
  * TODO: should we create a Map to store these based on the hash of the schema?
47
48
  */ const createYupSchema = (attributes$1 = {}, components = {}, options = {
48
49
  status: null
49
50
  })=>{
50
- const createModelSchema = (attributes$1)=>yup__namespace.object().shape(Object.entries(attributes$1).reduce((acc, [name, attribute])=>{
51
+ const createModelSchema = (attributes$1, removedAttributes = [])=>yup__namespace.object().shape(Object.entries(attributes$1).reduce((acc, [name, attribute])=>{
52
+ const getNestedPathsForAttribute = (removed, attrName)=>{
53
+ const prefix = `${attrName}.`;
54
+ const bracketRegex = new RegExp(`^${escapeRegex(attrName)}\\[\\d+\\]\\.`);
55
+ return removed.filter((p)=>p.startsWith(prefix) || bracketRegex.test(p)).map((p)=>p.startsWith(prefix) ? p.slice(prefix.length) : p.replace(bracketRegex, ''));
56
+ };
51
57
  if (attributes.DOCUMENT_META_FIELDS.includes(name)) {
52
58
  return acc;
53
59
  }
60
+ if (removedAttributes?.includes(name)) {
61
+ // If the attribute is not visible, we don't want to validate it
62
+ return acc;
63
+ }
64
+ const nestedRemoved = getNestedPathsForAttribute(removedAttributes, name);
54
65
  /**
55
66
  * These validations won't apply to every attribute
56
67
  * and that's okay, in that case we just return the
@@ -72,12 +83,12 @@ const arrayValidator = (attribute, options)=>({
72
83
  if (attribute.repeatable) {
73
84
  return {
74
85
  ...acc,
75
- [name]: transformSchema(yup__namespace.array().of(createModelSchema(attributes).nullable(false))).test(arrayValidator(attribute, options))
86
+ [name]: transformSchema(yup__namespace.array().of(createModelSchema(attributes, nestedRemoved).nullable(false))).test(arrayValidator(attribute, options))
76
87
  };
77
88
  } else {
78
89
  return {
79
90
  ...acc,
80
- [name]: transformSchema(createModelSchema(attributes).nullable())
91
+ [name]: transformSchema(createModelSchema(attributes, nestedRemoved).nullable())
81
92
  };
82
93
  }
83
94
  }
@@ -92,7 +103,7 @@ const arrayValidator = (attribute, options)=>({
92
103
  if (!attributes) {
93
104
  return validation;
94
105
  }
95
- return validation.concat(createModelSchema(attributes));
106
+ return validation.concat(createModelSchema(attributes, nestedRemoved));
96
107
  }))).test(arrayValidator(attribute, options))
97
108
  };
98
109
  case 'relation':
@@ -126,7 +137,7 @@ const arrayValidator = (attribute, options)=>({
126
137
  }, {}))/**
127
138
  * TODO: investigate why an undefined object fails a check of `nullable`.
128
139
  */ .default(null);
129
- return createModelSchema(attributes$1);
140
+ return createModelSchema(attributes$1, options.removedAttributes);
130
141
  };
131
142
  const createAttributeSchema = (attribute)=>{
132
143
  switch(attribute.type){
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","sources":["../../../admin/src/utils/validation.ts"],"sourcesContent":["import { translatedErrors } from '@strapi/admin/strapi-admin';\nimport pipe from 'lodash/fp/pipe';\nimport * as yup from 'yup';\n\nimport { DOCUMENT_META_FIELDS } from '../constants/attributes';\n\nimport type { ComponentsDictionary, Schema } from '../hooks/useDocument';\nimport type { Schema as SchemaUtils } from '@strapi/types';\nimport type { ObjectShape } from 'yup/lib/object';\n\ntype AnySchema =\n | yup.StringSchema\n | yup.NumberSchema\n | yup.BooleanSchema\n | yup.DateSchema\n | yup.ArraySchema<any>\n | yup.ObjectSchema<any>;\n\n/* -------------------------------------------------------------------------------------------------\n * createYupSchema\n * -----------------------------------------------------------------------------------------------*/\n\ninterface ValidationOptions {\n status: 'draft' | 'published' | null;\n}\n\nconst arrayValidator = (attribute: Schema['attributes'][string], options: ValidationOptions) => ({\n message: translatedErrors.required,\n test(value: unknown) {\n if (options.status === 'draft') {\n return true;\n }\n\n if (!attribute.required) {\n return true;\n }\n\n if (!value) {\n return false;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n\n return true;\n },\n});\n\n/**\n * TODO: should we create a Map to store these based on the hash of the schema?\n */\nconst createYupSchema = (\n attributes: Schema['attributes'] = {},\n components: ComponentsDictionary = {},\n options: ValidationOptions = { status: null }\n): yup.ObjectSchema<any> => {\n const createModelSchema = (attributes: Schema['attributes']): yup.ObjectSchema<any> =>\n yup\n .object()\n .shape(\n Object.entries(attributes).reduce<ObjectShape>((acc, [name, attribute]) => {\n if (DOCUMENT_META_FIELDS.includes(name)) {\n return acc;\n }\n\n /**\n * These validations won't apply to every attribute\n * and that's okay, in that case we just return the\n * schema as it was passed.\n */\n const validations = [\n addNullableValidation,\n addRequiredValidation,\n addMinLengthValidation,\n addMaxLengthValidation,\n addMinValidation,\n addMaxValidation,\n addRegexValidation,\n ].map((fn) => fn(attribute, options));\n\n const transformSchema = pipe(...validations);\n\n switch (attribute.type) {\n case 'component': {\n const { attributes } = components[attribute.component];\n\n if (attribute.repeatable) {\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(createModelSchema(attributes).nullable(false))\n ).test(arrayValidator(attribute, options)),\n };\n } else {\n return {\n ...acc,\n [name]: transformSchema(createModelSchema(attributes).nullable()),\n };\n }\n }\n case 'dynamiczone':\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(\n yup.lazy(\n (\n data: SchemaUtils.Attribute.Value<SchemaUtils.Attribute.DynamicZone>[number]\n ) => {\n const attributes = components?.[data?.__component]?.attributes;\n\n const validation = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(components)),\n })\n .nullable(false);\n if (!attributes) {\n return validation;\n }\n\n return validation.concat(createModelSchema(attributes));\n }\n ) as unknown as yup.ObjectSchema<any>\n )\n ).test(arrayValidator(attribute, options)),\n };\n case 'relation':\n return {\n ...acc,\n [name]: transformSchema(\n yup.lazy((value) => {\n if (!value) {\n return yup.mixed().nullable(true);\n } else if (Array.isArray(value)) {\n // If a relation value is an array, we expect\n // an array of objects with {id} properties, representing the related entities.\n return yup.array().of(\n yup.object().shape({\n id: yup.number().required(),\n })\n );\n } else if (typeof value === 'object') {\n // A realtion value can also be an object. Some API\n // repsonses return the number of entities in the relation\n // as { count: x }\n return yup.object();\n } else {\n return yup\n .mixed()\n .test(\n 'type-error',\n 'Relation values must be either null, an array of objects with {id} or an object.',\n () => false\n );\n }\n })\n ),\n };\n default:\n return {\n ...acc,\n [name]: transformSchema(createAttributeSchema(attribute)),\n };\n }\n }, {})\n )\n /**\n * TODO: investigate why an undefined object fails a check of `nullable`.\n */\n .default(null);\n\n return createModelSchema(attributes);\n};\n\nconst createAttributeSchema = (\n attribute: Exclude<\n SchemaUtils.Attribute.AnyAttribute,\n { type: 'dynamiczone' } | { type: 'component' } | { type: 'relation' }\n >\n) => {\n switch (attribute.type) {\n case 'biginteger':\n return yup.string().matches(/^-?\\d*$/);\n case 'boolean':\n return yup.boolean();\n case 'blocks':\n return yup.mixed().test('isBlocks', translatedErrors.json, (value) => {\n if (!value || Array.isArray(value)) {\n return true;\n } else {\n return false;\n }\n });\n case 'decimal':\n case 'float':\n case 'integer':\n return yup.number();\n case 'email':\n return yup.string().email(translatedErrors.email);\n case 'enumeration':\n return yup.string().oneOf([...attribute.enum, null]);\n case 'json':\n return yup.mixed().test('isJSON', translatedErrors.json, (value) => {\n /**\n * We don't want to validate the JSON field if it's empty.\n */\n if (!value || (typeof value === 'string' && value.length === 0)) {\n return true;\n }\n\n // If the value was created via content API and wasn't changed, then it's still an object\n if (typeof value === 'object') {\n try {\n JSON.stringify(value);\n return true;\n } catch (err) {\n return false;\n }\n }\n\n try {\n JSON.parse(value);\n\n return true;\n } catch (err) {\n return false;\n }\n });\n case 'password':\n case 'richtext':\n case 'string':\n case 'text':\n return yup.string();\n case 'uid':\n return yup\n .string()\n .matches(attribute.regex ? new RegExp(attribute.regex) : /^[A-Za-z0-9-_.~]*$/);\n default:\n /**\n * This allows any value.\n */\n return yup.mixed();\n }\n};\n\n// Helper function to return schema.nullable() if it exists, otherwise return schema\nconst nullableSchema = <TSchema extends AnySchema>(schema: TSchema) => {\n return schema?.nullable\n ? schema.nullable()\n : // In some cases '.nullable' will not be available on the schema.\n // e.g. when the schema has been built using yup.lazy (e.g. for relations).\n // In these cases we should just return the schema as it is.\n schema;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Validators\n * -----------------------------------------------------------------------------------------------*/\n/**\n * Our validator functions can be preped with the\n * attribute and then have the schema piped through them.\n */\ntype ValidationFn = (\n attribute: Schema['attributes'][string],\n options: ValidationOptions\n) => <TSchema extends AnySchema>(schema: TSchema) => TSchema;\n\nconst addNullableValidation: ValidationFn = () => (schema) => {\n return nullableSchema(schema);\n};\n\nconst addRequiredValidation: ValidationFn = (attribute, options) => (schema) => {\n if (options.status === 'draft' || !attribute.required) {\n return schema;\n }\n\n if (attribute.required && 'required' in schema) {\n return schema.required(translatedErrors.required);\n }\n\n return schema;\n};\n\nconst addMinLengthValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // Skip minLength validation for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if (\n 'minLength' in attribute &&\n attribute.minLength &&\n Number.isInteger(attribute.minLength) &&\n 'min' in schema\n ) {\n return schema.min(attribute.minLength, {\n ...translatedErrors.minLength,\n values: {\n min: attribute.minLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMaxLengthValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if (\n 'maxLength' in attribute &&\n attribute.maxLength &&\n Number.isInteger(attribute.maxLength) &&\n 'max' in schema\n ) {\n return schema.max(attribute.maxLength, {\n ...translatedErrors.maxLength,\n values: {\n max: attribute.maxLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMinValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // do not validate min for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if ('min' in attribute && 'min' in schema) {\n const min = toInteger(attribute.min);\n\n if (min) {\n return schema.min(min, {\n ...translatedErrors.min,\n values: {\n min,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst addMaxValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('max' in attribute) {\n const max = toInteger(attribute.max);\n\n if ('max' in schema && max) {\n return schema.max(max, {\n ...translatedErrors.max,\n values: {\n max,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst toInteger = (val?: string | number): number | undefined => {\n if (typeof val === 'number' || val === undefined) {\n return val;\n } else {\n const num = Number(val);\n return isNaN(num) ? undefined : num;\n }\n};\n\nconst addRegexValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('regex' in attribute && attribute.regex && 'matches' in schema) {\n return schema.matches(new RegExp(attribute.regex), {\n message: {\n id: translatedErrors.regex.id,\n defaultMessage: 'The value does not match the defined pattern.',\n },\n\n excludeEmptyString: !attribute.required,\n }) as TSchema;\n }\n\n return schema;\n };\n\nexport { createYupSchema };\n"],"names":["arrayValidator","attribute","options","message","translatedErrors","required","test","value","status","Array","isArray","length","createYupSchema","attributes","components","createModelSchema","yup","object","shape","Object","entries","reduce","acc","name","DOCUMENT_META_FIELDS","includes","validations","addNullableValidation","addRequiredValidation","addMinLengthValidation","addMaxLengthValidation","addMinValidation","addMaxValidation","addRegexValidation","map","fn","transformSchema","pipe","type","component","repeatable","array","of","nullable","lazy","data","__component","validation","string","oneOf","keys","concat","mixed","id","number","createAttributeSchema","default","matches","boolean","json","email","enum","JSON","stringify","err","parse","regex","RegExp","nullableSchema","schema","minLength","Number","isInteger","min","values","maxLength","max","toInteger","val","undefined","num","isNaN","defaultMessage","excludeEmptyString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAMA,cAAiB,GAAA,CAACC,SAAyCC,EAAAA,OAAAA,IAAgC;AAC/FC,QAAAA,OAAAA,EAASC,6BAAiBC,QAAQ;AAClCC,QAAAA,IAAAA,CAAAA,CAAKC,KAAc,EAAA;YACjB,IAAIL,OAAAA,CAAQM,MAAM,KAAK,OAAS,EAAA;gBAC9B,OAAO,IAAA;AACT;YAEA,IAAI,CAACP,SAAUI,CAAAA,QAAQ,EAAE;gBACvB,OAAO,IAAA;AACT;AAEA,YAAA,IAAI,CAACE,KAAO,EAAA;gBACV,OAAO,KAAA;AACT;AAEA,YAAA,I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ACjC,aAAA,CAAA;AACF;QAEA,OAAOgE,MAAAA;AACT,KAAA;;;;"}
1
+ {"version":3,"file":"validation.js","sources":["../../../admin/src/utils/validation.ts"],"sourcesContent":["import { translatedErrors } from '@strapi/admin/strapi-admin';\nimport pipe from 'lodash/fp/pipe';\nimport * as yup from 'yup';\n\nimport { DOCUMENT_META_FIELDS } from '../constants/attributes';\n\nimport type { ComponentsDictionary, Schema } from '../hooks/useDocument';\nimport type { Schema as SchemaUtils } from '@strapi/types';\nimport type { ObjectShape } from 'yup/lib/object';\n\ntype AnySchema =\n | yup.StringSchema\n | yup.NumberSchema\n | yup.BooleanSchema\n | yup.DateSchema\n | yup.ArraySchema<any>\n | yup.ObjectSchema<any>;\n\n/* -------------------------------------------------------------------------------------------------\n * createYupSchema\n * -----------------------------------------------------------------------------------------------*/\n\ninterface ValidationOptions {\n status: 'draft' | 'published' | null;\n removedAttributes?: string[];\n}\n\nconst arrayValidator = (attribute: Schema['attributes'][string], options: ValidationOptions) => ({\n message: translatedErrors.required,\n test(value: unknown) {\n if (options.status === 'draft') {\n return true;\n }\n\n if (!attribute.required) {\n return true;\n }\n\n if (!value) {\n return false;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n\n return true;\n },\n});\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n/**\n * TODO: should we create a Map to store these based on the hash of the schema?\n */\nconst createYupSchema = (\n attributes: Schema['attributes'] = {},\n components: ComponentsDictionary = {},\n options: ValidationOptions = { status: null }\n): yup.ObjectSchema<any> => {\n const createModelSchema = (\n attributes: Schema['attributes'],\n removedAttributes: string[] = []\n ): yup.ObjectSchema<any> =>\n yup\n .object()\n .shape(\n Object.entries(attributes).reduce<ObjectShape>((acc, [name, attribute]) => {\n const getNestedPathsForAttribute = (removed: string[], attrName: string): string[] => {\n const prefix = `${attrName}.`;\n const bracketRegex = new RegExp(`^${escapeRegex(attrName)}\\\\[\\\\d+\\\\]\\\\.`);\n\n return removed\n .filter((p) => p.startsWith(prefix) || bracketRegex.test(p))\n .map((p) =>\n p.startsWith(prefix) ? p.slice(prefix.length) : p.replace(bracketRegex, '')\n );\n };\n\n if (DOCUMENT_META_FIELDS.includes(name)) {\n return acc;\n }\n\n if (removedAttributes?.includes(name)) {\n // If the attribute is not visible, we don't want to validate it\n return acc;\n }\n\n const nestedRemoved = getNestedPathsForAttribute(removedAttributes, name);\n\n /**\n * These validations won't apply to every attribute\n * and that's okay, in that case we just return the\n * schema as it was passed.\n */\n const validations = [\n addNullableValidation,\n addRequiredValidation,\n addMinLengthValidation,\n addMaxLengthValidation,\n addMinValidation,\n addMaxValidation,\n addRegexValidation,\n ].map((fn) => fn(attribute, options));\n\n const transformSchema = pipe(...validations);\n\n switch (attribute.type) {\n case 'component': {\n const { attributes } = components[attribute.component];\n\n if (attribute.repeatable) {\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(createModelSchema(attributes, nestedRemoved).nullable(false))\n ).test(arrayValidator(attribute, options)),\n };\n } else {\n return {\n ...acc,\n [name]: transformSchema(createModelSchema(attributes, nestedRemoved).nullable()),\n };\n }\n }\n case 'dynamiczone':\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(\n yup.lazy(\n (\n data: SchemaUtils.Attribute.Value<SchemaUtils.Attribute.DynamicZone>[number]\n ) => {\n const attributes = components?.[data?.__component]?.attributes;\n\n const validation = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(components)),\n })\n .nullable(false);\n if (!attributes) {\n return validation;\n }\n\n return validation.concat(createModelSchema(attributes, nestedRemoved));\n }\n ) as unknown as yup.ObjectSchema<any>\n )\n ).test(arrayValidator(attribute, options)),\n };\n case 'relation':\n return {\n ...acc,\n [name]: transformSchema(\n yup.lazy((value) => {\n if (!value) {\n return yup.mixed().nullable(true);\n } else if (Array.isArray(value)) {\n // If a relation value is an array, we expect\n // an array of objects with {id} properties, representing the related entities.\n return yup.array().of(\n yup.object().shape({\n id: yup.number().required(),\n })\n );\n } else if (typeof value === 'object') {\n // A realtion value can also be an object. Some API\n // repsonses return the number of entities in the relation\n // as { count: x }\n return yup.object();\n } else {\n return yup\n .mixed()\n .test(\n 'type-error',\n 'Relation values must be either null, an array of objects with {id} or an object.',\n () => false\n );\n }\n })\n ),\n };\n default:\n return {\n ...acc,\n [name]: transformSchema(createAttributeSchema(attribute)),\n };\n }\n }, {})\n )\n /**\n * TODO: investigate why an undefined object fails a check of `nullable`.\n */\n .default(null);\n\n return createModelSchema(attributes, options.removedAttributes);\n};\n\nconst createAttributeSchema = (\n attribute: Exclude<\n SchemaUtils.Attribute.AnyAttribute,\n { type: 'dynamiczone' } | { type: 'component' } | { type: 'relation' }\n >\n) => {\n switch (attribute.type) {\n case 'biginteger':\n return yup.string().matches(/^-?\\d*$/);\n case 'boolean':\n return yup.boolean();\n case 'blocks':\n return yup.mixed().test('isBlocks', translatedErrors.json, (value) => {\n if (!value || Array.isArray(value)) {\n return true;\n } else {\n return false;\n }\n });\n case 'decimal':\n case 'float':\n case 'integer':\n return yup.number();\n case 'email':\n return yup.string().email(translatedErrors.email);\n case 'enumeration':\n return yup.string().oneOf([...attribute.enum, null]);\n case 'json':\n return yup.mixed().test('isJSON', translatedErrors.json, (value) => {\n /**\n * We don't want to validate the JSON field if it's empty.\n */\n if (!value || (typeof value === 'string' && value.length === 0)) {\n return true;\n }\n\n // If the value was created via content API and wasn't changed, then it's still an object\n if (typeof value === 'object') {\n try {\n JSON.stringify(value);\n return true;\n } catch (err) {\n return false;\n }\n }\n\n try {\n JSON.parse(value);\n\n return true;\n } catch (err) {\n return false;\n }\n });\n case 'password':\n case 'richtext':\n case 'string':\n case 'text':\n return yup.string();\n case 'uid':\n return yup\n .string()\n .matches(attribute.regex ? new RegExp(attribute.regex) : /^[A-Za-z0-9-_.~]*$/);\n default:\n /**\n * This allows any value.\n */\n return yup.mixed();\n }\n};\n\n// Helper function to return schema.nullable() if it exists, otherwise return schema\nconst nullableSchema = <TSchema extends AnySchema>(schema: TSchema) => {\n return schema?.nullable\n ? schema.nullable()\n : // In some cases '.nullable' will not be available on the schema.\n // e.g. when the schema has been built using yup.lazy (e.g. for relations).\n // In these cases we should just return the schema as it is.\n schema;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Validators\n * -----------------------------------------------------------------------------------------------*/\n/**\n * Our validator functions can be preped with the\n * attribute and then have the schema piped through them.\n */\ntype ValidationFn = (\n attribute: Schema['attributes'][string],\n options: ValidationOptions\n) => <TSchema extends AnySchema>(schema: TSchema) => TSchema;\n\nconst addNullableValidation: ValidationFn = () => (schema) => {\n return nullableSchema(schema);\n};\n\nconst addRequiredValidation: ValidationFn = (attribute, options) => (schema) => {\n if (options.status === 'draft' || !attribute.required) {\n return schema;\n }\n\n if (attribute.required && 'required' in schema) {\n return schema.required(translatedErrors.required);\n }\n\n return schema;\n};\n\nconst addMinLengthValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // Skip minLength validation for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if (\n 'minLength' in attribute &&\n attribute.minLength &&\n Number.isInteger(attribute.minLength) &&\n 'min' in schema\n ) {\n return schema.min(attribute.minLength, {\n ...translatedErrors.minLength,\n values: {\n min: attribute.minLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMaxLengthValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if (\n 'maxLength' in attribute &&\n attribute.maxLength &&\n Number.isInteger(attribute.maxLength) &&\n 'max' in schema\n ) {\n return schema.max(attribute.maxLength, {\n ...translatedErrors.maxLength,\n values: {\n max: attribute.maxLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMinValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // do not validate min for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if ('min' in attribute && 'min' in schema) {\n const min = toInteger(attribute.min);\n\n if (min) {\n return schema.min(min, {\n ...translatedErrors.min,\n values: {\n min,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst addMaxValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('max' in attribute) {\n const max = toInteger(attribute.max);\n\n if ('max' in schema && max) {\n return schema.max(max, {\n ...translatedErrors.max,\n values: {\n max,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst toInteger = (val?: string | number): number | undefined => {\n if (typeof val === 'number' || val === undefined) {\n return val;\n } else {\n const num = Number(val);\n return isNaN(num) ? undefined : num;\n }\n};\n\nconst addRegexValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('regex' in attribute && attribute.regex && 'matches' in schema) {\n return schema.matches(new RegExp(attribute.regex), {\n message: {\n id: translatedErrors.regex.id,\n defaultMessage: 'The value does not match the defined pattern.',\n },\n\n excludeEmptyString: !attribute.required,\n }) as TSchema;\n }\n\n return schema;\n };\n\nexport { createYupSchema };\n"],"names":["arrayValidator","attribute","options","message","translatedErrors","required","test","value","status","Array","isArray","length","escapeRegex","str","replace","createYupSchema","attributes","components","createModelSchema","removedAttributes","yup","object","shape","Object","entries","reduce","acc","name","getNestedPathsForAttribute","removed","attrName","prefix","bracketRegex","RegExp","filter","p","startsWith","map","slice","DOCUMENT_META_FIELDS","includes","nestedRemoved","validations","addNullableValidation","addRequiredValidation","addMinLengthValidation","addMaxLengthValidation","addMinValidation","addMaxValidation","addRegexValidation","fn","transformSchema","pipe","type","component","repeatable","array","of","nullable","lazy","data","__component","validation","string","oneOf","keys","concat","mixed","id","number","createAttributeSchema","default","matches","boolean","json","email","enum","JSON","stringify","err","parse","regex","nullableSchema","schema","minLength","Number","isInteger","min","values","maxLength","max","toInteger","val","undefined","num","isNaN","defaultMessage","excludeEmptyString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAMA,cAA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