strapi-plugin-bulk-updater 1.6.1 → 1.6.3

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.
@@ -661,8 +661,18 @@ const csvController = ({ strapi }) => ({
661
661
  async exportCollection(ctx) {
662
662
  try {
663
663
  const { uid } = ctx.params;
664
- const { search, attribute, searchAttribute, filterOperator, filterQuery, limit, documentIds } = {
665
- ...ctx.query,
664
+ const {
665
+ search,
666
+ attribute,
667
+ searchAttribute,
668
+ filterOperator,
669
+ filterQuery,
670
+ limit,
671
+ documentIds,
672
+ exportMode,
673
+ selectedColumns
674
+ } = {
675
+ ...ctx.query || {},
666
676
  ...ctx.request?.body || {}
667
677
  };
668
678
  const csvService2 = strapi.plugin("bulk-updater").service("csv");
@@ -670,6 +680,10 @@ const csvController = ({ strapi }) => ({
670
680
  if (documentIds) {
671
681
  parsedDocIds = Array.isArray(documentIds) ? documentIds : String(documentIds).split(",").map((s) => s.trim()).filter(Boolean);
672
682
  }
683
+ let parsedSelectedColumns;
684
+ if (selectedColumns) {
685
+ parsedSelectedColumns = Array.isArray(selectedColumns) ? selectedColumns : String(selectedColumns).split(",").map((s) => s.trim()).filter(Boolean);
686
+ }
673
687
  const result = await csvService2.exportCollectionCsv(uid, {
674
688
  search: search ? String(search) : void 0,
675
689
  attribute: attribute ? String(attribute) : void 0,
@@ -677,7 +691,9 @@ const csvController = ({ strapi }) => ({
677
691
  filterOperator: filterOperator ? String(filterOperator) : void 0,
678
692
  filterQuery: filterQuery !== void 0 ? String(filterQuery) : void 0,
679
693
  limit: limit ? Number(limit) : void 0,
680
- documentIds: parsedDocIds
694
+ documentIds: parsedDocIds,
695
+ exportMode: exportMode ? String(exportMode) : void 0,
696
+ selectedColumns: parsedSelectedColumns
681
697
  });
682
698
  ctx.body = {
683
699
  success: true,
@@ -693,9 +709,15 @@ const csvController = ({ strapi }) => ({
693
709
  },
694
710
  async exportBulk(ctx) {
695
711
  try {
696
- const { selectedEntries } = ctx.request.body || {};
712
+ const { selectedEntries, selectedColumns } = ctx.request.body || {};
697
713
  const csvService2 = strapi.plugin("bulk-updater").service("csv");
698
- const result = await csvService2.exportBulkCsv(selectedEntries);
714
+ let parsedSelectedColumns;
715
+ if (selectedColumns) {
716
+ parsedSelectedColumns = Array.isArray(selectedColumns) ? selectedColumns : String(selectedColumns).split(",").map((s) => s.trim()).filter(Boolean);
717
+ }
718
+ const result = await csvService2.exportBulkCsv(selectedEntries, {
719
+ selectedColumns: parsedSelectedColumns
720
+ });
699
721
  ctx.body = {
700
722
  success: true,
701
723
  filename: result.filename,
@@ -1733,7 +1755,16 @@ function discoverSchema(strapi, uid) {
1733
1755
  };
1734
1756
  }
1735
1757
  const EXPLICIT_CLEAR_TOKENS = /* @__PURE__ */ new Set(["__CLEAR__", "__NULL__"]);
1758
+ const EXPLICIT_EMPTY_STRING_TOKEN = "__EMPTY__";
1759
+ const EXPLICIT_DELETE_KEY_TOKEN = "__DELETE__";
1736
1760
  const FORBIDDEN_OBJECT_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1761
+ function normalizeExportMode(raw) {
1762
+ const val = String(raw || "").trim().toLowerCase();
1763
+ if (val === "metafields") return "metafields";
1764
+ if (val === "topbarconfig") return "topbarconfig";
1765
+ if (val === "selective") return "selective";
1766
+ return "all";
1767
+ }
1737
1768
  function isPlainObject(val) {
1738
1769
  if (val === null || typeof val !== "object" || Array.isArray(val)) return false;
1739
1770
  if (val instanceof Date || val instanceof RegExp) return false;
@@ -1760,37 +1791,67 @@ function deepCloneValue(val) {
1760
1791
  }
1761
1792
  return val;
1762
1793
  }
1763
- function isSafePathSegment(segment) {
1764
- return Boolean(segment) && !FORBIDDEN_OBJECT_KEYS.has(segment);
1765
- }
1766
- function getValueAtPath(rootObj, pathSegments) {
1767
- let cursor = rootObj;
1768
- for (let i = 0; i < pathSegments.length; i++) {
1769
- const seg = pathSegments[i];
1770
- if (!isSafePathSegment(seg) || cursor === null || cursor === void 0 || typeof cursor !== "object") {
1771
- return { exists: false, value: void 0 };
1794
+ function deepEqualValues(a, b) {
1795
+ if (a === b) return true;
1796
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
1797
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
1798
+ if (Array.isArray(a) && Array.isArray(b)) {
1799
+ if (a.length !== b.length) return false;
1800
+ for (let i = 0; i < a.length; i++) {
1801
+ if (!deepEqualValues(a[i], b[i])) return false;
1802
+ }
1803
+ return true;
1804
+ }
1805
+ if (isPlainObject(a) && isPlainObject(b)) {
1806
+ const keysA = Object.keys(a).filter((k) => !FORBIDDEN_OBJECT_KEYS.has(k));
1807
+ const keysB = Object.keys(b).filter((k) => !FORBIDDEN_OBJECT_KEYS.has(k));
1808
+ if (keysA.length !== keysB.length) return false;
1809
+ for (const k of keysA) {
1810
+ if (!Object.prototype.hasOwnProperty.call(b, k)) return false;
1811
+ if (!deepEqualValues(a[k], b[k])) return false;
1772
1812
  }
1773
- if (Array.isArray(cursor) || !Object.prototype.hasOwnProperty.call(cursor, seg)) {
1774
- return { exists: false, value: void 0 };
1813
+ return true;
1814
+ }
1815
+ return false;
1816
+ }
1817
+ function isSafePropKey(segment) {
1818
+ return Boolean(segment) && !FORBIDDEN_OBJECT_KEYS.has(segment) && !segment.includes(".");
1819
+ }
1820
+ function getDeepProp(obj, path) {
1821
+ if (!obj || !path) return void 0;
1822
+ const parts = path.split(".");
1823
+ let cur = obj;
1824
+ for (const key of parts) {
1825
+ if (cur === null || cur === void 0 || typeof cur !== "object") return void 0;
1826
+ if (FORBIDDEN_OBJECT_KEYS.has(key)) return void 0;
1827
+ cur = cur[key];
1828
+ }
1829
+ return cur;
1830
+ }
1831
+ function setDeepProp(obj, path, value) {
1832
+ if (!obj || typeof obj !== "object" || !path) return false;
1833
+ const parts = path.split(".");
1834
+ let cur = obj;
1835
+ for (let i = 0; i < parts.length - 1; i++) {
1836
+ const key = parts[i];
1837
+ if (FORBIDDEN_OBJECT_KEYS.has(key)) return false;
1838
+ if (cur[key] === void 0 || cur[key] === null || typeof cur[key] !== "object") {
1839
+ cur[key] = {};
1775
1840
  }
1776
- cursor = cursor[seg];
1841
+ cur = cur[key];
1777
1842
  }
1778
- return { exists: true, value: cursor };
1843
+ const lastKey = parts[parts.length - 1];
1844
+ if (FORBIDDEN_OBJECT_KEYS.has(lastKey)) return false;
1845
+ cur[lastKey] = value;
1846
+ return true;
1779
1847
  }
1780
- function setValueAtPath(target, pathSegments, value) {
1781
- if (pathSegments.length === 0) return;
1782
- let cursor = target;
1783
- for (let i = 0; i < pathSegments.length - 1; i++) {
1784
- const seg = pathSegments[i];
1785
- if (!isSafePathSegment(seg)) return;
1786
- if (!isPlainObject(cursor[seg])) {
1787
- cursor[seg] = {};
1788
- }
1789
- cursor = cursor[seg];
1790
- }
1791
- const leafKey = pathSegments[pathSegments.length - 1];
1792
- if (!isSafePathSegment(leafKey)) return;
1793
- cursor[leafKey] = value;
1848
+ function resolveTargetObjectField(schema, exportMode) {
1849
+ if (exportMode === "all" || exportMode === "selective") return void 0;
1850
+ const keys = Object.keys(schema.fields || {});
1851
+ const exactMatch = keys.find((k) => k === exportMode);
1852
+ if (exactMatch) return exactMatch;
1853
+ const normalizedTarget = exportMode.toLowerCase().replace(/[_-]/g, "");
1854
+ return keys.find((k) => k.toLowerCase().replace(/[_-]/g, "") === normalizedTarget);
1794
1855
  }
1795
1856
  function classifyLeafType(val) {
1796
1857
  if (val === null) return "null";
@@ -1812,146 +1873,133 @@ function needsTypeAnnotation(val) {
1812
1873
  }
1813
1874
  return false;
1814
1875
  }
1815
- function collectDynamicPlainObjectPaths(values, baseSegments, blockedRootNames) {
1816
- const leafPaths = [];
1817
- const seenJoined = /* @__PURE__ */ new Set();
1818
- let hasAnyNonNullValue = false;
1819
- for (const val of values) {
1820
- if (val === null || val === void 0) continue;
1821
- hasAnyNonNullValue = true;
1822
- if (!isPlainObject(val)) {
1823
- return { canFlatten: false, paths: [] };
1824
- }
1825
- }
1826
- if (!hasAnyNonNullValue) {
1827
- return { canFlatten: false, paths: [] };
1828
- }
1829
- const walk = (node, relSegments, seenObjects) => {
1830
- if (relSegments.length > 25 || seenObjects.has(node)) return;
1831
- seenObjects.add(node);
1832
- for (const [key, child] of Object.entries(node)) {
1833
- if (!isSafePathSegment(key) || key.includes(".")) {
1834
- continue;
1835
- }
1836
- const nextRel = [...relSegments, key];
1837
- const fullPath = [...baseSegments, ...nextRel].join(".");
1838
- if (blockedRootNames.has(fullPath)) continue;
1839
- if (isPlainObject(child)) {
1840
- const childKeys = Object.keys(child).filter((ck) => isSafePathSegment(ck) && !ck.includes("."));
1841
- if (childKeys.length === 0) {
1842
- if (!seenJoined.has(fullPath)) {
1843
- seenJoined.add(fullPath);
1844
- leafPaths.push(nextRel);
1845
- }
1846
- } else {
1847
- if (seenJoined.has(fullPath)) {
1848
- seenJoined.delete(fullPath);
1849
- const idx = leafPaths.findIndex((p) => [...baseSegments, ...p].join(".") === fullPath);
1850
- if (idx >= 0) leafPaths.splice(idx, 1);
1851
- }
1852
- walk(child, nextRel, seenObjects);
1853
- }
1854
- } else {
1855
- if (!seenJoined.has(fullPath)) {
1856
- seenJoined.add(fullPath);
1857
- leafPaths.push(nextRel);
1858
- }
1859
- }
1860
- }
1861
- seenObjects.delete(node);
1862
- };
1863
- for (const val of values) {
1864
- if (isPlainObject(val)) {
1865
- walk(val, [], /* @__PURE__ */ new WeakSet());
1866
- }
1867
- }
1868
- return { canFlatten: leafPaths.length > 0, paths: leafPaths };
1869
- }
1870
- function collectComponentExportColumns(strapi, compUid, baseSegments, documents, blockedRootNames, visitedComps) {
1871
- const comp = strapi.components?.[compUid];
1872
- if (!comp?.attributes || visitedComps.has(compUid)) {
1873
- return [];
1874
- }
1875
- const nextVisited = new Set(visitedComps);
1876
- nextVisited.add(compUid);
1877
- const rootKey = baseSegments[0];
1876
+ function collectFirstLevelObjectColumns(strapi, rootKey, field, documents, blockedNames) {
1878
1877
  const result = [];
1879
- for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
1880
- if (!isSafePathSegment(attrName)) continue;
1881
- const norm = attrName.toLowerCase().replace(/[\s_-]/g, "");
1882
- if (SYSTEM_ATTRIBUTES.has(norm) || attrName === "id" || attrName === "__component") continue;
1883
- const attrType = String(attrDef?.type || "").toLowerCase();
1884
- const nextSegments = [...baseSegments, attrName];
1885
- const header = nextSegments.join(".");
1886
- if (blockedRootNames.has(header)) continue;
1887
- if (attrType === "component" && !attrDef.repeatable && attrDef.component) {
1888
- const nested = collectComponentExportColumns(
1889
- strapi,
1890
- attrDef.component,
1891
- nextSegments,
1892
- documents,
1893
- blockedRootNames,
1894
- nextVisited
1895
- );
1896
- if (nested.length > 0) {
1897
- result.push(...nested);
1898
- } else {
1878
+ const seenProps = /* @__PURE__ */ new Set();
1879
+ if (field.category === "component_single" && field.componentUid) {
1880
+ const comp = strapi.components?.[field.componentUid];
1881
+ if (comp?.attributes) {
1882
+ for (const [subKey, subDef] of Object.entries(comp.attributes)) {
1883
+ if (!isSafePropKey(subKey)) continue;
1884
+ const norm = subKey.toLowerCase().replace(/[\s_-]/g, "");
1885
+ if (SYSTEM_ATTRIBUTES.has(norm) || subKey === "id" || subKey === "__component") continue;
1886
+ const header = `${rootKey}.${subKey}`;
1887
+ if (blockedNames.has(header) || seenProps.has(subKey)) continue;
1888
+ seenProps.add(subKey);
1899
1889
  result.push({
1900
1890
  header,
1901
- kind: "flattened_component_leaf",
1891
+ kind: "flattened_first_level",
1902
1892
  rootKey,
1903
- pathSegments: nextSegments,
1904
- componentSubDef: attrDef
1893
+ propKey: subKey,
1894
+ field,
1895
+ componentSubDef: subDef
1905
1896
  });
1906
1897
  }
1907
- } else if (attrType === "json") {
1908
- const vals = documents.map((d) => getValueAtPath(d, nextSegments).value);
1909
- const { canFlatten, paths } = collectDynamicPlainObjectPaths(vals, nextSegments, blockedRootNames);
1910
- if (canFlatten) {
1911
- for (const relPath of paths) {
1912
- const fullSegments = [...nextSegments, ...relPath];
1913
- result.push({
1914
- header: fullSegments.join("."),
1915
- kind: "flattened_component_leaf",
1916
- rootKey,
1917
- pathSegments: fullSegments,
1918
- componentSubDef: { type: "json_leaf" }
1919
- });
1920
- }
1921
- } else {
1922
- result.push({
1923
- header,
1924
- kind: "flattened_component_leaf",
1925
- rootKey,
1926
- pathSegments: nextSegments,
1927
- componentSubDef: attrDef
1928
- });
1898
+ }
1899
+ }
1900
+ for (const doc of documents) {
1901
+ const obj = doc?.[rootKey];
1902
+ if (obj === null || obj === void 0) continue;
1903
+ if (!isPlainObject(obj)) {
1904
+ if (field.category === "json") {
1905
+ return [];
1929
1906
  }
1930
- } else {
1907
+ continue;
1908
+ }
1909
+ for (const propKey of Object.keys(obj)) {
1910
+ if (!isSafePropKey(propKey)) continue;
1911
+ const header = `${rootKey}.${propKey}`;
1912
+ if (blockedNames.has(header) || seenProps.has(propKey)) continue;
1913
+ seenProps.add(propKey);
1931
1914
  result.push({
1932
1915
  header,
1933
- kind: "flattened_component_leaf",
1916
+ kind: "flattened_first_level",
1934
1917
  rootKey,
1935
- pathSegments: nextSegments,
1936
- componentSubDef: attrDef
1918
+ propKey,
1919
+ field
1937
1920
  });
1938
1921
  }
1939
1922
  }
1940
1923
  return result;
1941
1924
  }
1942
- function buildExportColumnPlan(strapi, uid, documents, schemaOverride) {
1943
- const schema = schemaOverride || discoverSchema(strapi, uid);
1925
+ function buildExportColumnPlan(strapi, uid, documents, options = {}) {
1926
+ const schema = options.schema || discoverSchema(strapi, uid);
1927
+ const rawExportMode = options.exportMode;
1928
+ const hasSelectedColumns = Array.isArray(options.selectedColumns) && options.selectedColumns.length > 0;
1929
+ const exportMode = hasSelectedColumns ? "selective" : normalizeExportMode(rawExportMode);
1930
+ if (exportMode === "selective" && hasSelectedColumns) {
1931
+ const columns2 = [];
1932
+ const headers = [];
1933
+ columns2.push({
1934
+ header: "documentId",
1935
+ kind: "system",
1936
+ rootKey: "documentId"
1937
+ });
1938
+ headers.push("documentId");
1939
+ columns2.push({
1940
+ header: "slug",
1941
+ kind: schema.fields["slug"] ? "field" : "system",
1942
+ rootKey: "slug",
1943
+ field: schema.fields["slug"]
1944
+ });
1945
+ headers.push("slug");
1946
+ for (const rawCol of options.selectedColumns) {
1947
+ const colName = String(rawCol).trim();
1948
+ if (!colName || colName === "documentId" || colName === "slug" || colName === "__bulk_updater_metadata" || colName === "_bulk_updater_metadata") {
1949
+ continue;
1950
+ }
1951
+ if (headers.includes(colName)) {
1952
+ continue;
1953
+ }
1954
+ if (colName.includes(".")) {
1955
+ const rootKey = colName.split(".")[0];
1956
+ const rootField = schema.fields[rootKey];
1957
+ const isRepeated = rootField?.category === "component_repeatable" || rootField?.category === "dynamiczone" || rootField?.rawType === "dynamiczone" || Array.isArray(documents) && documents.some((d) => Array.isArray(d?.[rootKey]));
1958
+ columns2.push({
1959
+ header: colName,
1960
+ kind: "selective_nested",
1961
+ rootKey,
1962
+ isRepeatedNested: Boolean(isRepeated),
1963
+ field: rootField
1964
+ });
1965
+ headers.push(colName);
1966
+ } else {
1967
+ const field = schema.fields[colName];
1968
+ if (field) {
1969
+ columns2.push({
1970
+ header: colName,
1971
+ kind: "field",
1972
+ rootKey: colName,
1973
+ field
1974
+ });
1975
+ headers.push(colName);
1976
+ } else {
1977
+ columns2.push({
1978
+ header: colName,
1979
+ kind: "selective_nested",
1980
+ rootKey: colName,
1981
+ isRepeatedNested: false
1982
+ });
1983
+ headers.push(colName);
1984
+ }
1985
+ }
1986
+ }
1987
+ return {
1988
+ exportMode,
1989
+ columns: columns2,
1990
+ headers,
1991
+ selectedColumns: options.selectedColumns
1992
+ };
1993
+ }
1994
+ const targetObjectField = resolveTargetObjectField(schema, exportMode);
1944
1995
  const topLevelNames = new Set(schema.allExportKeys);
1945
1996
  const columns = [];
1946
- const flattenedJsonRoots = /* @__PURE__ */ new Set();
1947
- const flattenedComponentRoots = /* @__PURE__ */ new Set();
1948
1997
  for (const key of schema.allExportKeys) {
1949
1998
  if (key === "documentId" || key === "locale") {
1950
1999
  columns.push({
1951
2000
  header: key,
1952
2001
  kind: "system",
1953
- rootKey: key,
1954
- pathSegments: [key]
2002
+ rootKey: key
1955
2003
  });
1956
2004
  continue;
1957
2005
  }
@@ -1960,121 +2008,134 @@ function buildExportColumnPlan(strapi, uid, documents, schemaOverride) {
1960
2008
  columns.push({
1961
2009
  header: key,
1962
2010
  kind: "field",
1963
- rootKey: key,
1964
- pathSegments: [key]
2011
+ rootKey: key
1965
2012
  });
1966
2013
  continue;
1967
2014
  }
1968
- if (field.category === "json") {
1969
- const values = documents.map((d) => d?.[key]);
1970
- const { canFlatten, paths } = collectDynamicPlainObjectPaths(values, [key], topLevelNames);
1971
- if (canFlatten) {
1972
- flattenedJsonRoots.add(key);
1973
- for (const relPath of paths) {
1974
- const fullSegments = [key, ...relPath];
1975
- columns.push({
1976
- header: fullSegments.join("."),
1977
- kind: "flattened_json_leaf",
1978
- rootKey: key,
1979
- pathSegments: fullSegments,
1980
- field
1981
- });
2015
+ if (exportMode !== "all" && targetObjectField && key === targetObjectField) {
2016
+ if (field.category === "json" || field.category === "component_single") {
2017
+ const firstLevelCols = collectFirstLevelObjectColumns(
2018
+ strapi,
2019
+ key,
2020
+ field,
2021
+ documents,
2022
+ topLevelNames
2023
+ );
2024
+ if (firstLevelCols.length > 0) {
2025
+ columns.push(...firstLevelCols);
2026
+ continue;
1982
2027
  }
1983
- continue;
1984
- }
1985
- }
1986
- if (field.category === "component_single" && field.componentUid) {
1987
- const compColumns = collectComponentExportColumns(
1988
- strapi,
1989
- field.componentUid,
1990
- [key],
1991
- documents,
1992
- topLevelNames,
1993
- /* @__PURE__ */ new Set()
1994
- );
1995
- if (compColumns.length > 0) {
1996
- flattenedComponentRoots.add(key);
1997
- columns.push(...compColumns);
1998
- continue;
1999
2028
  }
2000
2029
  }
2001
2030
  columns.push({
2002
2031
  header: key,
2003
2032
  kind: "field",
2004
2033
  rootKey: key,
2005
- pathSegments: [key],
2006
2034
  field
2007
2035
  });
2008
2036
  }
2009
2037
  return {
2038
+ exportMode,
2039
+ targetObjectField,
2010
2040
  columns,
2011
- headers: columns.map((c) => c.header),
2012
- flattenedJsonRoots,
2013
- flattenedComponentRoots
2041
+ headers: columns.map((c) => c.header)
2014
2042
  };
2015
2043
  }
2016
2044
  function extractRowFlattenedMetadata(plan, doc) {
2017
- const applicableFields = [];
2018
- const flatTypes = {};
2019
- const flattenedRoots = /* @__PURE__ */ new Set([
2020
- ...plan.flattenedJsonRoots,
2021
- ...plan.flattenedComponentRoots
2022
- ]);
2023
- for (const rootKey of flattenedRoots) {
2024
- const val = doc?.[rootKey];
2025
- if (val !== null && val !== void 0) {
2026
- applicableFields.push(rootKey);
2027
- if (plan.flattenedJsonRoots.has(rootKey) && isPlainObject(val) && Object.keys(val).length === 0) {
2028
- flatTypes[rootKey] = "object";
2029
- }
2030
- }
2045
+ const out = {
2046
+ exportMode: plan.exportMode
2047
+ };
2048
+ if (plan.exportMode === "selective") {
2049
+ out.selectedColumns = plan.selectedColumns || plan.headers.filter((h) => h !== "documentId" && h !== "slug");
2050
+ return out;
2031
2051
  }
2032
- for (const col of plan.columns) {
2033
- if (col.kind !== "flattened_json_leaf") continue;
2034
- const { exists, value } = getValueAtPath(doc, col.pathSegments);
2035
- if (!exists || value === void 0) continue;
2036
- if (needsTypeAnnotation(value)) {
2037
- flatTypes[col.header] = classifyLeafType(value);
2038
- }
2052
+ if (plan.exportMode === "all" || !plan.targetObjectField) {
2053
+ return out;
2039
2054
  }
2040
- const out = {};
2041
- if (flattenedRoots.size > 0) {
2042
- out.applicableFields = applicableFields;
2055
+ const rootKey = plan.targetObjectField;
2056
+ out.targetObjectField = rootKey;
2057
+ const hasOwn = doc && typeof doc === "object" && Object.prototype.hasOwnProperty.call(doc, rootKey);
2058
+ const rawVal = hasOwn ? doc[rootKey] : void 0;
2059
+ if (!hasOwn || rawVal === void 0) {
2060
+ out.targetObjectState = "absent";
2061
+ out.applicableFields = [];
2062
+ return out;
2043
2063
  }
2044
- if (Object.keys(flatTypes).length > 0) {
2045
- out.flatTypes = flatTypes;
2064
+ if (rawVal === null) {
2065
+ out.targetObjectState = "null";
2066
+ out.applicableFields = [];
2067
+ return out;
2046
2068
  }
2069
+ if (isPlainObject(rawVal)) {
2070
+ const keys = Object.keys(rawVal);
2071
+ out.targetObjectState = keys.length === 0 ? "empty_object" : "present";
2072
+ out.applicableFields = [rootKey];
2073
+ const flatTypes = {};
2074
+ for (const col of plan.columns) {
2075
+ if (col.kind !== "flattened_first_level" || !col.propKey) continue;
2076
+ if (!Object.prototype.hasOwnProperty.call(rawVal, col.propKey)) continue;
2077
+ const leafVal = rawVal[col.propKey];
2078
+ if (leafVal !== void 0 && needsTypeAnnotation(leafVal)) {
2079
+ flatTypes[col.header] = classifyLeafType(leafVal);
2080
+ }
2081
+ }
2082
+ if (Object.keys(flatTypes).length > 0) {
2083
+ out.flatTypes = flatTypes;
2084
+ }
2085
+ return out;
2086
+ }
2087
+ out.targetObjectState = "present";
2088
+ out.applicableFields = [rootKey];
2047
2089
  return out;
2048
2090
  }
2049
- function serializeFlattenedLeafValue(val) {
2050
- if (val === void 0 || val === null) return "";
2051
- if (val instanceof Date) return val.toISOString();
2052
- if (Array.isArray(val) || isPlainObject(val)) {
2053
- return JSON.stringify(val);
2054
- }
2055
- if (typeof val === "boolean") return val ? "true" : "false";
2056
- if (typeof val === "number") return Number.isFinite(val) ? String(val) : "";
2057
- return String(val);
2058
- }
2059
2091
  function serializePlannedCell(col, doc, serializeFieldFallback) {
2060
2092
  if (col.kind === "system") {
2061
2093
  if (col.header === "documentId") return doc?.documentId || doc?.id || "";
2062
2094
  if (col.header === "locale") return doc?.locale || "";
2095
+ if (col.header === "slug") return doc?.slug ?? "";
2063
2096
  return doc?.[col.header] ?? "";
2064
2097
  }
2065
- if (col.kind === "flattened_json_leaf") {
2066
- const { exists, value } = getValueAtPath(doc, col.pathSegments);
2067
- if (!exists) return "";
2068
- if (isPlainObject(value) && Object.keys(value).length === 0) return "";
2069
- return serializeFlattenedLeafValue(value);
2098
+ if (col.kind === "selective_nested") {
2099
+ if (col.isRepeatedNested) {
2100
+ const matches = getAllNestedValues(doc, col.header);
2101
+ if (!matches || matches.length === 0) {
2102
+ return "";
2103
+ }
2104
+ const occurrences = matches.map((m) => {
2105
+ const item = { value: m.value };
2106
+ if (m.componentId !== void 0 && m.componentId !== null) {
2107
+ item.id = m.componentId;
2108
+ }
2109
+ if (m.componentUid) {
2110
+ item.__component = m.componentUid;
2111
+ }
2112
+ if (m.index !== void 0) {
2113
+ item.index = m.index;
2114
+ }
2115
+ return item;
2116
+ });
2117
+ return JSON.stringify(occurrences);
2118
+ } else {
2119
+ const val = getDeepProp(doc, col.header);
2120
+ if (val === void 0 || val === null) return "";
2121
+ if (val instanceof Date) return val.toISOString();
2122
+ if (Array.isArray(val) || isPlainObject(val)) return JSON.stringify(val);
2123
+ if (typeof val === "boolean") return val ? "true" : "false";
2124
+ if (typeof val === "number") return Number.isFinite(val) ? String(val) : "";
2125
+ return String(val);
2126
+ }
2070
2127
  }
2071
- if (col.kind === "flattened_component_leaf") {
2072
- const { exists, value } = getValueAtPath(doc, col.pathSegments);
2073
- if (!exists || value === void 0 || value === null) return "";
2128
+ if (col.kind === "flattened_first_level" && col.propKey) {
2129
+ const rootObj = doc?.[col.rootKey];
2130
+ if (!isPlainObject(rootObj) || !Object.prototype.hasOwnProperty.call(rootObj, col.propKey)) {
2131
+ return "";
2132
+ }
2133
+ const val = rootObj[col.propKey];
2134
+ if (val === void 0 || val === null) return "";
2074
2135
  const subDef = col.componentSubDef || {};
2075
2136
  const subType = String(subDef.type || "").toLowerCase();
2076
2137
  if (subType === "media") {
2077
- return serializeFieldFallback(value, {
2138
+ return serializeFieldFallback(val, {
2078
2139
  key: col.header,
2079
2140
  label: col.header,
2080
2141
  category: subDef.multiple ? "media_to_many" : "media_single",
@@ -2084,7 +2145,7 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2084
2145
  }
2085
2146
  if (subType === "relation") {
2086
2147
  const isToMany = String(subDef.relation || "").toLowerCase().endsWith("many");
2087
- return serializeFieldFallback(value, {
2148
+ return serializeFieldFallback(val, {
2088
2149
  key: col.header,
2089
2150
  label: col.header,
2090
2151
  category: isToMany ? "relation_to_many" : "relation_to_one",
@@ -2092,13 +2153,13 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2092
2153
  relationType: subDef.relation
2093
2154
  });
2094
2155
  }
2095
- if (subType === "component" && subDef.repeatable) {
2096
- return Array.isArray(value) ? JSON.stringify(value) : "";
2097
- }
2098
- if (subType === "blocks" || subType === "json") {
2099
- return typeof value === "object" ? JSON.stringify(value) : String(value);
2156
+ if (val instanceof Date) return val.toISOString();
2157
+ if (Array.isArray(val) || isPlainObject(val)) {
2158
+ return JSON.stringify(val);
2100
2159
  }
2101
- return serializeFlattenedLeafValue(value);
2160
+ if (typeof val === "boolean") return val ? "true" : "false";
2161
+ if (typeof val === "number") return Number.isFinite(val) ? String(val) : "";
2162
+ return String(val);
2102
2163
  }
2103
2164
  const rawValue = doc?.[col.rootKey];
2104
2165
  if (col.field) {
@@ -2106,197 +2167,274 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2106
2167
  }
2107
2168
  return rawValue;
2108
2169
  }
2109
- function parseFlattenedLeafValue(rawCell, annotatedType, existingLeafValue) {
2110
- if (rawCell === null || rawCell === void 0) return null;
2111
- if (typeof rawCell !== "string") return rawCell;
2112
- const trimmed = rawCell.trim();
2113
- if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2114
- return null;
2170
+ function inspectRowMetadataMode(rawRow) {
2171
+ if (!rawRow || typeof rawRow !== "object") {
2172
+ return { mode: "legacy" };
2115
2173
  }
2116
- if (annotatedType === "string") {
2117
- return rawCell;
2174
+ const rawMetaCell = rawRow["__bulk_updater_metadata"] !== void 0 ? rawRow["__bulk_updater_metadata"] : rawRow["_bulk_updater_metadata"];
2175
+ if (rawMetaCell === void 0 || rawMetaCell === null || String(rawMetaCell).trim() === "") {
2176
+ return { mode: "legacy" };
2118
2177
  }
2119
- if (annotatedType === "number" || typeof existingLeafValue === "number") {
2120
- if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
2121
- const num = Number(trimmed);
2122
- if (Number.isFinite(num)) return num;
2178
+ let parsed = rawMetaCell;
2179
+ if (typeof rawMetaCell === "string") {
2180
+ try {
2181
+ parsed = JSON.parse(rawMetaCell);
2182
+ } catch {
2183
+ return {
2184
+ mode: "legacy",
2185
+ error: "Corrupted __bulk_updater_metadata cell: invalid JSON."
2186
+ };
2123
2187
  }
2124
2188
  }
2125
- if (annotatedType === "boolean" || typeof existingLeafValue === "boolean") {
2126
- const low = trimmed.toLowerCase();
2127
- if (low === "true") return true;
2128
- if (low === "false") return false;
2189
+ if (!isPlainObject(parsed)) {
2190
+ return {
2191
+ mode: "legacy",
2192
+ error: "Corrupted __bulk_updater_metadata cell: expected JSON object."
2193
+ };
2129
2194
  }
2130
- if (annotatedType === "array" || Array.isArray(existingLeafValue)) {
2131
- if (trimmed.startsWith("[")) {
2195
+ if (parsed.exportMode === void 0) {
2196
+ return {
2197
+ mode: "legacy",
2198
+ applicableFields: Array.isArray(parsed.applicableFields) ? parsed.applicableFields : void 0,
2199
+ flatTypes: isPlainObject(parsed.flatTypes) ? parsed.flatTypes : void 0,
2200
+ selectedColumns: Array.isArray(parsed.selectedColumns) ? parsed.selectedColumns : void 0
2201
+ };
2202
+ }
2203
+ const rawMode = String(parsed.exportMode).trim().toLowerCase();
2204
+ if (rawMode !== "all" && rawMode !== "metafields" && rawMode !== "topbarconfig" && rawMode !== "selective") {
2205
+ return {
2206
+ mode: "legacy",
2207
+ error: `Unsupported CSV exportMode "${parsed.exportMode}" in metadata.`
2208
+ };
2209
+ }
2210
+ return {
2211
+ mode: rawMode,
2212
+ targetObjectField: typeof parsed.targetObjectField === "string" && parsed.targetObjectField.trim() ? parsed.targetObjectField.trim() : void 0,
2213
+ targetObjectState: parsed.targetObjectState,
2214
+ applicableFields: Array.isArray(parsed.applicableFields) ? parsed.applicableFields : void 0,
2215
+ flatTypes: isPlainObject(parsed.flatTypes) ? parsed.flatTypes : void 0,
2216
+ selectedColumns: Array.isArray(parsed.selectedColumns) ? parsed.selectedColumns : void 0
2217
+ };
2218
+ }
2219
+ function detectCsvBatchExportMode(rows) {
2220
+ const seenModes = /* @__PURE__ */ new Set();
2221
+ for (let i = 0; i < rows.length; i++) {
2222
+ const info = inspectRowMetadataMode(rows[i]);
2223
+ if (info.error) {
2224
+ return { mode: "legacy", error: `Row ${i + 2}: ${info.error}` };
2225
+ }
2226
+ seenModes.add(info.mode);
2227
+ }
2228
+ if (seenModes.size > 1) {
2229
+ return {
2230
+ mode: "legacy",
2231
+ error: `Inconsistent CSV export modes detected across rows (${Array.from(seenModes).join(", ")}). Re-export the file cleanly before importing.`
2232
+ };
2233
+ }
2234
+ const first = Array.from(seenModes)[0];
2235
+ return { mode: first || "legacy" };
2236
+ }
2237
+ function parseFirstLevelCellValue(rawCell, annotatedType, existingPropValue) {
2238
+ if (rawCell === null || rawCell === void 0) return { value: null };
2239
+ if (typeof rawCell !== "string") return { value: rawCell };
2240
+ const trimmed = rawCell.trim();
2241
+ if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2242
+ return { value: null };
2243
+ }
2244
+ if (trimmed === EXPLICIT_EMPTY_STRING_TOKEN) {
2245
+ return { value: "" };
2246
+ }
2247
+ if (annotatedType === "string") {
2248
+ return { value: rawCell };
2249
+ }
2250
+ if (annotatedType === "object" || isPlainObject(existingPropValue)) {
2251
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2132
2252
  try {
2133
- return JSON.parse(trimmed);
2253
+ return { value: JSON.parse(trimmed) };
2134
2254
  } catch {
2255
+ return {
2256
+ value: rawCell,
2257
+ error: `Invalid JSON object value: "${rawCell}"`
2258
+ };
2135
2259
  }
2136
2260
  }
2137
2261
  }
2138
- if (annotatedType === "object" || isPlainObject(existingLeafValue)) {
2139
- if (trimmed.startsWith("{")) {
2262
+ if (annotatedType === "array" || Array.isArray(existingPropValue)) {
2263
+ if (trimmed.startsWith("[")) {
2140
2264
  try {
2141
- return JSON.parse(trimmed);
2265
+ const parsed = JSON.parse(trimmed);
2266
+ return { value: parsed };
2142
2267
  } catch {
2268
+ return {
2269
+ value: rawCell,
2270
+ error: `Invalid JSON array value: "${rawCell}"`
2271
+ };
2143
2272
  }
2144
2273
  }
2145
2274
  }
2146
- if (typeof existingLeafValue === "string") {
2275
+ if (annotatedType === "number" || typeof existingPropValue === "number") {
2276
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
2277
+ const num = Number(trimmed);
2278
+ if (Number.isFinite(num)) return { value: num };
2279
+ }
2280
+ }
2281
+ if (annotatedType === "boolean" || typeof existingPropValue === "boolean") {
2282
+ const low = trimmed.toLowerCase();
2283
+ if (low === "true") return { value: true };
2284
+ if (low === "false") return { value: false };
2285
+ }
2286
+ if (typeof existingPropValue === "string") {
2147
2287
  if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2148
2288
  try {
2149
- return JSON.parse(trimmed);
2289
+ return { value: JSON.parse(trimmed) };
2150
2290
  } catch {
2151
2291
  }
2152
2292
  }
2153
- return rawCell;
2293
+ return { value: rawCell };
2154
2294
  }
2155
- if (trimmed === "null") return null;
2156
- if (trimmed === "true") return true;
2157
- if (trimmed === "false") return false;
2295
+ if (trimmed === "null") return { value: null };
2296
+ if (trimmed === "true") return { value: true };
2297
+ if (trimmed === "false") return { value: false };
2158
2298
  if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
2159
2299
  const num = Number(trimmed);
2160
- if (Number.isFinite(num)) return num;
2300
+ if (Number.isFinite(num)) return { value: num };
2161
2301
  }
2162
2302
  if (trimmed.startsWith("[") && trimmed.endsWith("]") || trimmed.startsWith("{") && trimmed.endsWith("}")) {
2163
2303
  try {
2164
- return JSON.parse(trimmed);
2304
+ return { value: JSON.parse(trimmed) };
2165
2305
  } catch {
2166
2306
  }
2167
2307
  }
2168
- return rawCell;
2308
+ return { value: rawCell };
2169
2309
  }
2170
- function reconstructFlattenedJsonAttribute(params) {
2310
+ function reconstructTargetedFirstLevelObject(params) {
2171
2311
  const {
2172
- attrName,
2173
- existingVal,
2174
- hasDirectKey,
2175
- directRawVal,
2176
- dotEntries,
2312
+ targetAttr,
2313
+ exportMode,
2314
+ existingDoc,
2315
+ docIdForError,
2316
+ rawRow,
2177
2317
  rowMeta,
2178
- isPartialUpdate
2318
+ isAttrRequired = false
2179
2319
  } = params;
2180
- const hasExistingPlainObj = isPlainObject(existingVal);
2181
- const directTrimmed = typeof directRawVal === "string" ? directRawVal.trim() : "";
2182
- if (dotEntries.length === 0) {
2183
- if (!hasDirectKey) return { shouldSet: false, value: void 0 };
2184
- if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
2185
- return { shouldSet: true, value: null };
2186
- }
2187
- if (directRawVal === "" || directRawVal === void 0 || directRawVal === null) {
2188
- return { shouldSet: false, value: void 0 };
2320
+ const prefix = `${targetAttr}.`;
2321
+ const firstLevelEntries = [];
2322
+ const invalidNestedColumns = [];
2323
+ for (const [colKey, val] of Object.entries(rawRow)) {
2324
+ if (!colKey.startsWith(prefix)) continue;
2325
+ const propKey = colKey.slice(prefix.length);
2326
+ if (!propKey) continue;
2327
+ if (propKey.includes(".")) {
2328
+ if (val !== void 0 && val !== null && String(val) !== "") {
2329
+ invalidNestedColumns.push(colKey);
2330
+ }
2331
+ continue;
2189
2332
  }
2190
- if (typeof directRawVal === "string") {
2191
- try {
2192
- return { shouldSet: true, value: JSON.parse(directRawVal) };
2193
- } catch {
2194
- return { shouldSet: true, value: directRawVal };
2333
+ if (!isSafePropKey(propKey)) continue;
2334
+ firstLevelEntries.push([colKey, propKey, val]);
2335
+ }
2336
+ if (invalidNestedColumns.length > 0) {
2337
+ return {
2338
+ shouldSet: false,
2339
+ value: void 0,
2340
+ errors: [
2341
+ `Deeply nested column(s) [${invalidNestedColumns.join(", ")}] are not valid in "${exportMode}" one-level targeted mode.`
2342
+ ]
2343
+ };
2344
+ }
2345
+ const directRawVal = targetAttr in rawRow ? rawRow[targetAttr] : void 0;
2346
+ const directTrimmed = typeof directRawVal === "string" ? directRawVal.trim() : "";
2347
+ const hasNonEmptyFirstLevelEdit = firstLevelEntries.some(
2348
+ ([, , val]) => val !== void 0 && val !== null && String(val) !== ""
2349
+ );
2350
+ if (existingDoc) {
2351
+ const existingObj = existingDoc[targetAttr];
2352
+ const hasObjectOnRecord = isPlainObject(existingObj);
2353
+ if (!hasObjectOnRecord) {
2354
+ const attemptedDirectEdit = directRawVal !== void 0 && directRawVal !== null && directTrimmed !== "";
2355
+ if (!hasNonEmptyFirstLevelEdit && !attemptedDirectEdit) {
2356
+ return { shouldSet: false, value: void 0, errors: [] };
2357
+ }
2358
+ if (!isAttrRequired) {
2359
+ const recordRef = docIdForError || existingDoc.documentId || existingDoc.id || "record";
2360
+ return {
2361
+ shouldSet: false,
2362
+ value: void 0,
2363
+ errors: [
2364
+ `Field "${targetAttr}" is not applicable or absent on document "${recordRef}". Targeted "${exportMode}" import will not create a new "${targetAttr}" object automatically.`
2365
+ ]
2366
+ };
2195
2367
  }
2196
2368
  }
2197
- return { shouldSet: true, value: directRawVal };
2369
+ } else {
2370
+ if (!hasNonEmptyFirstLevelEdit && (!directTrimmed || directTrimmed === "")) {
2371
+ return { shouldSet: false, value: void 0, errors: [] };
2372
+ }
2198
2373
  }
2199
- let baseObj = hasExistingPlainObj ? deepCloneValue(existingVal) : null;
2200
- let hasEffectiveChange = false;
2201
- if (hasDirectKey && directRawVal !== "" && directRawVal !== void 0 && directRawVal !== null) {
2374
+ const base = isPlainObject(existingDoc?.[targetAttr]) ? deepCloneValue(existingDoc[targetAttr]) : {};
2375
+ const errors = [];
2376
+ let appliedAnyModification = false;
2377
+ if (firstLevelEntries.length === 0 && directRawVal !== void 0 && directRawVal !== null && directTrimmed !== "") {
2202
2378
  if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
2203
- return { shouldSet: true, value: null };
2379
+ return { shouldSet: true, value: null, errors: [] };
2204
2380
  }
2205
2381
  try {
2206
2382
  const parsedDirect = typeof directRawVal === "string" ? JSON.parse(directRawVal) : directRawVal;
2207
2383
  if (isPlainObject(parsedDirect)) {
2208
- baseObj = { ...baseObj || {}, ...deepCloneValue(parsedDirect) };
2209
- hasEffectiveChange = true;
2210
- } else {
2211
- return { shouldSet: true, value: parsedDirect };
2384
+ return {
2385
+ shouldSet: true,
2386
+ value: { ...base, ...deepCloneValue(parsedDirect) },
2387
+ errors: []
2388
+ };
2212
2389
  }
2390
+ return { shouldSet: true, value: parsedDirect, errors: [] };
2213
2391
  } catch {
2214
- return { shouldSet: true, value: directRawVal };
2392
+ return {
2393
+ shouldSet: false,
2394
+ value: void 0,
2395
+ errors: [`Column "${targetAttr}" contains invalid JSON: "${directRawVal}"`]
2396
+ };
2215
2397
  }
2216
2398
  }
2217
- for (const [fullKey, rawCell] of dotEntries) {
2218
- const prefix = `${attrName}.`;
2219
- if (!fullKey.startsWith(prefix)) continue;
2220
- const relPathStr = fullKey.slice(prefix.length);
2221
- const relSegments = relPathStr.split(".").filter(Boolean);
2222
- if (relSegments.length === 0 || relSegments.some((s) => !isSafePathSegment(s))) {
2223
- continue;
2224
- }
2225
- const strCell = rawCell === null || rawCell === void 0 ? "" : String(rawCell);
2399
+ for (const [colKey, propKey, rawCell] of firstLevelEntries) {
2400
+ if (rawCell === void 0 || rawCell === null) continue;
2401
+ const strCell = String(rawCell);
2226
2402
  const trimmed = strCell.trim();
2227
- const annotatedType = rowMeta?.flatTypes?.[fullKey];
2228
- if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2229
- if (!baseObj) baseObj = {};
2230
- setValueAtPath(baseObj, relSegments, null);
2231
- hasEffectiveChange = true;
2232
- continue;
2233
- }
2234
- if (strCell === "") {
2235
- if (hasExistingPlainObj && annotatedType && (annotatedType === "string" || annotatedType === "null" || annotatedType === "object")) {
2236
- const existingAtPath = getValueAtPath(existingVal, relSegments);
2237
- if (existingAtPath.exists) {
2238
- if (annotatedType === "object" && isPlainObject(existingAtPath.value)) {
2239
- if (!isPartialUpdate) hasEffectiveChange = true;
2240
- } else if (annotatedType === "null" && existingAtPath.value === null) {
2241
- if (!isPartialUpdate) hasEffectiveChange = true;
2242
- } else if (annotatedType === "string" && existingAtPath.value === "") {
2243
- if (!isPartialUpdate) hasEffectiveChange = true;
2244
- }
2245
- }
2403
+ if (trimmed === EXPLICIT_DELETE_KEY_TOKEN) {
2404
+ if (Object.prototype.hasOwnProperty.call(base, propKey)) {
2405
+ delete base[propKey];
2406
+ appliedAnyModification = true;
2246
2407
  }
2247
2408
  continue;
2248
2409
  }
2249
- const existingLeaf = hasExistingPlainObj ? getValueAtPath(existingVal, relSegments).value : void 0;
2250
- const parsedVal = parseFlattenedLeafValue(strCell, annotatedType, existingLeaf);
2251
- if (!baseObj) baseObj = {};
2252
- setValueAtPath(baseObj, relSegments, parsedVal);
2253
- hasEffectiveChange = true;
2254
- }
2255
- if (!hasEffectiveChange) {
2256
- if (!isPartialUpdate && hasExistingPlainObj && (rowMeta?.applicableFields?.includes(attrName) || rowMeta?.flatTypes?.[attrName] === "object")) {
2257
- return { shouldSet: true, value: deepCloneValue(existingVal) };
2258
- }
2259
- return { shouldSet: false, value: void 0 };
2260
- }
2261
- return { shouldSet: true, value: baseObj || {} };
2262
- }
2263
- function buildNestedComponentPatchFromDots(attrName, dotEntries) {
2264
- const patch = {};
2265
- let hasEffectiveEdits = false;
2266
- const prefix = `${attrName}.`;
2267
- for (const [fullKey, rawCell] of dotEntries) {
2268
- if (!fullKey.startsWith(prefix)) continue;
2269
- const relPathStr = fullKey.slice(prefix.length);
2270
- const relSegments = relPathStr.split(".").filter(Boolean);
2271
- if (relSegments.length === 0 || relSegments.some((s) => !isSafePathSegment(s))) {
2410
+ if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2411
+ base[propKey] = null;
2412
+ appliedAnyModification = true;
2272
2413
  continue;
2273
2414
  }
2274
- if (rawCell === void 0 || rawCell === null || rawCell === "") {
2415
+ if (strCell === "") {
2275
2416
  continue;
2276
2417
  }
2277
- const strCell = String(rawCell);
2278
- const trimmed = strCell.trim();
2279
- if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2280
- setValueAtPath(patch, relSegments, null);
2281
- hasEffectiveEdits = true;
2418
+ const annotatedType = rowMeta.flatTypes?.[colKey];
2419
+ const existingPropValue = isPlainObject(existingDoc?.[targetAttr]) ? existingDoc[targetAttr][propKey] : void 0;
2420
+ const parsed = parseFirstLevelCellValue(strCell, annotatedType, existingPropValue);
2421
+ if (parsed.error) {
2422
+ errors.push(`Column "${colKey}": ${parsed.error}`);
2282
2423
  continue;
2283
2424
  }
2284
- setValueAtPath(patch, relSegments, strCell);
2285
- hasEffectiveEdits = true;
2425
+ base[propKey] = parsed.value;
2426
+ appliedAnyModification = true;
2286
2427
  }
2287
- return { hasEffectiveEdits, patch };
2288
- }
2289
- function resolveDottedComponentAttrDef(strapi, rootDef, segments) {
2290
- if (!rootDef || segments.length === 0) return null;
2291
- if (segments.length === 1) return rootDef;
2292
- if (rootDef.type === "component" && !rootDef.repeatable && rootDef.component) {
2293
- const comp = strapi.components?.[rootDef.component];
2294
- if (!comp?.attributes) return null;
2295
- const nextAttr = comp.attributes[segments[1]];
2296
- if (!nextAttr) return null;
2297
- return resolveDottedComponentAttrDef(strapi, nextAttr, segments.slice(1));
2428
+ if (errors.length > 0) {
2429
+ return { shouldSet: false, value: void 0, errors };
2298
2430
  }
2299
- return null;
2431
+ if (!appliedAnyModification) {
2432
+ return { shouldSet: false, value: void 0, errors: [] };
2433
+ }
2434
+ if (existingDoc && isPlainObject(existingDoc[targetAttr]) && deepEqualValues(base, existingDoc[targetAttr])) {
2435
+ return { shouldSet: false, value: void 0, errors: [] };
2436
+ }
2437
+ return { shouldSet: true, value: base, errors: [] };
2300
2438
  }
2301
2439
  function validateRecordSchemaConstraints(strapi, uid, existingDoc, payload, rawRow, options) {
2302
2440
  const ct = strapi.contentTypes?.[uid];
@@ -2304,51 +2442,25 @@ function validateRecordSchemaConstraints(strapi, uid, existingDoc, payload, rawR
2304
2442
  const attrs = ct.attributes || {};
2305
2443
  const errors = [];
2306
2444
  const warnings = [];
2307
- const applicableList = Array.isArray(options.rowMeta?.applicableFields) ? new Set(options.rowMeta.applicableFields) : null;
2445
+ const isTargeted = options.detectedMode === "metafields" || options.detectedMode === "topbarconfig";
2308
2446
  const isMissingRequiredValue = (val) => val === void 0 || val === null || typeof val === "string" && val.trim() === "";
2309
- for (const [colKey, rawVal] of Object.entries(rawRow)) {
2310
- if (rawVal === void 0 || rawVal === null) continue;
2311
- const strVal = String(rawVal);
2312
- const trimmed = strVal.trim();
2313
- if (!trimmed || EXPLICIT_CLEAR_TOKENS.has(trimmed)) continue;
2314
- if (colKey.includes(".")) {
2315
- const segments = colKey.split(".").filter(Boolean);
2316
- const rootAttr = attrs[segments[0]];
2317
- if (rootAttr?.type === "component" && !rootAttr.repeatable) {
2318
- const subDef = resolveDottedComponentAttrDef(strapi, rootAttr, segments);
2319
- if (subDef) {
2320
- if (subDef.type === "integer" || subDef.type === "biginteger") {
2321
- if (!/^-?\d+$/.test(trimmed)) {
2322
- errors.push(`Column "${colKey}" expects an integer, received: "${rawVal}"`);
2323
- }
2324
- } else if (subDef.type === "float" || subDef.type === "decimal") {
2325
- if (isNaN(Number(trimmed))) {
2326
- errors.push(`Column "${colKey}" expects a numeric float/decimal, received: "${rawVal}"`);
2327
- }
2328
- } else if (subDef.type === "enumeration" && Array.isArray(subDef.enum)) {
2329
- if (!subDef.enum.includes(trimmed)) {
2330
- warnings.push(
2331
- `Column "${colKey}" value "${rawVal}" is not in defined enum options: [${subDef.enum.join(", ")}]`
2332
- );
2333
- }
2334
- }
2447
+ if (!isTargeted || options.isCreate) {
2448
+ for (const [attrName, attrDef] of Object.entries(attrs)) {
2449
+ if (!attrDef?.required) continue;
2450
+ const norm = attrName.toLowerCase().replace(/[\s_-]/g, "");
2451
+ if (SYSTEM_ATTRIBUTES.has(norm)) continue;
2452
+ if (options.isCreate) {
2453
+ if (isMissingRequiredValue(payload[attrName])) {
2454
+ errors.push(`Missing mandatory field "${attrName}".`);
2335
2455
  }
2456
+ } else if (attrName in payload && isMissingRequiredValue(payload[attrName])) {
2457
+ errors.push(`Mandatory field "${attrName}" cannot be empty or cleared.`);
2336
2458
  }
2337
2459
  }
2338
- }
2339
- for (const [attrName, attrDef] of Object.entries(attrs)) {
2340
- if (!attrDef?.required) continue;
2341
- const norm = attrName.toLowerCase().replace(/[\s_-]/g, "");
2342
- if (SYSTEM_ATTRIBUTES.has(norm)) continue;
2343
- if (options.isCreate) {
2344
- if (applicableList && !applicableList.has(attrName) && payload[attrName] === void 0) {
2345
- continue;
2346
- }
2347
- if (isMissingRequiredValue(payload[attrName])) {
2348
- errors.push(`Missing mandatory field "${attrName}".`);
2349
- }
2350
- } else if (attrName in payload && isMissingRequiredValue(payload[attrName])) {
2351
- errors.push(`Mandatory field "${attrName}" cannot be empty or cleared.`);
2460
+ } else if (options.targetObjectField) {
2461
+ const tDef = attrs[options.targetObjectField];
2462
+ if (tDef?.required && options.targetObjectField in payload && isMissingRequiredValue(payload[options.targetObjectField])) {
2463
+ errors.push(`Mandatory field "${options.targetObjectField}" cannot be empty or cleared.`);
2352
2464
  }
2353
2465
  }
2354
2466
  const validateComponentRequired = (compUid, valueObj, pathPrefix) => {
@@ -2370,7 +2482,36 @@ function validateRecordSchemaConstraints(strapi, uid, existingDoc, payload, rawR
2370
2482
  const nextCompVal = payload[attrName];
2371
2483
  if (isPlainObject(nextCompVal)) {
2372
2484
  validateComponentRequired(attrDef.component, nextCompVal, attrName);
2373
- } else if (nextCompVal === void 0 && isPlainObject(existingDoc?.[attrName]) && (applicableList === null || applicableList.has(attrName))) ;
2485
+ }
2486
+ }
2487
+ }
2488
+ if (isTargeted && options.targetObjectField) {
2489
+ const tDef = attrs[options.targetObjectField];
2490
+ if (tDef?.type === "component" && !tDef.repeatable && tDef.component && strapi.components?.[tDef.component]) {
2491
+ const compAttrs = strapi.components[tDef.component].attributes || {};
2492
+ const prefix = `${options.targetObjectField}.`;
2493
+ for (const [colKey, rawVal] of Object.entries(rawRow)) {
2494
+ if (!colKey.startsWith(prefix)) continue;
2495
+ const propKey = colKey.slice(prefix.length);
2496
+ const subDef = compAttrs[propKey];
2497
+ const trimmed = rawVal === void 0 || rawVal === null ? "" : String(rawVal).trim();
2498
+ if (!subDef || !trimmed || EXPLICIT_CLEAR_TOKENS.has(trimmed) || trimmed === EXPLICIT_DELETE_KEY_TOKEN || trimmed === EXPLICIT_EMPTY_STRING_TOKEN) {
2499
+ continue;
2500
+ }
2501
+ if (subDef.type === "integer" || subDef.type === "biginteger") {
2502
+ if (!/^-?\d+$/.test(trimmed)) {
2503
+ errors.push(`Column "${colKey}" expects an integer, received: "${rawVal}"`);
2504
+ }
2505
+ } else if (subDef.type === "float" || subDef.type === "decimal") {
2506
+ if (isNaN(Number(trimmed))) {
2507
+ errors.push(`Column "${colKey}" expects a numeric float/decimal, received: "${rawVal}"`);
2508
+ }
2509
+ } else if (subDef.type === "enumeration" && Array.isArray(subDef.enum)) {
2510
+ if (!subDef.enum.includes(trimmed)) {
2511
+ warnings.push(`Column "${colKey}" value "${rawVal}" is not in defined enum options: [${subDef.enum.join(", ")}]`);
2512
+ }
2513
+ }
2514
+ }
2374
2515
  }
2375
2516
  }
2376
2517
  return { errors, warnings };
@@ -2581,7 +2722,12 @@ function serializeFieldValue(value, field) {
2581
2722
  }
2582
2723
  function serializeDocumentsToCsv(strapi, uid, documents, options = {}) {
2583
2724
  const schema = options.schema || discoverSchema(strapi, uid);
2584
- const plan = buildExportColumnPlan(strapi, uid, documents || [], schema);
2725
+ const exportMode = normalizeExportMode(options.exportMode);
2726
+ const plan = buildExportColumnPlan(strapi, uid, documents || [], {
2727
+ schema,
2728
+ exportMode,
2729
+ selectedColumns: options.selectedColumns
2730
+ });
2585
2731
  const headers = [METADATA_COLUMN_KEY, ...plan.headers];
2586
2732
  const lines = [];
2587
2733
  lines.push(headers.map(escapeCsvCell).join(","));
@@ -2595,6 +2741,10 @@ function serializeDocumentsToCsv(strapi, uid, documents, options = {}) {
2595
2741
  documentId: String(doc.documentId || doc.id || ""),
2596
2742
  locale: doc.locale || void 0,
2597
2743
  exportedAt,
2744
+ ...flattenedMeta.exportMode ? { exportMode: flattenedMeta.exportMode } : {},
2745
+ ...flattenedMeta.selectedColumns ? { selectedColumns: flattenedMeta.selectedColumns } : {},
2746
+ ...flattenedMeta.targetObjectField ? { targetObjectField: flattenedMeta.targetObjectField } : {},
2747
+ ...flattenedMeta.targetObjectState ? { targetObjectState: flattenedMeta.targetObjectState } : {},
2598
2748
  ...flattenedMeta.applicableFields ? { applicableFields: flattenedMeta.applicableFields } : {},
2599
2749
  ...flattenedMeta.flatTypes ? { flatTypes: flattenedMeta.flatTypes } : {}
2600
2750
  };
@@ -2957,7 +3107,7 @@ async function resolveComponentPayload(strapi, compUid, rawVal, existingVal = {}
2957
3107
  if (isPlainObject(v) && isPlainObject(next[k])) {
2958
3108
  next[k] = deepMergePlain(next[k], v);
2959
3109
  } else {
2960
- next[k] = parseFlattenedLeafValue(v, void 0, next[k]);
3110
+ next[k] = parseFirstLevelCellValue(v, void 0, next[k]).value;
2961
3111
  }
2962
3112
  }
2963
3113
  return next;
@@ -2966,7 +3116,7 @@ async function resolveComponentPayload(strapi, compUid, rawVal, existingVal = {}
2966
3116
  } else if (isPlainObject(fieldVal)) {
2967
3117
  const parsedObj = {};
2968
3118
  for (const [k, v] of Object.entries(fieldVal)) {
2969
- parsedObj[k] = isPlainObject(v) ? deepCloneValue(v) : parseFlattenedLeafValue(v);
3119
+ parsedObj[k] = isPlainObject(v) ? deepCloneValue(v) : parseFirstLevelCellValue(v).value;
2970
3120
  }
2971
3121
  result[attrName] = parsedObj;
2972
3122
  } else if (typeof fieldVal === "string") {
@@ -3002,42 +3152,384 @@ async function resolveDynamicZonePayload(strapi, allowedComponents, rawVal, exis
3002
3152
  } catch {
3003
3153
  return existingVal || [];
3004
3154
  }
3005
- } else if (Array.isArray(rawVal)) {
3006
- list = rawVal;
3007
- } else {
3008
- return existingVal || [];
3009
- }
3010
- if (!Array.isArray(list)) return [];
3011
- const allowedSet = new Set(allowedComponents || []);
3012
- const resolvedBlocks = [];
3013
- for (const block of list) {
3014
- if (!block || typeof block !== "object") continue;
3015
- const compUid = block.__component;
3016
- if (!compUid || typeof compUid !== "string") {
3017
- continue;
3155
+ } else if (Array.isArray(rawVal)) {
3156
+ list = rawVal;
3157
+ } else {
3158
+ return existingVal || [];
3159
+ }
3160
+ if (!Array.isArray(list)) return [];
3161
+ const allowedSet = new Set(allowedComponents || []);
3162
+ const resolvedBlocks = [];
3163
+ for (const block of list) {
3164
+ if (!block || typeof block !== "object") continue;
3165
+ const compUid = block.__component;
3166
+ if (!compUid || typeof compUid !== "string") {
3167
+ continue;
3168
+ }
3169
+ if (allowedSet.size > 0 && !allowedSet.has(compUid)) {
3170
+ continue;
3171
+ }
3172
+ const resolvedAttrs = await resolveComponentPayload(strapi, compUid, block, {});
3173
+ resolvedAttrs.__component = compUid;
3174
+ resolvedBlocks.push(resolvedAttrs);
3175
+ }
3176
+ return resolvedBlocks;
3177
+ }
3178
+ const UNSAFE_PROP_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
3179
+ function buildLegacyNestedPatchFromDots(attrName, dotEntries) {
3180
+ const patch = {};
3181
+ let hasEffectiveEdits = false;
3182
+ const prefix = `${attrName}.`;
3183
+ for (const [fullKey, rawVal] of dotEntries) {
3184
+ if (!fullKey.startsWith(prefix)) continue;
3185
+ if (rawVal === void 0 || rawVal === null || rawVal === "") continue;
3186
+ const segments = fullKey.slice(prefix.length).split(".").filter(Boolean);
3187
+ if (segments.length === 0 || segments.some((s) => UNSAFE_PROP_NAMES.has(s))) continue;
3188
+ const strVal = String(rawVal);
3189
+ const trimmed = strVal.trim();
3190
+ if (trimmed === EXPLICIT_DELETE_KEY_TOKEN) continue;
3191
+ const parsedValue = EXPLICIT_CLEAR_TOKENS.has(trimmed) ? null : trimmed === EXPLICIT_EMPTY_STRING_TOKEN ? "" : parseFirstLevelCellValue(strVal).value;
3192
+ let cursor = patch;
3193
+ for (let i = 0; i < segments.length - 1; i++) {
3194
+ const seg = segments[i];
3195
+ if (!isPlainObject(cursor[seg])) {
3196
+ cursor[seg] = {};
3197
+ }
3198
+ cursor = cursor[seg];
3199
+ }
3200
+ cursor[segments[segments.length - 1]] = parsedValue;
3201
+ hasEffectiveEdits = true;
3202
+ }
3203
+ return { hasEffectiveEdits, patch };
3204
+ }
3205
+ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options = {}) {
3206
+ const schema = discoverSchema(strapi, uid);
3207
+ const payload = {};
3208
+ const errors = [];
3209
+ const warnings = [];
3210
+ const isPartialUpdate = options.isPartialUpdate !== false;
3211
+ const isCreate = options.isCreate !== void 0 ? options.isCreate : !existingDoc;
3212
+ const unescapedRow = {};
3213
+ for (const [k, v] of Object.entries(rawRow || {})) {
3214
+ let cleanVal = v;
3215
+ if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
3216
+ cleanVal = cleanVal.substring(1);
3217
+ }
3218
+ unescapedRow[k] = cleanVal;
3219
+ }
3220
+ const rowInfo = inspectRowMetadataMode(unescapedRow);
3221
+ if (rowInfo.error) {
3222
+ errors.push(rowInfo.error);
3223
+ }
3224
+ const detectedMode = rowInfo.mode;
3225
+ if (options.expectedExportMode && detectedMode !== options.expectedExportMode) {
3226
+ errors.push(
3227
+ `Row exportMode "${detectedMode}" conflicts with batch exportMode "${options.expectedExportMode}".`
3228
+ );
3229
+ }
3230
+ const isTargetedMode = detectedMode === "metafields" || detectedMode === "topbarconfig";
3231
+ const targetAttr = isTargetedMode ? rowInfo.targetObjectField || resolveTargetObjectField(schema, detectedMode) || detectedMode : void 0;
3232
+ if (isTargetedMode && targetAttr && !isCreate) {
3233
+ const targetField = schema.fields[targetAttr];
3234
+ if (!targetField || targetField.category !== "json" && targetField.category !== "component_single") {
3235
+ errors.push(
3236
+ `Target object field "${targetAttr}" for exportMode "${detectedMode}" was not found as an object/component attribute on "${uid}".`
3237
+ );
3238
+ return {
3239
+ payload,
3240
+ errors,
3241
+ warnings,
3242
+ detectedMode,
3243
+ targetObjectField: targetAttr,
3244
+ rowMeta: rowInfo
3245
+ };
3246
+ }
3247
+ const ctAttr = strapi.contentTypes?.[uid]?.attributes?.[targetAttr];
3248
+ const reconstructed = reconstructTargetedFirstLevelObject({
3249
+ targetAttr,
3250
+ exportMode: detectedMode,
3251
+ existingDoc,
3252
+ docIdForError: options.docIdForError,
3253
+ rawRow: unescapedRow,
3254
+ rowMeta: rowInfo,
3255
+ isAttrRequired: Boolean(ctAttr?.required)
3256
+ });
3257
+ if (reconstructed.errors.length > 0) {
3258
+ errors.push(...reconstructed.errors);
3259
+ }
3260
+ if (reconstructed.shouldSet) {
3261
+ if (targetField.category === "component_single" && targetField.componentUid && isPlainObject(reconstructed.value)) {
3262
+ payload[targetAttr] = await resolveComponentPayload(
3263
+ strapi,
3264
+ targetField.componentUid,
3265
+ reconstructed.value,
3266
+ existingDoc?.[targetAttr] || {}
3267
+ );
3268
+ } else {
3269
+ payload[targetAttr] = reconstructed.value;
3270
+ }
3271
+ }
3272
+ const schemaCheck2 = validateRecordSchemaConstraints(
3273
+ strapi,
3274
+ uid,
3275
+ existingDoc,
3276
+ payload,
3277
+ unescapedRow,
3278
+ {
3279
+ isCreate: false,
3280
+ detectedMode,
3281
+ targetObjectField: targetAttr
3282
+ }
3283
+ );
3284
+ errors.push(...schemaCheck2.errors);
3285
+ warnings.push(...schemaCheck2.warnings);
3286
+ return {
3287
+ payload,
3288
+ errors,
3289
+ warnings,
3290
+ detectedMode,
3291
+ targetObjectField: targetAttr,
3292
+ rowMeta: rowInfo
3293
+ };
3294
+ }
3295
+ if (detectedMode === "selective" && !isCreate) {
3296
+ const allowlistedHeaders = Object.keys(unescapedRow).filter(
3297
+ (k) => k !== METADATA_COLUMN_KEY && k !== "__bulk_updater_metadata" && k !== "_bulk_updater_metadata" && k !== "documentId" && k !== "slug"
3298
+ );
3299
+ if (allowlistedHeaders.length === 0) {
3300
+ return {
3301
+ payload: {},
3302
+ errors: [],
3303
+ warnings: [],
3304
+ detectedMode,
3305
+ rowMeta: rowInfo
3306
+ };
3307
+ }
3308
+ let hasRowChanges = false;
3309
+ const modifiedContainers = {};
3310
+ const containerChanged = {};
3311
+ for (const colKey of allowlistedHeaders) {
3312
+ const rawCell = unescapedRow[colKey];
3313
+ if (rawCell === void 0 || rawCell === null) {
3314
+ continue;
3315
+ }
3316
+ const strCell = typeof rawCell === "string" ? rawCell : String(rawCell);
3317
+ const trimmed = strCell.trim();
3318
+ if (strCell === "") {
3319
+ continue;
3320
+ }
3321
+ const isExplicitClear = EXPLICIT_CLEAR_TOKENS.has(trimmed) || trimmed === "null";
3322
+ const isExplicitEmptyString = trimmed === EXPLICIT_EMPTY_STRING_TOKEN;
3323
+ const firstDot = colKey.indexOf(".");
3324
+ if (firstDot === -1) {
3325
+ const field = schema.fields[colKey];
3326
+ const currentVal = existingDoc ? existingDoc[colKey] : void 0;
3327
+ let targetVal;
3328
+ if (isExplicitClear) {
3329
+ targetVal = null;
3330
+ } else if (isExplicitEmptyString) {
3331
+ targetVal = "";
3332
+ } else if (!field) {
3333
+ targetVal = strCell;
3334
+ } else if (field.category === "scalar") {
3335
+ if (field.rawType === "integer" || field.rawType === "biginteger") {
3336
+ targetVal = parseNumeric(strCell, true);
3337
+ } else if (field.rawType === "float" || field.rawType === "decimal") {
3338
+ targetVal = parseNumeric(strCell, false);
3339
+ } else if (field.rawType === "boolean") {
3340
+ targetVal = parseBoolean(strCell);
3341
+ } else if (field.rawType === "enumeration") {
3342
+ if (field.enumOptions && field.enumOptions.length > 0) {
3343
+ const match = field.enumOptions.find((o) => o.toLowerCase() === trimmed.toLowerCase());
3344
+ targetVal = match || trimmed;
3345
+ } else {
3346
+ targetVal = trimmed;
3347
+ }
3348
+ } else {
3349
+ targetVal = strCell;
3350
+ }
3351
+ } else if (field.category === "json") {
3352
+ targetVal = parseFirstLevelCellValue(strCell, "object", currentVal).value;
3353
+ } else if (field.category === "relation_to_one") {
3354
+ targetVal = resolveRelationPayload(strCell, false);
3355
+ } else if (field.category === "relation_to_many") {
3356
+ targetVal = resolveRelationPayload(strCell, true);
3357
+ } else if (field.category === "media_single") {
3358
+ targetVal = await resolveMediaIds(strapi, strCell, false);
3359
+ } else if (field.category === "media_to_many") {
3360
+ targetVal = await resolveMediaIds(strapi, strCell, true);
3361
+ } else {
3362
+ targetVal = strCell;
3363
+ }
3364
+ if (!deepEqualValues(targetVal, currentVal)) {
3365
+ payload[colKey] = targetVal;
3366
+ hasRowChanges = true;
3367
+ }
3368
+ } else {
3369
+ const rootKey = colKey.slice(0, firstDot);
3370
+ const nestedPath = colKey.slice(firstDot + 1);
3371
+ const rootField = schema.fields[rootKey];
3372
+ const isRepeatableOrDz = rootField?.category === "component_repeatable" || rootField?.category === "dynamiczone" || rootField?.rawType === "dynamiczone" || Array.isArray(existingDoc?.[rootKey]);
3373
+ if (isRepeatableOrDz) {
3374
+ const existingList = Array.isArray(existingDoc?.[rootKey]) ? existingDoc[rootKey] : [];
3375
+ let cellOccurrences = [];
3376
+ if (trimmed.startsWith("[")) {
3377
+ try {
3378
+ const parsed = JSON.parse(trimmed);
3379
+ cellOccurrences = Array.isArray(parsed) ? parsed : [parsed];
3380
+ } catch {
3381
+ errors.push(`Column "${colKey}" contains invalid JSON array: "${strCell}"`);
3382
+ continue;
3383
+ }
3384
+ } else {
3385
+ const existingMatches = getAllNestedValues(existingDoc, colKey);
3386
+ if (existingMatches.length > 1) {
3387
+ errors.push(
3388
+ `Ambiguous update: multiple occurrences (${existingMatches.length}) of "${colKey}" exist on document "${options.docIdForError || existingDoc.documentId}", but CSV provided an ambiguous scalar without occurrence IDs.`
3389
+ );
3390
+ continue;
3391
+ } else if (existingMatches.length === 1) {
3392
+ cellOccurrences = [
3393
+ {
3394
+ id: existingMatches[0].componentId,
3395
+ index: existingMatches[0].index,
3396
+ __component: existingMatches[0].componentUid,
3397
+ value: isExplicitClear ? null : isExplicitEmptyString ? "" : strCell
3398
+ }
3399
+ ];
3400
+ } else {
3401
+ errors.push(
3402
+ `Field "${colKey}" is not applicable or has no matching components on document "${options.docIdForError || existingDoc.documentId}".`
3403
+ );
3404
+ continue;
3405
+ }
3406
+ }
3407
+ if (!modifiedContainers[rootKey]) {
3408
+ modifiedContainers[rootKey] = deepCloneValue(existingList);
3409
+ containerChanged[rootKey] = false;
3410
+ }
3411
+ const workingList = modifiedContainers[rootKey];
3412
+ for (const occ of cellOccurrences) {
3413
+ if (!occ || typeof occ !== "object") continue;
3414
+ let targetItem = void 0;
3415
+ if (occ.id !== void 0 && occ.id !== null) {
3416
+ targetItem = workingList.find((it) => it && String(it.id) === String(occ.id));
3417
+ if (!targetItem) {
3418
+ errors.push(
3419
+ `Component occurrence with id "${occ.id}" not found in "${rootKey}" on document "${options.docIdForError || existingDoc.documentId}".`
3420
+ );
3421
+ continue;
3422
+ }
3423
+ } else if (occ.index !== void 0 && occ.index >= 0 && occ.index < workingList.length) {
3424
+ targetItem = workingList[occ.index];
3425
+ if (occ.__component && targetItem && targetItem.__component !== occ.__component) {
3426
+ errors.push(
3427
+ `Component occurrence at index ${occ.index} expected type "${occ.__component}" but found "${targetItem.__component}".`
3428
+ );
3429
+ continue;
3430
+ }
3431
+ } else if (workingList.length === 1) {
3432
+ targetItem = workingList[0];
3433
+ } else {
3434
+ errors.push(
3435
+ `Ambiguous component occurrence in column "${colKey}" on document "${options.docIdForError || existingDoc.documentId}": missing occurrence id.`
3436
+ );
3437
+ continue;
3438
+ }
3439
+ if (targetItem) {
3440
+ let targetVal = occ.value !== void 0 ? occ.value : occ;
3441
+ if (typeof targetVal === "string") {
3442
+ const normVal = targetVal.trim().toLowerCase();
3443
+ if (EXPLICIT_CLEAR_TOKENS.has(normVal)) {
3444
+ targetVal = null;
3445
+ } else if (targetVal === EXPLICIT_EMPTY_STRING_TOKEN) {
3446
+ targetVal = "";
3447
+ }
3448
+ }
3449
+ const currentItemVal = getDeepProp(targetItem, nestedPath);
3450
+ if (!deepEqualValues(targetVal, currentItemVal)) {
3451
+ setDeepProp(targetItem, nestedPath, targetVal);
3452
+ containerChanged[rootKey] = true;
3453
+ hasRowChanges = true;
3454
+ }
3455
+ }
3456
+ }
3457
+ } else {
3458
+ if (existingDoc && !isPlainObject(existingDoc[rootKey])) {
3459
+ const isAttrRequired = Boolean(strapi.contentTypes?.[uid]?.attributes?.[rootKey]?.required);
3460
+ if (!isAttrRequired) {
3461
+ errors.push(
3462
+ `Field "${rootKey}" is not applicable or absent on document "${options.docIdForError || existingDoc.documentId}". Selective import will not create a new "${rootKey}" object automatically.`
3463
+ );
3464
+ continue;
3465
+ }
3466
+ }
3467
+ if (!modifiedContainers[rootKey]) {
3468
+ modifiedContainers[rootKey] = isPlainObject(existingDoc?.[rootKey]) ? deepCloneValue(existingDoc[rootKey]) : {};
3469
+ containerChanged[rootKey] = false;
3470
+ }
3471
+ const workingObj = modifiedContainers[rootKey];
3472
+ const currentVal = getDeepProp(existingDoc?.[rootKey], nestedPath);
3473
+ let targetVal;
3474
+ if (isExplicitClear) {
3475
+ targetVal = null;
3476
+ } else if (isExplicitEmptyString) {
3477
+ targetVal = "";
3478
+ } else {
3479
+ targetVal = parseFirstLevelCellValue(strCell, void 0, currentVal).value;
3480
+ }
3481
+ if (!deepEqualValues(targetVal, currentVal)) {
3482
+ setDeepProp(workingObj, nestedPath, targetVal);
3483
+ containerChanged[rootKey] = true;
3484
+ hasRowChanges = true;
3485
+ }
3486
+ }
3487
+ }
3488
+ }
3489
+ for (const [rKey, changed] of Object.entries(containerChanged)) {
3490
+ if (changed) {
3491
+ payload[rKey] = modifiedContainers[rKey];
3492
+ }
3018
3493
  }
3019
- if (allowedSet.size > 0 && !allowedSet.has(compUid)) {
3020
- continue;
3494
+ if (errors.length > 0) {
3495
+ return {
3496
+ payload: {},
3497
+ errors,
3498
+ warnings,
3499
+ detectedMode: "selective",
3500
+ rowMeta: rowInfo
3501
+ };
3021
3502
  }
3022
- const resolvedAttrs = await resolveComponentPayload(strapi, compUid, block, {});
3023
- resolvedAttrs.__component = compUid;
3024
- resolvedBlocks.push(resolvedAttrs);
3025
- }
3026
- return resolvedBlocks;
3027
- }
3028
- async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
3029
- const schema = discoverSchema(strapi, uid);
3030
- const payload = {};
3031
- const isPartialUpdate = options.isPartialUpdate !== false;
3032
- const unescapedRow = {};
3033
- for (const [k, v] of Object.entries(rawRow)) {
3034
- let cleanVal = v;
3035
- if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
3036
- cleanVal = cleanVal.substring(1);
3503
+ if (!hasRowChanges || Object.keys(payload).length === 0) {
3504
+ return {
3505
+ payload: {},
3506
+ errors: [],
3507
+ warnings: [],
3508
+ detectedMode: "selective",
3509
+ rowMeta: rowInfo
3510
+ };
3037
3511
  }
3038
- unescapedRow[k] = cleanVal;
3512
+ const schemaCheck2 = validateRecordSchemaConstraints(
3513
+ strapi,
3514
+ uid,
3515
+ existingDoc,
3516
+ payload,
3517
+ unescapedRow,
3518
+ {
3519
+ isCreate: false,
3520
+ detectedMode: "selective"
3521
+ }
3522
+ );
3523
+ errors.push(...schemaCheck2.errors);
3524
+ warnings.push(...schemaCheck2.warnings);
3525
+ return {
3526
+ payload,
3527
+ errors,
3528
+ warnings,
3529
+ detectedMode: "selective",
3530
+ rowMeta: rowInfo
3531
+ };
3039
3532
  }
3040
- const rowMeta = extractMetadataFromRow(unescapedRow);
3041
3533
  const dotEntriesByAttr = {};
3042
3534
  for (const [k, v] of Object.entries(unescapedRow)) {
3043
3535
  const firstDot = k.indexOf(".");
@@ -3051,6 +3543,34 @@ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, opti
3051
3543
  const hasDirectKey = attrName in unescapedRow;
3052
3544
  const dotEntries = dotEntriesByAttr[attrName] || [];
3053
3545
  const hasDotKeys = dotEntries.length > 0;
3546
+ if (isTargetedMode && isCreate && targetAttr === attrName) {
3547
+ const ctAttr = strapi.contentTypes?.[uid]?.attributes?.[targetAttr];
3548
+ const reconstructed = reconstructTargetedFirstLevelObject({
3549
+ targetAttr,
3550
+ exportMode: detectedMode,
3551
+ existingDoc: null,
3552
+ docIdForError: options.docIdForError,
3553
+ rawRow: unescapedRow,
3554
+ rowMeta: rowInfo,
3555
+ isAttrRequired: Boolean(ctAttr?.required)
3556
+ });
3557
+ if (reconstructed.errors.length > 0) {
3558
+ errors.push(...reconstructed.errors);
3559
+ }
3560
+ if (reconstructed.shouldSet) {
3561
+ if (field.category === "component_single" && field.componentUid && isPlainObject(reconstructed.value)) {
3562
+ payload[attrName] = await resolveComponentPayload(
3563
+ strapi,
3564
+ field.componentUid,
3565
+ reconstructed.value,
3566
+ {}
3567
+ );
3568
+ } else {
3569
+ payload[attrName] = reconstructed.value;
3570
+ }
3571
+ }
3572
+ continue;
3573
+ }
3054
3574
  if (!hasDirectKey && !hasDotKeys) {
3055
3575
  continue;
3056
3576
  }
@@ -3096,20 +3616,45 @@ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, opti
3096
3616
  break;
3097
3617
  }
3098
3618
  case "json": {
3099
- const reconstructed = reconstructFlattenedJsonAttribute({
3100
- attrName,
3101
- existingVal: existingDoc?.[attrName],
3102
- hasDirectKey,
3103
- directRawVal: rawVal,
3104
- dotEntries,
3105
- rowMeta: rowMeta ? {
3106
- applicableFields: rowMeta.applicableFields,
3107
- flatTypes: rowMeta.flatTypes
3108
- } : null,
3109
- isPartialUpdate
3110
- });
3111
- if (reconstructed.shouldSet) {
3112
- payload[attrName] = reconstructed.value;
3619
+ if (hasDotKeys) {
3620
+ const { hasEffectiveEdits, patch } = buildLegacyNestedPatchFromDots(
3621
+ attrName,
3622
+ dotEntries
3623
+ );
3624
+ if (hasEffectiveEdits) {
3625
+ const mergeDeep = (base, p) => {
3626
+ if (!isPlainObject(base) || !isPlainObject(p)) return p;
3627
+ const next = deepCloneValue(base);
3628
+ for (const [k, v] of Object.entries(p)) {
3629
+ if (isPlainObject(v) && isPlainObject(next[k])) {
3630
+ next[k] = mergeDeep(next[k], v);
3631
+ } else {
3632
+ next[k] = deepCloneValue(v);
3633
+ }
3634
+ }
3635
+ return next;
3636
+ };
3637
+ payload[attrName] = isPlainObject(existingDoc?.[attrName]) ? mergeDeep(existingDoc[attrName], patch) : patch;
3638
+ break;
3639
+ }
3640
+ }
3641
+ if (hasDirectKey) {
3642
+ const trimmed = typeof rawVal === "string" ? rawVal.trim() : "";
3643
+ if (rawVal === void 0 || rawVal === null || rawVal === "") {
3644
+ if (!isPartialUpdate) {
3645
+ payload[attrName] = null;
3646
+ }
3647
+ } else if (EXPLICIT_CLEAR_TOKENS.has(trimmed) || trimmed === "null") {
3648
+ payload[attrName] = null;
3649
+ } else if (typeof rawVal === "string") {
3650
+ try {
3651
+ payload[attrName] = JSON.parse(rawVal);
3652
+ } catch {
3653
+ payload[attrName] = rawVal;
3654
+ }
3655
+ } else {
3656
+ payload[attrName] = rawVal;
3657
+ }
3113
3658
  }
3114
3659
  break;
3115
3660
  }
@@ -3117,7 +3662,7 @@ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, opti
3117
3662
  if (field.componentUid) {
3118
3663
  const directTrimmed = typeof rawVal === "string" ? rawVal.trim() : "";
3119
3664
  if (hasDotKeys) {
3120
- const { hasEffectiveEdits, patch } = buildNestedComponentPatchFromDots(
3665
+ const { hasEffectiveEdits, patch } = buildLegacyNestedPatchFromDots(
3121
3666
  attrName,
3122
3667
  dotEntries
3123
3668
  );
@@ -3218,7 +3763,32 @@ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, opti
3218
3763
  payload[attrName] = rawVal;
3219
3764
  }
3220
3765
  }
3221
- return payload;
3766
+ const schemaCheck = validateRecordSchemaConstraints(
3767
+ strapi,
3768
+ uid,
3769
+ existingDoc,
3770
+ payload,
3771
+ unescapedRow,
3772
+ {
3773
+ isCreate,
3774
+ detectedMode,
3775
+ targetObjectField: targetAttr
3776
+ }
3777
+ );
3778
+ errors.push(...schemaCheck.errors);
3779
+ warnings.push(...schemaCheck.warnings);
3780
+ return {
3781
+ payload,
3782
+ errors,
3783
+ warnings,
3784
+ detectedMode,
3785
+ targetObjectField: targetAttr,
3786
+ rowMeta: rowInfo
3787
+ };
3788
+ }
3789
+ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
3790
+ const plan = await prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options);
3791
+ return plan.payload;
3222
3792
  }
3223
3793
  function formatComponentDisplayName(compUid) {
3224
3794
  if (!compUid) return "Component";
@@ -4414,6 +4984,7 @@ function getAllNestedValues(obj, path) {
4414
4984
  const parts = parsed.cleanPath.split(".");
4415
4985
  const [head, ...tail] = parts;
4416
4986
  const rootTarget = obj[head];
4987
+ if (rootTarget === void 0 || rootTarget === null) return [];
4417
4988
  if (Array.isArray(rootTarget)) {
4418
4989
  const results = [];
4419
4990
  rootTarget.forEach((item, idx) => {
@@ -4422,12 +4993,29 @@ function getAllNestedValues(obj, path) {
4422
4993
  if (parsed.targetComponentUid && item.__component !== parsed.targetComponentUid) return;
4423
4994
  const compSchema = global.strapi?.components?.[item.__component];
4424
4995
  const fieldInSchema = tail.length > 0 && compSchema?.attributes ? tail[0] in compSchema.attributes : false;
4996
+ if (tail.length > 0) {
4997
+ const subMatches = getAllNestedValues(item, tail.join("."));
4998
+ if (subMatches.length > 0) {
4999
+ subMatches.forEach((sm) => {
5000
+ results.push({
5001
+ index: idx,
5002
+ componentUid: item.__component || sm.componentUid,
5003
+ componentName: item.__component ? formatComponentName(item.__component) : sm.componentName,
5004
+ componentId: item.id !== void 0 && item.id !== null ? item.id : sm.componentId,
5005
+ value: sm.value,
5006
+ path: `${head}[#${idx}${item.__component ? ` ${formatComponentName(item.__component)}` : ""}].${sm.path}`
5007
+ });
5008
+ });
5009
+ return;
5010
+ }
5011
+ }
4425
5012
  const subVal = tail.length > 0 ? getDeepProperty(item, tail.join(".")) : item;
4426
5013
  if (subVal !== void 0 || fieldInSchema) {
4427
5014
  results.push({
4428
5015
  index: idx,
4429
5016
  componentUid: item.__component,
4430
5017
  componentName: formatComponentName(item.__component),
5018
+ componentId: item.id !== void 0 && item.id !== null ? item.id : void 0,
4431
5019
  value: subVal !== void 0 ? subVal : null,
4432
5020
  path: `${head}[#${idx}${item.__component ? ` ${formatComponentName(item.__component)}` : ""}].${tail.join(".")}`
4433
5021
  });
@@ -4435,6 +5023,15 @@ function getAllNestedValues(obj, path) {
4435
5023
  });
4436
5024
  return results;
4437
5025
  }
5026
+ if (typeof rootTarget === "object" && tail.length > 0) {
5027
+ const subMatches = getAllNestedValues(rootTarget, tail.join("."));
5028
+ if (subMatches.length > 0) {
5029
+ return subMatches.map((sm) => ({
5030
+ ...sm,
5031
+ path: `${head}.${sm.path}`
5032
+ }));
5033
+ }
5034
+ }
4438
5035
  const singleVal = getDeepProperty(obj, parsed.cleanPath);
4439
5036
  if (singleVal !== void 0) {
4440
5037
  return [
@@ -9242,13 +9839,44 @@ function formatValueDisplay(val) {
9242
9839
  }
9243
9840
  async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, publishedCounterparts, stats, actionLabel = "Updated") {
9244
9841
  const resolvedDocId = existing.documentId;
9245
- const updatePayload = await buildDocumentUpdatePayload(
9842
+ const mutationPlan = await prepareCsvRowMutation(
9246
9843
  strapi,
9247
9844
  uid,
9248
9845
  existing,
9249
9846
  row,
9250
- { isPartialUpdate: options.mode === "update" }
9847
+ {
9848
+ isPartialUpdate: options.mode === "update",
9849
+ isCreate: false,
9850
+ expectedExportMode: options.expectedExportMode,
9851
+ docIdForError: resolvedDocId
9852
+ }
9251
9853
  );
9854
+ const updatePayload = mutationPlan.payload;
9855
+ if (mutationPlan.errors.length > 0) {
9856
+ const errMsg = mutationPlan.errors[0];
9857
+ stats.skipped++;
9858
+ if (stats.failed !== void 0) stats.failed++;
9859
+ recordFailedCsvRow(
9860
+ stats,
9861
+ rowNumber,
9862
+ row,
9863
+ errMsg,
9864
+ resolvedDocId,
9865
+ options.originalHeaders
9866
+ );
9867
+ stats.diffs.push({
9868
+ uid,
9869
+ collectionName: ct.info?.displayName || uid,
9870
+ documentId: resolvedDocId,
9871
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
9872
+ attribute: mutationPlan.targetObjectField || "",
9873
+ oldValue: null,
9874
+ newValue: null,
9875
+ status: "error",
9876
+ message: errMsg
9877
+ });
9878
+ return;
9879
+ }
9252
9880
  if (Object.keys(updatePayload).length === 0) {
9253
9881
  stats.skipped++;
9254
9882
  stats.diffs.push({
@@ -9300,46 +9928,6 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
9300
9928
  publishStrategy: options.publishStrategy || "safe",
9301
9929
  unreviewedConsent: options.unreviewedConsent
9302
9930
  });
9303
- const rowMeta = extractMetadataFromRow(row);
9304
- const schemaValidation = validateRecordSchemaConstraints(
9305
- strapi,
9306
- uid,
9307
- existing,
9308
- updatePayload,
9309
- row,
9310
- {
9311
- isCreate: false,
9312
- rowMeta: rowMeta ? {
9313
- applicableFields: rowMeta.applicableFields,
9314
- flatTypes: rowMeta.flatTypes
9315
- } : null
9316
- }
9317
- );
9318
- if (schemaValidation.errors.length > 0) {
9319
- const errMsg = schemaValidation.errors[0];
9320
- stats.skipped++;
9321
- if (stats.failed !== void 0) stats.failed++;
9322
- recordFailedCsvRow(
9323
- stats,
9324
- rowNumber,
9325
- row,
9326
- errMsg,
9327
- resolvedDocId,
9328
- options.originalHeaders
9329
- );
9330
- stats.diffs.push({
9331
- uid,
9332
- collectionName: ct.info?.displayName || uid,
9333
- documentId: resolvedDocId,
9334
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
9335
- attribute: "",
9336
- oldValue: null,
9337
- newValue: null,
9338
- status: "error",
9339
- message: errMsg
9340
- });
9341
- return;
9342
- }
9343
9931
  const proposedEntity = deepMergeEntities(existing, updatePayload);
9344
9932
  const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
9345
9933
  if (!valResult.isValid) {
@@ -9422,30 +10010,21 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
9422
10010
  }
9423
10011
  }
9424
10012
  async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, stats) {
9425
- const createPayload = await buildDocumentUpdatePayload(
10013
+ const mutationPlan = await prepareCsvRowMutation(
9426
10014
  strapi,
9427
10015
  uid,
9428
10016
  null,
9429
10017
  row,
9430
- { isPartialUpdate: false }
9431
- );
9432
- const rowMeta = extractMetadataFromRow(row);
9433
- const schemaValidation = validateRecordSchemaConstraints(
9434
- strapi,
9435
- uid,
9436
- null,
9437
- createPayload,
9438
- row,
9439
10018
  {
10019
+ isPartialUpdate: false,
9440
10020
  isCreate: true,
9441
- rowMeta: rowMeta ? {
9442
- applicableFields: rowMeta.applicableFields,
9443
- flatTypes: rowMeta.flatTypes
9444
- } : null
10021
+ expectedExportMode: options.expectedExportMode,
10022
+ docIdForError: docId || `row-${rowNumber}`
9445
10023
  }
9446
10024
  );
9447
- if (schemaValidation.errors.length > 0) {
9448
- const errMsg = schemaValidation.errors[0];
10025
+ const createPayload = mutationPlan.payload;
10026
+ if (mutationPlan.errors.length > 0) {
10027
+ const errMsg = mutationPlan.errors[0];
9449
10028
  stats.skipped++;
9450
10029
  if (stats.failed !== void 0) stats.failed++;
9451
10030
  recordFailedCsvRow(
@@ -9571,6 +10150,40 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9571
10150
  failedRows: [],
9572
10151
  diffs: []
9573
10152
  };
10153
+ const batchModeInfo = detectCsvBatchExportMode(rows);
10154
+ if (batchModeInfo.error) {
10155
+ for (let i = 0; i < rows.length; i++) {
10156
+ const rowNumber = startRowNumber + i;
10157
+ const row = rows[i];
10158
+ const docId = extractDocId(row);
10159
+ stats.skipped++;
10160
+ if (stats.failed !== void 0) stats.failed++;
10161
+ recordFailedCsvRow(
10162
+ stats,
10163
+ rowNumber,
10164
+ row,
10165
+ batchModeInfo.error,
10166
+ docId || void 0,
10167
+ originalHeaders
10168
+ );
10169
+ stats.diffs.push({
10170
+ uid,
10171
+ collectionName: ct.info?.displayName || uid,
10172
+ documentId: docId || `(Row #${rowNumber})`,
10173
+ label: `Row #${rowNumber}`,
10174
+ attribute: "__bulk_updater_metadata",
10175
+ oldValue: null,
10176
+ newValue: null,
10177
+ status: "error",
10178
+ message: batchModeInfo.error
10179
+ });
10180
+ }
10181
+ return stats;
10182
+ }
10183
+ const rowOptions = {
10184
+ ...options,
10185
+ expectedExportMode: batchModeInfo.mode
10186
+ };
9574
10187
  for (let i = 0; i < rows.length; i++) {
9575
10188
  const rowNumber = startRowNumber + i;
9576
10189
  const row = rows[i];
@@ -9623,7 +10236,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9623
10236
  existing,
9624
10237
  row,
9625
10238
  rowNumber,
9626
- options,
10239
+ rowOptions,
9627
10240
  effectiveLocale,
9628
10241
  isEditing,
9629
10242
  isDraftAndPublish,
@@ -9644,7 +10257,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9644
10257
  existing,
9645
10258
  row,
9646
10259
  rowNumber,
9647
- options,
10260
+ rowOptions,
9648
10261
  effectiveLocale,
9649
10262
  isEditing,
9650
10263
  isDraftAndPublish,
@@ -9660,7 +10273,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9660
10273
  docId,
9661
10274
  row,
9662
10275
  rowNumber,
9663
- options,
10276
+ rowOptions,
9664
10277
  effectiveLocale,
9665
10278
  isEditing,
9666
10279
  isDraftAndPublish,
@@ -9680,7 +10293,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9680
10293
  existing,
9681
10294
  row,
9682
10295
  rowNumber,
9683
- options,
10296
+ rowOptions,
9684
10297
  effectiveLocale,
9685
10298
  isEditing,
9686
10299
  isDraftAndPublish,
@@ -9696,7 +10309,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9696
10309
  docId,
9697
10310
  row,
9698
10311
  rowNumber,
9699
- options,
10312
+ rowOptions,
9700
10313
  effectiveLocale,
9701
10314
  isEditing,
9702
10315
  isDraftAndPublish,
@@ -9877,6 +10490,7 @@ const csvService = ({ strapi }) => ({
9877
10490
  }
9878
10491
  const schema = discoverSchema(strapi, uid);
9879
10492
  const deepPopulate = buildLosslessPopulate(strapi, uid);
10493
+ const exportMode = normalizeExportMode(options.exportMode);
9880
10494
  const filterMeta = buildCollectionQueryFilters(strapi, ct, {
9881
10495
  attribute: options.attribute,
9882
10496
  searchAttribute: options.searchAttribute || options.attribute,
@@ -9886,12 +10500,17 @@ const csvService = ({ strapi }) => ({
9886
10500
  documentIds: options.documentIds
9887
10501
  });
9888
10502
  if (!filterMeta.colHasAttribute && filterMeta.normOp && filterMeta.normOp !== "none") {
9889
- const emptySerialized = serializeDocumentsToCsv(strapi, uid, [], { schema });
10503
+ const emptySerialized = serializeDocumentsToCsv(strapi, uid, [], {
10504
+ schema,
10505
+ exportMode,
10506
+ selectedColumns: options.selectedColumns
10507
+ });
9890
10508
  return {
9891
10509
  filename: `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`,
9892
10510
  csvContent: emptySerialized.csvContent,
9893
10511
  count: 0,
9894
- fields: emptySerialized.headers
10512
+ fields: emptySerialized.headers,
10513
+ exportMode
9895
10514
  };
9896
10515
  }
9897
10516
  const filters = filterMeta.filters;
@@ -10002,13 +10621,19 @@ const csvService = ({ strapi }) => ({
10002
10621
  await new Promise((resolve) => setImmediate(resolve));
10003
10622
  }
10004
10623
  }
10005
- const serialized = serializeDocumentsToCsv(strapi, uid, exportedDocs, { exportedAt, schema });
10624
+ const serialized = serializeDocumentsToCsv(strapi, uid, exportedDocs, {
10625
+ exportedAt,
10626
+ schema,
10627
+ exportMode,
10628
+ selectedColumns: options.selectedColumns
10629
+ });
10006
10630
  const filename = `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
10007
10631
  return {
10008
10632
  filename,
10009
10633
  csvContent: serialized.csvContent,
10010
10634
  count: serialized.count,
10011
- fields: serialized.headers
10635
+ fields: serialized.headers,
10636
+ exportMode
10012
10637
  };
10013
10638
  },
10014
10639
  async exportViolationsCsv(ruleId) {
@@ -10053,7 +10678,7 @@ const csvService = ({ strapi }) => ({
10053
10678
  /**
10054
10679
  * Bulk Export: Exports selected entries across multiple collections or a multi-collection batch.
10055
10680
  */
10056
- async exportBulkCsv(selectedEntries) {
10681
+ async exportBulkCsv(selectedEntries, options = {}) {
10057
10682
  if (!selectedEntries || selectedEntries.length === 0) {
10058
10683
  throw new Error("No entries selected for bulk export");
10059
10684
  }
@@ -10065,7 +10690,11 @@ const csvService = ({ strapi }) => ({
10065
10690
  const uids = Object.keys(byUid);
10066
10691
  if (uids.length === 1) {
10067
10692
  const uid = uids[0];
10068
- return await this.exportCollectionCsv(uid, { documentIds: byUid[uid], limit: 0 });
10693
+ return await this.exportCollectionCsv(uid, {
10694
+ documentIds: byUid[uid],
10695
+ limit: 0,
10696
+ selectedColumns: options.selectedColumns
10697
+ });
10069
10698
  }
10070
10699
  const rows = [];
10071
10700
  const headers = [
@@ -10383,6 +11012,28 @@ const csvService = ({ strapi }) => ({
10383
11012
  };
10384
11013
  const errors = [];
10385
11014
  const warnings = [];
11015
+ const batchModeInfo = detectCsvBatchExportMode(rows);
11016
+ if (batchModeInfo.error) {
11017
+ errors.push({
11018
+ row: 1,
11019
+ error: batchModeInfo.error
11020
+ });
11021
+ return {
11022
+ success: true,
11023
+ detectedExportMode: "invalid",
11024
+ totalRows: rows.length,
11025
+ validRows: 0,
11026
+ estimatedUpdates: 0,
11027
+ estimatedCreates: 0,
11028
+ lifecycleStats,
11029
+ hasErrors: true,
11030
+ hasWarnings: false,
11031
+ errors,
11032
+ warnings: [],
11033
+ totalErrorCount: errors.length,
11034
+ totalWarningCount: 0
11035
+ };
11036
+ }
10386
11037
  const docIdsInPreflight = rows.map((r) => extractDocId(r)).filter(Boolean);
10387
11038
  const publishedCounterparts = /* @__PURE__ */ new Map();
10388
11039
  if (isDraftAndPublish && docIdsInPreflight.length > 0) {
@@ -10545,49 +11196,46 @@ const csvService = ({ strapi }) => ({
10545
11196
  }
10546
11197
  }
10547
11198
  }
10548
- let proposedPayload = {};
10549
- try {
10550
- proposedPayload = await buildDocumentUpdatePayload(
10551
- strapi,
10552
- uid,
10553
- existing,
10554
- row,
10555
- { isPartialUpdate: mode === "update" }
10556
- );
10557
- } catch {
10558
- }
10559
- const rowMeta = extractMetadataFromRow(row);
10560
11199
  const isRowCreate = mode === "create_or_override" ? !existing : !existing && mode !== "update";
11200
+ let proposedPayload = {};
10561
11201
  if (!(mode === "update" && (!docId || !existing))) {
10562
- const schemaValidation = validateRecordSchemaConstraints(
10563
- strapi,
10564
- uid,
10565
- existing,
10566
- proposedPayload,
10567
- row,
10568
- {
10569
- isCreate: isRowCreate,
10570
- rowMeta: rowMeta ? {
10571
- applicableFields: rowMeta.applicableFields,
10572
- flatTypes: rowMeta.flatTypes
10573
- } : null
11202
+ try {
11203
+ const mutationPlan = await prepareCsvRowMutation(
11204
+ strapi,
11205
+ uid,
11206
+ existing,
11207
+ row,
11208
+ {
11209
+ isPartialUpdate: mode === "update",
11210
+ isCreate: isRowCreate,
11211
+ expectedExportMode: batchModeInfo.mode,
11212
+ docIdForError: docId || `row-${rowNumber}`
11213
+ }
11214
+ );
11215
+ proposedPayload = mutationPlan.payload;
11216
+ for (const errStr of mutationPlan.errors) {
11217
+ errors.push({
11218
+ row: rowNumber,
11219
+ documentId: docId || void 0,
11220
+ error: errStr
11221
+ });
11222
+ rowHasError = true;
10574
11223
  }
10575
- );
10576
- for (const errStr of schemaValidation.errors) {
11224
+ for (const warnStr of mutationPlan.warnings) {
11225
+ warnings.push({
11226
+ row: rowNumber,
11227
+ documentId: docId || void 0,
11228
+ warning: warnStr
11229
+ });
11230
+ }
11231
+ } catch (prepErr) {
10577
11232
  errors.push({
10578
11233
  row: rowNumber,
10579
11234
  documentId: docId || void 0,
10580
- error: errStr
11235
+ error: prepErr?.message || "Failed to reconstruct CSV payload."
10581
11236
  });
10582
11237
  rowHasError = true;
10583
11238
  }
10584
- for (const warnStr of schemaValidation.warnings) {
10585
- warnings.push({
10586
- row: rowNumber,
10587
- documentId: docId || void 0,
10588
- warning: warnStr
10589
- });
10590
- }
10591
11239
  }
10592
11240
  if (activeRules.length > 0) {
10593
11241
  const proposedEntity = existing ? deepMergeEntities(existing, proposedPayload) : proposedPayload;
@@ -10607,6 +11255,7 @@ const csvService = ({ strapi }) => ({
10607
11255
  }
10608
11256
  return {
10609
11257
  success: true,
11258
+ detectedExportMode: batchModeInfo.mode,
10610
11259
  totalRows: rows.length,
10611
11260
  validRows,
10612
11261
  estimatedUpdates,
@@ -10631,6 +11280,37 @@ const csvService = ({ strapi }) => ({
10631
11280
  }
10632
11281
  const attrs = ct.attributes || {};
10633
11282
  const { mode = "auto" } = options;
11283
+ const batchModeInfo = detectCsvBatchExportMode(rows);
11284
+ if (batchModeInfo.error) {
11285
+ return {
11286
+ success: true,
11287
+ detectedExportMode: "invalid",
11288
+ summary: {
11289
+ total: rows.length,
11290
+ willUpdate: 0,
11291
+ willCreate: 0,
11292
+ unchanged: 0,
11293
+ skipped: rows.length
11294
+ },
11295
+ diffs: [
11296
+ {
11297
+ uid,
11298
+ collectionName: ct.info?.displayName || uid,
11299
+ documentId: "(batch)",
11300
+ label: "CSV Export Mode Check",
11301
+ attribute: "__bulk_updater_metadata",
11302
+ oldValue: null,
11303
+ newValue: null,
11304
+ oldDisplay: "—",
11305
+ newDisplay: "—",
11306
+ hasChange: false,
11307
+ status: "error",
11308
+ action: "skip",
11309
+ message: batchModeInfo.error
11310
+ }
11311
+ ]
11312
+ };
11313
+ }
10634
11314
  const diffs = [];
10635
11315
  let willUpdateCount = 0;
10636
11316
  let willCreateCount = 0;
@@ -10676,13 +11356,39 @@ const csvService = ({ strapi }) => ({
10676
11356
  });
10677
11357
  continue;
10678
11358
  }
10679
- const payload = await buildDocumentUpdatePayload(
11359
+ const isRowCreate = !existing;
11360
+ const mutationPlan = await prepareCsvRowMutation(
10680
11361
  strapi,
10681
11362
  uid,
10682
11363
  existing,
10683
11364
  row,
10684
- { isPartialUpdate: mode === "update" }
11365
+ {
11366
+ isPartialUpdate: mode === "update",
11367
+ isCreate: isRowCreate,
11368
+ expectedExportMode: batchModeInfo.mode,
11369
+ docIdForError: docId || `row-${rowNumber}`
11370
+ }
10685
11371
  );
11372
+ if (mutationPlan.errors.length > 0) {
11373
+ skippedCount++;
11374
+ diffs.push({
11375
+ uid,
11376
+ collectionName: ct.info?.displayName || uid,
11377
+ documentId: existing?.documentId || docId || `(Row #${rowNumber})`,
11378
+ label: existing?.title || existing?.name || existing?.slug || `Row #${rowNumber}`,
11379
+ attribute: mutationPlan.targetObjectField || "(validation)",
11380
+ oldValue: null,
11381
+ newValue: null,
11382
+ oldDisplay: "—",
11383
+ newDisplay: "—",
11384
+ hasChange: false,
11385
+ status: "error",
11386
+ action: "skip",
11387
+ message: mutationPlan.errors.join(" | ")
11388
+ });
11389
+ continue;
11390
+ }
11391
+ const payload = mutationPlan.payload;
10686
11392
  if (existing) {
10687
11393
  const resolvedDocId = existing.documentId || docId;
10688
11394
  const entryLabel = existing.title || existing.name || existing.slug || `Entry #${resolvedDocId}`;
@@ -10785,6 +11491,7 @@ const csvService = ({ strapi }) => ({
10785
11491
  }
10786
11492
  return {
10787
11493
  success: true,
11494
+ detectedExportMode: batchModeInfo.mode,
10788
11495
  summary: {
10789
11496
  total: rows.length,
10790
11497
  willUpdate: willUpdateCount,
@@ -11262,6 +11969,8 @@ const index = {
11262
11969
  };
11263
11970
  exports.CURRENT_SCHEMA_VERSION = CURRENT_SCHEMA_VERSION;
11264
11971
  exports.EXPLICIT_CLEAR_TOKENS = EXPLICIT_CLEAR_TOKENS;
11972
+ exports.EXPLICIT_DELETE_KEY_TOKEN = EXPLICIT_DELETE_KEY_TOKEN;
11973
+ exports.EXPLICIT_EMPTY_STRING_TOKEN = EXPLICIT_EMPTY_STRING_TOKEN;
11265
11974
  exports.FORBIDDEN_OBJECT_KEYS = FORBIDDEN_OBJECT_KEYS;
11266
11975
  exports.METADATA_COLUMN_KEY = METADATA_COLUMN_KEY;
11267
11976
  exports.SYSTEM_ATTRIBUTES = SYSTEM_ATTRIBUTES;
@@ -11271,13 +11980,14 @@ exports.buildDocumentUpdatePayload = buildDocumentUpdatePayload;
11271
11980
  exports.buildErrorCsv = buildErrorCsv;
11272
11981
  exports.buildExportColumnPlan = buildExportColumnPlan;
11273
11982
  exports.buildLosslessPopulate = buildLosslessPopulate;
11274
- exports.buildNestedComponentPatchFromDots = buildNestedComponentPatchFromDots;
11275
11983
  exports.buildRichAttributeMeta = buildRichAttributeMeta;
11276
11984
  exports.classifyAttribute = classifyAttribute;
11277
11985
  exports.coerceAndValidateFieldValue = coerceAndValidateFieldValue;
11278
11986
  exports.deepCloneValue = deepCloneValue;
11987
+ exports.deepEqualValues = deepEqualValues;
11279
11988
  exports.deepMergeEntities = deepMergeEntities;
11280
11989
  exports.default = index;
11990
+ exports.detectCsvBatchExportMode = detectCsvBatchExportMode;
11281
11991
  exports.discoverComponentFields = discoverComponentFields;
11282
11992
  exports.discoverSchema = discoverSchema;
11283
11993
  exports.enumerateOccurrences = enumerateOccurrences;
@@ -11287,27 +11997,30 @@ exports.extractMetadataFromRow = extractMetadataFromRow;
11287
11997
  exports.extractRowFlattenedMetadata = extractRowFlattenedMetadata;
11288
11998
  exports.formatErrorCsvFilename = formatErrorCsvFilename;
11289
11999
  exports.getAllNestedValues = getAllNestedValues;
11290
- exports.getValueAtPath = getValueAtPath;
12000
+ exports.getDeepProp = getDeepProp;
12001
+ exports.inspectRowMetadataMode = inspectRowMetadataMode;
11291
12002
  exports.isPlainObject = isPlainObject;
11292
12003
  exports.isValidDocumentId = isValidDocumentId;
12004
+ exports.normalizeExportMode = normalizeExportMode;
11293
12005
  exports.parseBoolean = parseBoolean;
11294
12006
  exports.parseCsvToMatrix = parseCsvToMatrix;
11295
12007
  exports.parseCsvToRecords = parseCsvToRecords;
11296
- exports.parseFlattenedLeafValue = parseFlattenedLeafValue;
12008
+ exports.parseFirstLevelCellValue = parseFirstLevelCellValue;
11297
12009
  exports.parseNumeric = parseNumeric;
11298
- exports.reconstructFlattenedJsonAttribute = reconstructFlattenedJsonAttribute;
12010
+ exports.prepareCsvRowMutation = prepareCsvRowMutation;
12011
+ exports.reconstructTargetedFirstLevelObject = reconstructTargetedFirstLevelObject;
11299
12012
  exports.resolveBatchTargets = resolveBatchTargets;
11300
12013
  exports.resolveComponentPayload = resolveComponentPayload;
11301
12014
  exports.resolveDynamicZonePayload = resolveDynamicZonePayload;
11302
12015
  exports.resolveErrorColumnName = resolveErrorColumnName;
11303
12016
  exports.resolveMediaIds = resolveMediaIds;
11304
12017
  exports.resolveRelationPayload = resolveRelationPayload;
12018
+ exports.resolveTargetObjectField = resolveTargetObjectField;
11305
12019
  exports.sanitizeUserErrorMessage = sanitizeUserErrorMessage;
11306
12020
  exports.serializeDocumentsToCsv = serializeDocumentsToCsv;
11307
12021
  exports.serializeFieldValue = serializeFieldValue;
11308
- exports.serializeFlattenedLeafValue = serializeFlattenedLeafValue;
11309
12022
  exports.serializePlannedCell = serializePlannedCell;
11310
- exports.setValueAtPath = setValueAtPath;
12023
+ exports.setDeepProp = setDeepProp;
11311
12024
  exports.sortAuditRecordsDesc = sortAuditRecordsDesc;
11312
12025
  exports.validateEntityQuotas = validateEntityQuotas;
11313
12026
  exports.validateRecordSchemaConstraints = validateRecordSchemaConstraints;