strapi-plugin-bulk-updater 1.7.0 → 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 (29) hide show
  1. package/dist/_chunks/{BulkUpdater-Cnzgw4UH.js → BulkUpdater-BdsfPqoX.js} +85 -41
  2. package/dist/_chunks/BulkUpdater-BdsfPqoX.js.map +1 -0
  3. package/dist/_chunks/{BulkUpdater-CV49TvOV.mjs → BulkUpdater-KWmfElh6.mjs} +85 -41
  4. package/dist/_chunks/BulkUpdater-KWmfElh6.mjs.map +1 -0
  5. package/dist/_chunks/{SettingsPage-DXRWLRp_.mjs → SettingsPage-BdwchEyi.mjs} +2 -2
  6. package/dist/_chunks/{SettingsPage-DXRWLRp_.mjs.map → SettingsPage-BdwchEyi.mjs.map} +1 -1
  7. package/dist/_chunks/{SettingsPage-w_Lz-N0V.js → SettingsPage-DqJ_zBde.js} +2 -2
  8. package/dist/_chunks/{SettingsPage-w_Lz-N0V.js.map → SettingsPage-DqJ_zBde.js.map} +1 -1
  9. package/dist/_chunks/{ValidationRulesTab-eN_vH3TB.mjs → ValidationRulesTab-DUtycMm1.mjs} +23 -3
  10. package/dist/_chunks/ValidationRulesTab-DUtycMm1.mjs.map +1 -0
  11. package/dist/_chunks/{ValidationRulesTab-of8bIzre.js → ValidationRulesTab-DVvVevbW.js} +23 -3
  12. package/dist/_chunks/ValidationRulesTab-DVvVevbW.js.map +1 -0
  13. package/dist/_chunks/{index-C2HoRm23.js → index-BZ5NTSJQ.js} +12 -4
  14. package/dist/_chunks/index-BZ5NTSJQ.js.map +1 -0
  15. package/dist/_chunks/{index-2DodYa70.mjs → index-C9zsPQim.mjs} +12 -4
  16. package/dist/_chunks/index-C9zsPQim.mjs.map +1 -0
  17. package/dist/admin/index.js +1 -1
  18. package/dist/admin/index.mjs +1 -1
  19. package/dist/server/index.js +757 -298
  20. package/dist/server/index.js.map +1 -1
  21. package/dist/server/index.mjs +757 -298
  22. package/dist/server/index.mjs.map +1 -1
  23. package/package.json +1 -1
  24. package/dist/_chunks/BulkUpdater-CV49TvOV.mjs.map +0 -1
  25. package/dist/_chunks/BulkUpdater-Cnzgw4UH.js.map +0 -1
  26. package/dist/_chunks/ValidationRulesTab-eN_vH3TB.mjs.map +0 -1
  27. package/dist/_chunks/ValidationRulesTab-of8bIzre.js.map +0 -1
  28. package/dist/_chunks/index-2DodYa70.mjs.map +0 -1
  29. package/dist/_chunks/index-C2HoRm23.js.map +0 -1
@@ -20,6 +20,10 @@ const PERMISSIONS = {
20
20
  // CSV Management
21
21
  csvExport: `plugin::${PLUGIN_ID}.csv.export`,
22
22
  csvImport: `plugin::${PLUGIN_ID}.csv.import`,
23
+ csvSubmitForChecker: `plugin::${PLUGIN_ID}.csv.submit-for-checker`,
24
+ csvForceRunNow: `plugin::${PLUGIN_ID}.csv.force-run-now`,
25
+ csvQueueForOffPeak: `plugin::${PLUGIN_ID}.csv.queue-for-off-peak`,
26
+ csvPreFlightDryRun: `plugin::${PLUGIN_ID}.csv.pre-flight-dry-run`,
23
27
  // Audit Trail
24
28
  auditView: `plugin::${PLUGIN_ID}.audit.view`,
25
29
  auditDetails: `plugin::${PLUGIN_ID}.audit.details`,
@@ -106,6 +110,34 @@ const BULK_UPDATER_PERMISSION_ACTIONS = [
106
110
  pluginName: PLUGIN_ID,
107
111
  subCategory: "CSV Management"
108
112
  },
113
+ {
114
+ section: "plugins",
115
+ displayName: "CSV Submit For Checker",
116
+ uid: "csv.submit-for-checker",
117
+ pluginName: PLUGIN_ID,
118
+ subCategory: "CSV Management"
119
+ },
120
+ {
121
+ section: "plugins",
122
+ displayName: "CSV Force Run Now",
123
+ uid: "csv.force-run-now",
124
+ pluginName: PLUGIN_ID,
125
+ subCategory: "CSV Management"
126
+ },
127
+ {
128
+ section: "plugins",
129
+ displayName: "CSV Queue For Off-Peak",
130
+ uid: "csv.queue-for-off-peak",
131
+ pluginName: PLUGIN_ID,
132
+ subCategory: "CSV Management"
133
+ },
134
+ {
135
+ section: "plugins",
136
+ displayName: "CSV Run Pre-Flight Dry Run",
137
+ uid: "csv.pre-flight-dry-run",
138
+ pluginName: PLUGIN_ID,
139
+ subCategory: "CSV Management"
140
+ },
109
141
  {
110
142
  section: "plugins",
111
143
  displayName: "View Audit History",
@@ -188,7 +220,27 @@ const BATCH_UPDATE_POLICY_CONFIG = {
188
220
  mode: "any",
189
221
  enforceBatchUpdateExecutionMode: true
190
222
  };
191
- function resolveBatchUpdateRequiredPermissions(body) {
223
+ const CSV_SUBMIT_BATCH_POLICY_CONFIG = {
224
+ actions: [
225
+ PERMISSIONS.csvImport,
226
+ PERMISSIONS.csvSubmitForChecker,
227
+ PERMISSIONS.csvForceRunNow,
228
+ PERMISSIONS.csvQueueForOffPeak
229
+ ],
230
+ mode: "any",
231
+ enforceCsvSubmitExecutionMode: true
232
+ };
233
+ const WORKSPACE_MODE_PERMISSIONS = {
234
+ maker_checker: PERMISSIONS.workspaceSubmitForChecker,
235
+ queue_offpeak: PERMISSIONS.workspaceQueueForOffPeak,
236
+ immediate: PERMISSIONS.workspaceForceRunNow
237
+ };
238
+ const CSV_MODE_PERMISSIONS = {
239
+ maker_checker: PERMISSIONS.csvSubmitForChecker,
240
+ queue_offpeak: PERMISSIONS.csvQueueForOffPeak,
241
+ immediate: PERMISSIONS.csvForceRunNow
242
+ };
243
+ function resolveExecutionModeRequiredPermissions(body, modePermissionMap, checkPreviewOrigin) {
192
244
  const rawMode = body?.executionMode;
193
245
  const effectiveMode = rawMode === void 0 ? "immediate" : rawMode;
194
246
  if (typeof effectiveMode !== "string" || !["maker_checker", "queue_offpeak", "immediate"].includes(effectiveMode)) {
@@ -198,20 +250,23 @@ function resolveBatchUpdateRequiredPermissions(body) {
198
250
  reason: `Unsupported or unauthorized execution mode "${String(rawMode)}".`
199
251
  };
200
252
  }
201
- const required = [];
202
- if (effectiveMode === "maker_checker") {
203
- required.push(PERMISSIONS.workspaceSubmitForChecker);
204
- } else if (effectiveMode === "queue_offpeak") {
205
- required.push(PERMISSIONS.workspaceQueueForOffPeak);
206
- } else {
207
- required.push(PERMISSIONS.workspaceForceRunNow);
208
- }
209
- const isPreviewInitiated = body?.initiatedFromPreview === true || body?.initiatedFromPreview === "true" || body?.source === "preview" || body?.executionSource === "preview";
210
- if (isPreviewInitiated) {
211
- required.push(PERMISSIONS.workspaceProceedToExecute);
253
+ const required = [
254
+ modePermissionMap[effectiveMode]
255
+ ];
256
+ if (checkPreviewOrigin) {
257
+ const isPreviewInitiated = body?.initiatedFromPreview === true || body?.initiatedFromPreview === "true" || body?.source === "preview" || body?.executionSource === "preview";
258
+ if (isPreviewInitiated) {
259
+ required.push(PERMISSIONS.workspaceProceedToExecute);
260
+ }
212
261
  }
213
262
  return { valid: true, actions: required };
214
263
  }
264
+ function resolveBatchUpdateRequiredPermissions(body) {
265
+ return resolveExecutionModeRequiredPermissions(body, WORKSPACE_MODE_PERMISSIONS, true);
266
+ }
267
+ function resolveCsvSubmitRequiredPermissions(body) {
268
+ return resolveExecutionModeRequiredPermissions(body, CSV_MODE_PERMISSIONS, false);
269
+ }
215
270
  function setForbiddenResponse(ctx, message = "You do not have permission to perform this action.") {
216
271
  if (ctx) {
217
272
  ctx.status = 403;
@@ -230,6 +285,7 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
230
285
  let actions = [];
231
286
  let mode = "all";
232
287
  let enforceBatchMode = false;
288
+ let enforceCsvMode = false;
233
289
  if (Array.isArray(config)) {
234
290
  actions = config;
235
291
  } else if (config && typeof config === "object") {
@@ -238,6 +294,7 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
238
294
  mode = "any";
239
295
  }
240
296
  enforceBatchMode = Boolean(config.enforceBatchUpdateExecutionMode);
297
+ enforceCsvMode = Boolean(config.enforceCsvSubmitExecutionMode);
241
298
  } else if (typeof config === "string") {
242
299
  actions = [config];
243
300
  }
@@ -250,8 +307,8 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
250
307
  return true;
251
308
  }
252
309
  let batchModeActions = null;
253
- if (enforceBatchMode) {
254
- const resolved = resolveBatchUpdateRequiredPermissions(ctx?.request?.body);
310
+ if (enforceBatchMode || enforceCsvMode) {
311
+ const resolved = enforceCsvMode ? resolveCsvSubmitRequiredPermissions(ctx?.request?.body) : resolveBatchUpdateRequiredPermissions(ctx?.request?.body);
255
312
  if (!resolved.valid) {
256
313
  setForbiddenResponse(ctx, resolved.reason || "You do not have permission to perform this action.");
257
314
  return false;
@@ -289,6 +346,14 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
289
346
  }
290
347
  return true;
291
348
  };
349
+ const CSV_READ_PERMISSIONS = [
350
+ PERMISSIONS.csvExport,
351
+ PERMISSIONS.csvImport,
352
+ PERMISSIONS.csvSubmitForChecker,
353
+ PERMISSIONS.csvForceRunNow,
354
+ PERMISSIONS.csvQueueForOffPeak,
355
+ PERMISSIONS.csvPreFlightDryRun
356
+ ];
292
357
  function requirePermissions(actions, mode = "all") {
293
358
  return [
294
359
  {
@@ -312,8 +377,7 @@ const routes = {
312
377
  policies: requirePermissions(
313
378
  [
314
379
  PERMISSIONS.workspaceView,
315
- PERMISSIONS.csvExport,
316
- PERMISSIONS.csvImport,
380
+ ...CSV_READ_PERMISSIONS,
317
381
  PERMISSIONS.validationView
318
382
  ],
319
383
  "any"
@@ -326,7 +390,7 @@ const routes = {
326
390
  handler: "bulkUpdater.getCollectionEntries",
327
391
  config: {
328
392
  policies: requirePermissions(
329
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
393
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
330
394
  "any"
331
395
  )
332
396
  }
@@ -337,7 +401,7 @@ const routes = {
337
401
  handler: "bulkUpdater.getRelationOptions",
338
402
  config: {
339
403
  policies: requirePermissions(
340
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
404
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
341
405
  "any"
342
406
  )
343
407
  }
@@ -348,7 +412,7 @@ const routes = {
348
412
  handler: "bulkUpdater.getMediaOptions",
349
413
  config: {
350
414
  policies: requirePermissions(
351
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
415
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
352
416
  "any"
353
417
  )
354
418
  }
@@ -435,6 +499,9 @@ const routes = {
435
499
  PERMISSIONS.workspaceView,
436
500
  PERMISSIONS.workspaceExecute,
437
501
  PERMISSIONS.csvImport,
502
+ PERMISSIONS.csvSubmitForChecker,
503
+ PERMISSIONS.csvForceRunNow,
504
+ PERMISSIONS.csvQueueForOffPeak,
438
505
  PERMISSIONS.auditView,
439
506
  PERMISSIONS.approvalView
440
507
  ],
@@ -527,7 +594,7 @@ const routes = {
527
594
  path: "/csv/template/:uid",
528
595
  handler: "csv.getTemplate",
529
596
  config: {
530
- policies: requirePermissions([PERMISSIONS.csvExport, PERMISSIONS.csvImport], "any")
597
+ policies: requirePermissions(CSV_READ_PERMISSIONS, "any")
531
598
  }
532
599
  },
533
600
  {
@@ -567,7 +634,7 @@ const routes = {
567
634
  path: "/csv/import",
568
635
  handler: "csv.importCsv",
569
636
  config: {
570
- policies: requirePermissions(PERMISSIONS.csvImport)
637
+ policies: requirePermissions(PERMISSIONS.csvForceRunNow)
571
638
  }
572
639
  },
573
640
  {
@@ -575,7 +642,7 @@ const routes = {
575
642
  path: "/csv/import-chunk",
576
643
  handler: "csv.importChunk",
577
644
  config: {
578
- policies: requirePermissions(PERMISSIONS.csvImport)
645
+ policies: requirePermissions(PERMISSIONS.csvForceRunNow)
579
646
  }
580
647
  },
581
648
  {
@@ -583,7 +650,7 @@ const routes = {
583
650
  path: "/csv/validate-preflight",
584
651
  handler: "csv.validatePreflight",
585
652
  config: {
586
- policies: requirePermissions(PERMISSIONS.csvImport)
653
+ policies: requirePermissions(PERMISSIONS.csvPreFlightDryRun)
587
654
  }
588
655
  },
589
656
  {
@@ -591,7 +658,12 @@ const routes = {
591
658
  path: "/csv/submit-batch",
592
659
  handler: "csv.submitBatch",
593
660
  config: {
594
- policies: requirePermissions(PERMISSIONS.csvImport)
661
+ policies: [
662
+ {
663
+ name: "plugin::bulk-updater.hasPermissions",
664
+ config: CSV_SUBMIT_BATCH_POLICY_CONFIG
665
+ }
666
+ ]
595
667
  }
596
668
  }
597
669
  ]
@@ -672,7 +744,15 @@ const contentTypes = {
672
744
  schema: auditLog
673
745
  }
674
746
  };
747
+ const { AsyncLocalStorage } = require("async_hooks");
675
748
  const CRASH_GUARD_SYMBOL = Symbol.for("strapi-plugin-bulk-updater.undiciCrashGuardInstalled");
749
+ const rollbackContextStorage = new AsyncLocalStorage();
750
+ function runInRollbackContext(fn) {
751
+ return rollbackContextStorage.run(true, fn);
752
+ }
753
+ function isRollbackContext() {
754
+ return rollbackContextStorage.getStore() === true;
755
+ }
676
756
  let activeBulkOperations = 0;
677
757
  function getActiveBulkOperationCount() {
678
758
  return activeBulkOperations;
@@ -1037,7 +1117,8 @@ const auditController = ({ strapi }) => ({
1037
1117
  const { batchId } = ctx.params;
1038
1118
  const service = strapi.plugin("bulk-updater").service("audit");
1039
1119
  const currentUser = ctx.state.user;
1040
- const result = await service.rollbackBatch(batchId, currentUser);
1120
+ const confirmOverwrite = Boolean(ctx.request?.body?.confirmOverwrite);
1121
+ const result = await service.rollbackBatch(batchId, currentUser, { confirmOverwrite });
1041
1122
  ctx.body = result;
1042
1123
  } catch (err) {
1043
1124
  ctx.status = 400;
@@ -1119,6 +1200,13 @@ const validationRulesController = ({ strapi }) => ({
1119
1200
  }
1120
1201
  }
1121
1202
  });
1203
+ function ensureCsvAuthorized(ctx, policyConfig, strapi) {
1204
+ const hasAuthContext = Boolean(
1205
+ ctx?.state?.userAbility || Array.isArray(ctx?.state?.permissions) || Array.isArray(ctx?.state?.user?.permissions) || ctx?.state?.user?.isSuperAdmin !== void 0
1206
+ );
1207
+ if (!hasAuthContext) return true;
1208
+ return hasPermissionsPolicy(ctx, policyConfig, { strapi });
1209
+ }
1122
1210
  const csvController = ({ strapi }) => ({
1123
1211
  async getTemplate(ctx) {
1124
1212
  try {
@@ -1227,6 +1315,9 @@ const csvController = ({ strapi }) => ({
1227
1315
  },
1228
1316
  async importCsv(ctx) {
1229
1317
  try {
1318
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
1319
+ return;
1320
+ }
1230
1321
  const { uid, csvText, mode, publish, publishStrategy, unreviewedConsent } = ctx.request.body;
1231
1322
  if (!uid) {
1232
1323
  ctx.status = 400;
@@ -1256,6 +1347,9 @@ const csvController = ({ strapi }) => ({
1256
1347
  },
1257
1348
  async importChunk(ctx) {
1258
1349
  try {
1350
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
1351
+ return;
1352
+ }
1259
1353
  const { uid, rows, batchId, isFirstChunk, isLastChunk, startRowNumber, mode, publish, publishStrategy, unreviewedConsent, originalHeaders } = ctx.request.body;
1260
1354
  if (!uid) {
1261
1355
  ctx.status = 400;
@@ -1290,7 +1384,10 @@ const csvController = ({ strapi }) => ({
1290
1384
  },
1291
1385
  async validatePreflight(ctx) {
1292
1386
  try {
1293
- const { uid, rows, mode } = ctx.request.body;
1387
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvPreFlightDryRun] }, strapi)) {
1388
+ return;
1389
+ }
1390
+ const { uid, rows, mode, originalHeaders } = ctx.request.body;
1294
1391
  if (!uid) {
1295
1392
  ctx.status = 400;
1296
1393
  ctx.body = { success: false, error: "Target collection UID is required." };
@@ -1303,7 +1400,8 @@ const csvController = ({ strapi }) => ({
1303
1400
  }
1304
1401
  const csvService2 = strapi.plugin("bulk-updater").service("csv");
1305
1402
  const result = await csvService2.validatePreflight(uid, rows, {
1306
- mode: mode === "update" ? "update" : mode === "create_or_override" ? "create_or_override" : "auto"
1403
+ mode: mode === "update" ? "update" : mode === "create_or_override" ? "create_or_override" : "auto",
1404
+ originalHeaders: Array.isArray(originalHeaders) ? originalHeaders.map(String) : void 0
1307
1405
  });
1308
1406
  ctx.body = result;
1309
1407
  } catch (err) {
@@ -1313,6 +1411,9 @@ const csvController = ({ strapi }) => ({
1313
1411
  },
1314
1412
  async submitBatch(ctx) {
1315
1413
  try {
1414
+ if (!ensureCsvAuthorized(ctx, CSV_SUBMIT_BATCH_POLICY_CONFIG, strapi)) {
1415
+ return;
1416
+ }
1316
1417
  const { uid, rows, executionMode, makerNotes, forceImmediate, mode, publish, publishStrategy, unreviewedConsent, unreviewedCount } = ctx.request.body;
1317
1418
  if (!uid) {
1318
1419
  ctx.status = 400;
@@ -2465,6 +2566,8 @@ function buildExportColumnPlan(strapi, uid, documents, options = {}) {
2465
2566
  if (exportMode === "selective" && hasSelectedColumns) {
2466
2567
  const columns2 = [];
2467
2568
  const headers = [];
2569
+ const seenSelected = /* @__PURE__ */ new Set();
2570
+ const cleanSelectedColumns = [];
2468
2571
  columns2.push({
2469
2572
  header: "documentId",
2470
2573
  kind: "system",
@@ -2480,50 +2583,61 @@ function buildExportColumnPlan(strapi, uid, documents, options = {}) {
2480
2583
  headers.push("slug");
2481
2584
  for (const rawCol of options.selectedColumns) {
2482
2585
  const colName = String(rawCol).trim();
2483
- if (!colName || colName === "documentId" || colName === "slug" || colName === "__bulk_updater_metadata" || colName === "_bulk_updater_metadata") {
2484
- continue;
2485
- }
2486
- if (headers.includes(colName)) {
2586
+ if (!colName || colName === "documentId" || colName === "slug" || colName === "__bulk_updater_metadata" || colName === "_bulk_updater_metadata" || seenSelected.has(colName)) {
2487
2587
  continue;
2488
2588
  }
2589
+ seenSelected.add(colName);
2590
+ cleanSelectedColumns.push(colName);
2591
+ let baseDescriptor;
2489
2592
  if (colName.includes(".")) {
2490
2593
  const rootKey = colName.split(".")[0];
2491
2594
  const rootField = schema.fields[rootKey];
2492
2595
  const isRepeated = rootField?.category === "component_repeatable" || rootField?.category === "dynamiczone" || rootField?.rawType === "dynamiczone" || Array.isArray(documents) && documents.some((d) => Array.isArray(d?.[rootKey]));
2493
- columns2.push({
2494
- header: colName,
2596
+ baseDescriptor = {
2495
2597
  kind: "selective_nested",
2496
2598
  rootKey,
2497
2599
  isRepeatedNested: Boolean(isRepeated),
2498
2600
  field: rootField
2499
- });
2500
- headers.push(colName);
2601
+ };
2501
2602
  } else {
2502
2603
  const field = schema.fields[colName];
2503
2604
  if (field) {
2504
- columns2.push({
2505
- header: colName,
2605
+ baseDescriptor = {
2506
2606
  kind: "field",
2507
2607
  rootKey: colName,
2508
2608
  field
2509
- });
2510
- headers.push(colName);
2609
+ };
2511
2610
  } else {
2512
- columns2.push({
2513
- header: colName,
2611
+ baseDescriptor = {
2514
2612
  kind: "selective_nested",
2515
2613
  rootKey: colName,
2516
2614
  isRepeatedNested: false
2517
- });
2518
- headers.push(colName);
2615
+ };
2519
2616
  }
2520
2617
  }
2618
+ const beforeHeader = `${colName}_before`;
2619
+ const targetHeader = `${colName}_target`;
2620
+ columns2.push({
2621
+ ...baseDescriptor,
2622
+ header: beforeHeader,
2623
+ role: "before",
2624
+ targetKey: colName
2625
+ });
2626
+ headers.push(beforeHeader);
2627
+ columns2.push({
2628
+ ...baseDescriptor,
2629
+ header: targetHeader,
2630
+ role: "target",
2631
+ targetKey: colName
2632
+ });
2633
+ headers.push(targetHeader);
2521
2634
  }
2522
2635
  return {
2523
2636
  exportMode,
2637
+ columnLayout: "before_target",
2524
2638
  columns: columns2,
2525
2639
  headers,
2526
- selectedColumns: options.selectedColumns
2640
+ selectedColumns: cleanSelectedColumns
2527
2641
  };
2528
2642
  }
2529
2643
  const targetObjectField = resolveTargetObjectField(schema, exportMode);
@@ -2581,6 +2695,9 @@ function extractRowFlattenedMetadata(plan, doc) {
2581
2695
  exportMode: plan.exportMode
2582
2696
  };
2583
2697
  if (plan.exportMode === "selective") {
2698
+ if (plan.columnLayout === "before_target") {
2699
+ out.columnLayout = "before_target";
2700
+ }
2584
2701
  out.selectedColumns = plan.selectedColumns || plan.headers.filter((h) => h !== "documentId" && h !== "slug");
2585
2702
  return out;
2586
2703
  }
@@ -2631,8 +2748,9 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2631
2748
  return doc?.[col.header] ?? "";
2632
2749
  }
2633
2750
  if (col.kind === "selective_nested") {
2751
+ const lookupKey = col.targetKey || col.header;
2634
2752
  if (col.isRepeatedNested) {
2635
- const matches = getAllNestedValues(doc, col.header);
2753
+ const matches = getAllNestedValues(doc, lookupKey);
2636
2754
  if (!matches || matches.length === 0) {
2637
2755
  return "";
2638
2756
  }
@@ -2651,7 +2769,7 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2651
2769
  });
2652
2770
  return JSON.stringify(occurrences);
2653
2771
  } else {
2654
- const val = getDeepProp(doc, col.header);
2772
+ const val = getDeepProp(doc, lookupKey);
2655
2773
  if (val === void 0 || val === null) return "";
2656
2774
  if (val instanceof Date) return val.toISOString();
2657
2775
  if (Array.isArray(val) || isPlainObject(val)) return JSON.stringify(val);
@@ -2742,8 +2860,20 @@ function inspectRowMetadataMode(rawRow) {
2742
2860
  error: `Unsupported CSV exportMode "${parsed.exportMode}" in metadata.`
2743
2861
  };
2744
2862
  }
2863
+ let columnLayout;
2864
+ if (parsed.columnLayout !== void 0) {
2865
+ const rawLayout = String(parsed.columnLayout).trim().toLowerCase();
2866
+ if (rawLayout !== "before_target") {
2867
+ return {
2868
+ mode: rawMode,
2869
+ error: `Unsupported CSV columnLayout "${parsed.columnLayout}" in metadata.`
2870
+ };
2871
+ }
2872
+ columnLayout = "before_target";
2873
+ }
2745
2874
  return {
2746
2875
  mode: rawMode,
2876
+ ...columnLayout ? { columnLayout } : {},
2747
2877
  targetObjectField: typeof parsed.targetObjectField === "string" && parsed.targetObjectField.trim() ? parsed.targetObjectField.trim() : void 0,
2748
2878
  targetObjectState: parsed.targetObjectState,
2749
2879
  applicableFields: Array.isArray(parsed.applicableFields) ? parsed.applicableFields : void 0,
@@ -2769,6 +2899,189 @@ function detectCsvBatchExportMode(rows) {
2769
2899
  const first = Array.from(seenModes)[0];
2770
2900
  return { mode: first || "legacy" };
2771
2901
  }
2902
+ const PRESERVED_SYSTEM_AND_STATUS_KEYS = /* @__PURE__ */ new Set([
2903
+ "__bulk_updater_metadata",
2904
+ "_bulk_updater_metadata",
2905
+ "documentId",
2906
+ "document_id",
2907
+ "Document ID",
2908
+ "Document Id",
2909
+ "docId",
2910
+ "id",
2911
+ "ID",
2912
+ "Id",
2913
+ "slug",
2914
+ "locale",
2915
+ "Locale",
2916
+ "strapi_locale",
2917
+ "status",
2918
+ "Status",
2919
+ "STATUS",
2920
+ "Published Status",
2921
+ "published_status",
2922
+ "strapi_status",
2923
+ "publishedAt",
2924
+ "published_at",
2925
+ "PublishedAt"
2926
+ ]);
2927
+ function findDuplicateCsvHeaders(headers) {
2928
+ if (!Array.isArray(headers) || headers.length === 0) return [];
2929
+ const seen = /* @__PURE__ */ new Set();
2930
+ const duplicates = [];
2931
+ for (const raw of headers) {
2932
+ const trimmed = String(raw || "").trim();
2933
+ if (!trimmed) continue;
2934
+ if (seen.has(trimmed)) {
2935
+ if (!duplicates.includes(trimmed)) {
2936
+ duplicates.push(trimmed);
2937
+ }
2938
+ } else {
2939
+ seen.add(trimmed);
2940
+ }
2941
+ }
2942
+ return duplicates;
2943
+ }
2944
+ function hasCanonicalSchemaTarget(schema, key) {
2945
+ if (!schema || !key) return false;
2946
+ if (schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, key)) {
2947
+ return true;
2948
+ }
2949
+ const bracketIdx = key.indexOf("[");
2950
+ const dotIdx = key.indexOf(".");
2951
+ let rootKey = key;
2952
+ if (bracketIdx > 0 && (dotIdx === -1 || bracketIdx < dotIdx)) {
2953
+ rootKey = key.slice(0, bracketIdx);
2954
+ } else if (dotIdx > 0) {
2955
+ rootKey = key.slice(0, dotIdx);
2956
+ }
2957
+ return Boolean(rootKey && schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, rootKey));
2958
+ }
2959
+ function normalizeSelectiveBeforeTargetRow(rawRow, rowInfo, schema) {
2960
+ if (!rawRow || typeof rawRow !== "object") {
2961
+ return {
2962
+ normalizedRow: rawRow,
2963
+ isBeforeTarget: false,
2964
+ ignoredBeforeColumns: [],
2965
+ mappedTargetFields: [],
2966
+ errors: []
2967
+ };
2968
+ }
2969
+ if (rowInfo.mode === "selective" && rowInfo.columnLayout === "before_target") {
2970
+ const normalizedRow = {};
2971
+ const ignoredBeforeColumns = [];
2972
+ const mappedTargetFields = [];
2973
+ const errors = [];
2974
+ const selectedCols = Array.isArray(rowInfo.selectedColumns) ? rowInfo.selectedColumns.map((c) => String(c).trim()).filter(Boolean) : [];
2975
+ const beforeSet = /* @__PURE__ */ new Set();
2976
+ const targetMap = /* @__PURE__ */ new Map();
2977
+ for (const col of selectedCols) {
2978
+ beforeSet.add(`${col}_before`);
2979
+ targetMap.set(`${col}_target`, col);
2980
+ }
2981
+ if (selectedCols.length > 0) {
2982
+ const hasAnyTargetCol = selectedCols.some(
2983
+ (col) => Object.prototype.hasOwnProperty.call(rawRow, `${col}_target`)
2984
+ );
2985
+ const presentBeforeCols = selectedCols.filter(
2986
+ (col) => Object.prototype.hasOwnProperty.call(rawRow, `${col}_before`)
2987
+ );
2988
+ if (!hasAnyTargetCol && presentBeforeCols.length > 0) {
2989
+ const expectedTargets = presentBeforeCols.map((col) => `${col}_target`);
2990
+ errors.push(
2991
+ `Missing Target column(s) [${expectedTargets.join(", ")}] in Before/Target CSV. Import requires "<field>_target" headers.`
2992
+ );
2993
+ }
2994
+ }
2995
+ for (const [k, v] of Object.entries(rawRow)) {
2996
+ if (PRESERVED_SYSTEM_AND_STATUS_KEYS.has(k)) {
2997
+ normalizedRow[k] = v;
2998
+ continue;
2999
+ }
3000
+ if (beforeSet.size > 0) {
3001
+ if (beforeSet.has(k)) {
3002
+ ignoredBeforeColumns.push(k);
3003
+ continue;
3004
+ }
3005
+ if (targetMap.has(k)) {
3006
+ const canonicalKey = targetMap.get(k);
3007
+ normalizedRow[canonicalKey] = v;
3008
+ mappedTargetFields.push(canonicalKey);
3009
+ }
3010
+ } else {
3011
+ if (k.endsWith("_before")) {
3012
+ ignoredBeforeColumns.push(k);
3013
+ continue;
3014
+ }
3015
+ if (k.endsWith("_target")) {
3016
+ const canonicalKey = k.slice(0, -7);
3017
+ if (canonicalKey) {
3018
+ normalizedRow[canonicalKey] = v;
3019
+ mappedTargetFields.push(canonicalKey);
3020
+ }
3021
+ }
3022
+ }
3023
+ }
3024
+ return {
3025
+ normalizedRow,
3026
+ isBeforeTarget: true,
3027
+ ignoredBeforeColumns,
3028
+ mappedTargetFields,
3029
+ errors
3030
+ };
3031
+ }
3032
+ if (rowInfo.mode === "legacy" && schema) {
3033
+ const pairedBases = /* @__PURE__ */ new Map();
3034
+ for (const key of Object.keys(rawRow)) {
3035
+ if (PRESERVED_SYSTEM_AND_STATUS_KEYS.has(key) || !key.endsWith("_target")) continue;
3036
+ const base = key.slice(0, -7);
3037
+ if (!base) continue;
3038
+ const beforeKey = `${base}_before`;
3039
+ const isLiteralTargetAttr = Boolean(schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, key));
3040
+ const isLiteralBeforeAttr = Boolean(schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, beforeKey));
3041
+ if (!isLiteralTargetAttr && !isLiteralBeforeAttr && Object.prototype.hasOwnProperty.call(rawRow, beforeKey) && hasCanonicalSchemaTarget(schema, base)) {
3042
+ pairedBases.set(base, { beforeKey, targetKey: key });
3043
+ }
3044
+ }
3045
+ if (pairedBases.size > 0) {
3046
+ const beforeSet = /* @__PURE__ */ new Set();
3047
+ const targetMap = /* @__PURE__ */ new Map();
3048
+ for (const [base, pair] of pairedBases.entries()) {
3049
+ beforeSet.add(pair.beforeKey);
3050
+ targetMap.set(pair.targetKey, base);
3051
+ }
3052
+ const normalizedRow = {};
3053
+ const ignoredBeforeColumns = [];
3054
+ const mappedTargetFields = [];
3055
+ for (const [k, v] of Object.entries(rawRow)) {
3056
+ if (beforeSet.has(k)) {
3057
+ ignoredBeforeColumns.push(k);
3058
+ continue;
3059
+ }
3060
+ if (targetMap.has(k)) {
3061
+ const canonicalKey = targetMap.get(k);
3062
+ normalizedRow[canonicalKey] = v;
3063
+ mappedTargetFields.push(canonicalKey);
3064
+ continue;
3065
+ }
3066
+ normalizedRow[k] = v;
3067
+ }
3068
+ return {
3069
+ normalizedRow,
3070
+ isBeforeTarget: true,
3071
+ ignoredBeforeColumns,
3072
+ mappedTargetFields,
3073
+ errors: []
3074
+ };
3075
+ }
3076
+ }
3077
+ return {
3078
+ normalizedRow: rawRow,
3079
+ isBeforeTarget: false,
3080
+ ignoredBeforeColumns: [],
3081
+ mappedTargetFields: [],
3082
+ errors: []
3083
+ };
3084
+ }
2772
3085
  function parseFirstLevelCellValue(rawCell, annotatedType, existingPropValue) {
2773
3086
  if (rawCell === null || rawCell === void 0) return { value: null };
2774
3087
  if (typeof rawCell !== "string") return { value: rawCell };
@@ -3277,6 +3590,7 @@ function serializeDocumentsToCsv(strapi, uid, documents, options = {}) {
3277
3590
  locale: doc.locale || void 0,
3278
3591
  exportedAt,
3279
3592
  ...flattenedMeta.exportMode ? { exportMode: flattenedMeta.exportMode } : {},
3593
+ ...flattenedMeta.columnLayout ? { columnLayout: flattenedMeta.columnLayout } : {},
3280
3594
  ...flattenedMeta.selectedColumns ? { selectedColumns: flattenedMeta.selectedColumns } : {},
3281
3595
  ...flattenedMeta.targetObjectField ? { targetObjectField: flattenedMeta.targetObjectField } : {},
3282
3596
  ...flattenedMeta.targetObjectState ? { targetObjectState: flattenedMeta.targetObjectState } : {},
@@ -3744,18 +4058,30 @@ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options =
3744
4058
  const warnings = [];
3745
4059
  const isPartialUpdate = options.isPartialUpdate !== false;
3746
4060
  const isCreate = options.isCreate !== void 0 ? options.isCreate : !existingDoc;
3747
- const unescapedRow = {};
4061
+ const rawUnescapedRow = {};
3748
4062
  for (const [k, v] of Object.entries(rawRow || {})) {
3749
4063
  let cleanVal = v;
3750
4064
  if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
3751
4065
  cleanVal = cleanVal.substring(1);
3752
4066
  }
3753
- unescapedRow[k] = cleanVal;
4067
+ rawUnescapedRow[k] = cleanVal;
3754
4068
  }
3755
- const rowInfo = inspectRowMetadataMode(unescapedRow);
4069
+ const rowInfo = inspectRowMetadataMode(rawUnescapedRow);
3756
4070
  if (rowInfo.error) {
3757
4071
  errors.push(rowInfo.error);
3758
4072
  }
4073
+ const beforeTargetNorm = normalizeSelectiveBeforeTargetRow(rawUnescapedRow, rowInfo, schema);
4074
+ if (beforeTargetNorm.errors.length > 0) {
4075
+ errors.push(...beforeTargetNorm.errors);
4076
+ return {
4077
+ payload: {},
4078
+ errors,
4079
+ warnings,
4080
+ detectedMode: rowInfo.mode,
4081
+ rowMeta: rowInfo
4082
+ };
4083
+ }
4084
+ const unescapedRow = beforeTargetNorm.normalizedRow;
3759
4085
  const detectedMode = rowInfo.mode;
3760
4086
  if (options.expectedExportMode && detectedMode !== options.expectedExportMode) {
3761
4087
  errors.push(
@@ -3885,6 +4211,18 @@ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options =
3885
4211
  }
3886
4212
  } else if (field.category === "json") {
3887
4213
  targetVal = parseFirstLevelCellValue(strCell, "object", currentVal).value;
4214
+ } else if (field.category === "blocks") {
4215
+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
4216
+ try {
4217
+ const parsedBlocks = JSON.parse(trimmed);
4218
+ targetVal = Array.isArray(parsedBlocks) ? parsedBlocks : [parsedBlocks];
4219
+ } catch {
4220
+ errors.push(`Column "${colKey}": Invalid JSON blocks value.`);
4221
+ continue;
4222
+ }
4223
+ } else {
4224
+ targetVal = [{ type: "paragraph", children: [{ type: "text", text: strCell }] }];
4225
+ }
3888
4226
  } else if (field.category === "relation_to_one") {
3889
4227
  targetVal = resolveRelationPayload(strCell, false);
3890
4228
  } else if (field.category === "relation_to_many") {
@@ -3896,7 +4234,24 @@ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options =
3896
4234
  } else {
3897
4235
  targetVal = strCell;
3898
4236
  }
3899
- if (!deepEqualValues(targetVal, currentVal)) {
4237
+ let hasFieldChanged = true;
4238
+ if (field?.category === "relation_to_one" || field?.category === "relation_to_many") {
4239
+ if (targetVal && typeof targetVal === "object" && Array.isArray(targetVal.set) && !targetVal.connect && !targetVal.disconnect) {
4240
+ 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)] : [];
4241
+ hasFieldChanged = !deepEqualValues(targetVal.set, existingDocIds);
4242
+ } else {
4243
+ hasFieldChanged = !deepEqualValues(targetVal, currentVal);
4244
+ }
4245
+ } else if (field?.category === "media_single") {
4246
+ const existingMediaId = currentVal && typeof currentVal === "object" ? currentVal.id ?? null : currentVal ?? null;
4247
+ hasFieldChanged = (targetVal ?? null) !== existingMediaId;
4248
+ } else if (field?.category === "media_to_many") {
4249
+ const existingMediaIds = Array.isArray(currentVal) ? currentVal.map((f) => f && typeof f === "object" ? f.id : f).filter((v) => v !== void 0 && v !== null) : [];
4250
+ hasFieldChanged = !deepEqualValues(Array.isArray(targetVal) ? targetVal : [], existingMediaIds);
4251
+ } else {
4252
+ hasFieldChanged = !deepEqualValues(targetVal, currentVal);
4253
+ }
4254
+ if (hasFieldChanged) {
3900
4255
  payload[colKey] = targetVal;
3901
4256
  hasRowChanges = true;
3902
4257
  }
@@ -9248,6 +9603,96 @@ function withRollbackLock(fn) {
9248
9603
  }
9249
9604
  });
9250
9605
  }
9606
+ function getDiffEntryKey(item) {
9607
+ const loc = item?.locale && item.locale !== "null" && item.locale !== "undefined" ? item.locale : "";
9608
+ return `${item.uid}@@@${item.documentId}@@@${loc}`;
9609
+ }
9610
+ function getRevertibleDiffs(diffs) {
9611
+ if (!Array.isArray(diffs)) return [];
9612
+ return diffs.filter(
9613
+ (item) => item?.status === "updated" && item?.uid && item?.documentId && item?.attribute
9614
+ );
9615
+ }
9616
+ function computeRollbackOverlap(sortedHistory, targetIdx) {
9617
+ const empty = {
9618
+ hasOverlap: false,
9619
+ newerActiveBatchIds: [],
9620
+ affectedDocumentIds: [],
9621
+ affectedEntryCount: 0
9622
+ };
9623
+ if (targetIdx <= 0 || targetIdx >= sortedHistory.length) {
9624
+ return empty;
9625
+ }
9626
+ const targetDiffs = getRevertibleDiffs(sortedHistory[targetIdx]?.diffs);
9627
+ if (targetDiffs.length === 0) {
9628
+ return empty;
9629
+ }
9630
+ const targetEntryKeys = new Set(targetDiffs.map(getDiffEntryKey));
9631
+ const newerActiveBatchIds = [];
9632
+ const affectedEntryKeySet = /* @__PURE__ */ new Set();
9633
+ const affectedDocumentIdSet = /* @__PURE__ */ new Set();
9634
+ for (let i = 0; i < targetIdx; i++) {
9635
+ const newer = sortedHistory[i];
9636
+ if (!newer || newer.isRolledBack) continue;
9637
+ const newerDiffs = getRevertibleDiffs(newer.diffs);
9638
+ let batchOverlaps = false;
9639
+ for (const nd of newerDiffs) {
9640
+ const key = getDiffEntryKey(nd);
9641
+ if (targetEntryKeys.has(key)) {
9642
+ batchOverlaps = true;
9643
+ affectedEntryKeySet.add(key);
9644
+ if (nd.documentId) affectedDocumentIdSet.add(String(nd.documentId));
9645
+ }
9646
+ }
9647
+ if (batchOverlaps && newer.batchId) {
9648
+ newerActiveBatchIds.push(String(newer.batchId));
9649
+ }
9650
+ }
9651
+ return {
9652
+ hasOverlap: newerActiveBatchIds.length > 0,
9653
+ newerActiveBatchIds,
9654
+ affectedDocumentIds: Array.from(affectedDocumentIdSet),
9655
+ affectedEntryCount: affectedEntryKeySet.size
9656
+ };
9657
+ }
9658
+ function isBatchRollbackEligible(rec) {
9659
+ if (!rec || rec.isRolledBack) return false;
9660
+ const rawDiffs = Array.isArray(rec.diffs) ? rec.diffs : [];
9661
+ if (rawDiffs.length === 0) return true;
9662
+ return getRevertibleDiffs(rawDiffs).length > 0;
9663
+ }
9664
+ function enrichAuditHistoryWithRollbackMeta(sortedHistory) {
9665
+ const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
9666
+ return sortedHistory.map((rec, idx) => ({
9667
+ ...rec,
9668
+ isLatestEligible: Boolean(
9669
+ latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
9670
+ ),
9671
+ isRollbackEligible: isBatchRollbackEligible(rec),
9672
+ overlapWarning: !rec?.isRolledBack ? computeRollbackOverlap(sortedHistory, idx) : { hasOverlap: false, newerActiveBatchIds: [], affectedDocumentIds: [], affectedEntryCount: 0 }
9673
+ }));
9674
+ }
9675
+ function validateRollbackCandidate(sortedHistory, batchId, confirmOverwrite) {
9676
+ const targetIdx = sortedHistory.findIndex((r) => r.batchId === batchId);
9677
+ if (targetIdx === -1) {
9678
+ throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
9679
+ }
9680
+ const targetRecord = sortedHistory[targetIdx];
9681
+ if (targetRecord.isRolledBack) {
9682
+ throw new Error(`Batch "${batchId}" has already been rolled back.`);
9683
+ }
9684
+ const rawDiffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
9685
+ if (rawDiffs.length > 0 && getRevertibleDiffs(rawDiffs).length === 0) {
9686
+ throw new Error(`Batch "${batchId}" has no revertible updates to roll back.`);
9687
+ }
9688
+ const overlap = computeRollbackOverlap(sortedHistory, targetIdx);
9689
+ if (overlap.hasOverlap && !confirmOverwrite) {
9690
+ throw new Error(
9691
+ `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.`
9692
+ );
9693
+ }
9694
+ return { targetRecord, overlap };
9695
+ }
9251
9696
  const auditService = ({ strapi }) => ({
9252
9697
  /**
9253
9698
  * Detects whether Strapi Enterprise Native Audit Log service is available.
@@ -9478,13 +9923,7 @@ const auditService = ({ strapi }) => ({
9478
9923
  const stored = await store.get({}) || { history: [] };
9479
9924
  const rawHistory = Array.isArray(stored.history) ? stored.history : [];
9480
9925
  const sortedHistory = sortAuditRecordsDesc(rawHistory);
9481
- const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
9482
- const history = sortedHistory.map((rec) => ({
9483
- ...rec,
9484
- isLatestEligible: Boolean(
9485
- latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
9486
- )
9487
- }));
9926
+ const history = enrichAuditHistoryWithRollbackMeta(sortedHistory);
9488
9927
  return {
9489
9928
  enabled: true,
9490
9929
  mode: "store",
@@ -9530,13 +9969,7 @@ const auditService = ({ strapi }) => ({
9530
9969
  createdAt: r.createdAt
9531
9970
  }));
9532
9971
  const sortedHistory = sortAuditRecordsDesc(normalized);
9533
- const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
9534
- const history = sortedHistory.map((rec) => ({
9535
- ...rec,
9536
- isLatestEligible: Boolean(
9537
- latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
9538
- )
9539
- }));
9972
+ const history = enrichAuditHistoryWithRollbackMeta(sortedHistory);
9540
9973
  return {
9541
9974
  enabled: true,
9542
9975
  mode: config.mode,
@@ -9556,243 +9989,246 @@ const auditService = ({ strapi }) => ({
9556
9989
  * Helper to revert diff items back to original values
9557
9990
  */
9558
9991
  async revertDiffItems(diffs, userId) {
9559
- let revertedCount = 0;
9560
- const rollbackDetails = [];
9561
- for (const item of diffs) {
9562
- if (item.status === "updated" && item.uid && item.documentId && item.attribute) {
9563
- try {
9564
- const ct = strapi.contentTypes[item.uid];
9565
- if (!ct) {
9566
- throw new Error(`Content type "${item.uid}" does not exist in schema.`);
9567
- }
9568
- const isRel = item.oldValue && typeof item.oldValue === "object" && item.oldValue.isRelation;
9569
- let rollbackPayload;
9570
- if (isRel) {
9571
- const oldDocIds = Array.isArray(item.oldValue.documentIds) ? item.oldValue.documentIds : [];
9572
- rollbackPayload = { set: oldDocIds };
9573
- } else {
9574
- rollbackPayload = item.oldValue ?? null;
9575
- }
9576
- const parsed = parseDynamicZonePath(item.attribute);
9577
- const rootKey = parsed.rootKey;
9578
- const rootAttrDef = ct.attributes?.[rootKey];
9579
- const isComponent = rootAttrDef?.type === "component";
9580
- const isDynamicZone = rootAttrDef?.type === "dynamiczone";
9581
- const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
9582
- const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
9583
- const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
9584
- const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
9585
- const findOneArgs = { documentId: item.documentId };
9586
- if (populateOption) {
9587
- findOneArgs.populate = populateOption;
9588
- }
9589
- if (isLocalized) {
9590
- findOneArgs.locale = item.locale;
9591
- }
9592
- const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
9593
- if (!currentDoc) {
9594
- throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
9595
- }
9596
- if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
9597
- const isRootDz = isDynamicZone;
9598
- const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
9599
- let restoredRoot;
9600
- if (Array.isArray(item.dynamicZoneDiffs) && item.dynamicZoneDiffs.length > 0) {
9601
- const hasStructuredSegments = item.dynamicZoneDiffs.some(
9602
- (dz) => Array.isArray(dz?.segments) && dz.segments.length > 0
9603
- );
9604
- if (hasStructuredSegments) {
9605
- const occUpdates = item.dynamicZoneDiffs.map((dzDiff) => {
9606
- const isRelDiff = dzDiff.oldValue && typeof dzDiff.oldValue === "object" && dzDiff.oldValue.isRelation;
9607
- const val = isRelDiff ? { mode: "set", documentIds: Array.isArray(dzDiff.oldValue.documentIds) ? dzDiff.oldValue.documentIds : [] } : dzDiff.oldValue ?? null;
9608
- return {
9609
- occurrenceKey: dzDiff.occurrenceKey,
9610
- segments: dzDiff.segments,
9611
- dynamicZoneIndex: dzDiff.index,
9612
- componentId: dzDiff.componentId,
9613
- componentUid: dzDiff.componentUid,
9614
- value: val
9615
- };
9616
- });
9617
- const reverted = await applyOccurrenceUpdatesToDocument({
9618
- strapi,
9619
- contentType: ct,
9620
- allComponents: strapi.components,
9621
- currentDoc,
9622
- attribute: item.attribute,
9623
- updates: occUpdates
9624
- });
9625
- if (reverted.errors.length > 0) {
9626
- throw new Error(reverted.errors.join("; "));
9627
- }
9628
- restoredRoot = reverted.updateData[rootKey];
9629
- } else {
9630
- let workingRoot = existingRoot;
9631
- for (const dzDiff of item.dynamicZoneDiffs) {
9632
- const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
9633
- const dzParts = parsedDz.cleanPath.split(".").slice(1);
9634
- const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
9635
- workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
9636
- targetIndexes,
9637
- targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
9638
- strapi
9992
+ return runInRollbackContext(async () => {
9993
+ const revertedEntryKeys = /* @__PURE__ */ new Set();
9994
+ const rollbackDetails = [];
9995
+ for (const item of diffs) {
9996
+ if (item.status === "updated" && item.uid && item.documentId && item.attribute) {
9997
+ try {
9998
+ const ct = strapi.contentTypes[item.uid];
9999
+ if (!ct) {
10000
+ throw new Error(`Content type "${item.uid}" does not exist in schema.`);
10001
+ }
10002
+ const isRel = item.oldValue && typeof item.oldValue === "object" && item.oldValue.isRelation;
10003
+ let rollbackPayload;
10004
+ if (isRel) {
10005
+ const oldDocIds = Array.isArray(item.oldValue.documentIds) ? item.oldValue.documentIds : [];
10006
+ rollbackPayload = { set: oldDocIds };
10007
+ } else {
10008
+ rollbackPayload = item.oldValue ?? null;
10009
+ }
10010
+ const parsed = parseDynamicZonePath(item.attribute);
10011
+ const rootKey = parsed.rootKey;
10012
+ const rootAttrDef = ct.attributes?.[rootKey];
10013
+ const isComponent = rootAttrDef?.type === "component";
10014
+ const isDynamicZone = rootAttrDef?.type === "dynamiczone";
10015
+ const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
10016
+ const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
10017
+ const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
10018
+ const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
10019
+ const findOneArgs = { documentId: item.documentId };
10020
+ if (populateOption) {
10021
+ findOneArgs.populate = populateOption;
10022
+ }
10023
+ if (isLocalized) {
10024
+ findOneArgs.locale = item.locale;
10025
+ }
10026
+ const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
10027
+ if (!currentDoc) {
10028
+ throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
10029
+ }
10030
+ if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
10031
+ const isRootDz = isDynamicZone;
10032
+ const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
10033
+ let restoredRoot;
10034
+ if (Array.isArray(item.dynamicZoneDiffs) && item.dynamicZoneDiffs.length > 0) {
10035
+ const hasStructuredSegments = item.dynamicZoneDiffs.some(
10036
+ (dz) => Array.isArray(dz?.segments) && dz.segments.length > 0
10037
+ );
10038
+ if (hasStructuredSegments) {
10039
+ const occUpdates = item.dynamicZoneDiffs.map((dzDiff) => {
10040
+ const isRelDiff = dzDiff.oldValue && typeof dzDiff.oldValue === "object" && dzDiff.oldValue.isRelation;
10041
+ const val = isRelDiff ? { mode: "set", documentIds: Array.isArray(dzDiff.oldValue.documentIds) ? dzDiff.oldValue.documentIds : [] } : dzDiff.oldValue ?? null;
10042
+ return {
10043
+ occurrenceKey: dzDiff.occurrenceKey,
10044
+ segments: dzDiff.segments,
10045
+ dynamicZoneIndex: dzDiff.index,
10046
+ componentId: dzDiff.componentId,
10047
+ componentUid: dzDiff.componentUid,
10048
+ value: val
10049
+ };
10050
+ });
10051
+ const reverted = await applyOccurrenceUpdatesToDocument({
10052
+ strapi,
10053
+ contentType: ct,
10054
+ allComponents: strapi.components,
10055
+ currentDoc,
10056
+ attribute: item.attribute,
10057
+ updates: occUpdates
9639
10058
  });
10059
+ if (reverted.errors.length > 0) {
10060
+ throw new Error(reverted.errors.join("; "));
10061
+ }
10062
+ restoredRoot = reverted.updateData[rootKey];
10063
+ } else {
10064
+ let workingRoot = existingRoot;
10065
+ for (const dzDiff of item.dynamicZoneDiffs) {
10066
+ const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
10067
+ const dzParts = parsedDz.cleanPath.split(".").slice(1);
10068
+ const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
10069
+ workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
10070
+ targetIndexes,
10071
+ targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
10072
+ strapi
10073
+ });
10074
+ }
10075
+ restoredRoot = workingRoot;
9640
10076
  }
9641
- restoredRoot = workingRoot;
10077
+ } else {
10078
+ const parts = parsed.cleanPath.split(".");
10079
+ const pathParts = parts.slice(1);
10080
+ const targetIndexes = parsed.targetIndex !== void 0 ? [parsed.targetIndex] : void 0;
10081
+ const targetComponentUid = parsed.targetComponentUid;
10082
+ restoredRoot = setDeepProperty(existingRoot, pathParts, rollbackPayload, {
10083
+ targetIndexes,
10084
+ targetComponentUid,
10085
+ strapi
10086
+ });
9642
10087
  }
9643
- } else {
9644
- const parts = parsed.cleanPath.split(".");
9645
- const pathParts = parts.slice(1);
9646
- const targetIndexes = parsed.targetIndex !== void 0 ? [parsed.targetIndex] : void 0;
9647
- const targetComponentUid = parsed.targetComponentUid;
9648
- restoredRoot = setDeepProperty(existingRoot, pathParts, rollbackPayload, {
9649
- targetIndexes,
9650
- targetComponentUid,
9651
- strapi
10088
+ await strapi.documents(item.uid).update({
10089
+ documentId: item.documentId,
10090
+ ...isLocalized ? { locale: item.locale } : {},
10091
+ data: {
10092
+ [rootKey]: restoredRoot
10093
+ }
9652
10094
  });
9653
- }
9654
- await strapi.documents(item.uid).update({
9655
- documentId: item.documentId,
9656
- ...isLocalized ? { locale: item.locale } : {},
9657
- data: {
9658
- [rootKey]: restoredRoot
9659
- }
9660
- });
9661
- } else {
9662
- await strapi.documents(item.uid).update({
9663
- documentId: item.documentId,
9664
- ...isLocalized ? { locale: item.locale } : {},
9665
- data: {
9666
- [item.attribute]: rollbackPayload
9667
- }
9668
- });
9669
- }
9670
- let targetStatus = void 0;
9671
- if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
9672
- targetStatus = item.previousStatus;
9673
- } else if (item.hadPublishedVersion === false) {
9674
- targetStatus = "draft";
9675
- } else if (item.hadPublishedVersion === true) {
9676
- targetStatus = "published";
9677
- }
9678
- if (isDraftAndPublish && !targetStatus) {
9679
- let publishedCounterpart = null;
9680
- try {
9681
- const docSvc = strapi.documents(item.uid);
9682
- if (typeof docSvc.findMany === "function") {
9683
- const pubs = await docSvc.findMany({
9684
- status: "published",
9685
- filters: { documentId: item.documentId },
9686
- fields: ["documentId", "publishedAt"],
9687
- limit: 1,
9688
- ...isLocalized ? { locale: item.locale } : {}
9689
- });
9690
- if (pubs && pubs.length > 0) {
9691
- publishedCounterpart = pubs[0];
10095
+ } else {
10096
+ await strapi.documents(item.uid).update({
10097
+ documentId: item.documentId,
10098
+ ...isLocalized ? { locale: item.locale } : {},
10099
+ data: {
10100
+ [item.attribute]: rollbackPayload
9692
10101
  }
9693
- }
9694
- } catch {
10102
+ });
9695
10103
  }
9696
- if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
9697
- targetStatus = "published";
9698
- } else {
10104
+ let targetStatus = void 0;
10105
+ if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
10106
+ targetStatus = item.previousStatus;
10107
+ } else if (item.hadPublishedVersion === false) {
9699
10108
  targetStatus = "draft";
10109
+ } else if (item.hadPublishedVersion === true) {
10110
+ targetStatus = "published";
9700
10111
  }
9701
- }
9702
- if (isDraftAndPublish) {
9703
- const docSvc = strapi.documents(item.uid);
9704
- if (targetStatus === "published") {
10112
+ if (isDraftAndPublish && !targetStatus) {
10113
+ let publishedCounterpart = null;
9705
10114
  try {
9706
- if (typeof docSvc.publish === "function") {
9707
- await docSvc.publish({
9708
- documentId: item.documentId,
10115
+ const docSvc = strapi.documents(item.uid);
10116
+ if (typeof docSvc.findMany === "function") {
10117
+ const pubs = await docSvc.findMany({
10118
+ status: "published",
10119
+ filters: { documentId: item.documentId },
10120
+ fields: ["documentId", "publishedAt"],
10121
+ limit: 1,
9709
10122
  ...isLocalized ? { locale: item.locale } : {}
9710
10123
  });
10124
+ if (pubs && pubs.length > 0) {
10125
+ publishedCounterpart = pubs[0];
10126
+ }
9711
10127
  }
9712
- } catch (publishErr) {
9713
- strapi.log.warn(
9714
- `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
9715
- publishErr?.message
9716
- );
10128
+ } catch {
9717
10129
  }
9718
- } else if (targetStatus === "draft") {
9719
- try {
9720
- if (typeof docSvc.unpublish === "function") {
9721
- let hasPublished = false;
9722
- if (typeof docSvc.findMany === "function") {
9723
- const pubs = await docSvc.findMany({
9724
- status: "published",
9725
- filters: { documentId: item.documentId },
9726
- fields: ["documentId", "publishedAt"],
9727
- limit: 1,
10130
+ if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
10131
+ targetStatus = "published";
10132
+ } else {
10133
+ targetStatus = "draft";
10134
+ }
10135
+ }
10136
+ if (isDraftAndPublish) {
10137
+ const docSvc = strapi.documents(item.uid);
10138
+ if (targetStatus === "published") {
10139
+ try {
10140
+ if (typeof docSvc.publish === "function") {
10141
+ await docSvc.publish({
10142
+ documentId: item.documentId,
9728
10143
  ...isLocalized ? { locale: item.locale } : {}
9729
10144
  });
9730
- if (pubs && pubs.length > 0) {
10145
+ }
10146
+ } catch (publishErr) {
10147
+ strapi.log.warn(
10148
+ `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
10149
+ publishErr?.message
10150
+ );
10151
+ }
10152
+ } else if (targetStatus === "draft") {
10153
+ try {
10154
+ if (typeof docSvc.unpublish === "function") {
10155
+ let hasPublished = false;
10156
+ if (typeof docSvc.findMany === "function") {
10157
+ const pubs = await docSvc.findMany({
10158
+ status: "published",
10159
+ filters: { documentId: item.documentId },
10160
+ fields: ["documentId", "publishedAt"],
10161
+ limit: 1,
10162
+ ...isLocalized ? { locale: item.locale } : {}
10163
+ });
10164
+ if (pubs && pubs.length > 0) {
10165
+ hasPublished = true;
10166
+ }
10167
+ } else if (currentDoc?.publishedAt) {
9731
10168
  hasPublished = true;
9732
10169
  }
9733
- } else if (currentDoc?.publishedAt) {
9734
- hasPublished = true;
9735
- }
9736
- if (hasPublished) {
9737
- await docSvc.unpublish({
9738
- documentId: item.documentId,
9739
- ...isLocalized ? { locale: item.locale } : {}
9740
- });
10170
+ if (hasPublished) {
10171
+ await docSvc.unpublish({
10172
+ documentId: item.documentId,
10173
+ ...isLocalized ? { locale: item.locale } : {}
10174
+ });
10175
+ }
9741
10176
  }
10177
+ } catch (unpubErr) {
10178
+ strapi.log.warn(
10179
+ `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
10180
+ unpubErr?.message
10181
+ );
9742
10182
  }
9743
- } catch (unpubErr) {
9744
- strapi.log.warn(
9745
- `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
9746
- unpubErr?.message
9747
- );
9748
10183
  }
9749
10184
  }
9750
- }
9751
- try {
9752
- await recordContentHistoryVersion(strapi, {
10185
+ try {
10186
+ await recordContentHistoryVersion(strapi, {
10187
+ uid: item.uid,
10188
+ documentId: item.documentId,
10189
+ userId,
10190
+ statusOverride: isDraftAndPublish ? targetStatus : "published"
10191
+ });
10192
+ } catch {
10193
+ }
10194
+ try {
10195
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
10196
+ if (bulkService?.invalidateCache) {
10197
+ bulkService.invalidateCache(item.uid);
10198
+ }
10199
+ } catch {
10200
+ }
10201
+ const entryKey = `${item.uid}@@@${item.documentId}@@@${isLocalized ? item.locale : ""}`;
10202
+ revertedEntryKeys.add(entryKey);
10203
+ rollbackDetails.push({
9753
10204
  uid: item.uid,
9754
10205
  documentId: item.documentId,
9755
- userId,
9756
- statusOverride: isDraftAndPublish ? targetStatus : "published"
10206
+ label: item.label,
10207
+ attribute: item.attribute,
10208
+ revertedTo: item.oldValue,
10209
+ status: "reverted",
10210
+ restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
10211
+ });
10212
+ } catch (err) {
10213
+ rollbackDetails.push({
10214
+ uid: item.uid,
10215
+ documentId: item.documentId,
10216
+ label: item.label,
10217
+ status: "error",
10218
+ message: err.message
9757
10219
  });
9758
- } catch {
9759
- }
9760
- try {
9761
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
9762
- if (bulkService?.invalidateCache) {
9763
- bulkService.invalidateCache(item.uid);
9764
- }
9765
- } catch {
9766
10220
  }
9767
- revertedCount++;
9768
- rollbackDetails.push({
9769
- uid: item.uid,
9770
- documentId: item.documentId,
9771
- label: item.label,
9772
- attribute: item.attribute,
9773
- revertedTo: item.oldValue,
9774
- status: "reverted",
9775
- restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
9776
- });
9777
- } catch (err) {
9778
- rollbackDetails.push({
9779
- uid: item.uid,
9780
- documentId: item.documentId,
9781
- label: item.label,
9782
- status: "error",
9783
- message: err.message
9784
- });
9785
10221
  }
9786
10222
  }
9787
- }
9788
- return { revertedCount, rollbackDetails };
10223
+ return { revertedCount: revertedEntryKeys.size, rollbackDetails };
10224
+ });
9789
10225
  },
9790
10226
  /**
9791
- * Performs deterministic rollback of a batch.
9792
- * Strict invariant: ONLY the latest completed update is eligible for rollback.
9793
- * Older completed updates, already rolled-back updates, and pending/failed/executing batches are strictly rejected.
10227
+ * Performs deterministic rollback of an eligible batch (latest or historical).
10228
+ * Already rolled-back updates, non-revertible batches, and pending/failed/executing batches are rejected.
10229
+ * Historical batches overlapping newer active batches on shared entries require `confirmOverwrite: true`.
9794
10230
  */
9795
- async rollbackBatch(batchId, currentUser) {
10231
+ async rollbackBatch(batchId, currentUser, options) {
9796
10232
  return withRollbackLock(async () => {
9797
10233
  const config = this.getAuditConfig();
9798
10234
  if (!config.enabled) {
@@ -9831,17 +10267,11 @@ const auditService = ({ strapi }) => ({
9831
10267
  throw new Error("No completed update records found in audit trail.");
9832
10268
  }
9833
10269
  const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
9834
- const targetRecord2 = sortedHistory2.find((r) => r.batchId === batchId);
9835
- if (!targetRecord2) {
9836
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
9837
- }
9838
- const latestRecord2 = sortedHistory2[0];
9839
- if (latestRecord2.batchId !== batchId) {
9840
- throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
9841
- }
9842
- if (targetRecord2.isRolledBack) {
9843
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
9844
- }
10270
+ const { targetRecord: targetRecord2, overlap: overlap2 } = validateRollbackCandidate(
10271
+ sortedHistory2,
10272
+ batchId,
10273
+ options?.confirmOverwrite
10274
+ );
9845
10275
  const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
9846
10276
  const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
9847
10277
  const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
@@ -9876,6 +10306,7 @@ const auditService = ({ strapi }) => ({
9876
10306
  success: true,
9877
10307
  batchId,
9878
10308
  revertedCount: revertedCount2,
10309
+ overwrittenBatchIds: overlap2.hasOverlap ? overlap2.newerActiveBatchIds : [],
9879
10310
  details: rollbackDetails2
9880
10311
  };
9881
10312
  }
@@ -9908,17 +10339,11 @@ const auditService = ({ strapi }) => ({
9908
10339
  createdAt: r.createdAt
9909
10340
  }));
9910
10341
  const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
9911
- const targetRecord = sortedHistory.find((r) => r.batchId === batchId);
9912
- if (!targetRecord) {
9913
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
9914
- }
9915
- const latestRecord = sortedHistory[0];
9916
- if (latestRecord.batchId !== batchId) {
9917
- throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
9918
- }
9919
- if (targetRecord.isRolledBack) {
9920
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
9921
- }
10342
+ const { targetRecord, overlap } = validateRollbackCandidate(
10343
+ sortedHistory,
10344
+ batchId,
10345
+ options?.confirmOverwrite
10346
+ );
9922
10347
  const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
9923
10348
  const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
9924
10349
  const updateData = {};
@@ -9953,6 +10378,7 @@ const auditService = ({ strapi }) => ({
9953
10378
  success: true,
9954
10379
  batchId,
9955
10380
  revertedCount,
10381
+ overwrittenBatchIds: overlap.hasOverlap ? overlap.newerActiveBatchIds : [],
9956
10382
  details: rollbackDetails
9957
10383
  };
9958
10384
  });
@@ -10963,8 +11389,10 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
10963
11389
  failedRows: [],
10964
11390
  diffs: []
10965
11391
  };
11392
+ const duplicateHeaders = findDuplicateCsvHeaders(originalHeaders);
10966
11393
  const batchModeInfo = detectCsvBatchExportMode(rows);
10967
- if (batchModeInfo.error) {
11394
+ const batchLevelError = duplicateHeaders.length > 0 ? `Duplicate CSV column header(s) detected: [${duplicateHeaders.join(", ")}]. Each column header must be unique.` : batchModeInfo.error;
11395
+ if (batchLevelError) {
10968
11396
  for (let i = 0; i < rows.length; i++) {
10969
11397
  const rowNumber = startRowNumber + i;
10970
11398
  const row = rows[i];
@@ -10975,7 +11403,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
10975
11403
  stats,
10976
11404
  rowNumber,
10977
11405
  row,
10978
- batchModeInfo.error,
11406
+ batchLevelError,
10979
11407
  docId || void 0,
10980
11408
  originalHeaders
10981
11409
  );
@@ -10984,11 +11412,11 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
10984
11412
  collectionName: ct.info?.displayName || uid,
10985
11413
  documentId: docId || `(Row #${rowNumber})`,
10986
11414
  label: `Row #${rowNumber}`,
10987
- attribute: "__bulk_updater_metadata",
11415
+ attribute: duplicateHeaders.length > 0 ? duplicateHeaders[0] : "__bulk_updater_metadata",
10988
11416
  oldValue: null,
10989
11417
  newValue: null,
10990
11418
  status: "error",
10991
- message: batchModeInfo.error
11419
+ message: batchLevelError
10992
11420
  });
10993
11421
  }
10994
11422
  return stats;
@@ -11810,6 +12238,7 @@ const csvService = ({ strapi }) => ({
11810
12238
  }
11811
12239
  const { mode = "auto" } = options;
11812
12240
  const attrs = ct.attributes || {};
12241
+ const schema = discoverSchema(strapi, uid);
11813
12242
  let validationRulesService2 = null;
11814
12243
  let activeRules = [];
11815
12244
  try {
@@ -11834,6 +12263,28 @@ const csvService = ({ strapi }) => ({
11834
12263
  };
11835
12264
  const errors = [];
11836
12265
  const warnings = [];
12266
+ const duplicateHeaders = findDuplicateCsvHeaders(options.originalHeaders);
12267
+ if (duplicateHeaders.length > 0) {
12268
+ errors.push({
12269
+ row: 1,
12270
+ error: `Duplicate CSV column header(s) detected: [${duplicateHeaders.join(", ")}]. Each column header must be unique.`
12271
+ });
12272
+ return {
12273
+ success: true,
12274
+ detectedExportMode: "invalid",
12275
+ totalRows: rows.length,
12276
+ validRows: 0,
12277
+ estimatedUpdates: 0,
12278
+ estimatedCreates: 0,
12279
+ lifecycleStats,
12280
+ hasErrors: true,
12281
+ hasWarnings: false,
12282
+ errors,
12283
+ warnings: [],
12284
+ totalErrorCount: errors.length,
12285
+ totalWarningCount: 0
12286
+ };
12287
+ }
11837
12288
  const batchModeInfo = detectCsvBatchExportMode(rows);
11838
12289
  if (batchModeInfo.error) {
11839
12290
  errors.push({
@@ -11947,7 +12398,10 @@ const csvService = ({ strapi }) => ({
11947
12398
  }
11948
12399
  }
11949
12400
  }
11950
- for (const [colKey, rawVal] of Object.entries(row)) {
12401
+ const rowMetaInfo = inspectRowMetadataMode(row);
12402
+ const beforeTargetNorm = normalizeSelectiveBeforeTargetRow(row, rowMetaInfo, schema);
12403
+ const normalizedScanRow = beforeTargetNorm.normalizedRow;
12404
+ for (const [colKey, rawVal] of Object.entries(normalizedScanRow)) {
11951
12405
  if (!rawVal || rawVal.trim() === "") continue;
11952
12406
  const normalizedKey = colKey.toLowerCase().replace(/[\s_-]/g, "");
11953
12407
  if (SYSTEM_FIELD_KEYS.has(normalizedKey)) continue;
@@ -12661,6 +13115,9 @@ const index = {
12661
13115
  }
12662
13116
  });
12663
13117
  strapi.documents.use(async (context, next) => {
13118
+ if (isRollbackContext()) {
13119
+ return await next();
13120
+ }
12664
13121
  if (typeof context.uid === "string" && context.uid.startsWith("plugin::bulk-updater.")) {
12665
13122
  return await next();
12666
13123
  }
@@ -12849,6 +13306,7 @@ exports.escapeCsvCell = escapeCsvCell;
12849
13306
  exports.extractHeadingsFromRichText = extractHeadingsFromRichText;
12850
13307
  exports.extractMetadataFromRow = extractMetadataFromRow;
12851
13308
  exports.extractRowFlattenedMetadata = extractRowFlattenedMetadata;
13309
+ exports.findDuplicateCsvHeaders = findDuplicateCsvHeaders;
12852
13310
  exports.formatErrorCsvFilename = formatErrorCsvFilename;
12853
13311
  exports.formatErrorWithCause = formatErrorWithCause;
12854
13312
  exports.formatRelationState = formatRelationState;
@@ -12863,6 +13321,7 @@ exports.isPlainObject = isPlainObject;
12863
13321
  exports.isValidDocumentId = isValidDocumentId;
12864
13322
  exports.normalizeExportMode = normalizeExportMode;
12865
13323
  exports.normalizeRuleQuotas = normalizeRuleQuotas;
13324
+ exports.normalizeSelectiveBeforeTargetRow = normalizeSelectiveBeforeTargetRow;
12866
13325
  exports.parseBoolean = parseBoolean;
12867
13326
  exports.parseCsvToMatrix = parseCsvToMatrix;
12868
13327
  exports.parseCsvToRecords = parseCsvToRecords;