strapi-plugin-bulk-updater 1.7.1 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/_chunks/{BulkUpdater-BrBWtCjS.js → BulkUpdater-BdsfPqoX.js} +56 -18
  2. package/dist/_chunks/BulkUpdater-BdsfPqoX.js.map +1 -0
  3. package/dist/_chunks/{BulkUpdater-BQnhVw0j.mjs → BulkUpdater-KWmfElh6.mjs} +56 -18
  4. package/dist/_chunks/BulkUpdater-KWmfElh6.mjs.map +1 -0
  5. package/dist/_chunks/{SettingsPage-DYD6M988.mjs → SettingsPage-BdwchEyi.mjs} +2 -2
  6. package/dist/_chunks/{SettingsPage-DYD6M988.mjs.map → SettingsPage-BdwchEyi.mjs.map} +1 -1
  7. package/dist/_chunks/{SettingsPage-DsKfbhNd.js → SettingsPage-DqJ_zBde.js} +2 -2
  8. package/dist/_chunks/{SettingsPage-DsKfbhNd.js.map → SettingsPage-DqJ_zBde.js.map} +1 -1
  9. package/dist/_chunks/{ValidationRulesTab-BzS4_gcN.mjs → ValidationRulesTab-DUtycMm1.mjs} +2 -2
  10. package/dist/_chunks/{ValidationRulesTab-BzS4_gcN.mjs.map → ValidationRulesTab-DUtycMm1.mjs.map} +1 -1
  11. package/dist/_chunks/{ValidationRulesTab-DZw6CujQ.js → ValidationRulesTab-DVvVevbW.js} +2 -2
  12. package/dist/_chunks/{ValidationRulesTab-DZw6CujQ.js.map → ValidationRulesTab-DVvVevbW.js.map} +1 -1
  13. package/dist/_chunks/{index-BCOsNd1S.js → index-BZ5NTSJQ.js} +3 -3
  14. package/dist/_chunks/{index-BCOsNd1S.js.map → index-BZ5NTSJQ.js.map} +1 -1
  15. package/dist/_chunks/{index-CjbxZZjb.mjs → index-C9zsPQim.mjs} +3 -3
  16. package/dist/_chunks/{index-CjbxZZjb.mjs.map → index-C9zsPQim.mjs.map} +1 -1
  17. package/dist/admin/index.js +1 -1
  18. package/dist/admin/index.mjs +1 -1
  19. package/dist/server/index.js +425 -71
  20. package/dist/server/index.js.map +1 -1
  21. package/dist/server/index.mjs +425 -71
  22. package/dist/server/index.mjs.map +1 -1
  23. package/package.json +1 -1
  24. package/dist/_chunks/BulkUpdater-BQnhVw0j.mjs.map +0 -1
  25. package/dist/_chunks/BulkUpdater-BrBWtCjS.js.map +0 -1
@@ -1113,7 +1113,8 @@ const auditController = ({ strapi }) => ({
1113
1113
  const { batchId } = ctx.params;
1114
1114
  const service = strapi.plugin("bulk-updater").service("audit");
1115
1115
  const currentUser = ctx.state.user;
1116
- const result = await service.rollbackBatch(batchId, currentUser);
1116
+ const confirmOverwrite = Boolean(ctx.request?.body?.confirmOverwrite);
1117
+ const result = await service.rollbackBatch(batchId, currentUser, { confirmOverwrite });
1117
1118
  ctx.body = result;
1118
1119
  } catch (err) {
1119
1120
  ctx.status = 400;
@@ -1382,7 +1383,7 @@ const csvController = ({ strapi }) => ({
1382
1383
  if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvPreFlightDryRun] }, strapi)) {
1383
1384
  return;
1384
1385
  }
1385
- const { uid, rows, mode } = ctx.request.body;
1386
+ const { uid, rows, mode, originalHeaders } = ctx.request.body;
1386
1387
  if (!uid) {
1387
1388
  ctx.status = 400;
1388
1389
  ctx.body = { success: false, error: "Target collection UID is required." };
@@ -1395,7 +1396,8 @@ const csvController = ({ strapi }) => ({
1395
1396
  }
1396
1397
  const csvService2 = strapi.plugin("bulk-updater").service("csv");
1397
1398
  const result = await csvService2.validatePreflight(uid, rows, {
1398
- mode: mode === "update" ? "update" : mode === "create_or_override" ? "create_or_override" : "auto"
1399
+ mode: mode === "update" ? "update" : mode === "create_or_override" ? "create_or_override" : "auto",
1400
+ originalHeaders: Array.isArray(originalHeaders) ? originalHeaders.map(String) : void 0
1399
1401
  });
1400
1402
  ctx.body = result;
1401
1403
  } catch (err) {
@@ -2560,6 +2562,8 @@ function buildExportColumnPlan(strapi, uid, documents, options = {}) {
2560
2562
  if (exportMode === "selective" && hasSelectedColumns) {
2561
2563
  const columns2 = [];
2562
2564
  const headers = [];
2565
+ const seenSelected = /* @__PURE__ */ new Set();
2566
+ const cleanSelectedColumns = [];
2563
2567
  columns2.push({
2564
2568
  header: "documentId",
2565
2569
  kind: "system",
@@ -2575,50 +2579,61 @@ function buildExportColumnPlan(strapi, uid, documents, options = {}) {
2575
2579
  headers.push("slug");
2576
2580
  for (const rawCol of options.selectedColumns) {
2577
2581
  const colName = String(rawCol).trim();
2578
- if (!colName || colName === "documentId" || colName === "slug" || colName === "__bulk_updater_metadata" || colName === "_bulk_updater_metadata") {
2579
- continue;
2580
- }
2581
- if (headers.includes(colName)) {
2582
+ if (!colName || colName === "documentId" || colName === "slug" || colName === "__bulk_updater_metadata" || colName === "_bulk_updater_metadata" || seenSelected.has(colName)) {
2582
2583
  continue;
2583
2584
  }
2585
+ seenSelected.add(colName);
2586
+ cleanSelectedColumns.push(colName);
2587
+ let baseDescriptor;
2584
2588
  if (colName.includes(".")) {
2585
2589
  const rootKey = colName.split(".")[0];
2586
2590
  const rootField = schema.fields[rootKey];
2587
2591
  const isRepeated = rootField?.category === "component_repeatable" || rootField?.category === "dynamiczone" || rootField?.rawType === "dynamiczone" || Array.isArray(documents) && documents.some((d) => Array.isArray(d?.[rootKey]));
2588
- columns2.push({
2589
- header: colName,
2592
+ baseDescriptor = {
2590
2593
  kind: "selective_nested",
2591
2594
  rootKey,
2592
2595
  isRepeatedNested: Boolean(isRepeated),
2593
2596
  field: rootField
2594
- });
2595
- headers.push(colName);
2597
+ };
2596
2598
  } else {
2597
2599
  const field = schema.fields[colName];
2598
2600
  if (field) {
2599
- columns2.push({
2600
- header: colName,
2601
+ baseDescriptor = {
2601
2602
  kind: "field",
2602
2603
  rootKey: colName,
2603
2604
  field
2604
- });
2605
- headers.push(colName);
2605
+ };
2606
2606
  } else {
2607
- columns2.push({
2608
- header: colName,
2607
+ baseDescriptor = {
2609
2608
  kind: "selective_nested",
2610
2609
  rootKey: colName,
2611
2610
  isRepeatedNested: false
2612
- });
2613
- headers.push(colName);
2611
+ };
2614
2612
  }
2615
2613
  }
2614
+ const beforeHeader = `${colName}_before`;
2615
+ const targetHeader = `${colName}_target`;
2616
+ columns2.push({
2617
+ ...baseDescriptor,
2618
+ header: beforeHeader,
2619
+ role: "before",
2620
+ targetKey: colName
2621
+ });
2622
+ headers.push(beforeHeader);
2623
+ columns2.push({
2624
+ ...baseDescriptor,
2625
+ header: targetHeader,
2626
+ role: "target",
2627
+ targetKey: colName
2628
+ });
2629
+ headers.push(targetHeader);
2616
2630
  }
2617
2631
  return {
2618
2632
  exportMode,
2633
+ columnLayout: "before_target",
2619
2634
  columns: columns2,
2620
2635
  headers,
2621
- selectedColumns: options.selectedColumns
2636
+ selectedColumns: cleanSelectedColumns
2622
2637
  };
2623
2638
  }
2624
2639
  const targetObjectField = resolveTargetObjectField(schema, exportMode);
@@ -2676,6 +2691,9 @@ function extractRowFlattenedMetadata(plan, doc) {
2676
2691
  exportMode: plan.exportMode
2677
2692
  };
2678
2693
  if (plan.exportMode === "selective") {
2694
+ if (plan.columnLayout === "before_target") {
2695
+ out.columnLayout = "before_target";
2696
+ }
2679
2697
  out.selectedColumns = plan.selectedColumns || plan.headers.filter((h) => h !== "documentId" && h !== "slug");
2680
2698
  return out;
2681
2699
  }
@@ -2726,8 +2744,9 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2726
2744
  return doc?.[col.header] ?? "";
2727
2745
  }
2728
2746
  if (col.kind === "selective_nested") {
2747
+ const lookupKey = col.targetKey || col.header;
2729
2748
  if (col.isRepeatedNested) {
2730
- const matches = getAllNestedValues(doc, col.header);
2749
+ const matches = getAllNestedValues(doc, lookupKey);
2731
2750
  if (!matches || matches.length === 0) {
2732
2751
  return "";
2733
2752
  }
@@ -2746,7 +2765,7 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2746
2765
  });
2747
2766
  return JSON.stringify(occurrences);
2748
2767
  } else {
2749
- const val = getDeepProp(doc, col.header);
2768
+ const val = getDeepProp(doc, lookupKey);
2750
2769
  if (val === void 0 || val === null) return "";
2751
2770
  if (val instanceof Date) return val.toISOString();
2752
2771
  if (Array.isArray(val) || isPlainObject(val)) return JSON.stringify(val);
@@ -2837,8 +2856,20 @@ function inspectRowMetadataMode(rawRow) {
2837
2856
  error: `Unsupported CSV exportMode "${parsed.exportMode}" in metadata.`
2838
2857
  };
2839
2858
  }
2859
+ let columnLayout;
2860
+ if (parsed.columnLayout !== void 0) {
2861
+ const rawLayout = String(parsed.columnLayout).trim().toLowerCase();
2862
+ if (rawLayout !== "before_target") {
2863
+ return {
2864
+ mode: rawMode,
2865
+ error: `Unsupported CSV columnLayout "${parsed.columnLayout}" in metadata.`
2866
+ };
2867
+ }
2868
+ columnLayout = "before_target";
2869
+ }
2840
2870
  return {
2841
2871
  mode: rawMode,
2872
+ ...columnLayout ? { columnLayout } : {},
2842
2873
  targetObjectField: typeof parsed.targetObjectField === "string" && parsed.targetObjectField.trim() ? parsed.targetObjectField.trim() : void 0,
2843
2874
  targetObjectState: parsed.targetObjectState,
2844
2875
  applicableFields: Array.isArray(parsed.applicableFields) ? parsed.applicableFields : void 0,
@@ -2864,6 +2895,189 @@ function detectCsvBatchExportMode(rows) {
2864
2895
  const first = Array.from(seenModes)[0];
2865
2896
  return { mode: first || "legacy" };
2866
2897
  }
2898
+ const PRESERVED_SYSTEM_AND_STATUS_KEYS = /* @__PURE__ */ new Set([
2899
+ "__bulk_updater_metadata",
2900
+ "_bulk_updater_metadata",
2901
+ "documentId",
2902
+ "document_id",
2903
+ "Document ID",
2904
+ "Document Id",
2905
+ "docId",
2906
+ "id",
2907
+ "ID",
2908
+ "Id",
2909
+ "slug",
2910
+ "locale",
2911
+ "Locale",
2912
+ "strapi_locale",
2913
+ "status",
2914
+ "Status",
2915
+ "STATUS",
2916
+ "Published Status",
2917
+ "published_status",
2918
+ "strapi_status",
2919
+ "publishedAt",
2920
+ "published_at",
2921
+ "PublishedAt"
2922
+ ]);
2923
+ function findDuplicateCsvHeaders(headers) {
2924
+ if (!Array.isArray(headers) || headers.length === 0) return [];
2925
+ const seen = /* @__PURE__ */ new Set();
2926
+ const duplicates = [];
2927
+ for (const raw of headers) {
2928
+ const trimmed = String(raw || "").trim();
2929
+ if (!trimmed) continue;
2930
+ if (seen.has(trimmed)) {
2931
+ if (!duplicates.includes(trimmed)) {
2932
+ duplicates.push(trimmed);
2933
+ }
2934
+ } else {
2935
+ seen.add(trimmed);
2936
+ }
2937
+ }
2938
+ return duplicates;
2939
+ }
2940
+ function hasCanonicalSchemaTarget(schema, key) {
2941
+ if (!schema || !key) return false;
2942
+ if (schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, key)) {
2943
+ return true;
2944
+ }
2945
+ const bracketIdx = key.indexOf("[");
2946
+ const dotIdx = key.indexOf(".");
2947
+ let rootKey = key;
2948
+ if (bracketIdx > 0 && (dotIdx === -1 || bracketIdx < dotIdx)) {
2949
+ rootKey = key.slice(0, bracketIdx);
2950
+ } else if (dotIdx > 0) {
2951
+ rootKey = key.slice(0, dotIdx);
2952
+ }
2953
+ return Boolean(rootKey && schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, rootKey));
2954
+ }
2955
+ function normalizeSelectiveBeforeTargetRow(rawRow, rowInfo, schema) {
2956
+ if (!rawRow || typeof rawRow !== "object") {
2957
+ return {
2958
+ normalizedRow: rawRow,
2959
+ isBeforeTarget: false,
2960
+ ignoredBeforeColumns: [],
2961
+ mappedTargetFields: [],
2962
+ errors: []
2963
+ };
2964
+ }
2965
+ if (rowInfo.mode === "selective" && rowInfo.columnLayout === "before_target") {
2966
+ const normalizedRow = {};
2967
+ const ignoredBeforeColumns = [];
2968
+ const mappedTargetFields = [];
2969
+ const errors2 = [];
2970
+ const selectedCols = Array.isArray(rowInfo.selectedColumns) ? rowInfo.selectedColumns.map((c) => String(c).trim()).filter(Boolean) : [];
2971
+ const beforeSet = /* @__PURE__ */ new Set();
2972
+ const targetMap = /* @__PURE__ */ new Map();
2973
+ for (const col of selectedCols) {
2974
+ beforeSet.add(`${col}_before`);
2975
+ targetMap.set(`${col}_target`, col);
2976
+ }
2977
+ if (selectedCols.length > 0) {
2978
+ const hasAnyTargetCol = selectedCols.some(
2979
+ (col) => Object.prototype.hasOwnProperty.call(rawRow, `${col}_target`)
2980
+ );
2981
+ const presentBeforeCols = selectedCols.filter(
2982
+ (col) => Object.prototype.hasOwnProperty.call(rawRow, `${col}_before`)
2983
+ );
2984
+ if (!hasAnyTargetCol && presentBeforeCols.length > 0) {
2985
+ const expectedTargets = presentBeforeCols.map((col) => `${col}_target`);
2986
+ errors2.push(
2987
+ `Missing Target column(s) [${expectedTargets.join(", ")}] in Before/Target CSV. Import requires "<field>_target" headers.`
2988
+ );
2989
+ }
2990
+ }
2991
+ for (const [k, v] of Object.entries(rawRow)) {
2992
+ if (PRESERVED_SYSTEM_AND_STATUS_KEYS.has(k)) {
2993
+ normalizedRow[k] = v;
2994
+ continue;
2995
+ }
2996
+ if (beforeSet.size > 0) {
2997
+ if (beforeSet.has(k)) {
2998
+ ignoredBeforeColumns.push(k);
2999
+ continue;
3000
+ }
3001
+ if (targetMap.has(k)) {
3002
+ const canonicalKey = targetMap.get(k);
3003
+ normalizedRow[canonicalKey] = v;
3004
+ mappedTargetFields.push(canonicalKey);
3005
+ }
3006
+ } else {
3007
+ if (k.endsWith("_before")) {
3008
+ ignoredBeforeColumns.push(k);
3009
+ continue;
3010
+ }
3011
+ if (k.endsWith("_target")) {
3012
+ const canonicalKey = k.slice(0, -7);
3013
+ if (canonicalKey) {
3014
+ normalizedRow[canonicalKey] = v;
3015
+ mappedTargetFields.push(canonicalKey);
3016
+ }
3017
+ }
3018
+ }
3019
+ }
3020
+ return {
3021
+ normalizedRow,
3022
+ isBeforeTarget: true,
3023
+ ignoredBeforeColumns,
3024
+ mappedTargetFields,
3025
+ errors: errors2
3026
+ };
3027
+ }
3028
+ if (rowInfo.mode === "legacy" && schema) {
3029
+ const pairedBases = /* @__PURE__ */ new Map();
3030
+ for (const key of Object.keys(rawRow)) {
3031
+ if (PRESERVED_SYSTEM_AND_STATUS_KEYS.has(key) || !key.endsWith("_target")) continue;
3032
+ const base = key.slice(0, -7);
3033
+ if (!base) continue;
3034
+ const beforeKey = `${base}_before`;
3035
+ const isLiteralTargetAttr = Boolean(schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, key));
3036
+ const isLiteralBeforeAttr = Boolean(schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, beforeKey));
3037
+ if (!isLiteralTargetAttr && !isLiteralBeforeAttr && Object.prototype.hasOwnProperty.call(rawRow, beforeKey) && hasCanonicalSchemaTarget(schema, base)) {
3038
+ pairedBases.set(base, { beforeKey, targetKey: key });
3039
+ }
3040
+ }
3041
+ if (pairedBases.size > 0) {
3042
+ const beforeSet = /* @__PURE__ */ new Set();
3043
+ const targetMap = /* @__PURE__ */ new Map();
3044
+ for (const [base, pair] of pairedBases.entries()) {
3045
+ beforeSet.add(pair.beforeKey);
3046
+ targetMap.set(pair.targetKey, base);
3047
+ }
3048
+ const normalizedRow = {};
3049
+ const ignoredBeforeColumns = [];
3050
+ const mappedTargetFields = [];
3051
+ for (const [k, v] of Object.entries(rawRow)) {
3052
+ if (beforeSet.has(k)) {
3053
+ ignoredBeforeColumns.push(k);
3054
+ continue;
3055
+ }
3056
+ if (targetMap.has(k)) {
3057
+ const canonicalKey = targetMap.get(k);
3058
+ normalizedRow[canonicalKey] = v;
3059
+ mappedTargetFields.push(canonicalKey);
3060
+ continue;
3061
+ }
3062
+ normalizedRow[k] = v;
3063
+ }
3064
+ return {
3065
+ normalizedRow,
3066
+ isBeforeTarget: true,
3067
+ ignoredBeforeColumns,
3068
+ mappedTargetFields,
3069
+ errors: []
3070
+ };
3071
+ }
3072
+ }
3073
+ return {
3074
+ normalizedRow: rawRow,
3075
+ isBeforeTarget: false,
3076
+ ignoredBeforeColumns: [],
3077
+ mappedTargetFields: [],
3078
+ errors: []
3079
+ };
3080
+ }
2867
3081
  function parseFirstLevelCellValue(rawCell, annotatedType, existingPropValue) {
2868
3082
  if (rawCell === null || rawCell === void 0) return { value: null };
2869
3083
  if (typeof rawCell !== "string") return { value: rawCell };
@@ -3372,6 +3586,7 @@ function serializeDocumentsToCsv(strapi, uid, documents, options = {}) {
3372
3586
  locale: doc.locale || void 0,
3373
3587
  exportedAt,
3374
3588
  ...flattenedMeta.exportMode ? { exportMode: flattenedMeta.exportMode } : {},
3589
+ ...flattenedMeta.columnLayout ? { columnLayout: flattenedMeta.columnLayout } : {},
3375
3590
  ...flattenedMeta.selectedColumns ? { selectedColumns: flattenedMeta.selectedColumns } : {},
3376
3591
  ...flattenedMeta.targetObjectField ? { targetObjectField: flattenedMeta.targetObjectField } : {},
3377
3592
  ...flattenedMeta.targetObjectState ? { targetObjectState: flattenedMeta.targetObjectState } : {},
@@ -3839,18 +4054,30 @@ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options =
3839
4054
  const warnings = [];
3840
4055
  const isPartialUpdate = options.isPartialUpdate !== false;
3841
4056
  const isCreate = options.isCreate !== void 0 ? options.isCreate : !existingDoc;
3842
- const unescapedRow = {};
4057
+ const rawUnescapedRow = {};
3843
4058
  for (const [k, v] of Object.entries(rawRow || {})) {
3844
4059
  let cleanVal = v;
3845
4060
  if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
3846
4061
  cleanVal = cleanVal.substring(1);
3847
4062
  }
3848
- unescapedRow[k] = cleanVal;
4063
+ rawUnescapedRow[k] = cleanVal;
3849
4064
  }
3850
- const rowInfo = inspectRowMetadataMode(unescapedRow);
4065
+ const rowInfo = inspectRowMetadataMode(rawUnescapedRow);
3851
4066
  if (rowInfo.error) {
3852
4067
  errors2.push(rowInfo.error);
3853
4068
  }
4069
+ const beforeTargetNorm = normalizeSelectiveBeforeTargetRow(rawUnescapedRow, rowInfo, schema);
4070
+ if (beforeTargetNorm.errors.length > 0) {
4071
+ errors2.push(...beforeTargetNorm.errors);
4072
+ return {
4073
+ payload: {},
4074
+ errors: errors2,
4075
+ warnings,
4076
+ detectedMode: rowInfo.mode,
4077
+ rowMeta: rowInfo
4078
+ };
4079
+ }
4080
+ const unescapedRow = beforeTargetNorm.normalizedRow;
3854
4081
  const detectedMode = rowInfo.mode;
3855
4082
  if (options.expectedExportMode && detectedMode !== options.expectedExportMode) {
3856
4083
  errors2.push(
@@ -3980,6 +4207,18 @@ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options =
3980
4207
  }
3981
4208
  } else if (field.category === "json") {
3982
4209
  targetVal = parseFirstLevelCellValue(strCell, "object", currentVal).value;
4210
+ } else if (field.category === "blocks") {
4211
+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
4212
+ try {
4213
+ const parsedBlocks = JSON.parse(trimmed);
4214
+ targetVal = Array.isArray(parsedBlocks) ? parsedBlocks : [parsedBlocks];
4215
+ } catch {
4216
+ errors2.push(`Column "${colKey}": Invalid JSON blocks value.`);
4217
+ continue;
4218
+ }
4219
+ } else {
4220
+ targetVal = [{ type: "paragraph", children: [{ type: "text", text: strCell }] }];
4221
+ }
3983
4222
  } else if (field.category === "relation_to_one") {
3984
4223
  targetVal = resolveRelationPayload(strCell, false);
3985
4224
  } else if (field.category === "relation_to_many") {
@@ -3991,7 +4230,24 @@ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options =
3991
4230
  } else {
3992
4231
  targetVal = strCell;
3993
4232
  }
3994
- if (!deepEqualValues(targetVal, currentVal)) {
4233
+ let hasFieldChanged = true;
4234
+ if (field?.category === "relation_to_one" || field?.category === "relation_to_many") {
4235
+ if (targetVal && typeof targetVal === "object" && Array.isArray(targetVal.set) && !targetVal.connect && !targetVal.disconnect) {
4236
+ const existingDocIds = Array.isArray(currentVal) ? currentVal.map((item) => String(item?.documentId || item?.id || item)).filter(Boolean) : currentVal && typeof currentVal === "object" ? currentVal.documentId || currentVal.id ? [String(currentVal.documentId || currentVal.id)] : [] : currentVal !== null && currentVal !== void 0 && currentVal !== "" ? [String(currentVal)] : [];
4237
+ hasFieldChanged = !deepEqualValues(targetVal.set, existingDocIds);
4238
+ } else {
4239
+ hasFieldChanged = !deepEqualValues(targetVal, currentVal);
4240
+ }
4241
+ } else if (field?.category === "media_single") {
4242
+ const existingMediaId = currentVal && typeof currentVal === "object" ? currentVal.id ?? null : currentVal ?? null;
4243
+ hasFieldChanged = (targetVal ?? null) !== existingMediaId;
4244
+ } else if (field?.category === "media_to_many") {
4245
+ const existingMediaIds = Array.isArray(currentVal) ? currentVal.map((f) => f && typeof f === "object" ? f.id : f).filter((v) => v !== void 0 && v !== null) : [];
4246
+ hasFieldChanged = !deepEqualValues(Array.isArray(targetVal) ? targetVal : [], existingMediaIds);
4247
+ } else {
4248
+ hasFieldChanged = !deepEqualValues(targetVal, currentVal);
4249
+ }
4250
+ if (hasFieldChanged) {
3995
4251
  payload[colKey] = targetVal;
3996
4252
  hasRowChanges = true;
3997
4253
  }
@@ -9343,6 +9599,96 @@ function withRollbackLock(fn) {
9343
9599
  }
9344
9600
  });
9345
9601
  }
9602
+ function getDiffEntryKey(item) {
9603
+ const loc = item?.locale && item.locale !== "null" && item.locale !== "undefined" ? item.locale : "";
9604
+ return `${item.uid}@@@${item.documentId}@@@${loc}`;
9605
+ }
9606
+ function getRevertibleDiffs(diffs) {
9607
+ if (!Array.isArray(diffs)) return [];
9608
+ return diffs.filter(
9609
+ (item) => item?.status === "updated" && item?.uid && item?.documentId && item?.attribute
9610
+ );
9611
+ }
9612
+ function computeRollbackOverlap(sortedHistory, targetIdx) {
9613
+ const empty = {
9614
+ hasOverlap: false,
9615
+ newerActiveBatchIds: [],
9616
+ affectedDocumentIds: [],
9617
+ affectedEntryCount: 0
9618
+ };
9619
+ if (targetIdx <= 0 || targetIdx >= sortedHistory.length) {
9620
+ return empty;
9621
+ }
9622
+ const targetDiffs = getRevertibleDiffs(sortedHistory[targetIdx]?.diffs);
9623
+ if (targetDiffs.length === 0) {
9624
+ return empty;
9625
+ }
9626
+ const targetEntryKeys = new Set(targetDiffs.map(getDiffEntryKey));
9627
+ const newerActiveBatchIds = [];
9628
+ const affectedEntryKeySet = /* @__PURE__ */ new Set();
9629
+ const affectedDocumentIdSet = /* @__PURE__ */ new Set();
9630
+ for (let i = 0; i < targetIdx; i++) {
9631
+ const newer = sortedHistory[i];
9632
+ if (!newer || newer.isRolledBack) continue;
9633
+ const newerDiffs = getRevertibleDiffs(newer.diffs);
9634
+ let batchOverlaps = false;
9635
+ for (const nd of newerDiffs) {
9636
+ const key = getDiffEntryKey(nd);
9637
+ if (targetEntryKeys.has(key)) {
9638
+ batchOverlaps = true;
9639
+ affectedEntryKeySet.add(key);
9640
+ if (nd.documentId) affectedDocumentIdSet.add(String(nd.documentId));
9641
+ }
9642
+ }
9643
+ if (batchOverlaps && newer.batchId) {
9644
+ newerActiveBatchIds.push(String(newer.batchId));
9645
+ }
9646
+ }
9647
+ return {
9648
+ hasOverlap: newerActiveBatchIds.length > 0,
9649
+ newerActiveBatchIds,
9650
+ affectedDocumentIds: Array.from(affectedDocumentIdSet),
9651
+ affectedEntryCount: affectedEntryKeySet.size
9652
+ };
9653
+ }
9654
+ function isBatchRollbackEligible(rec) {
9655
+ if (!rec || rec.isRolledBack) return false;
9656
+ const rawDiffs = Array.isArray(rec.diffs) ? rec.diffs : [];
9657
+ if (rawDiffs.length === 0) return true;
9658
+ return getRevertibleDiffs(rawDiffs).length > 0;
9659
+ }
9660
+ function enrichAuditHistoryWithRollbackMeta(sortedHistory) {
9661
+ const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
9662
+ return sortedHistory.map((rec, idx) => ({
9663
+ ...rec,
9664
+ isLatestEligible: Boolean(
9665
+ latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
9666
+ ),
9667
+ isRollbackEligible: isBatchRollbackEligible(rec),
9668
+ overlapWarning: !rec?.isRolledBack ? computeRollbackOverlap(sortedHistory, idx) : { hasOverlap: false, newerActiveBatchIds: [], affectedDocumentIds: [], affectedEntryCount: 0 }
9669
+ }));
9670
+ }
9671
+ function validateRollbackCandidate(sortedHistory, batchId, confirmOverwrite) {
9672
+ const targetIdx = sortedHistory.findIndex((r) => r.batchId === batchId);
9673
+ if (targetIdx === -1) {
9674
+ throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
9675
+ }
9676
+ const targetRecord = sortedHistory[targetIdx];
9677
+ if (targetRecord.isRolledBack) {
9678
+ throw new Error(`Batch "${batchId}" has already been rolled back.`);
9679
+ }
9680
+ const rawDiffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
9681
+ if (rawDiffs.length > 0 && getRevertibleDiffs(rawDiffs).length === 0) {
9682
+ throw new Error(`Batch "${batchId}" has no revertible updates to roll back.`);
9683
+ }
9684
+ const overlap = computeRollbackOverlap(sortedHistory, targetIdx);
9685
+ if (overlap.hasOverlap && !confirmOverwrite) {
9686
+ throw new Error(
9687
+ `Historical rollback of batch "${batchId}" overlaps newer active batch(es) [${overlap.newerActiveBatchIds.join(", ")}] on ${overlap.affectedEntryCount} entry/entries and will overwrite newer changes/status with pre-batch snapshots. Pass confirmOverwrite=true to proceed.`
9688
+ );
9689
+ }
9690
+ return { targetRecord, overlap };
9691
+ }
9346
9692
  const auditService = ({ strapi }) => ({
9347
9693
  /**
9348
9694
  * Detects whether Strapi Enterprise Native Audit Log service is available.
@@ -9573,13 +9919,7 @@ const auditService = ({ strapi }) => ({
9573
9919
  const stored = await store.get({}) || { history: [] };
9574
9920
  const rawHistory = Array.isArray(stored.history) ? stored.history : [];
9575
9921
  const sortedHistory = sortAuditRecordsDesc(rawHistory);
9576
- const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
9577
- const history = sortedHistory.map((rec) => ({
9578
- ...rec,
9579
- isLatestEligible: Boolean(
9580
- latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
9581
- )
9582
- }));
9922
+ const history = enrichAuditHistoryWithRollbackMeta(sortedHistory);
9583
9923
  return {
9584
9924
  enabled: true,
9585
9925
  mode: "store",
@@ -9625,13 +9965,7 @@ const auditService = ({ strapi }) => ({
9625
9965
  createdAt: r.createdAt
9626
9966
  }));
9627
9967
  const sortedHistory = sortAuditRecordsDesc(normalized);
9628
- const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
9629
- const history = sortedHistory.map((rec) => ({
9630
- ...rec,
9631
- isLatestEligible: Boolean(
9632
- latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
9633
- )
9634
- }));
9968
+ const history = enrichAuditHistoryWithRollbackMeta(sortedHistory);
9635
9969
  return {
9636
9970
  enabled: true,
9637
9971
  mode: config.mode,
@@ -9886,11 +10220,11 @@ const auditService = ({ strapi }) => ({
9886
10220
  });
9887
10221
  },
9888
10222
  /**
9889
- * Performs deterministic rollback of a batch.
9890
- * Strict invariant: ONLY the latest completed update is eligible for rollback.
9891
- * Older completed updates, already rolled-back updates, and pending/failed/executing batches are strictly rejected.
10223
+ * Performs deterministic rollback of an eligible batch (latest or historical).
10224
+ * Already rolled-back updates, non-revertible batches, and pending/failed/executing batches are rejected.
10225
+ * Historical batches overlapping newer active batches on shared entries require `confirmOverwrite: true`.
9892
10226
  */
9893
- async rollbackBatch(batchId, currentUser) {
10227
+ async rollbackBatch(batchId, currentUser, options) {
9894
10228
  return withRollbackLock(async () => {
9895
10229
  const config = this.getAuditConfig();
9896
10230
  if (!config.enabled) {
@@ -9929,17 +10263,11 @@ const auditService = ({ strapi }) => ({
9929
10263
  throw new Error("No completed update records found in audit trail.");
9930
10264
  }
9931
10265
  const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
9932
- const targetRecord2 = sortedHistory2.find((r) => r.batchId === batchId);
9933
- if (!targetRecord2) {
9934
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
9935
- }
9936
- const latestRecord2 = sortedHistory2[0];
9937
- if (latestRecord2.batchId !== batchId) {
9938
- throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
9939
- }
9940
- if (targetRecord2.isRolledBack) {
9941
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
9942
- }
10266
+ const { targetRecord: targetRecord2, overlap: overlap2 } = validateRollbackCandidate(
10267
+ sortedHistory2,
10268
+ batchId,
10269
+ options?.confirmOverwrite
10270
+ );
9943
10271
  const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
9944
10272
  const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
9945
10273
  const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
@@ -9974,6 +10302,7 @@ const auditService = ({ strapi }) => ({
9974
10302
  success: true,
9975
10303
  batchId,
9976
10304
  revertedCount: revertedCount2,
10305
+ overwrittenBatchIds: overlap2.hasOverlap ? overlap2.newerActiveBatchIds : [],
9977
10306
  details: rollbackDetails2
9978
10307
  };
9979
10308
  }
@@ -10006,17 +10335,11 @@ const auditService = ({ strapi }) => ({
10006
10335
  createdAt: r.createdAt
10007
10336
  }));
10008
10337
  const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
10009
- const targetRecord = sortedHistory.find((r) => r.batchId === batchId);
10010
- if (!targetRecord) {
10011
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
10012
- }
10013
- const latestRecord = sortedHistory[0];
10014
- if (latestRecord.batchId !== batchId) {
10015
- throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
10016
- }
10017
- if (targetRecord.isRolledBack) {
10018
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
10019
- }
10338
+ const { targetRecord, overlap } = validateRollbackCandidate(
10339
+ sortedHistory,
10340
+ batchId,
10341
+ options?.confirmOverwrite
10342
+ );
10020
10343
  const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
10021
10344
  const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
10022
10345
  const updateData = {};
@@ -10051,6 +10374,7 @@ const auditService = ({ strapi }) => ({
10051
10374
  success: true,
10052
10375
  batchId,
10053
10376
  revertedCount,
10377
+ overwrittenBatchIds: overlap.hasOverlap ? overlap.newerActiveBatchIds : [],
10054
10378
  details: rollbackDetails
10055
10379
  };
10056
10380
  });
@@ -11061,8 +11385,10 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
11061
11385
  failedRows: [],
11062
11386
  diffs: []
11063
11387
  };
11388
+ const duplicateHeaders = findDuplicateCsvHeaders(originalHeaders);
11064
11389
  const batchModeInfo = detectCsvBatchExportMode(rows);
11065
- if (batchModeInfo.error) {
11390
+ const batchLevelError = duplicateHeaders.length > 0 ? `Duplicate CSV column header(s) detected: [${duplicateHeaders.join(", ")}]. Each column header must be unique.` : batchModeInfo.error;
11391
+ if (batchLevelError) {
11066
11392
  for (let i = 0; i < rows.length; i++) {
11067
11393
  const rowNumber = startRowNumber + i;
11068
11394
  const row = rows[i];
@@ -11073,7 +11399,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
11073
11399
  stats,
11074
11400
  rowNumber,
11075
11401
  row,
11076
- batchModeInfo.error,
11402
+ batchLevelError,
11077
11403
  docId || void 0,
11078
11404
  originalHeaders
11079
11405
  );
@@ -11082,11 +11408,11 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
11082
11408
  collectionName: ct.info?.displayName || uid,
11083
11409
  documentId: docId || `(Row #${rowNumber})`,
11084
11410
  label: `Row #${rowNumber}`,
11085
- attribute: "__bulk_updater_metadata",
11411
+ attribute: duplicateHeaders.length > 0 ? duplicateHeaders[0] : "__bulk_updater_metadata",
11086
11412
  oldValue: null,
11087
11413
  newValue: null,
11088
11414
  status: "error",
11089
- message: batchModeInfo.error
11415
+ message: batchLevelError
11090
11416
  });
11091
11417
  }
11092
11418
  return stats;
@@ -11908,6 +12234,7 @@ const csvService = ({ strapi }) => ({
11908
12234
  }
11909
12235
  const { mode = "auto" } = options;
11910
12236
  const attrs = ct.attributes || {};
12237
+ const schema = discoverSchema(strapi, uid);
11911
12238
  let validationRulesService2 = null;
11912
12239
  let activeRules = [];
11913
12240
  try {
@@ -11932,6 +12259,28 @@ const csvService = ({ strapi }) => ({
11932
12259
  };
11933
12260
  const errors2 = [];
11934
12261
  const warnings = [];
12262
+ const duplicateHeaders = findDuplicateCsvHeaders(options.originalHeaders);
12263
+ if (duplicateHeaders.length > 0) {
12264
+ errors2.push({
12265
+ row: 1,
12266
+ error: `Duplicate CSV column header(s) detected: [${duplicateHeaders.join(", ")}]. Each column header must be unique.`
12267
+ });
12268
+ return {
12269
+ success: true,
12270
+ detectedExportMode: "invalid",
12271
+ totalRows: rows.length,
12272
+ validRows: 0,
12273
+ estimatedUpdates: 0,
12274
+ estimatedCreates: 0,
12275
+ lifecycleStats,
12276
+ hasErrors: true,
12277
+ hasWarnings: false,
12278
+ errors: errors2,
12279
+ warnings: [],
12280
+ totalErrorCount: errors2.length,
12281
+ totalWarningCount: 0
12282
+ };
12283
+ }
11935
12284
  const batchModeInfo = detectCsvBatchExportMode(rows);
11936
12285
  if (batchModeInfo.error) {
11937
12286
  errors2.push({
@@ -12045,7 +12394,10 @@ const csvService = ({ strapi }) => ({
12045
12394
  }
12046
12395
  }
12047
12396
  }
12048
- for (const [colKey, rawVal] of Object.entries(row)) {
12397
+ const rowMetaInfo = inspectRowMetadataMode(row);
12398
+ const beforeTargetNorm = normalizeSelectiveBeforeTargetRow(row, rowMetaInfo, schema);
12399
+ const normalizedScanRow = beforeTargetNorm.normalizedRow;
12400
+ for (const [colKey, rawVal] of Object.entries(normalizedScanRow)) {
12049
12401
  if (!rawVal || rawVal.trim() === "") continue;
12050
12402
  const normalizedKey = colKey.toLowerCase().replace(/[\s_-]/g, "");
12051
12403
  if (SYSTEM_FIELD_KEYS.has(normalizedKey)) continue;
@@ -12951,6 +13303,7 @@ export {
12951
13303
  extractHeadingsFromRichText,
12952
13304
  extractMetadataFromRow,
12953
13305
  extractRowFlattenedMetadata,
13306
+ findDuplicateCsvHeaders,
12954
13307
  formatErrorCsvFilename,
12955
13308
  formatErrorWithCause,
12956
13309
  formatRelationState,
@@ -12965,6 +13318,7 @@ export {
12965
13318
  isValidDocumentId,
12966
13319
  normalizeExportMode,
12967
13320
  normalizeRuleQuotas,
13321
+ normalizeSelectiveBeforeTargetRow,
12968
13322
  parseBoolean,
12969
13323
  parseCsvToMatrix,
12970
13324
  parseCsvToRecords,