strapi-plugin-bulk-updater 1.5.12 → 1.5.13

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.
@@ -960,331 +960,931 @@ const contentHistoryService = {
960
960
  recordContentHistoryVersion,
961
961
  recordContentHistoryVersionsBatch
962
962
  };
963
- const queryCache = /* @__PURE__ */ new Map();
964
- const modelsCache = /* @__PURE__ */ new Map();
965
- const MAX_QUERY_CACHE_SIZE = 500;
966
- const CACHE_TTL_MS = 60 * 1e3;
967
- let staticSchemaCache = null;
968
- function formatEntryRecord(entry) {
969
- if (!entry || typeof entry !== "object") return entry;
970
- const formatted = {
971
- id: entry.id,
972
- documentId: entry.documentId,
973
- status: entry.status !== void 0 ? entry.status : void 0,
974
- ...entry
975
- };
976
- if (entry.updatedAt !== void 0 && formatted.updated_at === void 0) {
977
- formatted.updated_at = entry.updatedAt;
963
+ const DEFAULT_RULES = [
964
+ {
965
+ id: "rule_seo_heading_h1",
966
+ name: "SEO Single H1 Page Rule",
967
+ description: "Enforces that only one H1 heading tag can be selected across all dynamic zone heading blocks within an entry, combined with rich text HTML.",
968
+ collectionUid: "*",
969
+ targetField: "headingLevel",
970
+ quotas: {
971
+ h1: 1,
972
+ h2: 3
973
+ },
974
+ exceededAction: "disable",
975
+ enabled: true,
976
+ scope: "entry",
977
+ includeRichTextHtml: true,
978
+ richTextFields: [],
979
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
980
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
978
981
  }
979
- if (entry.updated_at !== void 0 && formatted.updatedAt === void 0) {
980
- formatted.updatedAt = entry.updated_at;
982
+ ];
983
+ function extractHeadingsFromRichText(content) {
984
+ const counts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
985
+ if (!content) return counts;
986
+ if (Array.isArray(content)) {
987
+ for (const node of content) {
988
+ if (node && typeof node === "object") {
989
+ if (node.type === "heading" && typeof node.level === "number") {
990
+ const tag = `h${node.level}`;
991
+ if (counts[tag] !== void 0) counts[tag]++;
992
+ }
993
+ if (Array.isArray(node.children)) {
994
+ const sub = extractHeadingsFromRichText(node.children);
995
+ for (const k of Object.keys(counts)) counts[k] += sub[k];
996
+ }
997
+ }
998
+ }
999
+ return counts;
981
1000
  }
982
- if (entry.createdAt !== void 0 && formatted.created_at === void 0) {
983
- formatted.created_at = entry.createdAt;
1001
+ if (typeof content === "string") {
1002
+ for (let level = 1; level <= 6; level++) {
1003
+ const tag = `h${level}`;
1004
+ const htmlMatches = content.match(new RegExp(`<${tag}\\b[^>]*>`, "gi"));
1005
+ if (htmlMatches) {
1006
+ counts[tag] += htmlMatches.length;
1007
+ }
1008
+ const mdRegex = new RegExp(`(?:^|\\n)${"#".repeat(level)}\\s+[^\\n]+`, "g");
1009
+ const mdMatches = content.match(mdRegex);
1010
+ if (mdMatches) {
1011
+ counts[tag] += mdMatches.length;
1012
+ }
1013
+ }
984
1014
  }
985
- if (entry.created_at !== void 0 && formatted.createdAt === void 0) {
986
- formatted.createdAt = entry.created_at;
1015
+ return counts;
1016
+ }
1017
+ function cleanKey(str) {
1018
+ return (str || "").replace(/[-_]/g, "").toLowerCase().trim();
1019
+ }
1020
+ function matchesPath(normalizedPath, leafKey, targetField) {
1021
+ if (!targetField) return false;
1022
+ const pClean = cleanKey(normalizedPath);
1023
+ const kClean = cleanKey(leafKey);
1024
+ const tClean = cleanKey(targetField);
1025
+ if (kClean === tClean || pClean === tClean) return true;
1026
+ const targetSegments = targetField.replace(/^api::/i, "").split(".").map(cleanKey).filter(Boolean);
1027
+ const pathSegments = normalizedPath.split(".").map(cleanKey).filter(Boolean);
1028
+ if (targetSegments.length === 0 || pathSegments.length === 0) return false;
1029
+ if (targetSegments.length === 1) {
1030
+ const single = targetSegments[0];
1031
+ return kClean === single || pathSegments[pathSegments.length - 1] === single;
987
1032
  }
988
- if (entry.publishedAt !== void 0 && formatted.published_at === void 0) {
989
- formatted.published_at = entry.publishedAt;
1033
+ let isSuffix = true;
1034
+ for (let i = 0; i < targetSegments.length; i++) {
1035
+ const tSeg = targetSegments[targetSegments.length - 1 - i];
1036
+ const pSeg = pathSegments[pathSegments.length - 1 - i];
1037
+ if (tSeg !== "*" && tSeg !== pSeg) {
1038
+ isSuffix = false;
1039
+ break;
1040
+ }
990
1041
  }
991
- if (entry.published_at !== void 0 && formatted.publishedAt === void 0) {
992
- formatted.publishedAt = entry.published_at;
1042
+ if (isSuffix) return true;
1043
+ for (let startIdx = 1; startIdx < targetSegments.length; startIdx++) {
1044
+ const subTarget = targetSegments.slice(startIdx);
1045
+ if (subTarget.length > pathSegments.length) continue;
1046
+ let subSuffix = true;
1047
+ for (let i = 0; i < subTarget.length; i++) {
1048
+ const tSeg = subTarget[subTarget.length - 1 - i];
1049
+ const pSeg = pathSegments[pathSegments.length - 1 - i];
1050
+ if (tSeg !== "*" && tSeg !== pSeg) {
1051
+ subSuffix = false;
1052
+ break;
1053
+ }
1054
+ }
1055
+ if (subSuffix) return true;
993
1056
  }
994
- return formatted;
995
- }
996
- function isRowInEditingStage$1(row) {
997
- if (!row || typeof row !== "object") return false;
998
- const candidates = [
999
- row.strapi_stage,
1000
- row["strapi_stage"],
1001
- row.strapiStage,
1002
- row["Strapi Stage"],
1003
- row["strapi-stage"],
1004
- row.stage,
1005
- row.Stage,
1006
- row.review_stage,
1007
- row.workflow_stage
1008
- ];
1009
- if (row.status && typeof row.status === "string") {
1010
- const s = row.status.trim().toLowerCase();
1011
- if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
1012
- candidates.push(row.status);
1057
+ let pIdx = 0;
1058
+ let matchesInOrder = true;
1059
+ let tStart = 0;
1060
+ if (targetSegments.length > 2 && targetSegments[0] !== pathSegments[0] && targetSegments[0] !== "*") {
1061
+ tStart = 1;
1062
+ }
1063
+ for (let tIdx = tStart; tIdx < targetSegments.length; tIdx++) {
1064
+ const tSeg = targetSegments[tIdx];
1065
+ if (tSeg === "*") continue;
1066
+ let found = false;
1067
+ while (pIdx < pathSegments.length) {
1068
+ if (pathSegments[pIdx] === tSeg) {
1069
+ found = true;
1070
+ pIdx++;
1071
+ break;
1072
+ }
1073
+ pIdx++;
1074
+ }
1075
+ if (!found) {
1076
+ matchesInOrder = false;
1077
+ break;
1013
1078
  }
1014
1079
  }
1015
- for (const c of candidates) {
1016
- if (c !== void 0 && c !== null) {
1017
- let stageName = "";
1018
- if (typeof c === "object") {
1019
- stageName = String(c.name || c.title || c.status || c.documentId || c.id || "").trim();
1020
- } else if (typeof c === "string") {
1021
- const trimmed = c.trim();
1022
- if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
1023
- try {
1024
- const parsed = JSON.parse(trimmed);
1025
- if (typeof parsed === "object" && parsed !== null) {
1026
- stageName = String(parsed.name || parsed.title || parsed.status || parsed.documentId || parsed.id || "").trim();
1027
- }
1028
- } catch {
1029
- }
1030
- }
1031
- if (!stageName) {
1032
- stageName = trimmed;
1033
- }
1080
+ return matchesInOrder;
1081
+ }
1082
+ function deepMergeEntities(target, source) {
1083
+ if (!target || typeof target !== "object") {
1084
+ return source;
1085
+ }
1086
+ if (!source || typeof source !== "object") {
1087
+ return source !== void 0 ? source : target;
1088
+ }
1089
+ if (Array.isArray(source) || Array.isArray(target)) {
1090
+ return source;
1091
+ }
1092
+ const result = { ...target };
1093
+ for (const key of Object.keys(source)) {
1094
+ const sVal = source[key];
1095
+ const tVal = target[key];
1096
+ if (sVal === void 0) continue;
1097
+ if (sVal !== null && typeof sVal === "object" && !Array.isArray(sVal)) {
1098
+ if (tVal !== null && typeof tVal === "object" && !Array.isArray(tVal)) {
1099
+ result[key] = deepMergeEntities(tVal, sVal);
1034
1100
  } else {
1035
- stageName = String(c).trim();
1101
+ result[key] = sVal;
1036
1102
  }
1037
- if (stageName) {
1038
- const s = stageName.toLowerCase();
1039
- if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
1040
- return true;
1103
+ } else {
1104
+ result[key] = sVal;
1105
+ }
1106
+ }
1107
+ return result;
1108
+ }
1109
+ function filterAndEnrichRules(strapi, collectionUid, activeRules) {
1110
+ const effectiveRules = [
1111
+ ...(activeRules || []).filter((r) => {
1112
+ if (!r.collectionUid || r.collectionUid === "*") return true;
1113
+ if (r.collectionUid === collectionUid) return true;
1114
+ const cleanRuleCol = cleanKey(r.collectionUid);
1115
+ const cleanCtxCol = cleanKey(collectionUid);
1116
+ return cleanCtxCol.includes(cleanRuleCol) || cleanRuleCol.includes(cleanCtxCol);
1117
+ }).map((r) => ({
1118
+ id: r.id || r.targetField,
1119
+ name: r.name || r.targetField,
1120
+ collectionUid: r.collectionUid || "*",
1121
+ targetField: r.targetField,
1122
+ quotas: r.quotas || {},
1123
+ includeRichTextHtml: Boolean(r.includeRichTextHtml),
1124
+ richTextFields: Array.isArray(r.richTextFields) ? r.richTextFields : []
1125
+ }))
1126
+ ];
1127
+ const allComponents = strapi?.components || {};
1128
+ const ct = strapi?.contentTypes?.[collectionUid];
1129
+ const schemasToInspect = [
1130
+ ...Object.values(allComponents),
1131
+ ...ct ? [ct] : []
1132
+ ];
1133
+ for (const schema of schemasToInspect) {
1134
+ const attrs = schema?.attributes || {};
1135
+ for (const [attrName, attrDef] of Object.entries(attrs)) {
1136
+ if (attrDef.type === "customField" && (attrDef.customField === "plugin::bulk-updater.scoped-select" || attrDef.customField === "global::scoped-select") && !effectiveRules.some((r) => matchesPath(attrName, attrName, r.targetField))) {
1137
+ const quotas = attrDef.options?.quotas || {};
1138
+ const items = attrDef.options?.items || [];
1139
+ const itemQuotas = {};
1140
+ for (const item of items) {
1141
+ if (typeof item.maxAllowed === "number" && item.maxAllowed > 0) {
1142
+ itemQuotas[item.value] = item.maxAllowed;
1143
+ }
1041
1144
  }
1145
+ effectiveRules.push({
1146
+ id: `schema_${attrName}`,
1147
+ name: `${attrName} quota rule`,
1148
+ collectionUid: "*",
1149
+ targetField: attrName,
1150
+ quotas: {
1151
+ h1: 1,
1152
+ h2: 3,
1153
+ ...itemQuotas,
1154
+ ...quotas
1155
+ },
1156
+ includeRichTextHtml: true,
1157
+ richTextFields: []
1158
+ });
1042
1159
  }
1043
1160
  }
1044
1161
  }
1045
- return false;
1162
+ return effectiveRules;
1046
1163
  }
1047
- function resolveRecordPublicationStatus(entry, publishedRecord, isDraftAndPublish) {
1048
- if (isDraftAndPublish === false) {
1049
- return { status: "published", hadPublishedVersion: true };
1050
- }
1051
- if (!entry || typeof entry !== "object") {
1052
- return { status: "unknown", hadPublishedVersion: false };
1164
+ async function validateEntityQuotas(strapi, collectionUid, entity, customRules) {
1165
+ if (!entity || typeof entity !== "object") {
1166
+ return { isValid: true };
1053
1167
  }
1054
- if (typeof entry.status === "string" && entry.status.trim()) {
1055
- const s = entry.status.trim().toLowerCase();
1056
- if (s === "published") {
1057
- return { status: "published", hadPublishedVersion: true };
1058
- }
1059
- if (s === "modified") {
1060
- return { status: "modified", hadPublishedVersion: true };
1061
- }
1062
- if (s === "draft") {
1063
- return { status: "draft", hadPublishedVersion: false };
1168
+ let effectiveRules = [];
1169
+ if (customRules && Array.isArray(customRules)) {
1170
+ effectiveRules = customRules;
1171
+ } else {
1172
+ try {
1173
+ const rulesService = strapi.plugin("bulk-updater").service("validationRules");
1174
+ if (rulesService) {
1175
+ const allRules = await rulesService.getRules();
1176
+ const activeUiRules = (allRules || []).filter((r) => r.enabled);
1177
+ effectiveRules = filterAndEnrichRules(strapi, collectionUid, activeUiRules);
1178
+ }
1179
+ } catch (err) {
1180
+ strapi.log?.warn?.("[bulk-updater] Failed to fetch validation rules for quota check:", err);
1064
1181
  }
1065
1182
  }
1066
- const pub = publishedRecord || (entry.publishedAt ? entry : null);
1067
- if (!pub) {
1068
- return { status: "draft", hadPublishedVersion: false };
1183
+ if (effectiveRules.length === 0) {
1184
+ return { isValid: true };
1069
1185
  }
1070
- const draftUpdatedTime = new Date(entry.updatedAt || entry.updated_at || 0).getTime();
1071
- const pubUpdatedTime = new Date(pub.updatedAt || pub.updated_at || 0).getTime();
1072
- const pubPublishedTime = new Date(pub.publishedAt || pub.published_at || 0).getTime();
1073
- const lastPublishedTime = Math.max(
1074
- isNaN(pubUpdatedTime) ? 0 : pubUpdatedTime,
1075
- isNaN(pubPublishedTime) ? 0 : pubPublishedTime
1076
- );
1077
- if (isNaN(draftUpdatedTime) || lastPublishedTime === 0) {
1078
- if (pub.publishedAt || pub.published_at) {
1079
- return { status: "published", hadPublishedVersion: true };
1186
+ const structuredCounts = {};
1187
+ const richTextCounts = {};
1188
+ for (const rule of effectiveRules) {
1189
+ structuredCounts[rule.id] = {};
1190
+ richTextCounts[rule.id] = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
1191
+ }
1192
+ function scanDataTree(obj, currentPath = "", depth = 0) {
1193
+ if (!obj || typeof obj !== "object" || depth > 20) return;
1194
+ const compName = typeof obj.__component === "string" ? obj.__component : "";
1195
+ if (Array.isArray(obj)) {
1196
+ for (let i = 0; i < obj.length; i++) {
1197
+ const item = obj[i];
1198
+ if (item && typeof item === "object") {
1199
+ scanDataTree(item, currentPath ? `${currentPath}.${i}` : `${i}`, depth + 1);
1200
+ }
1201
+ }
1202
+ return;
1203
+ }
1204
+ for (const key of Object.keys(obj)) {
1205
+ if (key === "__component") continue;
1206
+ const val = obj[key];
1207
+ const newPath = currentPath ? `${currentPath}.${key}` : key;
1208
+ const normalizedPath = newPath.replace(/\.\d+/g, "");
1209
+ const compPath = compName ? (currentPath ? `${currentPath}.${compName}.${key}` : `${compName}.${key}`).replace(/\.\d+/g, "") : "";
1210
+ for (const rule of effectiveRules) {
1211
+ const isMatch = matchesPath(normalizedPath, key, rule.targetField) || (compPath ? matchesPath(compPath, key, rule.targetField) : false);
1212
+ if (isMatch && (typeof val === "string" || typeof val === "number") && String(val).trim()) {
1213
+ const lowerVal = String(val).toLowerCase().trim();
1214
+ structuredCounts[rule.id][lowerVal] = (structuredCounts[rule.id][lowerVal] || 0) + 1;
1215
+ }
1216
+ }
1217
+ const isRichTextString = typeof val === "string" && (/<h[1-6]\b/i.test(val) || val.includes("#"));
1218
+ const isBlocksArray = Array.isArray(val) && val.length > 0 && typeof val[0] === "object" && val[0]?.type;
1219
+ if (isRichTextString || isBlocksArray) {
1220
+ const headings = extractHeadingsFromRichText(val);
1221
+ for (const rule of effectiveRules) {
1222
+ if (!rule.includeRichTextHtml) continue;
1223
+ if (Array.isArray(rule.richTextFields) && rule.richTextFields.length > 0) {
1224
+ const matchesSpecificField = rule.richTextFields.some(
1225
+ (rf) => matchesPath(normalizedPath, key, rf) || (compPath ? matchesPath(compPath, key, rf) : false)
1226
+ );
1227
+ if (!matchesSpecificField) continue;
1228
+ }
1229
+ for (const [tag, count] of Object.entries(headings)) {
1230
+ if (count > 0) {
1231
+ richTextCounts[rule.id][tag] = (richTextCounts[rule.id][tag] || 0) + count;
1232
+ }
1233
+ }
1234
+ }
1235
+ if (isBlocksArray) {
1236
+ continue;
1237
+ }
1238
+ }
1239
+ if (typeof val === "object" && val !== null) {
1240
+ scanDataTree(val, newPath, depth + 1);
1241
+ }
1080
1242
  }
1081
- return { status: "unknown", hadPublishedVersion: false };
1082
1243
  }
1083
- if (draftUpdatedTime > lastPublishedTime) {
1084
- return { status: "modified", hadPublishedVersion: true };
1244
+ scanDataTree(entity);
1245
+ for (const rule of effectiveRules) {
1246
+ const ruleCounts = structuredCounts[rule.id] || {};
1247
+ const rtRuleCounts = richTextCounts[rule.id] || {};
1248
+ for (const [quotaKey, maxAllowed] of Object.entries(rule.quotas || {})) {
1249
+ const lowerVal = quotaKey.toLowerCase().trim();
1250
+ const structCount = ruleCounts[lowerVal] || 0;
1251
+ const rtCount = rule.includeRichTextHtml ? rtRuleCounts[lowerVal] || 0 : 0;
1252
+ const totalFound = structCount + rtCount;
1253
+ if (totalFound > maxAllowed) {
1254
+ let detailMsg = `Option "${quotaKey.toUpperCase()}" cannot appear more than ${maxAllowed} time(s) across this entry.`;
1255
+ if (rtCount > 0 && structCount > 0) {
1256
+ detailMsg += ` Found ${totalFound} occurrences combined: ${structCount} in structured component ('${rule.targetField}') and ${rtCount} in rich text HTML / Markdown.`;
1257
+ } else if (rtCount > 0) {
1258
+ detailMsg += ` Found ${totalFound} in rich text HTML / Markdown content.`;
1259
+ } else {
1260
+ detailMsg += ` Found ${totalFound} in structured field '${rule.targetField}'.`;
1261
+ }
1262
+ const fullErrorMessage = `Validation Error (${rule.name}): ${detailMsg}`;
1263
+ return {
1264
+ isValid: false,
1265
+ ruleId: rule.id,
1266
+ ruleName: rule.name,
1267
+ targetField: rule.targetField,
1268
+ violatingOption: quotaKey.toUpperCase(),
1269
+ foundCount: totalFound,
1270
+ maxAllowed,
1271
+ structuredCount: structCount,
1272
+ richTextCount: rtCount,
1273
+ errorMessage: fullErrorMessage
1274
+ };
1275
+ }
1276
+ }
1085
1277
  }
1086
- return { status: "published", hadPublishedVersion: true };
1278
+ return { isValid: true };
1087
1279
  }
1088
- function evaluateShouldPublish({
1089
- isDraftAndPublish,
1090
- hadPublishedVersion,
1091
- isEditing,
1092
- publishOnApproval = true,
1093
- publishStrategy = "safe",
1094
- unreviewedConsent = false
1095
- }) {
1096
- if (!isDraftAndPublish) return false;
1097
- if (!hadPublishedVersion) return false;
1098
- if (!publishOnApproval) return false;
1099
- if (isEditing) return false;
1100
- return true;
1101
- }
1102
- async function populateDocumentLifecycleStatus(strapi, uid, entries) {
1103
- if (!entries || !Array.isArray(entries) || entries.length === 0) {
1104
- return entries;
1105
- }
1106
- const contentType = strapi?.contentTypes?.[uid];
1107
- if (!contentType) {
1108
- return entries;
1109
- }
1110
- const hasDraftAndPublish = Boolean(contentType.options?.draftAndPublish);
1111
- if (!hasDraftAndPublish) {
1112
- for (const entry of entries) {
1113
- if (entry && typeof entry === "object") {
1114
- entry.status = "published";
1115
- }
1280
+ const validationRulesService = ({ strapi }) => ({
1281
+ async getStore() {
1282
+ return strapi.store({
1283
+ type: "plugin",
1284
+ name: "bulk-updater",
1285
+ key: "validation-rules"
1286
+ });
1287
+ },
1288
+ async getRules() {
1289
+ const store = await this.getStore();
1290
+ const stored = await store.get({});
1291
+ if (!stored || !Array.isArray(stored.rules)) {
1292
+ await store.set({ value: { rules: DEFAULT_RULES } });
1293
+ return DEFAULT_RULES;
1116
1294
  }
1117
- return entries;
1118
- }
1119
- const hasSlugInSchema = Boolean(contentType.attributes?.slug);
1120
- const docIds = [];
1121
- const slugs = [];
1122
- for (const entry of entries) {
1123
- if (!entry || typeof entry !== "object") continue;
1124
- if (entry.documentId) {
1125
- docIds.push(String(entry.documentId));
1126
- } else if (hasSlugInSchema && entry.slug) {
1127
- slugs.push(String(entry.slug));
1295
+ return stored.rules;
1296
+ },
1297
+ async saveRule(ruleData) {
1298
+ const store = await this.getStore();
1299
+ const rules = await this.getRules();
1300
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1301
+ let savedRule;
1302
+ if (ruleData.id) {
1303
+ const index2 = rules.findIndex((r) => r.id === ruleData.id);
1304
+ if (index2 !== -1) {
1305
+ savedRule = {
1306
+ ...rules[index2],
1307
+ ...ruleData,
1308
+ collectionUid: ruleData.collectionUid !== void 0 ? ruleData.collectionUid : rules[index2].collectionUid || "*",
1309
+ includeRichTextHtml: ruleData.includeRichTextHtml !== void 0 ? Boolean(ruleData.includeRichTextHtml) : Boolean(rules[index2].includeRichTextHtml),
1310
+ richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : rules[index2].richTextFields || [],
1311
+ updatedAt: now
1312
+ };
1313
+ rules[index2] = savedRule;
1314
+ } else {
1315
+ savedRule = {
1316
+ id: ruleData.id,
1317
+ name: ruleData.name || "New Rule",
1318
+ description: ruleData.description || "",
1319
+ collectionUid: ruleData.collectionUid || "*",
1320
+ targetField: ruleData.targetField || "headingLevel",
1321
+ quotas: ruleData.quotas || { h1: 1 },
1322
+ exceededAction: ruleData.exceededAction || "disable",
1323
+ enabled: ruleData.enabled ?? true,
1324
+ scope: ruleData.scope || "entry",
1325
+ includeRichTextHtml: Boolean(ruleData.includeRichTextHtml),
1326
+ richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : [],
1327
+ createdAt: now,
1328
+ updatedAt: now
1329
+ };
1330
+ rules.push(savedRule);
1331
+ }
1128
1332
  } else {
1129
- entry.status = "unknown";
1333
+ const id = `rule_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`;
1334
+ savedRule = {
1335
+ id,
1336
+ name: ruleData.name || "Custom Quota Rule",
1337
+ description: ruleData.description || "",
1338
+ collectionUid: ruleData.collectionUid || "*",
1339
+ targetField: ruleData.targetField || "headingLevel",
1340
+ quotas: ruleData.quotas || { h1: 1 },
1341
+ exceededAction: ruleData.exceededAction || "disable",
1342
+ enabled: ruleData.enabled ?? true,
1343
+ scope: ruleData.scope || "entry",
1344
+ includeRichTextHtml: Boolean(ruleData.includeRichTextHtml),
1345
+ richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : [],
1346
+ createdAt: now,
1347
+ updatedAt: now
1348
+ };
1349
+ rules.push(savedRule);
1130
1350
  }
1131
- }
1132
- if (docIds.length === 0 && slugs.length === 0) {
1133
- return entries;
1134
- }
1135
- let filterClause;
1136
- if (docIds.length > 0 && slugs.length > 0) {
1137
- filterClause = {
1138
- $or: [
1139
- { documentId: { $in: docIds } },
1140
- { slug: { $in: slugs } }
1141
- ]
1351
+ await store.set({ value: { rules } });
1352
+ return savedRule;
1353
+ },
1354
+ async deleteRule(ruleId) {
1355
+ const store = await this.getStore();
1356
+ const rules = await this.getRules();
1357
+ const filtered = rules.filter((r) => r.id !== ruleId);
1358
+ await store.set({ value: { rules: filtered } });
1359
+ return true;
1360
+ },
1361
+ async toggleRule(ruleId, enabled) {
1362
+ const store = await this.getStore();
1363
+ const rules = await this.getRules();
1364
+ const index2 = rules.findIndex((r) => r.id === ruleId);
1365
+ if (index2 === -1) return null;
1366
+ const current = rules[index2];
1367
+ const newEnabled = typeof enabled === "boolean" ? enabled : !current.enabled;
1368
+ const updated = {
1369
+ ...current,
1370
+ enabled: newEnabled,
1371
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1142
1372
  };
1143
- } else if (docIds.length > 0) {
1144
- filterClause = { documentId: { $in: docIds } };
1145
- } else {
1146
- filterClause = { slug: { $in: slugs } };
1147
- }
1148
- const queryFields = ["documentId", "updatedAt", "publishedAt"];
1149
- if (hasSlugInSchema) {
1150
- queryFields.push("slug");
1151
- }
1152
- let publishedRecords = [];
1153
- try {
1154
- const docService = strapi?.documents?.(uid);
1155
- if (docService?.findMany) {
1156
- publishedRecords = await docService.findMany({
1157
- status: "published",
1158
- filters: filterClause,
1159
- fields: queryFields,
1160
- limit: Math.max(entries.length, 100)
1161
- });
1373
+ rules[index2] = updated;
1374
+ await store.set({ value: { rules } });
1375
+ return updated;
1376
+ },
1377
+ async scanViolations(ruleId) {
1378
+ const rules = await this.getRules();
1379
+ const rule = rules.find((r) => r.id === ruleId);
1380
+ if (!rule) {
1381
+ throw new Error(`Validation rule ${ruleId} not found`);
1162
1382
  }
1163
- } catch (err) {
1164
- strapi?.log?.warn?.(`[bulk-updater] Failed to fetch published status for ${uid}: ${err?.message || err}`);
1165
- for (const entry of entries) {
1166
- if (entry && typeof entry === "object" && entry.status !== "unknown") {
1167
- entry.status = "unknown";
1383
+ const targetField = rule.targetField;
1384
+ const quotas = rule.quotas || {};
1385
+ const violations = [];
1386
+ let totalScanned = 0;
1387
+ const allContentTypes = strapi.contentTypes || {};
1388
+ const allComponents = strapi.components || {};
1389
+ function componentHasField(compUid, targetField2) {
1390
+ const comp = allComponents[compUid];
1391
+ if (!comp?.attributes) return false;
1392
+ if (matchesPath(compUid, compUid, targetField2)) return true;
1393
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
1394
+ if (matchesPath(attrName, attrName, targetField2) || matchesPath(`${compUid}.${attrName}`, attrName, targetField2)) return true;
1395
+ if (attrDef.type === "component" && attrDef.component) {
1396
+ if (componentHasField(attrDef.component, targetField2)) return true;
1397
+ } else if (attrDef.type === "dynamiczone" && Array.isArray(attrDef.components)) {
1398
+ if (attrDef.components.some((c) => componentHasField(c, targetField2))) return true;
1399
+ }
1168
1400
  }
1401
+ return false;
1169
1402
  }
1170
- return entries;
1171
- }
1172
- const publishedByDocId = /* @__PURE__ */ new Map();
1173
- const publishedBySlug = /* @__PURE__ */ new Map();
1174
- for (const pub of publishedRecords || []) {
1175
- if (pub?.documentId) {
1176
- publishedByDocId.set(String(pub.documentId), pub);
1177
- }
1178
- if (pub?.slug && hasSlugInSchema) {
1179
- publishedBySlug.set(String(pub.slug), pub);
1180
- }
1181
- }
1182
- for (const entry of entries) {
1183
- if (!entry || typeof entry !== "object") continue;
1184
- if (entry.status === "unknown") continue;
1185
- const pub = entry.documentId && publishedByDocId.get(String(entry.documentId)) || hasSlugInSchema && entry.slug && publishedBySlug.get(String(entry.slug));
1186
- if (!pub) {
1187
- entry.status = "draft";
1188
- entry.publishedAt = null;
1189
- entry.published_at = null;
1190
- } else {
1191
- entry.publishedAt = pub.publishedAt || pub.published_at || null;
1192
- entry.published_at = entry.publishedAt;
1193
- const draftUpdatedTime = new Date(entry.updatedAt || entry.updated_at || 0).getTime();
1194
- const pubUpdatedTime = new Date(pub.updatedAt || pub.updated_at || 0).getTime();
1195
- const pubPublishedTime = new Date(pub.publishedAt || pub.published_at || 0).getTime();
1196
- const lastPublishedTime = Math.max(
1197
- isNaN(pubUpdatedTime) ? 0 : pubUpdatedTime,
1198
- isNaN(pubPublishedTime) ? 0 : pubPublishedTime
1199
- );
1200
- if (isNaN(draftUpdatedTime) || lastPublishedTime === 0) {
1201
- if (pub.publishedAt) {
1202
- entry.status = "published";
1203
- } else {
1204
- entry.status = "unknown";
1403
+ function schemaHasField(ctSchema) {
1404
+ if (!ctSchema || !ctSchema.attributes) return { hasField: false, populateAttrs: {} };
1405
+ const rawAttrs = ctSchema.attributes;
1406
+ const populateAttrs = {};
1407
+ let hasField = false;
1408
+ for (const [attrKey, attrDef] of Object.entries(rawAttrs)) {
1409
+ if (matchesPath(attrKey, attrKey, targetField)) {
1410
+ hasField = true;
1411
+ }
1412
+ if (attrDef.type === "component" && attrDef.component) {
1413
+ if (componentHasField(attrDef.component, targetField)) {
1414
+ hasField = true;
1415
+ populateAttrs[attrKey] = { populate: "*" };
1416
+ }
1417
+ } else if (attrDef.type === "dynamiczone" && Array.isArray(attrDef.components)) {
1418
+ const matchingComp = attrDef.components.some(
1419
+ (compUid) => componentHasField(compUid, targetField) || matchesPath(`${attrKey}.${compUid}`, compUid, targetField)
1420
+ );
1421
+ if (matchingComp) {
1422
+ hasField = true;
1423
+ populateAttrs[attrKey] = { populate: "*" };
1424
+ }
1205
1425
  }
1206
- } else if (draftUpdatedTime > lastPublishedTime) {
1207
- entry.status = "modified";
1208
- } else {
1209
- entry.status = "published";
1210
1426
  }
1427
+ return { hasField, populateAttrs };
1211
1428
  }
1429
+ const candidateUids = Object.keys(allContentTypes).filter((uid) => {
1430
+ if (!uid.startsWith("api::") || uid.includes("bulk-updater")) return false;
1431
+ if (rule.collectionUid && rule.collectionUid !== "*") {
1432
+ if (rule.collectionUid === uid) return true;
1433
+ const cleanRuleCol = cleanKey(rule.collectionUid);
1434
+ const cleanUid = cleanKey(uid);
1435
+ if (cleanUid.includes(cleanRuleCol) || cleanRuleCol.includes(cleanUid)) return true;
1436
+ return false;
1437
+ }
1438
+ return true;
1439
+ });
1440
+ const relevantCollections = [];
1441
+ for (const uid of candidateUids) {
1442
+ const ct = allContentTypes[uid];
1443
+ if (!ct) continue;
1444
+ const { hasField, populateAttrs } = schemaHasField(ct);
1445
+ const isTargetCol = rule.collectionUid && (rule.collectionUid === uid || cleanKey(uid).includes(cleanKey(rule.collectionUid)));
1446
+ if (hasField || isTargetCol) {
1447
+ relevantCollections.push({
1448
+ uid,
1449
+ displayName: ct.info?.displayName || uid,
1450
+ populateOption: Object.keys(populateAttrs).length > 0 ? populateAttrs : "*"
1451
+ });
1452
+ }
1453
+ }
1454
+ const BATCH_SIZE = 250;
1455
+ await Promise.all(
1456
+ relevantCollections.map(async ({ uid, displayName, populateOption }) => {
1457
+ try {
1458
+ let page = 1;
1459
+ while (true) {
1460
+ const entries = await strapi.documents(uid).findMany({
1461
+ page,
1462
+ pageSize: BATCH_SIZE,
1463
+ populate: populateOption
1464
+ });
1465
+ if (!entries || entries.length === 0) break;
1466
+ for (const entry of entries) {
1467
+ let traverse = function(obj, currentPath = "") {
1468
+ if (!obj || typeof obj !== "object") return;
1469
+ const compName = typeof obj.__component === "string" ? obj.__component : "";
1470
+ for (const key of Object.keys(obj)) {
1471
+ if (key === "__component") continue;
1472
+ const val = obj[key];
1473
+ const newPath = currentPath ? `${currentPath}.${key}` : key;
1474
+ const normalizedPath = newPath.replace(/\.\d+/g, "");
1475
+ const compPath = compName ? (currentPath ? `${currentPath}.${compName}.${key}` : `${compName}.${key}`).replace(/\.\d+/g, "") : "";
1476
+ const isMatch = matchesPath(normalizedPath, key, targetField) || (compPath ? matchesPath(compPath, key, targetField) : false);
1477
+ if (isMatch && typeof val === "string" && val.trim()) {
1478
+ const lower = val.toLowerCase().trim();
1479
+ structuredCounts[lower] = (structuredCounts[lower] || 0) + 1;
1480
+ }
1481
+ if (rule.includeRichTextHtml) {
1482
+ if (typeof val === "string" && (val.includes("<h") || val.includes("#"))) {
1483
+ const headings = extractHeadingsFromRichText(val);
1484
+ for (const [tag, count] of Object.entries(headings)) {
1485
+ if (count > 0) {
1486
+ richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
1487
+ }
1488
+ }
1489
+ } else if (Array.isArray(val) && val.length > 0 && typeof val[0] === "object" && val[0]?.type) {
1490
+ const headings = extractHeadingsFromRichText(val);
1491
+ for (const [tag, count] of Object.entries(headings)) {
1492
+ if (count > 0) {
1493
+ richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
1494
+ }
1495
+ }
1496
+ continue;
1497
+ }
1498
+ }
1499
+ if (typeof val === "object" && val !== null) {
1500
+ traverse(val, newPath);
1501
+ }
1502
+ }
1503
+ };
1504
+ totalScanned++;
1505
+ const structuredCounts = {};
1506
+ const richTextCounts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
1507
+ traverse(entry);
1508
+ for (const [optKey, max] of Object.entries(quotas)) {
1509
+ const lowerOpt = optKey.toLowerCase().trim();
1510
+ const structCount = structuredCounts[lowerOpt] || 0;
1511
+ const rtCount = rule.includeRichTextHtml ? richTextCounts[lowerOpt] || 0 : 0;
1512
+ const combinedCount = structCount + rtCount;
1513
+ if (combinedCount > max) {
1514
+ const entryLabel = entry.title || entry.name || entry.email || `Entry #${entry.documentId}`;
1515
+ let detail = "";
1516
+ if (rtCount > 0 && structCount > 0) {
1517
+ detail = `${structCount} structured + ${rtCount} in rich text HTML`;
1518
+ } else if (rtCount > 0) {
1519
+ detail = `${rtCount} in rich text HTML / Markdown`;
1520
+ } else {
1521
+ detail = `${structCount} in structured component`;
1522
+ }
1523
+ violations.push({
1524
+ uid,
1525
+ collectionDisplayName: displayName,
1526
+ documentId: entry.documentId,
1527
+ entryLabel,
1528
+ violatingOption: optKey.toUpperCase(),
1529
+ foundCount: combinedCount,
1530
+ structuredCount: structCount,
1531
+ richTextCount: rtCount,
1532
+ maxAllowed: max,
1533
+ detail,
1534
+ editUrl: `/admin/content-manager/collection-types/${uid}/${entry.documentId}`
1535
+ });
1536
+ }
1537
+ }
1538
+ }
1539
+ if (entries.length < BATCH_SIZE) break;
1540
+ page++;
1541
+ }
1542
+ } catch (err) {
1543
+ strapi.log.warn(`[bulk-updater] Failed scanning ${uid} for rule ${ruleId}:`, err);
1544
+ }
1545
+ })
1546
+ );
1547
+ return {
1548
+ rule,
1549
+ totalScanned,
1550
+ totalViolations: violations.length,
1551
+ violations
1552
+ };
1553
+ },
1554
+ async getEffectiveRules(collectionUid) {
1555
+ const allRules = await this.getRules();
1556
+ const activeUiRules = (allRules || []).filter((r) => r.enabled);
1557
+ return filterAndEnrichRules(strapi, collectionUid, activeUiRules);
1558
+ },
1559
+ async validateEntity(entity, collectionUid, customRules) {
1560
+ return validateEntityQuotas(strapi, collectionUid, entity, customRules);
1212
1561
  }
1213
- return entries;
1214
- }
1215
- function resolveContentTypeField(contentType, field) {
1216
- if (!field) return null;
1217
- const attrs = contentType?.attributes || {};
1218
- if (attrs[field]) return field;
1219
- if (field === "updated_at" || field === "updatedAt") {
1220
- return attrs["updated_at"] ? "updated_at" : "updatedAt";
1221
- }
1222
- if (field === "created_at" || field === "createdAt") {
1223
- return attrs["created_at"] ? "created_at" : "createdAt";
1224
- }
1225
- if (field === "published_at" || field === "publishedAt") {
1226
- return attrs["published_at"] ? "published_at" : "publishedAt";
1562
+ });
1563
+ const queryCache = /* @__PURE__ */ new Map();
1564
+ const modelsCache = /* @__PURE__ */ new Map();
1565
+ const MAX_QUERY_CACHE_SIZE = 500;
1566
+ const CACHE_TTL_MS = 60 * 1e3;
1567
+ let staticSchemaCache = null;
1568
+ function formatEntryRecord(entry) {
1569
+ if (!entry || typeof entry !== "object") return entry;
1570
+ const formatted = {
1571
+ id: entry.id,
1572
+ documentId: entry.documentId,
1573
+ status: entry.status !== void 0 ? entry.status : void 0,
1574
+ ...entry
1575
+ };
1576
+ if (entry.updatedAt !== void 0 && formatted.updated_at === void 0) {
1577
+ formatted.updated_at = entry.updatedAt;
1227
1578
  }
1228
- if (field === "id" || field === "documentId") {
1229
- return field;
1579
+ if (entry.updated_at !== void 0 && formatted.updatedAt === void 0) {
1580
+ formatted.updatedAt = entry.updated_at;
1230
1581
  }
1231
- const camel = field.replace(/_([a-z0-9])/g, (_, l) => l.toUpperCase());
1232
- if (attrs[camel]) return camel;
1233
- const snake = field.replace(/([A-Z])/g, "_$1").toLowerCase();
1234
- if (attrs[snake]) return snake;
1235
- const lower = field.toLowerCase().replace(/_/g, "");
1236
- const matched = Object.keys(attrs).find(
1237
- (k) => k.toLowerCase().replace(/_/g, "") === lower
1238
- );
1239
- if (matched) return matched;
1240
- return null;
1582
+ if (entry.createdAt !== void 0 && formatted.created_at === void 0) {
1583
+ formatted.created_at = entry.createdAt;
1584
+ }
1585
+ if (entry.created_at !== void 0 && formatted.createdAt === void 0) {
1586
+ formatted.createdAt = entry.created_at;
1587
+ }
1588
+ if (entry.publishedAt !== void 0 && formatted.published_at === void 0) {
1589
+ formatted.published_at = entry.publishedAt;
1590
+ }
1591
+ if (entry.published_at !== void 0 && formatted.publishedAt === void 0) {
1592
+ formatted.publishedAt = entry.published_at;
1593
+ }
1594
+ return formatted;
1241
1595
  }
1242
- function buildDeepPopulate$1(attributes, allComponents, depth = 0) {
1243
- if (depth > 5) return void 0;
1244
- const populate = {};
1245
- for (const [key, def] of Object.entries(attributes || {})) {
1246
- if (def.type === "component" && def.component) {
1247
- const comp = allComponents[def.component];
1248
- if (comp?.attributes) {
1249
- const subPopulate = buildDeepPopulate$1(comp.attributes, allComponents, depth + 1);
1250
- if (subPopulate && Object.keys(subPopulate).length > 0) {
1251
- populate[key] = {
1252
- populate: subPopulate
1253
- };
1254
- } else {
1255
- populate[key] = true;
1596
+ function isRowInEditingStage$1(row) {
1597
+ if (!row || typeof row !== "object") return false;
1598
+ const candidates = [
1599
+ row.strapi_stage,
1600
+ row["strapi_stage"],
1601
+ row.strapiStage,
1602
+ row["Strapi Stage"],
1603
+ row["strapi-stage"],
1604
+ row.stage,
1605
+ row.Stage,
1606
+ row.review_stage,
1607
+ row.workflow_stage
1608
+ ];
1609
+ if (row.status && typeof row.status === "string") {
1610
+ const s = row.status.trim().toLowerCase();
1611
+ if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
1612
+ candidates.push(row.status);
1613
+ }
1614
+ }
1615
+ for (const c of candidates) {
1616
+ if (c !== void 0 && c !== null) {
1617
+ let stageName = "";
1618
+ if (typeof c === "object") {
1619
+ stageName = String(c.name || c.title || c.status || c.documentId || c.id || "").trim();
1620
+ } else if (typeof c === "string") {
1621
+ const trimmed = c.trim();
1622
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
1623
+ try {
1624
+ const parsed = JSON.parse(trimmed);
1625
+ if (typeof parsed === "object" && parsed !== null) {
1626
+ stageName = String(parsed.name || parsed.title || parsed.status || parsed.documentId || parsed.id || "").trim();
1627
+ }
1628
+ } catch {
1629
+ }
1630
+ }
1631
+ if (!stageName) {
1632
+ stageName = trimmed;
1256
1633
  }
1257
1634
  } else {
1258
- populate[key] = true;
1635
+ stageName = String(c).trim();
1636
+ }
1637
+ if (stageName) {
1638
+ const s = stageName.toLowerCase();
1639
+ if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
1640
+ return true;
1641
+ }
1259
1642
  }
1260
- } else if (def.type === "dynamiczone") {
1261
- populate[key] = {
1262
- populate: "*"
1263
- };
1264
- } else if (def.type === "relation" || def.type === "media") {
1265
- populate[key] = true;
1266
1643
  }
1267
1644
  }
1268
- return Object.keys(populate).length > 0 ? populate : void 0;
1645
+ return false;
1269
1646
  }
1270
- function discoverComponentAttributes(strapi, compUid, prefix, currentDepth, maxDepth, systemFields, allContentTypes, relationsByAttr, allRelationsMeta, attributesMeta) {
1271
- if (currentDepth > maxDepth || !compUid) return [];
1272
- const compSchema = strapi.components[compUid];
1273
- if (!compSchema?.attributes) return [];
1274
- const discoveredAttrs = [];
1275
- for (const [subKey, subAttr] of Object.entries(compSchema.attributes)) {
1276
- if (systemFields.includes(subKey)) continue;
1277
- const fullPath = prefix ? `${prefix}.${subKey}` : subKey;
1278
- if (subAttr.type === "dynamiczone") {
1279
- const dzComps = Array.isArray(subAttr.components) ? subAttr.components : [];
1280
- for (const dzCompUid of dzComps) {
1281
- const deeper = discoverComponentAttributes(
1282
- strapi,
1283
- dzCompUid,
1284
- fullPath,
1285
- currentDepth + 1,
1286
- maxDepth,
1287
- systemFields,
1647
+ function resolveRecordPublicationStatus(entry, publishedRecord, isDraftAndPublish) {
1648
+ if (isDraftAndPublish === false) {
1649
+ return { status: "published", hadPublishedVersion: true };
1650
+ }
1651
+ if (!entry || typeof entry !== "object") {
1652
+ return { status: "unknown", hadPublishedVersion: false };
1653
+ }
1654
+ if (typeof entry.status === "string" && entry.status.trim()) {
1655
+ const s = entry.status.trim().toLowerCase();
1656
+ if (s === "published") {
1657
+ return { status: "published", hadPublishedVersion: true };
1658
+ }
1659
+ if (s === "modified") {
1660
+ return { status: "modified", hadPublishedVersion: true };
1661
+ }
1662
+ if (s === "draft") {
1663
+ return { status: "draft", hadPublishedVersion: false };
1664
+ }
1665
+ }
1666
+ const pub = publishedRecord || (entry.publishedAt ? entry : null);
1667
+ if (!pub) {
1668
+ return { status: "draft", hadPublishedVersion: false };
1669
+ }
1670
+ const draftUpdatedTime = new Date(entry.updatedAt || entry.updated_at || 0).getTime();
1671
+ const pubUpdatedTime = new Date(pub.updatedAt || pub.updated_at || 0).getTime();
1672
+ const pubPublishedTime = new Date(pub.publishedAt || pub.published_at || 0).getTime();
1673
+ const lastPublishedTime = Math.max(
1674
+ isNaN(pubUpdatedTime) ? 0 : pubUpdatedTime,
1675
+ isNaN(pubPublishedTime) ? 0 : pubPublishedTime
1676
+ );
1677
+ if (isNaN(draftUpdatedTime) || lastPublishedTime === 0) {
1678
+ if (pub.publishedAt || pub.published_at) {
1679
+ return { status: "published", hadPublishedVersion: true };
1680
+ }
1681
+ return { status: "unknown", hadPublishedVersion: false };
1682
+ }
1683
+ if (draftUpdatedTime > lastPublishedTime) {
1684
+ return { status: "modified", hadPublishedVersion: true };
1685
+ }
1686
+ return { status: "published", hadPublishedVersion: true };
1687
+ }
1688
+ function evaluateShouldPublish({
1689
+ isDraftAndPublish,
1690
+ hadPublishedVersion,
1691
+ isEditing,
1692
+ publishOnApproval = true,
1693
+ publishStrategy = "safe",
1694
+ unreviewedConsent = false
1695
+ }) {
1696
+ if (!isDraftAndPublish) return false;
1697
+ if (!hadPublishedVersion) return false;
1698
+ if (!publishOnApproval) return false;
1699
+ if (isEditing) return false;
1700
+ return true;
1701
+ }
1702
+ async function populateDocumentLifecycleStatus(strapi, uid, entries) {
1703
+ if (!entries || !Array.isArray(entries) || entries.length === 0) {
1704
+ return entries;
1705
+ }
1706
+ const contentType = strapi?.contentTypes?.[uid];
1707
+ if (!contentType) {
1708
+ return entries;
1709
+ }
1710
+ const hasDraftAndPublish = Boolean(contentType.options?.draftAndPublish);
1711
+ if (!hasDraftAndPublish) {
1712
+ for (const entry of entries) {
1713
+ if (entry && typeof entry === "object") {
1714
+ entry.status = "published";
1715
+ }
1716
+ }
1717
+ return entries;
1718
+ }
1719
+ const hasSlugInSchema = Boolean(contentType.attributes?.slug);
1720
+ const docIds = [];
1721
+ const slugs = [];
1722
+ for (const entry of entries) {
1723
+ if (!entry || typeof entry !== "object") continue;
1724
+ if (entry.documentId) {
1725
+ docIds.push(String(entry.documentId));
1726
+ } else if (hasSlugInSchema && entry.slug) {
1727
+ slugs.push(String(entry.slug));
1728
+ } else {
1729
+ entry.status = "unknown";
1730
+ }
1731
+ }
1732
+ if (docIds.length === 0 && slugs.length === 0) {
1733
+ return entries;
1734
+ }
1735
+ let filterClause;
1736
+ if (docIds.length > 0 && slugs.length > 0) {
1737
+ filterClause = {
1738
+ $or: [
1739
+ { documentId: { $in: docIds } },
1740
+ { slug: { $in: slugs } }
1741
+ ]
1742
+ };
1743
+ } else if (docIds.length > 0) {
1744
+ filterClause = { documentId: { $in: docIds } };
1745
+ } else {
1746
+ filterClause = { slug: { $in: slugs } };
1747
+ }
1748
+ const queryFields = ["documentId", "updatedAt", "publishedAt"];
1749
+ if (hasSlugInSchema) {
1750
+ queryFields.push("slug");
1751
+ }
1752
+ let publishedRecords = [];
1753
+ try {
1754
+ const docService = strapi?.documents?.(uid);
1755
+ if (docService?.findMany) {
1756
+ publishedRecords = await docService.findMany({
1757
+ status: "published",
1758
+ filters: filterClause,
1759
+ fields: queryFields,
1760
+ limit: Math.max(entries.length, 100)
1761
+ });
1762
+ }
1763
+ } catch (err) {
1764
+ strapi?.log?.warn?.(`[bulk-updater] Failed to fetch published status for ${uid}: ${err?.message || err}`);
1765
+ for (const entry of entries) {
1766
+ if (entry && typeof entry === "object" && entry.status !== "unknown") {
1767
+ entry.status = "unknown";
1768
+ }
1769
+ }
1770
+ return entries;
1771
+ }
1772
+ const publishedByDocId = /* @__PURE__ */ new Map();
1773
+ const publishedBySlug = /* @__PURE__ */ new Map();
1774
+ for (const pub of publishedRecords || []) {
1775
+ if (pub?.documentId) {
1776
+ publishedByDocId.set(String(pub.documentId), pub);
1777
+ }
1778
+ if (pub?.slug && hasSlugInSchema) {
1779
+ publishedBySlug.set(String(pub.slug), pub);
1780
+ }
1781
+ }
1782
+ for (const entry of entries) {
1783
+ if (!entry || typeof entry !== "object") continue;
1784
+ if (entry.status === "unknown") continue;
1785
+ const pub = entry.documentId && publishedByDocId.get(String(entry.documentId)) || hasSlugInSchema && entry.slug && publishedBySlug.get(String(entry.slug));
1786
+ if (!pub) {
1787
+ entry.status = "draft";
1788
+ entry.publishedAt = null;
1789
+ entry.published_at = null;
1790
+ } else {
1791
+ entry.publishedAt = pub.publishedAt || pub.published_at || null;
1792
+ entry.published_at = entry.publishedAt;
1793
+ const draftUpdatedTime = new Date(entry.updatedAt || entry.updated_at || 0).getTime();
1794
+ const pubUpdatedTime = new Date(pub.updatedAt || pub.updated_at || 0).getTime();
1795
+ const pubPublishedTime = new Date(pub.publishedAt || pub.published_at || 0).getTime();
1796
+ const lastPublishedTime = Math.max(
1797
+ isNaN(pubUpdatedTime) ? 0 : pubUpdatedTime,
1798
+ isNaN(pubPublishedTime) ? 0 : pubPublishedTime
1799
+ );
1800
+ if (isNaN(draftUpdatedTime) || lastPublishedTime === 0) {
1801
+ if (pub.publishedAt) {
1802
+ entry.status = "published";
1803
+ } else {
1804
+ entry.status = "unknown";
1805
+ }
1806
+ } else if (draftUpdatedTime > lastPublishedTime) {
1807
+ entry.status = "modified";
1808
+ } else {
1809
+ entry.status = "published";
1810
+ }
1811
+ }
1812
+ }
1813
+ return entries;
1814
+ }
1815
+ function resolveContentTypeField(contentType, field) {
1816
+ if (!field) return null;
1817
+ const attrs = contentType?.attributes || {};
1818
+ if (attrs[field]) return field;
1819
+ if (field === "updated_at" || field === "updatedAt") {
1820
+ return attrs["updated_at"] ? "updated_at" : "updatedAt";
1821
+ }
1822
+ if (field === "created_at" || field === "createdAt") {
1823
+ return attrs["created_at"] ? "created_at" : "createdAt";
1824
+ }
1825
+ if (field === "published_at" || field === "publishedAt") {
1826
+ return attrs["published_at"] ? "published_at" : "publishedAt";
1827
+ }
1828
+ if (field === "id" || field === "documentId") {
1829
+ return field;
1830
+ }
1831
+ const camel = field.replace(/_([a-z0-9])/g, (_, l) => l.toUpperCase());
1832
+ if (attrs[camel]) return camel;
1833
+ const snake = field.replace(/([A-Z])/g, "_$1").toLowerCase();
1834
+ if (attrs[snake]) return snake;
1835
+ const lower = field.toLowerCase().replace(/_/g, "");
1836
+ const matched = Object.keys(attrs).find(
1837
+ (k) => k.toLowerCase().replace(/_/g, "") === lower
1838
+ );
1839
+ if (matched) return matched;
1840
+ return null;
1841
+ }
1842
+ function buildDeepPopulate$1(attributes, allComponents, depth = 0) {
1843
+ if (depth > 5) return void 0;
1844
+ const populate = {};
1845
+ for (const [key, def] of Object.entries(attributes || {})) {
1846
+ if (def.type === "component" && def.component) {
1847
+ const comp = allComponents[def.component];
1848
+ if (comp?.attributes) {
1849
+ const subPopulate = buildDeepPopulate$1(comp.attributes, allComponents, depth + 1);
1850
+ if (subPopulate && Object.keys(subPopulate).length > 0) {
1851
+ populate[key] = {
1852
+ populate: subPopulate
1853
+ };
1854
+ } else {
1855
+ populate[key] = true;
1856
+ }
1857
+ } else {
1858
+ populate[key] = true;
1859
+ }
1860
+ } else if (def.type === "dynamiczone") {
1861
+ populate[key] = {
1862
+ populate: "*"
1863
+ };
1864
+ } else if (def.type === "relation" || def.type === "media") {
1865
+ populate[key] = true;
1866
+ }
1867
+ }
1868
+ return Object.keys(populate).length > 0 ? populate : void 0;
1869
+ }
1870
+ function discoverComponentAttributes(strapi, compUid, prefix, currentDepth, maxDepth, systemFields, allContentTypes, relationsByAttr, allRelationsMeta, attributesMeta) {
1871
+ if (currentDepth > maxDepth || !compUid) return [];
1872
+ const compSchema = strapi.components[compUid];
1873
+ if (!compSchema?.attributes) return [];
1874
+ const discoveredAttrs = [];
1875
+ for (const [subKey, subAttr] of Object.entries(compSchema.attributes)) {
1876
+ if (systemFields.includes(subKey)) continue;
1877
+ const fullPath = prefix ? `${prefix}.${subKey}` : subKey;
1878
+ if (subAttr.type === "dynamiczone") {
1879
+ const dzComps = Array.isArray(subAttr.components) ? subAttr.components : [];
1880
+ for (const dzCompUid of dzComps) {
1881
+ const deeper = discoverComponentAttributes(
1882
+ strapi,
1883
+ dzCompUid,
1884
+ fullPath,
1885
+ currentDepth + 1,
1886
+ maxDepth,
1887
+ systemFields,
1288
1888
  allContentTypes,
1289
1889
  relationsByAttr,
1290
1890
  allRelationsMeta,
@@ -1779,9 +2379,14 @@ async function executeBatchInternal(strapi, {
1779
2379
  const getDocumentDeduplicated = (uid, documentId) => {
1780
2380
  const loaderKey = `${uid}@@@${documentId}`;
1781
2381
  if (!documentLoader.has(loaderKey)) {
2382
+ const ct = strapi.contentTypes[uid];
2383
+ const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
1782
2384
  documentLoader.set(
1783
2385
  loaderKey,
1784
- strapi.documents(uid).findOne({ documentId })
2386
+ strapi.documents(uid).findOne({
2387
+ documentId,
2388
+ ...populateDef ? { populate: populateDef } : { populate: "*" }
2389
+ })
1785
2390
  );
1786
2391
  }
1787
2392
  return documentLoader.get(loaderKey);
@@ -1865,6 +2470,21 @@ async function executeBatchInternal(strapi, {
1865
2470
  publishStrategy,
1866
2471
  unreviewedConsent
1867
2472
  });
2473
+ const proposedEntityComp = deepMergeEntities(currentEntryWithPopulate || currentEntry, { [rootKey]: updatedRoot });
2474
+ const valResultComp = await validateEntityQuotas(strapi, target.uid, proposedEntityComp);
2475
+ if (!valResultComp.isValid) {
2476
+ return {
2477
+ uid: target.uid,
2478
+ collectionName: displayName,
2479
+ documentId: target.documentId,
2480
+ label: entryLabel,
2481
+ attribute,
2482
+ oldValue: currentVal2 ?? null,
2483
+ newValue: newValue2,
2484
+ status: "error",
2485
+ message: valResultComp.errorMessage
2486
+ };
2487
+ }
1868
2488
  const updateArgsComp = {
1869
2489
  documentId: target.documentId,
1870
2490
  data: {
@@ -2002,6 +2622,21 @@ async function executeBatchInternal(strapi, {
2002
2622
  publishStrategy,
2003
2623
  unreviewedConsent
2004
2624
  });
2625
+ const proposedEntityRel = deepMergeEntities(currentEntry, { [attribute]: relationPayload });
2626
+ const valResultRel = await validateEntityQuotas(strapi, target.uid, proposedEntityRel);
2627
+ if (!valResultRel.isValid) {
2628
+ return {
2629
+ uid: target.uid,
2630
+ collectionName: displayName,
2631
+ documentId: target.documentId,
2632
+ label: entryLabel,
2633
+ attribute,
2634
+ oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
2635
+ newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
2636
+ status: "error",
2637
+ message: valResultRel.errorMessage
2638
+ };
2639
+ }
2005
2640
  const updateArgsRel = {
2006
2641
  documentId: target.documentId,
2007
2642
  data: {
@@ -2085,13 +2720,28 @@ async function executeBatchInternal(strapi, {
2085
2720
  publishStrategy,
2086
2721
  unreviewedConsent
2087
2722
  });
2088
- const updateArgsScalar = {
2089
- documentId: target.documentId,
2090
- data: {
2091
- [attribute]: newValue
2092
- }
2093
- };
2094
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
2723
+ const proposedEntityScalar = deepMergeEntities(currentEntry, { [attribute]: newValue });
2724
+ const valResultScalar = await validateEntityQuotas(strapi, target.uid, proposedEntityScalar);
2725
+ if (!valResultScalar.isValid) {
2726
+ return {
2727
+ uid: target.uid,
2728
+ collectionName: displayName,
2729
+ documentId: target.documentId,
2730
+ label: entryLabel,
2731
+ attribute,
2732
+ oldValue: currentVal ?? null,
2733
+ newValue,
2734
+ status: "error",
2735
+ message: valResultScalar.errorMessage
2736
+ };
2737
+ }
2738
+ const updateArgsScalar = {
2739
+ documentId: target.documentId,
2740
+ data: {
2741
+ [attribute]: newValue
2742
+ }
2743
+ };
2744
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
2095
2745
  updateArgsScalar.locale = candLocaleScalar;
2096
2746
  }
2097
2747
  await strapi.documents(target.uid).update(updateArgsScalar);
@@ -4472,7 +5122,7 @@ const auditService = ({ strapi }) => ({
4472
5122
  /**
4473
5123
  * Optionally writes an audit event directly to Strapi Enterprise's native Audit Logs table.
4474
5124
  */
4475
- async recordToEnterpriseNative(action, payload, user) {
5125
+ async recordToEnterpriseNative(action, payload2, user) {
4476
5126
  try {
4477
5127
  const eeService = this.getEnterpriseAuditService();
4478
5128
  if (eeService && typeof eeService.save === "function") {
@@ -4480,7 +5130,7 @@ const auditService = ({ strapi }) => ({
4480
5130
  action,
4481
5131
  date: /* @__PURE__ */ new Date(),
4482
5132
  userId: user?.id,
4483
- payload
5133
+ payload: payload2
4484
5134
  });
4485
5135
  strapi.log.info(
4486
5136
  `[bulk-updater] Successfully dispatched event to Strapi Enterprise Audit Log: ${action}`
@@ -4725,562 +5375,168 @@ const auditService = ({ strapi }) => ({
4725
5375
  [rootKey]: restoredRoot
4726
5376
  }
4727
5377
  });
4728
- } else {
4729
- const currentDoc = await strapi.documents(item.uid).findOne({
4730
- documentId: item.documentId
4731
- });
4732
- wasPublished = Boolean(currentDoc?.publishedAt);
4733
- await strapi.documents(item.uid).update({
4734
- documentId: item.documentId,
4735
- data: {
4736
- [item.attribute]: rollbackPayload
4737
- }
4738
- });
4739
- }
4740
- if (ct?.options?.draftAndPublish && wasPublished) {
4741
- try {
4742
- await strapi.documents(item.uid).publish({
4743
- documentId: item.documentId
4744
- });
4745
- } catch (publishErr) {
4746
- strapi.log.warn(`[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`, publishErr?.message);
4747
- }
4748
- }
4749
- try {
4750
- await recordContentHistoryVersion(strapi, {
4751
- uid: item.uid,
4752
- documentId: item.documentId,
4753
- userId,
4754
- statusOverride: ct?.options?.draftAndPublish ? wasPublished ? "published" : "draft" : void 0
4755
- });
4756
- } catch {
4757
- }
4758
- try {
4759
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
4760
- if (bulkService?.invalidateCache) {
4761
- bulkService.invalidateCache(item.uid);
4762
- }
4763
- } catch {
4764
- }
4765
- revertedCount++;
4766
- rollbackDetails.push({
4767
- uid: item.uid,
4768
- documentId: item.documentId,
4769
- label: item.label,
4770
- attribute: item.attribute,
4771
- revertedTo: item.oldValue,
4772
- status: "reverted"
4773
- });
4774
- } catch (err) {
4775
- rollbackDetails.push({
4776
- uid: item.uid,
4777
- documentId: item.documentId,
4778
- label: item.label,
4779
- status: "error",
4780
- message: err.message
4781
- });
4782
- }
4783
- }
4784
- }
4785
- return { revertedCount, rollbackDetails };
4786
- },
4787
- /**
4788
- * Performs deterministic rollback of a batch
4789
- */
4790
- async rollbackBatch(batchId, currentUser) {
4791
- const config = this.getAuditConfig();
4792
- if (!config.enabled) {
4793
- throw new Error("Audit trail is not configured or disabled.");
4794
- }
4795
- if (config.mode === "store") {
4796
- const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
4797
- const stored = await store.get({}) || { history: [] };
4798
- const history = Array.isArray(stored.history) ? stored.history : [];
4799
- const recordIndex = history.findIndex((r) => r.batchId === batchId);
4800
- if (recordIndex === -1) {
4801
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
4802
- }
4803
- const record2 = history[recordIndex];
4804
- if (record2.isRolledBack) {
4805
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
4806
- }
4807
- const diffs2 = Array.isArray(record2.diffs) ? record2.diffs : [];
4808
- const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
4809
- record2.isRolledBack = true;
4810
- record2.rolledBackAt = (/* @__PURE__ */ new Date()).toISOString();
4811
- record2.rolledBackBy = currentUser?.email || "Admin";
4812
- history[recordIndex] = record2;
4813
- await store.set({ value: { history } });
4814
- try {
4815
- const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
4816
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
4817
- affectedUids.forEach((uid) => {
4818
- if (uid && bulkService?.invalidateCache) {
4819
- bulkService.invalidateCache(uid);
4820
- }
4821
- });
4822
- } catch {
4823
- }
4824
- await this.recordToEnterpriseNative(
4825
- "bulk-updater.rollback",
4826
- {
4827
- batchId,
4828
- revertedCount: revertedCount2
4829
- },
4830
- currentUser
4831
- );
4832
- return {
4833
- success: true,
4834
- batchId,
4835
- revertedCount: revertedCount2,
4836
- details: rollbackDetails2
4837
- };
4838
- }
4839
- if (!config.contentType || !config.fields) {
4840
- throw new Error("Audit trail is not configured or disabled.");
4841
- }
4842
- const f = config.fields;
4843
- const records = await strapi.documents(config.contentType).findMany({
4844
- filters: {
4845
- [f.batchId]: { $eq: batchId }
4846
- }
4847
- });
4848
- const record = records?.[0];
4849
- if (!record) {
4850
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
4851
- }
4852
- if (record[f.isRolledBack]) {
4853
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
4854
- }
4855
- const diffs = typeof record[f.diffs] === "string" ? JSON.parse(record[f.diffs]) : record[f.diffs] || [];
4856
- const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
4857
- const updateData = {};
4858
- if (f.isRolledBack) updateData[f.isRolledBack] = true;
4859
- if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
4860
- if (f.rolledBackBy) {
4861
- updateData[f.rolledBackBy] = currentUser?.email || "Admin";
4862
- }
4863
- await strapi.documents(config.contentType).update({
4864
- documentId: record.documentId,
4865
- data: updateData
4866
- });
4867
- try {
4868
- const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
4869
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
4870
- affectedUids.forEach((uid) => {
4871
- if (uid && bulkService?.invalidateCache) {
4872
- bulkService.invalidateCache(uid);
4873
- }
4874
- });
4875
- } catch {
4876
- }
4877
- await this.recordToEnterpriseNative(
4878
- "bulk-updater.rollback",
4879
- {
4880
- batchId,
4881
- revertedCount
4882
- },
4883
- currentUser
4884
- );
4885
- return {
4886
- success: true,
4887
- batchId,
4888
- revertedCount,
4889
- details: rollbackDetails
4890
- };
4891
- }
4892
- });
4893
- const DEFAULT_RULES = [
4894
- {
4895
- id: "rule_seo_heading_h1",
4896
- name: "SEO Single H1 Page Rule",
4897
- description: "Enforces that only one H1 heading tag can be selected across all dynamic zone heading blocks within an entry, combined with rich text HTML.",
4898
- collectionUid: "*",
4899
- targetField: "headingLevel",
4900
- quotas: {
4901
- h1: 1,
4902
- h2: 3
4903
- },
4904
- exceededAction: "disable",
4905
- enabled: true,
4906
- scope: "entry",
4907
- includeRichTextHtml: true,
4908
- richTextFields: [],
4909
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4910
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4911
- }
4912
- ];
4913
- function extractHeadingsFromRichText(content) {
4914
- const counts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
4915
- if (!content) return counts;
4916
- if (Array.isArray(content)) {
4917
- for (const node of content) {
4918
- if (node && typeof node === "object") {
4919
- if (node.type === "heading" && typeof node.level === "number") {
4920
- const tag = `h${node.level}`;
4921
- if (counts[tag] !== void 0) counts[tag]++;
4922
- }
4923
- if (Array.isArray(node.children)) {
4924
- const sub = extractHeadingsFromRichText(node.children);
4925
- for (const k of Object.keys(counts)) counts[k] += sub[k];
4926
- }
4927
- }
4928
- }
4929
- return counts;
4930
- }
4931
- if (typeof content === "string") {
4932
- for (let level = 1; level <= 6; level++) {
4933
- const tag = `h${level}`;
4934
- const htmlMatches = content.match(new RegExp(`<${tag}\\b[^>]*>`, "gi"));
4935
- if (htmlMatches) {
4936
- counts[tag] += htmlMatches.length;
4937
- }
4938
- const mdRegex = new RegExp(`(?:^|\\n)${"#".repeat(level)}\\s+[^\\n]+`, "g");
4939
- const mdMatches = content.match(mdRegex);
4940
- if (mdMatches) {
4941
- counts[tag] += mdMatches.length;
4942
- }
4943
- }
4944
- }
4945
- return counts;
4946
- }
4947
- function cleanKey(str) {
4948
- return (str || "").replace(/[-_]/g, "").toLowerCase().trim();
4949
- }
4950
- function matchesPath(normalizedPath, leafKey, targetField) {
4951
- if (!targetField) return false;
4952
- const pClean = cleanKey(normalizedPath);
4953
- const kClean = cleanKey(leafKey);
4954
- const tClean = cleanKey(targetField);
4955
- if (kClean === tClean || pClean === tClean) return true;
4956
- const targetSegments = targetField.replace(/^api::/i, "").split(".").map(cleanKey).filter(Boolean);
4957
- const pathSegments = normalizedPath.split(".").map(cleanKey).filter(Boolean);
4958
- if (targetSegments.length === 0 || pathSegments.length === 0) return false;
4959
- if (targetSegments.length === 1) {
4960
- const single = targetSegments[0];
4961
- return kClean === single || pathSegments[pathSegments.length - 1] === single;
4962
- }
4963
- let isSuffix = true;
4964
- for (let i = 0; i < targetSegments.length; i++) {
4965
- const tSeg = targetSegments[targetSegments.length - 1 - i];
4966
- const pSeg = pathSegments[pathSegments.length - 1 - i];
4967
- if (tSeg !== "*" && tSeg !== pSeg) {
4968
- isSuffix = false;
4969
- break;
4970
- }
4971
- }
4972
- if (isSuffix) return true;
4973
- for (let startIdx = 1; startIdx < targetSegments.length; startIdx++) {
4974
- const subTarget = targetSegments.slice(startIdx);
4975
- if (subTarget.length > pathSegments.length) continue;
4976
- let subSuffix = true;
4977
- for (let i = 0; i < subTarget.length; i++) {
4978
- const tSeg = subTarget[subTarget.length - 1 - i];
4979
- const pSeg = pathSegments[pathSegments.length - 1 - i];
4980
- if (tSeg !== "*" && tSeg !== pSeg) {
4981
- subSuffix = false;
4982
- break;
4983
- }
4984
- }
4985
- if (subSuffix) return true;
4986
- }
4987
- let pIdx = 0;
4988
- let matchesInOrder = true;
4989
- let tStart = 0;
4990
- if (targetSegments.length > 2 && targetSegments[0] !== pathSegments[0] && targetSegments[0] !== "*") {
4991
- tStart = 1;
4992
- }
4993
- for (let tIdx = tStart; tIdx < targetSegments.length; tIdx++) {
4994
- const tSeg = targetSegments[tIdx];
4995
- if (tSeg === "*") continue;
4996
- let found = false;
4997
- while (pIdx < pathSegments.length) {
4998
- if (pathSegments[pIdx] === tSeg) {
4999
- found = true;
5000
- pIdx++;
5001
- break;
5002
- }
5003
- pIdx++;
5004
- }
5005
- if (!found) {
5006
- matchesInOrder = false;
5007
- break;
5008
- }
5009
- }
5010
- return matchesInOrder;
5011
- }
5012
- const validationRulesService = ({ strapi }) => ({
5013
- async getStore() {
5014
- return strapi.store({
5015
- type: "plugin",
5016
- name: "bulk-updater",
5017
- key: "validation-rules"
5018
- });
5019
- },
5020
- async getRules() {
5021
- const store = await this.getStore();
5022
- const stored = await store.get({});
5023
- if (!stored || !Array.isArray(stored.rules)) {
5024
- await store.set({ value: { rules: DEFAULT_RULES } });
5025
- return DEFAULT_RULES;
5026
- }
5027
- return stored.rules;
5028
- },
5029
- async saveRule(ruleData) {
5030
- const store = await this.getStore();
5031
- const rules = await this.getRules();
5032
- const now = (/* @__PURE__ */ new Date()).toISOString();
5033
- let savedRule;
5034
- if (ruleData.id) {
5035
- const index2 = rules.findIndex((r) => r.id === ruleData.id);
5036
- if (index2 !== -1) {
5037
- savedRule = {
5038
- ...rules[index2],
5039
- ...ruleData,
5040
- collectionUid: ruleData.collectionUid !== void 0 ? ruleData.collectionUid : rules[index2].collectionUid || "*",
5041
- includeRichTextHtml: ruleData.includeRichTextHtml !== void 0 ? Boolean(ruleData.includeRichTextHtml) : Boolean(rules[index2].includeRichTextHtml),
5042
- richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : rules[index2].richTextFields || [],
5043
- updatedAt: now
5044
- };
5045
- rules[index2] = savedRule;
5046
- } else {
5047
- savedRule = {
5048
- id: ruleData.id,
5049
- name: ruleData.name || "New Rule",
5050
- description: ruleData.description || "",
5051
- collectionUid: ruleData.collectionUid || "*",
5052
- targetField: ruleData.targetField || "headingLevel",
5053
- quotas: ruleData.quotas || { h1: 1 },
5054
- exceededAction: ruleData.exceededAction || "disable",
5055
- enabled: ruleData.enabled ?? true,
5056
- scope: ruleData.scope || "entry",
5057
- includeRichTextHtml: Boolean(ruleData.includeRichTextHtml),
5058
- richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : [],
5059
- createdAt: now,
5060
- updatedAt: now
5061
- };
5062
- rules.push(savedRule);
5063
- }
5064
- } else {
5065
- const id = `rule_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`;
5066
- savedRule = {
5067
- id,
5068
- name: ruleData.name || "Custom Quota Rule",
5069
- description: ruleData.description || "",
5070
- collectionUid: ruleData.collectionUid || "*",
5071
- targetField: ruleData.targetField || "headingLevel",
5072
- quotas: ruleData.quotas || { h1: 1 },
5073
- exceededAction: ruleData.exceededAction || "disable",
5074
- enabled: ruleData.enabled ?? true,
5075
- scope: ruleData.scope || "entry",
5076
- includeRichTextHtml: Boolean(ruleData.includeRichTextHtml),
5077
- richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : [],
5078
- createdAt: now,
5079
- updatedAt: now
5080
- };
5081
- rules.push(savedRule);
5082
- }
5083
- await store.set({ value: { rules } });
5084
- return savedRule;
5085
- },
5086
- async deleteRule(ruleId) {
5087
- const store = await this.getStore();
5088
- const rules = await this.getRules();
5089
- const filtered = rules.filter((r) => r.id !== ruleId);
5090
- await store.set({ value: { rules: filtered } });
5091
- return true;
5092
- },
5093
- async toggleRule(ruleId, enabled) {
5094
- const store = await this.getStore();
5095
- const rules = await this.getRules();
5096
- const index2 = rules.findIndex((r) => r.id === ruleId);
5097
- if (index2 === -1) return null;
5098
- const current = rules[index2];
5099
- const newEnabled = typeof enabled === "boolean" ? enabled : !current.enabled;
5100
- const updated = {
5101
- ...current,
5102
- enabled: newEnabled,
5103
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5104
- };
5105
- rules[index2] = updated;
5106
- await store.set({ value: { rules } });
5107
- return updated;
5108
- },
5109
- async scanViolations(ruleId) {
5110
- const rules = await this.getRules();
5111
- const rule = rules.find((r) => r.id === ruleId);
5112
- if (!rule) {
5113
- throw new Error(`Validation rule ${ruleId} not found`);
5114
- }
5115
- const targetField = rule.targetField;
5116
- const quotas = rule.quotas || {};
5117
- const violations = [];
5118
- let totalScanned = 0;
5119
- const allContentTypes = strapi.contentTypes || {};
5120
- const allComponents = strapi.components || {};
5121
- function componentHasField(compUid, targetField2) {
5122
- const comp = allComponents[compUid];
5123
- if (!comp?.attributes) return false;
5124
- if (matchesPath(compUid, compUid, targetField2)) return true;
5125
- for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
5126
- if (matchesPath(attrName, attrName, targetField2) || matchesPath(`${compUid}.${attrName}`, attrName, targetField2)) return true;
5127
- if (attrDef.type === "component" && attrDef.component) {
5128
- if (componentHasField(attrDef.component, targetField2)) return true;
5129
- } else if (attrDef.type === "dynamiczone" && Array.isArray(attrDef.components)) {
5130
- if (attrDef.components.some((c) => componentHasField(c, targetField2))) return true;
5131
- }
5132
- }
5133
- return false;
5134
- }
5135
- function schemaHasField(ctSchema) {
5136
- if (!ctSchema || !ctSchema.attributes) return { hasField: false, populateAttrs: {} };
5137
- const rawAttrs = ctSchema.attributes;
5138
- const populateAttrs = {};
5139
- let hasField = false;
5140
- for (const [attrKey, attrDef] of Object.entries(rawAttrs)) {
5141
- if (matchesPath(attrKey, attrKey, targetField)) {
5142
- hasField = true;
5143
- }
5144
- if (attrDef.type === "component" && attrDef.component) {
5145
- if (componentHasField(attrDef.component, targetField)) {
5146
- hasField = true;
5147
- populateAttrs[attrKey] = { populate: "*" };
5148
- }
5149
- } else if (attrDef.type === "dynamiczone" && Array.isArray(attrDef.components)) {
5150
- const matchingComp = attrDef.components.some(
5151
- (compUid) => componentHasField(compUid, targetField) || matchesPath(`${attrKey}.${compUid}`, compUid, targetField)
5152
- );
5153
- if (matchingComp) {
5154
- hasField = true;
5155
- populateAttrs[attrKey] = { populate: "*" };
5156
- }
5157
- }
5158
- }
5159
- return { hasField, populateAttrs };
5160
- }
5161
- const candidateUids = Object.keys(allContentTypes).filter((uid) => {
5162
- if (!uid.startsWith("api::") || uid.includes("bulk-updater")) return false;
5163
- if (rule.collectionUid && rule.collectionUid !== "*") {
5164
- if (rule.collectionUid === uid) return true;
5165
- const cleanRuleCol = cleanKey(rule.collectionUid);
5166
- const cleanUid = cleanKey(uid);
5167
- if (cleanUid.includes(cleanRuleCol) || cleanRuleCol.includes(cleanUid)) return true;
5168
- return false;
5169
- }
5170
- return true;
5171
- });
5172
- const relevantCollections = [];
5173
- for (const uid of candidateUids) {
5174
- const ct = allContentTypes[uid];
5175
- if (!ct) continue;
5176
- const { hasField, populateAttrs } = schemaHasField(ct);
5177
- const isTargetCol = rule.collectionUid && (rule.collectionUid === uid || cleanKey(uid).includes(cleanKey(rule.collectionUid)));
5178
- if (hasField || isTargetCol) {
5179
- relevantCollections.push({
5180
- uid,
5181
- displayName: ct.info?.displayName || uid,
5182
- populateOption: Object.keys(populateAttrs).length > 0 ? populateAttrs : "*"
5183
- });
5184
- }
5185
- }
5186
- const BATCH_SIZE = 250;
5187
- await Promise.all(
5188
- relevantCollections.map(async ({ uid, displayName, populateOption }) => {
5189
- try {
5190
- let page = 1;
5191
- while (true) {
5192
- const entries = await strapi.documents(uid).findMany({
5193
- page,
5194
- pageSize: BATCH_SIZE,
5195
- populate: populateOption
5196
- });
5197
- if (!entries || entries.length === 0) break;
5198
- for (const entry of entries) {
5199
- let traverse = function(obj, currentPath = "") {
5200
- if (!obj || typeof obj !== "object") return;
5201
- const compName = typeof obj.__component === "string" ? obj.__component : "";
5202
- for (const key of Object.keys(obj)) {
5203
- if (key === "__component") continue;
5204
- const val = obj[key];
5205
- const newPath = currentPath ? `${currentPath}.${key}` : key;
5206
- const normalizedPath = newPath.replace(/\.\d+/g, "");
5207
- const compPath = compName ? (currentPath ? `${currentPath}.${compName}.${key}` : `${compName}.${key}`).replace(/\.\d+/g, "") : "";
5208
- const isMatch = matchesPath(normalizedPath, key, targetField) || (compPath ? matchesPath(compPath, key, targetField) : false);
5209
- if (isMatch && typeof val === "string" && val.trim()) {
5210
- const lower = val.toLowerCase().trim();
5211
- structuredCounts[lower] = (structuredCounts[lower] || 0) + 1;
5212
- }
5213
- if (rule.includeRichTextHtml) {
5214
- if (typeof val === "string" && (val.includes("<h") || val.includes("#"))) {
5215
- const headings = extractHeadingsFromRichText(val);
5216
- for (const [tag, count] of Object.entries(headings)) {
5217
- if (count > 0) {
5218
- richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
5219
- }
5220
- }
5221
- } else if (Array.isArray(val) && val.length > 0 && typeof val[0] === "object" && val[0]?.type) {
5222
- const headings = extractHeadingsFromRichText(val);
5223
- for (const [tag, count] of Object.entries(headings)) {
5224
- if (count > 0) {
5225
- richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
5226
- }
5227
- }
5228
- continue;
5229
- }
5230
- }
5231
- if (typeof val === "object" && val !== null) {
5232
- traverse(val, newPath);
5233
- }
5234
- }
5235
- };
5236
- totalScanned++;
5237
- const structuredCounts = {};
5238
- const richTextCounts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
5239
- traverse(entry);
5240
- for (const [optKey, max] of Object.entries(quotas)) {
5241
- const lowerOpt = optKey.toLowerCase().trim();
5242
- const structCount = structuredCounts[lowerOpt] || 0;
5243
- const rtCount = rule.includeRichTextHtml ? richTextCounts[lowerOpt] || 0 : 0;
5244
- const combinedCount = structCount + rtCount;
5245
- if (combinedCount > max) {
5246
- const entryLabel = entry.title || entry.name || entry.email || `Entry #${entry.documentId}`;
5247
- let detail = "";
5248
- if (rtCount > 0 && structCount > 0) {
5249
- detail = `${structCount} structured + ${rtCount} in rich text HTML`;
5250
- } else if (rtCount > 0) {
5251
- detail = `${rtCount} in rich text HTML / Markdown`;
5252
- } else {
5253
- detail = `${structCount} in structured component`;
5254
- }
5255
- violations.push({
5256
- uid,
5257
- collectionDisplayName: displayName,
5258
- documentId: entry.documentId,
5259
- entryLabel,
5260
- violatingOption: optKey.toUpperCase(),
5261
- foundCount: combinedCount,
5262
- structuredCount: structCount,
5263
- richTextCount: rtCount,
5264
- maxAllowed: max,
5265
- detail,
5266
- editUrl: `/admin/content-manager/collection-types/${uid}/${entry.documentId}`
5267
- });
5268
- }
5378
+ } else {
5379
+ const currentDoc = await strapi.documents(item.uid).findOne({
5380
+ documentId: item.documentId
5381
+ });
5382
+ wasPublished = Boolean(currentDoc?.publishedAt);
5383
+ await strapi.documents(item.uid).update({
5384
+ documentId: item.documentId,
5385
+ data: {
5386
+ [item.attribute]: rollbackPayload
5269
5387
  }
5388
+ });
5389
+ }
5390
+ if (ct?.options?.draftAndPublish && wasPublished) {
5391
+ try {
5392
+ await strapi.documents(item.uid).publish({
5393
+ documentId: item.documentId
5394
+ });
5395
+ } catch (publishErr) {
5396
+ strapi.log.warn(`[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`, publishErr?.message);
5270
5397
  }
5271
- if (entries.length < BATCH_SIZE) break;
5272
- page++;
5273
5398
  }
5399
+ try {
5400
+ await recordContentHistoryVersion(strapi, {
5401
+ uid: item.uid,
5402
+ documentId: item.documentId,
5403
+ userId,
5404
+ statusOverride: ct?.options?.draftAndPublish ? wasPublished ? "published" : "draft" : void 0
5405
+ });
5406
+ } catch {
5407
+ }
5408
+ try {
5409
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5410
+ if (bulkService?.invalidateCache) {
5411
+ bulkService.invalidateCache(item.uid);
5412
+ }
5413
+ } catch {
5414
+ }
5415
+ revertedCount++;
5416
+ rollbackDetails.push({
5417
+ uid: item.uid,
5418
+ documentId: item.documentId,
5419
+ label: item.label,
5420
+ attribute: item.attribute,
5421
+ revertedTo: item.oldValue,
5422
+ status: "reverted"
5423
+ });
5274
5424
  } catch (err) {
5275
- strapi.log.warn(`[bulk-updater] Failed scanning ${uid} for rule ${ruleId}:`, err);
5425
+ rollbackDetails.push({
5426
+ uid: item.uid,
5427
+ documentId: item.documentId,
5428
+ label: item.label,
5429
+ status: "error",
5430
+ message: err.message
5431
+ });
5276
5432
  }
5277
- })
5433
+ }
5434
+ }
5435
+ return { revertedCount, rollbackDetails };
5436
+ },
5437
+ /**
5438
+ * Performs deterministic rollback of a batch
5439
+ */
5440
+ async rollbackBatch(batchId, currentUser) {
5441
+ const config = this.getAuditConfig();
5442
+ if (!config.enabled) {
5443
+ throw new Error("Audit trail is not configured or disabled.");
5444
+ }
5445
+ if (config.mode === "store") {
5446
+ const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
5447
+ const stored = await store.get({}) || { history: [] };
5448
+ const history = Array.isArray(stored.history) ? stored.history : [];
5449
+ const recordIndex = history.findIndex((r) => r.batchId === batchId);
5450
+ if (recordIndex === -1) {
5451
+ throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5452
+ }
5453
+ const record2 = history[recordIndex];
5454
+ if (record2.isRolledBack) {
5455
+ throw new Error(`Batch "${batchId}" has already been rolled back.`);
5456
+ }
5457
+ const diffs2 = Array.isArray(record2.diffs) ? record2.diffs : [];
5458
+ const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
5459
+ record2.isRolledBack = true;
5460
+ record2.rolledBackAt = (/* @__PURE__ */ new Date()).toISOString();
5461
+ record2.rolledBackBy = currentUser?.email || "Admin";
5462
+ history[recordIndex] = record2;
5463
+ await store.set({ value: { history } });
5464
+ try {
5465
+ const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
5466
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5467
+ affectedUids.forEach((uid) => {
5468
+ if (uid && bulkService?.invalidateCache) {
5469
+ bulkService.invalidateCache(uid);
5470
+ }
5471
+ });
5472
+ } catch {
5473
+ }
5474
+ await this.recordToEnterpriseNative(
5475
+ "bulk-updater.rollback",
5476
+ {
5477
+ batchId,
5478
+ revertedCount: revertedCount2
5479
+ },
5480
+ currentUser
5481
+ );
5482
+ return {
5483
+ success: true,
5484
+ batchId,
5485
+ revertedCount: revertedCount2,
5486
+ details: rollbackDetails2
5487
+ };
5488
+ }
5489
+ if (!config.contentType || !config.fields) {
5490
+ throw new Error("Audit trail is not configured or disabled.");
5491
+ }
5492
+ const f = config.fields;
5493
+ const records = await strapi.documents(config.contentType).findMany({
5494
+ filters: {
5495
+ [f.batchId]: { $eq: batchId }
5496
+ }
5497
+ });
5498
+ const record = records?.[0];
5499
+ if (!record) {
5500
+ throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5501
+ }
5502
+ if (record[f.isRolledBack]) {
5503
+ throw new Error(`Batch "${batchId}" has already been rolled back.`);
5504
+ }
5505
+ const diffs = typeof record[f.diffs] === "string" ? JSON.parse(record[f.diffs]) : record[f.diffs] || [];
5506
+ const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
5507
+ const updateData = {};
5508
+ if (f.isRolledBack) updateData[f.isRolledBack] = true;
5509
+ if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
5510
+ if (f.rolledBackBy) {
5511
+ updateData[f.rolledBackBy] = currentUser?.email || "Admin";
5512
+ }
5513
+ await strapi.documents(config.contentType).update({
5514
+ documentId: record.documentId,
5515
+ data: updateData
5516
+ });
5517
+ try {
5518
+ const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
5519
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5520
+ affectedUids.forEach((uid) => {
5521
+ if (uid && bulkService?.invalidateCache) {
5522
+ bulkService.invalidateCache(uid);
5523
+ }
5524
+ });
5525
+ } catch {
5526
+ }
5527
+ await this.recordToEnterpriseNative(
5528
+ "bulk-updater.rollback",
5529
+ {
5530
+ batchId,
5531
+ revertedCount
5532
+ },
5533
+ currentUser
5278
5534
  );
5279
5535
  return {
5280
- rule,
5281
- totalScanned,
5282
- totalViolations: violations.length,
5283
- violations
5536
+ success: true,
5537
+ batchId,
5538
+ revertedCount,
5539
+ details: rollbackDetails
5284
5540
  };
5285
5541
  }
5286
5542
  });
@@ -5713,8 +5969,12 @@ async function findExistingDocument(strapi, uid, targetDocId, docLocale) {
5713
5969
  if (!targetDocId) return null;
5714
5970
  const ct = strapi.contentTypes[uid];
5715
5971
  const effectiveLocale = getEffectiveLocale(ct, docLocale);
5972
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
5716
5973
  try {
5717
- const queryArgs = { documentId: targetDocId };
5974
+ const queryArgs = {
5975
+ documentId: targetDocId,
5976
+ ...populateDef ? { populate: populateDef } : { populate: "*" }
5977
+ };
5718
5978
  if (effectiveLocale) queryArgs.locale = effectiveLocale;
5719
5979
  const found = await strapi.documents(uid).findOne(queryArgs);
5720
5980
  if (found) return found;
@@ -5877,7 +6137,7 @@ function parseMediaValue(rawVal, isMultiple = false) {
5877
6137
  return isMultiple ? [] : null;
5878
6138
  }
5879
6139
  function parseRowToPayload(strapi, attrs, row) {
5880
- const payload = {};
6140
+ const payload2 = {};
5881
6141
  for (const [key, rawVal] of Object.entries(row)) {
5882
6142
  const normalizedKey = key.toLowerCase().replace(/[\s_-]/g, "");
5883
6143
  if (SYSTEM_FIELD_KEYS.has(normalizedKey)) continue;
@@ -5886,7 +6146,7 @@ function parseRowToPayload(strapi, attrs, row) {
5886
6146
  if (SYSTEM_FIELD_KEYS.has(topPart)) continue;
5887
6147
  const parts = key.split(".");
5888
6148
  let currentAttrs = attrs;
5889
- let currentTarget = payload;
6149
+ let currentTarget = payload2;
5890
6150
  for (let pIdx = 0; pIdx < parts.length; pIdx++) {
5891
6151
  const part = parts[pIdx];
5892
6152
  const isLeaf = pIdx === parts.length - 1;
@@ -5984,61 +6244,61 @@ function parseRowToPayload(strapi, attrs, row) {
5984
6244
  }
5985
6245
  if (rawVal === "" || rawVal === null || rawVal === void 0) {
5986
6246
  if (attrDef.type !== "dynamiczone" && !(attrDef.type === "component" && attrDef.repeatable) && attrDef.type !== "relation" && attrDef.type !== "password") {
5987
- payload[key] = null;
6247
+ payload2[key] = null;
5988
6248
  }
5989
6249
  continue;
5990
6250
  }
5991
6251
  switch (attrDef.type) {
5992
6252
  case "integer":
5993
6253
  case "biginteger":
5994
- payload[key] = parseNumberValue(rawVal, true);
6254
+ payload2[key] = parseNumberValue(rawVal, true);
5995
6255
  break;
5996
6256
  case "float":
5997
6257
  case "decimal":
5998
- payload[key] = parseNumberValue(rawVal, false);
6258
+ payload2[key] = parseNumberValue(rawVal, false);
5999
6259
  break;
6000
6260
  case "boolean":
6001
- payload[key] = parseBooleanValue(rawVal);
6261
+ payload2[key] = parseBooleanValue(rawVal);
6002
6262
  break;
6003
6263
  case "blocks":
6004
- payload[key] = parseBlocksValue(rawVal);
6264
+ payload2[key] = parseBlocksValue(rawVal);
6005
6265
  break;
6006
6266
  case "enumeration":
6007
- payload[key] = parseEnumValue(rawVal, attrDef.enum);
6267
+ payload2[key] = parseEnumValue(rawVal, attrDef.enum);
6008
6268
  break;
6009
6269
  case "relation":
6010
- payload[key] = parseRelationValue(rawVal, attrDef.relation);
6270
+ payload2[key] = parseRelationValue(rawVal, attrDef.relation);
6011
6271
  break;
6012
6272
  case "media":
6013
- payload[key] = parseMediaValue(rawVal, Boolean(attrDef.multiple));
6273
+ payload2[key] = parseMediaValue(rawVal, Boolean(attrDef.multiple));
6014
6274
  break;
6015
6275
  case "date":
6016
6276
  case "time":
6017
6277
  case "datetime":
6018
6278
  case "timestamp":
6019
- payload[key] = String(rawVal).trim() || null;
6279
+ payload2[key] = String(rawVal).trim() || null;
6020
6280
  break;
6021
6281
  case "email":
6022
6282
  case "uid":
6023
- payload[key] = String(rawVal).trim();
6283
+ payload2[key] = String(rawVal).trim();
6024
6284
  break;
6025
6285
  case "password":
6026
6286
  if (String(rawVal).trim()) {
6027
- payload[key] = String(rawVal).trim();
6287
+ payload2[key] = String(rawVal).trim();
6028
6288
  }
6029
6289
  break;
6030
6290
  case "json":
6031
6291
  try {
6032
- payload[key] = JSON.parse(rawVal);
6292
+ payload2[key] = JSON.parse(rawVal);
6033
6293
  } catch {
6034
- payload[key] = rawVal;
6294
+ payload2[key] = rawVal;
6035
6295
  }
6036
6296
  break;
6037
6297
  case "dynamiczone": {
6038
6298
  try {
6039
6299
  const parsed = JSON.parse(rawVal);
6040
6300
  if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object" && typeof item.__component === "string")) {
6041
- payload[key] = parsed;
6301
+ payload2[key] = parsed;
6042
6302
  }
6043
6303
  } catch {
6044
6304
  }
@@ -6049,7 +6309,7 @@ function parseRowToPayload(strapi, attrs, row) {
6049
6309
  try {
6050
6310
  const parsed = JSON.parse(rawVal);
6051
6311
  if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object")) {
6052
- payload[key] = parsed;
6312
+ payload2[key] = parsed;
6053
6313
  }
6054
6314
  } catch {
6055
6315
  }
@@ -6057,7 +6317,7 @@ function parseRowToPayload(strapi, attrs, row) {
6057
6317
  try {
6058
6318
  const parsed = JSON.parse(rawVal);
6059
6319
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6060
- payload[key] = parsed;
6320
+ payload2[key] = parsed;
6061
6321
  }
6062
6322
  } catch {
6063
6323
  }
@@ -6065,10 +6325,10 @@ function parseRowToPayload(strapi, attrs, row) {
6065
6325
  break;
6066
6326
  }
6067
6327
  default:
6068
- payload[key] = rawVal;
6328
+ payload2[key] = rawVal;
6069
6329
  }
6070
6330
  }
6071
- return payload;
6331
+ return payload2;
6072
6332
  }
6073
6333
  function formatValueDisplay(val) {
6074
6334
  if (val === null || val === void 0) return "(empty)";
@@ -6112,6 +6372,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6112
6372
  created: 0,
6113
6373
  updated: 0,
6114
6374
  skipped: 0,
6375
+ failed: 0,
6115
6376
  newWithoutDocId: 0,
6116
6377
  errors: [],
6117
6378
  diffs: []
@@ -6134,7 +6395,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6134
6395
  } catch {
6135
6396
  }
6136
6397
  }
6137
- const payload = parseRowToPayload(strapi, attrs, row);
6398
+ const payload2 = parseRowToPayload(strapi, attrs, row);
6138
6399
  try {
6139
6400
  if (mode === "update") {
6140
6401
  if (!docId) {
@@ -6156,10 +6417,10 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6156
6417
  continue;
6157
6418
  }
6158
6419
  const resolvedDocId = existing.documentId || docId;
6159
- const mergedPayload = { ...payload };
6160
- for (const key of Object.keys(payload)) {
6161
- if (attrs[key]?.type === "component" && typeof payload[key] === "object" && payload[key] !== null) {
6162
- mergedPayload[key] = deepMergeComponent(existing[key], payload[key]);
6420
+ const mergedPayload = { ...payload2 };
6421
+ for (const key of Object.keys(payload2)) {
6422
+ if (attrs[key]?.type === "component" && typeof payload2[key] === "object" && payload2[key] !== null) {
6423
+ mergedPayload[key] = deepMergeComponent(existing[key], payload2[key]);
6163
6424
  }
6164
6425
  }
6165
6426
  if (Object.keys(mergedPayload).length === 0) {
@@ -6214,6 +6475,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6214
6475
  data: mergedPayload
6215
6476
  };
6216
6477
  if (effectiveLocale) updateArgs.locale = effectiveLocale;
6478
+ const proposedEntity = deepMergeEntities(existing, mergedPayload);
6479
+ const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
6480
+ if (!valResult.isValid) {
6481
+ stats.skipped++;
6482
+ if (stats.failed !== void 0) stats.failed++;
6483
+ stats.errors.push({
6484
+ row: rowNumber,
6485
+ documentId: resolvedDocId,
6486
+ error: valResult.errorMessage
6487
+ });
6488
+ stats.diffs.push({
6489
+ uid,
6490
+ collectionName: ct.info?.displayName || uid,
6491
+ documentId: resolvedDocId,
6492
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6493
+ attribute: valResult.targetField || "",
6494
+ oldValue: existing?.[valResult.targetField || ""] ?? null,
6495
+ newValue: mergedPayload?.[valResult.targetField || ""] ?? null,
6496
+ status: "error",
6497
+ message: valResult.errorMessage
6498
+ });
6499
+ continue;
6500
+ }
6217
6501
  await strapi.documents(uid).update(updateArgs);
6218
6502
  if (shouldPublish) {
6219
6503
  try {
@@ -6234,9 +6518,9 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6234
6518
  } catch {
6235
6519
  }
6236
6520
  stats.updated++;
6237
- for (const attrKey of Object.keys(payload)) {
6521
+ for (const attrKey of Object.keys(payload2)) {
6238
6522
  const oldVal = existing?.[attrKey] ?? null;
6239
- const newVal = payload[attrKey];
6523
+ const newVal = payload2[attrKey];
6240
6524
  stats.diffs.push({
6241
6525
  uid,
6242
6526
  collectionName: ct.info?.displayName || uid,
@@ -6256,10 +6540,10 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6256
6540
  }
6257
6541
  if (existing) {
6258
6542
  const resolvedDocId = existing.documentId || docId;
6259
- const mergedPayload = { ...payload };
6260
- for (const key of Object.keys(payload)) {
6261
- if (attrs[key]?.type === "component" && typeof payload[key] === "object" && payload[key] !== null) {
6262
- mergedPayload[key] = deepMergeComponent(existing[key], payload[key]);
6543
+ const mergedPayload = { ...payload2 };
6544
+ for (const key of Object.keys(payload2)) {
6545
+ if (attrs[key]?.type === "component" && typeof payload2[key] === "object" && payload2[key] !== null) {
6546
+ mergedPayload[key] = deepMergeComponent(existing[key], payload2[key]);
6263
6547
  }
6264
6548
  }
6265
6549
  let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
@@ -6299,6 +6583,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6299
6583
  data: mergedPayload
6300
6584
  };
6301
6585
  if (effectiveLocale) updateArgs.locale = effectiveLocale;
6586
+ const proposedEntity = deepMergeEntities(existing, mergedPayload);
6587
+ const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
6588
+ if (!valResult.isValid) {
6589
+ stats.skipped++;
6590
+ if (stats.failed !== void 0) stats.failed++;
6591
+ stats.errors.push({
6592
+ row: rowNumber,
6593
+ documentId: resolvedDocId,
6594
+ error: valResult.errorMessage
6595
+ });
6596
+ stats.diffs.push({
6597
+ uid,
6598
+ collectionName: ct.info?.displayName || uid,
6599
+ documentId: resolvedDocId,
6600
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6601
+ attribute: valResult.targetField || "",
6602
+ oldValue: existing?.[valResult.targetField || ""] ?? null,
6603
+ newValue: mergedPayload?.[valResult.targetField || ""] ?? null,
6604
+ status: "error",
6605
+ message: valResult.errorMessage
6606
+ });
6607
+ continue;
6608
+ }
6302
6609
  await strapi.documents(uid).update(updateArgs);
6303
6610
  if (shouldPublish) {
6304
6611
  try {
@@ -6319,9 +6626,9 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6319
6626
  } catch {
6320
6627
  }
6321
6628
  stats.updated++;
6322
- for (const attrKey of Object.keys(payload)) {
6629
+ for (const attrKey of Object.keys(payload2)) {
6323
6630
  const oldVal = existing?.[attrKey] ?? null;
6324
- const newVal = payload[attrKey];
6631
+ const newVal = payload2[attrKey];
6325
6632
  stats.diffs.push({
6326
6633
  uid,
6327
6634
  collectionName: ct.info?.displayName || uid,
@@ -6336,7 +6643,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6336
6643
  }
6337
6644
  continue;
6338
6645
  }
6339
- const createArgs = { data: payload };
6646
+ const valResultNew = await validateEntityQuotas(strapi, uid, payload2);
6647
+ if (!valResultNew.isValid) {
6648
+ stats.skipped++;
6649
+ if (stats.failed !== void 0) stats.failed++;
6650
+ stats.errors.push({
6651
+ row: rowNumber,
6652
+ documentId: docId || "new",
6653
+ error: valResultNew.errorMessage
6654
+ });
6655
+ stats.diffs.push({
6656
+ uid,
6657
+ collectionName: ct.info?.displayName || uid,
6658
+ documentId: docId || "new",
6659
+ label: `Row ${rowNumber}`,
6660
+ attribute: valResultNew.targetField || "",
6661
+ oldValue: null,
6662
+ newValue: payload2?.[valResultNew.targetField || ""] ?? null,
6663
+ status: "error",
6664
+ message: valResultNew.errorMessage
6665
+ });
6666
+ continue;
6667
+ }
6668
+ const createArgs = { data: payload2 };
6340
6669
  if (effectiveLocale) createArgs.locale = effectiveLocale;
6341
6670
  const created = await strapi.documents(uid).create(createArgs);
6342
6671
  const newDocId = created?.documentId || docId;
@@ -6363,7 +6692,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6363
6692
  if (!docId) {
6364
6693
  stats.newWithoutDocId++;
6365
6694
  }
6366
- for (const attrKey of Object.keys(payload)) {
6695
+ for (const attrKey of Object.keys(payload2)) {
6367
6696
  stats.diffs.push({
6368
6697
  uid,
6369
6698
  collectionName: ct.info?.displayName || uid,
@@ -6371,7 +6700,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6371
6700
  label: created?.title || created?.name || `New Entry #${newDocId}`,
6372
6701
  attribute: attrKey,
6373
6702
  oldValue: null,
6374
- newValue: payload[attrKey],
6703
+ newValue: payload2[attrKey],
6375
6704
  status: "created",
6376
6705
  message: docId ? `Created "${attrKey}" via CSV import (row ${rowNumber})` : `Created "${attrKey}" as new entry (row ${rowNumber})`
6377
6706
  });
@@ -6383,10 +6712,10 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6383
6712
  }
6384
6713
  if (existing) {
6385
6714
  const resolvedDocId = existing.documentId || docId;
6386
- const mergedPayload = { ...payload };
6387
- for (const key of Object.keys(payload)) {
6388
- if (attrs[key]?.type === "component" && typeof payload[key] === "object" && payload[key] !== null) {
6389
- mergedPayload[key] = deepMergeComponent(existing[key], payload[key]);
6715
+ const mergedPayload = { ...payload2 };
6716
+ for (const key of Object.keys(payload2)) {
6717
+ if (attrs[key]?.type === "component" && typeof payload2[key] === "object" && payload2[key] !== null) {
6718
+ mergedPayload[key] = deepMergeComponent(existing[key], payload2[key]);
6390
6719
  }
6391
6720
  }
6392
6721
  let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
@@ -6426,6 +6755,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6426
6755
  data: mergedPayload
6427
6756
  };
6428
6757
  if (effectiveLocale) updateArgs.locale = effectiveLocale;
6758
+ const proposedEntity = deepMergeEntities(existing, mergedPayload);
6759
+ const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
6760
+ if (!valResult.isValid) {
6761
+ stats.skipped++;
6762
+ if (stats.failed !== void 0) stats.failed++;
6763
+ stats.errors.push({
6764
+ row: rowNumber,
6765
+ documentId: resolvedDocId,
6766
+ error: valResult.errorMessage
6767
+ });
6768
+ stats.diffs.push({
6769
+ uid,
6770
+ collectionName: ct.info?.displayName || uid,
6771
+ documentId: resolvedDocId,
6772
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6773
+ attribute: valResult.targetField || "",
6774
+ oldValue: existing?.[valResult.targetField || ""] ?? null,
6775
+ newValue: mergedPayload?.[valResult.targetField || ""] ?? null,
6776
+ status: "error",
6777
+ message: valResult.errorMessage
6778
+ });
6779
+ continue;
6780
+ }
6429
6781
  await strapi.documents(uid).update(updateArgs);
6430
6782
  if (shouldPublish) {
6431
6783
  try {
@@ -6446,9 +6798,9 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6446
6798
  } catch {
6447
6799
  }
6448
6800
  stats.updated++;
6449
- for (const attrKey of Object.keys(payload)) {
6801
+ for (const attrKey of Object.keys(payload2)) {
6450
6802
  const oldVal = existing?.[attrKey] ?? null;
6451
- const newVal = payload[attrKey];
6803
+ const newVal = payload2[attrKey];
6452
6804
  stats.diffs.push({
6453
6805
  uid,
6454
6806
  collectionName: ct.info?.displayName || uid,
@@ -6463,7 +6815,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6463
6815
  }
6464
6816
  continue;
6465
6817
  }
6466
- const createArgs = { data: payload };
6818
+ const valResultNew = await validateEntityQuotas(strapi, uid, payload2);
6819
+ if (!valResultNew.isValid) {
6820
+ stats.skipped++;
6821
+ if (stats.failed !== void 0) stats.failed++;
6822
+ stats.errors.push({
6823
+ row: rowNumber,
6824
+ documentId: docId || "new",
6825
+ error: valResultNew.errorMessage
6826
+ });
6827
+ stats.diffs.push({
6828
+ uid,
6829
+ collectionName: ct.info?.displayName || uid,
6830
+ documentId: docId || "new",
6831
+ label: `Row ${rowNumber}`,
6832
+ attribute: valResultNew.targetField || "",
6833
+ oldValue: null,
6834
+ newValue: payload2?.[valResultNew.targetField || ""] ?? null,
6835
+ status: "error",
6836
+ message: valResultNew.errorMessage
6837
+ });
6838
+ continue;
6839
+ }
6840
+ const createArgs = { data: payload2 };
6467
6841
  if (effectiveLocale) createArgs.locale = effectiveLocale;
6468
6842
  const created = await strapi.documents(uid).create(createArgs);
6469
6843
  const newDocId = created?.documentId || docId;
@@ -6490,7 +6864,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6490
6864
  if (!docId) {
6491
6865
  stats.newWithoutDocId++;
6492
6866
  }
6493
- for (const attrKey of Object.keys(payload)) {
6867
+ for (const attrKey of Object.keys(payload2)) {
6494
6868
  stats.diffs.push({
6495
6869
  uid,
6496
6870
  collectionName: ct.info?.displayName || uid,
@@ -6498,7 +6872,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6498
6872
  label: created?.title || created?.name || `New Entry #${newDocId}`,
6499
6873
  attribute: attrKey,
6500
6874
  oldValue: null,
6501
- newValue: payload[attrKey],
6875
+ newValue: payload2[attrKey],
6502
6876
  status: "created",
6503
6877
  message: docId ? `Created "${attrKey}" as new entry (documentId "${docId}" not found in database - row ${rowNumber})` : `Created "${attrKey}" as new entry (no documentId provided in CSV - row ${rowNumber})`
6504
6878
  });
@@ -6907,6 +7281,7 @@ const csvService = ({ strapi }) => ({
6907
7281
  created: 0,
6908
7282
  updated: 0,
6909
7283
  skipped: 0,
7284
+ failed: 0,
6910
7285
  newWithoutDocId: 0,
6911
7286
  errors: [],
6912
7287
  diffs: [],
@@ -6921,6 +7296,7 @@ const csvService = ({ strapi }) => ({
6921
7296
  session.created += chunkStats.created;
6922
7297
  session.updated += chunkStats.updated;
6923
7298
  session.skipped += chunkStats.skipped;
7299
+ session.failed = (session.failed || 0) + (chunkStats.failed || 0);
6924
7300
  session.newWithoutDocId += chunkStats.newWithoutDocId;
6925
7301
  session.errors.push(...chunkStats.errors);
6926
7302
  session.diffs.push(...chunkStats.diffs);
@@ -6948,6 +7324,7 @@ const csvService = ({ strapi }) => ({
6948
7324
  created: session.created,
6949
7325
  updated: session.updated,
6950
7326
  skipped: session.skipped,
7327
+ failed: session.failed || 0,
6951
7328
  newWithoutDocId: session.newWithoutDocId,
6952
7329
  errors: session.errors,
6953
7330
  diffs: session.diffs
@@ -7224,7 +7601,7 @@ const csvService = ({ strapi }) => ({
7224
7601
  if (activeRules.length > 0) {
7225
7602
  for (const rule of activeRules) {
7226
7603
  if (rule.collectionUid && rule.collectionUid !== "*" && rule.collectionUid !== uid) continue;
7227
- if (rule.includeRichTextHtml && (rawVal.includes("<h") || rawVal.includes("# "))) {
7604
+ if (rule.includeRichTextHtml && (/<h[1-6]\b/i.test(rawVal) || rawVal.includes("# "))) {
7228
7605
  const headings = extractHeadingsFromRichText(rawVal);
7229
7606
  for (const [tag, count] of Object.entries(headings)) {
7230
7607
  const max = rule.quotas?.[tag.toLowerCase()];
@@ -7240,6 +7617,18 @@ const csvService = ({ strapi }) => ({
7240
7617
  }
7241
7618
  }
7242
7619
  }
7620
+ if (activeRules.length > 0) {
7621
+ const proposedEntity = existing ? deepMergeEntities(existing, payload) : payload;
7622
+ const valResult = await validateEntityQuotas(strapi, uid, proposedEntity, activeRules);
7623
+ if (!valResult.isValid) {
7624
+ errors.push({
7625
+ row: rowNumber,
7626
+ documentId: docId || void 0,
7627
+ error: valResult.errorMessage
7628
+ });
7629
+ rowHasError = true;
7630
+ }
7631
+ }
7243
7632
  if (!rowHasError) {
7244
7633
  validRows++;
7245
7634
  }
@@ -7315,12 +7704,12 @@ const csvService = ({ strapi }) => ({
7315
7704
  });
7316
7705
  continue;
7317
7706
  }
7318
- const payload = parseRowToPayload(strapi, attrs, row);
7707
+ const payload2 = parseRowToPayload(strapi, attrs, row);
7319
7708
  if (existing) {
7320
7709
  const resolvedDocId = existing.documentId || docId;
7321
7710
  const entryLabel = existing.title || existing.name || existing.slug || `Entry #${resolvedDocId}`;
7322
7711
  let rowHasChanges = false;
7323
- const payloadKeys = Object.keys(payload);
7712
+ const payloadKeys = Object.keys(payload2);
7324
7713
  if (payloadKeys.length === 0) {
7325
7714
  unchangedCount++;
7326
7715
  diffs.push({
@@ -7341,7 +7730,7 @@ const csvService = ({ strapi }) => ({
7341
7730
  } else {
7342
7731
  for (const attrKey of payloadKeys) {
7343
7732
  const oldVal = existing?.[attrKey] ?? null;
7344
- let newVal = payload[attrKey];
7733
+ let newVal = payload2[attrKey];
7345
7734
  if (attrs[attrKey]?.type === "component" && typeof newVal === "object" && newVal !== null) {
7346
7735
  newVal = deepMergeComponent(existing[attrKey], newVal);
7347
7736
  }
@@ -7376,8 +7765,8 @@ const csvService = ({ strapi }) => ({
7376
7765
  } else {
7377
7766
  willCreateCount++;
7378
7767
  const resolvedDocId = docId || `(Auto-generated)`;
7379
- const entryLabel = payload.title || payload.name || payload.slug || `New Entry (Row #${rowNumber})`;
7380
- const payloadKeys = Object.keys(payload);
7768
+ const entryLabel = payload2.title || payload2.name || payload2.slug || `New Entry (Row #${rowNumber})`;
7769
+ const payloadKeys = Object.keys(payload2);
7381
7770
  if (payloadKeys.length === 0) {
7382
7771
  diffs.push({
7383
7772
  uid,
@@ -7396,7 +7785,7 @@ const csvService = ({ strapi }) => ({
7396
7785
  });
7397
7786
  } else {
7398
7787
  for (const attrKey of payloadKeys) {
7399
- const newVal = payload[attrKey];
7788
+ const newVal = payload2[attrKey];
7400
7789
  diffs.push({
7401
7790
  uid,
7402
7791
  collectionName: ct.info?.displayName || uid,
@@ -7744,139 +8133,28 @@ const index = {
7744
8133
  if (["create", "update"].includes(context.action)) {
7745
8134
  const data = params?.data;
7746
8135
  if (data && typeof data === "object") {
7747
- let scanDataTree = function(obj, currentPath = "") {
7748
- if (!obj || typeof obj !== "object") return;
7749
- const compName = typeof obj.__component === "string" ? obj.__component : "";
7750
- for (const key of Object.keys(obj)) {
7751
- if (key === "__component") continue;
7752
- const val = obj[key];
7753
- const newPath = currentPath ? `${currentPath}.${key}` : key;
7754
- const normalizedPath = newPath.replace(/\.\d+/g, "");
7755
- const compPath = compName ? (currentPath ? `${currentPath}.${compName}.${key}` : `${compName}.${key}`).replace(/\.\d+/g, "") : "";
7756
- for (const rule of effectiveRules) {
7757
- const isMatch = matchesPath(normalizedPath, key, rule.targetField) || (compPath ? matchesPath(compPath, key, rule.targetField) : false);
7758
- if (isMatch && typeof val === "string" && val.trim()) {
7759
- const lowerVal = val.toLowerCase().trim();
7760
- structuredCounts[rule.id] = structuredCounts[rule.id] || {};
7761
- structuredCounts[rule.id][lowerVal] = (structuredCounts[rule.id][lowerVal] || 0) + 1;
7762
- }
7763
- }
7764
- if (typeof val === "string" && (val.includes("<h") || val.includes("#"))) {
7765
- const headings = extractHeadingsFromRichText(val);
7766
- for (const [tag, count] of Object.entries(headings)) {
7767
- if (count > 0) {
7768
- richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
7769
- }
7770
- }
7771
- } else if (Array.isArray(val) && val.length > 0 && typeof val[0] === "object" && val[0]?.type) {
7772
- const headings = extractHeadingsFromRichText(val);
7773
- for (const [tag, count] of Object.entries(headings)) {
7774
- if (count > 0) {
7775
- richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
7776
- }
7777
- }
7778
- continue;
7779
- }
7780
- if (typeof val === "object" && val !== null) {
7781
- scanDataTree(val, newPath);
7782
- }
7783
- }
7784
- };
7785
- let activeUiRules = [];
7786
- try {
7787
- const rulesService = strapi.plugin("bulk-updater").service("validationRules");
7788
- if (rulesService) {
7789
- const allRules = await rulesService.getRules();
7790
- activeUiRules = allRules.filter((r) => r.enabled);
7791
- }
7792
- } catch (err) {
7793
- strapi.log.warn("[bulk-updater] Failed to fetch active UI validation rules:", err);
7794
- }
7795
- const effectiveRules = [
7796
- ...activeUiRules.filter((r) => {
7797
- if (!r.collectionUid || r.collectionUid === "*") return true;
7798
- if (r.collectionUid === context.uid) return true;
7799
- const cleanRuleCol = cleanKey(r.collectionUid);
7800
- const cleanCtxCol = cleanKey(context.uid);
7801
- return cleanCtxCol.includes(cleanRuleCol) || cleanRuleCol.includes(cleanCtxCol);
7802
- }).map((r) => ({
7803
- id: r.id || r.targetField,
7804
- name: r.name || r.targetField,
7805
- collectionUid: r.collectionUid || "*",
7806
- targetField: r.targetField,
7807
- quotas: r.quotas || {},
7808
- includeRichTextHtml: Boolean(r.includeRichTextHtml),
7809
- richTextFields: r.richTextFields || []
7810
- }))
7811
- ];
7812
- const allComponents = strapi.components || {};
7813
- for (const comp of Object.values(allComponents)) {
7814
- const attrs = comp.attributes || {};
7815
- for (const [attrName, attrDef] of Object.entries(attrs)) {
7816
- if (attrDef.type === "customField" && (attrDef.customField === "plugin::bulk-updater.scoped-select" || attrDef.customField === "global::scoped-select") && !effectiveRules.some((r) => matchesPath(attrName, attrName, r.targetField))) {
7817
- const quotas = attrDef.options?.quotas || {};
7818
- const items = attrDef.options?.items || [];
7819
- const itemQuotas = {};
7820
- for (const item of items) {
7821
- if (typeof item.maxAllowed === "number" && item.maxAllowed > 0) {
7822
- itemQuotas[item.value] = item.maxAllowed;
7823
- }
7824
- }
7825
- effectiveRules.push({
7826
- id: `schema_${attrName}`,
7827
- name: `${attrName} quota rule`,
7828
- collectionUid: "*",
7829
- targetField: attrName,
7830
- quotas: {
7831
- h1: 1,
7832
- h2: 3,
7833
- ...itemQuotas,
7834
- ...quotas
7835
- },
7836
- includeRichTextHtml: true,
7837
- richTextFields: []
7838
- });
7839
- }
7840
- }
7841
- }
7842
- const structuredCounts = {};
7843
- const richTextCounts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
7844
- let dataToScan = data;
8136
+ let fullEntity = data;
7845
8137
  if (context.action === "update" && (params?.documentId || params?.where?.documentId)) {
7846
8138
  const docId = params?.documentId || params?.where?.documentId;
7847
8139
  if (context.uid && docId) {
7848
8140
  try {
7849
- const existing = await strapi.db?.query?.(context.uid)?.findOne?.({
7850
- where: { documentId: docId },
7851
- populate: true
8141
+ const ct = strapi.contentTypes[context.uid];
8142
+ const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
8143
+ const existing = await strapi.documents(context.uid).findOne({
8144
+ documentId: docId,
8145
+ ...params?.locale ? { locale: params.locale } : {},
8146
+ ...populateDef ? { populate: populateDef } : { populate: "*" }
7852
8147
  });
7853
8148
  if (existing) {
7854
- dataToScan = { ...existing, ...data };
8149
+ fullEntity = deepMergeEntities(existing, data);
7855
8150
  }
7856
8151
  } catch {
7857
8152
  }
7858
8153
  }
7859
8154
  }
7860
- scanDataTree(dataToScan);
7861
- for (const rule of effectiveRules) {
7862
- const ruleCounts = structuredCounts[rule.id] || {};
7863
- for (const [quotaKey, maxAllowed] of Object.entries(rule.quotas || {})) {
7864
- const lowerVal = quotaKey.toLowerCase().trim();
7865
- const structCount = ruleCounts[lowerVal] || 0;
7866
- const rtCount = rule.includeRichTextHtml ? richTextCounts[lowerVal] || 0 : 0;
7867
- const totalFound = structCount + rtCount;
7868
- if (totalFound > maxAllowed) {
7869
- let detailMsg = `Option "${quotaKey.toUpperCase()}" cannot appear more than ${maxAllowed} time(s) across this entry.`;
7870
- if (rtCount > 0 && structCount > 0) {
7871
- detailMsg += ` Found ${totalFound} occurrences combined: ${structCount} in structured component ('${rule.targetField}') and ${rtCount} in rich text HTML / Markdown.`;
7872
- } else if (rtCount > 0) {
7873
- detailMsg += ` Found ${totalFound} in rich text HTML / Markdown content.`;
7874
- } else {
7875
- detailMsg += ` Found ${totalFound} in structured field '${rule.targetField}'.`;
7876
- }
7877
- throw createValidationError(rule.name, detailMsg, rule.targetField);
7878
- }
7879
- }
8155
+ const valResult = await validateEntityQuotas(strapi, context.uid, fullEntity);
8156
+ if (!valResult.isValid) {
8157
+ throw createValidationError(valResult.ruleName, valResult.errorMessage, valResult.targetField);
7880
8158
  }
7881
8159
  }
7882
8160
  }