strapi-plugin-bulk-updater 1.6.5 → 1.6.7

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.
@@ -335,6 +335,137 @@ const contentTypes = {
335
335
  schema: auditLog
336
336
  }
337
337
  };
338
+ const CRASH_GUARD_SYMBOL = Symbol.for("strapi-plugin-bulk-updater.undiciCrashGuardInstalled");
339
+ let activeBulkOperations = 0;
340
+ function getActiveBulkOperationCount() {
341
+ return activeBulkOperations;
342
+ }
343
+ async function trackActiveBulkOperation(fn) {
344
+ activeBulkOperations++;
345
+ try {
346
+ return await fn();
347
+ } finally {
348
+ activeBulkOperations = Math.max(0, activeBulkOperations - 1);
349
+ }
350
+ }
351
+ function getBatchConcurrency(strapi) {
352
+ const DEFAULT_CONCURRENCY = 5;
353
+ const MIN_CONCURRENCY = 1;
354
+ const MAX_CONCURRENCY = 10;
355
+ try {
356
+ const configured = strapi?.config?.get?.("plugin::bulk-updater.batchConcurrency");
357
+ if (configured !== void 0 && configured !== null && configured !== "") {
358
+ const parsed = Number(configured);
359
+ if (Number.isFinite(parsed) && parsed >= MIN_CONCURRENCY) {
360
+ return Math.min(MAX_CONCURRENCY, Math.floor(parsed));
361
+ }
362
+ }
363
+ } catch {
364
+ }
365
+ return DEFAULT_CONCURRENCY;
366
+ }
367
+ function sanitizeSensitiveErrorText(text) {
368
+ if (!text || typeof text !== "string") return "";
369
+ return text.replace(/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi, "Bearer [REDACTED]").replace(/Basic\s+[A-Za-z0-9+/=]+/gi, "Basic [REDACTED]").replace(/(authorization|api[_-]?key|token|secret|password)\s*[:=]\s*[^\s,;'"}\]]+/gi, "$1=[REDACTED]").replace(/([?&](?:token|key|api_key|apikey|secret|password|auth)=)[^&\s]+/gi, "$1[REDACTED]");
370
+ }
371
+ function isFetchFailedError(err) {
372
+ if (!err) return false;
373
+ const visited = /* @__PURE__ */ new Set();
374
+ let current = err;
375
+ while (current && typeof current === "object" && !visited.has(current)) {
376
+ visited.add(current);
377
+ const msg = typeof current.message === "string" ? current.message : "";
378
+ const code = typeof current.code === "string" ? current.code : "";
379
+ const stack = typeof current.stack === "string" ? current.stack : "";
380
+ if (/fetch failed/i.test(msg) || code.startsWith("UND_ERR_") || stack.includes("node:internal/deps/undici")) {
381
+ return true;
382
+ }
383
+ if (Array.isArray(current.errors)) {
384
+ for (const sub of current.errors) {
385
+ if (isFetchFailedError(sub)) return true;
386
+ }
387
+ }
388
+ current = current.cause;
389
+ }
390
+ return false;
391
+ }
392
+ function formatErrorWithCause(err, fallback = "Unknown error") {
393
+ if (!err) return fallback;
394
+ if (typeof err === "string") return sanitizeSensitiveErrorText(err) || fallback;
395
+ const primaryMsg = typeof err.message === "string" && err.message.trim() && err.message !== "[object Object]" ? err.message.trim() : fallback;
396
+ const causeParts = [];
397
+ const visited = /* @__PURE__ */ new Set([err]);
398
+ let current = err.cause;
399
+ while (current && !visited.has(current) && causeParts.length < 4) {
400
+ visited.add(current);
401
+ if (typeof current === "string") {
402
+ if (current.trim()) causeParts.push(current.trim());
403
+ break;
404
+ }
405
+ if (typeof current === "object") {
406
+ const code = typeof current.code === "string" ? current.code.trim() : "";
407
+ const msg = typeof current.message === "string" ? current.message.trim() : "";
408
+ const addr = typeof current.address === "string" ? current.address.trim() : "";
409
+ const port = current.port !== void 0 && current.port !== null ? String(current.port) : "";
410
+ const endpoint = addr ? port ? `${addr}:${port}` : addr : "";
411
+ const pieces = [];
412
+ if (code) pieces.push(code);
413
+ if (msg && msg !== code) pieces.push(msg);
414
+ if (endpoint && !msg.includes(endpoint)) pieces.push(endpoint);
415
+ if (pieces.length > 0) {
416
+ causeParts.push(pieces.join(" - "));
417
+ } else if (Array.isArray(current.errors) && current.errors.length > 0) {
418
+ const subMsgs = current.errors.slice(0, 2).map((e) => {
419
+ const subCode = e?.code ? `${e.code}: ` : "";
420
+ return `${subCode}${e?.message || ""}`.trim();
421
+ }).filter(Boolean);
422
+ if (subMsgs.length > 0) {
423
+ causeParts.push(subMsgs.join("; "));
424
+ }
425
+ }
426
+ current = current.cause;
427
+ } else {
428
+ break;
429
+ }
430
+ }
431
+ let formatted = primaryMsg;
432
+ if (causeParts.length > 0) {
433
+ formatted = `${primaryMsg} (${causeParts.join(" -> ")})`;
434
+ }
435
+ if (isFetchFailedError(err) && !formatted.toLowerCase().includes("webhook")) {
436
+ formatted += " — downstream webhook or lifecycle HTTP request failed";
437
+ }
438
+ return sanitizeSensitiveErrorText(formatted);
439
+ }
440
+ function installUndiciCrashGuard(strapi) {
441
+ const globalObj = globalThis;
442
+ if (globalObj[CRASH_GUARD_SYMBOL]) {
443
+ return globalObj[CRASH_GUARD_SYMBOL];
444
+ }
445
+ const handler = (reason) => {
446
+ if (!isFetchFailedError(reason)) {
447
+ return;
448
+ }
449
+ const formatted = formatErrorWithCause(reason, "fetch failed");
450
+ const inBulk = activeBulkOperations > 0;
451
+ const contextNote = inBulk ? `during active bulk/CSV operation (${activeBulkOperations} active)` : "outside active bulk operation";
452
+ const logMsg = `[bulk-updater] Prevented server crash from unhandled undici fetch rejection ${contextNote}: ${formatted}. Check Strapi Settings > Webhooks or custom lifecycle hooks for unreachable/slow endpoints.`;
453
+ if (strapi?.log?.error) {
454
+ strapi.log.error(logMsg);
455
+ } else {
456
+ console.error(logMsg);
457
+ }
458
+ };
459
+ process.on("unhandledRejection", handler);
460
+ const uninstall = () => {
461
+ process.removeListener("unhandledRejection", handler);
462
+ if (globalObj[CRASH_GUARD_SYMBOL] === uninstall) {
463
+ delete globalObj[CRASH_GUARD_SYMBOL];
464
+ }
465
+ };
466
+ globalObj[CRASH_GUARD_SYMBOL] = uninstall;
467
+ return uninstall;
468
+ }
338
469
  const bulkUpdaterController = ({ strapi }) => ({
339
470
  async getModels(ctx) {
340
471
  try {
@@ -410,8 +541,10 @@ const bulkUpdaterController = ({ strapi }) => ({
410
541
  const result = await service.batchUpdate(ctx.request.body || {}, currentUser);
411
542
  ctx.body = result;
412
543
  } catch (err) {
413
- ctx.status = 400;
414
- ctx.body = { success: false, error: err.message };
544
+ const formatted = formatErrorWithCause(err, "Batch update failed");
545
+ strapi.log?.error?.(`[bulk-updater] POST /batch-update error: ${formatted}`);
546
+ ctx.status = isFetchFailedError(err) ? 502 : 400;
547
+ ctx.body = { success: false, error: formatted };
415
548
  }
416
549
  },
417
550
  async batchPublish(ctx) {
@@ -421,8 +554,10 @@ const bulkUpdaterController = ({ strapi }) => ({
421
554
  const result = await service.batchPublish(ctx.request.body || {}, currentUser);
422
555
  ctx.body = result;
423
556
  } catch (err) {
424
- ctx.status = 400;
425
- ctx.body = { success: false, error: err.message };
557
+ const formatted = formatErrorWithCause(err, "Batch publish failed");
558
+ strapi.log?.error?.(`[bulk-updater] POST /batch-publish error: ${formatted}`);
559
+ ctx.status = isFetchFailedError(err) ? 502 : 400;
560
+ ctx.body = { success: false, error: formatted };
426
561
  }
427
562
  },
428
563
  async previewBatch(ctx) {
@@ -454,8 +589,10 @@ const bulkUpdaterController = ({ strapi }) => ({
454
589
  const result = await service.approveBatch(batchId, currentUser, { executeImmediately });
455
590
  ctx.body = result;
456
591
  } catch (err) {
457
- ctx.status = 400;
458
- ctx.body = { success: false, error: err.message };
592
+ const formatted = formatErrorWithCause(err, "Batch approval failed");
593
+ strapi.log?.error?.(`[bulk-updater] POST /batches/${ctx.params?.batchId}/approve error: ${formatted}`);
594
+ ctx.status = isFetchFailedError(err) ? 502 : 400;
595
+ ctx.body = { success: false, error: formatted };
459
596
  }
460
597
  },
461
598
  async rejectBatch(ctx) {
@@ -479,8 +616,10 @@ const bulkUpdaterController = ({ strapi }) => ({
479
616
  const result = await service.executeNow(batchId, currentUser);
480
617
  ctx.body = result;
481
618
  } catch (err) {
482
- ctx.status = 400;
483
- ctx.body = { success: false, error: err.message };
619
+ const formatted = formatErrorWithCause(err, "Batch execution failed");
620
+ strapi.log?.error?.(`[bulk-updater] POST /batches/${ctx.params?.batchId}/execute-now error: ${formatted}`);
621
+ ctx.status = isFetchFailedError(err) ? 502 : 400;
622
+ ctx.body = { success: false, error: formatted };
484
623
  }
485
624
  },
486
625
  async getBatchStatus(ctx) {
@@ -766,8 +905,10 @@ const csvController = ({ strapi }) => ({
766
905
  });
767
906
  ctx.body = result;
768
907
  } catch (err) {
769
- ctx.status = 500;
770
- ctx.body = { success: false, error: err.message };
908
+ const formatted = formatErrorWithCause(err, "CSV import failed");
909
+ strapi.log?.error?.(`[bulk-updater] POST /csv/import error: ${formatted}`);
910
+ ctx.status = isFetchFailedError(err) ? 502 : 500;
911
+ ctx.body = { success: false, error: formatted };
771
912
  }
772
913
  },
773
914
  async importChunk(ctx) {
@@ -798,8 +939,10 @@ const csvController = ({ strapi }) => ({
798
939
  });
799
940
  ctx.body = result;
800
941
  } catch (err) {
801
- ctx.status = 500;
802
- ctx.body = { success: false, error: err.message };
942
+ const formatted = formatErrorWithCause(err, "CSV chunk import failed");
943
+ strapi.log?.error?.(`[bulk-updater] POST /csv/import-chunk error: ${formatted}`);
944
+ ctx.status = isFetchFailedError(err) ? 502 : 500;
945
+ ctx.body = { success: false, error: formatted };
803
946
  }
804
947
  },
805
948
  async validatePreflight(ctx) {
@@ -852,8 +995,10 @@ const csvController = ({ strapi }) => ({
852
995
  });
853
996
  ctx.body = result;
854
997
  } catch (err) {
855
- ctx.status = 500;
856
- ctx.body = { success: false, error: err.message };
998
+ const formatted = formatErrorWithCause(err, "CSV batch submission failed");
999
+ strapi.log?.error?.(`[bulk-updater] POST /csv/submit-batch error: ${formatted}`);
1000
+ ctx.status = isFetchFailedError(err) ? 502 : 500;
1001
+ ctx.body = { success: false, error: formatted };
857
1002
  }
858
1003
  }
859
1004
  });
@@ -5489,7 +5634,7 @@ async function resolveAndMaybePublishTarget({
5489
5634
  }
5490
5635
  }
5491
5636
  const inspectionTarget = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
5492
- const { hadPublishedVersion } = resolveRecordPublicationStatus(inspectionTarget, pubRecord, isDraftAndPublish);
5637
+ const { hadPublishedVersion, status: preStatus } = resolveRecordPublicationStatus(inspectionTarget, pubRecord, isDraftAndPublish);
5493
5638
  const isEditing = isRowInEditingStage$1(inspectionTarget) || isRowInEditingStage$1(target);
5494
5639
  const shouldPublish = evaluateShouldPublish({
5495
5640
  isDraftAndPublish,
@@ -5503,6 +5648,7 @@ async function resolveAndMaybePublishTarget({
5503
5648
  candLocale: isLocalized ? candLocale : void 0,
5504
5649
  isDraftAndPublish,
5505
5650
  hadPublishedVersion,
5651
+ previousStatus: preStatus,
5506
5652
  shouldPublish,
5507
5653
  async postUpdate(relatedTargetUid) {
5508
5654
  if (shouldPublish) {
@@ -5511,7 +5657,9 @@ async function resolveAndMaybePublishTarget({
5511
5657
  if (isLocalized) pubArgs.locale = candLocale;
5512
5658
  await strapi.documents(target.uid).publish(pubArgs);
5513
5659
  } catch (publishErr) {
5514
- strapi.log.warn(`[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}:`, publishErr);
5660
+ strapi.log.warn(
5661
+ `[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}: ${formatErrorWithCause(publishErr)}`
5662
+ );
5515
5663
  }
5516
5664
  }
5517
5665
  invalidateCollectionCache(target.uid);
@@ -5664,6 +5812,9 @@ async function executeGridTargetUpdate({
5664
5812
  oldValue: oldSummaryVal,
5665
5813
  newValue: newSummaryVal,
5666
5814
  status: "updated",
5815
+ previousStatus: lifecycle.previousStatus,
5816
+ hadPublishedVersion: lifecycle.hadPublishedVersion,
5817
+ isDraftAndPublish: lifecycle.isDraftAndPublish,
5667
5818
  message: isMultiOcc ? `Successfully updated ${changedDiffs.length} grid occurrence(s) in ${attribute}` : `Successfully updated ${attribute}`,
5668
5819
  dynamicZoneDiffs: isComponentNested ? changedDiffs : void 0,
5669
5820
  gridGroupDiffs: changedDiffs.length > 1 || isComponentNested ? changedDiffs : void 0
@@ -5742,562 +5893,610 @@ async function executeBatchInternal(strapi, {
5742
5893
  results: []
5743
5894
  };
5744
5895
  batchJobsMap.set(batchId, jobState);
5745
- let regexObj = null;
5746
- if (effectiveEditMode !== "grid" && isRegex && regexPattern) {
5747
- regexObj = new RegExp(regexPattern, "g");
5748
- }
5749
- const CHUNK_SIZE = 25;
5750
- const publishedCounterparts = /* @__PURE__ */ new Map();
5751
- const uidsWithDraftAndPublish = /* @__PURE__ */ new Set();
5752
- const docIdsByUid = /* @__PURE__ */ new Map();
5753
- for (const target of targets) {
5754
- if (target.uid && target.documentId) {
5755
- const ct = strapi.contentTypes[target.uid];
5756
- if (ct?.options?.draftAndPublish) {
5757
- uidsWithDraftAndPublish.add(target.uid);
5758
- if (!docIdsByUid.has(target.uid)) {
5759
- docIdsByUid.set(target.uid, []);
5896
+ return await trackActiveBulkOperation(async () => {
5897
+ try {
5898
+ let regexObj = null;
5899
+ if (effectiveEditMode !== "grid" && isRegex && regexPattern) {
5900
+ regexObj = new RegExp(regexPattern, "g");
5901
+ }
5902
+ const CHUNK_SIZE = getBatchConcurrency(strapi);
5903
+ const publishedCounterparts = /* @__PURE__ */ new Map();
5904
+ const uidsWithDraftAndPublish = /* @__PURE__ */ new Set();
5905
+ const docIdsByUid = /* @__PURE__ */ new Map();
5906
+ for (const target of targets) {
5907
+ if (target.uid && target.documentId) {
5908
+ const ct = strapi.contentTypes[target.uid];
5909
+ if (ct?.options?.draftAndPublish) {
5910
+ uidsWithDraftAndPublish.add(target.uid);
5911
+ if (!docIdsByUid.has(target.uid)) {
5912
+ docIdsByUid.set(target.uid, []);
5913
+ }
5914
+ docIdsByUid.get(target.uid).push(target.documentId);
5915
+ }
5760
5916
  }
5761
- docIdsByUid.get(target.uid).push(target.documentId);
5762
5917
  }
5763
- }
5764
- }
5765
- for (const colUid of uidsWithDraftAndPublish) {
5766
- const docIds = docIdsByUid.get(colUid) || [];
5767
- if (docIds.length > 0) {
5768
- try {
5769
- const pubDocs = await strapi.documents(colUid).findMany({
5770
- status: "published",
5771
- filters: { documentId: { $in: docIds } },
5772
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
5773
- limit: Math.max(docIds.length, 100)
5774
- });
5775
- for (const pub of pubDocs || []) {
5776
- if (pub?.documentId) {
5777
- publishedCounterparts.set(`${colUid}@@@${pub.documentId}`, pub);
5778
- if (pub.locale) {
5779
- publishedCounterparts.set(`${colUid}@@@${pub.documentId}@@@${pub.locale}`, pub);
5918
+ for (const colUid of uidsWithDraftAndPublish) {
5919
+ const docIds = docIdsByUid.get(colUid) || [];
5920
+ if (docIds.length > 0) {
5921
+ try {
5922
+ const pubDocs = await strapi.documents(colUid).findMany({
5923
+ status: "published",
5924
+ filters: { documentId: { $in: docIds } },
5925
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
5926
+ limit: Math.max(docIds.length, 100)
5927
+ });
5928
+ for (const pub of pubDocs || []) {
5929
+ if (pub?.documentId) {
5930
+ publishedCounterparts.set(`${colUid}@@@${pub.documentId}`, pub);
5931
+ if (pub.locale) {
5932
+ publishedCounterparts.set(`${colUid}@@@${pub.documentId}@@@${pub.locale}`, pub);
5933
+ }
5934
+ }
5780
5935
  }
5936
+ } catch {
5781
5937
  }
5782
5938
  }
5783
- } catch {
5784
5939
  }
5785
- }
5786
- }
5787
- const documentLoader = /* @__PURE__ */ new Map();
5788
- const getDocumentDeduplicated = (uid, documentId) => {
5789
- const loaderKey = `${uid}@@@${documentId}`;
5790
- if (!documentLoader.has(loaderKey)) {
5791
- const ct = strapi.contentTypes[uid];
5792
- const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
5793
- documentLoader.set(
5794
- loaderKey,
5795
- strapi.documents(uid).findOne({
5796
- documentId,
5797
- ...populateDef ? { populate: populateDef } : { populate: "*" }
5798
- })
5799
- );
5800
- }
5801
- return documentLoader.get(loaderKey);
5802
- };
5803
- for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
5804
- const chunk = targets.slice(i, i + CHUNK_SIZE);
5805
- const chunkPromises = chunk.map(async (target) => {
5806
- const contentType = strapi.contentTypes[target.uid];
5807
- const displayName = contentType?.info?.displayName || target.uid;
5808
- try {
5809
- if (effectiveEditMode === "grid") {
5810
- return await executeGridTargetUpdate({
5811
- strapi,
5812
- target,
5813
- attribute,
5814
- contentType,
5815
- displayName,
5816
- publishedCounterparts,
5817
- publishOnApproval: Boolean(publishOnApproval),
5818
- publishStrategy,
5819
- unreviewedConsent: Boolean(unreviewedConsent),
5820
- currentUser
5821
- });
5940
+ const documentLoader = /* @__PURE__ */ new Map();
5941
+ const getDocumentDeduplicated = (uid, documentId) => {
5942
+ const loaderKey = `${uid}@@@${documentId}`;
5943
+ if (!documentLoader.has(loaderKey)) {
5944
+ const ct = strapi.contentTypes[uid];
5945
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
5946
+ documentLoader.set(
5947
+ loaderKey,
5948
+ strapi.documents(uid).findOne({
5949
+ documentId,
5950
+ ...populateDef ? { populate: populateDef } : { populate: "*" }
5951
+ })
5952
+ );
5822
5953
  }
5823
- const currentEntry = await getDocumentDeduplicated(target.uid, target.documentId);
5824
- const entryLabel = currentEntry?.name || currentEntry?.title || currentEntry?.email || `Entry #${target.documentId}`;
5825
- const parsed = parseDynamicZonePath(attribute);
5826
- const isNested = attribute.includes(".") || attribute.includes("[");
5827
- const isComponentNested = isNested && isDeepComponentField(contentType, strapi.components, attribute);
5828
- const parts = isNested ? parsed.cleanPath.split(".") : [];
5829
- const rootKey = parsed.rootKey;
5830
- const targetComponentUid = target.targetComponentUid || parsed.targetComponentUid;
5831
- const targetIndexes = target.dynamicZoneIndexes;
5832
- const attrDef = contentType?.attributes?.[attribute];
5833
- const hasAttribute = Boolean(attrDef) || isComponentNested;
5834
- if (hasAttribute) {
5835
- if (isComponentNested) {
5836
- const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
5837
- const findOneArgs = { documentId: target.documentId };
5838
- if (populateOption) {
5839
- findOneArgs.populate = populateOption;
5954
+ return documentLoader.get(loaderKey);
5955
+ };
5956
+ for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
5957
+ const chunk = targets.slice(i, i + CHUNK_SIZE);
5958
+ const chunkPromises = chunk.map(async (target) => {
5959
+ const contentType = strapi.contentTypes[target.uid];
5960
+ const displayName = contentType?.info?.displayName || target.uid;
5961
+ try {
5962
+ if (effectiveEditMode === "grid") {
5963
+ return await executeGridTargetUpdate({
5964
+ strapi,
5965
+ target,
5966
+ attribute,
5967
+ contentType,
5968
+ displayName,
5969
+ publishedCounterparts,
5970
+ publishOnApproval: Boolean(publishOnApproval),
5971
+ publishStrategy,
5972
+ unreviewedConsent: Boolean(unreviewedConsent),
5973
+ currentUser
5974
+ });
5840
5975
  }
5841
- const currentEntryWithPopulate = await strapi.documents(target.uid).findOne(findOneArgs);
5842
- const isRootDz = contentType?.attributes?.[rootKey]?.type === "dynamiczone";
5843
- const existingRoot = currentEntryWithPopulate?.[rootKey] || (isRootDz ? [] : {});
5844
- let affectedMatches = [];
5845
- if (isRootDz && Array.isArray(existingRoot)) {
5846
- affectedMatches = getAllNestedValues({ [rootKey]: existingRoot }, attribute);
5847
- if (targetIndexes && targetIndexes.length > 0) {
5848
- affectedMatches = affectedMatches.filter((m) => targetIndexes.includes(m.index));
5849
- }
5850
- if (targetComponentUid) {
5851
- affectedMatches = affectedMatches.filter((m) => m.componentUid === targetComponentUid);
5976
+ const currentEntry = await getDocumentDeduplicated(target.uid, target.documentId);
5977
+ const entryLabel = currentEntry?.name || currentEntry?.title || currentEntry?.email || `Entry #${target.documentId}`;
5978
+ const parsed = parseDynamicZonePath(attribute);
5979
+ const isNested = attribute.includes(".") || attribute.includes("[");
5980
+ const isComponentNested = isNested && isDeepComponentField(contentType, strapi.components, attribute);
5981
+ const parts = isNested ? parsed.cleanPath.split(".") : [];
5982
+ const rootKey = parsed.rootKey;
5983
+ const targetComponentUid = target.targetComponentUid || parsed.targetComponentUid;
5984
+ const targetIndexes = target.dynamicZoneIndexes;
5985
+ const attrDef = contentType?.attributes?.[attribute];
5986
+ const hasAttribute = Boolean(attrDef) || isComponentNested;
5987
+ if (hasAttribute) {
5988
+ if (isComponentNested) {
5989
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
5990
+ const findOneArgs = { documentId: target.documentId };
5991
+ if (populateOption) {
5992
+ findOneArgs.populate = populateOption;
5993
+ }
5994
+ const currentEntryWithPopulate = await strapi.documents(target.uid).findOne(findOneArgs);
5995
+ const isRootDz = contentType?.attributes?.[rootKey]?.type === "dynamiczone";
5996
+ const existingRoot = currentEntryWithPopulate?.[rootKey] || (isRootDz ? [] : {});
5997
+ let affectedMatches = [];
5998
+ if (isRootDz && Array.isArray(existingRoot)) {
5999
+ affectedMatches = getAllNestedValues({ [rootKey]: existingRoot }, attribute);
6000
+ if (targetIndexes && targetIndexes.length > 0) {
6001
+ affectedMatches = affectedMatches.filter((m) => targetIndexes.includes(m.index));
6002
+ }
6003
+ if (targetComponentUid) {
6004
+ affectedMatches = affectedMatches.filter((m) => m.componentUid === targetComponentUid);
6005
+ }
6006
+ }
6007
+ const currentVal2 = isRootDz ? affectedMatches.length > 0 ? affectedMatches.map((m) => m.value).join(", ") : getDeepProperty(existingRoot, parts.slice(1).join(".")) : getDeepProperty(existingRoot, parts.slice(1).join("."));
6008
+ let newValue2 = value;
6009
+ if (regexObj && typeof currentVal2 === "string") {
6010
+ newValue2 = currentVal2.replace(regexObj, value);
6011
+ }
6012
+ const updatedRoot = setDeepProperty(existingRoot, parts.slice(1), newValue2, {
6013
+ targetIndexes,
6014
+ targetComponentUid
6015
+ });
6016
+ const isDraftAndPublishComp = Boolean(contentType?.options?.draftAndPublish);
6017
+ const candLocaleComp = target.locale || currentEntry?.locale;
6018
+ let pubRecordComp = candLocaleComp && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleComp}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6019
+ if (!pubRecordComp && isDraftAndPublishComp && target.documentId) {
6020
+ try {
6021
+ const singlePub = await strapi.documents(target.uid).findMany({
6022
+ status: "published",
6023
+ filters: { documentId: target.documentId },
6024
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6025
+ limit: 1
6026
+ });
6027
+ if (singlePub && singlePub.length > 0) {
6028
+ pubRecordComp = singlePub[0];
6029
+ publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordComp);
6030
+ }
6031
+ } catch {
6032
+ }
6033
+ }
6034
+ const inspectionTargetComp = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6035
+ const { hadPublishedVersion: hadPubComp, status: preStatusComp } = resolveRecordPublicationStatus(
6036
+ inspectionTargetComp,
6037
+ pubRecordComp,
6038
+ isDraftAndPublishComp
6039
+ );
6040
+ const isEditingComp = isRowInEditingStage$1(inspectionTargetComp) || isRowInEditingStage$1(target);
6041
+ const shouldPublishComp = evaluateShouldPublish({
6042
+ isDraftAndPublish: isDraftAndPublishComp,
6043
+ hadPublishedVersion: hadPubComp,
6044
+ isEditing: isEditingComp,
6045
+ publishOnApproval: Boolean(publishOnApproval),
6046
+ publishStrategy,
6047
+ unreviewedConsent
6048
+ });
6049
+ const proposedEntityComp = deepMergeEntities(currentEntryWithPopulate || currentEntry, { [rootKey]: updatedRoot });
6050
+ const valResultComp = await validateEntityQuotas(strapi, target.uid, proposedEntityComp);
6051
+ if (!valResultComp.isValid) {
6052
+ return {
6053
+ uid: target.uid,
6054
+ collectionName: displayName,
6055
+ documentId: target.documentId,
6056
+ label: entryLabel,
6057
+ attribute,
6058
+ oldValue: currentVal2 ?? null,
6059
+ newValue: newValue2,
6060
+ status: "error",
6061
+ message: valResultComp.errorMessage
6062
+ };
6063
+ }
6064
+ const updateArgsComp = {
6065
+ documentId: target.documentId,
6066
+ data: {
6067
+ [rootKey]: updatedRoot
6068
+ }
6069
+ };
6070
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleComp && candLocaleComp !== "null" && candLocaleComp !== "undefined") {
6071
+ updateArgsComp.locale = candLocaleComp;
6072
+ }
6073
+ await strapi.documents(target.uid).update(updateArgsComp);
6074
+ if (shouldPublishComp) {
6075
+ try {
6076
+ const pubArgs = {
6077
+ documentId: target.documentId
6078
+ };
6079
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleComp && candLocaleComp !== "null" && candLocaleComp !== "undefined") {
6080
+ pubArgs.locale = candLocaleComp;
6081
+ }
6082
+ await strapi.documents(target.uid).publish(pubArgs);
6083
+ } catch (publishErr) {
6084
+ strapi.log.warn(
6085
+ `[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}: ${formatErrorWithCause(publishErr)}`
6086
+ );
6087
+ }
6088
+ }
6089
+ invalidateCollectionCache(target.uid);
6090
+ await recordContentHistoryVersion(strapi, {
6091
+ uid: target.uid,
6092
+ documentId: target.documentId,
6093
+ userId: currentUser?.id,
6094
+ statusOverride: shouldPublishComp ? "published" : isDraftAndPublishComp ? hadPubComp ? "modified" : "draft" : void 0
6095
+ });
6096
+ const dzDiffs = isRootDz && affectedMatches.length > 0 ? affectedMatches.map((m) => ({
6097
+ index: m.index,
6098
+ componentUid: m.componentUid,
6099
+ componentName: m.componentName,
6100
+ attribute: `${rootKey}[#${m.index} ${m.componentName}].${parts.slice(1).join(".")}`,
6101
+ oldValue: m.value,
6102
+ newValue: regexObj && typeof m.value === "string" ? m.value.replace(regexObj, value) : value
6103
+ })) : [];
6104
+ return {
6105
+ uid: target.uid,
6106
+ collectionName: displayName,
6107
+ documentId: target.documentId,
6108
+ locale: candLocaleComp,
6109
+ label: entryLabel,
6110
+ attribute,
6111
+ oldValue: currentVal2 ?? null,
6112
+ newValue: newValue2,
6113
+ status: "updated",
6114
+ previousStatus: preStatusComp,
6115
+ hadPublishedVersion: hadPubComp,
6116
+ isDraftAndPublish: isDraftAndPublishComp,
6117
+ message: isRootDz ? `Successfully updated ${affectedMatches.length} dynamic zone item(s) in ${attribute}` : `Successfully updated nested field ${attribute}`,
6118
+ dynamicZoneDiffs: dzDiffs
6119
+ };
5852
6120
  }
5853
- }
5854
- const currentVal2 = isRootDz ? affectedMatches.length > 0 ? affectedMatches.map((m) => m.value).join(", ") : getDeepProperty(existingRoot, parts.slice(1).join(".")) : getDeepProperty(existingRoot, parts.slice(1).join("."));
5855
- let newValue2 = value;
5856
- if (regexObj && typeof currentVal2 === "string") {
5857
- newValue2 = currentVal2.replace(regexObj, value);
5858
- }
5859
- const updatedRoot = setDeepProperty(existingRoot, parts.slice(1), newValue2, {
5860
- targetIndexes,
5861
- targetComponentUid
5862
- });
5863
- const isDraftAndPublishComp = Boolean(contentType?.options?.draftAndPublish);
5864
- const candLocaleComp = target.locale || currentEntry?.locale;
5865
- let pubRecordComp = candLocaleComp && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleComp}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
5866
- if (!pubRecordComp && isDraftAndPublishComp && target.documentId) {
5867
- try {
5868
- const singlePub = await strapi.documents(target.uid).findMany({
5869
- status: "published",
5870
- filters: { documentId: target.documentId },
5871
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
5872
- limit: 1
6121
+ if (attrDef.type === "relation") {
6122
+ const isMulti = attrDef.relation === "oneToMany" || attrDef.relation === "manyToMany";
6123
+ const currentEntryWithPopulate = await strapi.documents(target.uid).findOne({
6124
+ documentId: target.documentId,
6125
+ populate: [attribute]
5873
6126
  });
5874
- if (singlePub && singlePub.length > 0) {
5875
- pubRecordComp = singlePub[0];
5876
- publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordComp);
6127
+ const currentRel = currentEntryWithPopulate?.[attribute];
6128
+ let oldDocIds = [];
6129
+ let oldDisplay = "";
6130
+ if (isMulti && Array.isArray(currentRel)) {
6131
+ oldDocIds = currentRel.map((r) => r.documentId).filter(Boolean);
6132
+ oldDisplay = currentRel.map((r) => r.name || r.title || r.email || r.documentId).join(", ") || "(empty)";
6133
+ } else if (currentRel) {
6134
+ oldDocIds = currentRel.documentId ? [currentRel.documentId] : [];
6135
+ oldDisplay = currentRel.name || currentRel.title || currentRel.email || currentRel.documentId || "(empty)";
6136
+ } else {
6137
+ oldDisplay = "(unlinked / none)";
5877
6138
  }
5878
- } catch {
6139
+ let mode = "set";
6140
+ let targetDocIds = [];
6141
+ let newDisplay = "";
6142
+ if (value === "__clear__" || value === "") {
6143
+ mode = "clear";
6144
+ newDisplay = "(cleared / unlinked)";
6145
+ } else {
6146
+ try {
6147
+ const parsed2 = JSON.parse(value);
6148
+ if (parsed2 && typeof parsed2 === "object" && parsed2.mode) {
6149
+ mode = parsed2.mode;
6150
+ targetDocIds = Array.isArray(parsed2.documentIds) ? parsed2.documentIds : parsed2.documentId ? [parsed2.documentId] : [];
6151
+ newDisplay = parsed2.label || targetDocIds.join(", ") || `[${mode}]`;
6152
+ } else if (Array.isArray(parsed2)) {
6153
+ targetDocIds = parsed2;
6154
+ newDisplay = targetDocIds.join(", ");
6155
+ } else {
6156
+ targetDocIds = [value];
6157
+ newDisplay = value;
6158
+ }
6159
+ } catch {
6160
+ targetDocIds = [value];
6161
+ newDisplay = value;
6162
+ }
6163
+ }
6164
+ let relationPayload;
6165
+ if (mode === "clear") {
6166
+ relationPayload = isMulti ? { set: [] } : null;
6167
+ } else if (mode === "set") {
6168
+ relationPayload = isMulti ? { set: targetDocIds } : targetDocIds[0] || null;
6169
+ } else if (mode === "connect") {
6170
+ relationPayload = { connect: targetDocIds };
6171
+ } else if (mode === "disconnect") {
6172
+ relationPayload = { disconnect: targetDocIds };
6173
+ }
6174
+ const isDraftAndPublishRel = Boolean(contentType?.options?.draftAndPublish);
6175
+ const candLocaleRel = target.locale || currentEntry?.locale;
6176
+ let pubRecordRel = candLocaleRel && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleRel}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6177
+ if (!pubRecordRel && isDraftAndPublishRel && target.documentId) {
6178
+ try {
6179
+ const singlePub = await strapi.documents(target.uid).findMany({
6180
+ status: "published",
6181
+ filters: { documentId: target.documentId },
6182
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6183
+ limit: 1
6184
+ });
6185
+ if (singlePub && singlePub.length > 0) {
6186
+ pubRecordRel = singlePub[0];
6187
+ publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordRel);
6188
+ }
6189
+ } catch {
6190
+ }
6191
+ }
6192
+ const inspectionTargetRel = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6193
+ const { hadPublishedVersion: hadPubRel, status: preStatusRel } = resolveRecordPublicationStatus(
6194
+ inspectionTargetRel,
6195
+ pubRecordRel,
6196
+ isDraftAndPublishRel
6197
+ );
6198
+ const isEditingRel = isRowInEditingStage$1(inspectionTargetRel) || isRowInEditingStage$1(target);
6199
+ const shouldPublishRel = evaluateShouldPublish({
6200
+ isDraftAndPublish: isDraftAndPublishRel,
6201
+ hadPublishedVersion: hadPubRel,
6202
+ isEditing: isEditingRel,
6203
+ publishOnApproval: Boolean(publishOnApproval),
6204
+ publishStrategy,
6205
+ unreviewedConsent
6206
+ });
6207
+ const proposedEntityRel = deepMergeEntities(currentEntry, { [attribute]: relationPayload });
6208
+ const valResultRel = await validateEntityQuotas(strapi, target.uid, proposedEntityRel);
6209
+ if (!valResultRel.isValid) {
6210
+ return {
6211
+ uid: target.uid,
6212
+ collectionName: displayName,
6213
+ documentId: target.documentId,
6214
+ label: entryLabel,
6215
+ attribute,
6216
+ oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
6217
+ newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
6218
+ status: "error",
6219
+ message: valResultRel.errorMessage
6220
+ };
6221
+ }
6222
+ const updateArgsRel = {
6223
+ documentId: target.documentId,
6224
+ data: {
6225
+ [attribute]: relationPayload
6226
+ }
6227
+ };
6228
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleRel && candLocaleRel !== "null" && candLocaleRel !== "undefined") {
6229
+ updateArgsRel.locale = candLocaleRel;
6230
+ }
6231
+ await strapi.documents(target.uid).update(updateArgsRel);
6232
+ if (shouldPublishRel) {
6233
+ try {
6234
+ const pubArgs = {
6235
+ documentId: target.documentId
6236
+ };
6237
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleRel && candLocaleRel !== "null" && candLocaleRel !== "undefined") {
6238
+ pubArgs.locale = candLocaleRel;
6239
+ }
6240
+ await strapi.documents(target.uid).publish(pubArgs);
6241
+ } catch (publishErr) {
6242
+ strapi.log.warn(
6243
+ `[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}: ${formatErrorWithCause(publishErr)}`
6244
+ );
6245
+ }
6246
+ }
6247
+ invalidateCollectionCache(target.uid);
6248
+ if (attrDef.target) {
6249
+ invalidateCollectionCache(attrDef.target);
6250
+ }
6251
+ await recordContentHistoryVersion(strapi, {
6252
+ uid: target.uid,
6253
+ documentId: target.documentId,
6254
+ userId: currentUser?.id,
6255
+ statusOverride: shouldPublishRel ? "published" : isDraftAndPublishRel ? hadPubRel ? "modified" : "draft" : void 0
6256
+ });
6257
+ return {
6258
+ uid: target.uid,
6259
+ collectionName: displayName,
6260
+ documentId: target.documentId,
6261
+ locale: candLocaleRel,
6262
+ label: entryLabel,
6263
+ attribute,
6264
+ oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
6265
+ newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
6266
+ status: "updated",
6267
+ previousStatus: preStatusRel,
6268
+ hadPublishedVersion: hadPubRel,
6269
+ isDraftAndPublish: isDraftAndPublishRel,
6270
+ message: `Successfully updated relation "${attribute}"`
6271
+ };
5879
6272
  }
5880
- }
5881
- const inspectionTargetComp = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
5882
- const { hadPublishedVersion: hadPubComp } = resolveRecordPublicationStatus(
5883
- inspectionTargetComp,
5884
- pubRecordComp,
5885
- isDraftAndPublishComp
5886
- );
5887
- const isEditingComp = isRowInEditingStage$1(inspectionTargetComp) || isRowInEditingStage$1(target);
5888
- const shouldPublishComp = evaluateShouldPublish({
5889
- isDraftAndPublish: isDraftAndPublishComp,
5890
- hadPublishedVersion: hadPubComp,
5891
- isEditing: isEditingComp,
5892
- publishOnApproval: Boolean(publishOnApproval),
5893
- publishStrategy,
5894
- unreviewedConsent
5895
- });
5896
- const proposedEntityComp = deepMergeEntities(currentEntryWithPopulate || currentEntry, { [rootKey]: updatedRoot });
5897
- const valResultComp = await validateEntityQuotas(strapi, target.uid, proposedEntityComp);
5898
- if (!valResultComp.isValid) {
6273
+ let newValue = value;
6274
+ const currentVal = currentEntry?.[attribute];
6275
+ if (regexObj && typeof currentVal === "string") {
6276
+ newValue = currentVal.replace(regexObj, value);
6277
+ }
6278
+ const isDraftAndPublishScalar = Boolean(contentType?.options?.draftAndPublish);
6279
+ const candLocaleScalar = target.locale || currentEntry?.locale;
6280
+ let pubRecordScalar = candLocaleScalar && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleScalar}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6281
+ if (!pubRecordScalar && isDraftAndPublishScalar && target.documentId) {
6282
+ try {
6283
+ const singlePub = await strapi.documents(target.uid).findMany({
6284
+ status: "published",
6285
+ filters: { documentId: target.documentId },
6286
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6287
+ limit: 1
6288
+ });
6289
+ if (singlePub && singlePub.length > 0) {
6290
+ pubRecordScalar = singlePub[0];
6291
+ publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordScalar);
6292
+ }
6293
+ } catch {
6294
+ }
6295
+ }
6296
+ const inspectionTargetScalar = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6297
+ const { hadPublishedVersion: hadPubScalar, status: preStatusScalar } = resolveRecordPublicationStatus(
6298
+ inspectionTargetScalar,
6299
+ pubRecordScalar,
6300
+ isDraftAndPublishScalar
6301
+ );
6302
+ const isEditingScalar = isRowInEditingStage$1(inspectionTargetScalar) || isRowInEditingStage$1(target);
6303
+ const shouldPublishScalar = evaluateShouldPublish({
6304
+ isDraftAndPublish: isDraftAndPublishScalar,
6305
+ hadPublishedVersion: hadPubScalar,
6306
+ isEditing: isEditingScalar,
6307
+ publishOnApproval: Boolean(publishOnApproval),
6308
+ publishStrategy,
6309
+ unreviewedConsent
6310
+ });
6311
+ const proposedEntityScalar = deepMergeEntities(currentEntry, { [attribute]: newValue });
6312
+ const valResultScalar = await validateEntityQuotas(strapi, target.uid, proposedEntityScalar);
6313
+ if (!valResultScalar.isValid) {
6314
+ return {
6315
+ uid: target.uid,
6316
+ collectionName: displayName,
6317
+ documentId: target.documentId,
6318
+ label: entryLabel,
6319
+ attribute,
6320
+ oldValue: currentVal ?? null,
6321
+ newValue,
6322
+ status: "error",
6323
+ message: valResultScalar.errorMessage
6324
+ };
6325
+ }
6326
+ const updateArgsScalar = {
6327
+ documentId: target.documentId,
6328
+ data: {
6329
+ [attribute]: newValue
6330
+ }
6331
+ };
6332
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
6333
+ updateArgsScalar.locale = candLocaleScalar;
6334
+ }
6335
+ await strapi.documents(target.uid).update(updateArgsScalar);
6336
+ if (shouldPublishScalar) {
6337
+ try {
6338
+ const pubArgs = {
6339
+ documentId: target.documentId
6340
+ };
6341
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
6342
+ pubArgs.locale = candLocaleScalar;
6343
+ }
6344
+ await strapi.documents(target.uid).publish(pubArgs);
6345
+ } catch (publishErr) {
6346
+ strapi.log.warn(
6347
+ `[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}: ${formatErrorWithCause(publishErr)}`
6348
+ );
6349
+ }
6350
+ }
6351
+ await recordContentHistoryVersion(strapi, {
6352
+ uid: target.uid,
6353
+ documentId: target.documentId,
6354
+ userId: currentUser?.id,
6355
+ statusOverride: shouldPublishScalar ? "published" : isDraftAndPublishScalar ? hadPubScalar ? "modified" : "draft" : void 0
6356
+ });
5899
6357
  return {
5900
6358
  uid: target.uid,
5901
6359
  collectionName: displayName,
5902
6360
  documentId: target.documentId,
6361
+ locale: candLocaleScalar,
5903
6362
  label: entryLabel,
5904
6363
  attribute,
5905
- oldValue: currentVal2 ?? null,
5906
- newValue: newValue2,
5907
- status: "error",
5908
- message: valResultComp.errorMessage
6364
+ oldValue: currentVal ?? null,
6365
+ newValue,
6366
+ status: "updated",
6367
+ previousStatus: preStatusScalar,
6368
+ hadPublishedVersion: hadPubScalar,
6369
+ isDraftAndPublish: isDraftAndPublishScalar,
6370
+ message: `Successfully updated ${attribute}`
6371
+ };
6372
+ } else {
6373
+ return {
6374
+ uid: target.uid,
6375
+ collectionName: displayName,
6376
+ documentId: target.documentId,
6377
+ label: entryLabel,
6378
+ attribute,
6379
+ status: "skipped",
6380
+ message: `Skipped: Attribute "${attribute}" does not exist in schema for ${displayName}`
5909
6381
  };
5910
6382
  }
5911
- const updateArgsComp = {
5912
- documentId: target.documentId,
5913
- data: {
5914
- [rootKey]: updatedRoot
5915
- }
5916
- };
5917
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleComp && candLocaleComp !== "null" && candLocaleComp !== "undefined") {
5918
- updateArgsComp.locale = candLocaleComp;
5919
- }
5920
- await strapi.documents(target.uid).update(updateArgsComp);
5921
- if (shouldPublishComp) {
5922
- try {
5923
- const pubArgs = {
5924
- documentId: target.documentId
5925
- };
5926
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleComp && candLocaleComp !== "null" && candLocaleComp !== "undefined") {
5927
- pubArgs.locale = candLocaleComp;
5928
- }
5929
- await strapi.documents(target.uid).publish(pubArgs);
5930
- } catch (publishErr) {
5931
- strapi.log.warn(`[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}:`, publishErr);
5932
- }
6383
+ } catch (updateErr) {
6384
+ const formattedErr = formatErrorWithCause(updateErr, "Failed to update record");
6385
+ if (isFetchFailedError(updateErr)) {
6386
+ strapi.log?.error?.(
6387
+ `[bulk-updater] Network/webhook fetch error during batch ${batchId} update of ${target.uid}/${target.documentId}: ${formattedErr}`
6388
+ );
5933
6389
  }
5934
- invalidateCollectionCache(target.uid);
5935
- await recordContentHistoryVersion(strapi, {
5936
- uid: target.uid,
5937
- documentId: target.documentId,
5938
- userId: currentUser?.id,
5939
- statusOverride: shouldPublishComp ? "published" : isDraftAndPublishComp ? hadPubComp ? "modified" : "draft" : void 0
5940
- });
5941
- const dzDiffs = isRootDz && affectedMatches.length > 0 ? affectedMatches.map((m) => ({
5942
- index: m.index,
5943
- componentUid: m.componentUid,
5944
- componentName: m.componentName,
5945
- attribute: `${rootKey}[#${m.index} ${m.componentName}].${parts.slice(1).join(".")}`,
5946
- oldValue: m.value,
5947
- newValue: regexObj && typeof m.value === "string" ? m.value.replace(regexObj, value) : value
5948
- })) : [];
5949
6390
  return {
5950
6391
  uid: target.uid,
5951
6392
  collectionName: displayName,
5952
6393
  documentId: target.documentId,
5953
- label: entryLabel,
6394
+ label: `Entry #${target.documentId}`,
5954
6395
  attribute,
5955
- oldValue: currentVal2 ?? null,
5956
- newValue: newValue2,
5957
- status: "updated",
5958
- message: isRootDz ? `Successfully updated ${affectedMatches.length} dynamic zone item(s) in ${attribute}` : `Successfully updated nested field ${attribute}`,
5959
- dynamicZoneDiffs: dzDiffs
6396
+ status: "error",
6397
+ message: formattedErr
5960
6398
  };
5961
6399
  }
5962
- if (attrDef.type === "relation") {
5963
- const isMulti = attrDef.relation === "oneToMany" || attrDef.relation === "manyToMany";
5964
- const currentEntryWithPopulate = await strapi.documents(target.uid).findOne({
5965
- documentId: target.documentId,
5966
- populate: [attribute]
6400
+ });
6401
+ const chunkResults = await Promise.all(chunkPromises);
6402
+ for (const res of chunkResults) {
6403
+ if (res.status === "updated") updatedCount++;
6404
+ else if (res.status === "skipped") skippedCount++;
6405
+ results.push(res);
6406
+ }
6407
+ jobState.processedCount = results.length;
6408
+ jobState.updatedCount = updatedCount;
6409
+ jobState.skippedCount = skippedCount;
6410
+ jobState.failedCount = results.filter((r) => r.status === "error").length;
6411
+ if (i + CHUNK_SIZE < targets.length) {
6412
+ await new Promise((resolve) => setImmediate(resolve));
6413
+ }
6414
+ }
6415
+ const affectedUids = new Set(targets.map((t) => t.uid));
6416
+ affectedUids.forEach((uid) => {
6417
+ invalidateCollectionCache(uid);
6418
+ });
6419
+ const failedCount = results.filter((r) => r.status === "error").length;
6420
+ jobState.failedCount = failedCount;
6421
+ jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6422
+ jobState.isLive = updatedCount > 0;
6423
+ jobState.status = failedCount === 0 && updatedCount > 0 ? "successful" : failedCount > 0 && updatedCount > 0 ? "partial_failure" : failedCount > 0 ? "failed" : "successful";
6424
+ jobState.results = results.map((r) => ({
6425
+ ...r,
6426
+ isLive: r.status === "updated"
6427
+ }));
6428
+ const flattenedDiffs = [];
6429
+ for (const r of results) {
6430
+ if (effectiveEditMode === "grid") {
6431
+ flattenedDiffs.push(r);
6432
+ } else if (r.dynamicZoneDiffs && r.dynamicZoneDiffs.length > 0) {
6433
+ for (const dz of r.dynamicZoneDiffs) {
6434
+ flattenedDiffs.push({
6435
+ uid: r.uid,
6436
+ collectionName: r.collectionName,
6437
+ documentId: r.documentId,
6438
+ locale: r.locale,
6439
+ label: `${r.label} [Block #${dz.index} (${dz.componentName})]`,
6440
+ attribute: dz.attribute,
6441
+ oldValue: dz.oldValue,
6442
+ newValue: dz.newValue,
6443
+ status: "updated",
6444
+ previousStatus: r.previousStatus,
6445
+ hadPublishedVersion: r.hadPublishedVersion,
6446
+ isDraftAndPublish: r.isDraftAndPublish,
6447
+ message: `Updated ${dz.attribute}`
5967
6448
  });
5968
- const currentRel = currentEntryWithPopulate?.[attribute];
5969
- let oldDocIds = [];
5970
- let oldDisplay = "";
5971
- if (isMulti && Array.isArray(currentRel)) {
5972
- oldDocIds = currentRel.map((r) => r.documentId).filter(Boolean);
5973
- oldDisplay = currentRel.map((r) => r.name || r.title || r.email || r.documentId).join(", ") || "(empty)";
5974
- } else if (currentRel) {
5975
- oldDocIds = currentRel.documentId ? [currentRel.documentId] : [];
5976
- oldDisplay = currentRel.name || currentRel.title || currentRel.email || currentRel.documentId || "(empty)";
5977
- } else {
5978
- oldDisplay = "(unlinked / none)";
5979
- }
5980
- let mode = "set";
5981
- let targetDocIds = [];
5982
- let newDisplay = "";
5983
- if (value === "__clear__" || value === "") {
5984
- mode = "clear";
5985
- newDisplay = "(cleared / unlinked)";
5986
- } else {
5987
- try {
5988
- const parsed2 = JSON.parse(value);
5989
- if (parsed2 && typeof parsed2 === "object" && parsed2.mode) {
5990
- mode = parsed2.mode;
5991
- targetDocIds = Array.isArray(parsed2.documentIds) ? parsed2.documentIds : parsed2.documentId ? [parsed2.documentId] : [];
5992
- newDisplay = parsed2.label || targetDocIds.join(", ") || `[${mode}]`;
5993
- } else if (Array.isArray(parsed2)) {
5994
- targetDocIds = parsed2;
5995
- newDisplay = targetDocIds.join(", ");
5996
- } else {
5997
- targetDocIds = [value];
5998
- newDisplay = value;
5999
- }
6000
- } catch {
6001
- targetDocIds = [value];
6002
- newDisplay = value;
6003
- }
6004
- }
6005
- let relationPayload;
6006
- if (mode === "clear") {
6007
- relationPayload = isMulti ? { set: [] } : null;
6008
- } else if (mode === "set") {
6009
- relationPayload = isMulti ? { set: targetDocIds } : targetDocIds[0] || null;
6010
- } else if (mode === "connect") {
6011
- relationPayload = { connect: targetDocIds };
6012
- } else if (mode === "disconnect") {
6013
- relationPayload = { disconnect: targetDocIds };
6014
- }
6015
- const isDraftAndPublishRel = Boolean(contentType?.options?.draftAndPublish);
6016
- const candLocaleRel = target.locale || currentEntry?.locale;
6017
- let pubRecordRel = candLocaleRel && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleRel}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6018
- if (!pubRecordRel && isDraftAndPublishRel && target.documentId) {
6019
- try {
6020
- const singlePub = await strapi.documents(target.uid).findMany({
6021
- status: "published",
6022
- filters: { documentId: target.documentId },
6023
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6024
- limit: 1
6025
- });
6026
- if (singlePub && singlePub.length > 0) {
6027
- pubRecordRel = singlePub[0];
6028
- publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordRel);
6029
- }
6030
- } catch {
6031
- }
6032
- }
6033
- const inspectionTargetRel = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6034
- const { hadPublishedVersion: hadPubRel } = resolveRecordPublicationStatus(
6035
- inspectionTargetRel,
6036
- pubRecordRel,
6037
- isDraftAndPublishRel
6038
- );
6039
- const isEditingRel = isRowInEditingStage$1(inspectionTargetRel) || isRowInEditingStage$1(target);
6040
- const shouldPublishRel = evaluateShouldPublish({
6041
- isDraftAndPublish: isDraftAndPublishRel,
6042
- hadPublishedVersion: hadPubRel,
6043
- isEditing: isEditingRel,
6044
- publishOnApproval: Boolean(publishOnApproval),
6045
- publishStrategy,
6046
- unreviewedConsent
6047
- });
6048
- const proposedEntityRel = deepMergeEntities(currentEntry, { [attribute]: relationPayload });
6049
- const valResultRel = await validateEntityQuotas(strapi, target.uid, proposedEntityRel);
6050
- if (!valResultRel.isValid) {
6051
- return {
6052
- uid: target.uid,
6053
- collectionName: displayName,
6054
- documentId: target.documentId,
6055
- label: entryLabel,
6056
- attribute,
6057
- oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
6058
- newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
6059
- status: "error",
6060
- message: valResultRel.errorMessage
6061
- };
6062
- }
6063
- const updateArgsRel = {
6064
- documentId: target.documentId,
6065
- data: {
6066
- [attribute]: relationPayload
6067
- }
6068
- };
6069
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleRel && candLocaleRel !== "null" && candLocaleRel !== "undefined") {
6070
- updateArgsRel.locale = candLocaleRel;
6071
- }
6072
- await strapi.documents(target.uid).update(updateArgsRel);
6073
- if (shouldPublishRel) {
6074
- try {
6075
- const pubArgs = {
6076
- documentId: target.documentId
6077
- };
6078
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleRel && candLocaleRel !== "null" && candLocaleRel !== "undefined") {
6079
- pubArgs.locale = candLocaleRel;
6080
- }
6081
- await strapi.documents(target.uid).publish(pubArgs);
6082
- } catch (publishErr) {
6083
- strapi.log.warn(`[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}:`, publishErr);
6084
- }
6085
- }
6086
- invalidateCollectionCache(target.uid);
6087
- if (attrDef.target) {
6088
- invalidateCollectionCache(attrDef.target);
6089
- }
6090
- await recordContentHistoryVersion(strapi, {
6091
- uid: target.uid,
6092
- documentId: target.documentId,
6093
- userId: currentUser?.id,
6094
- statusOverride: shouldPublishRel ? "published" : isDraftAndPublishRel ? hadPubRel ? "modified" : "draft" : void 0
6095
- });
6096
- return {
6097
- uid: target.uid,
6098
- collectionName: displayName,
6099
- documentId: target.documentId,
6100
- label: entryLabel,
6101
- attribute,
6102
- oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
6103
- newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
6104
- status: "updated",
6105
- message: `Successfully updated relation "${attribute}"`
6106
- };
6107
- }
6108
- let newValue = value;
6109
- const currentVal = currentEntry?.[attribute];
6110
- if (regexObj && typeof currentVal === "string") {
6111
- newValue = currentVal.replace(regexObj, value);
6112
- }
6113
- const isDraftAndPublishScalar = Boolean(contentType?.options?.draftAndPublish);
6114
- const candLocaleScalar = target.locale || currentEntry?.locale;
6115
- let pubRecordScalar = candLocaleScalar && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleScalar}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6116
- if (!pubRecordScalar && isDraftAndPublishScalar && target.documentId) {
6117
- try {
6118
- const singlePub = await strapi.documents(target.uid).findMany({
6119
- status: "published",
6120
- filters: { documentId: target.documentId },
6121
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6122
- limit: 1
6123
- });
6124
- if (singlePub && singlePub.length > 0) {
6125
- pubRecordScalar = singlePub[0];
6126
- publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordScalar);
6127
- }
6128
- } catch {
6129
- }
6130
- }
6131
- const inspectionTargetScalar = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6132
- const { hadPublishedVersion: hadPubScalar } = resolveRecordPublicationStatus(
6133
- inspectionTargetScalar,
6134
- pubRecordScalar,
6135
- isDraftAndPublishScalar
6136
- );
6137
- const isEditingScalar = isRowInEditingStage$1(inspectionTargetScalar) || isRowInEditingStage$1(target);
6138
- const shouldPublishScalar = evaluateShouldPublish({
6139
- isDraftAndPublish: isDraftAndPublishScalar,
6140
- hadPublishedVersion: hadPubScalar,
6141
- isEditing: isEditingScalar,
6142
- publishOnApproval: Boolean(publishOnApproval),
6143
- publishStrategy,
6144
- unreviewedConsent
6145
- });
6146
- const proposedEntityScalar = deepMergeEntities(currentEntry, { [attribute]: newValue });
6147
- const valResultScalar = await validateEntityQuotas(strapi, target.uid, proposedEntityScalar);
6148
- if (!valResultScalar.isValid) {
6149
- return {
6150
- uid: target.uid,
6151
- collectionName: displayName,
6152
- documentId: target.documentId,
6153
- label: entryLabel,
6154
- attribute,
6155
- oldValue: currentVal ?? null,
6156
- newValue,
6157
- status: "error",
6158
- message: valResultScalar.errorMessage
6159
- };
6160
6449
  }
6161
- const updateArgsScalar = {
6162
- documentId: target.documentId,
6163
- data: {
6164
- [attribute]: newValue
6165
- }
6166
- };
6167
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
6168
- updateArgsScalar.locale = candLocaleScalar;
6169
- }
6170
- await strapi.documents(target.uid).update(updateArgsScalar);
6171
- if (shouldPublishScalar) {
6172
- try {
6173
- const pubArgs = {
6174
- documentId: target.documentId
6175
- };
6176
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
6177
- pubArgs.locale = candLocaleScalar;
6178
- }
6179
- await strapi.documents(target.uid).publish(pubArgs);
6180
- } catch (publishErr) {
6181
- strapi.log.warn(`[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}:`, publishErr);
6182
- }
6183
- }
6184
- await recordContentHistoryVersion(strapi, {
6185
- uid: target.uid,
6186
- documentId: target.documentId,
6187
- userId: currentUser?.id,
6188
- statusOverride: shouldPublishScalar ? "published" : isDraftAndPublishScalar ? hadPubScalar ? "modified" : "draft" : void 0
6189
- });
6190
- return {
6191
- uid: target.uid,
6192
- collectionName: displayName,
6193
- documentId: target.documentId,
6194
- label: entryLabel,
6195
- attribute,
6196
- oldValue: currentVal ?? null,
6197
- newValue,
6198
- status: "updated",
6199
- message: `Successfully updated ${attribute}`
6200
- };
6201
6450
  } else {
6202
- return {
6203
- uid: target.uid,
6204
- collectionName: displayName,
6205
- documentId: target.documentId,
6206
- label: entryLabel,
6207
- attribute,
6208
- status: "skipped",
6209
- message: `Skipped: Attribute "${attribute}" does not exist in schema for ${displayName}`
6210
- };
6451
+ flattenedDiffs.push(r);
6211
6452
  }
6212
- } catch (updateErr) {
6213
- return {
6214
- uid: target.uid,
6215
- collectionName: displayName,
6216
- documentId: target.documentId,
6217
- label: `Entry #${target.documentId}`,
6218
- attribute,
6219
- status: "error",
6220
- message: updateErr.message
6221
- };
6222
6453
  }
6223
- });
6224
- const chunkResults = await Promise.all(chunkPromises);
6225
- for (const res of chunkResults) {
6226
- if (res.status === "updated") updatedCount++;
6227
- else if (res.status === "skipped") skippedCount++;
6228
- results.push(res);
6229
- }
6230
- jobState.processedCount = results.length;
6231
- jobState.updatedCount = updatedCount;
6232
- jobState.skippedCount = skippedCount;
6233
- jobState.failedCount = results.filter((r) => r.status === "error").length;
6234
- }
6235
- const affectedUids = new Set(targets.map((t) => t.uid));
6236
- affectedUids.forEach((uid) => {
6237
- invalidateCollectionCache(uid);
6238
- });
6239
- const failedCount = results.filter((r) => r.status === "error").length;
6240
- jobState.failedCount = failedCount;
6241
- jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6242
- jobState.isLive = updatedCount > 0;
6243
- jobState.status = failedCount === 0 && updatedCount > 0 ? "successful" : failedCount > 0 && updatedCount > 0 ? "partial_failure" : failedCount > 0 ? "failed" : "successful";
6244
- jobState.results = results.map((r) => ({
6245
- ...r,
6246
- isLive: r.status === "updated"
6247
- }));
6248
- const flattenedDiffs = [];
6249
- for (const r of results) {
6250
- if (effectiveEditMode === "grid") {
6251
- flattenedDiffs.push(r);
6252
- } else if (r.dynamicZoneDiffs && r.dynamicZoneDiffs.length > 0) {
6253
- for (const dz of r.dynamicZoneDiffs) {
6254
- flattenedDiffs.push({
6255
- uid: r.uid,
6256
- collectionName: r.collectionName,
6257
- documentId: r.documentId,
6258
- label: `${r.label} [Block #${dz.index} (${dz.componentName})]`,
6259
- attribute: dz.attribute,
6260
- oldValue: dz.oldValue,
6261
- newValue: dz.newValue,
6262
- status: "updated",
6263
- message: `Updated ${dz.attribute}`
6264
- });
6454
+ const batchSummary = {
6455
+ batchId,
6456
+ attribute,
6457
+ value: effectiveSummaryVal,
6458
+ editMode: effectiveEditMode,
6459
+ updatedCount,
6460
+ skippedCount,
6461
+ totalTargets: targets.length,
6462
+ publishOnApproval,
6463
+ publishStrategy,
6464
+ unreviewedConsent
6465
+ };
6466
+ try {
6467
+ await strapi.plugin("bulk-updater").service("audit").recordBatch(
6468
+ batchSummary,
6469
+ flattenedDiffs,
6470
+ currentUser
6471
+ );
6472
+ } catch (auditErr) {
6473
+ strapi.log?.warn?.(
6474
+ `[bulk-updater] Non-fatal audit logging failure for batch ${batchId}: ${formatErrorWithCause(auditErr)}`
6475
+ );
6265
6476
  }
6266
- } else {
6267
- flattenedDiffs.push(r);
6477
+ return {
6478
+ success: true,
6479
+ batchId,
6480
+ attribute,
6481
+ value: effectiveSummaryVal,
6482
+ editMode: effectiveEditMode,
6483
+ updatedCount,
6484
+ skippedCount,
6485
+ failedCount,
6486
+ totalTargets: targets.length,
6487
+ isLive: jobState.isLive,
6488
+ status: jobState.status,
6489
+ results
6490
+ };
6491
+ } catch (fatalErr) {
6492
+ const formattedFatal = formatErrorWithCause(fatalErr, "Batch execution failed");
6493
+ jobState.status = "failed";
6494
+ jobState.error = formattedFatal;
6495
+ jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6496
+ strapi.log?.error?.(`[bulk-updater] Batch ${batchId} aborted with error: ${formattedFatal}`);
6497
+ throw fatalErr;
6268
6498
  }
6269
- }
6270
- const batchSummary = {
6271
- batchId,
6272
- attribute,
6273
- value: effectiveSummaryVal,
6274
- editMode: effectiveEditMode,
6275
- updatedCount,
6276
- skippedCount,
6277
- totalTargets: targets.length,
6278
- publishOnApproval,
6279
- publishStrategy,
6280
- unreviewedConsent
6281
- };
6282
- await strapi.plugin("bulk-updater").service("audit").recordBatch(
6283
- batchSummary,
6284
- flattenedDiffs,
6285
- currentUser
6286
- );
6287
- return {
6288
- success: true,
6289
- batchId,
6290
- attribute,
6291
- value: effectiveSummaryVal,
6292
- editMode: effectiveEditMode,
6293
- updatedCount,
6294
- skippedCount,
6295
- failedCount,
6296
- totalTargets: targets.length,
6297
- isLive: jobState.isLive,
6298
- status: jobState.status,
6299
- results
6300
- };
6499
+ });
6301
6500
  }
6302
6501
  async function executePublishBatchInternal(strapi, {
6303
6502
  selectedEntries = [],
@@ -6351,120 +6550,146 @@ async function executePublishBatchInternal(strapi, {
6351
6550
  results: []
6352
6551
  };
6353
6552
  batchJobsMap.set(batchId, jobState);
6354
- const targets = Array.from(targetsMap.values());
6355
- const CHUNK_SIZE = 25;
6356
- for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
6357
- const chunk = targets.slice(i, i + CHUNK_SIZE);
6358
- const chunkPromises = chunk.map(async (target) => {
6359
- try {
6360
- const contentType = strapi.contentTypes[target.uid];
6361
- const displayName = contentType?.info?.displayName || target.uid;
6362
- const isDraftAndPublish = Boolean(contentType?.options?.draftAndPublish);
6363
- let existingDoc = null;
6364
- try {
6365
- existingDoc = await strapi.documents(target.uid).findOne({
6366
- documentId: target.documentId
6367
- });
6368
- } catch {
6369
- existingDoc = null;
6370
- }
6371
- const entryLabel = existingDoc?.name || existingDoc?.title || existingDoc?.label || existingDoc?.documentId || `Entry #${target.documentId}`;
6372
- if (!isDraftAndPublish) {
6373
- return {
6374
- uid: target.uid,
6375
- collectionName: displayName,
6376
- documentId: target.documentId,
6377
- label: entryLabel,
6378
- attribute: "(publish)",
6379
- status: "skipped",
6380
- message: `Skipped: Draft & Publish is disabled for collection ${displayName}`
6381
- };
6382
- }
6383
- const isAlreadyPublished = Boolean(existingDoc?.publishedAt);
6384
- await strapi.documents(target.uid).publish({
6385
- documentId: target.documentId
6386
- });
6387
- invalidateCollectionCache(target.uid);
6388
- await recordContentHistoryVersion(strapi, {
6389
- uid: target.uid,
6390
- documentId: target.documentId,
6391
- userId: currentUser?.id,
6392
- statusOverride: "published"
6553
+ return await trackActiveBulkOperation(async () => {
6554
+ try {
6555
+ const targets = Array.from(targetsMap.values());
6556
+ const CHUNK_SIZE = getBatchConcurrency(strapi);
6557
+ for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
6558
+ const chunk = targets.slice(i, i + CHUNK_SIZE);
6559
+ const chunkPromises = chunk.map(async (target) => {
6560
+ try {
6561
+ const contentType = strapi.contentTypes[target.uid];
6562
+ const displayName = contentType?.info?.displayName || target.uid;
6563
+ const isDraftAndPublish = Boolean(contentType?.options?.draftAndPublish);
6564
+ let existingDoc = null;
6565
+ try {
6566
+ existingDoc = await strapi.documents(target.uid).findOne({
6567
+ documentId: target.documentId
6568
+ });
6569
+ } catch {
6570
+ existingDoc = null;
6571
+ }
6572
+ const entryLabel = existingDoc?.name || existingDoc?.title || existingDoc?.label || existingDoc?.documentId || `Entry #${target.documentId}`;
6573
+ if (!isDraftAndPublish) {
6574
+ return {
6575
+ uid: target.uid,
6576
+ collectionName: displayName,
6577
+ documentId: target.documentId,
6578
+ label: entryLabel,
6579
+ attribute: "(publish)",
6580
+ status: "skipped",
6581
+ message: `Skipped: Draft & Publish is disabled for collection ${displayName}`
6582
+ };
6583
+ }
6584
+ const isAlreadyPublished = Boolean(existingDoc?.publishedAt);
6585
+ await strapi.documents(target.uid).publish({
6586
+ documentId: target.documentId
6587
+ });
6588
+ invalidateCollectionCache(target.uid);
6589
+ await recordContentHistoryVersion(strapi, {
6590
+ uid: target.uid,
6591
+ documentId: target.documentId,
6592
+ userId: currentUser?.id,
6593
+ statusOverride: "published"
6594
+ });
6595
+ return {
6596
+ uid: target.uid,
6597
+ collectionName: displayName,
6598
+ documentId: target.documentId,
6599
+ label: entryLabel,
6600
+ attribute: "(publish)",
6601
+ oldValue: isAlreadyPublished ? "published" : "draft",
6602
+ newValue: "published",
6603
+ status: "updated",
6604
+ message: isAlreadyPublished ? "Re-published latest version live" : "Successfully published to live"
6605
+ };
6606
+ } catch (pubErr) {
6607
+ const formattedPubErr = formatErrorWithCause(pubErr, "Failed to publish entry");
6608
+ if (isFetchFailedError(pubErr)) {
6609
+ strapi.log?.error?.(
6610
+ `[bulk-updater] Network/webhook fetch error during batch publish ${batchId} of ${target.uid}/${target.documentId}: ${formattedPubErr}`
6611
+ );
6612
+ }
6613
+ return {
6614
+ uid: target.uid,
6615
+ collectionName: strapi.contentTypes[target.uid]?.info?.displayName || target.uid,
6616
+ documentId: target.documentId,
6617
+ label: `Entry #${target.documentId}`,
6618
+ attribute: "(publish)",
6619
+ status: "error",
6620
+ message: formattedPubErr
6621
+ };
6622
+ }
6393
6623
  });
6394
- return {
6395
- uid: target.uid,
6396
- collectionName: displayName,
6397
- documentId: target.documentId,
6398
- label: entryLabel,
6399
- attribute: "(publish)",
6400
- oldValue: isAlreadyPublished ? "published" : "draft",
6401
- newValue: "published",
6402
- status: "updated",
6403
- message: isAlreadyPublished ? "Re-published latest version live" : "Successfully published to live"
6404
- };
6405
- } catch (pubErr) {
6406
- return {
6407
- uid: target.uid,
6408
- collectionName: strapi.contentTypes[target.uid]?.info?.displayName || target.uid,
6409
- documentId: target.documentId,
6410
- label: `Entry #${target.documentId}`,
6411
- attribute: "(publish)",
6412
- status: "error",
6413
- message: pubErr.message || "Failed to publish entry"
6414
- };
6624
+ const chunkResults = await Promise.all(chunkPromises);
6625
+ for (const res of chunkResults) {
6626
+ if (res.status === "updated") publishedCount++;
6627
+ else if (res.status === "skipped") skippedCount++;
6628
+ results.push(res);
6629
+ }
6630
+ jobState.processedCount = results.length;
6631
+ jobState.updatedCount = publishedCount;
6632
+ jobState.skippedCount = skippedCount;
6633
+ jobState.failedCount = results.filter((r) => r.status === "error").length;
6634
+ if (i + CHUNK_SIZE < targets.length) {
6635
+ await new Promise((resolve) => setImmediate(resolve));
6636
+ }
6637
+ }
6638
+ const affectedUids = new Set(targets.map((t) => t.uid));
6639
+ affectedUids.forEach((uid) => {
6640
+ invalidateCollectionCache(uid);
6641
+ });
6642
+ const failedCount = results.filter((r) => r.status === "error").length;
6643
+ jobState.failedCount = failedCount;
6644
+ jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6645
+ jobState.isLive = publishedCount > 0;
6646
+ jobState.status = failedCount === 0 && publishedCount > 0 ? "successful" : failedCount > 0 && publishedCount > 0 ? "partial_failure" : failedCount > 0 ? "failed" : "successful";
6647
+ jobState.results = results.map((r) => ({
6648
+ ...r,
6649
+ isLive: r.status === "updated"
6650
+ }));
6651
+ const batchSummary = {
6652
+ batchId,
6653
+ attribute: "(publish)",
6654
+ value: "published",
6655
+ updatedCount: publishedCount,
6656
+ skippedCount,
6657
+ totalTargets: targetsMap.size,
6658
+ publishOnApproval: true,
6659
+ unreviewedConsent
6660
+ };
6661
+ try {
6662
+ await strapi.plugin("bulk-updater").service("audit").recordBatch(
6663
+ batchSummary,
6664
+ results,
6665
+ currentUser
6666
+ );
6667
+ } catch (auditErr) {
6668
+ strapi.log?.warn?.(
6669
+ `[bulk-updater] Non-fatal audit logging failure for publish batch ${batchId}: ${formatErrorWithCause(auditErr)}`
6670
+ );
6415
6671
  }
6416
- });
6417
- const chunkResults = await Promise.all(chunkPromises);
6418
- for (const res of chunkResults) {
6419
- if (res.status === "updated") publishedCount++;
6420
- else if (res.status === "skipped") skippedCount++;
6421
- results.push(res);
6422
- }
6423
- jobState.processedCount = results.length;
6424
- jobState.updatedCount = publishedCount;
6425
- jobState.skippedCount = skippedCount;
6426
- jobState.failedCount = results.filter((r) => r.status === "error").length;
6427
- }
6428
- const affectedUids = new Set(targets.map((t) => t.uid));
6429
- affectedUids.forEach((uid) => {
6430
- invalidateCollectionCache(uid);
6672
+ return {
6673
+ success: true,
6674
+ batchId,
6675
+ publishedCount,
6676
+ updatedCount: publishedCount,
6677
+ skippedCount,
6678
+ failedCount,
6679
+ totalTargets: targetsMap.size,
6680
+ isLive: publishedCount > 0,
6681
+ status: jobState.status,
6682
+ results
6683
+ };
6684
+ } catch (fatalErr) {
6685
+ const formattedFatal = formatErrorWithCause(fatalErr, "Batch publish failed");
6686
+ jobState.status = "failed";
6687
+ jobState.error = formattedFatal;
6688
+ jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6689
+ strapi.log?.error?.(`[bulk-updater] Publish batch ${batchId} aborted with error: ${formattedFatal}`);
6690
+ throw fatalErr;
6691
+ }
6431
6692
  });
6432
- const failedCount = results.filter((r) => r.status === "error").length;
6433
- jobState.failedCount = failedCount;
6434
- jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6435
- jobState.isLive = publishedCount > 0;
6436
- jobState.status = failedCount === 0 && publishedCount > 0 ? "successful" : failedCount > 0 && publishedCount > 0 ? "partial_failure" : failedCount > 0 ? "failed" : "successful";
6437
- jobState.results = results.map((r) => ({
6438
- ...r,
6439
- isLive: r.status === "updated"
6440
- }));
6441
- const batchSummary = {
6442
- batchId,
6443
- attribute: "(publish)",
6444
- value: "published",
6445
- updatedCount: publishedCount,
6446
- skippedCount,
6447
- totalTargets: targetsMap.size,
6448
- publishOnApproval: true,
6449
- unreviewedConsent
6450
- };
6451
- await strapi.plugin("bulk-updater").service("audit").recordBatch(
6452
- batchSummary,
6453
- results,
6454
- currentUser
6455
- );
6456
- return {
6457
- success: true,
6458
- batchId,
6459
- publishedCount,
6460
- updatedCount: publishedCount,
6461
- skippedCount,
6462
- failedCount,
6463
- totalTargets: targetsMap.size,
6464
- isLive: publishedCount > 0,
6465
- status: jobState.status,
6466
- results
6467
- };
6468
6693
  }
6469
6694
  async function executeBatchByPayload(strapi, batch, currentUser) {
6470
6695
  if (batch.payload?.action === "csv_import") {
@@ -8841,21 +9066,20 @@ const auditService = ({ strapi }) => ({
8841
9066
  const isDynamicZone = rootAttrDef?.type === "dynamiczone";
8842
9067
  const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
8843
9068
  const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
8844
- let wasPublished = false;
9069
+ const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
9070
+ const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
9071
+ const findOneArgs = { documentId: item.documentId };
9072
+ if (populateOption) {
9073
+ findOneArgs.populate = populateOption;
9074
+ }
9075
+ if (isLocalized) {
9076
+ findOneArgs.locale = item.locale;
9077
+ }
9078
+ const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
9079
+ if (!currentDoc) {
9080
+ throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
9081
+ }
8845
9082
  if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
8846
- const populateOption = buildDeepPopulate(ct.attributes, strapi.components);
8847
- const findOneArgs = { documentId: item.documentId };
8848
- if (populateOption) {
8849
- findOneArgs.populate = populateOption;
8850
- }
8851
- if (isLocalized) {
8852
- findOneArgs.locale = item.locale;
8853
- }
8854
- const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
8855
- if (!currentDoc) {
8856
- throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
8857
- }
8858
- wasPublished = Boolean(currentDoc?.publishedAt);
8859
9083
  const isRootDz = isDynamicZone;
8860
9084
  const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
8861
9085
  let restoredRoot;
@@ -8921,11 +9145,6 @@ const auditService = ({ strapi }) => ({
8921
9145
  }
8922
9146
  });
8923
9147
  } else {
8924
- const currentDoc = await strapi.documents(item.uid).findOne({
8925
- documentId: item.documentId,
8926
- ...isLocalized ? { locale: item.locale } : {}
8927
- });
8928
- wasPublished = Boolean(currentDoc?.publishedAt);
8929
9148
  await strapi.documents(item.uid).update({
8930
9149
  documentId: item.documentId,
8931
9150
  ...isLocalized ? { locale: item.locale } : {},
@@ -8934,14 +9153,85 @@ const auditService = ({ strapi }) => ({
8934
9153
  }
8935
9154
  });
8936
9155
  }
8937
- if (ct?.options?.draftAndPublish && wasPublished) {
9156
+ let targetStatus = void 0;
9157
+ if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
9158
+ targetStatus = item.previousStatus;
9159
+ } else if (item.hadPublishedVersion === false) {
9160
+ targetStatus = "draft";
9161
+ } else if (item.hadPublishedVersion === true) {
9162
+ targetStatus = "published";
9163
+ }
9164
+ if (isDraftAndPublish && !targetStatus) {
9165
+ let publishedCounterpart = null;
8938
9166
  try {
8939
- await strapi.documents(item.uid).publish({
8940
- documentId: item.documentId,
8941
- ...isLocalized ? { locale: item.locale } : {}
8942
- });
8943
- } catch (publishErr) {
8944
- strapi.log.warn(`[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`, publishErr?.message);
9167
+ const docSvc = strapi.documents(item.uid);
9168
+ if (typeof docSvc.findMany === "function") {
9169
+ const pubs = await docSvc.findMany({
9170
+ status: "published",
9171
+ filters: { documentId: item.documentId },
9172
+ fields: ["documentId", "publishedAt"],
9173
+ limit: 1,
9174
+ ...isLocalized ? { locale: item.locale } : {}
9175
+ });
9176
+ if (pubs && pubs.length > 0) {
9177
+ publishedCounterpart = pubs[0];
9178
+ }
9179
+ }
9180
+ } catch {
9181
+ }
9182
+ if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
9183
+ targetStatus = "published";
9184
+ } else {
9185
+ targetStatus = "draft";
9186
+ }
9187
+ }
9188
+ if (isDraftAndPublish) {
9189
+ const docSvc = strapi.documents(item.uid);
9190
+ if (targetStatus === "published") {
9191
+ try {
9192
+ if (typeof docSvc.publish === "function") {
9193
+ await docSvc.publish({
9194
+ documentId: item.documentId,
9195
+ ...isLocalized ? { locale: item.locale } : {}
9196
+ });
9197
+ }
9198
+ } catch (publishErr) {
9199
+ strapi.log.warn(
9200
+ `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
9201
+ publishErr?.message
9202
+ );
9203
+ }
9204
+ } else if (targetStatus === "draft") {
9205
+ try {
9206
+ if (typeof docSvc.unpublish === "function") {
9207
+ let hasPublished = false;
9208
+ if (typeof docSvc.findMany === "function") {
9209
+ const pubs = await docSvc.findMany({
9210
+ status: "published",
9211
+ filters: { documentId: item.documentId },
9212
+ fields: ["documentId", "publishedAt"],
9213
+ limit: 1,
9214
+ ...isLocalized ? { locale: item.locale } : {}
9215
+ });
9216
+ if (pubs && pubs.length > 0) {
9217
+ hasPublished = true;
9218
+ }
9219
+ } else if (currentDoc?.publishedAt) {
9220
+ hasPublished = true;
9221
+ }
9222
+ if (hasPublished) {
9223
+ await docSvc.unpublish({
9224
+ documentId: item.documentId,
9225
+ ...isLocalized ? { locale: item.locale } : {}
9226
+ });
9227
+ }
9228
+ }
9229
+ } catch (unpubErr) {
9230
+ strapi.log.warn(
9231
+ `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
9232
+ unpubErr?.message
9233
+ );
9234
+ }
8945
9235
  }
8946
9236
  }
8947
9237
  try {
@@ -8949,7 +9239,7 @@ const auditService = ({ strapi }) => ({
8949
9239
  uid: item.uid,
8950
9240
  documentId: item.documentId,
8951
9241
  userId,
8952
- statusOverride: ct?.options?.draftAndPublish ? wasPublished ? "published" : "draft" : void 0
9242
+ statusOverride: isDraftAndPublish ? targetStatus : "published"
8953
9243
  });
8954
9244
  } catch {
8955
9245
  }
@@ -8967,7 +9257,8 @@ const auditService = ({ strapi }) => ({
8967
9257
  label: item.label,
8968
9258
  attribute: item.attribute,
8969
9259
  revertedTo: item.oldValue,
8970
- status: "reverted"
9260
+ status: "reverted",
9261
+ restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
8971
9262
  });
8972
9263
  } catch (err) {
8973
9264
  rollbackDetails.push({
@@ -9682,6 +9973,9 @@ function extractDetailedErrorMessage(err) {
9682
9973
  if (err.details?.message) {
9683
9974
  return err.details.message;
9684
9975
  }
9976
+ if (isFetchFailedError(err) || err.cause) {
9977
+ return formatErrorWithCause(err, "Error processing row");
9978
+ }
9685
9979
  if (err.message && err.message !== "[object Object]") {
9686
9980
  return err.message;
9687
9981
  }
@@ -9911,7 +10205,7 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
9911
10205
  ...rowStatus ? { status: rowStatus } : {},
9912
10206
  ...rowPubAt ? { publishedAt: rowPubAt } : {}
9913
10207
  } : existing;
9914
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
10208
+ const { hadPublishedVersion, status: preStatus } = resolveRecordPublicationStatus(
9915
10209
  inspectionExisting,
9916
10210
  pubRecord,
9917
10211
  isDraftAndPublish
@@ -9962,7 +10256,9 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
9962
10256
  if (effectiveLocale) pubArgs.locale = effectiveLocale;
9963
10257
  await strapi.documents(uid).publish(pubArgs);
9964
10258
  } catch (pubErr) {
9965
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
10259
+ strapi.log.warn(
10260
+ `[bulk-updater] Auto-publish failed for ${uid}/${resolvedDocId}: ${formatErrorWithCause(pubErr)}`
10261
+ );
9966
10262
  }
9967
10263
  }
9968
10264
  try {
@@ -9996,11 +10292,15 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
9996
10292
  uid,
9997
10293
  collectionName: ct.info?.displayName || uid,
9998
10294
  documentId: resolvedDocId,
10295
+ locale: effectiveLocale,
9999
10296
  label: existing.title || existing.name || `Entry #${resolvedDocId}`,
10000
10297
  attribute: attrKey,
10001
10298
  oldValue: oldVal,
10002
10299
  newValue: newVal,
10003
10300
  status: "updated",
10301
+ previousStatus: preStatus,
10302
+ hadPublishedVersion,
10303
+ isDraftAndPublish,
10004
10304
  message: `${actionLabel} "${attrKey}" via CSV import (row ${rowNumber})`
10005
10305
  });
10006
10306
  }
@@ -10080,7 +10380,9 @@ async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, opt
10080
10380
  if (effectiveLocale) pubArgs.locale = effectiveLocale;
10081
10381
  await strapi.documents(uid).publish(pubArgs);
10082
10382
  } catch (pubErr) {
10083
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
10383
+ strapi.log.warn(
10384
+ `[bulk-updater] Auto-publish failed for ${uid}/${newDocId}: ${formatErrorWithCause(pubErr)}`
10385
+ );
10084
10386
  }
10085
10387
  }
10086
10388
  try {
@@ -10111,177 +10413,121 @@ async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, opt
10111
10413
  }
10112
10414
  }
10113
10415
  async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
10114
- ct.attributes || {};
10115
- const { mode = "auto", publish = true, publishStrategy = "safe", user, originalHeaders } = options;
10116
- const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
10117
- const docIdsInChunk = rows.map((r) => extractDocId(r)).filter(Boolean);
10118
- const publishedCounterparts = /* @__PURE__ */ new Map();
10119
- if (isDraftAndPublish && docIdsInChunk.length > 0) {
10120
- try {
10121
- const pubDocs = await strapi.documents(uid).findMany({
10122
- status: "published",
10123
- filters: { documentId: { $in: docIdsInChunk } },
10124
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
10125
- limit: Math.max(docIdsInChunk.length, 100)
10126
- });
10127
- for (const pub of pubDocs || []) {
10128
- if (pub?.documentId) {
10129
- publishedCounterparts.set(String(pub.documentId), pub);
10130
- if (pub.locale) {
10131
- publishedCounterparts.set(`${pub.documentId}@@@${pub.locale}`, pub);
10416
+ return await trackActiveBulkOperation(async () => {
10417
+ const attrs = ct.attributes || {};
10418
+ const { mode = "auto", publish = true, publishStrategy = "safe", user, originalHeaders } = options;
10419
+ const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
10420
+ const docIdsInChunk = rows.map((r) => extractDocId(r)).filter(Boolean);
10421
+ const publishedCounterparts = /* @__PURE__ */ new Map();
10422
+ if (isDraftAndPublish && docIdsInChunk.length > 0) {
10423
+ try {
10424
+ const pubDocs = await strapi.documents(uid).findMany({
10425
+ status: "published",
10426
+ filters: { documentId: { $in: docIdsInChunk } },
10427
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
10428
+ limit: Math.max(docIdsInChunk.length, 100)
10429
+ });
10430
+ for (const pub of pubDocs || []) {
10431
+ if (pub?.documentId) {
10432
+ publishedCounterparts.set(String(pub.documentId), pub);
10433
+ if (pub.locale) {
10434
+ publishedCounterparts.set(`${pub.documentId}@@@${pub.locale}`, pub);
10435
+ }
10132
10436
  }
10133
10437
  }
10438
+ } catch {
10134
10439
  }
10135
- } catch {
10136
10440
  }
10137
- }
10138
- const stats = {
10139
- total: rows.length,
10140
- created: 0,
10141
- updated: 0,
10142
- skipped: 0,
10143
- failed: 0,
10144
- newWithoutDocId: 0,
10145
- errors: [],
10146
- failedRows: [],
10147
- diffs: []
10148
- };
10149
- const batchModeInfo = detectCsvBatchExportMode(rows);
10150
- if (batchModeInfo.error) {
10441
+ const stats = {
10442
+ total: rows.length,
10443
+ created: 0,
10444
+ updated: 0,
10445
+ skipped: 0,
10446
+ failed: 0,
10447
+ newWithoutDocId: 0,
10448
+ errors: [],
10449
+ failedRows: [],
10450
+ diffs: []
10451
+ };
10452
+ const batchModeInfo = detectCsvBatchExportMode(rows);
10453
+ if (batchModeInfo.error) {
10454
+ for (let i = 0; i < rows.length; i++) {
10455
+ const rowNumber = startRowNumber + i;
10456
+ const row = rows[i];
10457
+ const docId = extractDocId(row);
10458
+ stats.skipped++;
10459
+ if (stats.failed !== void 0) stats.failed++;
10460
+ recordFailedCsvRow(
10461
+ stats,
10462
+ rowNumber,
10463
+ row,
10464
+ batchModeInfo.error,
10465
+ docId || void 0,
10466
+ originalHeaders
10467
+ );
10468
+ stats.diffs.push({
10469
+ uid,
10470
+ collectionName: ct.info?.displayName || uid,
10471
+ documentId: docId || `(Row #${rowNumber})`,
10472
+ label: `Row #${rowNumber}`,
10473
+ attribute: "__bulk_updater_metadata",
10474
+ oldValue: null,
10475
+ newValue: null,
10476
+ status: "error",
10477
+ message: batchModeInfo.error
10478
+ });
10479
+ }
10480
+ return stats;
10481
+ }
10482
+ const rowOptions = {
10483
+ ...options,
10484
+ expectedExportMode: batchModeInfo.mode
10485
+ };
10151
10486
  for (let i = 0; i < rows.length; i++) {
10152
10487
  const rowNumber = startRowNumber + i;
10153
10488
  const row = rows[i];
10154
- const docId = extractDocId(row);
10155
- stats.skipped++;
10156
- if (stats.failed !== void 0) stats.failed++;
10157
- recordFailedCsvRow(
10158
- stats,
10159
- rowNumber,
10160
- row,
10161
- batchModeInfo.error,
10162
- docId || void 0,
10163
- originalHeaders
10164
- );
10165
- stats.diffs.push({
10166
- uid,
10167
- collectionName: ct.info?.displayName || uid,
10168
- documentId: docId || `(Row #${rowNumber})`,
10169
- label: `Row #${rowNumber}`,
10170
- attribute: "__bulk_updater_metadata",
10171
- oldValue: null,
10172
- newValue: null,
10173
- status: "error",
10174
- message: batchModeInfo.error
10175
- });
10176
- }
10177
- return stats;
10178
- }
10179
- const rowOptions = {
10180
- ...options,
10181
- expectedExportMode: batchModeInfo.mode
10182
- };
10183
- for (let i = 0; i < rows.length; i++) {
10184
- const rowNumber = startRowNumber + i;
10185
- const row = rows[i];
10186
- let docId = extractDocId(row);
10187
- const rowLocale = extractLocale(row);
10188
- const effectiveLocale = getEffectiveLocale(ct, rowLocale);
10189
- const isEditing = isRowInEditingStage(row);
10190
- if (ct.kind === "singleType" && !docId) {
10191
- try {
10192
- const findSingleArgs = {};
10193
- if (effectiveLocale) findSingleArgs.locale = effectiveLocale;
10194
- const singleDoc = await strapi.documents(uid).findFirst(findSingleArgs);
10195
- if (singleDoc?.documentId) {
10196
- docId = singleDoc.documentId;
10489
+ let docId = extractDocId(row);
10490
+ const rowLocale = extractLocale(row);
10491
+ const effectiveLocale = getEffectiveLocale(ct, rowLocale);
10492
+ const isEditing = isRowInEditingStage(row);
10493
+ if (ct.kind === "singleType" && !docId) {
10494
+ try {
10495
+ const findSingleArgs = {};
10496
+ if (effectiveLocale) findSingleArgs.locale = effectiveLocale;
10497
+ const singleDoc = await strapi.documents(uid).findFirst(findSingleArgs);
10498
+ if (singleDoc?.documentId) {
10499
+ docId = singleDoc.documentId;
10500
+ }
10501
+ } catch {
10197
10502
  }
10198
- } catch {
10199
10503
  }
10200
- }
10201
- try {
10202
- if (mode === "update") {
10203
- if (!docId) {
10204
- stats.skipped++;
10205
- recordFailedCsvRow(
10206
- stats,
10207
- rowNumber,
10208
- row,
10209
- "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs).",
10210
- void 0,
10211
- originalHeaders
10212
- );
10213
- continue;
10214
- }
10215
- const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10216
- if (!existing) {
10217
- stats.skipped++;
10218
- recordFailedCsvRow(
10219
- stats,
10220
- rowNumber,
10221
- row,
10222
- `Document with ID "${docId}" not found in database.`,
10223
- docId,
10224
- originalHeaders
10225
- );
10226
- continue;
10227
- }
10228
- await executeUpdateMutation(
10229
- strapi,
10230
- ct,
10231
- uid,
10232
- existing,
10233
- row,
10234
- rowNumber,
10235
- rowOptions,
10236
- effectiveLocale,
10237
- isEditing,
10238
- isDraftAndPublish,
10239
- publishedCounterparts,
10240
- stats,
10241
- "Updated"
10242
- );
10243
- } else if (mode === "create_or_override") {
10244
- let existing = null;
10245
- if (docId) {
10246
- existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10247
- }
10248
- if (existing) {
10249
- await executeUpdateMutation(
10250
- strapi,
10251
- ct,
10252
- uid,
10253
- existing,
10254
- row,
10255
- rowNumber,
10256
- rowOptions,
10257
- effectiveLocale,
10258
- isEditing,
10259
- isDraftAndPublish,
10260
- publishedCounterparts,
10261
- stats,
10262
- "Overridden"
10263
- );
10264
- } else {
10265
- await executeCreateMutation(
10266
- strapi,
10267
- ct,
10268
- uid,
10269
- docId,
10270
- row,
10271
- rowNumber,
10272
- rowOptions,
10273
- effectiveLocale,
10274
- isEditing,
10275
- isDraftAndPublish,
10276
- stats
10277
- );
10278
- }
10279
- } else {
10280
- let existing = null;
10281
- if (docId) {
10282
- existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10283
- }
10284
- if (existing) {
10504
+ try {
10505
+ if (mode === "update") {
10506
+ if (!docId) {
10507
+ stats.skipped++;
10508
+ recordFailedCsvRow(
10509
+ stats,
10510
+ rowNumber,
10511
+ row,
10512
+ "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs).",
10513
+ void 0,
10514
+ originalHeaders
10515
+ );
10516
+ continue;
10517
+ }
10518
+ const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10519
+ if (!existing) {
10520
+ stats.skipped++;
10521
+ recordFailedCsvRow(
10522
+ stats,
10523
+ rowNumber,
10524
+ row,
10525
+ `Document with ID "${docId}" not found in database.`,
10526
+ docId,
10527
+ originalHeaders
10528
+ );
10529
+ continue;
10530
+ }
10285
10531
  await executeUpdateMutation(
10286
10532
  strapi,
10287
10533
  ct,
@@ -10297,48 +10543,114 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
10297
10543
  stats,
10298
10544
  "Updated"
10299
10545
  );
10546
+ } else if (mode === "create_or_override") {
10547
+ let existing = null;
10548
+ if (docId) {
10549
+ existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10550
+ }
10551
+ if (existing) {
10552
+ await executeUpdateMutation(
10553
+ strapi,
10554
+ ct,
10555
+ uid,
10556
+ existing,
10557
+ row,
10558
+ rowNumber,
10559
+ rowOptions,
10560
+ effectiveLocale,
10561
+ isEditing,
10562
+ isDraftAndPublish,
10563
+ publishedCounterparts,
10564
+ stats,
10565
+ "Overridden"
10566
+ );
10567
+ } else {
10568
+ await executeCreateMutation(
10569
+ strapi,
10570
+ ct,
10571
+ uid,
10572
+ docId,
10573
+ row,
10574
+ rowNumber,
10575
+ rowOptions,
10576
+ effectiveLocale,
10577
+ isEditing,
10578
+ isDraftAndPublish,
10579
+ stats
10580
+ );
10581
+ }
10300
10582
  } else {
10301
- await executeCreateMutation(
10302
- strapi,
10303
- ct,
10304
- uid,
10305
- docId,
10306
- row,
10307
- rowNumber,
10308
- rowOptions,
10309
- effectiveLocale,
10310
- isEditing,
10311
- isDraftAndPublish,
10312
- stats
10583
+ let existing = null;
10584
+ if (docId) {
10585
+ existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10586
+ }
10587
+ if (existing) {
10588
+ await executeUpdateMutation(
10589
+ strapi,
10590
+ ct,
10591
+ uid,
10592
+ existing,
10593
+ row,
10594
+ rowNumber,
10595
+ rowOptions,
10596
+ effectiveLocale,
10597
+ isEditing,
10598
+ isDraftAndPublish,
10599
+ publishedCounterparts,
10600
+ stats,
10601
+ "Updated"
10602
+ );
10603
+ } else {
10604
+ await executeCreateMutation(
10605
+ strapi,
10606
+ ct,
10607
+ uid,
10608
+ docId,
10609
+ row,
10610
+ rowNumber,
10611
+ rowOptions,
10612
+ effectiveLocale,
10613
+ isEditing,
10614
+ isDraftAndPublish,
10615
+ stats
10616
+ );
10617
+ }
10618
+ }
10619
+ } catch (err) {
10620
+ stats.skipped++;
10621
+ if (stats.failed !== void 0) stats.failed++;
10622
+ const errMsg = sanitizeUserErrorMessage(extractDetailedErrorMessage(err));
10623
+ if (isFetchFailedError(err)) {
10624
+ strapi.log?.error?.(
10625
+ `[bulk-updater] Network/webhook fetch error during CSV import row ${rowNumber} (${uid}/${docId || "new"}): ${errMsg}`
10313
10626
  );
10314
10627
  }
10628
+ recordFailedCsvRow(
10629
+ stats,
10630
+ rowNumber,
10631
+ row,
10632
+ errMsg,
10633
+ docId || void 0,
10634
+ originalHeaders
10635
+ );
10636
+ stats.diffs.push({
10637
+ uid,
10638
+ collectionName: ct.info?.displayName || uid,
10639
+ documentId: docId || `(Row #${rowNumber})`,
10640
+ label: `Row #${rowNumber}`,
10641
+ attribute: "(record)",
10642
+ oldValue: null,
10643
+ newValue: null,
10644
+ status: "error",
10645
+ message: `Failed to process row ${rowNumber}: ${errMsg}`
10646
+ });
10647
+ }
10648
+ if (i > 0 && i % 10 === 0) {
10649
+ await new Promise((resolve) => setImmediate(resolve));
10315
10650
  }
10316
- } catch (err) {
10317
- stats.skipped++;
10318
- if (stats.failed !== void 0) stats.failed++;
10319
- const errMsg = sanitizeUserErrorMessage(extractDetailedErrorMessage(err));
10320
- recordFailedCsvRow(
10321
- stats,
10322
- rowNumber,
10323
- row,
10324
- errMsg,
10325
- docId || void 0,
10326
- originalHeaders
10327
- );
10328
- stats.diffs.push({
10329
- uid,
10330
- collectionName: ct.info?.displayName || uid,
10331
- documentId: docId || `(Row #${rowNumber})`,
10332
- label: `Row #${rowNumber}`,
10333
- attribute: "(record)",
10334
- oldValue: null,
10335
- newValue: null,
10336
- status: "error",
10337
- message: `Failed to process row ${rowNumber}: ${errMsg}`
10338
- });
10339
10651
  }
10340
- }
10341
- return stats;
10652
+ return stats;
10653
+ });
10342
10654
  }
10343
10655
  async function recordCsvAuditLog(strapi, ct, uid, batchId, stats, user, publishOnApproval, publishStrategy, unreviewedConsent) {
10344
10656
  if (stats.updated === 0 && stats.created === 0) return;
@@ -11788,6 +12100,7 @@ const index = {
11788
12100
  });
11789
12101
  },
11790
12102
  bootstrap({ strapi }) {
12103
+ installUndiciCrashGuard(strapi);
11791
12104
  strapi.server.use(async (ctx, next) => {
11792
12105
  try {
11793
12106
  await next();
@@ -11810,6 +12123,9 @@ const index = {
11810
12123
  }
11811
12124
  });
11812
12125
  strapi.documents.use(async (context, next) => {
12126
+ if (typeof context.uid === "string" && context.uid.startsWith("plugin::bulk-updater.")) {
12127
+ return await next();
12128
+ }
11813
12129
  const params = context.params;
11814
12130
  if (["create", "update"].includes(context.action)) {
11815
12131
  const data = params?.data;
@@ -11993,9 +12309,14 @@ export {
11993
12309
  extractMetadataFromRow,
11994
12310
  extractRowFlattenedMetadata,
11995
12311
  formatErrorCsvFilename,
12312
+ formatErrorWithCause,
12313
+ getActiveBulkOperationCount,
11996
12314
  getAllNestedValues,
12315
+ getBatchConcurrency,
11997
12316
  getDeepProp,
11998
12317
  inspectRowMetadataMode,
12318
+ installUndiciCrashGuard,
12319
+ isFetchFailedError,
11999
12320
  isPlainObject,
12000
12321
  isValidDocumentId,
12001
12322
  normalizeExportMode,
@@ -12013,12 +12334,14 @@ export {
12013
12334
  resolveMediaIds,
12014
12335
  resolveRelationPayload,
12015
12336
  resolveTargetObjectField,
12337
+ sanitizeSensitiveErrorText,
12016
12338
  sanitizeUserErrorMessage,
12017
12339
  serializeDocumentsToCsv,
12018
12340
  serializeFieldValue,
12019
12341
  serializePlannedCell,
12020
12342
  setDeepProp,
12021
12343
  sortAuditRecordsDesc,
12344
+ trackActiveBulkOperation,
12022
12345
  validateEntityQuotas,
12023
12346
  validateRecordSchemaConstraints,
12024
12347
  verifyDocumentIntegrity,