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