strapi-plugin-bulk-updater 1.5.13 → 1.5.15

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.
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
2
3
  const crypto = require("crypto");
3
4
  const utils = require("@strapi/utils");
4
5
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
@@ -641,7 +642,7 @@ const csvController = ({ strapi }) => ({
641
642
  async exportCollection(ctx) {
642
643
  try {
643
644
  const { uid } = ctx.params;
644
- const { search, attribute, filterOperator, filterQuery, limit, documentIds } = {
645
+ const { search, attribute, searchAttribute, filterOperator, filterQuery, limit, documentIds } = {
645
646
  ...ctx.query,
646
647
  ...ctx.request?.body || {}
647
648
  };
@@ -653,6 +654,7 @@ const csvController = ({ strapi }) => ({
653
654
  const result = await csvService2.exportCollectionCsv(uid, {
654
655
  search: search ? String(search) : void 0,
655
656
  attribute: attribute ? String(attribute) : void 0,
657
+ searchAttribute: searchAttribute ? String(searchAttribute) : void 0,
656
658
  filterOperator: filterOperator ? String(filterOperator) : void 0,
657
659
  filterQuery: filterQuery !== void 0 ? String(filterQuery) : void 0,
658
660
  limit: limit ? Number(limit) : void 0,
@@ -1839,14 +1841,14 @@ function resolveContentTypeField(contentType, field) {
1839
1841
  if (matched) return matched;
1840
1842
  return null;
1841
1843
  }
1842
- function buildDeepPopulate$1(attributes, allComponents, depth = 0) {
1844
+ function buildDeepPopulate(attributes, allComponents, depth = 0) {
1843
1845
  if (depth > 5) return void 0;
1844
1846
  const populate = {};
1845
1847
  for (const [key, def] of Object.entries(attributes || {})) {
1846
1848
  if (def.type === "component" && def.component) {
1847
1849
  const comp = allComponents[def.component];
1848
1850
  if (comp?.attributes) {
1849
- const subPopulate = buildDeepPopulate$1(comp.attributes, allComponents, depth + 1);
1851
+ const subPopulate = buildDeepPopulate(comp.attributes, allComponents, depth + 1);
1850
1852
  if (subPopulate && Object.keys(subPopulate).length > 0) {
1851
1853
  populate[key] = {
1852
1854
  populate: subPopulate
@@ -2135,6 +2137,173 @@ function buildDeepFilter(pathParts, condition) {
2135
2137
  [head]: buildDeepFilter(tail, condition)
2136
2138
  };
2137
2139
  }
2140
+ function buildCollectionQueryFilters(strapi, contentType, options = {}) {
2141
+ const filters = {};
2142
+ const attrs = contentType?.attributes || {};
2143
+ const targetFilterAttr = options.searchAttribute || options.attribute || "";
2144
+ const normOp = (options.filterOperator || "").toLowerCase().replace(/_/g, "");
2145
+ const q = (options.filterQuery || "").trim();
2146
+ if (options.documentIds && Array.isArray(options.documentIds) && options.documentIds.length > 0) {
2147
+ filters.documentId = { $in: options.documentIds };
2148
+ }
2149
+ let colHasAttribute = false;
2150
+ let isNestedAttr = false;
2151
+ let isRootDz = false;
2152
+ let parts = [];
2153
+ let resolvedFilterAttr = targetFilterAttr;
2154
+ if (targetFilterAttr) {
2155
+ const resolvedField = resolveContentTypeField(contentType, targetFilterAttr);
2156
+ if (resolvedField) {
2157
+ resolvedFilterAttr = resolvedField;
2158
+ colHasAttribute = true;
2159
+ } else {
2160
+ const parsed = parseDynamicZonePath(targetFilterAttr);
2161
+ if (parsed.rootKey && contentType.attributes?.[parsed.rootKey]?.type === "dynamiczone") {
2162
+ isRootDz = true;
2163
+ colHasAttribute = true;
2164
+ isNestedAttr = true;
2165
+ parts = parsed.cleanPath.split(".");
2166
+ } else if (targetFilterAttr.includes(".") || targetFilterAttr.includes("[")) {
2167
+ isNestedAttr = isDeepComponentField(contentType, strapi?.components || {}, targetFilterAttr);
2168
+ if (isNestedAttr) {
2169
+ colHasAttribute = true;
2170
+ parts = parsed.cleanPath.split(".");
2171
+ }
2172
+ }
2173
+ }
2174
+ }
2175
+ if (normOp && normOp !== "none" && targetFilterAttr) {
2176
+ if (!colHasAttribute) {
2177
+ return {
2178
+ filters,
2179
+ colHasAttribute: false,
2180
+ isRootDz: false,
2181
+ targetFilterAttr,
2182
+ normOp,
2183
+ filterQuery: q
2184
+ };
2185
+ }
2186
+ let condition = void 0;
2187
+ const targetAttrSchema = isNestedAttr ? getLeafAttributeSchema(contentType, strapi?.components || {}, targetFilterAttr) : attrs[resolvedFilterAttr];
2188
+ const isRelation = targetAttrSchema?.type === "relation";
2189
+ const isStringLike = ["string", "text", "email", "richtext", "uid"].includes(targetAttrSchema?.type);
2190
+ if (isRelation) {
2191
+ const targetUid = targetAttrSchema?.target;
2192
+ const targetContentType = targetUid && strapi?.contentTypes ? strapi.contentTypes[targetUid] : void 0;
2193
+ const targetAttrs = targetContentType?.attributes || {};
2194
+ const targetStringAttrs = Object.keys(targetAttrs).filter(
2195
+ (k) => ["string", "text", "email", "uid"].includes(targetAttrs[k]?.type)
2196
+ );
2197
+ if (normOp === "empty") {
2198
+ condition = { documentId: { $null: true } };
2199
+ } else if (normOp === "notempty") {
2200
+ condition = { documentId: { $notNull: true } };
2201
+ } else if (q !== "") {
2202
+ const orConditions = [];
2203
+ targetStringAttrs.slice(0, 5).forEach((k) => {
2204
+ if (normOp === "equals") {
2205
+ orConditions.push({ [k]: { $eqi: q } });
2206
+ } else if (normOp === "startswith") {
2207
+ orConditions.push({ [k]: { $startsWithi: q } });
2208
+ } else if (normOp === "endswith") {
2209
+ orConditions.push({ [k]: { $endsWithi: q } });
2210
+ } else if (normOp === "notequals") {
2211
+ orConditions.push({ [k]: { $nei: q } });
2212
+ } else if (normOp === "notcontains") {
2213
+ orConditions.push({ [k]: { $notContainsi: q } });
2214
+ } else {
2215
+ orConditions.push({ [k]: { $containsi: q } });
2216
+ }
2217
+ });
2218
+ orConditions.push({ documentId: { $eq: q } });
2219
+ if (/^\d+$/.test(q)) {
2220
+ orConditions.push({ id: { $eq: Number(q) } });
2221
+ }
2222
+ condition = orConditions.length === 1 ? orConditions[0] : { $or: orConditions };
2223
+ }
2224
+ } else if (normOp === "empty") {
2225
+ condition = isStringLike ? { $or: [{ $null: true }, { $eq: "" }] } : { $null: true };
2226
+ } else if (normOp === "notempty") {
2227
+ condition = isStringLike ? { $and: [{ $notNull: true }, { $ne: "" }] } : { $notNull: true };
2228
+ } else if (q !== "") {
2229
+ let typedVal = q;
2230
+ const isNumeric = ["integer", "biginteger", "float", "decimal", "number"].includes(targetAttrSchema?.type);
2231
+ const isBoolean = targetAttrSchema?.type === "boolean";
2232
+ if (isNumeric && /^-?\d+(\.\d+)?$/.test(q)) {
2233
+ typedVal = Number(q);
2234
+ } else if (isBoolean) {
2235
+ if (q.toLowerCase() === "true") typedVal = true;
2236
+ else if (q.toLowerCase() === "false") typedVal = false;
2237
+ }
2238
+ switch (normOp) {
2239
+ case "equals":
2240
+ condition = isStringLike ? { $eqi: q } : { $eq: typedVal };
2241
+ break;
2242
+ case "notequals":
2243
+ condition = isStringLike ? { $nei: q } : { $ne: typedVal };
2244
+ break;
2245
+ case "contains":
2246
+ condition = { $containsi: q };
2247
+ break;
2248
+ case "notcontains":
2249
+ condition = { $notContainsi: q };
2250
+ break;
2251
+ case "startswith":
2252
+ condition = { $startsWithi: q };
2253
+ break;
2254
+ case "endswith":
2255
+ condition = { $endsWithi: q };
2256
+ break;
2257
+ }
2258
+ }
2259
+ if (condition !== void 0) {
2260
+ if (isNestedAttr) {
2261
+ if (isRootDz) ;
2262
+ else {
2263
+ const deepFilter = buildDeepFilter(parts, condition);
2264
+ Object.assign(filters, deepFilter);
2265
+ }
2266
+ } else {
2267
+ if (normOp === "empty" && isStringLike) {
2268
+ filters.$or = [
2269
+ { [resolvedFilterAttr]: { $null: true } },
2270
+ { [resolvedFilterAttr]: { $eq: "" } }
2271
+ ];
2272
+ } else if (normOp === "notempty" && isStringLike) {
2273
+ filters[resolvedFilterAttr] = { $notNull: true, $ne: "" };
2274
+ } else {
2275
+ filters[resolvedFilterAttr] = condition;
2276
+ }
2277
+ }
2278
+ }
2279
+ }
2280
+ if (options.search && options.search.trim() !== "") {
2281
+ const searchQ = options.search.trim();
2282
+ const searchableAttrs = Object.keys(attrs).filter(
2283
+ (k) => ["string", "text", "email", "uid"].includes(attrs[k]?.type)
2284
+ );
2285
+ if (searchableAttrs.length > 0) {
2286
+ const orList = searchableAttrs.slice(0, 6).map((k) => ({
2287
+ [k]: { $containsi: searchQ }
2288
+ }));
2289
+ if (Object.keys(filters).length > 0) {
2290
+ const existingFilters = { ...filters };
2291
+ Object.keys(filters).forEach((k) => delete filters[k]);
2292
+ filters.$and = [existingFilters, { $or: orList }];
2293
+ } else {
2294
+ filters.$or = orList;
2295
+ }
2296
+ }
2297
+ }
2298
+ return {
2299
+ filters,
2300
+ colHasAttribute: true,
2301
+ isRootDz,
2302
+ targetFilterAttr,
2303
+ normOp,
2304
+ filterQuery: q
2305
+ };
2306
+ }
2138
2307
  function getSafeTimezone(timeZone) {
2139
2308
  if (!timeZone || typeof timeZone !== "string") {
2140
2309
  return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
@@ -2380,7 +2549,7 @@ async function executeBatchInternal(strapi, {
2380
2549
  const loaderKey = `${uid}@@@${documentId}`;
2381
2550
  if (!documentLoader.has(loaderKey)) {
2382
2551
  const ct = strapi.contentTypes[uid];
2383
- const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
2552
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
2384
2553
  documentLoader.set(
2385
2554
  loaderKey,
2386
2555
  strapi.documents(uid).findOne({
@@ -2410,7 +2579,7 @@ async function executeBatchInternal(strapi, {
2410
2579
  const hasAttribute = Boolean(attrDef) || isComponentNested;
2411
2580
  if (hasAttribute) {
2412
2581
  if (isComponentNested) {
2413
- const populateOption = buildDeepPopulate$1(contentType.attributes, strapi.components);
2582
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
2414
2583
  const findOneArgs = { documentId: target.documentId };
2415
2584
  if (populateOption) {
2416
2585
  findOneArgs.populate = populateOption;
@@ -3254,7 +3423,7 @@ const bulkUpdaterService = ({ strapi }) => {
3254
3423
  let entries = [];
3255
3424
  let totalCount = 0;
3256
3425
  try {
3257
- const populateOption = buildDeepPopulate$1(allContentTypes[uid]?.attributes || {}, strapi.components);
3426
+ const populateOption = buildDeepPopulate(allContentTypes[uid]?.attributes || {}, strapi.components);
3258
3427
  if (meta.isSingleType) {
3259
3428
  const singleArgs = {};
3260
3429
  if (populateOption) {
@@ -3352,7 +3521,6 @@ const bulkUpdaterService = ({ strapi }) => {
3352
3521
  const currentPage = Math.max(Number(page) || 1, 1);
3353
3522
  const start = (currentPage - 1) * limit;
3354
3523
  const isSingleType = contentType.kind === "singleType";
3355
- const targetFilterAttr = searchAttribute || attribute;
3356
3524
  const signature = await getCollectionSignature(strapi, uid);
3357
3525
  const cacheKey = `${uid}:${limit}:${start}:${attribute || ""}:${searchAttribute || ""}:${filterOperator || ""}:${filterQuery || ""}:${search || ""}:${sortField || ""}:${sortOrder}`;
3358
3526
  const cached = queryCache.get(cacheKey);
@@ -3365,168 +3533,36 @@ const bulkUpdaterService = ({ strapi }) => {
3365
3533
  };
3366
3534
  }
3367
3535
  let result;
3368
- const filters = {};
3369
- const attrs = contentType.attributes || {};
3370
- let colHasAttribute = false;
3371
- let isNestedAttr = false;
3372
- let isRootDz = false;
3373
- let parts = [];
3374
- let resolvedFilterAttr = targetFilterAttr;
3375
- if (targetFilterAttr) {
3376
- const resolvedField = resolveContentTypeField(contentType, targetFilterAttr);
3377
- if (resolvedField) {
3378
- resolvedFilterAttr = resolvedField;
3379
- colHasAttribute = true;
3380
- } else {
3381
- const parsed = parseDynamicZonePath(targetFilterAttr);
3382
- if (parsed.rootKey && contentType.attributes?.[parsed.rootKey]?.type === "dynamiczone") {
3383
- isRootDz = true;
3384
- colHasAttribute = true;
3385
- isNestedAttr = true;
3386
- parts = parsed.cleanPath.split(".");
3387
- } else if (targetFilterAttr.includes(".") || targetFilterAttr.includes("[")) {
3388
- isNestedAttr = isDeepComponentField(contentType, strapi.components, targetFilterAttr);
3389
- if (isNestedAttr) {
3390
- colHasAttribute = true;
3391
- parts = parsed.cleanPath.split(".");
3392
- }
3393
- }
3394
- }
3395
- }
3396
- const normOp = (filterOperator || "").toLowerCase().replace(/_/g, "");
3397
- if (normOp && normOp !== "none") {
3398
- if (!colHasAttribute) {
3399
- result = {
3400
- uid,
3401
- status: "success",
3402
- displayName: contentType.info?.displayName || uid,
3403
- isSingleType,
3404
- draftAndPublish: Boolean(contentType.options?.draftAndPublish),
3405
- entries: [],
3406
- pagination: {
3407
- page: 1,
3408
- pageSize: limit,
3409
- total: 0,
3410
- pageCount: 0
3411
- }
3412
- };
3413
- queryCache.set(cacheKey, { signature, data: result, timestamp: Date.now() });
3414
- return { ...result, cached: false, etag };
3415
- }
3416
- let condition = void 0;
3417
- const q = (filterQuery || "").trim();
3418
- const targetAttrSchema = isNestedAttr ? getLeafAttributeSchema(contentType, strapi.components, targetFilterAttr) : attrs[resolvedFilterAttr];
3419
- const isRelation = targetAttrSchema?.type === "relation";
3420
- const isStringLike = ["string", "text", "email", "richtext", "uid"].includes(targetAttrSchema?.type);
3421
- if (isRelation) {
3422
- const targetUid = targetAttrSchema?.target;
3423
- const targetContentType = targetUid ? strapi.contentTypes[targetUid] : void 0;
3424
- const targetAttrs = targetContentType?.attributes || {};
3425
- const targetStringAttrs = Object.keys(targetAttrs).filter(
3426
- (k) => ["string", "text", "email", "uid"].includes(targetAttrs[k]?.type)
3427
- );
3428
- if (normOp === "empty") {
3429
- condition = { documentId: { $null: true } };
3430
- } else if (normOp === "notempty") {
3431
- condition = { documentId: { $notNull: true } };
3432
- } else if (q !== "") {
3433
- const orConditions = [];
3434
- targetStringAttrs.slice(0, 5).forEach((k) => {
3435
- if (normOp === "equals") {
3436
- orConditions.push({ [k]: { $eqi: q } });
3437
- } else if (normOp === "startswith") {
3438
- orConditions.push({ [k]: { $startsWithi: q } });
3439
- } else if (normOp === "endswith") {
3440
- orConditions.push({ [k]: { $endsWithi: q } });
3441
- } else if (normOp === "notequals") {
3442
- orConditions.push({ [k]: { $nei: q } });
3443
- } else if (normOp === "notcontains") {
3444
- orConditions.push({ [k]: { $notContainsi: q } });
3445
- } else {
3446
- orConditions.push({ [k]: { $containsi: q } });
3447
- }
3448
- });
3449
- orConditions.push({ documentId: { $eq: q } });
3450
- if (/^\d+$/.test(q)) {
3451
- orConditions.push({ id: { $eq: Number(q) } });
3452
- }
3453
- condition = orConditions.length === 1 ? orConditions[0] : { $or: orConditions };
3454
- }
3455
- } else if (normOp === "empty") {
3456
- condition = isStringLike ? { $or: [{ $null: true }, { $eq: "" }] } : { $null: true };
3457
- } else if (normOp === "notempty") {
3458
- condition = isStringLike ? { $and: [{ $notNull: true }, { $ne: "" }] } : { $notNull: true };
3459
- } else if (q !== "") {
3460
- let typedVal = q;
3461
- const isNumeric = ["integer", "biginteger", "float", "decimal", "number"].includes(targetAttrSchema?.type);
3462
- const isBoolean = targetAttrSchema?.type === "boolean";
3463
- if (isNumeric && /^-?\d+(\.\d+)?$/.test(q)) {
3464
- typedVal = Number(q);
3465
- } else if (isBoolean) {
3466
- if (q.toLowerCase() === "true") typedVal = true;
3467
- else if (q.toLowerCase() === "false") typedVal = false;
3468
- }
3469
- switch (normOp) {
3470
- case "equals":
3471
- condition = isStringLike ? { $eqi: q } : { $eq: typedVal };
3472
- break;
3473
- case "notequals":
3474
- condition = isStringLike ? { $nei: q } : { $ne: typedVal };
3475
- break;
3476
- case "contains":
3477
- condition = { $containsi: q };
3478
- break;
3479
- case "notcontains":
3480
- condition = { $notContainsi: q };
3481
- break;
3482
- case "startswith":
3483
- condition = { $startsWithi: q };
3484
- break;
3485
- case "endswith":
3486
- condition = { $endsWithi: q };
3487
- break;
3488
- }
3489
- }
3490
- if (condition !== void 0) {
3491
- if (isNestedAttr) {
3492
- if (isRootDz) ;
3493
- else {
3494
- const deepFilter = buildDeepFilter(parts, condition);
3495
- Object.assign(filters, deepFilter);
3496
- }
3497
- } else {
3498
- if (normOp === "empty" && isStringLike) {
3499
- filters.$or = [
3500
- { [resolvedFilterAttr]: { $null: true } },
3501
- { [resolvedFilterAttr]: { $eq: "" } }
3502
- ];
3503
- } else if (normOp === "notempty" && isStringLike) {
3504
- filters[resolvedFilterAttr] = { $notNull: true, $ne: "" };
3505
- } else {
3506
- filters[resolvedFilterAttr] = condition;
3507
- }
3508
- }
3509
- }
3510
- }
3511
- if (search && search.trim() !== "") {
3512
- const q = search.trim();
3513
- const searchableAttrs = Object.keys(attrs).filter(
3514
- (k) => ["string", "text", "email", "uid"].includes(attrs[k]?.type)
3515
- );
3516
- if (searchableAttrs.length > 0) {
3517
- const orList = searchableAttrs.slice(0, 6).map((k) => ({
3518
- [k]: { $containsi: q }
3519
- }));
3520
- if (Object.keys(filters).length > 0) {
3521
- const existingFilters = { ...filters };
3522
- Object.keys(filters).forEach((k) => delete filters[k]);
3523
- filters.$and = [existingFilters, { $or: orList }];
3524
- } else {
3525
- filters.$or = orList;
3536
+ const filterMeta = buildCollectionQueryFilters(strapi, contentType, {
3537
+ attribute,
3538
+ searchAttribute,
3539
+ filterOperator,
3540
+ filterQuery,
3541
+ search
3542
+ });
3543
+ if (!filterMeta.colHasAttribute && filterMeta.normOp && filterMeta.normOp !== "none") {
3544
+ result = {
3545
+ uid,
3546
+ status: "success",
3547
+ displayName: contentType.info?.displayName || uid,
3548
+ isSingleType,
3549
+ draftAndPublish: Boolean(contentType.options?.draftAndPublish),
3550
+ entries: [],
3551
+ pagination: {
3552
+ page: 1,
3553
+ pageSize: limit,
3554
+ total: 0,
3555
+ pageCount: 0
3526
3556
  }
3527
- }
3528
- }
3529
- const populateOption = buildDeepPopulate$1(contentType.attributes, strapi.components);
3557
+ };
3558
+ queryCache.set(cacheKey, { signature, data: result, timestamp: Date.now() });
3559
+ return { ...result, cached: false, etag };
3560
+ }
3561
+ const filters = filterMeta.filters;
3562
+ const isRootDz = filterMeta.isRootDz;
3563
+ const normOp = filterMeta.normOp;
3564
+ const targetFilterAttr = filterMeta.targetFilterAttr;
3565
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
3530
3566
  if (isSingleType) {
3531
3567
  let singleDoc = null;
3532
3568
  try {
@@ -3804,7 +3840,7 @@ const bulkUpdaterService = ({ strapi }) => {
3804
3840
  let currentEntry;
3805
3841
  if (isComponentNested) {
3806
3842
  const findOneArgs = { documentId: target.documentId };
3807
- const populateOption = buildDeepPopulate$1(contentType.attributes, strapi.components);
3843
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
3808
3844
  if (populateOption) {
3809
3845
  findOneArgs.populate = populateOption;
3810
3846
  }
@@ -5016,6 +5052,39 @@ const DEFAULT_CANDIDATE_TYPES = [
5016
5052
  "api::audit.audit",
5017
5053
  "api::bulk-audit-log.bulk-audit-log"
5018
5054
  ];
5055
+ function sortAuditRecordsDesc(records) {
5056
+ return [...records].sort((a, b) => {
5057
+ const timeA = a.executedAt || a.createdAt ? new Date(a.executedAt || a.createdAt).getTime() : 0;
5058
+ const validTimeA = Number.isNaN(timeA) ? 0 : timeA;
5059
+ const timeB = b.executedAt || b.createdAt ? new Date(b.executedAt || b.createdAt).getTime() : 0;
5060
+ const validTimeB = Number.isNaN(timeB) ? 0 : timeB;
5061
+ if (validTimeB !== validTimeA) {
5062
+ return validTimeB - validTimeA;
5063
+ }
5064
+ if (typeof a.id === "number" && typeof b.id === "number") {
5065
+ return b.id - a.id;
5066
+ }
5067
+ const idA = String(a.id ?? a.batchId ?? "");
5068
+ const idB = String(b.id ?? b.batchId ?? "");
5069
+ return idB.localeCompare(idA);
5070
+ });
5071
+ }
5072
+ let rollbackLock = Promise.resolve();
5073
+ function withRollbackLock(fn) {
5074
+ const previousLock = rollbackLock;
5075
+ let release = () => {
5076
+ };
5077
+ rollbackLock = new Promise((resolve) => {
5078
+ release = resolve;
5079
+ });
5080
+ return previousLock.then(async () => {
5081
+ try {
5082
+ return await fn();
5083
+ } finally {
5084
+ release();
5085
+ }
5086
+ });
5087
+ }
5019
5088
  const auditService = ({ strapi }) => ({
5020
5089
  /**
5021
5090
  * Detects whether Strapi Enterprise Native Audit Log service is available.
@@ -5122,7 +5191,7 @@ const auditService = ({ strapi }) => ({
5122
5191
  /**
5123
5192
  * Optionally writes an audit event directly to Strapi Enterprise's native Audit Logs table.
5124
5193
  */
5125
- async recordToEnterpriseNative(action, payload2, user) {
5194
+ async recordToEnterpriseNative(action, payload, user) {
5126
5195
  try {
5127
5196
  const eeService = this.getEnterpriseAuditService();
5128
5197
  if (eeService && typeof eeService.save === "function") {
@@ -5130,7 +5199,7 @@ const auditService = ({ strapi }) => ({
5130
5199
  action,
5131
5200
  date: /* @__PURE__ */ new Date(),
5132
5201
  userId: user?.id,
5133
- payload: payload2
5202
+ payload
5134
5203
  });
5135
5204
  strapi.log.info(
5136
5205
  `[bulk-updater] Successfully dispatched event to Strapi Enterprise Audit Log: ${action}`
@@ -5244,7 +5313,15 @@ const auditService = ({ strapi }) => ({
5244
5313
  try {
5245
5314
  const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
5246
5315
  const stored = await store.get({}) || { history: [] };
5247
- const history = Array.isArray(stored.history) ? stored.history : [];
5316
+ const rawHistory = Array.isArray(stored.history) ? stored.history : [];
5317
+ const sortedHistory = sortAuditRecordsDesc(rawHistory);
5318
+ const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
5319
+ const history = sortedHistory.map((rec) => ({
5320
+ ...rec,
5321
+ isLatestEligible: Boolean(
5322
+ latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
5323
+ )
5324
+ }));
5248
5325
  return {
5249
5326
  enabled: true,
5250
5327
  mode: "store",
@@ -5286,14 +5363,23 @@ const auditService = ({ strapi }) => ({
5286
5363
  isRolledBack: Boolean(r[f.isRolledBack]),
5287
5364
  rolledBackAt: r[f.rolledBackAt] || null,
5288
5365
  rolledBackBy: r[f.rolledBackBy] || null,
5289
- executedAt: r[f.executedAt] || r.createdAt
5366
+ executedAt: r[f.executedAt] || r.createdAt,
5367
+ createdAt: r.createdAt
5368
+ }));
5369
+ const sortedHistory = sortAuditRecordsDesc(normalized);
5370
+ const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
5371
+ const history = sortedHistory.map((rec) => ({
5372
+ ...rec,
5373
+ isLatestEligible: Boolean(
5374
+ latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
5375
+ )
5290
5376
  }));
5291
5377
  return {
5292
5378
  enabled: true,
5293
5379
  mode: config.mode,
5294
5380
  contentType: config.contentType,
5295
5381
  isEnterpriseNativeAvailable: config.isEnterpriseNativeAvailable,
5296
- history: normalized
5382
+ history
5297
5383
  };
5298
5384
  } catch (err) {
5299
5385
  return {
@@ -5332,7 +5418,7 @@ const auditService = ({ strapi }) => ({
5332
5418
  const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
5333
5419
  let wasPublished = false;
5334
5420
  if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
5335
- const populateOption = buildDeepPopulate$1(ct.attributes, strapi.components);
5421
+ const populateOption = buildDeepPopulate(ct.attributes, strapi.components);
5336
5422
  const findOneArgs = { documentId: item.documentId };
5337
5423
  if (populateOption) {
5338
5424
  findOneArgs.populate = populateOption;
@@ -5435,34 +5521,151 @@ const auditService = ({ strapi }) => ({
5435
5521
  return { revertedCount, rollbackDetails };
5436
5522
  },
5437
5523
  /**
5438
- * Performs deterministic rollback of a batch
5524
+ * Performs deterministic rollback of a batch.
5525
+ * Strict invariant: ONLY the latest completed update is eligible for rollback.
5526
+ * Older completed updates, already rolled-back updates, and pending/failed/executing batches are strictly rejected.
5439
5527
  */
5440
5528
  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) {
5529
+ return withRollbackLock(async () => {
5530
+ const config = this.getAuditConfig();
5531
+ if (!config.enabled) {
5532
+ throw new Error("Audit trail is not configured or disabled.");
5533
+ }
5534
+ if (!batchId) {
5535
+ throw new Error("A valid batchId is required to perform rollback.");
5536
+ }
5537
+ try {
5538
+ const bulkService = strapi.plugin("bulk-updater")?.service("bulkUpdater");
5539
+ if (bulkService && typeof bulkService.getBatchStatus === "function") {
5540
+ const statusRes = await bulkService.getBatchStatus(batchId);
5541
+ const batchJob = statusRes?.batch;
5542
+ if (batchJob) {
5543
+ if (batchJob.status === "pending_approval" || batchJob.status === "queued_offpeak") {
5544
+ throw new Error(`Batch "${batchId}" is currently pending and cannot be rolled back.`);
5545
+ }
5546
+ if (batchJob.status === "processing" || batchJob.status === "running" || batchJob.status === "executing") {
5547
+ throw new Error(`Batch "${batchId}" is currently executing and cannot be rolled back.`);
5548
+ }
5549
+ if (batchJob.status === "failed") {
5550
+ throw new Error(`Batch "${batchId}" failed during execution and cannot be rolled back.`);
5551
+ }
5552
+ }
5553
+ }
5554
+ } catch (checkErr) {
5555
+ if (checkErr.message?.startsWith('Batch "')) {
5556
+ throw checkErr;
5557
+ }
5558
+ }
5559
+ if (config.mode === "store") {
5560
+ const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
5561
+ const stored = await store.get({}) || { history: [] };
5562
+ const rawHistory = Array.isArray(stored.history) ? stored.history : [];
5563
+ if (rawHistory.length === 0) {
5564
+ throw new Error("No completed update records found in audit trail.");
5565
+ }
5566
+ const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
5567
+ const targetRecord2 = sortedHistory2.find((r) => r.batchId === batchId);
5568
+ if (!targetRecord2) {
5569
+ throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5570
+ }
5571
+ const latestRecord2 = sortedHistory2[0];
5572
+ if (latestRecord2.batchId !== batchId) {
5573
+ throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
5574
+ }
5575
+ if (targetRecord2.isRolledBack) {
5576
+ throw new Error(`Batch "${batchId}" has already been rolled back.`);
5577
+ }
5578
+ const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
5579
+ const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
5580
+ const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
5581
+ if (recordIndex !== -1) {
5582
+ rawHistory[recordIndex] = {
5583
+ ...rawHistory[recordIndex],
5584
+ isRolledBack: true,
5585
+ rolledBackAt: (/* @__PURE__ */ new Date()).toISOString(),
5586
+ rolledBackBy: currentUser?.email || "Admin"
5587
+ };
5588
+ await store.set({ value: { history: rawHistory } });
5589
+ }
5590
+ try {
5591
+ const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
5592
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5593
+ affectedUids.forEach((uid) => {
5594
+ if (uid && bulkService?.invalidateCache) {
5595
+ bulkService.invalidateCache(uid);
5596
+ }
5597
+ });
5598
+ } catch {
5599
+ }
5600
+ await this.recordToEnterpriseNative(
5601
+ "bulk-updater.rollback",
5602
+ {
5603
+ batchId,
5604
+ revertedCount: revertedCount2
5605
+ },
5606
+ currentUser
5607
+ );
5608
+ return {
5609
+ success: true,
5610
+ batchId,
5611
+ revertedCount: revertedCount2,
5612
+ details: rollbackDetails2
5613
+ };
5614
+ }
5615
+ if (!config.contentType || !config.fields) {
5616
+ throw new Error("Audit trail is not configured or disabled.");
5617
+ }
5618
+ const f = config.fields;
5619
+ const allRecords = await strapi.documents(config.contentType).findMany({
5620
+ sort: { createdAt: "desc" }
5621
+ });
5622
+ if (!allRecords || allRecords.length === 0) {
5623
+ throw new Error("No completed update records found in audit trail.");
5624
+ }
5625
+ const normalizedHistory = allRecords.map((r) => ({
5626
+ id: r.id,
5627
+ documentId: r.documentId,
5628
+ batchId: r[f.batchId] || r.documentId,
5629
+ attribute: r[f.attribute],
5630
+ value: r[f.value],
5631
+ userEmail: r[f.userEmail] || "admin@strapi.io",
5632
+ userName: r[f.userName] || "Admin",
5633
+ updatedCount: r[f.updatedCount] || 0,
5634
+ skippedCount: r[f.skippedCount] || 0,
5635
+ totalTargets: r[f.totalTargets] || 0,
5636
+ diffs: typeof r[f.diffs] === "string" ? JSON.parse(r[f.diffs]) : r[f.diffs] || [],
5637
+ isRolledBack: Boolean(r[f.isRolledBack]),
5638
+ rolledBackAt: r[f.rolledBackAt] || null,
5639
+ rolledBackBy: r[f.rolledBackBy] || null,
5640
+ executedAt: r[f.executedAt] || r.createdAt,
5641
+ createdAt: r.createdAt
5642
+ }));
5643
+ const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
5644
+ const targetRecord = sortedHistory.find((r) => r.batchId === batchId);
5645
+ if (!targetRecord) {
5451
5646
  throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5452
5647
  }
5453
- const record2 = history[recordIndex];
5454
- if (record2.isRolledBack) {
5648
+ const latestRecord = sortedHistory[0];
5649
+ if (latestRecord.batchId !== batchId) {
5650
+ throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
5651
+ }
5652
+ if (targetRecord.isRolledBack) {
5455
5653
  throw new Error(`Batch "${batchId}" has already been rolled back.`);
5456
5654
  }
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 } });
5655
+ const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
5656
+ const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
5657
+ const updateData = {};
5658
+ if (f.isRolledBack) updateData[f.isRolledBack] = true;
5659
+ if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
5660
+ if (f.rolledBackBy) {
5661
+ updateData[f.rolledBackBy] = currentUser?.email || "Admin";
5662
+ }
5663
+ await strapi.documents(config.contentType).update({
5664
+ documentId: targetRecord.documentId,
5665
+ data: updateData
5666
+ });
5464
5667
  try {
5465
- const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
5668
+ const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
5466
5669
  const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5467
5670
  affectedUids.forEach((uid) => {
5468
5671
  if (uid && bulkService?.invalidateCache) {
@@ -5475,72 +5678,278 @@ const auditService = ({ strapi }) => ({
5475
5678
  "bulk-updater.rollback",
5476
5679
  {
5477
5680
  batchId,
5478
- revertedCount: revertedCount2
5681
+ revertedCount
5479
5682
  },
5480
5683
  currentUser
5481
5684
  );
5482
5685
  return {
5483
5686
  success: true,
5484
5687
  batchId,
5485
- revertedCount: revertedCount2,
5486
- details: rollbackDetails2
5688
+ revertedCount,
5689
+ details: rollbackDetails
5487
5690
  };
5691
+ });
5692
+ }
5693
+ });
5694
+ const SYSTEM_ATTRIBUTES = /* @__PURE__ */ new Set([
5695
+ "createdat",
5696
+ "updatedat",
5697
+ "publishedat",
5698
+ "createdby",
5699
+ "updatedby",
5700
+ "localizations",
5701
+ "locale",
5702
+ "documentid",
5703
+ "id",
5704
+ "strapistage",
5705
+ "strapi_stage",
5706
+ "strapiassignee",
5707
+ "strapi_assignee",
5708
+ "strapistatus",
5709
+ "strapi_status"
5710
+ ]);
5711
+ function classifyAttribute(attrName, attrDef) {
5712
+ const normKey = attrName.toLowerCase().replace(/[\s_-]/g, "");
5713
+ if (SYSTEM_ATTRIBUTES.has(normKey)) {
5714
+ return "system";
5715
+ }
5716
+ if (!attrDef || typeof attrDef !== "object") {
5717
+ return "scalar";
5718
+ }
5719
+ const type = String(attrDef.type || "").toLowerCase();
5720
+ if (type === "component") {
5721
+ return attrDef.repeatable ? "component_repeatable" : "component_single";
5722
+ }
5723
+ if (type === "dynamiczone") {
5724
+ return "dynamiczone";
5725
+ }
5726
+ if (type === "relation") {
5727
+ const rel = String(attrDef.relation || "").toLowerCase();
5728
+ const isMany = rel.endsWith("many") || rel === "onetomany" || rel === "manytomany" || rel === "morphone" || rel === "morphmany";
5729
+ return isMany ? "relation_to_many" : "relation_to_one";
5730
+ }
5731
+ if (type === "media") {
5732
+ return attrDef.multiple ? "media_to_many" : "media_single";
5733
+ }
5734
+ if (type === "blocks") {
5735
+ return "blocks";
5736
+ }
5737
+ if (type === "json") {
5738
+ return "json";
5739
+ }
5740
+ return "scalar";
5741
+ }
5742
+ function discoverComponentFields(strapi, compUid, visited = /* @__PURE__ */ new Set(), depth = 0, maxDepth = 6) {
5743
+ const result = {};
5744
+ if (depth >= maxDepth) return result;
5745
+ const comp = strapi.components?.[compUid];
5746
+ if (!comp?.attributes) return result;
5747
+ const nextVisited = new Set(visited);
5748
+ nextVisited.add(compUid);
5749
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
5750
+ const normKey = attrName.toLowerCase().replace(/[\s_-]/g, "");
5751
+ if (SYSTEM_ATTRIBUTES.has(normKey)) continue;
5752
+ const category = classifyAttribute(attrName, attrDef);
5753
+ if (category === "system") continue;
5754
+ const field = {
5755
+ key: attrName,
5756
+ label: attrName,
5757
+ category,
5758
+ rawType: attrDef.type,
5759
+ repeatable: Boolean(attrDef.repeatable),
5760
+ componentUid: attrDef.component,
5761
+ dzComponents: Array.isArray(attrDef.components) ? attrDef.components : void 0,
5762
+ targetUid: attrDef.target,
5763
+ relationType: attrDef.relation,
5764
+ multiple: Boolean(attrDef.multiple),
5765
+ enumOptions: Array.isArray(attrDef.enum) ? attrDef.enum : void 0,
5766
+ required: Boolean(attrDef.required)
5767
+ };
5768
+ if (category === "component_single" && attrDef.component) {
5769
+ if (!visited.has(attrDef.component)) {
5770
+ field.subFields = discoverComponentFields(
5771
+ strapi,
5772
+ attrDef.component,
5773
+ nextVisited,
5774
+ depth + 1,
5775
+ maxDepth
5776
+ );
5777
+ }
5778
+ } else if (category === "component_repeatable" && attrDef.component) {
5779
+ if (!visited.has(attrDef.component)) {
5780
+ field.subFields = discoverComponentFields(
5781
+ strapi,
5782
+ attrDef.component,
5783
+ nextVisited,
5784
+ depth + 1,
5785
+ maxDepth
5786
+ );
5787
+ }
5488
5788
  }
5489
- if (!config.contentType || !config.fields) {
5490
- throw new Error("Audit trail is not configured or disabled.");
5789
+ result[attrName] = field;
5790
+ }
5791
+ return result;
5792
+ }
5793
+ function discoverSchema(strapi, uid) {
5794
+ const ct = strapi.contentTypes[uid];
5795
+ if (!ct) {
5796
+ throw new Error(`Content type "${uid}" not found in registered Strapi schema.`);
5797
+ }
5798
+ const fields = {};
5799
+ const allExportKeys = ["documentId"];
5800
+ const isLocalized = Boolean(ct.pluginOptions?.i18n?.localized);
5801
+ if (isLocalized) {
5802
+ allExportKeys.push("locale");
5803
+ }
5804
+ const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
5805
+ for (const [attrName, attrDef] of Object.entries(ct.attributes || {})) {
5806
+ const normKey = attrName.toLowerCase().replace(/[\s_-]/g, "");
5807
+ if (SYSTEM_ATTRIBUTES.has(normKey)) continue;
5808
+ if (attrDef?.target?.includes("review-workflow") || attrDef?.target === "admin::review-workflow-stage") {
5809
+ continue;
5491
5810
  }
5492
- const f = config.fields;
5493
- const records = await strapi.documents(config.contentType).findMany({
5494
- filters: {
5495
- [f.batchId]: { $eq: batchId }
5811
+ const category = classifyAttribute(attrName, attrDef);
5812
+ if (category === "system") continue;
5813
+ const field = {
5814
+ key: attrName,
5815
+ label: attrName,
5816
+ category,
5817
+ rawType: attrDef.type,
5818
+ repeatable: Boolean(attrDef.repeatable),
5819
+ componentUid: attrDef.component,
5820
+ dzComponents: Array.isArray(attrDef.components) ? attrDef.components : void 0,
5821
+ targetUid: attrDef.target,
5822
+ relationType: attrDef.relation,
5823
+ multiple: Boolean(attrDef.multiple),
5824
+ enumOptions: Array.isArray(attrDef.enum) ? attrDef.enum : void 0,
5825
+ required: Boolean(attrDef.required)
5826
+ };
5827
+ if ((category === "component_single" || category === "component_repeatable") && attrDef.component) {
5828
+ field.subFields = discoverComponentFields(strapi, attrDef.component, /* @__PURE__ */ new Set(), 0, 6);
5829
+ }
5830
+ fields[attrName] = field;
5831
+ allExportKeys.push(attrName);
5832
+ }
5833
+ return {
5834
+ uid,
5835
+ displayName: ct.info?.displayName || uid,
5836
+ singularName: ct.info?.singularName || uid,
5837
+ kind: ct.kind === "singleType" ? "singleType" : "collectionType",
5838
+ isDraftAndPublish,
5839
+ isLocalized,
5840
+ fields,
5841
+ allExportKeys
5842
+ };
5843
+ }
5844
+ function buildComponentPopulate(strapi, compUid, visited, depth, maxDepth) {
5845
+ if (depth >= maxDepth) return true;
5846
+ if (visited.has(compUid)) return true;
5847
+ const comp = strapi.components?.[compUid];
5848
+ if (!comp?.attributes) return true;
5849
+ const nextVisited = new Set(visited);
5850
+ nextVisited.add(compUid);
5851
+ const populate = {};
5852
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
5853
+ const category = classifyAttribute(attrName, attrDef);
5854
+ if (category === "component_single" || category === "component_repeatable") {
5855
+ if (attrDef.component) {
5856
+ const subPop = buildComponentPopulate(
5857
+ strapi,
5858
+ attrDef.component,
5859
+ nextVisited,
5860
+ depth + 1,
5861
+ maxDepth
5862
+ );
5863
+ populate[attrName] = typeof subPop === "object" && Object.keys(subPop).length > 0 ? { populate: subPop } : true;
5864
+ } else {
5865
+ populate[attrName] = true;
5866
+ }
5867
+ } else if (category === "dynamiczone") {
5868
+ const dzComponents = Array.isArray(attrDef.components) ? attrDef.components : [];
5869
+ if (dzComponents.length > 0) {
5870
+ const onPopulate = {};
5871
+ for (const dzCompUid of dzComponents) {
5872
+ const dzCompPop = buildComponentPopulate(
5873
+ strapi,
5874
+ dzCompUid,
5875
+ nextVisited,
5876
+ depth + 1,
5877
+ maxDepth
5878
+ );
5879
+ onPopulate[dzCompUid] = typeof dzCompPop === "object" && Object.keys(dzCompPop).length > 0 ? { populate: dzCompPop } : true;
5880
+ }
5881
+ populate[attrName] = { on: onPopulate };
5882
+ } else {
5883
+ populate[attrName] = { populate: "*" };
5496
5884
  }
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);
5885
+ } else if (category === "relation_to_one" || category === "relation_to_many") {
5886
+ populate[attrName] = true;
5887
+ } else if (category === "media_single" || category === "media_to_many") {
5888
+ populate[attrName] = true;
5889
+ }
5890
+ }
5891
+ return Object.keys(populate).length > 0 ? populate : true;
5892
+ }
5893
+ function buildLosslessPopulate(strapi, uid, options = {}) {
5894
+ const maxDepth = options.maxDepth || 5;
5895
+ const schema = discoverSchema(strapi, uid);
5896
+ const populate = {};
5897
+ const visited = /* @__PURE__ */ new Set([uid]);
5898
+ for (const [fieldName, field] of Object.entries(schema.fields)) {
5899
+ switch (field.category) {
5900
+ case "component_single":
5901
+ case "component_repeatable": {
5902
+ if (field.componentUid) {
5903
+ const compPop = buildComponentPopulate(
5904
+ strapi,
5905
+ field.componentUid,
5906
+ visited,
5907
+ 0,
5908
+ maxDepth
5909
+ );
5910
+ populate[fieldName] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
5911
+ } else {
5912
+ populate[fieldName] = true;
5523
5913
  }
5524
- });
5525
- } catch {
5914
+ break;
5915
+ }
5916
+ case "dynamiczone": {
5917
+ const dzComponents = field.dzComponents || [];
5918
+ if (dzComponents.length > 0) {
5919
+ const onPopulate = {};
5920
+ for (const compUid of dzComponents) {
5921
+ const compPop = buildComponentPopulate(
5922
+ strapi,
5923
+ compUid,
5924
+ visited,
5925
+ 0,
5926
+ maxDepth
5927
+ );
5928
+ onPopulate[compUid] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
5929
+ }
5930
+ populate[fieldName] = { on: onPopulate };
5931
+ } else {
5932
+ populate[fieldName] = { populate: "*" };
5933
+ }
5934
+ break;
5935
+ }
5936
+ case "relation_to_one":
5937
+ case "relation_to_many": {
5938
+ populate[fieldName] = true;
5939
+ break;
5940
+ }
5941
+ case "media_single":
5942
+ case "media_to_many": {
5943
+ populate[fieldName] = true;
5944
+ break;
5945
+ }
5526
5946
  }
5527
- await this.recordToEnterpriseNative(
5528
- "bulk-updater.rollback",
5529
- {
5530
- batchId,
5531
- revertedCount
5532
- },
5533
- currentUser
5534
- );
5535
- return {
5536
- success: true,
5537
- batchId,
5538
- revertedCount,
5539
- details: rollbackDetails
5540
- };
5541
5947
  }
5542
- });
5543
- function escapeCsvValue(val) {
5948
+ return Object.keys(populate).length > 0 ? populate : void 0;
5949
+ }
5950
+ const METADATA_COLUMN_KEY = "__bulk_updater_metadata";
5951
+ const CURRENT_SCHEMA_VERSION = 1;
5952
+ function escapeCsvCell(val) {
5544
5953
  if (val === null || val === void 0) return "";
5545
5954
  let str = "";
5546
5955
  if (val instanceof Date) {
@@ -5551,15 +5960,15 @@ function escapeCsvValue(val) {
5551
5960
  str = String(val);
5552
5961
  }
5553
5962
  str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
5554
- if (/^[=+@-]$/.test(str.charAt(0))) {
5963
+ if (/^[=+@-]/.test(str)) {
5555
5964
  str = `'${str}`;
5556
5965
  }
5557
- if (str.includes(",") || str.includes('"') || str.includes("\n")) {
5966
+ if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
5558
5967
  return `"${str.replace(/"/g, '""')}"`;
5559
5968
  }
5560
5969
  return str;
5561
5970
  }
5562
- function parseCsvRows(csvText) {
5971
+ function parseCsvToMatrix(csvText) {
5563
5972
  if (!csvText) return [];
5564
5973
  let text = csvText;
5565
5974
  if (text.charCodeAt(0) === 65279) {
@@ -5627,13 +6036,13 @@ function parseCsvRows(csvText) {
5627
6036
  }
5628
6037
  return rows;
5629
6038
  }
5630
- function parseCsv(csvText) {
5631
- const rows = parseCsvRows(csvText);
5632
- if (rows.length < 2) return [];
5633
- const headers = rows[0].map((h) => h.trim());
6039
+ function parseCsvToRecords(csvText) {
6040
+ const matrix = parseCsvToMatrix(csvText);
6041
+ if (matrix.length < 2) return [];
6042
+ const headers = matrix[0].map((h) => h.trim());
5634
6043
  const records = [];
5635
- for (let i = 1; i < rows.length; i++) {
5636
- const row = rows[i];
6044
+ for (let i = 1; i < matrix.length; i++) {
6045
+ const row = matrix[i];
5637
6046
  const record = {};
5638
6047
  headers.forEach((h, idx) => {
5639
6048
  let val = row[idx] !== void 0 ? row[idx] : "";
@@ -5646,306 +6055,1042 @@ function parseCsv(csvText) {
5646
6055
  }
5647
6056
  return records;
5648
6057
  }
5649
- const LIFECYCLE_STATUS_WORDS = /* @__PURE__ */ new Set([
5650
- "pending review",
5651
- "pending_review",
5652
- "pending approval",
5653
- "pending_approval",
5654
- "approved",
5655
- "rejected",
5656
- "draft",
5657
- "published",
5658
- "modified",
5659
- "supported",
5660
- "ignored",
5661
- "editing",
5662
- "in review",
5663
- "in_review",
5664
- "ready to publish",
5665
- "ready_to_publish",
5666
- "null",
5667
- "undefined"
5668
- ]);
5669
- function isValidDocId(val) {
5670
- if (!val || typeof val !== "string") return false;
5671
- const trimmed = val.trim();
5672
- if (!trimmed) return false;
5673
- if (LIFECYCLE_STATUS_WORDS.has(trimmed.toLowerCase())) return false;
5674
- if (/\s/.test(trimmed)) return false;
5675
- return /^[a-zA-Z0-9_-]+$/.test(trimmed);
5676
- }
5677
- function extractDocId(row) {
5678
- if (!row || typeof row !== "object") return "";
5679
- const candidates = [
5680
- row.documentId,
5681
- row.document_id,
5682
- row["Document ID"],
5683
- row["Document Id"],
5684
- row["document_id"],
5685
- row.docId,
5686
- row["docId"],
5687
- row.id,
5688
- row.ID,
5689
- row.Id
5690
- ];
5691
- for (const c of candidates) {
5692
- if (c !== void 0 && c !== null) {
5693
- const str = String(c).trim();
5694
- if (isValidDocId(str)) {
5695
- return str;
6058
+ function serializeFieldValue(value, field) {
6059
+ if (value === null || value === void 0) {
6060
+ return "";
6061
+ }
6062
+ switch (field.category) {
6063
+ case "scalar": {
6064
+ if (value instanceof Date) {
6065
+ return value.toISOString();
5696
6066
  }
6067
+ return String(value);
5697
6068
  }
5698
- }
5699
- return "";
5700
- }
5701
- function extractLocale(row) {
5702
- if (!row || typeof row !== "object") return void 0;
5703
- const candidates = [
5704
- row.locale,
5705
- row.Locale,
5706
- row["locale"],
5707
- row["Locale"],
5708
- row.strapi_locale,
5709
- row["strapi_locale"]
5710
- ];
5711
- for (const c of candidates) {
5712
- if (c !== void 0 && c !== null) {
5713
- const str = String(c).trim();
5714
- if (str && str.toLowerCase() !== "null" && str.toLowerCase() !== "undefined" && str.toLowerCase() !== "[null]" && str.toLowerCase() !== '""') {
5715
- return str;
6069
+ case "blocks":
6070
+ case "json": {
6071
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
6072
+ }
6073
+ case "component_single": {
6074
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
6075
+ }
6076
+ case "component_repeatable": {
6077
+ if (Array.isArray(value)) {
6078
+ return JSON.stringify(value);
5716
6079
  }
6080
+ return typeof value === "object" ? JSON.stringify([value]) : "";
5717
6081
  }
5718
- }
5719
- return void 0;
5720
- }
5721
- function getEffectiveLocale(ct, rowLocale) {
5722
- if (!ct?.pluginOptions?.i18n?.localized) {
5723
- return void 0;
5724
- }
5725
- if (!rowLocale) {
5726
- return void 0;
5727
- }
5728
- const trimmed = rowLocale.trim();
5729
- if (!trimmed || trimmed.toLowerCase() === "null" || trimmed.toLowerCase() === "undefined" || trimmed.toLowerCase() === "[null]" || trimmed.toLowerCase() === '""') {
5730
- return void 0;
5731
- }
5732
- return trimmed;
5733
- }
5734
- function isRowInEditingStage(row) {
5735
- if (!row || typeof row !== "object") return false;
5736
- const candidates = [
5737
- row.strapi_stage,
5738
- row["strapi_stage"],
5739
- row.strapiStage,
5740
- row["Strapi Stage"],
5741
- row["strapi-stage"],
5742
- row.stage,
5743
- row.Stage,
5744
- row.status,
5745
- row.Status
5746
- ];
5747
- for (const c of candidates) {
5748
- if (c !== void 0 && c !== null) {
5749
- let stageName = "";
5750
- if (typeof c === "object") {
5751
- stageName = String(c.name || c.title || c.status || c.documentId || c.id || "").trim();
5752
- } else if (typeof c === "string") {
5753
- const trimmed = c.trim();
5754
- if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
5755
- try {
5756
- const parsed = JSON.parse(trimmed);
5757
- if (typeof parsed === "object" && parsed !== null) {
5758
- stageName = String(parsed.name || parsed.title || parsed.status || parsed.documentId || parsed.id || "").trim();
5759
- }
5760
- } catch {
6082
+ case "dynamiczone": {
6083
+ if (Array.isArray(value)) {
6084
+ const cleaned = value.map((block) => {
6085
+ if (block && typeof block === "object") {
6086
+ return { ...block };
5761
6087
  }
5762
- }
5763
- if (!stageName) {
5764
- stageName = trimmed;
5765
- }
5766
- } else {
5767
- stageName = String(c).trim();
6088
+ return block;
6089
+ });
6090
+ return JSON.stringify(cleaned);
5768
6091
  }
5769
- if (stageName) {
5770
- const s = stageName.toLowerCase();
5771
- if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
5772
- return true;
5773
- }
6092
+ return "";
6093
+ }
6094
+ case "relation_to_one": {
6095
+ if (typeof value === "object" && value !== null) {
6096
+ const docId = value.documentId || value.id || "";
6097
+ return JSON.stringify({
6098
+ documentId: String(docId),
6099
+ title: value.title || value.name || value.slug || void 0
6100
+ });
5774
6101
  }
6102
+ return String(value);
5775
6103
  }
5776
- }
5777
- return false;
5778
- }
5779
- function extractDetailedErrorMessage(err) {
5780
- if (!err) return "Error processing row";
5781
- const detailsErrors = err.details?.errors || err.error?.details?.errors;
5782
- if (Array.isArray(detailsErrors) && detailsErrors.length > 0) {
5783
- const messages = detailsErrors.map((e) => {
5784
- if (!e) return "";
5785
- const path = Array.isArray(e.path) ? e.path.join(".") : e.path;
5786
- const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
5787
- return path ? `${path}: ${msg}` : msg;
5788
- }).filter(Boolean);
5789
- if (messages.length > 0) return messages.join("; ");
5790
- }
5791
- if (Array.isArray(err.inner) && err.inner.length > 0) {
5792
- const messages = err.inner.map((e) => {
5793
- if (!e) return "";
5794
- const path = e.path;
5795
- const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
5796
- return path ? `${path}: ${msg}` : msg;
5797
- }).filter(Boolean);
5798
- if (messages.length > 0) return messages.join("; ");
5799
- }
5800
- if (Array.isArray(err.errors) && err.errors.length > 0) {
5801
- return err.errors.join("; ");
5802
- }
5803
- if (typeof err.details === "string" && err.details.trim()) {
5804
- return err.details;
5805
- }
5806
- if (err.details?.message) {
5807
- return err.details.message;
5808
- }
5809
- if (err.message && err.message !== "[object Object]") {
5810
- return err.message;
5811
- }
5812
- return "Error processing row";
5813
- }
5814
- function discoverExportFields(ct, allComponents, maxDepth = 4) {
5815
- const fields = [{ key: "documentId", label: "documentId", type: "string" }];
5816
- const excluded = ["createdBy", "updatedBy", "localizations"];
5817
- function walkComponent(compUid, pathPrefix, labelPrefix, depth) {
5818
- if (depth >= maxDepth) return;
5819
- const comp = allComponents[compUid];
5820
- if (!comp?.attributes) return;
5821
- for (const [subKey, subDef] of Object.entries(comp.attributes)) {
5822
- if (excluded.includes(subKey)) continue;
5823
- const keyPath = `${pathPrefix}.${subKey}`;
5824
- const displayLabel = `${labelPrefix} > ${subKey}`;
5825
- if (subDef.type === "component" && subDef.component) {
5826
- if (!subDef.repeatable) {
5827
- walkComponent(subDef.component, keyPath, displayLabel, depth + 1);
5828
- } else {
5829
- fields.push({ key: keyPath, label: displayLabel, type: "component" });
5830
- }
5831
- } else {
5832
- fields.push({ key: keyPath, label: displayLabel, type: subDef.type });
6104
+ case "relation_to_many": {
6105
+ if (Array.isArray(value)) {
6106
+ const list = value.map((item) => {
6107
+ if (typeof item === "object" && item !== null) {
6108
+ const docId = item.documentId || item.id || "";
6109
+ return {
6110
+ documentId: String(docId),
6111
+ title: item.title || item.name || item.slug || void 0
6112
+ };
6113
+ }
6114
+ return { documentId: String(item) };
6115
+ });
6116
+ return JSON.stringify(list);
6117
+ }
6118
+ return "";
6119
+ }
6120
+ case "media_single": {
6121
+ if (typeof value === "object" && value !== null) {
6122
+ return JSON.stringify({
6123
+ id: value.id,
6124
+ documentId: value.documentId,
6125
+ name: value.name,
6126
+ url: value.url,
6127
+ mime: value.mime
6128
+ });
5833
6129
  }
6130
+ return String(value);
5834
6131
  }
5835
- }
5836
- for (const [attrName, attrDef] of Object.entries(ct.attributes || {})) {
5837
- if (excluded.includes(attrName)) continue;
5838
- if (attrDef.type === "component" && attrDef.component) {
5839
- if (!attrDef.repeatable) {
5840
- walkComponent(attrDef.component, attrName, attrName, 0);
5841
- } else {
5842
- fields.push({ key: attrName, label: attrName, type: "component" });
6132
+ case "media_to_many": {
6133
+ if (Array.isArray(value)) {
6134
+ const list = value.map((file) => {
6135
+ if (typeof file === "object" && file !== null) {
6136
+ return {
6137
+ id: file.id,
6138
+ documentId: file.documentId,
6139
+ name: file.name,
6140
+ url: file.url,
6141
+ mime: file.mime
6142
+ };
6143
+ }
6144
+ return file;
6145
+ });
6146
+ return JSON.stringify(list);
5843
6147
  }
5844
- } else {
5845
- fields.push({ key: attrName, label: attrName, type: attrDef.type });
6148
+ return "";
5846
6149
  }
6150
+ default:
6151
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
5847
6152
  }
5848
- return fields;
5849
6153
  }
5850
- function buildDeepPopulate(attributes, allComponents, depth = 0) {
5851
- if (depth > 5) return void 0;
5852
- const populate = {};
5853
- for (const [key, def] of Object.entries(attributes || {})) {
5854
- if (def.type === "component" && def.component) {
5855
- const comp = allComponents[def.component];
5856
- if (comp?.attributes) {
5857
- const subPopulate = buildDeepPopulate(comp.attributes, allComponents, depth + 1);
5858
- if (subPopulate && Object.keys(subPopulate).length > 0) {
5859
- populate[key] = {
5860
- populate: subPopulate
5861
- };
6154
+ function serializeDocumentsToCsv(strapi, uid, documents) {
6155
+ const schema = discoverSchema(strapi, uid);
6156
+ const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
6157
+ const lines = [];
6158
+ lines.push(headers.map(escapeCsvCell).join(","));
6159
+ const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
6160
+ for (const doc of documents) {
6161
+ const rowValues = [];
6162
+ const metadata = {
6163
+ schemaVersion: CURRENT_SCHEMA_VERSION,
6164
+ contentType: uid,
6165
+ documentId: String(doc.documentId || doc.id || ""),
6166
+ locale: doc.locale || void 0,
6167
+ exportedAt
6168
+ };
6169
+ rowValues.push(escapeCsvCell(metadata));
6170
+ for (const key of schema.allExportKeys) {
6171
+ if (key === "documentId") {
6172
+ rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
6173
+ } else if (key === "locale") {
6174
+ rowValues.push(escapeCsvCell(doc.locale || ""));
6175
+ } else {
6176
+ const field = schema.fields[key];
6177
+ const rawValue = doc[key];
6178
+ if (field) {
6179
+ const serialized = serializeFieldValue(rawValue, field);
6180
+ rowValues.push(escapeCsvCell(serialized));
5862
6181
  } else {
5863
- populate[key] = true;
6182
+ rowValues.push(escapeCsvCell(rawValue));
5864
6183
  }
5865
- } else {
5866
- populate[key] = true;
5867
6184
  }
5868
- } else if (def.type === "dynamiczone") {
5869
- populate[key] = true;
5870
- } else if (def.type === "relation" || def.type === "media") {
5871
- populate[key] = true;
5872
6185
  }
6186
+ lines.push(rowValues.join(","));
5873
6187
  }
5874
- return Object.keys(populate).length > 0 ? populate : void 0;
6188
+ const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
6189
+ return {
6190
+ csvContent,
6191
+ headers,
6192
+ count: documents.length
6193
+ };
5875
6194
  }
5876
- function getNestedExportValue(entry, path) {
5877
- if (!entry || !path) return "";
5878
- const parts = path.split(".");
5879
- let current = entry;
5880
- for (let i = 0; i < parts.length; i++) {
5881
- const part = parts[i];
5882
- if (current === null || current === void 0) return "";
5883
- if (Array.isArray(current)) {
5884
- const subPath = parts.slice(i).join(".");
5885
- return current.map((item) => {
5886
- if (!item) return "";
5887
- if (typeof item === "object") {
5888
- const val = getNestedExportValue(item, subPath);
5889
- return typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
5890
- }
5891
- return String(item);
5892
- }).filter(Boolean).join("; ");
5893
- }
5894
- if (current && typeof current === "object") {
5895
- if (current[part] !== void 0) {
5896
- current = current[part];
5897
- } else {
5898
- const camel = part.replace(/_([a-z0-9])/g, (_, l) => l.toUpperCase());
5899
- const snake = part.replace(/([A-Z])/g, "_$1").toLowerCase();
5900
- if (current[camel] !== void 0) {
5901
- current = current[camel];
5902
- } else if (current[snake] !== void 0) {
5903
- current = current[snake];
5904
- } else {
5905
- current = void 0;
5906
- }
6195
+ function extractMetadataFromRow(row) {
6196
+ if (!row || typeof row !== "object") return null;
6197
+ const rawMeta = row[METADATA_COLUMN_KEY] || row["__bulk_updater_metadata"];
6198
+ if (!rawMeta) return null;
6199
+ if (typeof rawMeta === "object") {
6200
+ return rawMeta;
6201
+ }
6202
+ if (typeof rawMeta === "string") {
6203
+ try {
6204
+ const parsed = JSON.parse(rawMeta);
6205
+ if (parsed && typeof parsed === "object") {
6206
+ return parsed;
5907
6207
  }
5908
- } else {
5909
- current = void 0;
6208
+ } catch {
5910
6209
  }
5911
6210
  }
5912
- if (current === null || current === void 0) return "";
5913
- if (Array.isArray(current) && current.length > 0 && current[0]?.type && Array.isArray(current[0]?.children)) {
5914
- return JSON.stringify(current);
5915
- }
5916
- if (typeof current === "object" && current.url) {
5917
- return current.url;
6211
+ return null;
6212
+ }
6213
+ function isValidDocumentId(val) {
6214
+ if (!val || typeof val !== "string") return false;
6215
+ const trimmed = val.trim();
6216
+ if (!trimmed) return false;
6217
+ if (/\s/.test(trimmed)) return false;
6218
+ return /^[a-zA-Z0-9_-]+$/.test(trimmed);
6219
+ }
6220
+ function parseNumeric(rawVal, isInteger) {
6221
+ if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
6222
+ const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
6223
+ if (isInteger) {
6224
+ const n = parseInt(cleanStr, 10);
6225
+ return isNaN(n) ? null : n;
5918
6226
  }
5919
- if (typeof current === "object" && !Array.isArray(current)) {
5920
- if (current.name && (current.locale === null || !current.documentId)) {
5921
- return current.name;
5922
- }
5923
- if (current.documentId || current.id || current.name || current.title) {
5924
- return current.documentId || current.id || current.name || current.title;
5925
- }
6227
+ const f = parseFloat(cleanStr);
6228
+ return isNaN(f) ? null : f;
6229
+ }
6230
+ function parseBoolean(rawVal) {
6231
+ if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
6232
+ const s = String(rawVal).trim().toLowerCase();
6233
+ if (s === "true" || s === "1" || s === "yes" || s === "y" || s === "on") return true;
6234
+ if (s === "false" || s === "0" || s === "no" || s === "n" || s === "off") return false;
6235
+ return null;
6236
+ }
6237
+ async function resolveMediaIds(strapi, rawVal, isMultiple) {
6238
+ if (rawVal === null || rawVal === void 0 || rawVal === "") {
6239
+ return isMultiple ? [] : null;
5926
6240
  }
5927
- if (Array.isArray(current)) {
5928
- return current.map((item) => {
5929
- if (!item) return "";
5930
- if (typeof item === "object") {
5931
- if (item.url) return item.url;
5932
- return item.documentId || item.id || item.name || item.title || JSON.stringify(item);
6241
+ let parsed = rawVal;
6242
+ if (typeof rawVal === "string") {
6243
+ const trimmed = rawVal.trim();
6244
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
6245
+ try {
6246
+ parsed = JSON.parse(trimmed);
6247
+ } catch {
5933
6248
  }
5934
- return String(item);
5935
- }).filter(Boolean).join("; ");
5936
- }
5937
- return current;
5938
- }
5939
- const csvImportSessions = /* @__PURE__ */ new Map();
5940
- function cleanupStaleSessions() {
5941
- const oneHourAgo = Date.now() - 36e5;
5942
- for (const [id, session] of csvImportSessions.entries()) {
5943
- if (session.createdAt < oneHourAgo) {
5944
- csvImportSessions.delete(id);
5945
6249
  }
5946
6250
  }
5947
- }
5948
- const SYSTEM_FIELD_KEYS = /* @__PURE__ */ new Set([
6251
+ const numericIds = [];
6252
+ const candidateLookups = [];
6253
+ const inspectItem = (item) => {
6254
+ if (item === null || item === void 0) return;
6255
+ if (typeof item === "number" && !isNaN(item)) {
6256
+ numericIds.push(item);
6257
+ return;
6258
+ }
6259
+ if (typeof item === "object") {
6260
+ if (typeof item.id === "number") {
6261
+ numericIds.push(item.id);
6262
+ return;
6263
+ }
6264
+ if (typeof item.id === "string" && /^\d+$/.test(item.id)) {
6265
+ numericIds.push(parseInt(item.id, 10));
6266
+ return;
6267
+ }
6268
+ if (item.documentId) {
6269
+ candidateLookups.push(String(item.documentId));
6270
+ return;
6271
+ }
6272
+ if (item.url) {
6273
+ candidateLookups.push(String(item.url));
6274
+ return;
6275
+ }
6276
+ }
6277
+ const str = String(item).trim();
6278
+ if (/^\d+$/.test(str)) {
6279
+ numericIds.push(parseInt(str, 10));
6280
+ } else if (str) {
6281
+ candidateLookups.push(str);
6282
+ }
6283
+ };
6284
+ if (Array.isArray(parsed)) {
6285
+ for (const el of parsed) {
6286
+ inspectItem(el);
6287
+ }
6288
+ } else if (typeof parsed === "object" && parsed !== null) {
6289
+ inspectItem(parsed);
6290
+ } else if (typeof rawVal === "string" && (rawVal.includes(",") || rawVal.includes(";"))) {
6291
+ const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean);
6292
+ for (const part of parts) {
6293
+ inspectItem(part);
6294
+ }
6295
+ } else {
6296
+ inspectItem(parsed);
6297
+ }
6298
+ if (candidateLookups.length > 0) {
6299
+ try {
6300
+ const fileQuery = strapi.db?.query("plugin::upload.file");
6301
+ if (fileQuery) {
6302
+ for (const candidate of candidateLookups) {
6303
+ const found = await fileQuery.findOne({
6304
+ where: {
6305
+ $or: [
6306
+ { documentId: candidate },
6307
+ { url: candidate },
6308
+ { hash: candidate },
6309
+ { name: candidate }
6310
+ ]
6311
+ },
6312
+ select: ["id"]
6313
+ });
6314
+ if (found?.id) {
6315
+ numericIds.push(found.id);
6316
+ }
6317
+ }
6318
+ }
6319
+ } catch {
6320
+ }
6321
+ }
6322
+ const uniqueNumericIds = Array.from(new Set(numericIds));
6323
+ if (isMultiple) {
6324
+ return uniqueNumericIds;
6325
+ }
6326
+ return uniqueNumericIds.length > 0 ? uniqueNumericIds[0] : null;
6327
+ }
6328
+ function resolveRelationPayload(rawVal, isToMany) {
6329
+ if (rawVal === null || rawVal === void 0 || rawVal === "") {
6330
+ return isToMany ? { set: [] } : { set: [] };
6331
+ }
6332
+ let parsed = rawVal;
6333
+ if (typeof rawVal === "string") {
6334
+ const trimmed = rawVal.trim();
6335
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
6336
+ try {
6337
+ parsed = JSON.parse(trimmed);
6338
+ } catch {
6339
+ }
6340
+ }
6341
+ }
6342
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6343
+ if (parsed.set || parsed.connect || parsed.disconnect) {
6344
+ return parsed;
6345
+ }
6346
+ const singleDocId = parsed.documentId || parsed.id;
6347
+ if (singleDocId && isValidDocumentId(String(singleDocId))) {
6348
+ return isToMany ? { set: [String(singleDocId).trim()] } : { set: [String(singleDocId).trim()] };
6349
+ }
6350
+ }
6351
+ const docIds = [];
6352
+ if (Array.isArray(parsed)) {
6353
+ for (const item of parsed) {
6354
+ if (item && typeof item === "object") {
6355
+ const id = item.documentId || item.id;
6356
+ if (id && isValidDocumentId(String(id))) {
6357
+ docIds.push(String(id).trim());
6358
+ }
6359
+ } else if (isValidDocumentId(String(item))) {
6360
+ docIds.push(String(item).trim());
6361
+ }
6362
+ }
6363
+ } else if (typeof rawVal === "string") {
6364
+ if (rawVal.includes(",") || rawVal.includes(";")) {
6365
+ const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocumentId(p));
6366
+ docIds.push(...parts);
6367
+ } else if (isValidDocumentId(rawVal.trim())) {
6368
+ docIds.push(rawVal.trim());
6369
+ }
6370
+ }
6371
+ const uniqueDocIds = Array.from(new Set(docIds));
6372
+ return { set: uniqueDocIds };
6373
+ }
6374
+ async function resolveComponentPayload(strapi, compUid, rawVal, existingVal = {}) {
6375
+ const comp = strapi.components?.[compUid];
6376
+ if (!comp?.attributes) {
6377
+ return typeof rawVal === "object" ? rawVal : {};
6378
+ }
6379
+ let sourceObj = {};
6380
+ if (typeof rawVal === "string") {
6381
+ try {
6382
+ sourceObj = JSON.parse(rawVal);
6383
+ } catch {
6384
+ return existingVal || {};
6385
+ }
6386
+ } else if (typeof rawVal === "object" && rawVal !== null) {
6387
+ sourceObj = rawVal;
6388
+ } else {
6389
+ return existingVal || {};
6390
+ }
6391
+ const result = { ...existingVal || {} };
6392
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
6393
+ if (SYSTEM_ATTRIBUTES.has(attrName.toLowerCase().replace(/[\s_-]/g, ""))) continue;
6394
+ if (!(attrName in sourceObj)) {
6395
+ continue;
6396
+ }
6397
+ const fieldVal = sourceObj[attrName];
6398
+ const type = String(attrDef.type || "").toLowerCase();
6399
+ if (type === "component") {
6400
+ if (attrDef.repeatable) {
6401
+ const list = Array.isArray(fieldVal) ? fieldVal : [];
6402
+ const cleanedList = [];
6403
+ for (const item of list) {
6404
+ const subCleaned = await resolveComponentPayload(strapi, attrDef.component, item, {});
6405
+ cleanedList.push(subCleaned);
6406
+ }
6407
+ result[attrName] = cleanedList;
6408
+ } else {
6409
+ result[attrName] = await resolveComponentPayload(
6410
+ strapi,
6411
+ attrDef.component,
6412
+ fieldVal,
6413
+ existingVal?.[attrName] || {}
6414
+ );
6415
+ }
6416
+ } else if (type === "relation") {
6417
+ const isToMany = String(attrDef.relation || "").toLowerCase().endsWith("many");
6418
+ result[attrName] = resolveRelationPayload(fieldVal, isToMany);
6419
+ } else if (type === "media") {
6420
+ result[attrName] = await resolveMediaIds(strapi, fieldVal, Boolean(attrDef.multiple));
6421
+ } else if (type === "integer" || type === "biginteger") {
6422
+ result[attrName] = parseNumeric(fieldVal, true);
6423
+ } else if (type === "float" || type === "decimal") {
6424
+ result[attrName] = parseNumeric(fieldVal, false);
6425
+ } else if (type === "boolean") {
6426
+ result[attrName] = parseBoolean(fieldVal);
6427
+ } else if (type === "json" || type === "blocks") {
6428
+ if (typeof fieldVal === "string") {
6429
+ try {
6430
+ result[attrName] = JSON.parse(fieldVal);
6431
+ } catch {
6432
+ result[attrName] = fieldVal;
6433
+ }
6434
+ } else {
6435
+ result[attrName] = fieldVal;
6436
+ }
6437
+ } else {
6438
+ result[attrName] = fieldVal === null || fieldVal === void 0 ? null : String(fieldVal);
6439
+ }
6440
+ }
6441
+ return result;
6442
+ }
6443
+ async function resolveDynamicZonePayload(strapi, allowedComponents, rawVal, existingVal = []) {
6444
+ let list = [];
6445
+ if (typeof rawVal === "string") {
6446
+ try {
6447
+ list = JSON.parse(rawVal);
6448
+ } catch {
6449
+ return existingVal || [];
6450
+ }
6451
+ } else if (Array.isArray(rawVal)) {
6452
+ list = rawVal;
6453
+ } else {
6454
+ return existingVal || [];
6455
+ }
6456
+ if (!Array.isArray(list)) return [];
6457
+ const allowedSet = new Set(allowedComponents || []);
6458
+ const resolvedBlocks = [];
6459
+ for (const block of list) {
6460
+ if (!block || typeof block !== "object") continue;
6461
+ const compUid = block.__component;
6462
+ if (!compUid || typeof compUid !== "string") {
6463
+ continue;
6464
+ }
6465
+ if (allowedSet.size > 0 && !allowedSet.has(compUid)) {
6466
+ continue;
6467
+ }
6468
+ const resolvedAttrs = await resolveComponentPayload(strapi, compUid, block, {});
6469
+ resolvedAttrs.__component = compUid;
6470
+ resolvedBlocks.push(resolvedAttrs);
6471
+ }
6472
+ return resolvedBlocks;
6473
+ }
6474
+ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
6475
+ const schema = discoverSchema(strapi, uid);
6476
+ const payload = {};
6477
+ const unescapedRow = {};
6478
+ for (const [k, v] of Object.entries(rawRow)) {
6479
+ let cleanVal = v;
6480
+ if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
6481
+ cleanVal = cleanVal.substring(1);
6482
+ }
6483
+ unescapedRow[k] = cleanVal;
6484
+ }
6485
+ const dotNotationMap = {};
6486
+ for (const [k, v] of Object.entries(unescapedRow)) {
6487
+ if (k.includes(".")) {
6488
+ const [parent, ...rest] = k.split(".");
6489
+ const child = rest.join(".");
6490
+ if (!dotNotationMap[parent]) dotNotationMap[parent] = {};
6491
+ dotNotationMap[parent][child] = v;
6492
+ }
6493
+ }
6494
+ for (const [attrName, field] of Object.entries(schema.fields)) {
6495
+ const hasDirectKey = attrName in unescapedRow;
6496
+ const hasDotKeys = Boolean(dotNotationMap[attrName]);
6497
+ if (!hasDirectKey && !hasDotKeys) {
6498
+ continue;
6499
+ }
6500
+ const rawVal = hasDirectKey ? unescapedRow[attrName] : void 0;
6501
+ switch (field.category) {
6502
+ case "scalar": {
6503
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
6504
+ payload[attrName] = null;
6505
+ } else if (field.rawType === "integer" || field.rawType === "biginteger") {
6506
+ payload[attrName] = parseNumeric(rawVal, true);
6507
+ } else if (field.rawType === "float" || field.rawType === "decimal") {
6508
+ payload[attrName] = parseNumeric(rawVal, false);
6509
+ } else if (field.rawType === "boolean") {
6510
+ payload[attrName] = parseBoolean(rawVal);
6511
+ } else if (field.rawType === "date" || field.rawType === "time" || field.rawType === "datetime" || field.rawType === "timestamp") {
6512
+ payload[attrName] = String(rawVal).trim() || null;
6513
+ } else if (field.rawType === "enumeration") {
6514
+ const trimmed = String(rawVal).trim();
6515
+ if (field.enumOptions && field.enumOptions.length > 0) {
6516
+ const match = field.enumOptions.find((o) => o.toLowerCase() === trimmed.toLowerCase());
6517
+ payload[attrName] = match || trimmed;
6518
+ } else {
6519
+ payload[attrName] = trimmed;
6520
+ }
6521
+ } else {
6522
+ payload[attrName] = String(rawVal).trim();
6523
+ }
6524
+ break;
6525
+ }
6526
+ case "blocks": {
6527
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
6528
+ payload[attrName] = [];
6529
+ } else {
6530
+ try {
6531
+ const parsed = JSON.parse(rawVal);
6532
+ payload[attrName] = Array.isArray(parsed) ? parsed : [parsed];
6533
+ } catch {
6534
+ payload[attrName] = [
6535
+ { type: "paragraph", children: [{ type: "text", text: String(rawVal).trim() }] }
6536
+ ];
6537
+ }
6538
+ }
6539
+ break;
6540
+ }
6541
+ case "json": {
6542
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
6543
+ payload[attrName] = null;
6544
+ } else {
6545
+ try {
6546
+ payload[attrName] = JSON.parse(rawVal);
6547
+ } catch {
6548
+ payload[attrName] = rawVal;
6549
+ }
6550
+ }
6551
+ break;
6552
+ }
6553
+ case "component_single": {
6554
+ if (field.componentUid) {
6555
+ let compInput = rawVal;
6556
+ if (hasDotKeys) {
6557
+ compInput = { ...existingDoc?.[attrName] || {}, ...dotNotationMap[attrName] };
6558
+ }
6559
+ if (compInput === "" || compInput === null) {
6560
+ payload[attrName] = null;
6561
+ } else {
6562
+ payload[attrName] = await resolveComponentPayload(
6563
+ strapi,
6564
+ field.componentUid,
6565
+ compInput,
6566
+ existingDoc?.[attrName] || {}
6567
+ );
6568
+ }
6569
+ }
6570
+ break;
6571
+ }
6572
+ case "component_repeatable": {
6573
+ if (field.componentUid) {
6574
+ if (rawVal === "" || rawVal === null || rawVal === void 0) {
6575
+ payload[attrName] = [];
6576
+ } else {
6577
+ let list = [];
6578
+ try {
6579
+ list = typeof rawVal === "string" ? JSON.parse(rawVal) : rawVal;
6580
+ } catch {
6581
+ }
6582
+ if (Array.isArray(list)) {
6583
+ const cleanedItems = [];
6584
+ for (const item of list) {
6585
+ const cleaned = await resolveComponentPayload(
6586
+ strapi,
6587
+ field.componentUid,
6588
+ item,
6589
+ {}
6590
+ );
6591
+ cleanedItems.push(cleaned);
6592
+ }
6593
+ payload[attrName] = cleanedItems;
6594
+ } else {
6595
+ payload[attrName] = [];
6596
+ }
6597
+ }
6598
+ }
6599
+ break;
6600
+ }
6601
+ case "dynamiczone": {
6602
+ const allowedComponents = field.dzComponents || [];
6603
+ if (rawVal === "" || rawVal === null || rawVal === void 0) {
6604
+ payload[attrName] = [];
6605
+ } else {
6606
+ payload[attrName] = await resolveDynamicZonePayload(
6607
+ strapi,
6608
+ allowedComponents,
6609
+ rawVal,
6610
+ existingDoc?.[attrName] || []
6611
+ );
6612
+ }
6613
+ break;
6614
+ }
6615
+ case "relation_to_one": {
6616
+ payload[attrName] = resolveRelationPayload(rawVal, false);
6617
+ break;
6618
+ }
6619
+ case "relation_to_many": {
6620
+ payload[attrName] = resolveRelationPayload(rawVal, true);
6621
+ break;
6622
+ }
6623
+ case "media_single": {
6624
+ payload[attrName] = await resolveMediaIds(strapi, rawVal, false);
6625
+ break;
6626
+ }
6627
+ case "media_to_many": {
6628
+ payload[attrName] = await resolveMediaIds(strapi, rawVal, true);
6629
+ break;
6630
+ }
6631
+ default:
6632
+ payload[attrName] = rawVal;
6633
+ }
6634
+ }
6635
+ return payload;
6636
+ }
6637
+ function normalizeVal(val) {
6638
+ if (val === null || val === void 0) return null;
6639
+ if (typeof val === "string") return val.trim();
6640
+ if (typeof val === "number" || typeof val === "boolean") return val;
6641
+ if (Array.isArray(val)) {
6642
+ return val.map(normalizeVal);
6643
+ }
6644
+ if (typeof val === "object") {
6645
+ const copy = {};
6646
+ for (const [k, v] of Object.entries(val)) {
6647
+ if (SYSTEM_ATTRIBUTES.has(k.toLowerCase().replace(/[\s_-]/g, ""))) continue;
6648
+ copy[k] = normalizeVal(v);
6649
+ }
6650
+ return copy;
6651
+ }
6652
+ return val;
6653
+ }
6654
+ function verifyDocumentIntegrity(strapi, uid, originalDoc, appliedPayload, savedDoc) {
6655
+ const schema = discoverSchema(strapi, uid);
6656
+ const diffs = [];
6657
+ let scalarOk = true;
6658
+ let componentsOk = true;
6659
+ let dynamicZonesOk = true;
6660
+ let relationsOk = true;
6661
+ let mediaOk = true;
6662
+ let missingDataCount = 0;
6663
+ let invalidRelationsCount = 0;
6664
+ let missingMediaCount = 0;
6665
+ let structuralDifferencesCount = 0;
6666
+ let hasComponents = false;
6667
+ let hasDynamicZones = false;
6668
+ let hasRelations = false;
6669
+ let hasMedia = false;
6670
+ for (const [key, field] of Object.entries(schema.fields)) {
6671
+ const isTargeted = key in appliedPayload;
6672
+ const expected = isTargeted ? appliedPayload[key] : originalDoc?.[key];
6673
+ const actual = savedDoc?.[key];
6674
+ switch (field.category) {
6675
+ case "scalar": {
6676
+ const normExpected = normalizeVal(expected);
6677
+ const normActual = normalizeVal(actual);
6678
+ if (normExpected !== null && normActual !== normExpected) {
6679
+ if (String(normExpected) !== String(normActual)) {
6680
+ diffs.push({
6681
+ path: key,
6682
+ expected: normExpected,
6683
+ actual: normActual,
6684
+ message: `Scalar value mismatch on "${key}"`
6685
+ });
6686
+ scalarOk = false;
6687
+ structuralDifferencesCount++;
6688
+ }
6689
+ }
6690
+ break;
6691
+ }
6692
+ case "component_single":
6693
+ case "component_repeatable": {
6694
+ hasComponents = true;
6695
+ if (field.category === "component_repeatable") {
6696
+ const expArr = Array.isArray(expected) ? expected : [];
6697
+ const actArr = Array.isArray(actual) ? actual : [];
6698
+ if (expArr.length !== actArr.length) {
6699
+ diffs.push({
6700
+ path: key,
6701
+ expected: `Array of length ${expArr.length}`,
6702
+ actual: `Array of length ${actArr.length}`,
6703
+ message: `Repeatable component length mismatch on "${key}"`
6704
+ });
6705
+ componentsOk = false;
6706
+ structuralDifferencesCount++;
6707
+ }
6708
+ }
6709
+ break;
6710
+ }
6711
+ case "dynamiczone": {
6712
+ hasDynamicZones = true;
6713
+ const expBlocks = Array.isArray(expected) ? expected : [];
6714
+ const actBlocks = Array.isArray(actual) ? actual : [];
6715
+ if (expBlocks.length !== actBlocks.length) {
6716
+ diffs.push({
6717
+ path: key,
6718
+ expected: `Dynamic zone of length ${expBlocks.length}`,
6719
+ actual: `Dynamic zone of length ${actBlocks.length}`,
6720
+ message: `Dynamic zone count mismatch on "${key}"`
6721
+ });
6722
+ dynamicZonesOk = false;
6723
+ structuralDifferencesCount++;
6724
+ } else {
6725
+ for (let b = 0; b < expBlocks.length; b++) {
6726
+ const expComp = expBlocks[b]?.__component;
6727
+ const actComp = actBlocks[b]?.__component;
6728
+ if (expComp !== actComp) {
6729
+ diffs.push({
6730
+ path: `${key}[${b}].__component`,
6731
+ expected: expComp || "(missing __component)",
6732
+ actual: actComp || "(missing __component)",
6733
+ message: `Dynamic zone block type mismatch at position ${b}: expected "${expComp}", found "${actComp || "missing __component"}"`
6734
+ });
6735
+ dynamicZonesOk = false;
6736
+ structuralDifferencesCount++;
6737
+ }
6738
+ }
6739
+ }
6740
+ break;
6741
+ }
6742
+ case "relation_to_one":
6743
+ case "relation_to_many": {
6744
+ hasRelations = true;
6745
+ if (isTargeted && expected && typeof expected === "object" && expected.set) {
6746
+ const expectedIds = expected.set || [];
6747
+ if (field.category === "relation_to_many") {
6748
+ const actualIds = Array.isArray(actual) ? actual.map((item) => String(item?.documentId || item?.id || item)).filter(Boolean) : [];
6749
+ const missing = expectedIds.filter((id) => !actualIds.includes(id));
6750
+ if (missing.length > 0) {
6751
+ diffs.push({
6752
+ path: key,
6753
+ expected: expectedIds,
6754
+ actual: actualIds,
6755
+ message: `Missing relations on "${key}": ${missing.join(", ")}`
6756
+ });
6757
+ relationsOk = false;
6758
+ invalidRelationsCount += missing.length;
6759
+ }
6760
+ }
6761
+ }
6762
+ break;
6763
+ }
6764
+ case "media_single":
6765
+ case "media_to_many": {
6766
+ hasMedia = true;
6767
+ if (isTargeted && expected !== null && expected !== void 0) {
6768
+ const expectedIds = Array.isArray(expected) ? expected : [expected];
6769
+ const actualIds = Array.isArray(actual) ? actual.map((f) => f?.id || f).filter(Boolean) : actual?.id ? [actual.id] : [];
6770
+ const missing = expectedIds.filter((id) => !actualIds.includes(id));
6771
+ if (missing.length > 0) {
6772
+ diffs.push({
6773
+ path: key,
6774
+ expected: expectedIds,
6775
+ actual: actualIds,
6776
+ message: `Missing media references on "${key}"`
6777
+ });
6778
+ mediaOk = false;
6779
+ missingMediaCount += missing.length;
6780
+ }
6781
+ }
6782
+ break;
6783
+ }
6784
+ }
6785
+ }
6786
+ const docId = String(savedDoc?.documentId || originalDoc?.documentId || "unknown");
6787
+ const title = String(savedDoc?.title || savedDoc?.name || `Entry #${docId}`);
6788
+ const status = diffs.length === 0 ? "SUCCESS" : diffs.length <= 2 ? "WARNING" : "FAILED";
6789
+ return {
6790
+ documentId: docId,
6791
+ title,
6792
+ status,
6793
+ scalarFields: scalarOk ? "Verified" : "Mismatch",
6794
+ components: hasComponents ? componentsOk ? "Verified" : "Mismatch" : "N/A",
6795
+ dynamicZones: hasDynamicZones ? dynamicZonesOk ? "Verified" : "Mismatch" : "N/A",
6796
+ relations: hasRelations ? relationsOk ? "Verified" : "Mismatch" : "N/A",
6797
+ media: hasMedia ? mediaOk ? "Verified" : "Mismatch" : "N/A",
6798
+ missingDataCount,
6799
+ invalidRelationsCount,
6800
+ missingMediaCount,
6801
+ structuralDifferencesCount,
6802
+ diffs
6803
+ };
6804
+ }
6805
+ function escapeCsvValue(val) {
6806
+ if (val === null || val === void 0) return "";
6807
+ let str = "";
6808
+ if (val instanceof Date) {
6809
+ str = val.toISOString();
6810
+ } else if (typeof val === "object") {
6811
+ str = JSON.stringify(val);
6812
+ } else {
6813
+ str = String(val);
6814
+ }
6815
+ str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
6816
+ if (/^[=+@-]$/.test(str.charAt(0))) {
6817
+ str = `'${str}`;
6818
+ }
6819
+ if (str.includes(",") || str.includes('"') || str.includes("\n")) {
6820
+ return `"${str.replace(/"/g, '""')}"`;
6821
+ }
6822
+ return str;
6823
+ }
6824
+ function parseCsvRows(csvText) {
6825
+ if (!csvText) return [];
6826
+ let text = csvText;
6827
+ if (text.charCodeAt(0) === 65279) {
6828
+ text = text.slice(1);
6829
+ }
6830
+ const rows = [];
6831
+ let currentRow = [];
6832
+ let currentCell = "";
6833
+ let inQuotes = false;
6834
+ let cellIsQuoted = false;
6835
+ for (let i = 0; i < text.length; i++) {
6836
+ const char = text[i];
6837
+ const nextChar = text[i + 1];
6838
+ if (inQuotes) {
6839
+ if (char === '"') {
6840
+ if (nextChar === '"') {
6841
+ currentCell += '"';
6842
+ i++;
6843
+ } else {
6844
+ inQuotes = false;
6845
+ }
6846
+ } else {
6847
+ currentCell += char;
6848
+ }
6849
+ } else {
6850
+ if (char === '"' && !cellIsQuoted && currentCell.trim() === "") {
6851
+ inQuotes = true;
6852
+ cellIsQuoted = true;
6853
+ currentCell = "";
6854
+ } else if (char === ",") {
6855
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6856
+ currentCell = "";
6857
+ cellIsQuoted = false;
6858
+ } else if (char === "\r") {
6859
+ if (nextChar === "\n") {
6860
+ i++;
6861
+ }
6862
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6863
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
6864
+ rows.push(currentRow);
6865
+ }
6866
+ currentRow = [];
6867
+ currentCell = "";
6868
+ cellIsQuoted = false;
6869
+ } else if (char === "\n") {
6870
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6871
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
6872
+ rows.push(currentRow);
6873
+ }
6874
+ currentRow = [];
6875
+ currentCell = "";
6876
+ cellIsQuoted = false;
6877
+ } else {
6878
+ if (!(cellIsQuoted && !inQuotes && (char === " " || char === " "))) {
6879
+ currentCell += char;
6880
+ }
6881
+ }
6882
+ }
6883
+ }
6884
+ if (currentCell !== "" || cellIsQuoted || currentRow.length > 0) {
6885
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6886
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
6887
+ rows.push(currentRow);
6888
+ }
6889
+ }
6890
+ return rows;
6891
+ }
6892
+ function parseCsv(csvText) {
6893
+ const rows = parseCsvRows(csvText);
6894
+ if (rows.length < 2) return [];
6895
+ const headers = rows[0].map((h) => h.trim());
6896
+ const records = [];
6897
+ for (let i = 1; i < rows.length; i++) {
6898
+ const row = rows[i];
6899
+ const record = {};
6900
+ headers.forEach((h, idx) => {
6901
+ let val = row[idx] !== void 0 ? row[idx] : "";
6902
+ if (typeof val === "string" && /^'[=+@-]/.test(val)) {
6903
+ val = val.substring(1);
6904
+ }
6905
+ record[h] = val;
6906
+ });
6907
+ records.push(record);
6908
+ }
6909
+ return records;
6910
+ }
6911
+ const LIFECYCLE_STATUS_WORDS = /* @__PURE__ */ new Set([
6912
+ "pending review",
6913
+ "pending_review",
6914
+ "pending approval",
6915
+ "pending_approval",
6916
+ "approved",
6917
+ "rejected",
6918
+ "draft",
6919
+ "published",
6920
+ "modified",
6921
+ "supported",
6922
+ "ignored",
6923
+ "editing",
6924
+ "in review",
6925
+ "in_review",
6926
+ "ready to publish",
6927
+ "ready_to_publish",
6928
+ "null",
6929
+ "undefined"
6930
+ ]);
6931
+ function isValidDocId(val) {
6932
+ if (!val || typeof val !== "string") return false;
6933
+ const trimmed = val.trim();
6934
+ if (!trimmed) return false;
6935
+ if (LIFECYCLE_STATUS_WORDS.has(trimmed.toLowerCase())) return false;
6936
+ if (/\s/.test(trimmed)) return false;
6937
+ return /^[a-zA-Z0-9_-]+$/.test(trimmed);
6938
+ }
6939
+ function extractDocId(row) {
6940
+ if (!row || typeof row !== "object") return "";
6941
+ const meta = extractMetadataFromRow(row);
6942
+ if (meta?.documentId && isValidDocId(String(meta.documentId).trim())) {
6943
+ return String(meta.documentId).trim();
6944
+ }
6945
+ const candidates = [
6946
+ row.documentId,
6947
+ row.document_id,
6948
+ row["Document ID"],
6949
+ row["Document Id"],
6950
+ row["document_id"],
6951
+ row.docId,
6952
+ row["docId"],
6953
+ row.id,
6954
+ row.ID,
6955
+ row.Id
6956
+ ];
6957
+ for (const c of candidates) {
6958
+ if (c !== void 0 && c !== null) {
6959
+ const str = String(c).trim();
6960
+ if (isValidDocId(str)) {
6961
+ return str;
6962
+ }
6963
+ }
6964
+ }
6965
+ return "";
6966
+ }
6967
+ function extractLocale(row) {
6968
+ if (!row || typeof row !== "object") return void 0;
6969
+ const meta = extractMetadataFromRow(row);
6970
+ if (meta?.locale && String(meta.locale).trim()) {
6971
+ return String(meta.locale).trim();
6972
+ }
6973
+ const candidates = [
6974
+ row.locale,
6975
+ row.Locale,
6976
+ row["locale"],
6977
+ row["Locale"],
6978
+ row.strapi_locale,
6979
+ row["strapi_locale"]
6980
+ ];
6981
+ for (const c of candidates) {
6982
+ if (c !== void 0 && c !== null) {
6983
+ const str = String(c).trim();
6984
+ if (str && str.toLowerCase() !== "null" && str.toLowerCase() !== "undefined" && str.toLowerCase() !== "[null]" && str.toLowerCase() !== '""') {
6985
+ return str;
6986
+ }
6987
+ }
6988
+ }
6989
+ return void 0;
6990
+ }
6991
+ function getEffectiveLocale(ct, rowLocale) {
6992
+ if (!ct?.pluginOptions?.i18n?.localized) {
6993
+ return void 0;
6994
+ }
6995
+ if (!rowLocale) {
6996
+ return void 0;
6997
+ }
6998
+ const trimmed = rowLocale.trim();
6999
+ if (!trimmed || trimmed.toLowerCase() === "null" || trimmed.toLowerCase() === "undefined" || trimmed.toLowerCase() === "[null]" || trimmed.toLowerCase() === '""') {
7000
+ return void 0;
7001
+ }
7002
+ return trimmed;
7003
+ }
7004
+ function isRowInEditingStage(row) {
7005
+ if (!row || typeof row !== "object") return false;
7006
+ const candidates = [
7007
+ row.strapi_stage,
7008
+ row["strapi_stage"],
7009
+ row.strapiStage,
7010
+ row["Strapi Stage"],
7011
+ row["strapi-stage"],
7012
+ row.stage,
7013
+ row.Stage,
7014
+ row.status,
7015
+ row.Status
7016
+ ];
7017
+ for (const c of candidates) {
7018
+ if (c !== void 0 && c !== null) {
7019
+ let stageName = "";
7020
+ if (typeof c === "object") {
7021
+ stageName = String(c.name || c.title || c.status || c.documentId || c.id || "").trim();
7022
+ } else if (typeof c === "string") {
7023
+ const trimmed = c.trim();
7024
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
7025
+ try {
7026
+ const parsed = JSON.parse(trimmed);
7027
+ if (typeof parsed === "object" && parsed !== null) {
7028
+ stageName = String(parsed.name || parsed.title || parsed.status || parsed.documentId || parsed.id || "").trim();
7029
+ }
7030
+ } catch {
7031
+ }
7032
+ }
7033
+ if (!stageName) {
7034
+ stageName = trimmed;
7035
+ }
7036
+ } else {
7037
+ stageName = String(c).trim();
7038
+ }
7039
+ if (stageName) {
7040
+ const s = stageName.toLowerCase();
7041
+ if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
7042
+ return true;
7043
+ }
7044
+ }
7045
+ }
7046
+ }
7047
+ return false;
7048
+ }
7049
+ function extractDetailedErrorMessage(err) {
7050
+ if (!err) return "Error processing row";
7051
+ const detailsErrors = err.details?.errors || err.error?.details?.errors;
7052
+ if (Array.isArray(detailsErrors) && detailsErrors.length > 0) {
7053
+ const messages = detailsErrors.map((e) => {
7054
+ if (!e) return "";
7055
+ const path = Array.isArray(e.path) ? e.path.join(".") : e.path;
7056
+ const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
7057
+ return path ? `${path}: ${msg}` : msg;
7058
+ }).filter(Boolean);
7059
+ if (messages.length > 0) return messages.join("; ");
7060
+ }
7061
+ if (Array.isArray(err.inner) && err.inner.length > 0) {
7062
+ const messages = err.inner.map((e) => {
7063
+ if (!e) return "";
7064
+ const path = e.path;
7065
+ const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
7066
+ return path ? `${path}: ${msg}` : msg;
7067
+ }).filter(Boolean);
7068
+ if (messages.length > 0) return messages.join("; ");
7069
+ }
7070
+ if (Array.isArray(err.errors) && err.errors.length > 0) {
7071
+ return err.errors.join("; ");
7072
+ }
7073
+ if (typeof err.details === "string" && err.details.trim()) {
7074
+ return err.details;
7075
+ }
7076
+ if (err.details?.message) {
7077
+ return err.details.message;
7078
+ }
7079
+ if (err.message && err.message !== "[object Object]") {
7080
+ return err.message;
7081
+ }
7082
+ return "Error processing row";
7083
+ }
7084
+ const csvImportSessions = /* @__PURE__ */ new Map();
7085
+ function cleanupStaleSessions() {
7086
+ const oneHourAgo = Date.now() - 36e5;
7087
+ for (const [id, session] of csvImportSessions.entries()) {
7088
+ if (session.createdAt < oneHourAgo) {
7089
+ csvImportSessions.delete(id);
7090
+ }
7091
+ }
7092
+ }
7093
+ const SYSTEM_FIELD_KEYS = /* @__PURE__ */ new Set([
5949
7094
  "documentid",
5950
7095
  "document_id",
5951
7096
  "docid",
@@ -5969,7 +7114,7 @@ async function findExistingDocument(strapi, uid, targetDocId, docLocale) {
5969
7114
  if (!targetDocId) return null;
5970
7115
  const ct = strapi.contentTypes[uid];
5971
7116
  const effectiveLocale = getEffectiveLocale(ct, docLocale);
5972
- const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
7117
+ const populateDef = ct ? buildLosslessPopulate(strapi, uid) : void 0;
5973
7118
  try {
5974
7119
  const queryArgs = {
5975
7120
  documentId: targetDocId,
@@ -5998,352 +7143,252 @@ async function findExistingDocument(strapi, uid, targetDocId, docLocale) {
5998
7143
  };
5999
7144
  if (effectiveLocale) queryArgs.locale = effectiveLocale;
6000
7145
  const list = await strapi.documents(uid).findMany(queryArgs);
6001
- if (list && list.length > 0) return list[0];
6002
- } catch {
6003
- }
6004
- }
6005
- return null;
6006
- }
6007
- function deepMergeComponent(existingVal, newVal) {
6008
- if (!existingVal || typeof existingVal !== "object" || Array.isArray(existingVal)) {
6009
- return newVal;
6010
- }
6011
- if (!newVal || typeof newVal !== "object" || Array.isArray(newVal)) {
6012
- return newVal;
6013
- }
6014
- const merged = { ...existingVal };
6015
- for (const k of Object.keys(newVal)) {
6016
- if (newVal[k] && typeof newVal[k] === "object" && !Array.isArray(newVal[k])) {
6017
- merged[k] = deepMergeComponent(existingVal[k], newVal[k]);
6018
- } else if (newVal[k] !== void 0) {
6019
- merged[k] = newVal[k];
6020
- }
6021
- }
6022
- return merged;
6023
- }
6024
- function parseNumberValue(rawVal, isInteger) {
6025
- const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
6026
- if (isInteger) {
6027
- const n = parseInt(cleanStr, 10);
6028
- return isNaN(n) ? null : n;
6029
- } else {
6030
- const f = parseFloat(cleanStr);
6031
- return isNaN(f) ? null : f;
6032
- }
6033
- }
6034
- function parseBooleanValue(rawVal) {
6035
- const s = String(rawVal).trim().toLowerCase();
6036
- return s === "true" || s === "1" || s === "yes" || s === "y" || s === "on";
6037
- }
6038
- function parseBlocksValue(rawVal) {
6039
- try {
6040
- const parsed = JSON.parse(rawVal);
6041
- if (Array.isArray(parsed)) {
6042
- return parsed;
6043
- }
6044
- } catch {
6045
- }
6046
- const trimmed = String(rawVal).trim();
6047
- if (!trimmed) return [];
6048
- return [{ type: "paragraph", children: [{ type: "text", text: trimmed }] }];
6049
- }
6050
- function parseEnumValue(rawVal, allowedValues) {
6051
- const trimmed = String(rawVal).trim();
6052
- if (Array.isArray(allowedValues) && allowedValues.length > 0) {
6053
- const match = allowedValues.find((v) => v.toLowerCase() === trimmed.toLowerCase());
6054
- if (match) return match;
6055
- }
6056
- return trimmed;
6057
- }
6058
- function parseRelationValue(rawVal, relationType) {
6059
- const isToMany = relationType ? relationType.toLowerCase().endsWith("many") : false;
6060
- if (rawVal === null || rawVal === void 0) return isToMany ? [] : null;
6061
- let parsed = rawVal;
6062
- if (typeof rawVal === "string") {
6063
- const trimmed = rawVal.trim();
6064
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
6065
- try {
6066
- parsed = JSON.parse(trimmed);
6067
- } catch {
6068
- }
7146
+ if (list && list.length > 0) return list[0];
7147
+ } catch {
6069
7148
  }
6070
7149
  }
6071
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6072
- if (parsed.name && (parsed.locale === null || LIFECYCLE_STATUS_WORDS.has(String(parsed.name).trim().toLowerCase()))) {
6073
- return isToMany ? [] : null;
6074
- }
6075
- const docId = parsed.documentId || parsed.id || null;
6076
- if (docId && isValidDocId(String(docId).trim())) {
6077
- const validStr = String(docId).trim();
6078
- return isToMany ? [validStr] : validStr;
6079
- }
6080
- return isToMany ? [] : null;
7150
+ return null;
7151
+ }
7152
+ function deepMergeComponent(existingVal, newVal) {
7153
+ if (!existingVal || typeof existingVal !== "object" || Array.isArray(existingVal)) {
7154
+ return newVal;
6081
7155
  }
6082
- if (Array.isArray(parsed)) {
6083
- const ids = parsed.map((item) => {
6084
- if (typeof item === "object" && item !== null) {
6085
- if (item.name && (item.locale === null || LIFECYCLE_STATUS_WORDS.has(String(item.name).trim().toLowerCase()))) {
6086
- return null;
6087
- }
6088
- const id = item.documentId || item.id;
6089
- return id && isValidDocId(String(id).trim()) ? String(id).trim() : null;
6090
- }
6091
- return isValidDocId(String(item).trim()) ? String(item).trim() : null;
6092
- }).filter(Boolean);
6093
- return isToMany ? ids : ids[0] || null;
7156
+ if (!newVal || typeof newVal !== "object" || Array.isArray(newVal)) {
7157
+ return newVal;
6094
7158
  }
6095
- if (typeof rawVal === "string") {
6096
- if (rawVal.includes(";") || rawVal.includes(",")) {
6097
- const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocId(p));
6098
- return isToMany ? parts : parts[0] || null;
7159
+ const merged = { ...existingVal };
7160
+ for (const k of Object.keys(newVal)) {
7161
+ if (newVal[k] && typeof newVal[k] === "object" && !Array.isArray(newVal[k])) {
7162
+ merged[k] = deepMergeComponent(existingVal[k], newVal[k]);
7163
+ } else if (newVal[k] !== void 0) {
7164
+ merged[k] = newVal[k];
6099
7165
  }
6100
- const trimmed = rawVal.trim();
6101
- if (isValidDocId(trimmed)) {
6102
- return isToMany ? [trimmed] : trimmed;
7166
+ }
7167
+ return merged;
7168
+ }
7169
+ function formatValueDisplay(val) {
7170
+ if (val === null || val === void 0) return "(empty)";
7171
+ if (typeof val === "object") {
7172
+ try {
7173
+ return JSON.stringify(val);
7174
+ } catch {
7175
+ return String(val);
6103
7176
  }
6104
7177
  }
6105
- return isToMany ? [] : null;
7178
+ const s = String(val).trim();
7179
+ return s === "" ? "(empty)" : s;
6106
7180
  }
6107
- function parseMediaValue(rawVal, isMultiple = false) {
6108
- const trimmed = String(rawVal).trim();
6109
- if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
7181
+ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, publishedCounterparts, stats, actionLabel = "Updated") {
7182
+ const resolvedDocId = existing.documentId;
7183
+ const updatePayload = await buildDocumentUpdatePayload(
7184
+ strapi,
7185
+ uid,
7186
+ existing,
7187
+ row,
7188
+ { isPartialUpdate: options.mode === "update" }
7189
+ );
7190
+ if (Object.keys(updatePayload).length === 0) {
7191
+ stats.skipped++;
7192
+ stats.diffs.push({
7193
+ uid,
7194
+ collectionName: ct.info?.displayName || uid,
7195
+ documentId: resolvedDocId,
7196
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
7197
+ attribute: "",
7198
+ oldValue: existing,
7199
+ newValue: {},
7200
+ status: "skipped",
7201
+ message: `Skipped (no editable attributes in row ${rowNumber})`
7202
+ });
7203
+ return;
7204
+ }
7205
+ let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
7206
+ if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6110
7207
  try {
6111
- const parsed = JSON.parse(trimmed);
6112
- if (Array.isArray(parsed)) {
6113
- const ids = parsed.map((item) => typeof item === "object" && item !== null ? item.id || item.documentId : item).filter(Boolean);
6114
- return isMultiple ? ids : ids[0] || null;
6115
- }
6116
- if (typeof parsed === "number") {
6117
- return isMultiple ? [parsed] : parsed;
6118
- }
6119
- if (typeof parsed === "object" && parsed !== null) {
6120
- const id = parsed.id || parsed.documentId || parsed;
6121
- return isMultiple ? [id] : id;
7208
+ const singlePub = await strapi.documents(uid).findMany({
7209
+ status: "published",
7210
+ filters: { documentId: resolvedDocId },
7211
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
7212
+ limit: 1
7213
+ });
7214
+ if (singlePub && singlePub.length > 0) {
7215
+ pubRecord = singlePub[0];
7216
+ publishedCounterparts.set(String(resolvedDocId), pubRecord);
6122
7217
  }
6123
7218
  } catch {
6124
7219
  }
6125
7220
  }
6126
- if (rawVal.includes(";") || rawVal.includes(",")) {
6127
- const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean).map((s) => /^\d+$/.test(s) ? parseInt(s, 10) : s);
6128
- return isMultiple ? parts : parts[0] || null;
7221
+ const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
7222
+ const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
7223
+ const inspectionExisting = rowStatus || rowPubAt ? {
7224
+ ...existing,
7225
+ ...rowStatus ? { status: rowStatus } : {},
7226
+ ...rowPubAt ? { publishedAt: rowPubAt } : {}
7227
+ } : existing;
7228
+ const { hadPublishedVersion } = resolveRecordPublicationStatus(
7229
+ inspectionExisting,
7230
+ pubRecord,
7231
+ isDraftAndPublish
7232
+ );
7233
+ const shouldPublish = evaluateShouldPublish({
7234
+ isDraftAndPublish,
7235
+ hadPublishedVersion,
7236
+ isEditing,
7237
+ publishOnApproval: Boolean(options.publish),
7238
+ publishStrategy: options.publishStrategy || "safe",
7239
+ unreviewedConsent: options.unreviewedConsent
7240
+ });
7241
+ const proposedEntity = deepMergeEntities(existing, updatePayload);
7242
+ const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
7243
+ if (!valResult.isValid) {
7244
+ stats.skipped++;
7245
+ if (stats.failed !== void 0) stats.failed++;
7246
+ stats.errors.push({
7247
+ row: rowNumber,
7248
+ documentId: resolvedDocId,
7249
+ error: valResult.errorMessage
7250
+ });
7251
+ stats.diffs.push({
7252
+ uid,
7253
+ collectionName: ct.info?.displayName || uid,
7254
+ documentId: resolvedDocId,
7255
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
7256
+ attribute: valResult.targetField || "",
7257
+ oldValue: existing?.[valResult.targetField || ""] ?? null,
7258
+ newValue: updatePayload?.[valResult.targetField || ""] ?? null,
7259
+ status: "error",
7260
+ message: valResult.errorMessage
7261
+ });
7262
+ return;
6129
7263
  }
6130
- if (/^\d+$/.test(trimmed)) {
6131
- const numId = parseInt(trimmed, 10);
6132
- return isMultiple ? [numId] : numId;
7264
+ const updateArgs = {
7265
+ documentId: resolvedDocId,
7266
+ data: updatePayload
7267
+ };
7268
+ if (effectiveLocale) updateArgs.locale = effectiveLocale;
7269
+ await strapi.documents(uid).update(updateArgs);
7270
+ if (shouldPublish) {
7271
+ try {
7272
+ const pubArgs = { documentId: resolvedDocId };
7273
+ if (effectiveLocale) pubArgs.locale = effectiveLocale;
7274
+ await strapi.documents(uid).publish(pubArgs);
7275
+ } catch (pubErr) {
7276
+ strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
7277
+ }
6133
7278
  }
6134
- if (isValidDocId(trimmed)) {
6135
- return isMultiple ? [trimmed] : trimmed;
7279
+ try {
7280
+ await recordContentHistoryVersion(strapi, {
7281
+ uid,
7282
+ documentId: resolvedDocId,
7283
+ userId: options.user?.id,
7284
+ statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
7285
+ });
7286
+ } catch {
6136
7287
  }
6137
- return isMultiple ? [] : null;
6138
- }
6139
- function parseRowToPayload(strapi, attrs, row) {
6140
- const payload2 = {};
6141
- for (const [key, rawVal] of Object.entries(row)) {
6142
- const normalizedKey = key.toLowerCase().replace(/[\s_-]/g, "");
6143
- if (SYSTEM_FIELD_KEYS.has(normalizedKey)) continue;
6144
- if (key.includes(".")) {
6145
- const topPart = key.split(".")[0].toLowerCase().replace(/[\s_-]/g, "");
6146
- if (SYSTEM_FIELD_KEYS.has(topPart)) continue;
6147
- const parts = key.split(".");
6148
- let currentAttrs = attrs;
6149
- let currentTarget = payload2;
6150
- for (let pIdx = 0; pIdx < parts.length; pIdx++) {
6151
- const part = parts[pIdx];
6152
- const isLeaf = pIdx === parts.length - 1;
6153
- if (isLeaf) {
6154
- let leafDef = currentAttrs[part];
6155
- if (!leafDef) {
6156
- const match = Object.keys(currentAttrs).find(
6157
- (k) => k.toLowerCase() === part.toLowerCase() || k.toLowerCase() === part.toLowerCase().replace(/\s+/g, "")
6158
- );
6159
- if (match) leafDef = currentAttrs[match];
6160
- }
6161
- if (!leafDef) {
6162
- break;
6163
- }
6164
- if (rawVal === "" || rawVal === null || rawVal === void 0) {
6165
- if (leafDef.type !== "dynamiczone" && !(leafDef.type === "component" && leafDef.repeatable) && leafDef.type !== "relation" && leafDef.type !== "password") {
6166
- currentTarget[part] = null;
6167
- }
6168
- } else if (leafDef.type === "integer" || leafDef.type === "biginteger") {
6169
- currentTarget[part] = parseNumberValue(rawVal, true);
6170
- } else if (leafDef.type === "float" || leafDef.type === "decimal") {
6171
- currentTarget[part] = parseNumberValue(rawVal, false);
6172
- } else if (leafDef.type === "boolean") {
6173
- currentTarget[part] = parseBooleanValue(rawVal);
6174
- } else if (leafDef.type === "blocks") {
6175
- currentTarget[part] = parseBlocksValue(rawVal);
6176
- } else if (leafDef.type === "enumeration") {
6177
- currentTarget[part] = parseEnumValue(rawVal, leafDef.enum);
6178
- } else if (leafDef.type === "relation") {
6179
- currentTarget[part] = parseRelationValue(rawVal, leafDef.relation);
6180
- } else if (leafDef.type === "media") {
6181
- currentTarget[part] = parseMediaValue(rawVal, Boolean(leafDef.multiple));
6182
- } else if (leafDef.type === "date" || leafDef.type === "time" || leafDef.type === "datetime" || leafDef.type === "timestamp") {
6183
- currentTarget[part] = String(rawVal).trim() || null;
6184
- } else if (leafDef.type === "email" || leafDef.type === "uid") {
6185
- currentTarget[part] = String(rawVal).trim();
6186
- } else if (leafDef.type === "password") {
6187
- if (String(rawVal).trim()) {
6188
- currentTarget[part] = String(rawVal).trim();
6189
- }
6190
- } else if (leafDef.type === "json") {
6191
- try {
6192
- currentTarget[part] = JSON.parse(rawVal);
6193
- } catch {
6194
- currentTarget[part] = rawVal;
6195
- }
6196
- } else if (leafDef.type === "component" && leafDef.repeatable) {
6197
- try {
6198
- const parsed = JSON.parse(rawVal);
6199
- if (Array.isArray(parsed)) {
6200
- currentTarget[part] = parsed;
6201
- }
6202
- } catch {
6203
- }
6204
- } else {
6205
- currentTarget[part] = rawVal;
6206
- }
6207
- } else {
6208
- let compDef = currentAttrs[part];
6209
- if (!compDef) {
6210
- const match = Object.keys(currentAttrs).find(
6211
- (k) => k.toLowerCase() === part.toLowerCase() || k.toLowerCase() === part.toLowerCase().replace(/\s+/g, "")
6212
- );
6213
- if (match) compDef = currentAttrs[match];
6214
- }
6215
- if (compDef?.type === "component" && !compDef.repeatable && compDef.component) {
6216
- const comp = strapi.components[compDef.component];
6217
- if (!comp?.attributes) {
6218
- break;
6219
- }
6220
- if (!currentTarget[part] || typeof currentTarget[part] !== "object" || Array.isArray(currentTarget[part])) {
6221
- currentTarget[part] = {};
6222
- }
6223
- currentTarget = currentTarget[part];
6224
- currentAttrs = comp.attributes;
6225
- } else {
6226
- break;
6227
- }
6228
- }
6229
- }
6230
- continue;
6231
- }
6232
- let attrDef = attrs[key];
6233
- if (!attrDef) {
6234
- const matchKey = Object.keys(attrs).find(
6235
- (k) => k.toLowerCase() === key.toLowerCase() || k.toLowerCase() === key.toLowerCase().replace(/\s+/g, "")
6236
- );
6237
- if (matchKey) {
6238
- attrDef = attrs[matchKey];
6239
- }
6240
- }
6241
- if (!attrDef) continue;
6242
- if (attrDef?.target?.includes("review-workflow") || attrDef?.target === "admin::review-workflow-stage") {
6243
- continue;
6244
- }
6245
- if (rawVal === "" || rawVal === null || rawVal === void 0) {
6246
- if (attrDef.type !== "dynamiczone" && !(attrDef.type === "component" && attrDef.repeatable) && attrDef.type !== "relation" && attrDef.type !== "password") {
6247
- payload2[key] = null;
6248
- }
6249
- continue;
6250
- }
6251
- switch (attrDef.type) {
6252
- case "integer":
6253
- case "biginteger":
6254
- payload2[key] = parseNumberValue(rawVal, true);
6255
- break;
6256
- case "float":
6257
- case "decimal":
6258
- payload2[key] = parseNumberValue(rawVal, false);
6259
- break;
6260
- case "boolean":
6261
- payload2[key] = parseBooleanValue(rawVal);
6262
- break;
6263
- case "blocks":
6264
- payload2[key] = parseBlocksValue(rawVal);
6265
- break;
6266
- case "enumeration":
6267
- payload2[key] = parseEnumValue(rawVal, attrDef.enum);
6268
- break;
6269
- case "relation":
6270
- payload2[key] = parseRelationValue(rawVal, attrDef.relation);
6271
- break;
6272
- case "media":
6273
- payload2[key] = parseMediaValue(rawVal, Boolean(attrDef.multiple));
6274
- break;
6275
- case "date":
6276
- case "time":
6277
- case "datetime":
6278
- case "timestamp":
6279
- payload2[key] = String(rawVal).trim() || null;
6280
- break;
6281
- case "email":
6282
- case "uid":
6283
- payload2[key] = String(rawVal).trim();
6284
- break;
6285
- case "password":
6286
- if (String(rawVal).trim()) {
6287
- payload2[key] = String(rawVal).trim();
6288
- }
6289
- break;
6290
- case "json":
6291
- try {
6292
- payload2[key] = JSON.parse(rawVal);
6293
- } catch {
6294
- payload2[key] = rawVal;
6295
- }
6296
- break;
6297
- case "dynamiczone": {
6298
- try {
6299
- const parsed = JSON.parse(rawVal);
6300
- if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object" && typeof item.__component === "string")) {
6301
- payload2[key] = parsed;
6302
- }
6303
- } catch {
6304
- }
6305
- break;
6306
- }
6307
- case "component": {
6308
- if (attrDef.repeatable) {
6309
- try {
6310
- const parsed = JSON.parse(rawVal);
6311
- if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object")) {
6312
- payload2[key] = parsed;
6313
- }
6314
- } catch {
6315
- }
6316
- } else {
6317
- try {
6318
- const parsed = JSON.parse(rawVal);
6319
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6320
- payload2[key] = parsed;
6321
- }
6322
- } catch {
6323
- }
6324
- }
6325
- break;
7288
+ try {
7289
+ const postDoc = await strapi.documents(uid).findOne({
7290
+ documentId: resolvedDocId,
7291
+ ...effectiveLocale ? { locale: effectiveLocale } : {},
7292
+ populate: buildLosslessPopulate(strapi, uid)
7293
+ });
7294
+ if (postDoc) {
7295
+ const integrityReport = verifyDocumentIntegrity(strapi, uid, existing, updatePayload, postDoc);
7296
+ if (integrityReport.status === "FAILED") {
7297
+ strapi.log.warn(`[bulk-updater] Data integrity warning on row ${rowNumber}:`, integrityReport.diffs);
6326
7298
  }
6327
- default:
6328
- payload2[key] = rawVal;
6329
7299
  }
7300
+ } catch {
7301
+ }
7302
+ stats.updated++;
7303
+ for (const attrKey of Object.keys(updatePayload)) {
7304
+ const oldVal = existing?.[attrKey] ?? null;
7305
+ const newVal = updatePayload[attrKey];
7306
+ stats.diffs.push({
7307
+ uid,
7308
+ collectionName: ct.info?.displayName || uid,
7309
+ documentId: resolvedDocId,
7310
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
7311
+ attribute: attrKey,
7312
+ oldValue: oldVal,
7313
+ newValue: newVal,
7314
+ status: "updated",
7315
+ message: `${actionLabel} "${attrKey}" via CSV import (row ${rowNumber})`
7316
+ });
6330
7317
  }
6331
- return payload2;
6332
7318
  }
6333
- function formatValueDisplay(val) {
6334
- if (val === null || val === void 0) return "(empty)";
6335
- if (typeof val === "object") {
7319
+ async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, stats) {
7320
+ const createPayload = await buildDocumentUpdatePayload(
7321
+ strapi,
7322
+ uid,
7323
+ null,
7324
+ row,
7325
+ {}
7326
+ );
7327
+ const valResultNew = await validateEntityQuotas(strapi, uid, createPayload);
7328
+ if (!valResultNew.isValid) {
7329
+ stats.skipped++;
7330
+ if (stats.failed !== void 0) stats.failed++;
7331
+ stats.errors.push({
7332
+ row: rowNumber,
7333
+ documentId: docId || "new",
7334
+ error: valResultNew.errorMessage
7335
+ });
7336
+ stats.diffs.push({
7337
+ uid,
7338
+ collectionName: ct.info?.displayName || uid,
7339
+ documentId: docId || "new",
7340
+ label: `Row ${rowNumber}`,
7341
+ attribute: valResultNew.targetField || "",
7342
+ oldValue: null,
7343
+ newValue: createPayload?.[valResultNew.targetField || ""] ?? null,
7344
+ status: "error",
7345
+ message: valResultNew.errorMessage
7346
+ });
7347
+ return;
7348
+ }
7349
+ const createArgs = { data: createPayload };
7350
+ if (effectiveLocale) createArgs.locale = effectiveLocale;
7351
+ const created = await strapi.documents(uid).create(createArgs);
7352
+ const newDocId = created?.documentId || docId;
7353
+ const shouldPublishNew = !isEditing && isDraftAndPublish && Boolean(options.publish) && (options.publishStrategy === "all" || options.unreviewedConsent ? true : false);
7354
+ if (shouldPublishNew && newDocId) {
6336
7355
  try {
6337
- return JSON.stringify(val);
6338
- } catch {
6339
- return String(val);
7356
+ const pubArgs = { documentId: newDocId };
7357
+ if (effectiveLocale) pubArgs.locale = effectiveLocale;
7358
+ await strapi.documents(uid).publish(pubArgs);
7359
+ } catch (pubErr) {
7360
+ strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
6340
7361
  }
6341
7362
  }
6342
- const s = String(val).trim();
6343
- return s === "" ? "(empty)" : s;
7363
+ try {
7364
+ await recordContentHistoryVersion(strapi, {
7365
+ uid,
7366
+ documentId: newDocId,
7367
+ userId: options.user?.id,
7368
+ statusOverride: shouldPublishNew ? "published" : isDraftAndPublish ? "draft" : void 0
7369
+ });
7370
+ } catch {
7371
+ }
7372
+ stats.created++;
7373
+ if (!docId) {
7374
+ stats.newWithoutDocId++;
7375
+ }
7376
+ for (const attrKey of Object.keys(createPayload)) {
7377
+ stats.diffs.push({
7378
+ uid,
7379
+ collectionName: ct.info?.displayName || uid,
7380
+ documentId: newDocId,
7381
+ label: created?.title || created?.name || `New Entry #${newDocId}`,
7382
+ attribute: attrKey,
7383
+ oldValue: null,
7384
+ newValue: createPayload[attrKey],
7385
+ status: "created",
7386
+ message: docId ? `Created "${attrKey}" via CSV import (row ${rowNumber})` : `Created "${attrKey}" as new entry (row ${rowNumber})`
7387
+ });
7388
+ }
6344
7389
  }
6345
7390
  async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6346
- const attrs = ct.attributes || {};
7391
+ ct.attributes || {};
6347
7392
  const { mode = "auto", publish = true, publishStrategy = "safe", user } = options;
6348
7393
  const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
6349
7394
  const docIdsInChunk = rows.map((r) => extractDocId(r)).filter(Boolean);
@@ -6387,323 +7432,84 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6387
7432
  if (ct.kind === "singleType" && !docId) {
6388
7433
  try {
6389
7434
  const findSingleArgs = {};
6390
- if (effectiveLocale) findSingleArgs.locale = effectiveLocale;
6391
- const singleDoc = await strapi.documents(uid).findFirst(findSingleArgs);
6392
- if (singleDoc?.documentId) {
6393
- docId = singleDoc.documentId;
6394
- }
6395
- } catch {
6396
- }
6397
- }
6398
- const payload2 = parseRowToPayload(strapi, attrs, row);
6399
- try {
6400
- if (mode === "update") {
6401
- if (!docId) {
6402
- stats.skipped++;
6403
- stats.errors.push({
6404
- row: rowNumber,
6405
- error: "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs)."
6406
- });
6407
- continue;
6408
- }
6409
- const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
6410
- if (!existing) {
6411
- stats.skipped++;
6412
- stats.errors.push({
6413
- row: rowNumber,
6414
- documentId: docId,
6415
- error: `Document with ID "${docId}" not found in database.`
6416
- });
6417
- continue;
6418
- }
6419
- const resolvedDocId = existing.documentId || docId;
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]);
6424
- }
6425
- }
6426
- if (Object.keys(mergedPayload).length === 0) {
6427
- stats.skipped++;
6428
- stats.diffs.push({
6429
- uid,
6430
- collectionName: ct.info?.displayName || uid,
6431
- documentId: resolvedDocId,
6432
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6433
- attribute: "",
6434
- oldValue: existing,
6435
- newValue: {},
6436
- status: "skipped",
6437
- message: `Skipped (no editable attributes in row ${rowNumber})`
6438
- });
6439
- continue;
6440
- }
6441
- let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
6442
- if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6443
- try {
6444
- const singlePub = await strapi.documents(uid).findMany({
6445
- status: "published",
6446
- filters: { documentId: resolvedDocId },
6447
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6448
- limit: 1
6449
- });
6450
- if (singlePub && singlePub.length > 0) {
6451
- pubRecord = singlePub[0];
6452
- publishedCounterparts.set(String(resolvedDocId), pubRecord);
6453
- }
6454
- } catch {
6455
- }
6456
- }
6457
- const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
6458
- const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
6459
- const inspectionExisting = rowStatus || rowPubAt ? { ...existing, ...rowStatus ? { status: rowStatus } : {}, ...rowPubAt ? { publishedAt: rowPubAt } : {} } : existing;
6460
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
6461
- inspectionExisting,
6462
- pubRecord,
6463
- isDraftAndPublish
6464
- );
6465
- const shouldPublish = evaluateShouldPublish({
6466
- isDraftAndPublish,
6467
- hadPublishedVersion,
6468
- isEditing,
6469
- publishOnApproval: Boolean(publish),
6470
- publishStrategy,
6471
- unreviewedConsent: options.unreviewedConsent
6472
- });
6473
- const updateArgs = {
6474
- documentId: resolvedDocId,
6475
- data: mergedPayload
6476
- };
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
- }
6501
- await strapi.documents(uid).update(updateArgs);
6502
- if (shouldPublish) {
6503
- try {
6504
- const pubArgs = { documentId: resolvedDocId };
6505
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6506
- await strapi.documents(uid).publish(pubArgs);
6507
- } catch (pubErr) {
6508
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
6509
- }
6510
- }
6511
- try {
6512
- await recordContentHistoryVersion(strapi, {
6513
- uid,
6514
- documentId: resolvedDocId,
6515
- userId: user?.id,
6516
- statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
6517
- });
6518
- } catch {
6519
- }
6520
- stats.updated++;
6521
- for (const attrKey of Object.keys(payload2)) {
6522
- const oldVal = existing?.[attrKey] ?? null;
6523
- const newVal = payload2[attrKey];
6524
- stats.diffs.push({
6525
- uid,
6526
- collectionName: ct.info?.displayName || uid,
6527
- documentId: resolvedDocId,
6528
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6529
- attribute: attrKey,
6530
- oldValue: oldVal,
6531
- newValue: newVal,
6532
- status: "updated",
6533
- message: `Updated "${attrKey}" via CSV import (row ${rowNumber})`
6534
- });
6535
- }
6536
- } else if (mode === "create_or_override") {
6537
- let existing = null;
6538
- if (docId) {
6539
- existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
7435
+ if (effectiveLocale) findSingleArgs.locale = effectiveLocale;
7436
+ const singleDoc = await strapi.documents(uid).findFirst(findSingleArgs);
7437
+ if (singleDoc?.documentId) {
7438
+ docId = singleDoc.documentId;
6540
7439
  }
6541
- if (existing) {
6542
- const resolvedDocId = existing.documentId || docId;
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]);
6547
- }
6548
- }
6549
- let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
6550
- if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6551
- try {
6552
- const singlePub = await strapi.documents(uid).findMany({
6553
- status: "published",
6554
- filters: { documentId: resolvedDocId },
6555
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6556
- limit: 1
6557
- });
6558
- if (singlePub && singlePub.length > 0) {
6559
- pubRecord = singlePub[0];
6560
- publishedCounterparts.set(String(resolvedDocId), pubRecord);
6561
- }
6562
- } catch {
6563
- }
6564
- }
6565
- const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
6566
- const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
6567
- const inspectionExisting = rowStatus || rowPubAt ? { ...existing, ...rowStatus ? { status: rowStatus } : {}, ...rowPubAt ? { publishedAt: rowPubAt } : {} } : existing;
6568
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
6569
- inspectionExisting,
6570
- pubRecord,
6571
- isDraftAndPublish
6572
- );
6573
- const shouldPublish = evaluateShouldPublish({
6574
- isDraftAndPublish,
6575
- hadPublishedVersion,
6576
- isEditing,
6577
- publishOnApproval: Boolean(publish),
6578
- publishStrategy,
6579
- unreviewedConsent: options.unreviewedConsent
7440
+ } catch {
7441
+ }
7442
+ }
7443
+ try {
7444
+ if (mode === "update") {
7445
+ if (!docId) {
7446
+ stats.skipped++;
7447
+ stats.errors.push({
7448
+ row: rowNumber,
7449
+ error: "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs)."
6580
7450
  });
6581
- const updateArgs = {
6582
- documentId: resolvedDocId,
6583
- data: mergedPayload
6584
- };
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
- }
6609
- await strapi.documents(uid).update(updateArgs);
6610
- if (shouldPublish) {
6611
- try {
6612
- const pubArgs = { documentId: resolvedDocId };
6613
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6614
- await strapi.documents(uid).publish(pubArgs);
6615
- } catch (pubErr) {
6616
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
6617
- }
6618
- }
6619
- try {
6620
- await recordContentHistoryVersion(strapi, {
6621
- uid,
6622
- documentId: resolvedDocId,
6623
- userId: user?.id,
6624
- statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
6625
- });
6626
- } catch {
6627
- }
6628
- stats.updated++;
6629
- for (const attrKey of Object.keys(payload2)) {
6630
- const oldVal = existing?.[attrKey] ?? null;
6631
- const newVal = payload2[attrKey];
6632
- stats.diffs.push({
6633
- uid,
6634
- collectionName: ct.info?.displayName || uid,
6635
- documentId: resolvedDocId,
6636
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6637
- attribute: attrKey,
6638
- oldValue: oldVal,
6639
- newValue: newVal,
6640
- status: "updated",
6641
- message: `Overridden "${attrKey}" via CSV import (row ${rowNumber})`
6642
- });
6643
- }
6644
7451
  continue;
6645
7452
  }
6646
- const valResultNew = await validateEntityQuotas(strapi, uid, payload2);
6647
- if (!valResultNew.isValid) {
7453
+ const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
7454
+ if (!existing) {
6648
7455
  stats.skipped++;
6649
- if (stats.failed !== void 0) stats.failed++;
6650
7456
  stats.errors.push({
6651
7457
  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
7458
+ documentId: docId,
7459
+ error: `Document with ID "${docId}" not found in database.`
6665
7460
  });
6666
7461
  continue;
6667
7462
  }
6668
- const createArgs = { data: payload2 };
6669
- if (effectiveLocale) createArgs.locale = effectiveLocale;
6670
- const created = await strapi.documents(uid).create(createArgs);
6671
- const newDocId = created?.documentId || docId;
6672
- const shouldPublishNew = !isEditing && isDraftAndPublish && Boolean(publish) && (publishStrategy === "all" || options.unreviewedConsent ? true : false);
6673
- if (shouldPublishNew && newDocId) {
6674
- try {
6675
- const pubArgs = { documentId: newDocId };
6676
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6677
- await strapi.documents(uid).publish(pubArgs);
6678
- } catch (pubErr) {
6679
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
6680
- }
7463
+ await executeUpdateMutation(
7464
+ strapi,
7465
+ ct,
7466
+ uid,
7467
+ existing,
7468
+ row,
7469
+ rowNumber,
7470
+ options,
7471
+ effectiveLocale,
7472
+ isEditing,
7473
+ isDraftAndPublish,
7474
+ publishedCounterparts,
7475
+ stats,
7476
+ "Updated"
7477
+ );
7478
+ } else if (mode === "create_or_override") {
7479
+ let existing = null;
7480
+ if (docId) {
7481
+ existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
6681
7482
  }
6682
- try {
6683
- await recordContentHistoryVersion(strapi, {
7483
+ if (existing) {
7484
+ await executeUpdateMutation(
7485
+ strapi,
7486
+ ct,
6684
7487
  uid,
6685
- documentId: newDocId,
6686
- userId: user?.id,
6687
- statusOverride: shouldPublishNew ? "published" : isDraftAndPublish ? "draft" : void 0
6688
- });
6689
- } catch {
6690
- }
6691
- stats.created++;
6692
- if (!docId) {
6693
- stats.newWithoutDocId++;
6694
- }
6695
- for (const attrKey of Object.keys(payload2)) {
6696
- stats.diffs.push({
7488
+ existing,
7489
+ row,
7490
+ rowNumber,
7491
+ options,
7492
+ effectiveLocale,
7493
+ isEditing,
7494
+ isDraftAndPublish,
7495
+ publishedCounterparts,
7496
+ stats,
7497
+ "Overridden"
7498
+ );
7499
+ } else {
7500
+ await executeCreateMutation(
7501
+ strapi,
7502
+ ct,
6697
7503
  uid,
6698
- collectionName: ct.info?.displayName || uid,
6699
- documentId: newDocId,
6700
- label: created?.title || created?.name || `New Entry #${newDocId}`,
6701
- attribute: attrKey,
6702
- oldValue: null,
6703
- newValue: payload2[attrKey],
6704
- status: "created",
6705
- message: docId ? `Created "${attrKey}" via CSV import (row ${rowNumber})` : `Created "${attrKey}" as new entry (row ${rowNumber})`
6706
- });
7504
+ docId,
7505
+ row,
7506
+ rowNumber,
7507
+ options,
7508
+ effectiveLocale,
7509
+ isEditing,
7510
+ isDraftAndPublish,
7511
+ stats
7512
+ );
6707
7513
  }
6708
7514
  } else {
6709
7515
  let existing = null;
@@ -6711,178 +7517,56 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6711
7517
  existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
6712
7518
  }
6713
7519
  if (existing) {
6714
- const resolvedDocId = existing.documentId || docId;
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]);
6719
- }
6720
- }
6721
- let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
6722
- if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6723
- try {
6724
- const singlePub = await strapi.documents(uid).findMany({
6725
- status: "published",
6726
- filters: { documentId: resolvedDocId },
6727
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6728
- limit: 1
6729
- });
6730
- if (singlePub && singlePub.length > 0) {
6731
- pubRecord = singlePub[0];
6732
- publishedCounterparts.set(String(resolvedDocId), pubRecord);
6733
- }
6734
- } catch {
6735
- }
6736
- }
6737
- const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
6738
- const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
6739
- const inspectionExisting = rowStatus || rowPubAt ? { ...existing, ...rowStatus ? { status: rowStatus } : {}, ...rowPubAt ? { publishedAt: rowPubAt } : {} } : existing;
6740
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
6741
- inspectionExisting,
6742
- pubRecord,
6743
- isDraftAndPublish
6744
- );
6745
- const shouldPublish = evaluateShouldPublish({
6746
- isDraftAndPublish,
6747
- hadPublishedVersion,
6748
- isEditing,
6749
- publishOnApproval: Boolean(publish),
6750
- publishStrategy,
6751
- unreviewedConsent: options.unreviewedConsent
6752
- });
6753
- const updateArgs = {
6754
- documentId: resolvedDocId,
6755
- data: mergedPayload
6756
- };
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
- }
6781
- await strapi.documents(uid).update(updateArgs);
6782
- if (shouldPublish) {
6783
- try {
6784
- const pubArgs = { documentId: resolvedDocId };
6785
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6786
- await strapi.documents(uid).publish(pubArgs);
6787
- } catch (pubErr) {
6788
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
6789
- }
6790
- }
6791
- try {
6792
- await recordContentHistoryVersion(strapi, {
6793
- uid,
6794
- documentId: resolvedDocId,
6795
- userId: user?.id,
6796
- statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
6797
- });
6798
- } catch {
6799
- }
6800
- stats.updated++;
6801
- for (const attrKey of Object.keys(payload2)) {
6802
- const oldVal = existing?.[attrKey] ?? null;
6803
- const newVal = payload2[attrKey];
6804
- stats.diffs.push({
6805
- uid,
6806
- collectionName: ct.info?.displayName || uid,
6807
- documentId: resolvedDocId,
6808
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6809
- attribute: attrKey,
6810
- oldValue: oldVal,
6811
- newValue: newVal,
6812
- status: "updated",
6813
- message: `Updated "${attrKey}" via CSV import (row ${rowNumber})`
6814
- });
6815
- }
6816
- continue;
6817
- }
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 };
6841
- if (effectiveLocale) createArgs.locale = effectiveLocale;
6842
- const created = await strapi.documents(uid).create(createArgs);
6843
- const newDocId = created?.documentId || docId;
6844
- const shouldPublishNew = !isEditing && isDraftAndPublish && Boolean(publish) && (publishStrategy === "all" || options.unreviewedConsent ? true : false);
6845
- if (shouldPublishNew && newDocId) {
6846
- try {
6847
- const pubArgs = { documentId: newDocId };
6848
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6849
- await strapi.documents(uid).publish(pubArgs);
6850
- } catch (pubErr) {
6851
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
6852
- }
6853
- }
6854
- try {
6855
- await recordContentHistoryVersion(strapi, {
7520
+ await executeUpdateMutation(
7521
+ strapi,
7522
+ ct,
6856
7523
  uid,
6857
- documentId: newDocId,
6858
- userId: user?.id,
6859
- statusOverride: shouldPublishNew ? "published" : isDraftAndPublish ? "draft" : void 0
6860
- });
6861
- } catch {
6862
- }
6863
- stats.created++;
6864
- if (!docId) {
6865
- stats.newWithoutDocId++;
6866
- }
6867
- for (const attrKey of Object.keys(payload2)) {
6868
- stats.diffs.push({
7524
+ existing,
7525
+ row,
7526
+ rowNumber,
7527
+ options,
7528
+ effectiveLocale,
7529
+ isEditing,
7530
+ isDraftAndPublish,
7531
+ publishedCounterparts,
7532
+ stats,
7533
+ "Updated"
7534
+ );
7535
+ } else {
7536
+ await executeCreateMutation(
7537
+ strapi,
7538
+ ct,
6869
7539
  uid,
6870
- collectionName: ct.info?.displayName || uid,
6871
- documentId: newDocId,
6872
- label: created?.title || created?.name || `New Entry #${newDocId}`,
6873
- attribute: attrKey,
6874
- oldValue: null,
6875
- newValue: payload2[attrKey],
6876
- status: "created",
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})`
6878
- });
7540
+ docId,
7541
+ row,
7542
+ rowNumber,
7543
+ options,
7544
+ effectiveLocale,
7545
+ isEditing,
7546
+ isDraftAndPublish,
7547
+ stats
7548
+ );
6879
7549
  }
6880
7550
  }
6881
7551
  } catch (err) {
7552
+ stats.skipped++;
7553
+ if (stats.failed !== void 0) stats.failed++;
7554
+ const errMsg = extractDetailedErrorMessage(err);
6882
7555
  stats.errors.push({
6883
7556
  row: rowNumber,
6884
7557
  documentId: docId || void 0,
6885
- error: extractDetailedErrorMessage(err)
7558
+ error: errMsg
7559
+ });
7560
+ stats.diffs.push({
7561
+ uid,
7562
+ collectionName: ct.info?.displayName || uid,
7563
+ documentId: docId || `(Row #${rowNumber})`,
7564
+ label: `Row #${rowNumber}`,
7565
+ attribute: "(record)",
7566
+ oldValue: null,
7567
+ newValue: null,
7568
+ status: "error",
7569
+ message: `Failed to process row ${rowNumber}: ${errMsg}`
6886
7570
  });
6887
7571
  }
6888
7572
  }
@@ -6961,133 +7645,183 @@ const csvService = ({ strapi }) => ({
6961
7645
  if (!ct) {
6962
7646
  throw new Error(`Content type ${uid} not found`);
6963
7647
  }
6964
- const attrs = ct.attributes || {};
6965
- const excluded = ["createdAt", "updatedAt", "publishedAt", "createdBy", "updatedBy", "localizations"];
6966
- const headers = ["documentId"];
6967
- const sampleRow = ["(Leave empty to create new, or enter existing docId)"];
6968
- for (const [attrName, attrDef] of Object.entries(attrs)) {
6969
- if (excluded.includes(attrName)) continue;
6970
- if (attrDef.type === "relation") continue;
6971
- if (attrDef.type === "component" || attrDef.type === "dynamiczone") continue;
6972
- headers.push(attrName);
6973
- let sampleVal = "";
6974
- switch (attrDef.type) {
6975
- case "string":
6976
- case "text":
6977
- case "richtext":
6978
- sampleVal = `Sample ${attrName}`;
6979
- break;
6980
- case "integer":
6981
- case "biginteger":
6982
- case "float":
6983
- case "decimal":
6984
- sampleVal = "10";
6985
- break;
6986
- case "boolean":
6987
- sampleVal = "true";
6988
- break;
6989
- case "email":
6990
- sampleVal = "sample@example.com";
6991
- break;
6992
- case "enumeration":
6993
- sampleVal = attrDef.enum?.[0] || "option1";
6994
- break;
6995
- case "customField":
6996
- sampleVal = "value";
6997
- break;
6998
- default:
7648
+ const schema = discoverSchema(strapi, uid);
7649
+ const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
7650
+ const sampleRow = [
7651
+ JSON.stringify({
7652
+ schemaVersion: CURRENT_SCHEMA_VERSION,
7653
+ contentType: uid,
7654
+ documentId: "",
7655
+ locale: schema.isLocalized ? "en" : void 0,
7656
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString()
7657
+ })
7658
+ ];
7659
+ for (const key of schema.allExportKeys) {
7660
+ if (key === "documentId") {
7661
+ sampleRow.push("(Leave empty to create new, or enter existing docId)");
7662
+ } else if (key === "locale") {
7663
+ sampleRow.push("en");
7664
+ } else {
7665
+ const field = schema.fields[key];
7666
+ let sampleVal = "";
7667
+ if (field) {
7668
+ switch (field.category) {
7669
+ case "scalar":
7670
+ sampleVal = field.rawType === "boolean" ? "true" : field.rawType === "integer" ? "10" : `Sample ${key}`;
7671
+ break;
7672
+ case "blocks":
7673
+ sampleVal = JSON.stringify([{ type: "paragraph", children: [{ type: "text", text: `Sample ${key}` }] }]);
7674
+ break;
7675
+ case "component_single":
7676
+ sampleVal = JSON.stringify({ sampleField: "Sample value" });
7677
+ break;
7678
+ case "component_repeatable":
7679
+ sampleVal = JSON.stringify([{ label: "Sample item", url: "/" }]);
7680
+ break;
7681
+ case "dynamiczone":
7682
+ sampleVal = JSON.stringify(
7683
+ field.dzComponents && field.dzComponents.length > 0 ? [{ __component: field.dzComponents[0], title: "Sample" }] : []
7684
+ );
7685
+ break;
7686
+ case "relation_to_one":
7687
+ sampleVal = JSON.stringify({ documentId: "target-doc-id" });
7688
+ break;
7689
+ case "relation_to_many":
7690
+ sampleVal = JSON.stringify([{ documentId: "target-doc-id-1" }]);
7691
+ break;
7692
+ case "media_single":
7693
+ sampleVal = JSON.stringify({ id: 1, url: "/uploads/sample.png" });
7694
+ break;
7695
+ case "media_to_many":
7696
+ sampleVal = JSON.stringify([{ id: 1, url: "/uploads/sample.png" }]);
7697
+ break;
7698
+ default:
7699
+ sampleVal = "sample";
7700
+ }
7701
+ } else {
6999
7702
  sampleVal = "sample";
7703
+ }
7704
+ sampleRow.push(sampleVal);
7000
7705
  }
7001
- sampleRow.push(sampleVal);
7002
7706
  }
7003
- const csvContent = "\uFEFF" + headers.map(escapeCsvValue).join(",") + "\r\n" + sampleRow.map(escapeCsvValue).join(",") + "\r\n";
7707
+ const csvContent = "\uFEFF" + headers.map(escapeCsvCell).join(",") + "\r\n" + sampleRow.map(escapeCsvCell).join(",") + "\r\n";
7004
7708
  return {
7005
7709
  filename: `${ct.info?.singularName || "template"}_template.csv`,
7006
7710
  csvContent,
7007
7711
  headers
7008
7712
  };
7009
7713
  },
7010
- /**
7011
- * Exports entries of a collection to CSV with deep nested component support,
7012
- * RFC-4180 CRLF line endings, and UTF-8 BOM for 100% Microsoft Excel compatibility.
7013
- */
7014
7714
  async exportCollectionCsv(uid, options = {}) {
7015
7715
  const ct = strapi.contentTypes[uid];
7016
7716
  if (!ct) {
7017
7717
  throw new Error(`Content type ${uid} not found`);
7018
7718
  }
7019
- const allComponents = strapi.components || {};
7020
- const fields = discoverExportFields(ct, allComponents);
7021
- const filters = {};
7022
- const { attribute, filterOperator, filterQuery, search, documentIds } = options;
7023
- if (documentIds && Array.isArray(documentIds) && documentIds.length > 0) {
7024
- filters.documentId = { $in: documentIds };
7025
- }
7026
- if (attribute && filterOperator && filterOperator !== "none") {
7027
- const isNested = attribute.includes(".");
7028
- if (filterOperator === "empty") {
7029
- if (isNested) {
7030
- const [parent, child] = attribute.split(".");
7031
- filters[parent] = { [child]: { $null: true } };
7032
- } else {
7033
- filters[attribute] = { $null: true };
7034
- }
7035
- } else if (filterOperator === "not_empty") {
7036
- if (isNested) {
7037
- const [parent, child] = attribute.split(".");
7038
- filters[parent] = { [child]: { $notNull: true } };
7039
- } else {
7040
- filters[attribute] = { $notNull: true };
7041
- }
7042
- } else if (filterQuery !== void 0 && filterQuery !== "") {
7043
- const opMap = {
7044
- equals: "$eq",
7045
- notEquals: "$ne",
7046
- contains: "$containsi",
7047
- notContains: "$notContainsi",
7048
- startsWith: "$startsWith",
7049
- endsWith: "$endsWith"
7050
- };
7051
- const strapiOp = opMap[filterOperator] || "$eq";
7052
- if (isNested) {
7053
- const [parent, child] = attribute.split(".");
7054
- filters[parent] = { [child]: { [strapiOp]: filterQuery } };
7055
- } else {
7056
- filters[attribute] = { [strapiOp]: filterQuery };
7057
- }
7058
- }
7719
+ const schema = discoverSchema(strapi, uid);
7720
+ const deepPopulate = buildLosslessPopulate(strapi, uid);
7721
+ const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
7722
+ const lines = [];
7723
+ lines.push(headers.map(escapeCsvCell).join(","));
7724
+ const filterMeta = buildCollectionQueryFilters(strapi, ct, {
7725
+ attribute: options.attribute,
7726
+ searchAttribute: options.searchAttribute || options.attribute,
7727
+ filterOperator: options.filterOperator,
7728
+ filterQuery: options.filterQuery,
7729
+ search: options.search,
7730
+ documentIds: options.documentIds
7731
+ });
7732
+ if (!filterMeta.colHasAttribute && filterMeta.normOp && filterMeta.normOp !== "none") {
7733
+ return {
7734
+ filename: `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`,
7735
+ csvContent: "\uFEFF" + lines.join("\r\n") + "\r\n",
7736
+ count: 0,
7737
+ fields: headers
7738
+ };
7059
7739
  }
7060
- if (search && search.trim() !== "") {
7061
- const q = search.trim();
7062
- const searchConditions = [];
7063
- const searchFields = ["name", "title", "email", "slug", "description"].filter(
7064
- (f) => ct.attributes?.[f] && ["string", "text", "email"].includes(ct.attributes[f].type)
7065
- );
7066
- for (const field of searchFields) {
7067
- searchConditions.push({ [field]: { $containsi: q } });
7740
+ const filters = filterMeta.filters;
7741
+ const isRootDz = filterMeta.isRootDz;
7742
+ const normOp = filterMeta.normOp;
7743
+ const targetFilterAttr = filterMeta.targetFilterAttr;
7744
+ const passesDzFilter = (entry) => {
7745
+ if (!isRootDz || !normOp || normOp === "none") return true;
7746
+ const matches = getAllNestedValues(entry, targetFilterAttr);
7747
+ if (normOp === "empty") {
7748
+ return matches.length === 0 || matches.every((m) => {
7749
+ const v = m.value;
7750
+ if (v === void 0 || v === null) return true;
7751
+ if (Array.isArray(v)) return v.length === 0;
7752
+ if (typeof v === "object") return Object.keys(v).length === 0;
7753
+ return String(v).trim() === "";
7754
+ });
7068
7755
  }
7069
- if (searchConditions.length > 0) {
7070
- if (filters && Object.keys(filters).length > 0) {
7071
- filters.$and = [{ $or: searchConditions }];
7072
- } else {
7073
- filters.$or = searchConditions;
7074
- }
7756
+ if (normOp === "notempty") {
7757
+ return matches.some((m) => {
7758
+ const v = m.value;
7759
+ if (v === void 0 || v === null) return false;
7760
+ if (Array.isArray(v)) return v.length > 0;
7761
+ if (typeof v === "object") return Object.keys(v).length > 0;
7762
+ return String(v).trim() !== "";
7763
+ });
7075
7764
  }
7076
- }
7077
- const deepPopulate = buildDeepPopulate(ct.attributes || {}, allComponents);
7078
- const lines = [];
7079
- lines.push(fields.map((f) => escapeCsvValue(f.key)).join(","));
7765
+ const qVal = (filterMeta.filterQuery || "").trim().toLowerCase();
7766
+ const testSingleValue = (v) => {
7767
+ if (v === void 0 || v === null) return false;
7768
+ if (Array.isArray(v)) return v.some(testSingleValue);
7769
+ if (typeof v === "object") {
7770
+ return testSingleValue(v.name) || testSingleValue(v.title) || testSingleValue(v.email) || testSingleValue(v.username) || testSingleValue(v.documentId) || testSingleValue(v.id) || testSingleValue(v.slug);
7771
+ }
7772
+ const valStr = String(v).trim().toLowerCase();
7773
+ switch (normOp) {
7774
+ case "equals":
7775
+ return valStr === qVal;
7776
+ case "notequals":
7777
+ return valStr !== qVal;
7778
+ case "contains":
7779
+ return valStr.includes(qVal);
7780
+ case "notcontains":
7781
+ return !valStr.includes(qVal);
7782
+ case "startswith":
7783
+ return valStr.startsWith(qVal);
7784
+ case "endswith":
7785
+ return valStr.endsWith(qVal);
7786
+ default:
7787
+ return valStr.includes(qVal);
7788
+ }
7789
+ };
7790
+ return matches.some((m) => testSingleValue(m.value));
7791
+ };
7080
7792
  let totalExported = 0;
7081
7793
  const maxLimit = options.limit && options.limit > 0 ? options.limit : Infinity;
7082
7794
  const BATCH_SIZE = 200;
7795
+ const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
7083
7796
  if (ct.kind === "singleType") {
7084
- const findFirstArgs = {};
7797
+ const findFirstArgs = {
7798
+ filters: Object.keys(filters).length > 0 ? filters : void 0
7799
+ };
7085
7800
  if (deepPopulate) {
7086
7801
  findFirstArgs.populate = deepPopulate;
7087
7802
  }
7088
7803
  const doc = await strapi.documents(uid).findFirst(findFirstArgs);
7089
- if (doc) {
7090
- const rowValues = fields.map((f) => escapeCsvValue(getNestedExportValue(doc, f.key)));
7804
+ if (doc && passesDzFilter(doc)) {
7805
+ const rowValues = [];
7806
+ const metadata = {
7807
+ schemaVersion: CURRENT_SCHEMA_VERSION,
7808
+ contentType: uid,
7809
+ documentId: String(doc.documentId || doc.id || ""),
7810
+ locale: doc.locale || void 0,
7811
+ exportedAt
7812
+ };
7813
+ rowValues.push(escapeCsvCell(metadata));
7814
+ for (const key of schema.allExportKeys) {
7815
+ if (key === "documentId") {
7816
+ rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
7817
+ } else if (key === "locale") {
7818
+ rowValues.push(escapeCsvCell(doc.locale || ""));
7819
+ } else {
7820
+ const field = schema.fields[key];
7821
+ const rawVal = doc[key];
7822
+ rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
7823
+ }
7824
+ }
7091
7825
  lines.push(rowValues.join(","));
7092
7826
  totalExported = 1;
7093
7827
  }
@@ -7115,7 +7849,29 @@ const csvService = ({ strapi }) => ({
7115
7849
  break;
7116
7850
  }
7117
7851
  for (const entry of chunkEntries) {
7118
- const rowValues = fields.map((f) => escapeCsvValue(getNestedExportValue(entry, f.key)));
7852
+ if (!passesDzFilter(entry)) {
7853
+ continue;
7854
+ }
7855
+ const rowValues = [];
7856
+ const metadata = {
7857
+ schemaVersion: CURRENT_SCHEMA_VERSION,
7858
+ contentType: uid,
7859
+ documentId: String(entry.documentId || entry.id || ""),
7860
+ locale: entry.locale || void 0,
7861
+ exportedAt
7862
+ };
7863
+ rowValues.push(escapeCsvCell(metadata));
7864
+ for (const key of schema.allExportKeys) {
7865
+ if (key === "documentId") {
7866
+ rowValues.push(escapeCsvCell(entry.documentId || entry.id || ""));
7867
+ } else if (key === "locale") {
7868
+ rowValues.push(escapeCsvCell(entry.locale || ""));
7869
+ } else {
7870
+ const field = schema.fields[key];
7871
+ const rawVal = entry[key];
7872
+ rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
7873
+ }
7874
+ }
7119
7875
  lines.push(rowValues.join(","));
7120
7876
  totalExported++;
7121
7877
  if (totalExported >= maxLimit) {
@@ -7137,12 +7893,9 @@ const csvService = ({ strapi }) => ({
7137
7893
  filename,
7138
7894
  csvContent,
7139
7895
  count: totalExported,
7140
- fields: fields.map((f) => f.key)
7896
+ fields: headers
7141
7897
  };
7142
7898
  },
7143
- /**
7144
- * Exports violations of a specific rule directly into a CSV
7145
- */
7146
7899
  async exportViolationsCsv(ruleId) {
7147
7900
  const validationRulesService2 = strapi.plugin("bulk-updater").service("validationRules");
7148
7901
  const scanReport = await validationRulesService2.scanViolations(ruleId);
@@ -7618,7 +8371,18 @@ const csvService = ({ strapi }) => ({
7618
8371
  }
7619
8372
  }
7620
8373
  if (activeRules.length > 0) {
7621
- const proposedEntity = existing ? deepMergeEntities(existing, payload) : payload;
8374
+ let proposedPayload = {};
8375
+ try {
8376
+ proposedPayload = await buildDocumentUpdatePayload(
8377
+ strapi,
8378
+ uid,
8379
+ existing,
8380
+ row,
8381
+ { isPartialUpdate: mode === "update" }
8382
+ );
8383
+ } catch {
8384
+ }
8385
+ const proposedEntity = existing ? deepMergeEntities(existing, proposedPayload) : proposedPayload;
7622
8386
  const valResult = await validateEntityQuotas(strapi, uid, proposedEntity, activeRules);
7623
8387
  if (!valResult.isValid) {
7624
8388
  errors.push({
@@ -7704,12 +8468,18 @@ const csvService = ({ strapi }) => ({
7704
8468
  });
7705
8469
  continue;
7706
8470
  }
7707
- const payload2 = parseRowToPayload(strapi, attrs, row);
8471
+ const payload = await buildDocumentUpdatePayload(
8472
+ strapi,
8473
+ uid,
8474
+ existing,
8475
+ row,
8476
+ {}
8477
+ );
7708
8478
  if (existing) {
7709
8479
  const resolvedDocId = existing.documentId || docId;
7710
8480
  const entryLabel = existing.title || existing.name || existing.slug || `Entry #${resolvedDocId}`;
7711
8481
  let rowHasChanges = false;
7712
- const payloadKeys = Object.keys(payload2);
8482
+ const payloadKeys = Object.keys(payload);
7713
8483
  if (payloadKeys.length === 0) {
7714
8484
  unchangedCount++;
7715
8485
  diffs.push({
@@ -7730,7 +8500,7 @@ const csvService = ({ strapi }) => ({
7730
8500
  } else {
7731
8501
  for (const attrKey of payloadKeys) {
7732
8502
  const oldVal = existing?.[attrKey] ?? null;
7733
- let newVal = payload2[attrKey];
8503
+ let newVal = payload[attrKey];
7734
8504
  if (attrs[attrKey]?.type === "component" && typeof newVal === "object" && newVal !== null) {
7735
8505
  newVal = deepMergeComponent(existing[attrKey], newVal);
7736
8506
  }
@@ -7765,8 +8535,8 @@ const csvService = ({ strapi }) => ({
7765
8535
  } else {
7766
8536
  willCreateCount++;
7767
8537
  const resolvedDocId = docId || `(Auto-generated)`;
7768
- const entryLabel = payload2.title || payload2.name || payload2.slug || `New Entry (Row #${rowNumber})`;
7769
- const payloadKeys = Object.keys(payload2);
8538
+ const entryLabel = payload.title || payload.name || payload.slug || `New Entry (Row #${rowNumber})`;
8539
+ const payloadKeys = Object.keys(payload);
7770
8540
  if (payloadKeys.length === 0) {
7771
8541
  diffs.push({
7772
8542
  uid,
@@ -7785,7 +8555,7 @@ const csvService = ({ strapi }) => ({
7785
8555
  });
7786
8556
  } else {
7787
8557
  for (const attrKey of payloadKeys) {
7788
- const newVal = payload2[attrKey];
8558
+ const newVal = payload[attrKey];
7789
8559
  diffs.push({
7790
8560
  uid,
7791
8561
  collectionName: ct.info?.displayName || uid,
@@ -8139,7 +8909,7 @@ const index = {
8139
8909
  if (context.uid && docId) {
8140
8910
  try {
8141
8911
  const ct = strapi.contentTypes[context.uid];
8142
- const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
8912
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
8143
8913
  const existing = await strapi.documents(context.uid).findOne({
8144
8914
  documentId: docId,
8145
8915
  ...params?.locale ? { locale: params.locale } : {},
@@ -8282,5 +9052,34 @@ const index = {
8282
9052
  contentHistory: contentHistoryService
8283
9053
  }
8284
9054
  };
8285
- module.exports = index;
9055
+ exports.CURRENT_SCHEMA_VERSION = CURRENT_SCHEMA_VERSION;
9056
+ exports.METADATA_COLUMN_KEY = METADATA_COLUMN_KEY;
9057
+ exports.SYSTEM_ATTRIBUTES = SYSTEM_ATTRIBUTES;
9058
+ exports.buildCollectionQueryFilters = buildCollectionQueryFilters;
9059
+ exports.buildDocumentUpdatePayload = buildDocumentUpdatePayload;
9060
+ exports.buildLosslessPopulate = buildLosslessPopulate;
9061
+ exports.classifyAttribute = classifyAttribute;
9062
+ exports.deepMergeEntities = deepMergeEntities;
9063
+ exports.default = index;
9064
+ exports.discoverComponentFields = discoverComponentFields;
9065
+ exports.discoverSchema = discoverSchema;
9066
+ exports.escapeCsvCell = escapeCsvCell;
9067
+ exports.extractHeadingsFromRichText = extractHeadingsFromRichText;
9068
+ exports.extractMetadataFromRow = extractMetadataFromRow;
9069
+ exports.getAllNestedValues = getAllNestedValues;
9070
+ exports.isValidDocumentId = isValidDocumentId;
9071
+ exports.parseBoolean = parseBoolean;
9072
+ exports.parseCsvToMatrix = parseCsvToMatrix;
9073
+ exports.parseCsvToRecords = parseCsvToRecords;
9074
+ exports.parseNumeric = parseNumeric;
9075
+ exports.resolveComponentPayload = resolveComponentPayload;
9076
+ exports.resolveDynamicZonePayload = resolveDynamicZonePayload;
9077
+ exports.resolveMediaIds = resolveMediaIds;
9078
+ exports.resolveRelationPayload = resolveRelationPayload;
9079
+ exports.serializeDocumentsToCsv = serializeDocumentsToCsv;
9080
+ exports.serializeFieldValue = serializeFieldValue;
9081
+ exports.sortAuditRecordsDesc = sortAuditRecordsDesc;
9082
+ exports.validateEntityQuotas = validateEntityQuotas;
9083
+ exports.verifyDocumentIntegrity = verifyDocumentIntegrity;
9084
+ exports.withRollbackLock = withRollbackLock;
8286
9085
  //# sourceMappingURL=index.js.map