strapi-plugin-bulk-updater 1.6.0 → 1.6.1
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.
- package/dist/_chunks/{BulkUpdater-D12SUhTd.js → BulkUpdater-DTJLdJJy.js} +344 -169
- package/dist/_chunks/BulkUpdater-DTJLdJJy.js.map +1 -0
- package/dist/_chunks/{BulkUpdater-CTKfvKhE.mjs → BulkUpdater-xj4wH_iI.mjs} +345 -170
- package/dist/_chunks/BulkUpdater-xj4wH_iI.mjs.map +1 -0
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/server/index.js +2367 -1587
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +2367 -1587
- package/dist/server/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/_chunks/BulkUpdater-CTKfvKhE.mjs.map +0 -1
- package/dist/_chunks/BulkUpdater-D12SUhTd.js.map +0 -1
package/dist/server/index.mjs
CHANGED
|
@@ -1728,1021 +1728,2085 @@ function discoverSchema(strapi, uid) {
|
|
|
1728
1728
|
allExportKeys
|
|
1729
1729
|
};
|
|
1730
1730
|
}
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
if (
|
|
1735
|
-
if (
|
|
1736
|
-
|
|
1731
|
+
const EXPLICIT_CLEAR_TOKENS = /* @__PURE__ */ new Set(["__CLEAR__", "__NULL__"]);
|
|
1732
|
+
const FORBIDDEN_OBJECT_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
1733
|
+
function isPlainObject(val) {
|
|
1734
|
+
if (val === null || typeof val !== "object" || Array.isArray(val)) return false;
|
|
1735
|
+
if (val instanceof Date || val instanceof RegExp) return false;
|
|
1736
|
+
const proto = Object.getPrototypeOf(val);
|
|
1737
|
+
return proto === Object.prototype || proto === null;
|
|
1737
1738
|
}
|
|
1738
|
-
function
|
|
1739
|
-
if (
|
|
1740
|
-
|
|
1741
|
-
if (isInteger) {
|
|
1742
|
-
const n = parseInt(cleanStr, 10);
|
|
1743
|
-
return isNaN(n) ? null : n;
|
|
1739
|
+
function deepCloneValue(val) {
|
|
1740
|
+
if (val === null || val === void 0 || typeof val !== "object") {
|
|
1741
|
+
return val;
|
|
1744
1742
|
}
|
|
1745
|
-
|
|
1746
|
-
|
|
1743
|
+
if (val instanceof Date) {
|
|
1744
|
+
return new Date(val.getTime());
|
|
1745
|
+
}
|
|
1746
|
+
if (Array.isArray(val)) {
|
|
1747
|
+
return val.map((item) => deepCloneValue(item));
|
|
1748
|
+
}
|
|
1749
|
+
if (isPlainObject(val)) {
|
|
1750
|
+
const out = {};
|
|
1751
|
+
for (const [k, v] of Object.entries(val)) {
|
|
1752
|
+
if (FORBIDDEN_OBJECT_KEYS.has(k)) continue;
|
|
1753
|
+
out[k] = deepCloneValue(v);
|
|
1754
|
+
}
|
|
1755
|
+
return out;
|
|
1756
|
+
}
|
|
1757
|
+
return val;
|
|
1747
1758
|
}
|
|
1748
|
-
function
|
|
1749
|
-
|
|
1750
|
-
const s = String(rawVal).trim().toLowerCase();
|
|
1751
|
-
if (s === "true" || s === "1" || s === "yes" || s === "y" || s === "on") return true;
|
|
1752
|
-
if (s === "false" || s === "0" || s === "no" || s === "n" || s === "off") return false;
|
|
1753
|
-
return null;
|
|
1759
|
+
function isSafePathSegment(segment) {
|
|
1760
|
+
return Boolean(segment) && !FORBIDDEN_OBJECT_KEYS.has(segment);
|
|
1754
1761
|
}
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
const trimmed = rawVal.trim();
|
|
1762
|
-
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
1763
|
-
try {
|
|
1764
|
-
parsed = JSON.parse(trimmed);
|
|
1765
|
-
} catch {
|
|
1766
|
-
}
|
|
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 };
|
|
1767
1768
|
}
|
|
1769
|
+
if (Array.isArray(cursor) || !Object.prototype.hasOwnProperty.call(cursor, seg)) {
|
|
1770
|
+
return { exists: false, value: void 0 };
|
|
1771
|
+
}
|
|
1772
|
+
cursor = cursor[seg];
|
|
1768
1773
|
}
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1774
|
+
return { exists: true, value: cursor };
|
|
1775
|
+
}
|
|
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;
|
|
1790
|
+
}
|
|
1791
|
+
function classifyLeafType(val) {
|
|
1792
|
+
if (val === null) return "null";
|
|
1793
|
+
if (Array.isArray(val)) return "array";
|
|
1794
|
+
if (isPlainObject(val)) return "object";
|
|
1795
|
+
if (typeof val === "number") return "number";
|
|
1796
|
+
if (typeof val === "boolean") return "boolean";
|
|
1797
|
+
return "string";
|
|
1798
|
+
}
|
|
1799
|
+
function needsTypeAnnotation(val) {
|
|
1800
|
+
if (val === null) return true;
|
|
1801
|
+
if (Array.isArray(val) || isPlainObject(val)) return true;
|
|
1802
|
+
if (typeof val === "number" || typeof val === "boolean") return true;
|
|
1803
|
+
if (typeof val === "string") {
|
|
1804
|
+
const trimmed = val.trim();
|
|
1805
|
+
if (val === "" || trimmed === "null" || trimmed === "true" || trimmed === "false" || trimmed.startsWith("[") || trimmed.startsWith("{") || /^-?\d+(?:\.\d+)?$/.test(trimmed)) {
|
|
1806
|
+
return true;
|
|
1776
1807
|
}
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1808
|
+
}
|
|
1809
|
+
return false;
|
|
1810
|
+
}
|
|
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;
|
|
1789
1831
|
}
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
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
|
+
}
|
|
1793
1855
|
}
|
|
1794
1856
|
}
|
|
1795
|
-
|
|
1796
|
-
if (/^\d+$/.test(str)) {
|
|
1797
|
-
numericIds.push(parseInt(str, 10));
|
|
1798
|
-
} else if (str) {
|
|
1799
|
-
candidateLookups.push(str);
|
|
1800
|
-
}
|
|
1857
|
+
seenObjects.delete(node);
|
|
1801
1858
|
};
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1859
|
+
for (const val of values) {
|
|
1860
|
+
if (isPlainObject(val)) {
|
|
1861
|
+
walk(val, [], /* @__PURE__ */ new WeakSet());
|
|
1805
1862
|
}
|
|
1806
|
-
}
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
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];
|
|
1874
|
+
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 {
|
|
1895
|
+
result.push({
|
|
1896
|
+
header,
|
|
1897
|
+
kind: "flattened_component_leaf",
|
|
1898
|
+
rootKey,
|
|
1899
|
+
pathSegments: nextSegments,
|
|
1900
|
+
componentSubDef: attrDef
|
|
1901
|
+
});
|
|
1902
|
+
}
|
|
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
|
+
});
|
|
1925
|
+
}
|
|
1926
|
+
} else {
|
|
1927
|
+
result.push({
|
|
1928
|
+
header,
|
|
1929
|
+
kind: "flattened_component_leaf",
|
|
1930
|
+
rootKey,
|
|
1931
|
+
pathSegments: nextSegments,
|
|
1932
|
+
componentSubDef: attrDef
|
|
1933
|
+
});
|
|
1812
1934
|
}
|
|
1813
|
-
} else {
|
|
1814
|
-
inspectItem(parsed);
|
|
1815
1935
|
}
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1936
|
+
return result;
|
|
1937
|
+
}
|
|
1938
|
+
function buildExportColumnPlan(strapi, uid, documents, schemaOverride) {
|
|
1939
|
+
const schema = schemaOverride || discoverSchema(strapi, uid);
|
|
1940
|
+
const topLevelNames = new Set(schema.allExportKeys);
|
|
1941
|
+
const columns = [];
|
|
1942
|
+
const flattenedJsonRoots = /* @__PURE__ */ new Set();
|
|
1943
|
+
const flattenedComponentRoots = /* @__PURE__ */ new Set();
|
|
1944
|
+
for (const key of schema.allExportKeys) {
|
|
1945
|
+
if (key === "documentId" || key === "locale") {
|
|
1946
|
+
columns.push({
|
|
1947
|
+
header: key,
|
|
1948
|
+
kind: "system",
|
|
1949
|
+
rootKey: key,
|
|
1950
|
+
pathSegments: [key]
|
|
1951
|
+
});
|
|
1952
|
+
continue;
|
|
1953
|
+
}
|
|
1954
|
+
const field = schema.fields[key];
|
|
1955
|
+
if (!field) {
|
|
1956
|
+
columns.push({
|
|
1957
|
+
header: key,
|
|
1958
|
+
kind: "field",
|
|
1959
|
+
rootKey: key,
|
|
1960
|
+
pathSegments: [key]
|
|
1961
|
+
});
|
|
1962
|
+
continue;
|
|
1963
|
+
}
|
|
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
|
|
1831
1977
|
});
|
|
1832
|
-
if (found?.id) {
|
|
1833
|
-
numericIds.push(found.id);
|
|
1834
|
-
}
|
|
1835
1978
|
}
|
|
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;
|
|
1836
1995
|
}
|
|
1837
|
-
} catch {
|
|
1838
1996
|
}
|
|
1997
|
+
columns.push({
|
|
1998
|
+
header: key,
|
|
1999
|
+
kind: "field",
|
|
2000
|
+
rootKey: key,
|
|
2001
|
+
pathSegments: [key],
|
|
2002
|
+
field
|
|
2003
|
+
});
|
|
1839
2004
|
}
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
2005
|
+
return {
|
|
2006
|
+
columns,
|
|
2007
|
+
headers: columns.map((c) => c.header),
|
|
2008
|
+
flattenedJsonRoots,
|
|
2009
|
+
flattenedComponentRoots
|
|
2010
|
+
};
|
|
2011
|
+
}
|
|
2012
|
+
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
|
+
}
|
|
1843
2027
|
}
|
|
1844
|
-
|
|
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
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
const out = {};
|
|
2037
|
+
if (flattenedRoots.size > 0) {
|
|
2038
|
+
out.applicableFields = applicableFields;
|
|
2039
|
+
}
|
|
2040
|
+
if (Object.keys(flatTypes).length > 0) {
|
|
2041
|
+
out.flatTypes = flatTypes;
|
|
2042
|
+
}
|
|
2043
|
+
return out;
|
|
1845
2044
|
}
|
|
1846
|
-
function
|
|
1847
|
-
if (
|
|
1848
|
-
|
|
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
|
+
function serializePlannedCell(col, doc, serializeFieldFallback) {
|
|
2056
|
+
if (col.kind === "system") {
|
|
2057
|
+
if (col.header === "documentId") return doc?.documentId || doc?.id || "";
|
|
2058
|
+
if (col.header === "locale") return doc?.locale || "";
|
|
2059
|
+
return doc?.[col.header] ?? "";
|
|
2060
|
+
}
|
|
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);
|
|
2066
|
+
}
|
|
2067
|
+
if (col.kind === "flattened_component_leaf") {
|
|
2068
|
+
const { exists, value } = getValueAtPath(doc, col.pathSegments);
|
|
2069
|
+
if (!exists || value === void 0 || value === null) return "";
|
|
2070
|
+
const subDef = col.componentSubDef || {};
|
|
2071
|
+
const subType = String(subDef.type || "").toLowerCase();
|
|
2072
|
+
if (subType === "media") {
|
|
2073
|
+
return serializeFieldFallback(value, {
|
|
2074
|
+
key: col.header,
|
|
2075
|
+
label: col.header,
|
|
2076
|
+
category: subDef.multiple ? "media_to_many" : "media_single",
|
|
2077
|
+
rawType: "media",
|
|
2078
|
+
multiple: Boolean(subDef.multiple)
|
|
2079
|
+
});
|
|
2080
|
+
}
|
|
2081
|
+
if (subType === "relation") {
|
|
2082
|
+
const isToMany = String(subDef.relation || "").toLowerCase().endsWith("many");
|
|
2083
|
+
return serializeFieldFallback(value, {
|
|
2084
|
+
key: col.header,
|
|
2085
|
+
label: col.header,
|
|
2086
|
+
category: isToMany ? "relation_to_many" : "relation_to_one",
|
|
2087
|
+
rawType: "relation",
|
|
2088
|
+
relationType: subDef.relation
|
|
2089
|
+
});
|
|
2090
|
+
}
|
|
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);
|
|
2096
|
+
}
|
|
2097
|
+
return serializeFlattenedLeafValue(value);
|
|
1849
2098
|
}
|
|
1850
|
-
|
|
1851
|
-
if (
|
|
1852
|
-
|
|
1853
|
-
|
|
2099
|
+
const rawValue = doc?.[col.rootKey];
|
|
2100
|
+
if (col.field) {
|
|
2101
|
+
return serializeFieldFallback(rawValue, col.field);
|
|
2102
|
+
}
|
|
2103
|
+
return rawValue;
|
|
2104
|
+
}
|
|
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;
|
|
2111
|
+
}
|
|
2112
|
+
if (annotatedType === "string") {
|
|
2113
|
+
return rawCell;
|
|
2114
|
+
}
|
|
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;
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
if (annotatedType === "boolean" || typeof existingLeafValue === "boolean") {
|
|
2122
|
+
const low = trimmed.toLowerCase();
|
|
2123
|
+
if (low === "true") return true;
|
|
2124
|
+
if (low === "false") return false;
|
|
2125
|
+
}
|
|
2126
|
+
if (annotatedType === "array" || Array.isArray(existingLeafValue)) {
|
|
2127
|
+
if (trimmed.startsWith("[")) {
|
|
1854
2128
|
try {
|
|
1855
|
-
|
|
2129
|
+
return JSON.parse(trimmed);
|
|
1856
2130
|
} catch {
|
|
1857
2131
|
}
|
|
1858
2132
|
}
|
|
1859
2133
|
}
|
|
1860
|
-
if (
|
|
1861
|
-
if (
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
return isToMany ? { set: [String(singleDocId).trim()] } : { set: [String(singleDocId).trim()] };
|
|
2134
|
+
if (annotatedType === "object" || isPlainObject(existingLeafValue)) {
|
|
2135
|
+
if (trimmed.startsWith("{")) {
|
|
2136
|
+
try {
|
|
2137
|
+
return JSON.parse(trimmed);
|
|
2138
|
+
} catch {
|
|
2139
|
+
}
|
|
1867
2140
|
}
|
|
1868
2141
|
}
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
if (id && isValidDocumentId(String(id))) {
|
|
1875
|
-
docIds.push(String(id).trim());
|
|
1876
|
-
}
|
|
1877
|
-
} else if (isValidDocumentId(String(item))) {
|
|
1878
|
-
docIds.push(String(item).trim());
|
|
2142
|
+
if (typeof existingLeafValue === "string") {
|
|
2143
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
2144
|
+
try {
|
|
2145
|
+
return JSON.parse(trimmed);
|
|
2146
|
+
} catch {
|
|
1879
2147
|
}
|
|
1880
2148
|
}
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
2149
|
+
return rawCell;
|
|
2150
|
+
}
|
|
2151
|
+
if (trimmed === "null") return null;
|
|
2152
|
+
if (trimmed === "true") return true;
|
|
2153
|
+
if (trimmed === "false") return false;
|
|
2154
|
+
if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
|
|
2155
|
+
const num = Number(trimmed);
|
|
2156
|
+
if (Number.isFinite(num)) return num;
|
|
2157
|
+
}
|
|
2158
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]") || trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
2159
|
+
try {
|
|
2160
|
+
return JSON.parse(trimmed);
|
|
2161
|
+
} catch {
|
|
1887
2162
|
}
|
|
1888
2163
|
}
|
|
1889
|
-
|
|
1890
|
-
return { set: uniqueDocIds };
|
|
2164
|
+
return rawCell;
|
|
1891
2165
|
}
|
|
1892
|
-
|
|
1893
|
-
const
|
|
1894
|
-
|
|
1895
|
-
|
|
2166
|
+
function reconstructFlattenedJsonAttribute(params) {
|
|
2167
|
+
const {
|
|
2168
|
+
attrName,
|
|
2169
|
+
existingVal,
|
|
2170
|
+
hasDirectKey,
|
|
2171
|
+
directRawVal,
|
|
2172
|
+
dotEntries,
|
|
2173
|
+
rowMeta,
|
|
2174
|
+
isPartialUpdate
|
|
2175
|
+
} = 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 };
|
|
2185
|
+
}
|
|
2186
|
+
if (typeof directRawVal === "string") {
|
|
2187
|
+
try {
|
|
2188
|
+
return { shouldSet: true, value: JSON.parse(directRawVal) };
|
|
2189
|
+
} catch {
|
|
2190
|
+
return { shouldSet: true, value: directRawVal };
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
return { shouldSet: true, value: directRawVal };
|
|
1896
2194
|
}
|
|
1897
|
-
let
|
|
1898
|
-
|
|
2195
|
+
let baseObj = hasExistingPlainObj ? deepCloneValue(existingVal) : null;
|
|
2196
|
+
let hasEffectiveChange = false;
|
|
2197
|
+
if (hasDirectKey && directRawVal !== "" && directRawVal !== void 0 && directRawVal !== null) {
|
|
2198
|
+
if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
|
|
2199
|
+
return { shouldSet: true, value: null };
|
|
2200
|
+
}
|
|
1899
2201
|
try {
|
|
1900
|
-
|
|
2202
|
+
const parsedDirect = typeof directRawVal === "string" ? JSON.parse(directRawVal) : directRawVal;
|
|
2203
|
+
if (isPlainObject(parsedDirect)) {
|
|
2204
|
+
baseObj = { ...baseObj || {}, ...deepCloneValue(parsedDirect) };
|
|
2205
|
+
hasEffectiveChange = true;
|
|
2206
|
+
} else {
|
|
2207
|
+
return { shouldSet: true, value: parsedDirect };
|
|
2208
|
+
}
|
|
1901
2209
|
} catch {
|
|
1902
|
-
return
|
|
2210
|
+
return { shouldSet: true, value: directRawVal };
|
|
1903
2211
|
}
|
|
1904
|
-
} else if (typeof rawVal === "object" && rawVal !== null) {
|
|
1905
|
-
sourceObj = rawVal;
|
|
1906
|
-
} else {
|
|
1907
|
-
return existingVal || {};
|
|
1908
2212
|
}
|
|
1909
|
-
const
|
|
1910
|
-
|
|
1911
|
-
if (
|
|
1912
|
-
|
|
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))) {
|
|
1913
2219
|
continue;
|
|
1914
2220
|
}
|
|
1915
|
-
const
|
|
1916
|
-
const
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
2221
|
+
const strCell = rawCell === null || rawCell === void 0 ? "" : String(rawCell);
|
|
2222
|
+
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
|
+
}
|
|
1924
2241
|
}
|
|
1925
|
-
result[attrName] = cleanedList;
|
|
1926
|
-
} else {
|
|
1927
|
-
result[attrName] = await resolveComponentPayload(
|
|
1928
|
-
strapi,
|
|
1929
|
-
attrDef.component,
|
|
1930
|
-
fieldVal,
|
|
1931
|
-
existingVal?.[attrName] || {}
|
|
1932
|
-
);
|
|
1933
|
-
}
|
|
1934
|
-
} else if (type === "relation") {
|
|
1935
|
-
const isToMany = String(attrDef.relation || "").toLowerCase().endsWith("many");
|
|
1936
|
-
result[attrName] = resolveRelationPayload(fieldVal, isToMany);
|
|
1937
|
-
} else if (type === "media") {
|
|
1938
|
-
result[attrName] = await resolveMediaIds(strapi, fieldVal, Boolean(attrDef.multiple));
|
|
1939
|
-
} else if (type === "integer" || type === "biginteger") {
|
|
1940
|
-
result[attrName] = parseNumeric(fieldVal, true);
|
|
1941
|
-
} else if (type === "float" || type === "decimal") {
|
|
1942
|
-
result[attrName] = parseNumeric(fieldVal, false);
|
|
1943
|
-
} else if (type === "boolean") {
|
|
1944
|
-
result[attrName] = parseBoolean(fieldVal);
|
|
1945
|
-
} else if (type === "json" || type === "blocks") {
|
|
1946
|
-
if (typeof fieldVal === "string") {
|
|
1947
|
-
try {
|
|
1948
|
-
result[attrName] = JSON.parse(fieldVal);
|
|
1949
|
-
} catch {
|
|
1950
|
-
result[attrName] = fieldVal;
|
|
1951
|
-
}
|
|
1952
|
-
} else {
|
|
1953
|
-
result[attrName] = fieldVal;
|
|
1954
2242
|
}
|
|
1955
|
-
|
|
1956
|
-
result[attrName] = fieldVal === null || fieldVal === void 0 ? null : String(fieldVal);
|
|
2243
|
+
continue;
|
|
1957
2244
|
}
|
|
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;
|
|
1958
2250
|
}
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
let list = [];
|
|
1963
|
-
if (typeof rawVal === "string") {
|
|
1964
|
-
try {
|
|
1965
|
-
list = JSON.parse(rawVal);
|
|
1966
|
-
} catch {
|
|
1967
|
-
return existingVal || [];
|
|
2251
|
+
if (!hasEffectiveChange) {
|
|
2252
|
+
if (!isPartialUpdate && hasExistingPlainObj && (rowMeta?.applicableFields?.includes(attrName) || rowMeta?.flatTypes?.[attrName] === "object")) {
|
|
2253
|
+
return { shouldSet: true, value: deepCloneValue(existingVal) };
|
|
1968
2254
|
}
|
|
1969
|
-
|
|
1970
|
-
list = rawVal;
|
|
1971
|
-
} else {
|
|
1972
|
-
return existingVal || [];
|
|
2255
|
+
return { shouldSet: false, value: void 0 };
|
|
1973
2256
|
}
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
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))) {
|
|
1981
2268
|
continue;
|
|
1982
2269
|
}
|
|
1983
|
-
if (
|
|
2270
|
+
if (rawCell === void 0 || rawCell === null || rawCell === "") {
|
|
1984
2271
|
continue;
|
|
1985
2272
|
}
|
|
1986
|
-
const
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
|
|
1993
|
-
const schema = discoverSchema(strapi, uid);
|
|
1994
|
-
const payload = {};
|
|
1995
|
-
const unescapedRow = {};
|
|
1996
|
-
for (const [k, v] of Object.entries(rawRow)) {
|
|
1997
|
-
let cleanVal = v;
|
|
1998
|
-
if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
|
|
1999
|
-
cleanVal = cleanVal.substring(1);
|
|
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;
|
|
2278
|
+
continue;
|
|
2000
2279
|
}
|
|
2001
|
-
|
|
2280
|
+
setValueAtPath(patch, relSegments, strCell);
|
|
2281
|
+
hasEffectiveEdits = true;
|
|
2002
2282
|
}
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
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));
|
|
2011
2294
|
}
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
if (
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
} else {
|
|
2037
|
-
payload[attrName] = trimmed;
|
|
2038
|
-
}
|
|
2039
|
-
} else {
|
|
2040
|
-
payload[attrName] = String(rawVal).trim();
|
|
2041
|
-
}
|
|
2042
|
-
break;
|
|
2043
|
-
}
|
|
2044
|
-
case "blocks": {
|
|
2045
|
-
if (rawVal === void 0 || rawVal === "" || rawVal === null) {
|
|
2046
|
-
payload[attrName] = [];
|
|
2047
|
-
} else {
|
|
2048
|
-
try {
|
|
2049
|
-
const parsed = JSON.parse(rawVal);
|
|
2050
|
-
payload[attrName] = Array.isArray(parsed) ? parsed : [parsed];
|
|
2051
|
-
} catch {
|
|
2052
|
-
payload[attrName] = [
|
|
2053
|
-
{ type: "paragraph", children: [{ type: "text", text: String(rawVal).trim() }] }
|
|
2054
|
-
];
|
|
2055
|
-
}
|
|
2056
|
-
}
|
|
2057
|
-
break;
|
|
2058
|
-
}
|
|
2059
|
-
case "json": {
|
|
2060
|
-
if (rawVal === void 0 || rawVal === "" || rawVal === null) {
|
|
2061
|
-
payload[attrName] = null;
|
|
2062
|
-
} else {
|
|
2063
|
-
try {
|
|
2064
|
-
payload[attrName] = JSON.parse(rawVal);
|
|
2065
|
-
} catch {
|
|
2066
|
-
payload[attrName] = rawVal;
|
|
2067
|
-
}
|
|
2068
|
-
}
|
|
2069
|
-
break;
|
|
2070
|
-
}
|
|
2071
|
-
case "component_single": {
|
|
2072
|
-
if (field.componentUid) {
|
|
2073
|
-
let compInput = rawVal;
|
|
2074
|
-
if (hasDotKeys) {
|
|
2075
|
-
compInput = { ...existingDoc?.[attrName] || {}, ...dotNotationMap[attrName] };
|
|
2076
|
-
}
|
|
2077
|
-
if (compInput === "" || compInput === null) {
|
|
2078
|
-
payload[attrName] = null;
|
|
2079
|
-
} else {
|
|
2080
|
-
payload[attrName] = await resolveComponentPayload(
|
|
2081
|
-
strapi,
|
|
2082
|
-
field.componentUid,
|
|
2083
|
-
compInput,
|
|
2084
|
-
existingDoc?.[attrName] || {}
|
|
2085
|
-
);
|
|
2086
|
-
}
|
|
2087
|
-
}
|
|
2088
|
-
break;
|
|
2089
|
-
}
|
|
2090
|
-
case "component_repeatable": {
|
|
2091
|
-
if (field.componentUid) {
|
|
2092
|
-
if (rawVal === "" || rawVal === null || rawVal === void 0) {
|
|
2093
|
-
payload[attrName] = [];
|
|
2094
|
-
} else {
|
|
2095
|
-
let list = [];
|
|
2096
|
-
try {
|
|
2097
|
-
list = typeof rawVal === "string" ? JSON.parse(rawVal) : rawVal;
|
|
2098
|
-
} catch {
|
|
2295
|
+
return null;
|
|
2296
|
+
}
|
|
2297
|
+
function validateRecordSchemaConstraints(strapi, uid, existingDoc, payload, rawRow, options) {
|
|
2298
|
+
const ct = strapi.contentTypes?.[uid];
|
|
2299
|
+
if (!ct) return { errors: [], warnings: [] };
|
|
2300
|
+
const attrs = ct.attributes || {};
|
|
2301
|
+
const errors2 = [];
|
|
2302
|
+
const warnings = [];
|
|
2303
|
+
const applicableList = Array.isArray(options.rowMeta?.applicableFields) ? new Set(options.rowMeta.applicableFields) : null;
|
|
2304
|
+
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}"`);
|
|
2099
2319
|
}
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
cleanedItems.push(cleaned);
|
|
2110
|
-
}
|
|
2111
|
-
payload[attrName] = cleanedItems;
|
|
2112
|
-
} else {
|
|
2113
|
-
payload[attrName] = [];
|
|
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
|
+
);
|
|
2114
2329
|
}
|
|
2115
2330
|
}
|
|
2116
2331
|
}
|
|
2117
|
-
break;
|
|
2118
|
-
}
|
|
2119
|
-
case "dynamiczone": {
|
|
2120
|
-
const allowedComponents = field.dzComponents || [];
|
|
2121
|
-
if (rawVal === "" || rawVal === null || rawVal === void 0) {
|
|
2122
|
-
payload[attrName] = [];
|
|
2123
|
-
} else {
|
|
2124
|
-
payload[attrName] = await resolveDynamicZonePayload(
|
|
2125
|
-
strapi,
|
|
2126
|
-
allowedComponents,
|
|
2127
|
-
rawVal,
|
|
2128
|
-
existingDoc?.[attrName] || []
|
|
2129
|
-
);
|
|
2130
|
-
}
|
|
2131
|
-
break;
|
|
2132
2332
|
}
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2333
|
+
}
|
|
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;
|
|
2136
2342
|
}
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
break;
|
|
2343
|
+
if (isMissingRequiredValue(payload[attrName])) {
|
|
2344
|
+
errors2.push(`Missing mandatory field "${attrName}".`);
|
|
2140
2345
|
}
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2346
|
+
} else if (attrName in payload && isMissingRequiredValue(payload[attrName])) {
|
|
2347
|
+
errors2.push(`Mandatory field "${attrName}" cannot be empty or cleared.`);
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
const validateComponentRequired = (compUid, valueObj, pathPrefix) => {
|
|
2351
|
+
const comp = strapi.components?.[compUid];
|
|
2352
|
+
if (!comp?.attributes || !isPlainObject(valueObj)) return;
|
|
2353
|
+
for (const [subKey, subDef] of Object.entries(comp.attributes)) {
|
|
2354
|
+
const subPath = `${pathPrefix}.${subKey}`;
|
|
2355
|
+
const subVal = valueObj[subKey];
|
|
2356
|
+
if (subDef?.required && isMissingRequiredValue(subVal)) {
|
|
2357
|
+
errors2.push(`Missing mandatory field "${subPath}".`);
|
|
2144
2358
|
}
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
break;
|
|
2359
|
+
if (subDef?.type === "component" && !subDef.repeatable && subDef.component && isPlainObject(subVal)) {
|
|
2360
|
+
validateComponentRequired(subDef.component, subVal, subPath);
|
|
2148
2361
|
}
|
|
2149
|
-
default:
|
|
2150
|
-
payload[attrName] = rawVal;
|
|
2151
2362
|
}
|
|
2152
|
-
}
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
}
|
|
2160
|
-
function parseAttrPath(path) {
|
|
2161
|
-
if (!path) return { cleanPath: "", rootKey: "", subPath: "" };
|
|
2162
|
-
const bracketMatch = path.match(/^([^.[]+)\[([^\]]+)\](?:\.(.+))?$/);
|
|
2163
|
-
if (bracketMatch) {
|
|
2164
|
-
const rootKey = bracketMatch[1];
|
|
2165
|
-
const selector = bracketMatch[2].trim();
|
|
2166
|
-
const subPath = bracketMatch[3] || "";
|
|
2167
|
-
const cleanPath = subPath ? `${rootKey}.${subPath}` : rootKey;
|
|
2168
|
-
const numMatch = selector.match(/^#?(\d+)/);
|
|
2169
|
-
if (numMatch) {
|
|
2170
|
-
return { cleanPath, rootKey, subPath, targetIndex: parseInt(numMatch[1], 10) };
|
|
2363
|
+
};
|
|
2364
|
+
for (const [attrName, attrDef] of Object.entries(attrs)) {
|
|
2365
|
+
if (attrDef?.type === "component" && !attrDef.repeatable && attrDef.component) {
|
|
2366
|
+
const nextCompVal = payload[attrName];
|
|
2367
|
+
if (isPlainObject(nextCompVal)) {
|
|
2368
|
+
validateComponentRequired(attrDef.component, nextCompVal, attrName);
|
|
2369
|
+
} else if (nextCompVal === void 0 && isPlainObject(existingDoc?.[attrName]) && (applicableList === null || applicableList.has(attrName))) ;
|
|
2171
2370
|
}
|
|
2172
|
-
return { cleanPath, rootKey, subPath, targetComponentUid: selector };
|
|
2173
2371
|
}
|
|
2174
|
-
|
|
2175
|
-
return {
|
|
2176
|
-
cleanPath: path,
|
|
2177
|
-
rootKey: parts[0] || "",
|
|
2178
|
-
subPath: parts.slice(1).join(".")
|
|
2179
|
-
};
|
|
2372
|
+
return { errors: errors2, warnings };
|
|
2180
2373
|
}
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2374
|
+
const METADATA_COLUMN_KEY = "__bulk_updater_metadata";
|
|
2375
|
+
const CURRENT_SCHEMA_VERSION = 1;
|
|
2376
|
+
function escapeCsvCell(val) {
|
|
2377
|
+
if (val === null || val === void 0) return "";
|
|
2378
|
+
let str = "";
|
|
2379
|
+
if (val instanceof Date) {
|
|
2380
|
+
str = val.toISOString();
|
|
2381
|
+
} else if (typeof val === "object") {
|
|
2382
|
+
str = JSON.stringify(val);
|
|
2383
|
+
} else {
|
|
2384
|
+
str = String(val);
|
|
2184
2385
|
}
|
|
2185
|
-
|
|
2186
|
-
if (
|
|
2187
|
-
|
|
2386
|
+
str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
2387
|
+
if (/^[=+@-]/.test(str)) {
|
|
2388
|
+
str = `'${str}`;
|
|
2188
2389
|
}
|
|
2189
|
-
if (
|
|
2190
|
-
|
|
2191
|
-
...attrDef.options.scope !== void 0 ? { scope: attrDef.options.scope } : {},
|
|
2192
|
-
...attrDef.options.disabledBehavior !== void 0 ? { disabledBehavior: attrDef.options.disabledBehavior } : {},
|
|
2193
|
-
...attrDef.options.quotas ? { quotas: { ...attrDef.options.quotas } } : {},
|
|
2194
|
-
...Array.isArray(attrDef.options.items) ? { items: attrDef.options.items.map((it) => ({ ...it })) } : {}
|
|
2195
|
-
};
|
|
2390
|
+
if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
|
|
2391
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
2196
2392
|
}
|
|
2197
|
-
|
|
2198
|
-
|
|
2393
|
+
return str;
|
|
2394
|
+
}
|
|
2395
|
+
function parseCsvToMatrix(csvText) {
|
|
2396
|
+
if (!csvText) return [];
|
|
2397
|
+
let text = csvText;
|
|
2398
|
+
if (text.charCodeAt(0) === 65279) {
|
|
2399
|
+
text = text.slice(1);
|
|
2199
2400
|
}
|
|
2200
|
-
|
|
2201
|
-
|
|
2401
|
+
const rows = [];
|
|
2402
|
+
let currentRow = [];
|
|
2403
|
+
let currentCell = "";
|
|
2404
|
+
let inQuotes = false;
|
|
2405
|
+
let cellIsQuoted = false;
|
|
2406
|
+
for (let i = 0; i < text.length; i++) {
|
|
2407
|
+
const char = text[i];
|
|
2408
|
+
const nextChar = text[i + 1];
|
|
2409
|
+
if (inQuotes) {
|
|
2410
|
+
if (char === '"') {
|
|
2411
|
+
if (nextChar === '"') {
|
|
2412
|
+
currentCell += '"';
|
|
2413
|
+
i++;
|
|
2414
|
+
} else {
|
|
2415
|
+
inQuotes = false;
|
|
2416
|
+
}
|
|
2417
|
+
} else {
|
|
2418
|
+
currentCell += char;
|
|
2419
|
+
}
|
|
2420
|
+
} else {
|
|
2421
|
+
if (char === '"' && !cellIsQuoted && currentCell.trim() === "") {
|
|
2422
|
+
inQuotes = true;
|
|
2423
|
+
cellIsQuoted = true;
|
|
2424
|
+
currentCell = "";
|
|
2425
|
+
} else if (char === ",") {
|
|
2426
|
+
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
2427
|
+
currentCell = "";
|
|
2428
|
+
cellIsQuoted = false;
|
|
2429
|
+
} else if (char === "\r") {
|
|
2430
|
+
if (nextChar === "\n") {
|
|
2431
|
+
i++;
|
|
2432
|
+
}
|
|
2433
|
+
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
2434
|
+
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
2435
|
+
rows.push(currentRow);
|
|
2436
|
+
}
|
|
2437
|
+
currentRow = [];
|
|
2438
|
+
currentCell = "";
|
|
2439
|
+
cellIsQuoted = false;
|
|
2440
|
+
} else if (char === "\n") {
|
|
2441
|
+
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
2442
|
+
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
2443
|
+
rows.push(currentRow);
|
|
2444
|
+
}
|
|
2445
|
+
currentRow = [];
|
|
2446
|
+
currentCell = "";
|
|
2447
|
+
cellIsQuoted = false;
|
|
2448
|
+
} else {
|
|
2449
|
+
if (!(cellIsQuoted && !inQuotes && (char === " " || char === " "))) {
|
|
2450
|
+
currentCell += char;
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2202
2454
|
}
|
|
2203
|
-
if (
|
|
2204
|
-
|
|
2455
|
+
if (currentCell !== "" || cellIsQuoted || currentRow.length > 0) {
|
|
2456
|
+
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
2457
|
+
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
2458
|
+
rows.push(currentRow);
|
|
2459
|
+
}
|
|
2205
2460
|
}
|
|
2206
|
-
|
|
2207
|
-
if (typeof attrDef.max === "number") enriched.max = attrDef.max;
|
|
2208
|
-
if (typeof attrDef.minLength === "number") enriched.minLength = attrDef.minLength;
|
|
2209
|
-
if (typeof attrDef.maxLength === "number") enriched.maxLength = attrDef.maxLength;
|
|
2210
|
-
if (typeof attrDef.regex === "string") enriched.regex = attrDef.regex;
|
|
2211
|
-
if (attrDef.required) enriched.required = true;
|
|
2212
|
-
if (attrDef.target) enriched.target = attrDef.target;
|
|
2213
|
-
if (attrDef.relation) enriched.relationType = attrDef.relation;
|
|
2214
|
-
return enriched;
|
|
2461
|
+
return rows;
|
|
2215
2462
|
}
|
|
2216
|
-
function
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2463
|
+
function parseCsvToRecords(csvText) {
|
|
2464
|
+
const matrix = parseCsvToMatrix(csvText);
|
|
2465
|
+
if (matrix.length < 2) return [];
|
|
2466
|
+
const headers = matrix[0].map((h) => h.trim());
|
|
2467
|
+
const records = [];
|
|
2468
|
+
for (let i = 1; i < matrix.length; i++) {
|
|
2469
|
+
const row = matrix[i];
|
|
2470
|
+
const record = {};
|
|
2471
|
+
headers.forEach((h, idx) => {
|
|
2472
|
+
let val = row[idx] !== void 0 ? row[idx] : "";
|
|
2473
|
+
if (typeof val === "string" && /^'[=+@-]/.test(val)) {
|
|
2474
|
+
val = val.substring(1);
|
|
2475
|
+
}
|
|
2476
|
+
record[h] = val;
|
|
2477
|
+
});
|
|
2478
|
+
records.push(record);
|
|
2479
|
+
}
|
|
2480
|
+
return records;
|
|
2224
2481
|
}
|
|
2225
|
-
function
|
|
2226
|
-
if (
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2482
|
+
function serializeFieldValue(value, field) {
|
|
2483
|
+
if (value === null || value === void 0) {
|
|
2484
|
+
return "";
|
|
2485
|
+
}
|
|
2486
|
+
switch (field.category) {
|
|
2487
|
+
case "scalar": {
|
|
2488
|
+
if (value instanceof Date) {
|
|
2489
|
+
return value.toISOString();
|
|
2490
|
+
}
|
|
2491
|
+
return String(value);
|
|
2231
2492
|
}
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
function enumerateOccurrences(contentType, allComponents, entity, attrPath) {
|
|
2236
|
-
if (!contentType || !attrPath) return [];
|
|
2237
|
-
const parsed = parseAttrPath(attrPath);
|
|
2238
|
-
const parts = parsed.cleanPath.split(".").filter(Boolean);
|
|
2239
|
-
if (parts.length === 0) return [];
|
|
2240
|
-
const results = [];
|
|
2241
|
-
function walk(currentSchema, currentVal, remainingParts, segments, missingIntermediate, firstArrayIndex, resolvedCompUid, resolvedCompId, isRootLevel) {
|
|
2242
|
-
if (!currentSchema?.attributes || remainingParts.length === 0) return;
|
|
2243
|
-
const [head, ...tail] = remainingParts;
|
|
2244
|
-
const attrDef = currentSchema.attributes[head];
|
|
2245
|
-
if (!attrDef) return;
|
|
2246
|
-
const nextVal = currentVal && typeof currentVal === "object" ? currentVal[head] : void 0;
|
|
2247
|
-
if (tail.length === 0) {
|
|
2248
|
-
const nextSegs = [...segments, { key: head }];
|
|
2249
|
-
results.push({
|
|
2250
|
-
occurrenceKey: segments.length === 0 ? "__scalar__" : buildOccurrenceKey(nextSegs),
|
|
2251
|
-
displayPath: buildReadableOccurrencePath(nextSegs),
|
|
2252
|
-
segments: nextSegs,
|
|
2253
|
-
value: nextVal !== void 0 ? nextVal : null,
|
|
2254
|
-
componentUid: resolvedCompUid,
|
|
2255
|
-
componentName: resolvedCompUid ? formatComponentDisplayName(resolvedCompUid) : void 0,
|
|
2256
|
-
componentId: resolvedCompId,
|
|
2257
|
-
index: firstArrayIndex ?? 0,
|
|
2258
|
-
isMissingIntermediate: missingIntermediate,
|
|
2259
|
-
leafSchema: attrDef
|
|
2260
|
-
});
|
|
2261
|
-
return;
|
|
2493
|
+
case "blocks":
|
|
2494
|
+
case "json": {
|
|
2495
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
2262
2496
|
}
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
nextVal.forEach((item, idx) => {
|
|
2266
|
-
if (!item || typeof item !== "object") return;
|
|
2267
|
-
if (isRootLevel && parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) return;
|
|
2268
|
-
if (isRootLevel && parsed.targetComponentUid && item.__component !== parsed.targetComponentUid) return;
|
|
2269
|
-
const compSchema = item.__component ? allComponents?.[item.__component] : null;
|
|
2270
|
-
if (!compSchema) return;
|
|
2271
|
-
const seg = {
|
|
2272
|
-
key: head,
|
|
2273
|
-
index: idx,
|
|
2274
|
-
componentId: item.id,
|
|
2275
|
-
componentUid: item.__component
|
|
2276
|
-
};
|
|
2277
|
-
walk(
|
|
2278
|
-
compSchema,
|
|
2279
|
-
item,
|
|
2280
|
-
tail,
|
|
2281
|
-
[...segments, seg],
|
|
2282
|
-
missingIntermediate,
|
|
2283
|
-
firstArrayIndex ?? idx,
|
|
2284
|
-
item.__component,
|
|
2285
|
-
resolvedCompId ?? item.id,
|
|
2286
|
-
false
|
|
2287
|
-
);
|
|
2288
|
-
});
|
|
2289
|
-
return;
|
|
2497
|
+
case "component_single": {
|
|
2498
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
2290
2499
|
}
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
};
|
|
2305
|
-
walk(
|
|
2306
|
-
compSchema,
|
|
2307
|
-
item,
|
|
2308
|
-
tail,
|
|
2309
|
-
[...segments, seg],
|
|
2310
|
-
missingIntermediate,
|
|
2311
|
-
firstArrayIndex ?? idx,
|
|
2312
|
-
attrDef.component,
|
|
2313
|
-
resolvedCompId ?? item.id,
|
|
2314
|
-
false
|
|
2315
|
-
);
|
|
2500
|
+
case "component_repeatable": {
|
|
2501
|
+
if (Array.isArray(value)) {
|
|
2502
|
+
return JSON.stringify(value);
|
|
2503
|
+
}
|
|
2504
|
+
return typeof value === "object" ? JSON.stringify([value]) : "";
|
|
2505
|
+
}
|
|
2506
|
+
case "dynamiczone": {
|
|
2507
|
+
if (Array.isArray(value)) {
|
|
2508
|
+
const cleaned = value.map((block) => {
|
|
2509
|
+
if (block && typeof block === "object") {
|
|
2510
|
+
return { ...block };
|
|
2511
|
+
}
|
|
2512
|
+
return block;
|
|
2316
2513
|
});
|
|
2317
|
-
|
|
2318
|
-
const isMissing = !nextVal || typeof nextVal !== "object";
|
|
2319
|
-
const seg = {
|
|
2320
|
-
key: head,
|
|
2321
|
-
componentId: !isMissing ? nextVal.id : void 0,
|
|
2322
|
-
componentUid: attrDef.component
|
|
2323
|
-
};
|
|
2324
|
-
walk(
|
|
2325
|
-
compSchema,
|
|
2326
|
-
isMissing ? void 0 : nextVal,
|
|
2327
|
-
tail,
|
|
2328
|
-
[...segments, seg],
|
|
2329
|
-
missingIntermediate || isMissing,
|
|
2330
|
-
firstArrayIndex,
|
|
2331
|
-
resolvedCompUid ?? attrDef.component,
|
|
2332
|
-
resolvedCompId ?? (!isMissing ? nextVal.id : void 0),
|
|
2333
|
-
false
|
|
2334
|
-
);
|
|
2514
|
+
return JSON.stringify(cleaned);
|
|
2335
2515
|
}
|
|
2516
|
+
return "";
|
|
2336
2517
|
}
|
|
2518
|
+
case "relation_to_one": {
|
|
2519
|
+
if (typeof value === "object" && value !== null) {
|
|
2520
|
+
const docId = value.documentId || value.id || "";
|
|
2521
|
+
return JSON.stringify({
|
|
2522
|
+
documentId: String(docId),
|
|
2523
|
+
title: value.title || value.name || value.slug || void 0
|
|
2524
|
+
});
|
|
2525
|
+
}
|
|
2526
|
+
return String(value);
|
|
2527
|
+
}
|
|
2528
|
+
case "relation_to_many": {
|
|
2529
|
+
if (Array.isArray(value)) {
|
|
2530
|
+
const list = value.map((item) => {
|
|
2531
|
+
if (typeof item === "object" && item !== null) {
|
|
2532
|
+
const docId = item.documentId || item.id || "";
|
|
2533
|
+
return {
|
|
2534
|
+
documentId: String(docId),
|
|
2535
|
+
title: item.title || item.name || item.slug || void 0
|
|
2536
|
+
};
|
|
2537
|
+
}
|
|
2538
|
+
return { documentId: String(item) };
|
|
2539
|
+
});
|
|
2540
|
+
return JSON.stringify(list);
|
|
2541
|
+
}
|
|
2542
|
+
return "";
|
|
2543
|
+
}
|
|
2544
|
+
case "media_single": {
|
|
2545
|
+
if (typeof value === "object" && value !== null) {
|
|
2546
|
+
return JSON.stringify({
|
|
2547
|
+
id: value.id,
|
|
2548
|
+
documentId: value.documentId,
|
|
2549
|
+
name: value.name,
|
|
2550
|
+
url: value.url,
|
|
2551
|
+
mime: value.mime
|
|
2552
|
+
});
|
|
2553
|
+
}
|
|
2554
|
+
return String(value);
|
|
2555
|
+
}
|
|
2556
|
+
case "media_to_many": {
|
|
2557
|
+
if (Array.isArray(value)) {
|
|
2558
|
+
const list = value.map((file) => {
|
|
2559
|
+
if (typeof file === "object" && file !== null) {
|
|
2560
|
+
return {
|
|
2561
|
+
id: file.id,
|
|
2562
|
+
documentId: file.documentId,
|
|
2563
|
+
name: file.name,
|
|
2564
|
+
url: file.url,
|
|
2565
|
+
mime: file.mime
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
return file;
|
|
2569
|
+
});
|
|
2570
|
+
return JSON.stringify(list);
|
|
2571
|
+
}
|
|
2572
|
+
return "";
|
|
2573
|
+
}
|
|
2574
|
+
default:
|
|
2575
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
2337
2576
|
}
|
|
2338
|
-
walk(contentType, entity, parts, [], false, void 0, void 0, void 0, true);
|
|
2339
|
-
return results;
|
|
2340
|
-
}
|
|
2341
|
-
function formatRelationState(currentRel, isMulti) {
|
|
2342
|
-
if (isMulti && Array.isArray(currentRel)) {
|
|
2343
|
-
const oldDocIds = currentRel.map((r) => r?.documentId).filter(Boolean);
|
|
2344
|
-
const oldDisplay = currentRel.map((r) => r?.name || r?.title || r?.email || r?.username || r?.documentId).filter(Boolean).join(", ") || "(unlinked / none)";
|
|
2345
|
-
return { oldDocIds, oldDisplay };
|
|
2346
|
-
}
|
|
2347
|
-
if (currentRel && typeof currentRel === "object") {
|
|
2348
|
-
const oldDocIds = currentRel.documentId ? [currentRel.documentId] : [];
|
|
2349
|
-
const oldDisplay = currentRel.name || currentRel.title || currentRel.email || currentRel.username || currentRel.documentId || "(unlinked / none)";
|
|
2350
|
-
return { oldDocIds, oldDisplay };
|
|
2351
|
-
}
|
|
2352
|
-
return { oldDocIds: [], oldDisplay: "(unlinked / none)" };
|
|
2353
2577
|
}
|
|
2354
|
-
function
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2578
|
+
function serializeDocumentsToCsv(strapi, uid, documents, options = {}) {
|
|
2579
|
+
const schema = options.schema || discoverSchema(strapi, uid);
|
|
2580
|
+
const plan = buildExportColumnPlan(strapi, uid, documents || [], schema);
|
|
2581
|
+
const headers = [METADATA_COLUMN_KEY, ...plan.headers];
|
|
2582
|
+
const lines = [];
|
|
2583
|
+
lines.push(headers.map(escapeCsvCell).join(","));
|
|
2584
|
+
const exportedAt = options.exportedAt || (/* @__PURE__ */ new Date()).toISOString();
|
|
2585
|
+
for (const doc of documents) {
|
|
2586
|
+
const rowValues = [];
|
|
2587
|
+
const flattenedMeta = extractRowFlattenedMetadata(plan, doc);
|
|
2588
|
+
const metadata = {
|
|
2589
|
+
schemaVersion: CURRENT_SCHEMA_VERSION,
|
|
2590
|
+
contentType: uid,
|
|
2591
|
+
documentId: String(doc.documentId || doc.id || ""),
|
|
2592
|
+
locale: doc.locale || void 0,
|
|
2593
|
+
exportedAt,
|
|
2594
|
+
...flattenedMeta.applicableFields ? { applicableFields: flattenedMeta.applicableFields } : {},
|
|
2595
|
+
...flattenedMeta.flatTypes ? { flatTypes: flattenedMeta.flatTypes } : {}
|
|
2596
|
+
};
|
|
2597
|
+
rowValues.push(escapeCsvCell(metadata));
|
|
2598
|
+
for (const col of plan.columns) {
|
|
2599
|
+
const cellValue = serializePlannedCell(col, doc, serializeFieldValue);
|
|
2600
|
+
rowValues.push(escapeCsvCell(cellValue));
|
|
2369
2601
|
}
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2602
|
+
lines.push(rowValues.join(","));
|
|
2603
|
+
}
|
|
2604
|
+
const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
|
|
2605
|
+
return {
|
|
2606
|
+
csvContent,
|
|
2607
|
+
headers,
|
|
2608
|
+
count: documents.length
|
|
2609
|
+
};
|
|
2610
|
+
}
|
|
2611
|
+
function extractMetadataFromRow(row) {
|
|
2612
|
+
if (!row || typeof row !== "object") return null;
|
|
2613
|
+
const rawMeta = row[METADATA_COLUMN_KEY] || row["__bulk_updater_metadata"];
|
|
2614
|
+
if (!rawMeta) return null;
|
|
2615
|
+
if (typeof rawMeta === "object") {
|
|
2616
|
+
return rawMeta;
|
|
2617
|
+
}
|
|
2618
|
+
if (typeof rawMeta === "string") {
|
|
2376
2619
|
try {
|
|
2377
|
-
const parsed = JSON.parse(
|
|
2378
|
-
if (parsed && typeof parsed === "object"
|
|
2379
|
-
|
|
2380
|
-
targetDocIds = Array.isArray(parsed.documentIds) ? parsed.documentIds.filter(Boolean).map(String) : parsed.documentId ? [String(parsed.documentId)] : [];
|
|
2381
|
-
display = parsed.label || targetDocIds.join(", ") || `[${mode}]`;
|
|
2382
|
-
} else if (Array.isArray(parsed)) {
|
|
2383
|
-
targetDocIds = parsed.filter(Boolean).map(String);
|
|
2384
|
-
display = targetDocIds.join(", ");
|
|
2385
|
-
} else {
|
|
2386
|
-
targetDocIds = [strVal];
|
|
2387
|
-
display = strVal;
|
|
2620
|
+
const parsed = JSON.parse(rawMeta);
|
|
2621
|
+
if (parsed && typeof parsed === "object") {
|
|
2622
|
+
return parsed;
|
|
2388
2623
|
}
|
|
2389
2624
|
} catch {
|
|
2390
|
-
targetDocIds = [strVal];
|
|
2391
|
-
display = strVal;
|
|
2392
2625
|
}
|
|
2393
2626
|
}
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2627
|
+
return null;
|
|
2628
|
+
}
|
|
2629
|
+
function sanitizeUserErrorMessage(msg) {
|
|
2630
|
+
if (msg === null || msg === void 0) return "Error processing row";
|
|
2631
|
+
const raw = typeof msg === "string" ? msg : String(msg);
|
|
2632
|
+
const cleanedLines = raw.split(/\r?\n/).filter((line) => !/^\s+at\s+.+(\(.+\)|:\d+:\d+)\s*$/.test(line)).map((line) => line.trim()).filter(Boolean);
|
|
2633
|
+
const result = cleanedLines.join(" ").trim();
|
|
2634
|
+
return result || "Error processing row";
|
|
2635
|
+
}
|
|
2636
|
+
function resolveErrorColumnName(existingHeaders) {
|
|
2637
|
+
const existingLower = new Set(
|
|
2638
|
+
existingHeaders.map((h) => String(h || "").trim().toLowerCase())
|
|
2639
|
+
);
|
|
2640
|
+
if (!existingLower.has("error")) {
|
|
2641
|
+
return "Error";
|
|
2403
2642
|
}
|
|
2404
|
-
|
|
2643
|
+
if (!existingLower.has("import error")) {
|
|
2644
|
+
return "Import Error";
|
|
2645
|
+
}
|
|
2646
|
+
let suffix = 2;
|
|
2647
|
+
while (existingLower.has(`import error (${suffix})`)) {
|
|
2648
|
+
suffix++;
|
|
2649
|
+
}
|
|
2650
|
+
return `Import Error (${suffix})`;
|
|
2405
2651
|
}
|
|
2406
|
-
|
|
2407
|
-
|
|
2652
|
+
function formatErrorCsvFilename(collectionTypeOrUid, date = /* @__PURE__ */ new Date()) {
|
|
2653
|
+
const rawSegment = collectionTypeOrUid ? String(collectionTypeOrUid).split(".").pop() || String(collectionTypeOrUid) : "collection";
|
|
2654
|
+
const safeType = rawSegment.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "collection";
|
|
2655
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
2656
|
+
const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(
|
|
2657
|
+
date.getHours()
|
|
2658
|
+
)}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
|
2659
|
+
return `error_${safeType}_${stamp}.csv`;
|
|
2660
|
+
}
|
|
2661
|
+
function buildErrorCsv(options) {
|
|
2662
|
+
const { headers, failedRows } = options || {};
|
|
2663
|
+
if (!Array.isArray(failedRows) || failedRows.length === 0) {
|
|
2408
2664
|
return {
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2665
|
+
csvContent: "",
|
|
2666
|
+
headers: headers ? [...headers] : [],
|
|
2667
|
+
errorColumnName: "Error",
|
|
2668
|
+
errorCount: 0
|
|
2412
2669
|
};
|
|
2413
2670
|
}
|
|
2414
|
-
const
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
const
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2671
|
+
const groupedByRow = /* @__PURE__ */ new Map();
|
|
2672
|
+
for (const item of failedRows) {
|
|
2673
|
+
if (!item || typeof item !== "object") continue;
|
|
2674
|
+
const rowNum = typeof item.row === "number" && !isNaN(item.row) ? item.row : groupedByRow.size + 2;
|
|
2675
|
+
const msg = sanitizeUserErrorMessage(item.error);
|
|
2676
|
+
const existing = groupedByRow.get(rowNum);
|
|
2677
|
+
if (existing) {
|
|
2678
|
+
if (!existing.messages.includes(msg)) {
|
|
2679
|
+
existing.messages.push(msg);
|
|
2680
|
+
}
|
|
2681
|
+
} else {
|
|
2682
|
+
groupedByRow.set(rowNum, {
|
|
2683
|
+
row: rowNum,
|
|
2684
|
+
documentId: item.documentId,
|
|
2685
|
+
messages: [msg],
|
|
2686
|
+
originalRow: item.originalRow && typeof item.originalRow === "object" ? item.originalRow : {}
|
|
2687
|
+
});
|
|
2426
2688
|
}
|
|
2689
|
+
}
|
|
2690
|
+
const orderedEntries = Array.from(groupedByRow.values()).sort((a, b) => a.row - b.row);
|
|
2691
|
+
if (orderedEntries.length === 0) {
|
|
2427
2692
|
return {
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
relationMeta: { isRelation: true, mode: cmd.mode, documentIds: cmd.targetDocIds, display: cmd.display }
|
|
2693
|
+
csvContent: "",
|
|
2694
|
+
headers: headers ? [...headers] : [],
|
|
2695
|
+
errorColumnName: "Error",
|
|
2696
|
+
errorCount: 0
|
|
2433
2697
|
};
|
|
2434
2698
|
}
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2699
|
+
let baseHeaders = [];
|
|
2700
|
+
if (Array.isArray(headers) && headers.length > 0) {
|
|
2701
|
+
baseHeaders = [...headers];
|
|
2702
|
+
} else {
|
|
2703
|
+
const keySet = /* @__PURE__ */ new Set();
|
|
2704
|
+
for (const entry of orderedEntries) {
|
|
2705
|
+
for (const k of Object.keys(entry.originalRow || {})) {
|
|
2706
|
+
if (!keySet.has(k)) {
|
|
2707
|
+
keySet.add(k);
|
|
2708
|
+
baseHeaders.push(k);
|
|
2709
|
+
}
|
|
2440
2710
|
}
|
|
2441
|
-
const cleared = isMultiple ? [] : null;
|
|
2442
|
-
return { valid: true, value: cleared, displayValue: "(cleared)" };
|
|
2443
|
-
}
|
|
2444
|
-
const mediaPayload = strapi ? await resolveMediaIds(strapi, rawValue, isMultiple) : rawValue;
|
|
2445
|
-
if (attrDef.required && (mediaPayload === null || Array.isArray(mediaPayload) && mediaPayload.length === 0)) {
|
|
2446
|
-
return { valid: false, value: rawValue, displayValue: "", error: "Media asset could not be resolved." };
|
|
2447
2711
|
}
|
|
2448
|
-
return {
|
|
2449
|
-
valid: true,
|
|
2450
|
-
value: mediaPayload,
|
|
2451
|
-
displayValue: Array.isArray(mediaPayload) ? `[${mediaPayload.length} asset(s)]` : mediaPayload !== null ? `#${mediaPayload}` : "(cleared)"
|
|
2452
|
-
};
|
|
2453
|
-
}
|
|
2454
|
-
const isEmptyInput = rawValue === null || rawValue === void 0 || rawValue === "";
|
|
2455
|
-
if (attrDef.required && (isEmptyInput || type === "boolean" && rawValue === null)) {
|
|
2456
|
-
return {
|
|
2457
|
-
valid: false,
|
|
2458
|
-
value: rawValue,
|
|
2459
|
-
displayValue: "",
|
|
2460
|
-
error: "Field is required and cannot be empty."
|
|
2461
|
-
};
|
|
2462
2712
|
}
|
|
2463
|
-
|
|
2464
|
-
|
|
2713
|
+
const errorColumnName = resolveErrorColumnName(baseHeaders);
|
|
2714
|
+
const finalHeaders = [...baseHeaders, errorColumnName];
|
|
2715
|
+
const lines = [];
|
|
2716
|
+
lines.push(finalHeaders.map(escapeCsvCell).join(","));
|
|
2717
|
+
for (const entry of orderedEntries) {
|
|
2718
|
+
const cells = baseHeaders.map((h) => {
|
|
2719
|
+
const val = entry.originalRow ? entry.originalRow[h] : "";
|
|
2720
|
+
return escapeCsvCell(val === void 0 || val === null ? "" : val);
|
|
2721
|
+
});
|
|
2722
|
+
cells.push(escapeCsvCell(entry.messages.join("; ")));
|
|
2723
|
+
lines.push(cells.join(","));
|
|
2465
2724
|
}
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2725
|
+
const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
|
|
2726
|
+
return {
|
|
2727
|
+
csvContent,
|
|
2728
|
+
headers: finalHeaders,
|
|
2729
|
+
errorColumnName,
|
|
2730
|
+
errorCount: orderedEntries.length
|
|
2731
|
+
};
|
|
2732
|
+
}
|
|
2733
|
+
function isValidDocumentId(val) {
|
|
2734
|
+
if (!val || typeof val !== "string") return false;
|
|
2735
|
+
const trimmed = val.trim();
|
|
2736
|
+
if (!trimmed) return false;
|
|
2737
|
+
if (/\s/.test(trimmed)) return false;
|
|
2738
|
+
return /^[a-zA-Z0-9_-]+$/.test(trimmed);
|
|
2739
|
+
}
|
|
2740
|
+
function parseNumeric(rawVal, isInteger) {
|
|
2741
|
+
if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
|
|
2742
|
+
const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
|
|
2743
|
+
if (isInteger) {
|
|
2744
|
+
const n = parseInt(cleanStr, 10);
|
|
2745
|
+
return isNaN(n) ? null : n;
|
|
2746
|
+
}
|
|
2747
|
+
const f = parseFloat(cleanStr);
|
|
2748
|
+
return isNaN(f) ? null : f;
|
|
2749
|
+
}
|
|
2750
|
+
function parseBoolean(rawVal) {
|
|
2751
|
+
if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
|
|
2752
|
+
const s = String(rawVal).trim().toLowerCase();
|
|
2753
|
+
if (s === "true" || s === "1" || s === "yes" || s === "y" || s === "on") return true;
|
|
2754
|
+
if (s === "false" || s === "0" || s === "no" || s === "n" || s === "off") return false;
|
|
2755
|
+
return null;
|
|
2756
|
+
}
|
|
2757
|
+
async function resolveMediaIds(strapi, rawVal, isMultiple) {
|
|
2758
|
+
if (rawVal === null || rawVal === void 0 || rawVal === "") {
|
|
2759
|
+
return isMultiple ? [] : null;
|
|
2760
|
+
}
|
|
2761
|
+
let parsed = rawVal;
|
|
2762
|
+
if (typeof rawVal === "string") {
|
|
2763
|
+
const trimmed = rawVal.trim();
|
|
2764
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
2765
|
+
try {
|
|
2766
|
+
parsed = JSON.parse(trimmed);
|
|
2767
|
+
} catch {
|
|
2490
2768
|
}
|
|
2491
|
-
return { valid: true, value: str, displayValue: str };
|
|
2492
2769
|
}
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
if (!Number.isFinite(num)) {
|
|
2502
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Number "${str}" is not finite.` };
|
|
2503
|
-
}
|
|
2504
|
-
if (typeof attrDef.min === "number" && num < attrDef.min) {
|
|
2505
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} is less than minimum ${attrDef.min}.` };
|
|
2506
|
-
}
|
|
2507
|
-
if (typeof attrDef.max === "number" && num > attrDef.max) {
|
|
2508
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} exceeds maximum ${attrDef.max}.` };
|
|
2509
|
-
}
|
|
2510
|
-
return { valid: true, value: num, displayValue: String(num) };
|
|
2770
|
+
}
|
|
2771
|
+
const numericIds = [];
|
|
2772
|
+
const candidateLookups = [];
|
|
2773
|
+
const inspectItem = (item) => {
|
|
2774
|
+
if (item === null || item === void 0) return;
|
|
2775
|
+
if (typeof item === "number" && !isNaN(item)) {
|
|
2776
|
+
numericIds.push(item);
|
|
2777
|
+
return;
|
|
2511
2778
|
}
|
|
2512
|
-
|
|
2513
|
-
if (
|
|
2514
|
-
|
|
2515
|
-
return
|
|
2516
|
-
}
|
|
2517
|
-
const lower = String(rawValue).trim().toLowerCase();
|
|
2518
|
-
if (lower === "true" || lower === "1" || lower === "yes") {
|
|
2519
|
-
return { valid: true, value: true, displayValue: "true" };
|
|
2520
|
-
}
|
|
2521
|
-
if (lower === "false" || lower === "0" || lower === "no") {
|
|
2522
|
-
return { valid: true, value: false, displayValue: "false" };
|
|
2779
|
+
if (typeof item === "object") {
|
|
2780
|
+
if (typeof item.id === "number") {
|
|
2781
|
+
numericIds.push(item.id);
|
|
2782
|
+
return;
|
|
2523
2783
|
}
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
2528
|
-
const str = String(rawValue);
|
|
2529
|
-
if (Array.isArray(attrDef.enum) && !attrDef.enum.includes(str)) {
|
|
2530
|
-
return {
|
|
2531
|
-
valid: false,
|
|
2532
|
-
value: rawValue,
|
|
2533
|
-
displayValue: str,
|
|
2534
|
-
error: `Value "${str}" is not an allowed enum option (${attrDef.enum.join(", ")}).`
|
|
2535
|
-
};
|
|
2784
|
+
if (typeof item.id === "string" && /^\d+$/.test(item.id)) {
|
|
2785
|
+
numericIds.push(parseInt(item.id, 10));
|
|
2786
|
+
return;
|
|
2536
2787
|
}
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
const str = String(rawValue).trim();
|
|
2541
|
-
if (str === "") return { valid: true, value: "", displayValue: "(empty)" };
|
|
2542
|
-
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str)) {
|
|
2543
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Invalid email address "${str}".` };
|
|
2788
|
+
if (item.documentId) {
|
|
2789
|
+
candidateLookups.push(String(item.documentId));
|
|
2790
|
+
return;
|
|
2544
2791
|
}
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
const str = String(rawValue).trim();
|
|
2549
|
-
if (str !== "" && !/^[A-Za-z0-9\-_.~]*$/.test(str)) {
|
|
2550
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Invalid UID slug "${str}". Allowed characters: A-Z a-z 0-9 - _ . ~` };
|
|
2792
|
+
if (item.url) {
|
|
2793
|
+
candidateLookups.push(String(item.url));
|
|
2794
|
+
return;
|
|
2551
2795
|
}
|
|
2552
|
-
return { valid: true, value: str, displayValue: str || "(empty)" };
|
|
2553
2796
|
}
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
try {
|
|
2560
|
-
parsedVal = JSON.parse(rawValue);
|
|
2561
|
-
} catch (err) {
|
|
2562
|
-
return {
|
|
2563
|
-
valid: false,
|
|
2564
|
-
value: rawValue,
|
|
2565
|
-
displayValue: rawValue,
|
|
2566
|
-
error: `Invalid ${type === "blocks" ? "Blocks" : "JSON"} syntax: ${err.message}`
|
|
2567
|
-
};
|
|
2568
|
-
}
|
|
2569
|
-
}
|
|
2570
|
-
if (type === "blocks" && parsedVal !== null && !Array.isArray(parsedVal)) {
|
|
2571
|
-
return { valid: false, value: rawValue, displayValue: String(rawValue), error: "Strapi Blocks field must be a JSON array." };
|
|
2572
|
-
}
|
|
2573
|
-
return {
|
|
2574
|
-
valid: true,
|
|
2575
|
-
value: parsedVal,
|
|
2576
|
-
displayValue: parsedVal === null ? "(empty)" : JSON.stringify(parsedVal)
|
|
2577
|
-
};
|
|
2797
|
+
const str = String(item).trim();
|
|
2798
|
+
if (/^\d+$/.test(str)) {
|
|
2799
|
+
numericIds.push(parseInt(str, 10));
|
|
2800
|
+
} else if (str) {
|
|
2801
|
+
candidateLookups.push(str);
|
|
2578
2802
|
}
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
const d = new Date(str);
|
|
2584
|
-
if (isNaN(d.getTime())) {
|
|
2585
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Invalid ${type} value "${str}".` };
|
|
2586
|
-
}
|
|
2587
|
-
const out = type === "date" ? /^\d{4}-\d{2}-\d{2}$/.test(str) ? str : d.toISOString().slice(0, 10) : d.toISOString();
|
|
2588
|
-
return { valid: true, value: out, displayValue: out };
|
|
2803
|
+
};
|
|
2804
|
+
if (Array.isArray(parsed)) {
|
|
2805
|
+
for (const el of parsed) {
|
|
2806
|
+
inspectItem(el);
|
|
2589
2807
|
}
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
return { valid: true, value: str, displayValue: str };
|
|
2808
|
+
} else if (typeof parsed === "object" && parsed !== null) {
|
|
2809
|
+
inspectItem(parsed);
|
|
2810
|
+
} else if (typeof rawVal === "string" && (rawVal.includes(",") || rawVal.includes(";"))) {
|
|
2811
|
+
const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean);
|
|
2812
|
+
for (const part of parts) {
|
|
2813
|
+
inspectItem(part);
|
|
2597
2814
|
}
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2815
|
+
} else {
|
|
2816
|
+
inspectItem(parsed);
|
|
2817
|
+
}
|
|
2818
|
+
if (candidateLookups.length > 0) {
|
|
2819
|
+
try {
|
|
2820
|
+
const fileQuery = strapi.db?.query("plugin::upload.file");
|
|
2821
|
+
if (fileQuery) {
|
|
2822
|
+
for (const candidate of candidateLookups) {
|
|
2823
|
+
const found = await fileQuery.findOne({
|
|
2824
|
+
where: {
|
|
2825
|
+
$or: [
|
|
2826
|
+
{ documentId: candidate },
|
|
2827
|
+
{ url: candidate },
|
|
2828
|
+
{ hash: candidate },
|
|
2829
|
+
{ name: candidate }
|
|
2830
|
+
]
|
|
2831
|
+
},
|
|
2832
|
+
select: ["id"]
|
|
2833
|
+
});
|
|
2834
|
+
if (found?.id) {
|
|
2835
|
+
numericIds.push(found.id);
|
|
2611
2836
|
}
|
|
2612
|
-
} catch {
|
|
2613
2837
|
}
|
|
2614
2838
|
}
|
|
2615
|
-
|
|
2839
|
+
} catch {
|
|
2616
2840
|
}
|
|
2617
2841
|
}
|
|
2842
|
+
const uniqueNumericIds = Array.from(new Set(numericIds));
|
|
2843
|
+
if (isMultiple) {
|
|
2844
|
+
return uniqueNumericIds;
|
|
2845
|
+
}
|
|
2846
|
+
return uniqueNumericIds.length > 0 ? uniqueNumericIds[0] : null;
|
|
2618
2847
|
}
|
|
2619
|
-
function
|
|
2620
|
-
if (
|
|
2621
|
-
|
|
2848
|
+
function resolveRelationPayload(rawVal, isToMany) {
|
|
2849
|
+
if (rawVal === null || rawVal === void 0 || rawVal === "") {
|
|
2850
|
+
return isToMany ? { set: [] } : { set: [] };
|
|
2622
2851
|
}
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
throw new Error(
|
|
2632
|
-
`Stale target: component instance (id: ${seg.componentId}) in "${arrFieldKey}" was modified or deleted. Please refresh the grid and retry.`
|
|
2633
|
-
);
|
|
2852
|
+
let parsed = rawVal;
|
|
2853
|
+
if (typeof rawVal === "string") {
|
|
2854
|
+
const trimmed = rawVal.trim();
|
|
2855
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
2856
|
+
try {
|
|
2857
|
+
parsed = JSON.parse(trimmed);
|
|
2858
|
+
} catch {
|
|
2859
|
+
}
|
|
2634
2860
|
}
|
|
2635
|
-
return idMatchIdx;
|
|
2636
2861
|
}
|
|
2637
|
-
if (typeof
|
|
2638
|
-
if (
|
|
2639
|
-
|
|
2640
|
-
`Stale target: occurrence #${seg.index} in "${arrFieldKey}" no longer exists (length ${arr.length}). Please refresh the grid and retry.`
|
|
2641
|
-
);
|
|
2862
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
2863
|
+
if (parsed.set || parsed.connect || parsed.disconnect) {
|
|
2864
|
+
return parsed;
|
|
2642
2865
|
}
|
|
2643
|
-
const
|
|
2644
|
-
if (
|
|
2645
|
-
|
|
2646
|
-
`Stale target: occurrence #${seg.index} in "${arrFieldKey}" changed component type to "${item.__component}". Please refresh the grid.`
|
|
2647
|
-
);
|
|
2866
|
+
const singleDocId = parsed.documentId || parsed.id;
|
|
2867
|
+
if (singleDocId && isValidDocumentId(String(singleDocId))) {
|
|
2868
|
+
return isToMany ? { set: [String(singleDocId).trim()] } : { set: [String(singleDocId).trim()] };
|
|
2648
2869
|
}
|
|
2649
|
-
return seg.index;
|
|
2650
2870
|
}
|
|
2651
|
-
|
|
2871
|
+
const docIds = [];
|
|
2872
|
+
if (Array.isArray(parsed)) {
|
|
2873
|
+
for (const item of parsed) {
|
|
2874
|
+
if (item && typeof item === "object") {
|
|
2875
|
+
const id = item.documentId || item.id;
|
|
2876
|
+
if (id && isValidDocumentId(String(id))) {
|
|
2877
|
+
docIds.push(String(id).trim());
|
|
2878
|
+
}
|
|
2879
|
+
} else if (isValidDocumentId(String(item))) {
|
|
2880
|
+
docIds.push(String(item).trim());
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
} else if (typeof rawVal === "string") {
|
|
2884
|
+
if (rawVal.includes(",") || rawVal.includes(";")) {
|
|
2885
|
+
const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocumentId(p));
|
|
2886
|
+
docIds.push(...parts);
|
|
2887
|
+
} else if (isValidDocumentId(rawVal.trim())) {
|
|
2888
|
+
docIds.push(rawVal.trim());
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
const uniqueDocIds = Array.from(new Set(docIds));
|
|
2892
|
+
return { set: uniqueDocIds };
|
|
2652
2893
|
}
|
|
2653
|
-
function
|
|
2654
|
-
|
|
2655
|
-
|
|
2894
|
+
async function resolveComponentPayload(strapi, compUid, rawVal, existingVal = {}) {
|
|
2895
|
+
const comp = strapi.components?.[compUid];
|
|
2896
|
+
if (!comp?.attributes) {
|
|
2897
|
+
return typeof rawVal === "object" ? rawVal : {};
|
|
2656
2898
|
}
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2899
|
+
let sourceObj = {};
|
|
2900
|
+
if (typeof rawVal === "string") {
|
|
2901
|
+
try {
|
|
2902
|
+
sourceObj = JSON.parse(rawVal);
|
|
2903
|
+
} catch {
|
|
2904
|
+
return existingVal || {};
|
|
2905
|
+
}
|
|
2906
|
+
} else if (typeof rawVal === "object" && rawVal !== null) {
|
|
2907
|
+
sourceObj = rawVal;
|
|
2908
|
+
} else {
|
|
2909
|
+
return existingVal || {};
|
|
2910
|
+
}
|
|
2911
|
+
const result = { ...existingVal || {} };
|
|
2912
|
+
for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
|
|
2913
|
+
if (SYSTEM_ATTRIBUTES.has(attrName.toLowerCase().replace(/[\s_-]/g, ""))) continue;
|
|
2914
|
+
if (!(attrName in sourceObj)) {
|
|
2915
|
+
continue;
|
|
2916
|
+
}
|
|
2917
|
+
const fieldVal = sourceObj[attrName];
|
|
2918
|
+
const type = String(attrDef.type || "").toLowerCase();
|
|
2919
|
+
if (type === "component") {
|
|
2920
|
+
if (attrDef.repeatable) {
|
|
2921
|
+
const list = Array.isArray(fieldVal) ? fieldVal : [];
|
|
2922
|
+
const cleanedList = [];
|
|
2923
|
+
for (const item of list) {
|
|
2924
|
+
const subCleaned = await resolveComponentPayload(strapi, attrDef.component, item, {});
|
|
2925
|
+
cleanedList.push(subCleaned);
|
|
2672
2926
|
}
|
|
2673
|
-
|
|
2927
|
+
result[attrName] = cleanedList;
|
|
2928
|
+
} else {
|
|
2929
|
+
result[attrName] = await resolveComponentPayload(
|
|
2930
|
+
strapi,
|
|
2931
|
+
attrDef.component,
|
|
2932
|
+
fieldVal,
|
|
2933
|
+
existingVal?.[attrName] || {}
|
|
2934
|
+
);
|
|
2674
2935
|
}
|
|
2675
|
-
|
|
2676
|
-
const
|
|
2677
|
-
|
|
2678
|
-
} else {
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2936
|
+
} else if (type === "relation") {
|
|
2937
|
+
const isToMany = String(attrDef.relation || "").toLowerCase().endsWith("many");
|
|
2938
|
+
result[attrName] = resolveRelationPayload(fieldVal, isToMany);
|
|
2939
|
+
} else if (type === "media") {
|
|
2940
|
+
result[attrName] = await resolveMediaIds(strapi, fieldVal, Boolean(attrDef.multiple));
|
|
2941
|
+
} else if (type === "integer" || type === "biginteger") {
|
|
2942
|
+
result[attrName] = parseNumeric(fieldVal, true);
|
|
2943
|
+
} else if (type === "float" || type === "decimal") {
|
|
2944
|
+
result[attrName] = parseNumeric(fieldVal, false);
|
|
2945
|
+
} else if (type === "boolean") {
|
|
2946
|
+
result[attrName] = parseBoolean(fieldVal);
|
|
2947
|
+
} else if (type === "json") {
|
|
2948
|
+
if (isPlainObject(fieldVal) && isPlainObject(existingVal?.[attrName])) {
|
|
2949
|
+
const deepMergePlain = (base, patch) => {
|
|
2950
|
+
if (!isPlainObject(base) || !isPlainObject(patch)) return patch;
|
|
2951
|
+
const next = deepCloneValue(base);
|
|
2952
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
2953
|
+
if (isPlainObject(v) && isPlainObject(next[k])) {
|
|
2954
|
+
next[k] = deepMergePlain(next[k], v);
|
|
2955
|
+
} else {
|
|
2956
|
+
next[k] = parseFlattenedLeafValue(v, void 0, next[k]);
|
|
2957
|
+
}
|
|
2958
|
+
}
|
|
2959
|
+
return next;
|
|
2960
|
+
};
|
|
2961
|
+
result[attrName] = deepMergePlain(existingVal[attrName], fieldVal);
|
|
2962
|
+
} else if (isPlainObject(fieldVal)) {
|
|
2963
|
+
const parsedObj = {};
|
|
2964
|
+
for (const [k, v] of Object.entries(fieldVal)) {
|
|
2965
|
+
parsedObj[k] = isPlainObject(v) ? deepCloneValue(v) : parseFlattenedLeafValue(v);
|
|
2966
|
+
}
|
|
2967
|
+
result[attrName] = parsedObj;
|
|
2968
|
+
} else if (typeof fieldVal === "string") {
|
|
2969
|
+
try {
|
|
2970
|
+
result[attrName] = JSON.parse(fieldVal);
|
|
2971
|
+
} catch {
|
|
2972
|
+
result[attrName] = fieldVal;
|
|
2973
|
+
}
|
|
2974
|
+
} else {
|
|
2975
|
+
result[attrName] = fieldVal;
|
|
2976
|
+
}
|
|
2977
|
+
} else if (type === "blocks") {
|
|
2978
|
+
if (typeof fieldVal === "string") {
|
|
2979
|
+
try {
|
|
2980
|
+
result[attrName] = JSON.parse(fieldVal);
|
|
2981
|
+
} catch {
|
|
2982
|
+
result[attrName] = fieldVal;
|
|
2983
|
+
}
|
|
2984
|
+
} else {
|
|
2985
|
+
result[attrName] = fieldVal;
|
|
2682
2986
|
}
|
|
2987
|
+
} else {
|
|
2988
|
+
result[attrName] = fieldVal === null || fieldVal === void 0 ? null : String(fieldVal);
|
|
2683
2989
|
}
|
|
2684
2990
|
}
|
|
2685
|
-
return
|
|
2991
|
+
return result;
|
|
2686
2992
|
}
|
|
2687
|
-
function
|
|
2688
|
-
|
|
2689
|
-
|
|
2993
|
+
async function resolveDynamicZonePayload(strapi, allowedComponents, rawVal, existingVal = []) {
|
|
2994
|
+
let list = [];
|
|
2995
|
+
if (typeof rawVal === "string") {
|
|
2996
|
+
try {
|
|
2997
|
+
list = JSON.parse(rawVal);
|
|
2998
|
+
} catch {
|
|
2999
|
+
return existingVal || [];
|
|
3000
|
+
}
|
|
3001
|
+
} else if (Array.isArray(rawVal)) {
|
|
3002
|
+
list = rawVal;
|
|
3003
|
+
} else {
|
|
3004
|
+
return existingVal || [];
|
|
2690
3005
|
}
|
|
2691
|
-
if (
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
currentDoc,
|
|
2700
|
-
attribute,
|
|
2701
|
-
updates
|
|
2702
|
-
}) {
|
|
2703
|
-
const parsed = parseAttrPath(attribute);
|
|
2704
|
-
const parts = parsed.cleanPath.split(".").filter(Boolean);
|
|
2705
|
-
const rootKey = parts[0];
|
|
2706
|
-
const rootAttrDef = contentType?.attributes?.[rootKey];
|
|
2707
|
-
const diffs = [];
|
|
2708
|
-
const errors2 = [];
|
|
2709
|
-
if (parts.length === 1 && rootAttrDef?.type !== "component" && rootAttrDef?.type !== "dynamiczone") {
|
|
2710
|
-
const updateItem = updates[0];
|
|
2711
|
-
if (!updateItem) {
|
|
2712
|
-
return { updateData: {}, diffs: [], errors: [] };
|
|
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;
|
|
2713
3014
|
}
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
const rawCurrent = currentDoc?.[rootKey];
|
|
2717
|
-
const coerced = await coerceAndValidateFieldValue(rootAttrDef, updateItem.value, strapi, { forComponentNested: false });
|
|
2718
|
-
if (!coerced.valid) {
|
|
2719
|
-
errors2.push(coerced.error || `Invalid value for ${rootKey}`);
|
|
2720
|
-
return { updateData: {}, diffs: [], errors: errors2 };
|
|
3015
|
+
if (allowedSet.size > 0 && !allowedSet.has(compUid)) {
|
|
3016
|
+
continue;
|
|
2721
3017
|
}
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
newValOut = coerced.value;
|
|
2738
|
-
newDisplay = coerced.displayValue;
|
|
2739
|
-
hasChange = !areValuesEquivalent(rawCurrent, coerced.value);
|
|
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);
|
|
2740
3033
|
}
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
3034
|
+
unescapedRow[k] = cleanVal;
|
|
3035
|
+
}
|
|
3036
|
+
const rowMeta = extractMetadataFromRow(unescapedRow);
|
|
3037
|
+
const dotEntriesByAttr = {};
|
|
3038
|
+
for (const [k, v] of Object.entries(unescapedRow)) {
|
|
3039
|
+
const firstDot = k.indexOf(".");
|
|
3040
|
+
if (firstDot > 0) {
|
|
3041
|
+
const parent = k.slice(0, firstDot);
|
|
3042
|
+
if (!dotEntriesByAttr[parent]) dotEntriesByAttr[parent] = [];
|
|
3043
|
+
dotEntriesByAttr[parent].push([k, v]);
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
for (const [attrName, field] of Object.entries(schema.fields)) {
|
|
3047
|
+
const hasDirectKey = attrName in unescapedRow;
|
|
3048
|
+
const dotEntries = dotEntriesByAttr[attrName] || [];
|
|
3049
|
+
const hasDotKeys = dotEntries.length > 0;
|
|
3050
|
+
if (!hasDirectKey && !hasDotKeys) {
|
|
3051
|
+
continue;
|
|
3052
|
+
}
|
|
3053
|
+
const rawVal = hasDirectKey ? unescapedRow[attrName] : void 0;
|
|
3054
|
+
switch (field.category) {
|
|
3055
|
+
case "scalar": {
|
|
3056
|
+
if (rawVal === void 0 || rawVal === "" || rawVal === null) {
|
|
3057
|
+
payload[attrName] = null;
|
|
3058
|
+
} else if (field.rawType === "integer" || field.rawType === "biginteger") {
|
|
3059
|
+
payload[attrName] = parseNumeric(rawVal, true);
|
|
3060
|
+
} else if (field.rawType === "float" || field.rawType === "decimal") {
|
|
3061
|
+
payload[attrName] = parseNumeric(rawVal, false);
|
|
3062
|
+
} else if (field.rawType === "boolean") {
|
|
3063
|
+
payload[attrName] = parseBoolean(rawVal);
|
|
3064
|
+
} else if (field.rawType === "date" || field.rawType === "time" || field.rawType === "datetime" || field.rawType === "timestamp") {
|
|
3065
|
+
payload[attrName] = String(rawVal).trim() || null;
|
|
3066
|
+
} else if (field.rawType === "enumeration") {
|
|
3067
|
+
const trimmed = String(rawVal).trim();
|
|
3068
|
+
if (field.enumOptions && field.enumOptions.length > 0) {
|
|
3069
|
+
const match = field.enumOptions.find((o) => o.toLowerCase() === trimmed.toLowerCase());
|
|
3070
|
+
payload[attrName] = match || trimmed;
|
|
3071
|
+
} else {
|
|
3072
|
+
payload[attrName] = trimmed;
|
|
3073
|
+
}
|
|
3074
|
+
} else {
|
|
3075
|
+
payload[attrName] = String(rawVal).trim();
|
|
3076
|
+
}
|
|
3077
|
+
break;
|
|
3078
|
+
}
|
|
3079
|
+
case "blocks": {
|
|
3080
|
+
if (rawVal === void 0 || rawVal === "" || rawVal === null) {
|
|
3081
|
+
payload[attrName] = [];
|
|
3082
|
+
} else {
|
|
3083
|
+
try {
|
|
3084
|
+
const parsed = JSON.parse(rawVal);
|
|
3085
|
+
payload[attrName] = Array.isArray(parsed) ? parsed : [parsed];
|
|
3086
|
+
} catch {
|
|
3087
|
+
payload[attrName] = [
|
|
3088
|
+
{ type: "paragraph", children: [{ type: "text", text: String(rawVal).trim() }] }
|
|
3089
|
+
];
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
break;
|
|
3093
|
+
}
|
|
3094
|
+
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;
|
|
3109
|
+
}
|
|
3110
|
+
break;
|
|
3111
|
+
}
|
|
3112
|
+
case "component_single": {
|
|
3113
|
+
if (field.componentUid) {
|
|
3114
|
+
const directTrimmed = typeof rawVal === "string" ? rawVal.trim() : "";
|
|
3115
|
+
if (hasDotKeys) {
|
|
3116
|
+
const { hasEffectiveEdits, patch } = buildNestedComponentPatchFromDots(
|
|
3117
|
+
attrName,
|
|
3118
|
+
dotEntries
|
|
3119
|
+
);
|
|
3120
|
+
if (hasEffectiveEdits) {
|
|
3121
|
+
payload[attrName] = await resolveComponentPayload(
|
|
3122
|
+
strapi,
|
|
3123
|
+
field.componentUid,
|
|
3124
|
+
patch,
|
|
3125
|
+
existingDoc?.[attrName] || {}
|
|
3126
|
+
);
|
|
3127
|
+
} else if (hasDirectKey && rawVal !== "" && rawVal !== void 0 && rawVal !== null) {
|
|
3128
|
+
if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
|
|
3129
|
+
payload[attrName] = null;
|
|
3130
|
+
} else {
|
|
3131
|
+
payload[attrName] = await resolveComponentPayload(
|
|
3132
|
+
strapi,
|
|
3133
|
+
field.componentUid,
|
|
3134
|
+
rawVal,
|
|
3135
|
+
existingDoc?.[attrName] || {}
|
|
3136
|
+
);
|
|
3137
|
+
}
|
|
3138
|
+
}
|
|
3139
|
+
} else if (hasDirectKey) {
|
|
3140
|
+
if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
|
|
3141
|
+
payload[attrName] = null;
|
|
3142
|
+
} else if (rawVal !== "" && rawVal !== null && rawVal !== void 0) {
|
|
3143
|
+
payload[attrName] = await resolveComponentPayload(
|
|
3144
|
+
strapi,
|
|
3145
|
+
field.componentUid,
|
|
3146
|
+
rawVal,
|
|
3147
|
+
existingDoc?.[attrName] || {}
|
|
3148
|
+
);
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
break;
|
|
3153
|
+
}
|
|
3154
|
+
case "component_repeatable": {
|
|
3155
|
+
if (field.componentUid) {
|
|
3156
|
+
if (rawVal === "" || rawVal === null || rawVal === void 0) {
|
|
3157
|
+
payload[attrName] = [];
|
|
3158
|
+
} else {
|
|
3159
|
+
let list = [];
|
|
3160
|
+
try {
|
|
3161
|
+
list = typeof rawVal === "string" ? JSON.parse(rawVal) : rawVal;
|
|
3162
|
+
} catch {
|
|
3163
|
+
}
|
|
3164
|
+
if (Array.isArray(list)) {
|
|
3165
|
+
const cleanedItems = [];
|
|
3166
|
+
for (const item of list) {
|
|
3167
|
+
const cleaned = await resolveComponentPayload(
|
|
3168
|
+
strapi,
|
|
3169
|
+
field.componentUid,
|
|
3170
|
+
item,
|
|
3171
|
+
{}
|
|
3172
|
+
);
|
|
3173
|
+
cleanedItems.push(cleaned);
|
|
3174
|
+
}
|
|
3175
|
+
payload[attrName] = cleanedItems;
|
|
3176
|
+
} else {
|
|
3177
|
+
payload[attrName] = [];
|
|
3178
|
+
}
|
|
3179
|
+
}
|
|
3180
|
+
}
|
|
3181
|
+
break;
|
|
3182
|
+
}
|
|
3183
|
+
case "dynamiczone": {
|
|
3184
|
+
const allowedComponents = field.dzComponents || [];
|
|
3185
|
+
if (rawVal === "" || rawVal === null || rawVal === void 0) {
|
|
3186
|
+
payload[attrName] = [];
|
|
3187
|
+
} else {
|
|
3188
|
+
payload[attrName] = await resolveDynamicZonePayload(
|
|
3189
|
+
strapi,
|
|
3190
|
+
allowedComponents,
|
|
3191
|
+
rawVal,
|
|
3192
|
+
existingDoc?.[attrName] || []
|
|
3193
|
+
);
|
|
3194
|
+
}
|
|
3195
|
+
break;
|
|
3196
|
+
}
|
|
3197
|
+
case "relation_to_one": {
|
|
3198
|
+
payload[attrName] = resolveRelationPayload(rawVal, false);
|
|
3199
|
+
break;
|
|
3200
|
+
}
|
|
3201
|
+
case "relation_to_many": {
|
|
3202
|
+
payload[attrName] = resolveRelationPayload(rawVal, true);
|
|
3203
|
+
break;
|
|
3204
|
+
}
|
|
3205
|
+
case "media_single": {
|
|
3206
|
+
payload[attrName] = await resolveMediaIds(strapi, rawVal, false);
|
|
3207
|
+
break;
|
|
3208
|
+
}
|
|
3209
|
+
case "media_to_many": {
|
|
3210
|
+
payload[attrName] = await resolveMediaIds(strapi, rawVal, true);
|
|
3211
|
+
break;
|
|
3212
|
+
}
|
|
3213
|
+
default:
|
|
3214
|
+
payload[attrName] = rawVal;
|
|
3215
|
+
}
|
|
3216
|
+
}
|
|
3217
|
+
return payload;
|
|
3218
|
+
}
|
|
3219
|
+
function formatComponentDisplayName(compUid) {
|
|
3220
|
+
if (!compUid) return "Component";
|
|
3221
|
+
const name = compUid.includes(".") ? compUid.split(".")[1] : compUid;
|
|
3222
|
+
return name.split(/[-_]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
|
|
3223
|
+
}
|
|
3224
|
+
function parseAttrPath(path) {
|
|
3225
|
+
if (!path) return { cleanPath: "", rootKey: "", subPath: "" };
|
|
3226
|
+
const bracketMatch = path.match(/^([^.[]+)\[([^\]]+)\](?:\.(.+))?$/);
|
|
3227
|
+
if (bracketMatch) {
|
|
3228
|
+
const rootKey = bracketMatch[1];
|
|
3229
|
+
const selector = bracketMatch[2].trim();
|
|
3230
|
+
const subPath = bracketMatch[3] || "";
|
|
3231
|
+
const cleanPath = subPath ? `${rootKey}.${subPath}` : rootKey;
|
|
3232
|
+
const numMatch = selector.match(/^#?(\d+)/);
|
|
3233
|
+
if (numMatch) {
|
|
3234
|
+
return { cleanPath, rootKey, subPath, targetIndex: parseInt(numMatch[1], 10) };
|
|
3235
|
+
}
|
|
3236
|
+
return { cleanPath, rootKey, subPath, targetComponentUid: selector };
|
|
3237
|
+
}
|
|
3238
|
+
const parts = path.split(".");
|
|
3239
|
+
return {
|
|
3240
|
+
cleanPath: path,
|
|
3241
|
+
rootKey: parts[0] || "",
|
|
3242
|
+
subPath: parts.slice(1).join(".")
|
|
3243
|
+
};
|
|
3244
|
+
}
|
|
3245
|
+
function buildRichAttributeMeta(attrDef, baseMeta) {
|
|
3246
|
+
if (!attrDef || typeof attrDef !== "object") {
|
|
3247
|
+
return { ...baseMeta };
|
|
3248
|
+
}
|
|
3249
|
+
const enriched = { ...baseMeta };
|
|
3250
|
+
if (attrDef.customField) {
|
|
3251
|
+
enriched.customField = String(attrDef.customField);
|
|
3252
|
+
}
|
|
3253
|
+
if (attrDef.options && typeof attrDef.options === "object") {
|
|
3254
|
+
enriched.options = {
|
|
3255
|
+
...attrDef.options.scope !== void 0 ? { scope: attrDef.options.scope } : {},
|
|
3256
|
+
...attrDef.options.disabledBehavior !== void 0 ? { disabledBehavior: attrDef.options.disabledBehavior } : {},
|
|
3257
|
+
...attrDef.options.quotas ? { quotas: { ...attrDef.options.quotas } } : {},
|
|
3258
|
+
...Array.isArray(attrDef.options.items) ? { items: attrDef.options.items.map((it) => ({ ...it })) } : {}
|
|
3259
|
+
};
|
|
3260
|
+
}
|
|
3261
|
+
if (Array.isArray(attrDef.enum)) {
|
|
3262
|
+
enriched.enumOptions = [...attrDef.enum];
|
|
3263
|
+
}
|
|
3264
|
+
if (attrDef.type === "media") {
|
|
3265
|
+
enriched.multiple = Boolean(attrDef.multiple);
|
|
3266
|
+
}
|
|
3267
|
+
if (attrDef.type === "component") {
|
|
3268
|
+
enriched.repeatable = Boolean(attrDef.repeatable);
|
|
3269
|
+
}
|
|
3270
|
+
if (typeof attrDef.min === "number") enriched.min = attrDef.min;
|
|
3271
|
+
if (typeof attrDef.max === "number") enriched.max = attrDef.max;
|
|
3272
|
+
if (typeof attrDef.minLength === "number") enriched.minLength = attrDef.minLength;
|
|
3273
|
+
if (typeof attrDef.maxLength === "number") enriched.maxLength = attrDef.maxLength;
|
|
3274
|
+
if (typeof attrDef.regex === "string") enriched.regex = attrDef.regex;
|
|
3275
|
+
if (attrDef.required) enriched.required = true;
|
|
3276
|
+
if (attrDef.target) enriched.target = attrDef.target;
|
|
3277
|
+
if (attrDef.relation) enriched.relationType = attrDef.relation;
|
|
3278
|
+
return enriched;
|
|
3279
|
+
}
|
|
3280
|
+
function buildOccurrenceKey(segments) {
|
|
3281
|
+
if (!segments || segments.length === 0) return "__scalar__";
|
|
3282
|
+
return segments.map((seg) => {
|
|
3283
|
+
if (seg.index !== void 0) {
|
|
3284
|
+
return seg.componentId !== void 0 && seg.componentId !== null ? `${seg.key}[${seg.index}#${seg.componentId}]` : `${seg.key}[${seg.index}]`;
|
|
3285
|
+
}
|
|
3286
|
+
return seg.key;
|
|
3287
|
+
}).join(".");
|
|
3288
|
+
}
|
|
3289
|
+
function buildReadableOccurrencePath(segments) {
|
|
3290
|
+
if (!segments || segments.length === 0) return "";
|
|
3291
|
+
return segments.map((seg) => {
|
|
3292
|
+
if (seg.index !== void 0) {
|
|
3293
|
+
const compLabel = seg.componentUid ? ` ${formatComponentDisplayName(seg.componentUid)}` : "";
|
|
3294
|
+
return `${seg.key}[#${seg.index}${compLabel}]`;
|
|
3295
|
+
}
|
|
3296
|
+
return seg.key;
|
|
3297
|
+
}).join(".");
|
|
3298
|
+
}
|
|
3299
|
+
function enumerateOccurrences(contentType, allComponents, entity, attrPath) {
|
|
3300
|
+
if (!contentType || !attrPath) return [];
|
|
3301
|
+
const parsed = parseAttrPath(attrPath);
|
|
3302
|
+
const parts = parsed.cleanPath.split(".").filter(Boolean);
|
|
3303
|
+
if (parts.length === 0) return [];
|
|
3304
|
+
const results = [];
|
|
3305
|
+
function walk(currentSchema, currentVal, remainingParts, segments, missingIntermediate, firstArrayIndex, resolvedCompUid, resolvedCompId, isRootLevel) {
|
|
3306
|
+
if (!currentSchema?.attributes || remainingParts.length === 0) return;
|
|
3307
|
+
const [head, ...tail] = remainingParts;
|
|
3308
|
+
const attrDef = currentSchema.attributes[head];
|
|
3309
|
+
if (!attrDef) return;
|
|
3310
|
+
const nextVal = currentVal && typeof currentVal === "object" ? currentVal[head] : void 0;
|
|
3311
|
+
if (tail.length === 0) {
|
|
3312
|
+
const nextSegs = [...segments, { key: head }];
|
|
3313
|
+
results.push({
|
|
3314
|
+
occurrenceKey: segments.length === 0 ? "__scalar__" : buildOccurrenceKey(nextSegs),
|
|
3315
|
+
displayPath: buildReadableOccurrencePath(nextSegs),
|
|
3316
|
+
segments: nextSegs,
|
|
3317
|
+
value: nextVal !== void 0 ? nextVal : null,
|
|
3318
|
+
componentUid: resolvedCompUid,
|
|
3319
|
+
componentName: resolvedCompUid ? formatComponentDisplayName(resolvedCompUid) : void 0,
|
|
3320
|
+
componentId: resolvedCompId,
|
|
3321
|
+
index: firstArrayIndex ?? 0,
|
|
3322
|
+
isMissingIntermediate: missingIntermediate,
|
|
3323
|
+
leafSchema: attrDef
|
|
3324
|
+
});
|
|
3325
|
+
return;
|
|
3326
|
+
}
|
|
3327
|
+
if (attrDef.type === "dynamiczone") {
|
|
3328
|
+
if (!Array.isArray(nextVal)) return;
|
|
3329
|
+
nextVal.forEach((item, idx) => {
|
|
3330
|
+
if (!item || typeof item !== "object") return;
|
|
3331
|
+
if (isRootLevel && parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) return;
|
|
3332
|
+
if (isRootLevel && parsed.targetComponentUid && item.__component !== parsed.targetComponentUid) return;
|
|
3333
|
+
const compSchema = item.__component ? allComponents?.[item.__component] : null;
|
|
3334
|
+
if (!compSchema) return;
|
|
3335
|
+
const seg = {
|
|
3336
|
+
key: head,
|
|
3337
|
+
index: idx,
|
|
3338
|
+
componentId: item.id,
|
|
3339
|
+
componentUid: item.__component
|
|
3340
|
+
};
|
|
3341
|
+
walk(
|
|
3342
|
+
compSchema,
|
|
3343
|
+
item,
|
|
3344
|
+
tail,
|
|
3345
|
+
[...segments, seg],
|
|
3346
|
+
missingIntermediate,
|
|
3347
|
+
firstArrayIndex ?? idx,
|
|
3348
|
+
item.__component,
|
|
3349
|
+
resolvedCompId ?? item.id,
|
|
3350
|
+
false
|
|
3351
|
+
);
|
|
3352
|
+
});
|
|
3353
|
+
return;
|
|
3354
|
+
}
|
|
3355
|
+
if (attrDef.type === "component" && attrDef.component) {
|
|
3356
|
+
const compSchema = allComponents?.[attrDef.component];
|
|
3357
|
+
if (!compSchema) return;
|
|
3358
|
+
if (attrDef.repeatable) {
|
|
3359
|
+
if (!Array.isArray(nextVal)) return;
|
|
3360
|
+
nextVal.forEach((item, idx) => {
|
|
3361
|
+
if (!item || typeof item !== "object") return;
|
|
3362
|
+
if (isRootLevel && parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) return;
|
|
3363
|
+
const seg = {
|
|
3364
|
+
key: head,
|
|
3365
|
+
index: idx,
|
|
3366
|
+
componentId: item.id,
|
|
3367
|
+
componentUid: attrDef.component
|
|
3368
|
+
};
|
|
3369
|
+
walk(
|
|
3370
|
+
compSchema,
|
|
3371
|
+
item,
|
|
3372
|
+
tail,
|
|
3373
|
+
[...segments, seg],
|
|
3374
|
+
missingIntermediate,
|
|
3375
|
+
firstArrayIndex ?? idx,
|
|
3376
|
+
attrDef.component,
|
|
3377
|
+
resolvedCompId ?? item.id,
|
|
3378
|
+
false
|
|
3379
|
+
);
|
|
3380
|
+
});
|
|
3381
|
+
} else {
|
|
3382
|
+
const isMissing = !nextVal || typeof nextVal !== "object";
|
|
3383
|
+
const seg = {
|
|
3384
|
+
key: head,
|
|
3385
|
+
componentId: !isMissing ? nextVal.id : void 0,
|
|
3386
|
+
componentUid: attrDef.component
|
|
3387
|
+
};
|
|
3388
|
+
walk(
|
|
3389
|
+
compSchema,
|
|
3390
|
+
isMissing ? void 0 : nextVal,
|
|
3391
|
+
tail,
|
|
3392
|
+
[...segments, seg],
|
|
3393
|
+
missingIntermediate || isMissing,
|
|
3394
|
+
firstArrayIndex,
|
|
3395
|
+
resolvedCompUid ?? attrDef.component,
|
|
3396
|
+
resolvedCompId ?? (!isMissing ? nextVal.id : void 0),
|
|
3397
|
+
false
|
|
3398
|
+
);
|
|
3399
|
+
}
|
|
3400
|
+
}
|
|
3401
|
+
}
|
|
3402
|
+
walk(contentType, entity, parts, [], false, void 0, void 0, void 0, true);
|
|
3403
|
+
return results;
|
|
3404
|
+
}
|
|
3405
|
+
function formatRelationState(currentRel, isMulti) {
|
|
3406
|
+
if (isMulti && Array.isArray(currentRel)) {
|
|
3407
|
+
const oldDocIds = currentRel.map((r) => r?.documentId).filter(Boolean);
|
|
3408
|
+
const oldDisplay = currentRel.map((r) => r?.name || r?.title || r?.email || r?.username || r?.documentId).filter(Boolean).join(", ") || "(unlinked / none)";
|
|
3409
|
+
return { oldDocIds, oldDisplay };
|
|
3410
|
+
}
|
|
3411
|
+
if (currentRel && typeof currentRel === "object") {
|
|
3412
|
+
const oldDocIds = currentRel.documentId ? [currentRel.documentId] : [];
|
|
3413
|
+
const oldDisplay = currentRel.name || currentRel.title || currentRel.email || currentRel.username || currentRel.documentId || "(unlinked / none)";
|
|
3414
|
+
return { oldDocIds, oldDisplay };
|
|
3415
|
+
}
|
|
3416
|
+
return { oldDocIds: [], oldDisplay: "(unlinked / none)" };
|
|
3417
|
+
}
|
|
3418
|
+
function resolveRelationCommand(rawValue, isMulti, forComponentNested = false) {
|
|
3419
|
+
let mode = "set";
|
|
3420
|
+
let targetDocIds = [];
|
|
3421
|
+
let display = "";
|
|
3422
|
+
if (rawValue === null || rawValue === void 0 || rawValue === "__clear__" || rawValue === "") {
|
|
3423
|
+
mode = "clear";
|
|
3424
|
+
display = "(cleared / unlinked)";
|
|
3425
|
+
} else if (typeof rawValue === "object" && !Array.isArray(rawValue)) {
|
|
3426
|
+
if (rawValue.mode) {
|
|
3427
|
+
mode = rawValue.mode;
|
|
3428
|
+
targetDocIds = Array.isArray(rawValue.documentIds) ? rawValue.documentIds.filter(Boolean).map(String) : rawValue.documentId ? [String(rawValue.documentId)] : [];
|
|
3429
|
+
display = rawValue.label || targetDocIds.join(", ") || `[${mode}]`;
|
|
3430
|
+
} else if (rawValue.documentId) {
|
|
3431
|
+
targetDocIds = [String(rawValue.documentId)];
|
|
3432
|
+
display = rawValue.label || targetDocIds[0];
|
|
3433
|
+
}
|
|
3434
|
+
} else if (Array.isArray(rawValue)) {
|
|
3435
|
+
targetDocIds = rawValue.map((v) => typeof v === "object" ? v?.documentId : v).filter(Boolean).map(String);
|
|
3436
|
+
display = targetDocIds.join(", ") || "(cleared / unlinked)";
|
|
3437
|
+
if (targetDocIds.length === 0) mode = "clear";
|
|
3438
|
+
} else {
|
|
3439
|
+
const strVal = String(rawValue);
|
|
3440
|
+
try {
|
|
3441
|
+
const parsed = JSON.parse(strVal);
|
|
3442
|
+
if (parsed && typeof parsed === "object" && parsed.mode) {
|
|
3443
|
+
mode = parsed.mode;
|
|
3444
|
+
targetDocIds = Array.isArray(parsed.documentIds) ? parsed.documentIds.filter(Boolean).map(String) : parsed.documentId ? [String(parsed.documentId)] : [];
|
|
3445
|
+
display = parsed.label || targetDocIds.join(", ") || `[${mode}]`;
|
|
3446
|
+
} else if (Array.isArray(parsed)) {
|
|
3447
|
+
targetDocIds = parsed.filter(Boolean).map(String);
|
|
3448
|
+
display = targetDocIds.join(", ");
|
|
3449
|
+
} else {
|
|
3450
|
+
targetDocIds = [strVal];
|
|
3451
|
+
display = strVal;
|
|
3452
|
+
}
|
|
3453
|
+
} catch {
|
|
3454
|
+
targetDocIds = [strVal];
|
|
3455
|
+
display = strVal;
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
let relationPayload;
|
|
3459
|
+
if (mode === "clear") {
|
|
3460
|
+
relationPayload = isMulti ? { set: [] } : null;
|
|
3461
|
+
} else if (mode === "set") {
|
|
3462
|
+
relationPayload = isMulti ? { set: targetDocIds } : targetDocIds[0] || null;
|
|
3463
|
+
} else if (mode === "connect") {
|
|
3464
|
+
relationPayload = { connect: targetDocIds };
|
|
3465
|
+
} else if (mode === "disconnect") {
|
|
3466
|
+
relationPayload = { disconnect: targetDocIds };
|
|
3467
|
+
}
|
|
3468
|
+
return { mode, targetDocIds, relationPayload, display };
|
|
3469
|
+
}
|
|
3470
|
+
async function coerceAndValidateFieldValue(attrDef, rawValue, strapi, options = {}) {
|
|
3471
|
+
if (!attrDef || typeof attrDef !== "object") {
|
|
3472
|
+
return {
|
|
3473
|
+
valid: true,
|
|
3474
|
+
value: rawValue,
|
|
3475
|
+
displayValue: rawValue !== void 0 && rawValue !== null ? String(rawValue) : "(empty)"
|
|
3476
|
+
};
|
|
3477
|
+
}
|
|
3478
|
+
const type = String(attrDef.type || "").toLowerCase();
|
|
3479
|
+
if (type === "relation") {
|
|
3480
|
+
const isMulti = attrDef.relation === "oneToMany" || attrDef.relation === "manyToMany";
|
|
3481
|
+
const cmd = resolveRelationCommand(rawValue, isMulti, options.forComponentNested);
|
|
3482
|
+
if (attrDef.required && (cmd.mode === "clear" || cmd.mode === "set" && cmd.targetDocIds.length === 0)) {
|
|
3483
|
+
return {
|
|
3484
|
+
valid: false,
|
|
3485
|
+
value: rawValue,
|
|
3486
|
+
displayValue: cmd.display,
|
|
3487
|
+
isRelation: true,
|
|
3488
|
+
error: "Relation field is required and cannot be cleared."
|
|
3489
|
+
};
|
|
3490
|
+
}
|
|
3491
|
+
return {
|
|
3492
|
+
valid: true,
|
|
3493
|
+
value: cmd.relationPayload,
|
|
3494
|
+
displayValue: cmd.display,
|
|
3495
|
+
isRelation: true,
|
|
3496
|
+
relationMeta: { isRelation: true, mode: cmd.mode, documentIds: cmd.targetDocIds, display: cmd.display }
|
|
3497
|
+
};
|
|
3498
|
+
}
|
|
3499
|
+
if (type === "media") {
|
|
3500
|
+
const isMultiple = Boolean(attrDef.multiple);
|
|
3501
|
+
if (rawValue === null || rawValue === void 0 || rawValue === "" || rawValue === "__clear__") {
|
|
3502
|
+
if (attrDef.required) {
|
|
3503
|
+
return { valid: false, value: rawValue, displayValue: "", error: "Media field is required." };
|
|
3504
|
+
}
|
|
3505
|
+
const cleared = isMultiple ? [] : null;
|
|
3506
|
+
return { valid: true, value: cleared, displayValue: "(cleared)" };
|
|
3507
|
+
}
|
|
3508
|
+
const mediaPayload = strapi ? await resolveMediaIds(strapi, rawValue, isMultiple) : rawValue;
|
|
3509
|
+
if (attrDef.required && (mediaPayload === null || Array.isArray(mediaPayload) && mediaPayload.length === 0)) {
|
|
3510
|
+
return { valid: false, value: rawValue, displayValue: "", error: "Media asset could not be resolved." };
|
|
3511
|
+
}
|
|
3512
|
+
return {
|
|
3513
|
+
valid: true,
|
|
3514
|
+
value: mediaPayload,
|
|
3515
|
+
displayValue: Array.isArray(mediaPayload) ? `[${mediaPayload.length} asset(s)]` : mediaPayload !== null ? `#${mediaPayload}` : "(cleared)"
|
|
3516
|
+
};
|
|
3517
|
+
}
|
|
3518
|
+
const isEmptyInput = rawValue === null || rawValue === void 0 || rawValue === "";
|
|
3519
|
+
if (attrDef.required && (isEmptyInput || type === "boolean" && rawValue === null)) {
|
|
3520
|
+
return {
|
|
3521
|
+
valid: false,
|
|
3522
|
+
value: rawValue,
|
|
3523
|
+
displayValue: "",
|
|
3524
|
+
error: "Field is required and cannot be empty."
|
|
3525
|
+
};
|
|
3526
|
+
}
|
|
3527
|
+
if (rawValue === null || rawValue === void 0) {
|
|
3528
|
+
return { valid: true, value: null, displayValue: "(empty)" };
|
|
3529
|
+
}
|
|
3530
|
+
switch (type) {
|
|
3531
|
+
case "integer": {
|
|
3532
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3533
|
+
const str = String(rawValue).trim();
|
|
3534
|
+
if (!/^-?\d+$/.test(str)) {
|
|
3535
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid integer value "${str}".` };
|
|
3536
|
+
}
|
|
3537
|
+
const num = Number(str);
|
|
3538
|
+
if (!Number.isSafeInteger(num)) {
|
|
3539
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Integer "${str}" is out of safe range.` };
|
|
3540
|
+
}
|
|
3541
|
+
if (typeof attrDef.min === "number" && num < attrDef.min) {
|
|
3542
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} is less than minimum ${attrDef.min}.` };
|
|
3543
|
+
}
|
|
3544
|
+
if (typeof attrDef.max === "number" && num > attrDef.max) {
|
|
3545
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} exceeds maximum ${attrDef.max}.` };
|
|
3546
|
+
}
|
|
3547
|
+
return { valid: true, value: num, displayValue: String(num) };
|
|
3548
|
+
}
|
|
3549
|
+
case "biginteger": {
|
|
3550
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3551
|
+
const str = String(rawValue).trim();
|
|
3552
|
+
if (!/^-?\d+$/.test(str)) {
|
|
3553
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid biginteger value "${str}".` };
|
|
3554
|
+
}
|
|
3555
|
+
return { valid: true, value: str, displayValue: str };
|
|
3556
|
+
}
|
|
3557
|
+
case "float":
|
|
3558
|
+
case "decimal": {
|
|
3559
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3560
|
+
const str = String(rawValue).trim();
|
|
3561
|
+
if (!/^-?\d+(\.\d+)?$/.test(str)) {
|
|
3562
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid decimal number "${str}".` };
|
|
3563
|
+
}
|
|
3564
|
+
const num = Number(str);
|
|
3565
|
+
if (!Number.isFinite(num)) {
|
|
3566
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Number "${str}" is not finite.` };
|
|
3567
|
+
}
|
|
3568
|
+
if (typeof attrDef.min === "number" && num < attrDef.min) {
|
|
3569
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} is less than minimum ${attrDef.min}.` };
|
|
3570
|
+
}
|
|
3571
|
+
if (typeof attrDef.max === "number" && num > attrDef.max) {
|
|
3572
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} exceeds maximum ${attrDef.max}.` };
|
|
3573
|
+
}
|
|
3574
|
+
return { valid: true, value: num, displayValue: String(num) };
|
|
3575
|
+
}
|
|
3576
|
+
case "boolean": {
|
|
3577
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3578
|
+
if (typeof rawValue === "boolean") {
|
|
3579
|
+
return { valid: true, value: rawValue, displayValue: String(rawValue) };
|
|
3580
|
+
}
|
|
3581
|
+
const lower = String(rawValue).trim().toLowerCase();
|
|
3582
|
+
if (lower === "true" || lower === "1" || lower === "yes") {
|
|
3583
|
+
return { valid: true, value: true, displayValue: "true" };
|
|
3584
|
+
}
|
|
3585
|
+
if (lower === "false" || lower === "0" || lower === "no") {
|
|
3586
|
+
return { valid: true, value: false, displayValue: "false" };
|
|
3587
|
+
}
|
|
3588
|
+
return { valid: false, value: rawValue, displayValue: String(rawValue), error: `Invalid boolean value "${rawValue}".` };
|
|
3589
|
+
}
|
|
3590
|
+
case "enumeration": {
|
|
3591
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3592
|
+
const str = String(rawValue);
|
|
3593
|
+
if (Array.isArray(attrDef.enum) && !attrDef.enum.includes(str)) {
|
|
3594
|
+
return {
|
|
3595
|
+
valid: false,
|
|
3596
|
+
value: rawValue,
|
|
3597
|
+
displayValue: str,
|
|
3598
|
+
error: `Value "${str}" is not an allowed enum option (${attrDef.enum.join(", ")}).`
|
|
3599
|
+
};
|
|
3600
|
+
}
|
|
3601
|
+
return { valid: true, value: str, displayValue: str };
|
|
3602
|
+
}
|
|
3603
|
+
case "email": {
|
|
3604
|
+
const str = String(rawValue).trim();
|
|
3605
|
+
if (str === "") return { valid: true, value: "", displayValue: "(empty)" };
|
|
3606
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str)) {
|
|
3607
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid email address "${str}".` };
|
|
3608
|
+
}
|
|
3609
|
+
return { valid: true, value: str, displayValue: str };
|
|
3610
|
+
}
|
|
3611
|
+
case "uid": {
|
|
3612
|
+
const str = String(rawValue).trim();
|
|
3613
|
+
if (str !== "" && !/^[A-Za-z0-9\-_.~]*$/.test(str)) {
|
|
3614
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid UID slug "${str}". Allowed characters: A-Z a-z 0-9 - _ . ~` };
|
|
3615
|
+
}
|
|
3616
|
+
return { valid: true, value: str, displayValue: str || "(empty)" };
|
|
3617
|
+
}
|
|
3618
|
+
case "json":
|
|
3619
|
+
case "blocks": {
|
|
3620
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3621
|
+
let parsedVal = rawValue;
|
|
3622
|
+
if (typeof rawValue === "string") {
|
|
3623
|
+
try {
|
|
3624
|
+
parsedVal = JSON.parse(rawValue);
|
|
3625
|
+
} catch (err) {
|
|
3626
|
+
return {
|
|
3627
|
+
valid: false,
|
|
3628
|
+
value: rawValue,
|
|
3629
|
+
displayValue: rawValue,
|
|
3630
|
+
error: `Invalid ${type === "blocks" ? "Blocks" : "JSON"} syntax: ${err.message}`
|
|
3631
|
+
};
|
|
3632
|
+
}
|
|
3633
|
+
}
|
|
3634
|
+
if (type === "blocks" && parsedVal !== null && !Array.isArray(parsedVal)) {
|
|
3635
|
+
return { valid: false, value: rawValue, displayValue: String(rawValue), error: "Strapi Blocks field must be a JSON array." };
|
|
3636
|
+
}
|
|
3637
|
+
return {
|
|
3638
|
+
valid: true,
|
|
3639
|
+
value: parsedVal,
|
|
3640
|
+
displayValue: parsedVal === null ? "(empty)" : JSON.stringify(parsedVal)
|
|
3641
|
+
};
|
|
3642
|
+
}
|
|
3643
|
+
case "date":
|
|
3644
|
+
case "datetime": {
|
|
3645
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3646
|
+
const str = String(rawValue).trim();
|
|
3647
|
+
const d = new Date(str);
|
|
3648
|
+
if (isNaN(d.getTime())) {
|
|
3649
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid ${type} value "${str}".` };
|
|
3650
|
+
}
|
|
3651
|
+
const out = type === "date" ? /^\d{4}-\d{2}-\d{2}$/.test(str) ? str : d.toISOString().slice(0, 10) : d.toISOString();
|
|
3652
|
+
return { valid: true, value: out, displayValue: out };
|
|
3653
|
+
}
|
|
3654
|
+
case "time": {
|
|
3655
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3656
|
+
const str = String(rawValue).trim();
|
|
3657
|
+
if (!/^\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?$/.test(str)) {
|
|
3658
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid time format "${str}" (expected HH:mm or HH:mm:ss).` };
|
|
3659
|
+
}
|
|
3660
|
+
return { valid: true, value: str, displayValue: str };
|
|
3661
|
+
}
|
|
3662
|
+
default: {
|
|
3663
|
+
const str = typeof rawValue === "object" ? JSON.stringify(rawValue) : String(rawValue);
|
|
3664
|
+
if (typeof attrDef.minLength === "number" && str.length < attrDef.minLength) {
|
|
3665
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Length ${str.length} is shorter than minimum ${attrDef.minLength}.` };
|
|
3666
|
+
}
|
|
3667
|
+
if (typeof attrDef.maxLength === "number" && str.length > attrDef.maxLength) {
|
|
3668
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Length ${str.length} exceeds maximum ${attrDef.maxLength}.` };
|
|
3669
|
+
}
|
|
3670
|
+
if (typeof attrDef.regex === "string" && attrDef.regex && str !== "") {
|
|
3671
|
+
try {
|
|
3672
|
+
const re = new RegExp(attrDef.regex);
|
|
3673
|
+
if (!re.test(str)) {
|
|
3674
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value does not match required pattern /${attrDef.regex}/.` };
|
|
3675
|
+
}
|
|
3676
|
+
} catch {
|
|
3677
|
+
}
|
|
3678
|
+
}
|
|
3679
|
+
return { valid: true, value: rawValue, displayValue: str || "(empty)" };
|
|
3680
|
+
}
|
|
3681
|
+
}
|
|
3682
|
+
}
|
|
3683
|
+
function findTargetArrayIndex(arr, seg, arrFieldKey) {
|
|
3684
|
+
if (!Array.isArray(arr)) {
|
|
3685
|
+
throw new Error(`Expected array for component/dynamiczone field "${arrFieldKey}".`);
|
|
3686
|
+
}
|
|
3687
|
+
if (seg.componentId !== void 0 && seg.componentId !== null) {
|
|
3688
|
+
const idMatchIdx = arr.findIndex((item) => {
|
|
3689
|
+
if (!item || typeof item !== "object") return false;
|
|
3690
|
+
if (String(item.id) !== String(seg.componentId)) return false;
|
|
3691
|
+
if (seg.componentUid && item.__component && item.__component !== seg.componentUid) return false;
|
|
3692
|
+
return true;
|
|
3693
|
+
});
|
|
3694
|
+
if (idMatchIdx === -1) {
|
|
3695
|
+
throw new Error(
|
|
3696
|
+
`Stale target: component instance (id: ${seg.componentId}) in "${arrFieldKey}" was modified or deleted. Please refresh the grid and retry.`
|
|
3697
|
+
);
|
|
3698
|
+
}
|
|
3699
|
+
return idMatchIdx;
|
|
3700
|
+
}
|
|
3701
|
+
if (typeof seg.index === "number") {
|
|
3702
|
+
if (seg.index < 0 || seg.index >= arr.length) {
|
|
3703
|
+
throw new Error(
|
|
3704
|
+
`Stale target: occurrence #${seg.index} in "${arrFieldKey}" no longer exists (length ${arr.length}). Please refresh the grid and retry.`
|
|
3705
|
+
);
|
|
3706
|
+
}
|
|
3707
|
+
const item = arr[seg.index];
|
|
3708
|
+
if (seg.componentUid && item?.__component && item.__component !== seg.componentUid) {
|
|
3709
|
+
throw new Error(
|
|
3710
|
+
`Stale target: occurrence #${seg.index} in "${arrFieldKey}" changed component type to "${item.__component}". Please refresh the grid.`
|
|
3711
|
+
);
|
|
3712
|
+
}
|
|
3713
|
+
return seg.index;
|
|
3714
|
+
}
|
|
3715
|
+
throw new Error(`Missing occurrence index/componentId for "${arrFieldKey}".`);
|
|
3716
|
+
}
|
|
3717
|
+
function buildFallbackSegmentsFromUpdate(contentType, allComponents, cleanPath, occUpdate, parsedTargetCompUid) {
|
|
3718
|
+
if (Array.isArray(occUpdate.segments) && occUpdate.segments.length > 0) {
|
|
3719
|
+
return occUpdate.segments;
|
|
3720
|
+
}
|
|
3721
|
+
const parts = cleanPath.split(".").filter(Boolean);
|
|
3722
|
+
const segs = [];
|
|
3723
|
+
let curSchema = contentType;
|
|
3724
|
+
let usedFirstArrayMeta = false;
|
|
3725
|
+
for (let i = 0; i < parts.length; i++) {
|
|
3726
|
+
const key = parts[i];
|
|
3727
|
+
const attrDef = curSchema?.attributes?.[key];
|
|
3728
|
+
const isLast = i === parts.length - 1;
|
|
3729
|
+
if (!isLast && attrDef && (attrDef.type === "dynamiczone" || attrDef.type === "component" && attrDef.repeatable)) {
|
|
3730
|
+
const seg = { key };
|
|
3731
|
+
if (!usedFirstArrayMeta) {
|
|
3732
|
+
if (occUpdate.dynamicZoneIndex !== void 0) seg.index = occUpdate.dynamicZoneIndex;
|
|
3733
|
+
if (occUpdate.componentId !== void 0) seg.componentId = occUpdate.componentId;
|
|
3734
|
+
if (occUpdate.componentUid || parsedTargetCompUid) {
|
|
3735
|
+
seg.componentUid = occUpdate.componentUid || parsedTargetCompUid;
|
|
3736
|
+
}
|
|
3737
|
+
usedFirstArrayMeta = true;
|
|
3738
|
+
}
|
|
3739
|
+
segs.push(seg);
|
|
3740
|
+
const nextCompUid = seg.componentUid || attrDef.component;
|
|
3741
|
+
curSchema = nextCompUid ? allComponents?.[nextCompUid] : void 0;
|
|
3742
|
+
} else {
|
|
3743
|
+
segs.push({ key });
|
|
3744
|
+
if (!isLast && attrDef?.type === "component" && attrDef.component) {
|
|
3745
|
+
curSchema = allComponents?.[attrDef.component];
|
|
3746
|
+
}
|
|
3747
|
+
}
|
|
3748
|
+
}
|
|
3749
|
+
return segs;
|
|
3750
|
+
}
|
|
3751
|
+
function formatValueDisplay$1(val, isRelation = false, isMulti = false) {
|
|
3752
|
+
if (isRelation) {
|
|
3753
|
+
return formatRelationState(val, isMulti).oldDisplay;
|
|
3754
|
+
}
|
|
3755
|
+
if (val === void 0 || val === null || val === "") return "(empty)";
|
|
3756
|
+
if (typeof val === "object") return JSON.stringify(val);
|
|
3757
|
+
return String(val);
|
|
3758
|
+
}
|
|
3759
|
+
async function applyOccurrenceUpdatesToDocument({
|
|
3760
|
+
strapi,
|
|
3761
|
+
contentType,
|
|
3762
|
+
allComponents,
|
|
3763
|
+
currentDoc,
|
|
3764
|
+
attribute,
|
|
3765
|
+
updates
|
|
3766
|
+
}) {
|
|
3767
|
+
const parsed = parseAttrPath(attribute);
|
|
3768
|
+
const parts = parsed.cleanPath.split(".").filter(Boolean);
|
|
3769
|
+
const rootKey = parts[0];
|
|
3770
|
+
const rootAttrDef = contentType?.attributes?.[rootKey];
|
|
3771
|
+
const diffs = [];
|
|
3772
|
+
const errors2 = [];
|
|
3773
|
+
if (parts.length === 1 && rootAttrDef?.type !== "component" && rootAttrDef?.type !== "dynamiczone") {
|
|
3774
|
+
const updateItem = updates[0];
|
|
3775
|
+
if (!updateItem) {
|
|
3776
|
+
return { updateData: {}, diffs: [], errors: [] };
|
|
3777
|
+
}
|
|
3778
|
+
const isRelation = rootAttrDef?.type === "relation";
|
|
3779
|
+
const isMulti = isRelation && (rootAttrDef.relation === "oneToMany" || rootAttrDef.relation === "manyToMany");
|
|
3780
|
+
const rawCurrent = currentDoc?.[rootKey];
|
|
3781
|
+
const coerced = await coerceAndValidateFieldValue(rootAttrDef, updateItem.value, strapi, { forComponentNested: false });
|
|
3782
|
+
if (!coerced.valid) {
|
|
3783
|
+
errors2.push(coerced.error || `Invalid value for ${rootKey}`);
|
|
3784
|
+
return { updateData: {}, diffs: [], errors: errors2 };
|
|
3785
|
+
}
|
|
3786
|
+
let oldVal;
|
|
3787
|
+
let oldDisplay;
|
|
3788
|
+
let newValOut;
|
|
3789
|
+
let newDisplay;
|
|
3790
|
+
let hasChange;
|
|
3791
|
+
if (isRelation) {
|
|
3792
|
+
const relState = formatRelationState(rawCurrent, isMulti);
|
|
3793
|
+
oldVal = { isRelation: true, documentIds: relState.oldDocIds, display: relState.oldDisplay };
|
|
3794
|
+
oldDisplay = relState.oldDisplay;
|
|
3795
|
+
newValOut = coerced.relationMeta;
|
|
3796
|
+
newDisplay = coerced.displayValue;
|
|
3797
|
+
hasChange = coerced.relationMeta?.mode === "clear" ? relState.oldDocIds.length > 0 : JSON.stringify(relState.oldDocIds) !== JSON.stringify(coerced.relationMeta?.documentIds || []) || coerced.relationMeta?.mode !== "set";
|
|
3798
|
+
} else {
|
|
3799
|
+
oldVal = rawCurrent ?? null;
|
|
3800
|
+
oldDisplay = formatValueDisplay$1(rawCurrent);
|
|
3801
|
+
newValOut = coerced.value;
|
|
3802
|
+
newDisplay = coerced.displayValue;
|
|
3803
|
+
hasChange = !areValuesEquivalent(rawCurrent, coerced.value);
|
|
3804
|
+
}
|
|
3805
|
+
diffs.push({
|
|
3806
|
+
occurrenceKey: "__scalar__",
|
|
3807
|
+
segments: [{ key: rootKey }],
|
|
3808
|
+
index: 0,
|
|
3809
|
+
attribute: rootKey,
|
|
2746
3810
|
oldValue: oldVal,
|
|
2747
3811
|
newValue: newValOut,
|
|
2748
3812
|
oldDisplay,
|
|
@@ -7296,674 +8360,307 @@ const auditService = ({ strapi }) => ({
|
|
|
7296
8360
|
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
7297
8361
|
if (bulkService?.invalidateCache) {
|
|
7298
8362
|
bulkService.invalidateCache(item.uid);
|
|
7299
|
-
}
|
|
7300
|
-
} catch {
|
|
7301
|
-
}
|
|
7302
|
-
revertedCount++;
|
|
7303
|
-
rollbackDetails.push({
|
|
7304
|
-
uid: item.uid,
|
|
7305
|
-
documentId: item.documentId,
|
|
7306
|
-
label: item.label,
|
|
7307
|
-
attribute: item.attribute,
|
|
7308
|
-
revertedTo: item.oldValue,
|
|
7309
|
-
status: "reverted"
|
|
7310
|
-
});
|
|
7311
|
-
} catch (err) {
|
|
7312
|
-
rollbackDetails.push({
|
|
7313
|
-
uid: item.uid,
|
|
7314
|
-
documentId: item.documentId,
|
|
7315
|
-
label: item.label,
|
|
7316
|
-
status: "error",
|
|
7317
|
-
message: err.message
|
|
7318
|
-
});
|
|
7319
|
-
}
|
|
7320
|
-
}
|
|
7321
|
-
}
|
|
7322
|
-
return { revertedCount, rollbackDetails };
|
|
7323
|
-
},
|
|
7324
|
-
/**
|
|
7325
|
-
* Performs deterministic rollback of a batch.
|
|
7326
|
-
* Strict invariant: ONLY the latest completed update is eligible for rollback.
|
|
7327
|
-
* Older completed updates, already rolled-back updates, and pending/failed/executing batches are strictly rejected.
|
|
7328
|
-
*/
|
|
7329
|
-
async rollbackBatch(batchId, currentUser) {
|
|
7330
|
-
return withRollbackLock(async () => {
|
|
7331
|
-
const config = this.getAuditConfig();
|
|
7332
|
-
if (!config.enabled) {
|
|
7333
|
-
throw new Error("Audit trail is not configured or disabled.");
|
|
7334
|
-
}
|
|
7335
|
-
if (!batchId) {
|
|
7336
|
-
throw new Error("A valid batchId is required to perform rollback.");
|
|
7337
|
-
}
|
|
7338
|
-
try {
|
|
7339
|
-
const bulkService = strapi.plugin("bulk-updater")?.service("bulkUpdater");
|
|
7340
|
-
if (bulkService && typeof bulkService.getBatchStatus === "function") {
|
|
7341
|
-
const statusRes = await bulkService.getBatchStatus(batchId);
|
|
7342
|
-
const batchJob = statusRes?.batch;
|
|
7343
|
-
if (batchJob) {
|
|
7344
|
-
if (batchJob.status === "pending_approval" || batchJob.status === "queued_offpeak") {
|
|
7345
|
-
throw new Error(`Batch "${batchId}" is currently pending and cannot be rolled back.`);
|
|
7346
|
-
}
|
|
7347
|
-
if (batchJob.status === "processing" || batchJob.status === "running" || batchJob.status === "executing") {
|
|
7348
|
-
throw new Error(`Batch "${batchId}" is currently executing and cannot be rolled back.`);
|
|
7349
|
-
}
|
|
7350
|
-
if (batchJob.status === "failed") {
|
|
7351
|
-
throw new Error(`Batch "${batchId}" failed during execution and cannot be rolled back.`);
|
|
7352
|
-
}
|
|
7353
|
-
}
|
|
7354
|
-
}
|
|
7355
|
-
} catch (checkErr) {
|
|
7356
|
-
if (checkErr.message?.startsWith('Batch "')) {
|
|
7357
|
-
throw checkErr;
|
|
7358
|
-
}
|
|
7359
|
-
}
|
|
7360
|
-
if (config.mode === "store") {
|
|
7361
|
-
const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
|
|
7362
|
-
const stored = await store.get({}) || { history: [] };
|
|
7363
|
-
const rawHistory = Array.isArray(stored.history) ? stored.history : [];
|
|
7364
|
-
if (rawHistory.length === 0) {
|
|
7365
|
-
throw new Error("No completed update records found in audit trail.");
|
|
7366
|
-
}
|
|
7367
|
-
const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
|
|
7368
|
-
const targetRecord2 = sortedHistory2.find((r) => r.batchId === batchId);
|
|
7369
|
-
if (!targetRecord2) {
|
|
7370
|
-
throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
|
|
7371
|
-
}
|
|
7372
|
-
const latestRecord2 = sortedHistory2[0];
|
|
7373
|
-
if (latestRecord2.batchId !== batchId) {
|
|
7374
|
-
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
7375
|
-
}
|
|
7376
|
-
if (targetRecord2.isRolledBack) {
|
|
7377
|
-
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
7378
|
-
}
|
|
7379
|
-
const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
|
|
7380
|
-
const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
|
|
7381
|
-
const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
|
|
7382
|
-
if (recordIndex !== -1) {
|
|
7383
|
-
rawHistory[recordIndex] = {
|
|
7384
|
-
...rawHistory[recordIndex],
|
|
7385
|
-
isRolledBack: true,
|
|
7386
|
-
rolledBackAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7387
|
-
rolledBackBy: currentUser?.email || "Admin"
|
|
7388
|
-
};
|
|
7389
|
-
await store.set({ value: { history: rawHistory } });
|
|
7390
|
-
}
|
|
7391
|
-
try {
|
|
7392
|
-
const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
|
|
7393
|
-
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
7394
|
-
affectedUids.forEach((uid) => {
|
|
7395
|
-
if (uid && bulkService?.invalidateCache) {
|
|
7396
|
-
bulkService.invalidateCache(uid);
|
|
7397
|
-
}
|
|
7398
|
-
});
|
|
7399
|
-
} catch {
|
|
7400
|
-
}
|
|
7401
|
-
await this.recordToEnterpriseNative(
|
|
7402
|
-
"bulk-updater.rollback",
|
|
7403
|
-
{
|
|
7404
|
-
batchId,
|
|
7405
|
-
revertedCount: revertedCount2
|
|
7406
|
-
},
|
|
7407
|
-
currentUser
|
|
7408
|
-
);
|
|
7409
|
-
return {
|
|
7410
|
-
success: true,
|
|
7411
|
-
batchId,
|
|
7412
|
-
revertedCount: revertedCount2,
|
|
7413
|
-
details: rollbackDetails2
|
|
7414
|
-
};
|
|
7415
|
-
}
|
|
7416
|
-
if (!config.contentType || !config.fields) {
|
|
7417
|
-
throw new Error("Audit trail is not configured or disabled.");
|
|
7418
|
-
}
|
|
7419
|
-
const f = config.fields;
|
|
7420
|
-
const allRecords = await strapi.documents(config.contentType).findMany({
|
|
7421
|
-
sort: { createdAt: "desc" }
|
|
7422
|
-
});
|
|
7423
|
-
if (!allRecords || allRecords.length === 0) {
|
|
7424
|
-
throw new Error("No completed update records found in audit trail.");
|
|
7425
|
-
}
|
|
7426
|
-
const normalizedHistory = allRecords.map((r) => ({
|
|
7427
|
-
id: r.id,
|
|
7428
|
-
documentId: r.documentId,
|
|
7429
|
-
batchId: r[f.batchId] || r.documentId,
|
|
7430
|
-
attribute: r[f.attribute],
|
|
7431
|
-
value: r[f.value],
|
|
7432
|
-
userEmail: r[f.userEmail] || "admin@strapi.io",
|
|
7433
|
-
userName: r[f.userName] || "Admin",
|
|
7434
|
-
updatedCount: r[f.updatedCount] || 0,
|
|
7435
|
-
skippedCount: r[f.skippedCount] || 0,
|
|
7436
|
-
totalTargets: r[f.totalTargets] || 0,
|
|
7437
|
-
diffs: typeof r[f.diffs] === "string" ? JSON.parse(r[f.diffs]) : r[f.diffs] || [],
|
|
7438
|
-
isRolledBack: Boolean(r[f.isRolledBack]),
|
|
7439
|
-
rolledBackAt: r[f.rolledBackAt] || null,
|
|
7440
|
-
rolledBackBy: r[f.rolledBackBy] || null,
|
|
7441
|
-
executedAt: r[f.executedAt] || r.createdAt,
|
|
7442
|
-
createdAt: r.createdAt
|
|
7443
|
-
}));
|
|
7444
|
-
const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
|
|
7445
|
-
const targetRecord = sortedHistory.find((r) => r.batchId === batchId);
|
|
7446
|
-
if (!targetRecord) {
|
|
7447
|
-
throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
|
|
7448
|
-
}
|
|
7449
|
-
const latestRecord = sortedHistory[0];
|
|
7450
|
-
if (latestRecord.batchId !== batchId) {
|
|
7451
|
-
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
7452
|
-
}
|
|
7453
|
-
if (targetRecord.isRolledBack) {
|
|
7454
|
-
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
7455
|
-
}
|
|
7456
|
-
const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
|
|
7457
|
-
const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
|
|
7458
|
-
const updateData = {};
|
|
7459
|
-
if (f.isRolledBack) updateData[f.isRolledBack] = true;
|
|
7460
|
-
if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
|
|
7461
|
-
if (f.rolledBackBy) {
|
|
7462
|
-
updateData[f.rolledBackBy] = currentUser?.email || "Admin";
|
|
7463
|
-
}
|
|
7464
|
-
await strapi.documents(config.contentType).update({
|
|
7465
|
-
documentId: targetRecord.documentId,
|
|
7466
|
-
data: updateData
|
|
7467
|
-
});
|
|
7468
|
-
try {
|
|
7469
|
-
const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
|
|
7470
|
-
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
7471
|
-
affectedUids.forEach((uid) => {
|
|
7472
|
-
if (uid && bulkService?.invalidateCache) {
|
|
7473
|
-
bulkService.invalidateCache(uid);
|
|
7474
|
-
}
|
|
7475
|
-
});
|
|
7476
|
-
} catch {
|
|
7477
|
-
}
|
|
7478
|
-
await this.recordToEnterpriseNative(
|
|
7479
|
-
"bulk-updater.rollback",
|
|
7480
|
-
{
|
|
7481
|
-
batchId,
|
|
7482
|
-
revertedCount
|
|
7483
|
-
},
|
|
7484
|
-
currentUser
|
|
7485
|
-
);
|
|
7486
|
-
return {
|
|
7487
|
-
success: true,
|
|
7488
|
-
batchId,
|
|
7489
|
-
revertedCount,
|
|
7490
|
-
details: rollbackDetails
|
|
7491
|
-
};
|
|
7492
|
-
});
|
|
7493
|
-
}
|
|
7494
|
-
});
|
|
7495
|
-
function buildComponentPopulate(strapi, compUid, visited, depth, maxDepth) {
|
|
7496
|
-
if (depth >= maxDepth) return true;
|
|
7497
|
-
if (visited.has(compUid)) return true;
|
|
7498
|
-
const comp = strapi.components?.[compUid];
|
|
7499
|
-
if (!comp?.attributes) return true;
|
|
7500
|
-
const nextVisited = new Set(visited);
|
|
7501
|
-
nextVisited.add(compUid);
|
|
7502
|
-
const populate = {};
|
|
7503
|
-
for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
|
|
7504
|
-
const category = classifyAttribute(attrName, attrDef);
|
|
7505
|
-
if (category === "component_single" || category === "component_repeatable") {
|
|
7506
|
-
if (attrDef.component) {
|
|
7507
|
-
const subPop = buildComponentPopulate(
|
|
7508
|
-
strapi,
|
|
7509
|
-
attrDef.component,
|
|
7510
|
-
nextVisited,
|
|
7511
|
-
depth + 1,
|
|
7512
|
-
maxDepth
|
|
7513
|
-
);
|
|
7514
|
-
populate[attrName] = typeof subPop === "object" && Object.keys(subPop).length > 0 ? { populate: subPop } : true;
|
|
7515
|
-
} else {
|
|
7516
|
-
populate[attrName] = true;
|
|
7517
|
-
}
|
|
7518
|
-
} else if (category === "dynamiczone") {
|
|
7519
|
-
const dzComponents = Array.isArray(attrDef.components) ? attrDef.components : [];
|
|
7520
|
-
if (dzComponents.length > 0) {
|
|
7521
|
-
const onPopulate = {};
|
|
7522
|
-
for (const dzCompUid of dzComponents) {
|
|
7523
|
-
const dzCompPop = buildComponentPopulate(
|
|
7524
|
-
strapi,
|
|
7525
|
-
dzCompUid,
|
|
7526
|
-
nextVisited,
|
|
7527
|
-
depth + 1,
|
|
7528
|
-
maxDepth
|
|
7529
|
-
);
|
|
7530
|
-
onPopulate[dzCompUid] = typeof dzCompPop === "object" && Object.keys(dzCompPop).length > 0 ? { populate: dzCompPop } : true;
|
|
8363
|
+
}
|
|
8364
|
+
} catch {
|
|
8365
|
+
}
|
|
8366
|
+
revertedCount++;
|
|
8367
|
+
rollbackDetails.push({
|
|
8368
|
+
uid: item.uid,
|
|
8369
|
+
documentId: item.documentId,
|
|
8370
|
+
label: item.label,
|
|
8371
|
+
attribute: item.attribute,
|
|
8372
|
+
revertedTo: item.oldValue,
|
|
8373
|
+
status: "reverted"
|
|
8374
|
+
});
|
|
8375
|
+
} catch (err) {
|
|
8376
|
+
rollbackDetails.push({
|
|
8377
|
+
uid: item.uid,
|
|
8378
|
+
documentId: item.documentId,
|
|
8379
|
+
label: item.label,
|
|
8380
|
+
status: "error",
|
|
8381
|
+
message: err.message
|
|
8382
|
+
});
|
|
7531
8383
|
}
|
|
7532
|
-
populate[attrName] = { on: onPopulate };
|
|
7533
|
-
} else {
|
|
7534
|
-
populate[attrName] = { populate: "*" };
|
|
7535
8384
|
}
|
|
7536
|
-
} else if (category === "relation_to_one" || category === "relation_to_many") {
|
|
7537
|
-
populate[attrName] = true;
|
|
7538
|
-
} else if (category === "media_single" || category === "media_to_many") {
|
|
7539
|
-
populate[attrName] = true;
|
|
7540
8385
|
}
|
|
7541
|
-
|
|
7542
|
-
|
|
7543
|
-
|
|
7544
|
-
|
|
7545
|
-
|
|
7546
|
-
|
|
7547
|
-
|
|
7548
|
-
|
|
7549
|
-
|
|
7550
|
-
|
|
7551
|
-
|
|
7552
|
-
|
|
7553
|
-
if (field.componentUid) {
|
|
7554
|
-
const compPop = buildComponentPopulate(
|
|
7555
|
-
strapi,
|
|
7556
|
-
field.componentUid,
|
|
7557
|
-
visited,
|
|
7558
|
-
0,
|
|
7559
|
-
maxDepth
|
|
7560
|
-
);
|
|
7561
|
-
populate[fieldName] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
|
|
7562
|
-
} else {
|
|
7563
|
-
populate[fieldName] = true;
|
|
7564
|
-
}
|
|
7565
|
-
break;
|
|
8386
|
+
return { revertedCount, rollbackDetails };
|
|
8387
|
+
},
|
|
8388
|
+
/**
|
|
8389
|
+
* Performs deterministic rollback of a batch.
|
|
8390
|
+
* Strict invariant: ONLY the latest completed update is eligible for rollback.
|
|
8391
|
+
* Older completed updates, already rolled-back updates, and pending/failed/executing batches are strictly rejected.
|
|
8392
|
+
*/
|
|
8393
|
+
async rollbackBatch(batchId, currentUser) {
|
|
8394
|
+
return withRollbackLock(async () => {
|
|
8395
|
+
const config = this.getAuditConfig();
|
|
8396
|
+
if (!config.enabled) {
|
|
8397
|
+
throw new Error("Audit trail is not configured or disabled.");
|
|
7566
8398
|
}
|
|
7567
|
-
|
|
7568
|
-
|
|
7569
|
-
|
|
7570
|
-
|
|
7571
|
-
|
|
7572
|
-
|
|
7573
|
-
|
|
7574
|
-
|
|
7575
|
-
|
|
7576
|
-
|
|
7577
|
-
|
|
7578
|
-
|
|
7579
|
-
|
|
8399
|
+
if (!batchId) {
|
|
8400
|
+
throw new Error("A valid batchId is required to perform rollback.");
|
|
8401
|
+
}
|
|
8402
|
+
try {
|
|
8403
|
+
const bulkService = strapi.plugin("bulk-updater")?.service("bulkUpdater");
|
|
8404
|
+
if (bulkService && typeof bulkService.getBatchStatus === "function") {
|
|
8405
|
+
const statusRes = await bulkService.getBatchStatus(batchId);
|
|
8406
|
+
const batchJob = statusRes?.batch;
|
|
8407
|
+
if (batchJob) {
|
|
8408
|
+
if (batchJob.status === "pending_approval" || batchJob.status === "queued_offpeak") {
|
|
8409
|
+
throw new Error(`Batch "${batchId}" is currently pending and cannot be rolled back.`);
|
|
8410
|
+
}
|
|
8411
|
+
if (batchJob.status === "processing" || batchJob.status === "running" || batchJob.status === "executing") {
|
|
8412
|
+
throw new Error(`Batch "${batchId}" is currently executing and cannot be rolled back.`);
|
|
8413
|
+
}
|
|
8414
|
+
if (batchJob.status === "failed") {
|
|
8415
|
+
throw new Error(`Batch "${batchId}" failed during execution and cannot be rolled back.`);
|
|
8416
|
+
}
|
|
7580
8417
|
}
|
|
7581
|
-
populate[fieldName] = { on: onPopulate };
|
|
7582
|
-
} else {
|
|
7583
|
-
populate[fieldName] = { populate: "*" };
|
|
7584
8418
|
}
|
|
7585
|
-
|
|
7586
|
-
|
|
7587
|
-
|
|
7588
|
-
case "relation_to_many": {
|
|
7589
|
-
populate[fieldName] = true;
|
|
7590
|
-
break;
|
|
7591
|
-
}
|
|
7592
|
-
case "media_single":
|
|
7593
|
-
case "media_to_many": {
|
|
7594
|
-
populate[fieldName] = true;
|
|
7595
|
-
break;
|
|
7596
|
-
}
|
|
7597
|
-
}
|
|
7598
|
-
}
|
|
7599
|
-
return Object.keys(populate).length > 0 ? populate : void 0;
|
|
7600
|
-
}
|
|
7601
|
-
const METADATA_COLUMN_KEY = "__bulk_updater_metadata";
|
|
7602
|
-
const CURRENT_SCHEMA_VERSION = 1;
|
|
7603
|
-
function escapeCsvCell(val) {
|
|
7604
|
-
if (val === null || val === void 0) return "";
|
|
7605
|
-
let str = "";
|
|
7606
|
-
if (val instanceof Date) {
|
|
7607
|
-
str = val.toISOString();
|
|
7608
|
-
} else if (typeof val === "object") {
|
|
7609
|
-
str = JSON.stringify(val);
|
|
7610
|
-
} else {
|
|
7611
|
-
str = String(val);
|
|
7612
|
-
}
|
|
7613
|
-
str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
7614
|
-
if (/^[=+@-]/.test(str)) {
|
|
7615
|
-
str = `'${str}`;
|
|
7616
|
-
}
|
|
7617
|
-
if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
|
|
7618
|
-
return `"${str.replace(/"/g, '""')}"`;
|
|
7619
|
-
}
|
|
7620
|
-
return str;
|
|
7621
|
-
}
|
|
7622
|
-
function parseCsvToMatrix(csvText) {
|
|
7623
|
-
if (!csvText) return [];
|
|
7624
|
-
let text = csvText;
|
|
7625
|
-
if (text.charCodeAt(0) === 65279) {
|
|
7626
|
-
text = text.slice(1);
|
|
7627
|
-
}
|
|
7628
|
-
const rows = [];
|
|
7629
|
-
let currentRow = [];
|
|
7630
|
-
let currentCell = "";
|
|
7631
|
-
let inQuotes = false;
|
|
7632
|
-
let cellIsQuoted = false;
|
|
7633
|
-
for (let i = 0; i < text.length; i++) {
|
|
7634
|
-
const char = text[i];
|
|
7635
|
-
const nextChar = text[i + 1];
|
|
7636
|
-
if (inQuotes) {
|
|
7637
|
-
if (char === '"') {
|
|
7638
|
-
if (nextChar === '"') {
|
|
7639
|
-
currentCell += '"';
|
|
7640
|
-
i++;
|
|
7641
|
-
} else {
|
|
7642
|
-
inQuotes = false;
|
|
8419
|
+
} catch (checkErr) {
|
|
8420
|
+
if (checkErr.message?.startsWith('Batch "')) {
|
|
8421
|
+
throw checkErr;
|
|
7643
8422
|
}
|
|
7644
|
-
} else {
|
|
7645
|
-
currentCell += char;
|
|
7646
8423
|
}
|
|
7647
|
-
|
|
7648
|
-
|
|
7649
|
-
|
|
7650
|
-
|
|
7651
|
-
|
|
7652
|
-
|
|
7653
|
-
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
7654
|
-
currentCell = "";
|
|
7655
|
-
cellIsQuoted = false;
|
|
7656
|
-
} else if (char === "\r") {
|
|
7657
|
-
if (nextChar === "\n") {
|
|
7658
|
-
i++;
|
|
8424
|
+
if (config.mode === "store") {
|
|
8425
|
+
const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
|
|
8426
|
+
const stored = await store.get({}) || { history: [] };
|
|
8427
|
+
const rawHistory = Array.isArray(stored.history) ? stored.history : [];
|
|
8428
|
+
if (rawHistory.length === 0) {
|
|
8429
|
+
throw new Error("No completed update records found in audit trail.");
|
|
7659
8430
|
}
|
|
7660
|
-
|
|
7661
|
-
|
|
7662
|
-
|
|
8431
|
+
const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
|
|
8432
|
+
const targetRecord2 = sortedHistory2.find((r) => r.batchId === batchId);
|
|
8433
|
+
if (!targetRecord2) {
|
|
8434
|
+
throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
|
|
7663
8435
|
}
|
|
7664
|
-
|
|
7665
|
-
|
|
7666
|
-
|
|
7667
|
-
} else if (char === "\n") {
|
|
7668
|
-
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
7669
|
-
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
7670
|
-
rows.push(currentRow);
|
|
8436
|
+
const latestRecord2 = sortedHistory2[0];
|
|
8437
|
+
if (latestRecord2.batchId !== batchId) {
|
|
8438
|
+
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
7671
8439
|
}
|
|
7672
|
-
|
|
7673
|
-
|
|
7674
|
-
cellIsQuoted = false;
|
|
7675
|
-
} else {
|
|
7676
|
-
if (!(cellIsQuoted && !inQuotes && (char === " " || char === " "))) {
|
|
7677
|
-
currentCell += char;
|
|
8440
|
+
if (targetRecord2.isRolledBack) {
|
|
8441
|
+
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
7678
8442
|
}
|
|
8443
|
+
const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
|
|
8444
|
+
const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
|
|
8445
|
+
const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
|
|
8446
|
+
if (recordIndex !== -1) {
|
|
8447
|
+
rawHistory[recordIndex] = {
|
|
8448
|
+
...rawHistory[recordIndex],
|
|
8449
|
+
isRolledBack: true,
|
|
8450
|
+
rolledBackAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8451
|
+
rolledBackBy: currentUser?.email || "Admin"
|
|
8452
|
+
};
|
|
8453
|
+
await store.set({ value: { history: rawHistory } });
|
|
8454
|
+
}
|
|
8455
|
+
try {
|
|
8456
|
+
const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
|
|
8457
|
+
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
8458
|
+
affectedUids.forEach((uid) => {
|
|
8459
|
+
if (uid && bulkService?.invalidateCache) {
|
|
8460
|
+
bulkService.invalidateCache(uid);
|
|
8461
|
+
}
|
|
8462
|
+
});
|
|
8463
|
+
} catch {
|
|
8464
|
+
}
|
|
8465
|
+
await this.recordToEnterpriseNative(
|
|
8466
|
+
"bulk-updater.rollback",
|
|
8467
|
+
{
|
|
8468
|
+
batchId,
|
|
8469
|
+
revertedCount: revertedCount2
|
|
8470
|
+
},
|
|
8471
|
+
currentUser
|
|
8472
|
+
);
|
|
8473
|
+
return {
|
|
8474
|
+
success: true,
|
|
8475
|
+
batchId,
|
|
8476
|
+
revertedCount: revertedCount2,
|
|
8477
|
+
details: rollbackDetails2
|
|
8478
|
+
};
|
|
7679
8479
|
}
|
|
7680
|
-
|
|
7681
|
-
|
|
7682
|
-
if (currentCell !== "" || cellIsQuoted || currentRow.length > 0) {
|
|
7683
|
-
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
7684
|
-
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
7685
|
-
rows.push(currentRow);
|
|
7686
|
-
}
|
|
7687
|
-
}
|
|
7688
|
-
return rows;
|
|
7689
|
-
}
|
|
7690
|
-
function parseCsvToRecords(csvText) {
|
|
7691
|
-
const matrix = parseCsvToMatrix(csvText);
|
|
7692
|
-
if (matrix.length < 2) return [];
|
|
7693
|
-
const headers = matrix[0].map((h) => h.trim());
|
|
7694
|
-
const records = [];
|
|
7695
|
-
for (let i = 1; i < matrix.length; i++) {
|
|
7696
|
-
const row = matrix[i];
|
|
7697
|
-
const record = {};
|
|
7698
|
-
headers.forEach((h, idx) => {
|
|
7699
|
-
let val = row[idx] !== void 0 ? row[idx] : "";
|
|
7700
|
-
if (typeof val === "string" && /^'[=+@-]/.test(val)) {
|
|
7701
|
-
val = val.substring(1);
|
|
7702
|
-
}
|
|
7703
|
-
record[h] = val;
|
|
7704
|
-
});
|
|
7705
|
-
records.push(record);
|
|
7706
|
-
}
|
|
7707
|
-
return records;
|
|
7708
|
-
}
|
|
7709
|
-
function serializeFieldValue(value, field) {
|
|
7710
|
-
if (value === null || value === void 0) {
|
|
7711
|
-
return "";
|
|
7712
|
-
}
|
|
7713
|
-
switch (field.category) {
|
|
7714
|
-
case "scalar": {
|
|
7715
|
-
if (value instanceof Date) {
|
|
7716
|
-
return value.toISOString();
|
|
8480
|
+
if (!config.contentType || !config.fields) {
|
|
8481
|
+
throw new Error("Audit trail is not configured or disabled.");
|
|
7717
8482
|
}
|
|
7718
|
-
|
|
7719
|
-
|
|
7720
|
-
|
|
7721
|
-
|
|
7722
|
-
|
|
7723
|
-
|
|
7724
|
-
case "component_single": {
|
|
7725
|
-
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
7726
|
-
}
|
|
7727
|
-
case "component_repeatable": {
|
|
7728
|
-
if (Array.isArray(value)) {
|
|
7729
|
-
return JSON.stringify(value);
|
|
8483
|
+
const f = config.fields;
|
|
8484
|
+
const allRecords = await strapi.documents(config.contentType).findMany({
|
|
8485
|
+
sort: { createdAt: "desc" }
|
|
8486
|
+
});
|
|
8487
|
+
if (!allRecords || allRecords.length === 0) {
|
|
8488
|
+
throw new Error("No completed update records found in audit trail.");
|
|
7730
8489
|
}
|
|
7731
|
-
|
|
7732
|
-
|
|
7733
|
-
|
|
7734
|
-
|
|
7735
|
-
|
|
7736
|
-
|
|
7737
|
-
|
|
7738
|
-
|
|
7739
|
-
|
|
7740
|
-
|
|
7741
|
-
|
|
8490
|
+
const normalizedHistory = allRecords.map((r) => ({
|
|
8491
|
+
id: r.id,
|
|
8492
|
+
documentId: r.documentId,
|
|
8493
|
+
batchId: r[f.batchId] || r.documentId,
|
|
8494
|
+
attribute: r[f.attribute],
|
|
8495
|
+
value: r[f.value],
|
|
8496
|
+
userEmail: r[f.userEmail] || "admin@strapi.io",
|
|
8497
|
+
userName: r[f.userName] || "Admin",
|
|
8498
|
+
updatedCount: r[f.updatedCount] || 0,
|
|
8499
|
+
skippedCount: r[f.skippedCount] || 0,
|
|
8500
|
+
totalTargets: r[f.totalTargets] || 0,
|
|
8501
|
+
diffs: typeof r[f.diffs] === "string" ? JSON.parse(r[f.diffs]) : r[f.diffs] || [],
|
|
8502
|
+
isRolledBack: Boolean(r[f.isRolledBack]),
|
|
8503
|
+
rolledBackAt: r[f.rolledBackAt] || null,
|
|
8504
|
+
rolledBackBy: r[f.rolledBackBy] || null,
|
|
8505
|
+
executedAt: r[f.executedAt] || r.createdAt,
|
|
8506
|
+
createdAt: r.createdAt
|
|
8507
|
+
}));
|
|
8508
|
+
const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
|
|
8509
|
+
const targetRecord = sortedHistory.find((r) => r.batchId === batchId);
|
|
8510
|
+
if (!targetRecord) {
|
|
8511
|
+
throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
|
|
7742
8512
|
}
|
|
7743
|
-
|
|
7744
|
-
|
|
7745
|
-
|
|
7746
|
-
if (typeof value === "object" && value !== null) {
|
|
7747
|
-
const docId = value.documentId || value.id || "";
|
|
7748
|
-
return JSON.stringify({
|
|
7749
|
-
documentId: String(docId),
|
|
7750
|
-
title: value.title || value.name || value.slug || void 0
|
|
7751
|
-
});
|
|
8513
|
+
const latestRecord = sortedHistory[0];
|
|
8514
|
+
if (latestRecord.batchId !== batchId) {
|
|
8515
|
+
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
7752
8516
|
}
|
|
7753
|
-
|
|
7754
|
-
|
|
7755
|
-
case "relation_to_many": {
|
|
7756
|
-
if (Array.isArray(value)) {
|
|
7757
|
-
const list = value.map((item) => {
|
|
7758
|
-
if (typeof item === "object" && item !== null) {
|
|
7759
|
-
const docId = item.documentId || item.id || "";
|
|
7760
|
-
return {
|
|
7761
|
-
documentId: String(docId),
|
|
7762
|
-
title: item.title || item.name || item.slug || void 0
|
|
7763
|
-
};
|
|
7764
|
-
}
|
|
7765
|
-
return { documentId: String(item) };
|
|
7766
|
-
});
|
|
7767
|
-
return JSON.stringify(list);
|
|
8517
|
+
if (targetRecord.isRolledBack) {
|
|
8518
|
+
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
7768
8519
|
}
|
|
7769
|
-
|
|
7770
|
-
|
|
7771
|
-
|
|
7772
|
-
if (
|
|
7773
|
-
|
|
7774
|
-
|
|
7775
|
-
|
|
7776
|
-
name: value.name,
|
|
7777
|
-
url: value.url,
|
|
7778
|
-
mime: value.mime
|
|
7779
|
-
});
|
|
8520
|
+
const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
|
|
8521
|
+
const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
|
|
8522
|
+
const updateData = {};
|
|
8523
|
+
if (f.isRolledBack) updateData[f.isRolledBack] = true;
|
|
8524
|
+
if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
|
|
8525
|
+
if (f.rolledBackBy) {
|
|
8526
|
+
updateData[f.rolledBackBy] = currentUser?.email || "Admin";
|
|
7780
8527
|
}
|
|
7781
|
-
|
|
7782
|
-
|
|
7783
|
-
|
|
7784
|
-
|
|
7785
|
-
|
|
7786
|
-
|
|
7787
|
-
|
|
7788
|
-
|
|
7789
|
-
|
|
7790
|
-
|
|
7791
|
-
url: file.url,
|
|
7792
|
-
mime: file.mime
|
|
7793
|
-
};
|
|
8528
|
+
await strapi.documents(config.contentType).update({
|
|
8529
|
+
documentId: targetRecord.documentId,
|
|
8530
|
+
data: updateData
|
|
8531
|
+
});
|
|
8532
|
+
try {
|
|
8533
|
+
const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
|
|
8534
|
+
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
8535
|
+
affectedUids.forEach((uid) => {
|
|
8536
|
+
if (uid && bulkService?.invalidateCache) {
|
|
8537
|
+
bulkService.invalidateCache(uid);
|
|
7794
8538
|
}
|
|
7795
|
-
return file;
|
|
7796
8539
|
});
|
|
7797
|
-
|
|
7798
|
-
}
|
|
7799
|
-
return "";
|
|
7800
|
-
}
|
|
7801
|
-
default:
|
|
7802
|
-
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
7803
|
-
}
|
|
7804
|
-
}
|
|
7805
|
-
function serializeDocumentsToCsv(strapi, uid, documents) {
|
|
7806
|
-
const schema = discoverSchema(strapi, uid);
|
|
7807
|
-
const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
|
|
7808
|
-
const lines = [];
|
|
7809
|
-
lines.push(headers.map(escapeCsvCell).join(","));
|
|
7810
|
-
const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
7811
|
-
for (const doc of documents) {
|
|
7812
|
-
const rowValues = [];
|
|
7813
|
-
const metadata = {
|
|
7814
|
-
schemaVersion: CURRENT_SCHEMA_VERSION,
|
|
7815
|
-
contentType: uid,
|
|
7816
|
-
documentId: String(doc.documentId || doc.id || ""),
|
|
7817
|
-
locale: doc.locale || void 0,
|
|
7818
|
-
exportedAt
|
|
7819
|
-
};
|
|
7820
|
-
rowValues.push(escapeCsvCell(metadata));
|
|
7821
|
-
for (const key of schema.allExportKeys) {
|
|
7822
|
-
if (key === "documentId") {
|
|
7823
|
-
rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
|
|
7824
|
-
} else if (key === "locale") {
|
|
7825
|
-
rowValues.push(escapeCsvCell(doc.locale || ""));
|
|
7826
|
-
} else {
|
|
7827
|
-
const field = schema.fields[key];
|
|
7828
|
-
const rawValue = doc[key];
|
|
7829
|
-
if (field) {
|
|
7830
|
-
const serialized = serializeFieldValue(rawValue, field);
|
|
7831
|
-
rowValues.push(escapeCsvCell(serialized));
|
|
7832
|
-
} else {
|
|
7833
|
-
rowValues.push(escapeCsvCell(rawValue));
|
|
7834
|
-
}
|
|
7835
|
-
}
|
|
7836
|
-
}
|
|
7837
|
-
lines.push(rowValues.join(","));
|
|
7838
|
-
}
|
|
7839
|
-
const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
|
|
7840
|
-
return {
|
|
7841
|
-
csvContent,
|
|
7842
|
-
headers,
|
|
7843
|
-
count: documents.length
|
|
7844
|
-
};
|
|
7845
|
-
}
|
|
7846
|
-
function extractMetadataFromRow(row) {
|
|
7847
|
-
if (!row || typeof row !== "object") return null;
|
|
7848
|
-
const rawMeta = row[METADATA_COLUMN_KEY] || row["__bulk_updater_metadata"];
|
|
7849
|
-
if (!rawMeta) return null;
|
|
7850
|
-
if (typeof rawMeta === "object") {
|
|
7851
|
-
return rawMeta;
|
|
7852
|
-
}
|
|
7853
|
-
if (typeof rawMeta === "string") {
|
|
7854
|
-
try {
|
|
7855
|
-
const parsed = JSON.parse(rawMeta);
|
|
7856
|
-
if (parsed && typeof parsed === "object") {
|
|
7857
|
-
return parsed;
|
|
8540
|
+
} catch {
|
|
7858
8541
|
}
|
|
7859
|
-
|
|
7860
|
-
|
|
7861
|
-
|
|
7862
|
-
|
|
7863
|
-
|
|
7864
|
-
|
|
7865
|
-
|
|
7866
|
-
|
|
7867
|
-
|
|
7868
|
-
|
|
7869
|
-
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
|
|
7873
|
-
|
|
7874
|
-
);
|
|
7875
|
-
if (!existingLower.has("error")) {
|
|
7876
|
-
return "Error";
|
|
7877
|
-
}
|
|
7878
|
-
if (!existingLower.has("import error")) {
|
|
7879
|
-
return "Import Error";
|
|
7880
|
-
}
|
|
7881
|
-
let suffix = 2;
|
|
7882
|
-
while (existingLower.has(`import error (${suffix})`)) {
|
|
7883
|
-
suffix++;
|
|
7884
|
-
}
|
|
7885
|
-
return `Import Error (${suffix})`;
|
|
7886
|
-
}
|
|
7887
|
-
function formatErrorCsvFilename(collectionTypeOrUid, date = /* @__PURE__ */ new Date()) {
|
|
7888
|
-
const rawSegment = collectionTypeOrUid ? String(collectionTypeOrUid).split(".").pop() || String(collectionTypeOrUid) : "collection";
|
|
7889
|
-
const safeType = rawSegment.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "collection";
|
|
7890
|
-
const pad = (n) => String(n).padStart(2, "0");
|
|
7891
|
-
const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(
|
|
7892
|
-
date.getHours()
|
|
7893
|
-
)}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
|
7894
|
-
return `error_${safeType}_${stamp}.csv`;
|
|
7895
|
-
}
|
|
7896
|
-
function buildErrorCsv(options) {
|
|
7897
|
-
const { headers, failedRows } = options || {};
|
|
7898
|
-
if (!Array.isArray(failedRows) || failedRows.length === 0) {
|
|
7899
|
-
return {
|
|
7900
|
-
csvContent: "",
|
|
7901
|
-
headers: headers ? [...headers] : [],
|
|
7902
|
-
errorColumnName: "Error",
|
|
7903
|
-
errorCount: 0
|
|
7904
|
-
};
|
|
8542
|
+
await this.recordToEnterpriseNative(
|
|
8543
|
+
"bulk-updater.rollback",
|
|
8544
|
+
{
|
|
8545
|
+
batchId,
|
|
8546
|
+
revertedCount
|
|
8547
|
+
},
|
|
8548
|
+
currentUser
|
|
8549
|
+
);
|
|
8550
|
+
return {
|
|
8551
|
+
success: true,
|
|
8552
|
+
batchId,
|
|
8553
|
+
revertedCount,
|
|
8554
|
+
details: rollbackDetails
|
|
8555
|
+
};
|
|
8556
|
+
});
|
|
7905
8557
|
}
|
|
7906
|
-
|
|
7907
|
-
|
|
7908
|
-
|
|
7909
|
-
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
7913
|
-
|
|
7914
|
-
|
|
8558
|
+
});
|
|
8559
|
+
function buildComponentPopulate(strapi, compUid, visited, depth, maxDepth) {
|
|
8560
|
+
if (depth >= maxDepth) return true;
|
|
8561
|
+
if (visited.has(compUid)) return true;
|
|
8562
|
+
const comp = strapi.components?.[compUid];
|
|
8563
|
+
if (!comp?.attributes) return true;
|
|
8564
|
+
const nextVisited = new Set(visited);
|
|
8565
|
+
nextVisited.add(compUid);
|
|
8566
|
+
const populate = {};
|
|
8567
|
+
for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
|
|
8568
|
+
const category = classifyAttribute(attrName, attrDef);
|
|
8569
|
+
if (category === "component_single" || category === "component_repeatable") {
|
|
8570
|
+
if (attrDef.component) {
|
|
8571
|
+
const subPop = buildComponentPopulate(
|
|
8572
|
+
strapi,
|
|
8573
|
+
attrDef.component,
|
|
8574
|
+
nextVisited,
|
|
8575
|
+
depth + 1,
|
|
8576
|
+
maxDepth
|
|
8577
|
+
);
|
|
8578
|
+
populate[attrName] = typeof subPop === "object" && Object.keys(subPop).length > 0 ? { populate: subPop } : true;
|
|
8579
|
+
} else {
|
|
8580
|
+
populate[attrName] = true;
|
|
7915
8581
|
}
|
|
7916
|
-
} else {
|
|
7917
|
-
|
|
7918
|
-
|
|
7919
|
-
|
|
7920
|
-
|
|
7921
|
-
|
|
7922
|
-
|
|
8582
|
+
} else if (category === "dynamiczone") {
|
|
8583
|
+
const dzComponents = Array.isArray(attrDef.components) ? attrDef.components : [];
|
|
8584
|
+
if (dzComponents.length > 0) {
|
|
8585
|
+
const onPopulate = {};
|
|
8586
|
+
for (const dzCompUid of dzComponents) {
|
|
8587
|
+
const dzCompPop = buildComponentPopulate(
|
|
8588
|
+
strapi,
|
|
8589
|
+
dzCompUid,
|
|
8590
|
+
nextVisited,
|
|
8591
|
+
depth + 1,
|
|
8592
|
+
maxDepth
|
|
8593
|
+
);
|
|
8594
|
+
onPopulate[dzCompUid] = typeof dzCompPop === "object" && Object.keys(dzCompPop).length > 0 ? { populate: dzCompPop } : true;
|
|
8595
|
+
}
|
|
8596
|
+
populate[attrName] = { on: onPopulate };
|
|
8597
|
+
} else {
|
|
8598
|
+
populate[attrName] = { populate: "*" };
|
|
8599
|
+
}
|
|
8600
|
+
} else if (category === "relation_to_one" || category === "relation_to_many") {
|
|
8601
|
+
populate[attrName] = true;
|
|
8602
|
+
} else if (category === "media_single" || category === "media_to_many") {
|
|
8603
|
+
populate[attrName] = true;
|
|
7923
8604
|
}
|
|
7924
8605
|
}
|
|
7925
|
-
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7932
|
-
|
|
7933
|
-
|
|
7934
|
-
|
|
7935
|
-
|
|
7936
|
-
|
|
7937
|
-
|
|
7938
|
-
|
|
7939
|
-
|
|
7940
|
-
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
8606
|
+
return Object.keys(populate).length > 0 ? populate : true;
|
|
8607
|
+
}
|
|
8608
|
+
function buildLosslessPopulate(strapi, uid, options = {}) {
|
|
8609
|
+
const maxDepth = options.maxDepth || 5;
|
|
8610
|
+
const schema = discoverSchema(strapi, uid);
|
|
8611
|
+
const populate = {};
|
|
8612
|
+
const visited = /* @__PURE__ */ new Set([uid]);
|
|
8613
|
+
for (const [fieldName, field] of Object.entries(schema.fields)) {
|
|
8614
|
+
switch (field.category) {
|
|
8615
|
+
case "component_single":
|
|
8616
|
+
case "component_repeatable": {
|
|
8617
|
+
if (field.componentUid) {
|
|
8618
|
+
const compPop = buildComponentPopulate(
|
|
8619
|
+
strapi,
|
|
8620
|
+
field.componentUid,
|
|
8621
|
+
visited,
|
|
8622
|
+
0,
|
|
8623
|
+
maxDepth
|
|
8624
|
+
);
|
|
8625
|
+
populate[fieldName] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
|
|
8626
|
+
} else {
|
|
8627
|
+
populate[fieldName] = true;
|
|
8628
|
+
}
|
|
8629
|
+
break;
|
|
8630
|
+
}
|
|
8631
|
+
case "dynamiczone": {
|
|
8632
|
+
const dzComponents = field.dzComponents || [];
|
|
8633
|
+
if (dzComponents.length > 0) {
|
|
8634
|
+
const onPopulate = {};
|
|
8635
|
+
for (const compUid of dzComponents) {
|
|
8636
|
+
const compPop = buildComponentPopulate(
|
|
8637
|
+
strapi,
|
|
8638
|
+
compUid,
|
|
8639
|
+
visited,
|
|
8640
|
+
0,
|
|
8641
|
+
maxDepth
|
|
8642
|
+
);
|
|
8643
|
+
onPopulate[compUid] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
|
|
8644
|
+
}
|
|
8645
|
+
populate[fieldName] = { on: onPopulate };
|
|
8646
|
+
} else {
|
|
8647
|
+
populate[fieldName] = { populate: "*" };
|
|
7944
8648
|
}
|
|
8649
|
+
break;
|
|
8650
|
+
}
|
|
8651
|
+
case "relation_to_one":
|
|
8652
|
+
case "relation_to_many": {
|
|
8653
|
+
populate[fieldName] = true;
|
|
8654
|
+
break;
|
|
8655
|
+
}
|
|
8656
|
+
case "media_single":
|
|
8657
|
+
case "media_to_many": {
|
|
8658
|
+
populate[fieldName] = true;
|
|
8659
|
+
break;
|
|
7945
8660
|
}
|
|
7946
8661
|
}
|
|
7947
8662
|
}
|
|
7948
|
-
|
|
7949
|
-
const finalHeaders = [...baseHeaders, errorColumnName];
|
|
7950
|
-
const lines = [];
|
|
7951
|
-
lines.push(finalHeaders.map(escapeCsvCell).join(","));
|
|
7952
|
-
for (const entry of orderedEntries) {
|
|
7953
|
-
const cells = baseHeaders.map((h) => {
|
|
7954
|
-
const val = entry.originalRow ? entry.originalRow[h] : "";
|
|
7955
|
-
return escapeCsvCell(val === void 0 || val === null ? "" : val);
|
|
7956
|
-
});
|
|
7957
|
-
cells.push(escapeCsvCell(entry.messages.join("; ")));
|
|
7958
|
-
lines.push(cells.join(","));
|
|
7959
|
-
}
|
|
7960
|
-
const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
|
|
7961
|
-
return {
|
|
7962
|
-
csvContent,
|
|
7963
|
-
headers: finalHeaders,
|
|
7964
|
-
errorColumnName,
|
|
7965
|
-
errorCount: orderedEntries.length
|
|
7966
|
-
};
|
|
8663
|
+
return Object.keys(populate).length > 0 ? populate : void 0;
|
|
7967
8664
|
}
|
|
7968
8665
|
function normalizeVal(val) {
|
|
7969
8666
|
if (val === null || val === void 0) return null;
|
|
@@ -8599,6 +9296,46 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
|
|
|
8599
9296
|
publishStrategy: options.publishStrategy || "safe",
|
|
8600
9297
|
unreviewedConsent: options.unreviewedConsent
|
|
8601
9298
|
});
|
|
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
|
+
}
|
|
8602
9339
|
const proposedEntity = deepMergeEntities(existing, updatePayload);
|
|
8603
9340
|
const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
|
|
8604
9341
|
if (!valResult.isValid) {
|
|
@@ -8686,8 +9423,48 @@ async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, opt
|
|
|
8686
9423
|
uid,
|
|
8687
9424
|
null,
|
|
8688
9425
|
row,
|
|
8689
|
-
{}
|
|
9426
|
+
{ isPartialUpdate: false }
|
|
9427
|
+
);
|
|
9428
|
+
const rowMeta = extractMetadataFromRow(row);
|
|
9429
|
+
const schemaValidation = validateRecordSchemaConstraints(
|
|
9430
|
+
strapi,
|
|
9431
|
+
uid,
|
|
9432
|
+
null,
|
|
9433
|
+
createPayload,
|
|
9434
|
+
row,
|
|
9435
|
+
{
|
|
9436
|
+
isCreate: true,
|
|
9437
|
+
rowMeta: rowMeta ? {
|
|
9438
|
+
applicableFields: rowMeta.applicableFields,
|
|
9439
|
+
flatTypes: rowMeta.flatTypes
|
|
9440
|
+
} : null
|
|
9441
|
+
}
|
|
8690
9442
|
);
|
|
9443
|
+
if (schemaValidation.errors.length > 0) {
|
|
9444
|
+
const errMsg = schemaValidation.errors[0];
|
|
9445
|
+
stats.skipped++;
|
|
9446
|
+
if (stats.failed !== void 0) stats.failed++;
|
|
9447
|
+
recordFailedCsvRow(
|
|
9448
|
+
stats,
|
|
9449
|
+
rowNumber,
|
|
9450
|
+
row,
|
|
9451
|
+
errMsg,
|
|
9452
|
+
docId || "new",
|
|
9453
|
+
options.originalHeaders
|
|
9454
|
+
);
|
|
9455
|
+
stats.diffs.push({
|
|
9456
|
+
uid,
|
|
9457
|
+
collectionName: ct.info?.displayName || uid,
|
|
9458
|
+
documentId: docId || "new",
|
|
9459
|
+
label: `Row ${rowNumber}`,
|
|
9460
|
+
attribute: "",
|
|
9461
|
+
oldValue: null,
|
|
9462
|
+
newValue: null,
|
|
9463
|
+
status: "error",
|
|
9464
|
+
message: errMsg
|
|
9465
|
+
});
|
|
9466
|
+
return;
|
|
9467
|
+
}
|
|
8691
9468
|
const valResultNew = await validateEntityQuotas(strapi, uid, createPayload);
|
|
8692
9469
|
if (!valResultNew.isValid) {
|
|
8693
9470
|
stats.skipped++;
|
|
@@ -9096,9 +9873,6 @@ const csvService = ({ strapi }) => ({
|
|
|
9096
9873
|
}
|
|
9097
9874
|
const schema = discoverSchema(strapi, uid);
|
|
9098
9875
|
const deepPopulate = buildLosslessPopulate(strapi, uid);
|
|
9099
|
-
const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
|
|
9100
|
-
const lines = [];
|
|
9101
|
-
lines.push(headers.map(escapeCsvCell).join(","));
|
|
9102
9876
|
const filterMeta = buildCollectionQueryFilters(strapi, ct, {
|
|
9103
9877
|
attribute: options.attribute,
|
|
9104
9878
|
searchAttribute: options.searchAttribute || options.attribute,
|
|
@@ -9108,11 +9882,12 @@ const csvService = ({ strapi }) => ({
|
|
|
9108
9882
|
documentIds: options.documentIds
|
|
9109
9883
|
});
|
|
9110
9884
|
if (!filterMeta.colHasAttribute && filterMeta.normOp && filterMeta.normOp !== "none") {
|
|
9885
|
+
const emptySerialized = serializeDocumentsToCsv(strapi, uid, [], { schema });
|
|
9111
9886
|
return {
|
|
9112
9887
|
filename: `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`,
|
|
9113
|
-
csvContent:
|
|
9888
|
+
csvContent: emptySerialized.csvContent,
|
|
9114
9889
|
count: 0,
|
|
9115
|
-
fields: headers
|
|
9890
|
+
fields: emptySerialized.headers
|
|
9116
9891
|
};
|
|
9117
9892
|
}
|
|
9118
9893
|
const filters = filterMeta.filters;
|
|
@@ -9167,7 +9942,7 @@ const csvService = ({ strapi }) => ({
|
|
|
9167
9942
|
};
|
|
9168
9943
|
return matches.some((m) => testSingleValue(m.value));
|
|
9169
9944
|
};
|
|
9170
|
-
|
|
9945
|
+
const exportedDocs = [];
|
|
9171
9946
|
const maxLimit = options.limit && options.limit > 0 ? options.limit : Infinity;
|
|
9172
9947
|
const BATCH_SIZE = 200;
|
|
9173
9948
|
const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -9180,35 +9955,14 @@ const csvService = ({ strapi }) => ({
|
|
|
9180
9955
|
}
|
|
9181
9956
|
const doc = await strapi.documents(uid).findFirst(findFirstArgs);
|
|
9182
9957
|
if (doc && passesDzFilter(doc)) {
|
|
9183
|
-
|
|
9184
|
-
const metadata = {
|
|
9185
|
-
schemaVersion: CURRENT_SCHEMA_VERSION,
|
|
9186
|
-
contentType: uid,
|
|
9187
|
-
documentId: String(doc.documentId || doc.id || ""),
|
|
9188
|
-
locale: doc.locale || void 0,
|
|
9189
|
-
exportedAt
|
|
9190
|
-
};
|
|
9191
|
-
rowValues.push(escapeCsvCell(metadata));
|
|
9192
|
-
for (const key of schema.allExportKeys) {
|
|
9193
|
-
if (key === "documentId") {
|
|
9194
|
-
rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
|
|
9195
|
-
} else if (key === "locale") {
|
|
9196
|
-
rowValues.push(escapeCsvCell(doc.locale || ""));
|
|
9197
|
-
} else {
|
|
9198
|
-
const field = schema.fields[key];
|
|
9199
|
-
const rawVal = doc[key];
|
|
9200
|
-
rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
|
|
9201
|
-
}
|
|
9202
|
-
}
|
|
9203
|
-
lines.push(rowValues.join(","));
|
|
9204
|
-
totalExported = 1;
|
|
9958
|
+
exportedDocs.push(doc);
|
|
9205
9959
|
}
|
|
9206
9960
|
} else {
|
|
9207
9961
|
let currentPage = 1;
|
|
9208
9962
|
let hasMore = true;
|
|
9209
9963
|
const sortClause = ct.attributes?.createdAt ? { createdAt: "desc" } : ct.attributes?.id ? { id: "desc" } : void 0;
|
|
9210
|
-
while (hasMore &&
|
|
9211
|
-
const remaining = maxLimit -
|
|
9964
|
+
while (hasMore && exportedDocs.length < maxLimit) {
|
|
9965
|
+
const remaining = maxLimit - exportedDocs.length;
|
|
9212
9966
|
const currentBatchLimit = Math.min(BATCH_SIZE, remaining);
|
|
9213
9967
|
const findPageArgs = {
|
|
9214
9968
|
filters: Object.keys(filters).length > 0 ? filters : void 0,
|
|
@@ -9230,29 +9984,8 @@ const csvService = ({ strapi }) => ({
|
|
|
9230
9984
|
if (!passesDzFilter(entry)) {
|
|
9231
9985
|
continue;
|
|
9232
9986
|
}
|
|
9233
|
-
|
|
9234
|
-
|
|
9235
|
-
schemaVersion: CURRENT_SCHEMA_VERSION,
|
|
9236
|
-
contentType: uid,
|
|
9237
|
-
documentId: String(entry.documentId || entry.id || ""),
|
|
9238
|
-
locale: entry.locale || void 0,
|
|
9239
|
-
exportedAt
|
|
9240
|
-
};
|
|
9241
|
-
rowValues.push(escapeCsvCell(metadata));
|
|
9242
|
-
for (const key of schema.allExportKeys) {
|
|
9243
|
-
if (key === "documentId") {
|
|
9244
|
-
rowValues.push(escapeCsvCell(entry.documentId || entry.id || ""));
|
|
9245
|
-
} else if (key === "locale") {
|
|
9246
|
-
rowValues.push(escapeCsvCell(entry.locale || ""));
|
|
9247
|
-
} else {
|
|
9248
|
-
const field = schema.fields[key];
|
|
9249
|
-
const rawVal = entry[key];
|
|
9250
|
-
rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
|
|
9251
|
-
}
|
|
9252
|
-
}
|
|
9253
|
-
lines.push(rowValues.join(","));
|
|
9254
|
-
totalExported++;
|
|
9255
|
-
if (totalExported >= maxLimit) {
|
|
9987
|
+
exportedDocs.push(entry);
|
|
9988
|
+
if (exportedDocs.length >= maxLimit) {
|
|
9256
9989
|
hasMore = false;
|
|
9257
9990
|
break;
|
|
9258
9991
|
}
|
|
@@ -9265,13 +9998,13 @@ const csvService = ({ strapi }) => ({
|
|
|
9265
9998
|
await new Promise((resolve) => setImmediate(resolve));
|
|
9266
9999
|
}
|
|
9267
10000
|
}
|
|
9268
|
-
const
|
|
10001
|
+
const serialized = serializeDocumentsToCsv(strapi, uid, exportedDocs, { exportedAt, schema });
|
|
9269
10002
|
const filename = `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
|
|
9270
10003
|
return {
|
|
9271
10004
|
filename,
|
|
9272
|
-
csvContent,
|
|
9273
|
-
count:
|
|
9274
|
-
fields: headers
|
|
10005
|
+
csvContent: serialized.csvContent,
|
|
10006
|
+
count: serialized.count,
|
|
10007
|
+
fields: serialized.headers
|
|
9275
10008
|
};
|
|
9276
10009
|
},
|
|
9277
10010
|
async exportViolationsCsv(ruleId) {
|
|
@@ -9808,18 +10541,51 @@ const csvService = ({ strapi }) => ({
|
|
|
9808
10541
|
}
|
|
9809
10542
|
}
|
|
9810
10543
|
}
|
|
9811
|
-
|
|
9812
|
-
|
|
9813
|
-
|
|
9814
|
-
|
|
9815
|
-
|
|
9816
|
-
|
|
9817
|
-
|
|
9818
|
-
|
|
9819
|
-
|
|
9820
|
-
|
|
9821
|
-
|
|
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
|
+
const isRowCreate = mode === "create_or_override" ? !existing : !existing && mode !== "update";
|
|
10557
|
+
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
|
|
10570
|
+
}
|
|
10571
|
+
);
|
|
10572
|
+
for (const errStr of schemaValidation.errors) {
|
|
10573
|
+
errors2.push({
|
|
10574
|
+
row: rowNumber,
|
|
10575
|
+
documentId: docId || void 0,
|
|
10576
|
+
error: errStr
|
|
10577
|
+
});
|
|
10578
|
+
rowHasError = true;
|
|
10579
|
+
}
|
|
10580
|
+
for (const warnStr of schemaValidation.warnings) {
|
|
10581
|
+
warnings.push({
|
|
10582
|
+
row: rowNumber,
|
|
10583
|
+
documentId: docId || void 0,
|
|
10584
|
+
warning: warnStr
|
|
10585
|
+
});
|
|
9822
10586
|
}
|
|
10587
|
+
}
|
|
10588
|
+
if (activeRules.length > 0) {
|
|
9823
10589
|
const proposedEntity = existing ? deepMergeEntities(existing, proposedPayload) : proposedPayload;
|
|
9824
10590
|
const valResult = await validateEntityQuotas(strapi, uid, proposedEntity, activeRules);
|
|
9825
10591
|
if (!valResult.isValid) {
|
|
@@ -9911,7 +10677,7 @@ const csvService = ({ strapi }) => ({
|
|
|
9911
10677
|
uid,
|
|
9912
10678
|
existing,
|
|
9913
10679
|
row,
|
|
9914
|
-
{}
|
|
10680
|
+
{ isPartialUpdate: mode === "update" }
|
|
9915
10681
|
);
|
|
9916
10682
|
if (existing) {
|
|
9917
10683
|
const resolvedDocId = existing.documentId || docId;
|
|
@@ -9944,7 +10710,7 @@ const csvService = ({ strapi }) => ({
|
|
|
9944
10710
|
}
|
|
9945
10711
|
const oldDisplay = formatValueDisplay(oldVal);
|
|
9946
10712
|
const newDisplay = formatValueDisplay(newVal);
|
|
9947
|
-
const hasChange = String(oldVal ?? "") !== String(newVal ?? "");
|
|
10713
|
+
const hasChange = typeof oldVal === "object" && oldVal !== null || typeof newVal === "object" && newVal !== null ? oldDisplay !== newDisplay : String(oldVal ?? "") !== String(newVal ?? "");
|
|
9948
10714
|
if (hasChange) {
|
|
9949
10715
|
rowHasChanges = true;
|
|
9950
10716
|
}
|
|
@@ -10492,16 +11258,21 @@ const index = {
|
|
|
10492
11258
|
};
|
|
10493
11259
|
export {
|
|
10494
11260
|
CURRENT_SCHEMA_VERSION,
|
|
11261
|
+
EXPLICIT_CLEAR_TOKENS,
|
|
11262
|
+
FORBIDDEN_OBJECT_KEYS,
|
|
10495
11263
|
METADATA_COLUMN_KEY,
|
|
10496
11264
|
SYSTEM_ATTRIBUTES,
|
|
10497
11265
|
applyOccurrenceUpdatesToDocument,
|
|
10498
11266
|
buildCollectionQueryFilters,
|
|
10499
11267
|
buildDocumentUpdatePayload,
|
|
10500
11268
|
buildErrorCsv,
|
|
11269
|
+
buildExportColumnPlan,
|
|
10501
11270
|
buildLosslessPopulate,
|
|
11271
|
+
buildNestedComponentPatchFromDots,
|
|
10502
11272
|
buildRichAttributeMeta,
|
|
10503
11273
|
classifyAttribute,
|
|
10504
11274
|
coerceAndValidateFieldValue,
|
|
11275
|
+
deepCloneValue,
|
|
10505
11276
|
deepMergeEntities,
|
|
10506
11277
|
index as default,
|
|
10507
11278
|
discoverComponentFields,
|
|
@@ -10510,13 +11281,18 @@ export {
|
|
|
10510
11281
|
escapeCsvCell,
|
|
10511
11282
|
extractHeadingsFromRichText,
|
|
10512
11283
|
extractMetadataFromRow,
|
|
11284
|
+
extractRowFlattenedMetadata,
|
|
10513
11285
|
formatErrorCsvFilename,
|
|
10514
11286
|
getAllNestedValues,
|
|
11287
|
+
getValueAtPath,
|
|
11288
|
+
isPlainObject,
|
|
10515
11289
|
isValidDocumentId,
|
|
10516
11290
|
parseBoolean,
|
|
10517
11291
|
parseCsvToMatrix,
|
|
10518
11292
|
parseCsvToRecords,
|
|
11293
|
+
parseFlattenedLeafValue,
|
|
10519
11294
|
parseNumeric,
|
|
11295
|
+
reconstructFlattenedJsonAttribute,
|
|
10520
11296
|
resolveBatchTargets,
|
|
10521
11297
|
resolveComponentPayload,
|
|
10522
11298
|
resolveDynamicZonePayload,
|
|
@@ -10526,8 +11302,12 @@ export {
|
|
|
10526
11302
|
sanitizeUserErrorMessage,
|
|
10527
11303
|
serializeDocumentsToCsv,
|
|
10528
11304
|
serializeFieldValue,
|
|
11305
|
+
serializeFlattenedLeafValue,
|
|
11306
|
+
serializePlannedCell,
|
|
11307
|
+
setValueAtPath,
|
|
10529
11308
|
sortAuditRecordsDesc,
|
|
10530
11309
|
validateEntityQuotas,
|
|
11310
|
+
validateRecordSchemaConstraints,
|
|
10531
11311
|
verifyDocumentIntegrity,
|
|
10532
11312
|
withRollbackLock
|
|
10533
11313
|
};
|