All files / utils packUpgrade.js

98.85% Statements 259/262
95.18% Branches 178/187
100% Functions 70/70
99.54% Lines 217/218

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579                                  3x 3x 3x 3x 3x 3x               3x             3x     3x 3x   37x 66x     33x 33x 238x 33x   33x 36x 36x 36x 36x   33x   32x                 37x     35x 35x 33x 32x 37x         3x       82x 8x 8x                     10x 10x 5x 10x 1x     10x 10x 10x 1x   10x 10x     10x 1x   10x 40x 10x     1x   10x                           51x 51x 115x 51x 51x 51x 51x   51x 130x 130x 83x 1x             1x   82x 82x 82x   26x 26x 25x 25x 15x 15x   10x 10x 6x     51x 102x   102x 60x 10x 10x 10x 2x   8x       130x 51x 102x 16x     51x                         51x 274x 51x 51x 51x 161x 161x   51x 115x 115x 115x     51x 46x     51x 51x 46x 46x 46x 46x 12x           29x       46x   51x                                                   50x 119x   50x 119x 50x 63x 5x   50x 52x 52x 52x     52x               52x 1x                           51x 115x 51x 130x 51x 130x   51x 102x   51x                           63x   50x     112x     50x 52x                               64x   20x     64x 64x 84x   64x 64x 146x 146x   64x                 6x     6x         5x                 1x                   6x                       81x 12x 12x 12x   12x               30x 30x   60x                 5x 4x 4x   7x   4x                         34x 32x 32x 38x 38x 34x 34x 37x   26x   34x 7x   34x   7x     34x 34x 4x 4x 34x 5x   34x   32x 32x 32x                     16x 16x       16x       16x   13x         34x 3x 3x 6x 4x   6x 4x   4x   3x                 17x 18x 17x     14x         2x     2x     17x 11x 10x         17x     3x                        
/**
 * Upgrading a flow's copies of a pack to its current version (UC-STORE-013.1).
 * See docs/architecture/ENTITY_STORE.md "Upgrades".
 *
 * A copy is matched to the version's entity by `packOrigin.entityKey`, and a
 * field by its `fieldId`, which installing keeps. What the version adds is
 * offered: fields the copy lacks and never got (a field the installer removed
 * from the copy is in `packOrigin.fieldIds`, and not offered again), and the
 * version's entities the flow has no copy of. What it changed is compared
 * three ways with the copy's baseline: what only Alice changed is offered,
 * the rest listed (compareWithVersion). An added field may take another name,
 * or the copy's field the version removed may be renamed, so that field names
 * stay unique per language (UC-ENTITY-029.1).
 *
 * @implements UC-STORE-013.1
 */
 
const { BatchGetCommand, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { normalizeName } = require('./nameUniqueness')
const { extractOptionValues, findRemovedWorkflowStates } = require('./entityFieldCascadeValidation')
const { diffUniqueFieldChanges } = require('./uniqueFieldValue')
const { diffEqualityIndexFieldChanges } = require('./equalityIndexValue')
const { definitionHash, sectionHash, differingProperties } = require('./packBaseline')
const {
  normalizeFieldName,
  namesByLanguage,
  nameIn,
  withNameIn,
  freeName,
  findFieldNameCollision
} = require('./fieldNameUniqueness')
 
/**
 * How many copies of one pack a flow's upgrade reads, at most: installing
 * again adds copies to the flow's row, 20 at a time at most. Past that, the
 * copies with the lowest ids are the ones considered.
 */
const MAX_PACK_COPIES = 100
 
/** DynamoDB BatchGetItem accepts at most 100 keys per request. */
const BATCH_GET_LIMIT = 100
const BATCH_GET_MAX_ATTEMPTS = 3
 
const importsTable = () => process.env.PACK_IMPORTS_TABLE_NAME
const entitiesTable = () => process.env.TABLE_NAME
 
async function batchGetEntities(docClient, ids) {
  const found = []
  for (let offset = 0; offset < ids.length; offset += BATCH_GET_LIMIT) {
    const keys = ids.slice(offset, offset + BATCH_GET_LIMIT).map((id) => ({ id }))
    let requestItems = { [entitiesTable()]: { Keys: keys } }
    // Entities can be large: a response over 16 MB leaves keys unprocessed
    for (let attempt = 0; attempt < BATCH_GET_MAX_ATTEMPTS && requestItems; attempt++) {
      const result = await docClient.send(new BatchGetCommand({ RequestItems: requestItems }))
      found.push(...(result.Responses?.[entitiesTable()] || []))
      const unprocessed = result.UnprocessedKeys
      requestItems = unprocessed && Object.keys(unprocessed).length > 0 ? unprocessed : null
    }
    if (requestItems) throw new Error('Could not read the copies of the pack')
  }
  return found
}
 
/**
 * The flow's copies of the pack: the entities its `PackImportsTable` row
 * remembers, still in the flow and still from the pack. A copy deleted since
 * is simply not found. One Get, and BatchGets bounded by `MAX_PACK_COPIES`.
 */
async function loadPackCopies(docClient, packId, flowId) {
  const row = await docClient.send(
    new GetCommand({ TableName: importsTable(), Key: { packId, flowId }, ConsistentRead: true })
  )
  const ids = [...(row.Item?.copyEntityIds || [])].sort().slice(0, MAX_PACK_COPIES)
  if (ids.length === 0) return []
  const entities = await batchGetEntities(docClient, ids)
  return entities.filter(
    (entity) => entity.flowId === flowId && entity.packOrigin?.packId === packId
  )
}
 
/** The sections of an entity compared as a whole, like a field. */
const SECTIONS = ['forms', 'emailTemplates']
 
/** The field, its link to one of the pack's entities pointing at the flow's copy of it. */
function remapReference(field, targets) {
  if (field.type !== 'entity_ref' || !field.reference?.entityId) return field
  const target = targets.get(field.reference.entityId)
  return target ? { ...field, reference: { ...field.reference, entityId: target } } : field
}
 
/**
 * Why a change Alice made cannot be applied for Bob, who is to make it by
 * hand: what an edit would do to his items (an option or a state removed, a
 * field made unique or no longer, an equality index gained or lost), a link to
 * one of the version's entities he has no copy of, or a name another of his
 * fields has.
 */
function manualReasons(mine, next, copy, tempIds) {
  const reasons = []
  if (['select', 'multiselect'].includes(mine.type)) {
    const kept = new Set(extractOptionValues(next.options))
    if (extractOptionValues(mine.options).some((value) => !kept.has(value))) {
      reasons.push('optionsRemoved')
    }
  }
  Iif (findRemovedWorkflowStates([mine], [next]).length > 0) reasons.push('statesRemoved')
  const unique = diffUniqueFieldChanges([mine], [next])
  if (unique.newlyUniqueFields.length > 0 || unique.noLongerUniqueFieldIds.length > 0) {
    reasons.push('unique')
  }
  const index = diffEqualityIndexFieldChanges([mine], [next])
  Iif (index.newlyEligibleFields.length > 0 || index.noLongerEligibleFieldIds.length > 0) {
    reasons.push('index')
  }
  if (next.type === 'entity_ref' && tempIds.has(next.reference?.entityId)) {
    reasons.push('reference')
  }
  const fields = copy.fields || []
  const after = fields.map((field) => (field.fieldId === next.fieldId ? next : field))
  if (
    findFieldNameCollision(after, { previousFields: fields, defaultLanguage: copy.defaultLanguage })
  ) {
    reasons.push('nameTaken')
  }
  return reasons
}
 
/**
 * The three-way comparison of a copy with the version, field by field and
 * section by section, against the copy's baseline (utils/packBaseline.js):
 * - what Alice did not change is left alone, whatever Bob did;
 * - what only Alice changed is offered (`changedFields`, `changedSections`),
 *   unless it would touch Bob's items, which is listed for him to do (`manual`);
 * - what both changed is listed as a `conflict`, never applied.
 * A copy without a baseline counts every difference as a conflict. Retyped
 * and removed fields are listed, never applied.
 */
function compareWithVersion(copy, packEntity, targets, tempIds) {
  const baseline = copy.packOrigin.baseline
  const copyFields = copy.fields || []
  const own = new Map(copyFields.map((field) => [field.fieldId, field]))
  const packFields = packEntity.fields || []
  const changedFields = []
  const changedSections = []
  const otherChanges = []
 
  for (const field of packFields) {
    const mine = own.get(field.fieldId)
    if (!mine) continue
    if (mine.type !== field.type) {
      otherChanges.push({
        change: 'retyped',
        fieldId: field.fieldId,
        name: mine.name,
        type: mine.type,
        packType: field.type
      })
      continue
    }
    const next = remapReference(field, targets)
    const properties = differingProperties(mine, next)
    if (properties.length === 0) continue
 
    const base = baseline?.fields?.[field.fieldId]
    if (base && definitionHash(field) === base.pack) continue
    const change = { fieldId: field.fieldId, name: mine.name, properties }
    if (!base || definitionHash(mine) !== base.copy) {
      otherChanges.push({ change: 'conflict', ...change })
      continue
    }
    const reasons = manualReasons(mine, next, copy, tempIds)
    if (reasons.length > 0) otherChanges.push({ change: 'manual', ...change, reasons })
    else changedFields.push({ ...change, packName: field.name, field: next })
  }
 
  for (const section of SECTIONS) {
    const theirs = packEntity[section]
    // A version without forms leaves the copy's own, generated or not
    if (section === 'forms' && sectionHash(theirs) === sectionHash(null)) continue
    if (sectionHash(theirs) === sectionHash(copy[section])) continue
    const base = baseline?.[section]
    Iif (base && sectionHash(theirs) === base.pack) continue
    if (!base || sectionHash(copy[section]) !== base.copy) {
      otherChanges.push({ change: 'conflict', section })
    } else {
      changedSections.push(section)
    }
  }
 
  const inPack = new Set(packFields.map((field) => field.fieldId))
  for (const fieldId of copy.packOrigin.fieldIds || []) {
    if (!inPack.has(fieldId) && own.has(fieldId)) {
      otherChanges.push({ change: 'removed', fieldId, name: own.get(fieldId).name })
    }
  }
  return { changedFields, changedSections, otherChanges }
}
 
/**
 * The added fields whose name a field of the copy already has, in one of its
 * languages (field names are unique per language, UC-ENTITY-029.1): for each,
 * the language, the copy's field holding the name, whether the version
 * removed that one (it can then be renamed instead), and a free name to
 * suggest, "Price (2)".
 *
 * @returns {Record<string, Array<{ language: string, fieldId: string, fieldName: string, removed: boolean, suggestedName: string }>>}
 */
function addedFieldConflicts(copy, addedFields, removedFieldIds) {
  const language = copy.defaultLanguage
  const key = (lang, name) => `${lang}\u0000${name}`
  const holders = new Map()
  const taken = new Map()
  const take = (lang, name) => {
    if (!taken.has(lang)) taken.set(lang, new Set())
    taken.get(lang).add(name)
  }
  for (const field of copy.fields || []) {
    for (const [lang, name] of namesByLanguage(field, language)) {
      if (!holders.has(key(lang, name))) holders.set(key(lang, name), field)
      take(lang, name)
    }
  }
  for (const field of addedFields) {
    for (const [lang, name] of namesByLanguage(field, language)) take(lang, name)
  }
 
  const conflicts = {}
  for (const field of addedFields) {
    const found = []
    for (const [lang, name] of namesByLanguage(field, language)) {
      const holder = holders.get(key(lang, name))
      if (!holder) continue
      found.push({
        language: lang,
        fieldId: holder.fieldId,
        fieldName: nameIn(holder.name, lang, language),
        removed: removedFieldIds.includes(holder.fieldId),
        suggestedName: freeName(nameIn(field.name, lang, language), (candidate) =>
          taken.get(lang).has(normalizeFieldName(candidate))
        )
      })
    }
    if (found.length > 0) conflicts[field.fieldId] = found
  }
  return conflicts
}
 
/**
 * What upgrading the copies to `version` offers. Only copies installed from an
 * earlier version are upgraded; new entities are offered with them.
 *
 * @param {{ entities: Array<{ tempId: string, packEntityKey?: string, entity: object }> }} bundle
 * @param {Array<object>} copies from `loadPackCopies`
 * @param {number} version the pack's current version, the bundle's
 * @returns {{
 *   fromVersion: number | null,
 *   toVersion: number,
 *   copies: Array<{
 *     entityId: string, name: unknown, version: number, tempId: string | null,
 *     addedFields: Array<object>, otherChanges: Array<object>,
 *     changedFields: Array<{ fieldId: string, name: unknown, packName: unknown, properties: string[], field: object }>,
 *     changedSections: string[], noBaseline: boolean,
 *     nameConflicts: Record<string, Array<object>>, removedFieldIds: string[],
 *     fields: Array<object>, forms?: Array<object>, emailTemplates?: Array<object>,
 *     defaultLanguage?: string, baseline?: object, packEntity?: object
 *   }>,
 *   newEntities: Array<{ tempId: string, entity: object }>
 * }}
 */
function planUpgrade(bundle, copies, version) {
  const byKey = new Map(
    bundle.entities.filter((entry) => entry.packEntityKey).map((e) => [e.packEntityKey, e])
  )
  const targets = copyTargets(bundle, copies)
  const tempIds = new Set(bundle.entities.map((entry) => entry.tempId))
  const behind = copies
    .filter((copy) => copy.packOrigin.version < version)
    .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))
 
  const planned = behind.map((copy) => {
    const source = byKey.get(copy.packOrigin.entityKey)
    const copyFields = copy.fields || []
    const gotFieldIds = copy.packOrigin.fieldIds || []
    // An entity the version no longer has: nothing to add
    // The copy as it is, for applying the upgrade: never in the preview
    const current = {
      fields: copyFields,
      forms: copy.forms,
      emailTemplates: copy.emailTemplates,
      defaultLanguage: copy.defaultLanguage,
      baseline: copy.packOrigin.baseline,
      noBaseline: !copy.packOrigin.baseline
    }
    if (!source) {
      return {
        entityId: copy.id,
        name: copy.name,
        version: copy.packOrigin.version,
        tempId: null,
        addedFields: [],
        otherChanges: [{ change: 'entityRemoved' }],
        changedFields: [],
        changedSections: [],
        nameConflicts: {},
        removedFieldIds: [],
        ...current
      }
    }
    const packFields = source.entity.fields || []
    const own = new Set(copyFields.map((field) => field.fieldId))
    const got = new Set(gotFieldIds)
    const inPack = new Set(packFields.map((field) => field.fieldId))
    const addedFields = packFields.filter(
      (field) => !own.has(field.fieldId) && !got.has(field.fieldId)
    )
    const removedFieldIds = gotFieldIds.filter(
      (fieldId) => !inPack.has(fieldId) && own.has(fieldId)
    )
    return {
      entityId: copy.id,
      name: copy.name,
      version: copy.packOrigin.version,
      tempId: source.tempId,
      addedFields,
      ...compareWithVersion(copy, source.entity, targets, tempIds),
      nameConflicts: addedFieldConflicts(copy, addedFields, removedFieldIds),
      removedFieldIds,
      packEntity: source.entity,
      ...current
    }
  })
 
  const copiedKeys = new Set(copies.map((copy) => copy.packOrigin.entityKey))
  const newEntities =
    planned.length === 0
      ? []
      : bundle.entities.filter(
          (entry) => entry.packEntityKey && !copiedKeys.has(entry.packEntityKey)
        )
 
  return {
    fromVersion: planned.length > 0 ? Math.min(...planned.map((copy) => copy.version)) : null,
    toVersion: version,
    copies: planned,
    newEntities
  }
}
 
/**
 * Which of the flow's entities stands for each entity of the version: a
 * field the upgrade adds, or a new entity, pointing at one of the pack's
 * entities points at the flow's copy of it. With several copies of one
 * entity, the most recently upgraded, then the most recently created.
 *
 * @returns {Map<string, string>} tempId -> entity id
 */
function copyTargets(bundle, copies) {
  const ranked = [...copies].sort(
    (a, b) =>
      b.packOrigin.version - a.packOrigin.version ||
      String(b.createdAt).localeCompare(String(a.createdAt))
  )
  const byKey = new Map()
  for (const copy of ranked) {
    if (!byKey.has(copy.packOrigin.entityKey)) byKey.set(copy.packOrigin.entityKey, copy.id)
  }
  const targets = new Map()
  for (const entry of bundle.entities) {
    const target = entry.packEntityKey && byKey.get(entry.packEntityKey)
    if (target) targets.set(entry.tempId, target)
  }
  return targets
}
 
/**
 * The preview's public shape: names and types, never the version's internals.
 * `takenEntityNames` holds the flow's entity names, normalized: a new entity
 * whose name is among them needs another one.
 */
function toUpgradePreview(plan, { canUpdate, canCreate, takenEntityNames = new Set() }) {
  return {
    fromVersion: plan.fromVersion,
    toVersion: plan.toVersion,
    copies: plan.copies.map((copy) => ({
      entityId: copy.entityId,
      name: copy.name,
      version: copy.version,
      canUpdate: canUpdate.get(copy.entityId) === true,
      addedFields: copy.addedFields.map((field) => ({
        fieldId: field.fieldId,
        name: field.name,
        type: field.type,
        mandatory: field.mandatory === true,
        ...(copy.nameConflicts[field.fieldId] && {
          nameConflicts: copy.nameConflicts[field.fieldId]
        })
      })),
      changedFields: copy.changedFields.map(({ fieldId, name, packName, properties }) => ({
        fieldId,
        name,
        packName,
        properties
      })),
      changedSections: copy.changedSections,
      ...(copy.noBaseline && { noBaseline: true }),
      otherChanges: copy.otherChanges
    })),
    newEntities: plan.newEntities.map(({ tempId, entity }) => ({
      tempId,
      name: entity.name,
      fieldCount: (entity.fields || []).length,
      ...(takenEntityNames.has(normalizeName(entity.name)) && { nameTaken: true })
    })),
    canCreate
  }
}
 
/** The field with the names given, by language, the others kept. */
function withFieldNames(field, names, defaultLanguage) {
  if (!names) return field
  let name = field.name
  for (const [language, value] of Object.entries(names)) {
    name = withNameIn(name, language, value, defaultLanguage)
  }
  return { ...field, name }
}
 
/**
 * The copy's own fields after the upgrade, as an edit would leave them: the
 * renames chosen, then the version's definition of each field changed.
 */
function ownFieldsAfter(fields, { renames, changes }, defaultLanguage) {
  const changed = new Map((changes || []).map((field) => [field.fieldId, field]))
  return (fields || []).map(
    (field) =>
      changed.get(field.fieldId) ?? withFieldNames(field, renames?.[field.fieldId], defaultLanguage)
  )
}
 
/**
 * The version's forms for the copy: only the fields it has, a form left
 * without any dropped (utils/resolveEntityForms.js then completes them).
 */
function formsForCopy(forms, fields) {
  const fieldIds = new Set((fields || []).map((field) => field.fieldId))
  return (Array.isArray(forms) ? forms : [])
    .map((form) => ({
      ...form,
      fields: (form.fields || []).filter((entry) => fieldIds.has(entry.fieldId))
    }))
    .filter((form) => form.fields.length > 0)
}
 
/**
 * Keeps, of what the caller chose, only what the plan offers: a copy it
 * upgrades with the fields it adds, under the names chosen, and the new
 * entities. Only a field the version removed may be renamed. Client input
 * never adds anything else.
 *
 * @param {object} plan from `planUpgrade`
 * @param {{ copies: Array<{ entityId: string, fieldIds: string[], fieldNames?: object, renames?: object }>, entities: Array<{ tempId: string, name?: unknown }> }} chosen
 */
function selectUpgrade(plan, chosen) {
  const planned = new Map(plan.copies.map((copy) => [copy.entityId, copy]))
  const copies = []
  for (const choice of chosen.copies) {
    const copy = planned.get(choice.entityId)
    if (!copy) continue
    const wanted = new Set(choice.fieldIds)
    const fields = copy.addedFields
      .filter((field) => wanted.has(field.fieldId))
      .map((field) =>
        withFieldNames(field, choice.fieldNames?.[field.fieldId], copy.defaultLanguage)
      )
    const fieldNames = Object.fromEntries(
      Object.entries(choice.fieldNames || {}).filter(([fieldId]) => wanted.has(fieldId))
    )
    const renames = Object.fromEntries(
      Object.entries(choice.renames || {}).filter(([fieldId]) =>
        copy.removedFieldIds.includes(fieldId)
      )
    )
    const changedFieldIds = new Set(choice.changedFieldIds || [])
    const changes = copy.changedFields
      .filter((change) => changedFieldIds.has(change.fieldId))
      .map((change) => change.field)
    const sections = copy.changedSections.filter((section) =>
      (choice.sections || []).includes(section)
    )
    copies.push({ copy, fields, fieldNames, renames, changes, sections })
  }
  const offered = new Set(plan.newEntities.map((entry) => entry.tempId))
  const entities = chosen.entities.filter((choice) => offered.has(choice.tempId))
  return { copies, entities }
}
 
/**
 * The first copy whose fields, as the upgrade would leave them, have two
 * fields of one name in a language that the upgrade brings: an added field,
 * or a renamed one. The copy's own duplicates are not counted.
 *
 * @returns {{ entityId: string, fieldId: string, language: string } | null}
 */
function findUpgradeNameCollision(selection) {
  for (const { copy, fields, renames, changes } of selection.copies) {
    const next = [
      ...ownFieldsAfter(copy.fields, { renames, changes }, copy.defaultLanguage),
      ...fields
    ]
    const collision = findFieldNameCollision(next, {
      previousFields: copy.fields,
      defaultLanguage: copy.defaultLanguage
    })
    if (collision) return { entityId: copy.entityId, ...collision }
  }
  return null
}
 
/** `{ [fieldId]: { [language]: name } }` from the request, names trimmed and non-empty. */
function parseNames(value) {
  if (!value || typeof value !== 'object' || Array.isArray(value)) return {}
  const parsed = {}
  for (const [fieldId, names] of Object.entries(value)) {
    if (!names || typeof names !== 'object' || Array.isArray(names)) continue
    const kept = Object.fromEntries(
      Object.entries(names)
        .filter(([, name]) => typeof name === 'string' && name.trim())
        .map(([language, name]) => [language, name.trim()])
    )
    Eif (Object.keys(kept).length > 0) parsed[fieldId] = kept
  }
  return parsed
}
 
/**
 * Parses the request's choices, dropping anything malformed.
 *
 * @returns {{ copies: Array<{ entityId: string, fieldIds: string[], fieldNames: object, renames: object }>, entities: Array<{ tempId: string, name?: unknown }> }}
 */
function parseUpgradeChoices(payload) {
  const copies = (Array.isArray(payload?.copies) ? payload.copies : [])
    .filter((choice) => typeof choice?.entityId === 'string')
    .map((choice) => ({
      entityId: choice.entityId,
      fieldIds: (Array.isArray(choice.fieldIds) ? choice.fieldIds : []).filter(
        (fieldId) => typeof fieldId === 'string'
      ),
      fieldNames: parseNames(choice.fieldNames),
      renames: parseNames(choice.renames),
      changedFieldIds: (Array.isArray(choice.changedFieldIds) ? choice.changedFieldIds : []).filter(
        (fieldId) => typeof fieldId === 'string'
      ),
      sections: (Array.isArray(choice.sections) ? choice.sections : []).filter((section) =>
        SECTIONS.includes(section)
      )
    }))
  const entities = (Array.isArray(payload?.entities) ? payload.entities : [])
    .filter((choice) => typeof choice?.tempId === 'string')
    .map((choice) => ({
      tempId: choice.tempId,
      ...(typeof choice.name === 'string' && choice.name.trim() && { name: choice.name.trim() }),
      ...(choice.name && typeof choice.name === 'object' && { name: choice.name })
    }))
  return { copies, entities }
}
 
module.exports = {
  MAX_PACK_COPIES,
  loadPackCopies,
  planUpgrade,
  copyTargets,
  toUpgradePreview,
  selectUpgrade,
  ownFieldsAfter,
  formsForCopy,
  findUpgradeNameCollision,
  parseUpgradeChoices
}