{"version":3,"file":"index.mjs","sources":["../../../../server/src/services/migration-builder/index.ts"],"sourcesContent":["import path from 'node:path';\n\nimport { contentTypes as contentTypesUtils } from '@strapi/utils';\nimport type { Core } from '@strapi/types';\n\n/**\n * The CTB-level attribute definition of the *new* side of a rename hop (the\n * `properties` the admin sends for `newName`). Only the storage-relevant keys\n * are inspected; see `isCompatibleRename`.\n */\nexport interface RenameAttributeDefinition {\n  type?: string;\n  relation?: string;\n  target?: string;\n  component?: string;\n  repeatable?: boolean;\n  customField?: string;\n  targetAttribute?: string | null;\n  inversedBy?: string;\n  mappedBy?: string;\n  configurable?: boolean;\n  [key: string]: unknown;\n}\n\nexport interface RenameNames {\n  oldName: string;\n  newName: string;\n  /**\n   * Definition of the attribute under its new name, when known. Used to refuse\n   * hops that also change the attribute's storage (e.g. `string` -> `integer`,\n   * or a relation retargeted): renaming the column and letting schema sync\n   * alter its type in place can fail on Postgres/MySQL, whereas the legacy\n   * drop-and-recreate path is always safe.\n   */\n  newAttribute?: RenameAttributeDefinition;\n}\n\nexport type UnsupportedRenameReason =\n  | 'model-not-found'\n  | 'attribute-not-found'\n  | 'unsupported-type'\n  | 'type-changed'\n  | 'target-occupied';\n\nexport interface UnsupportedRename {\n  uid: string;\n  oldName: string;\n  newName: string;\n  reason: UnsupportedRenameReason;\n}\n\n/**\n * Whether a relation definition has a counterpart on its target. The live\n * schema carries `inversedBy` / `mappedBy`; the CTB payload carries\n * `targetAttribute`.\n */\nconst isBidirectionalRelation = (attribute: RenameAttributeDefinition): boolean =>\n  Boolean(attribute.inversedBy || attribute.mappedBy || attribute.targetAttribute);\n\n/**\n * Whether the storage of `oldAttribute` can host `newAttribute` after a plain\n * rename of its physical artifact. Anything else must go through the legacy\n * drop-and-recreate path, so the hop is reported as `type-changed`.\n *\n * `resolveType` maps a definition to its storage type. The builder passes one\n * that resolves custom fields (sent as `type: 'customField'` by the admin, but\n * already converted to their underlying type in the live schema).\n */\nexport const isCompatibleRename = (\n  oldAttribute: RenameAttributeDefinition | undefined,\n  newAttribute: RenameAttributeDefinition | undefined,\n  resolveType: (attribute: RenameAttributeDefinition) => string | undefined = (attribute) =>\n    attribute.type\n): boolean => {\n  const oldType = oldAttribute ? resolveType(oldAttribute) : undefined;\n  const newType = newAttribute ? resolveType(newAttribute) : undefined;\n\n  // Without both definitions there is nothing to compare; the metadata-based\n  // classification is the only guard we have.\n  if (!oldAttribute || !newAttribute || !oldType || !newType) {\n    return true;\n  }\n\n  if (oldType !== newType) {\n    return false;\n  }\n\n  // A different custom field on the same underlying type is still a different\n  // field.\n  if (\n    (oldAttribute.customField || newAttribute.customField) &&\n    oldAttribute.customField !== newAttribute.customField\n  ) {\n    return false;\n  }\n\n  switch (newType) {\n    case 'relation':\n      // `manyWay` and a bidirectional `oneToMany` share `relation: 'oneToMany'`,\n      // but switching between them moves join-table ownership.\n      return (\n        oldAttribute.relation === newAttribute.relation &&\n        oldAttribute.target === newAttribute.target &&\n        isBidirectionalRelation(oldAttribute) === isBidirectionalRelation(newAttribute)\n      );\n    case 'component':\n      return (\n        oldAttribute.component === newAttribute.component &&\n        Boolean(oldAttribute.repeatable) === Boolean(newAttribute.repeatable)\n      );\n    default:\n      return true;\n  }\n};\n\nexport interface BuiltMigration {\n  filename: string;\n  content: string;\n}\n\n/**\n * How a renamed attribute maps to a physical database artifact, resolved from\n * `strapi.db.metadata` (the live, pre-rename schema). The `from` field is the\n * current physical identifier and moves forward at each hop so rename chains and\n * user-routed swaps replay verbatim.\n *\n * - `scalarColumn` / `joinColumn`: a column on the model's own table. Scalar\n *   columns resolve names via `getColumnName`; relation join columns (`<field>_id`)\n *   via `getJoinColumnAttributeIdName`.\n * - `joinTable`: a relation backed by a join/link table (the table name encodes\n *   the owning attribute name).\n * - `component`: a component or dynamic zone — the attribute name is a *value* in\n *   the per-type link table's `field` column, so it is an `UPDATE`, not DDL.\n * - `media`: like `component`, but stored in the shared `files_related_morphs`\n *   table, so the `UPDATE` is additionally scoped by `related_type` (the uid).\n * - `skip`: recognised but needs no DB change (e.g. the inverse side of a\n *   bidirectional relation — the join table is named from the owning side).\n * - `unsupported`: cannot be migrated automatically (polymorphic morph relations,\n *   which are not creatable through the CTB UI anyway).\n */\ntype Resolved =\n  | { kind: 'scalarColumn'; table: string; from: string }\n  | { kind: 'joinColumn'; table: string; from: string }\n  | { kind: 'joinTable'; from: string }\n  | { kind: 'component'; table: string; fieldColumn: string; from: string }\n  | {\n      kind: 'media';\n      table: string;\n      fieldColumn: string;\n      typeColumn: string;\n      typeValue: string;\n      from: string;\n    }\n  | { kind: 'skip' }\n  | { kind: 'unsupported'; reason: UnsupportedRename['reason'] };\n\ninterface MigrationBuilderDeps {\n  strapi: Core.Strapi;\n}\n\n/**\n * The database metadata shapes the builder reads, derived from `Core.Strapi`\n * so the Content-Type Builder does not depend on `@strapi/database` directly.\n */\ntype ModelMeta = NonNullable<ReturnType<Core.Strapi['db']['metadata']['get']>>;\n\n/**\n * A metadata attribute, widened with the relation/join keys the builder\n * inspects (the metadata union only declares them on some members).\n */\ntype AttributeMeta = ModelMeta['attributes'][string] & {\n  relation?: string;\n  mappedBy?: string;\n  morphColumn?: unknown;\n  joinColumn?: { name?: string };\n  joinTable?: JoinTableMeta;\n};\n\ninterface JoinTableMeta {\n  name?: string;\n  on?: Record<string, unknown>;\n  morphColumn?: { typeColumn?: { name?: string } };\n}\n\ntype SchemaModel = Parameters<typeof contentTypesUtils.getNonVisibleAttributes>[0];\n\n/**\n * Per-uid `origin -> current name` of every received hop, accepted or refused:\n * the logical field is the same field even when its data cannot be carried.\n */\nexport type AttributeRenamesMapping = Record<string, Record<string, string>>;\n\nconst MIGRATION_NAME = 'rename-fields';\n\nexport const createMigrationBuilder = ({ strapi }: MigrationBuilderDeps) => {\n  const { db } = strapi;\n\n  const migrationFileBuilder = db.migrations.createFileBuilder();\n  const unsupported: UnsupportedRename[] = [];\n\n  // Physical-name rules shared with the metadata loader, so the *new* side of a\n  // rename is derived exactly as `db.metadata` will derive it after the reload.\n  const { naming } = db.metadata;\n\n  /**\n   * The app's *source* migrations dir. Generated files always land here (see\n   * `writeFiles`), and it is also the dir discovery reads from when\n   * `useTypescriptMigrations` is off or no tsconfig `outDir` resolves.\n   */\n  const sourceMigrationsDir = () => path.join(strapi.dirs.app.root, 'database', 'migrations');\n\n  let format: 'javascript' | 'typescript' | undefined;\n\n  /**\n   * Mirror the database's discovery decision (`Strapi.ts`): it reads from\n   * `<outDir>/database/migrations` only when `useTypescriptMigrations` is on\n   * *and* a tsconfig `outDir` resolves. In that case the source file must be\n   * `.ts` so `tsc` carries it into `dist`. Otherwise discovery reads the source\n   * dir and only loads `.js`, so a `.ts` file would never run.\n   *\n   * Memoised so the fallback warning is logged once per builder (both `build`\n   * and `writeFiles` call this).\n   */\n  const getFormat = (): 'javascript' | 'typescript' => {\n    if (format) {\n      return format;\n    }\n\n    const useTSM = strapi.config.get('database.settings.useTypescriptMigrations') === true;\n    const discoveryDir = db.config.settings.migrations?.dir;\n    const discoversFromDist =\n      typeof discoveryDir === 'string' &&\n      path.resolve(discoveryDir) !== path.resolve(sourceMigrationsDir());\n\n    if (useTSM && !discoversFromDist) {\n      strapi.log.warn(\n        'database.settings.useTypescriptMigrations is enabled but no TypeScript outDir was resolved for this app; ' +\n          'writing the rename migration as JavaScript so it is discovered from database/migrations.'\n      );\n    }\n\n    format = useTSM && discoversFromDist ? 'typescript' : 'javascript';\n    return format;\n  };\n\n  // Artifacts \"in flight\" for the current save, i.e. produced by an earlier\n  // rename hop in this same batch (e.g. the intermediate `tmp` field a user\n  // routes a swap through). Keyed per uid by the *logical* field name the hop\n  // produced; the value records how that field resolves to a physical artifact\n  // and its current `from` identifier, so a continuation hop replays from the\n  // right place instead of being treated as a brand-new, unknown attribute.\n  const inFlight = new Map<string, Map<string, Resolved>>();\n\n  // CTB-level definition of each in-flight field (per uid, by logical name), so\n  // a continuation hop can still be checked for a storage change against the\n  // definition the chain started from.\n  const inFlightDefinitions = new Map<string, Map<string, RenameAttributeDefinition>>();\n\n  // Logical names vacated by an earlier accepted hop of this batch (per uid). A\n  // refused hop never vacates its source: the artifact stays live until schema\n  // sync drops it. A hop may only target a name that is free: not live in the\n  // pre-reload schema (unless an earlier accepted hop vacated it) and not\n  // produced by an earlier hop still in flight. At migration time the schema-sync drop of a still-live field has\n  // not happened yet, so renaming onto it would collide and the runtime guard\n  // would silently skip the hop. Refusing it here surfaces the problem (e.g. a\n  // truncated chain sent by a client) instead of losing data.\n  const vacated = new Map<string, Set<string>>();\n\n  const isTargetOccupied = (uid: string, newName: string): boolean => {\n    if (inFlight.get(uid)?.has(newName)) {\n      return true;\n    }\n    return Boolean(schemaAttributeOf(uid, newName)) && !(vacated.get(uid)?.has(newName) ?? false);\n  };\n\n  const trackVacated = (uid: string, oldName: string, newName: string): void => {\n    let names = vacated.get(uid);\n    if (!names) {\n      names = new Set<string>();\n      vacated.set(uid, names);\n    }\n    names.add(oldName);\n    // The target is occupied again by the in-flight field.\n    names.delete(newName);\n  };\n\n  const markInFlight = (uid: string, name: string, resolved: Resolved): void => {\n    let entries = inFlight.get(uid);\n    if (!entries) {\n      entries = new Map<string, Resolved>();\n      inFlight.set(uid, entries);\n    }\n    entries.set(name, resolved);\n  };\n\n  // Per uid, logical origin name -> current name, folded over every received hop.\n  const origins = new Map<string, Map<string, string>>();\n\n  const trackOrigin = (uid: string, oldName: string, newName: string): void => {\n    let byOrigin = origins.get(uid);\n    if (!byOrigin) {\n      byOrigin = new Map<string, string>();\n      origins.set(uid, byOrigin);\n    }\n\n    for (const [origin, current] of byOrigin) {\n      if (current === oldName) {\n        byOrigin.set(origin, newName);\n        return;\n      }\n    }\n\n    // A name that is already an origin but no longer current was re-occupied by\n    // something this save did not rename; do not overwrite its logical field.\n    if (!byOrigin.has(oldName)) {\n      byOrigin.set(oldName, newName);\n    }\n  };\n\n  const isMorphRelation = (attribute: AttributeMeta): boolean =>\n    typeof attribute.relation === 'string' && attribute.relation.startsWith('morph');\n\n  const schemaModelOf = (\n    uid: string\n  ): { attributes?: Record<string, RenameAttributeDefinition> } | undefined => {\n    const contentTypes = strapi.contentTypes as Record<string, unknown> | undefined;\n    const components = strapi.components as Record<string, unknown> | undefined;\n    return (contentTypes?.[uid] ?? components?.[uid]) as\n      { attributes?: Record<string, RenameAttributeDefinition> } | undefined;\n  };\n\n  const schemaAttributeOf = (uid: string, name: string): RenameAttributeDefinition | undefined =>\n    schemaModelOf(uid)?.attributes?.[name];\n\n  /**\n   * The type an attribute is stored as. Custom fields are sent by the admin as\n   * `type: 'customField'`, while the live schema already carries their\n   * underlying type, so both sides are resolved through the registry.\n   */\n  const storageTypeOf = (attribute: RenameAttributeDefinition): string | undefined => {\n    if (attribute.type !== 'customField' && typeof attribute.customField !== 'string') {\n      return attribute.type;\n    }\n\n    try {\n      const customField = strapi.get('custom-fields').get(attribute.customField as string) as\n        { type?: string } | undefined;\n      return customField?.type ?? attribute.type;\n    } catch {\n      // Unknown custom field (e.g. its plugin was removed).\n      return attribute.type;\n    }\n  };\n\n  const schemaTypeOf = (uid: string, name: string): string | undefined =>\n    schemaAttributeOf(uid, name)?.type;\n\n  // Resolves the shared upload morph table (e.g. `files_related_morphs`) and its\n  // `related_type` column from the file model's `related` morph attribute. This\n  // is the single table every media field across all types writes to, keyed by\n  // (`field` = attribute name, `related_type` = owning uid).\n  const resolveUploadMorphTable = ():\n    { table: string; fieldColumn: string; typeColumn: string } | undefined => {\n    if (!db.metadata.has('plugin::upload.file')) {\n      return undefined;\n    }\n    const fileMeta = db.metadata.get('plugin::upload.file');\n    const related = fileMeta.attributes?.related as\n      (AttributeMeta & { morphColumn?: JoinTableMeta['morphColumn'] }) | undefined;\n    const joinTable = related?.joinTable;\n    const morphColumn = joinTable?.morphColumn ?? related?.morphColumn;\n    if (!joinTable?.name || !morphColumn?.typeColumn?.name) {\n      return undefined;\n    }\n    return {\n      table: joinTable.name,\n      fieldColumn: db.metadata.identifiers.FIELD_COLUMN,\n      typeColumn: morphColumn.typeColumn.name,\n    };\n  };\n\n  /**\n   * Classifies the *first* hop of a rename by inspecting the live metadata, which\n   * still reflects the pre-rename schema. Continuation hops never reach here —\n   * they inherit their classification from the in-flight map.\n   */\n  const classifyMedia = (\n    uid: string,\n    oldName: string,\n    joinTable: JoinTableMeta | undefined,\n    upload: ReturnType<typeof resolveUploadMorphTable>\n  ): Resolved | undefined => {\n    // Media: the attribute name is a value in the shared `files_related_morphs`\n    // `field` column, scoped by `related_type` (the owning uid). Detect it by\n    // schema type OR by the join table being the shared upload table — the\n    // latter guard is critical so a media field can never fall through to the\n    // unscoped component branch and corrupt other types' media on the shared\n    // table.\n    const isMedia =\n      schemaTypeOf(uid, oldName) === 'media' || (!!upload && joinTable?.name === upload.table);\n    if (!isMedia) {\n      return undefined;\n    }\n    if (!upload) {\n      return { kind: 'unsupported', reason: 'unsupported-type' };\n    }\n    return {\n      kind: 'media',\n      table: upload.table,\n      fieldColumn: upload.fieldColumn,\n      typeColumn: upload.typeColumn,\n      typeValue: uid,\n      from: oldName,\n    };\n  };\n\n  const classifyComponent = (\n    oldName: string,\n    joinTable: JoinTableMeta | undefined\n  ): Resolved | undefined => {\n    const on = joinTable?.on;\n    if (!joinTable?.name || !on || typeof on !== 'object') {\n      return undefined;\n    }\n    const fieldColumn = Object.keys(on).find((key) => on[key] === oldName);\n    if (!fieldColumn) {\n      return undefined;\n    }\n    return { kind: 'component', table: joinTable.name, fieldColumn, from: oldName };\n  };\n\n  const classifyRelation = (\n    meta: ModelMeta,\n    attribute: AttributeMeta,\n    joinTable: JoinTableMeta | undefined\n  ): Resolved => {\n    // Polymorphic morph relations need shared-table handling and are not\n    // creatable through the CTB UI, so they are left unsupported.\n    if (isMorphRelation(attribute) || attribute.morphColumn) {\n      return { kind: 'unsupported', reason: 'unsupported-type' };\n    }\n\n    // Join column on the owner's own table (`<field>_id`), e.g. useJoinTable:false.\n    // The inverse side of a bidirectional join-column relation also carries a\n    // `joinColumn` (pointing at `id`), but owns no column.\n    if (attribute.joinColumn?.name && !joinTable) {\n      if (attribute.mappedBy) {\n        return { kind: 'skip' };\n      }\n      return { kind: 'joinColumn', table: meta.tableName, from: attribute.joinColumn.name };\n    }\n\n    if (joinTable?.name) {\n      // The inverse side of a bidirectional relation: the join table is named\n      // from the owning attribute, so renaming this side touches no artifact.\n      if (attribute.mappedBy) {\n        return { kind: 'skip' };\n      }\n      return { kind: 'joinTable', from: joinTable.name };\n    }\n\n    return { kind: 'unsupported', reason: 'unsupported-type' };\n  };\n\n  /**\n   * Whether the schema lets users rename this attribute at all. System\n   * attributes (`documentId`, `createdBy`, `locale`, `publishedAt`, review\n   * workflow stages…) are also in the metadata and would otherwise be renamed\n   * away, only for sync to re-add them empty.\n   */\n  const isRenamableAttribute = (uid: string, name: string): boolean => {\n    const schemaAttribute = schemaAttributeOf(uid, name);\n    // Same rule as payload validation applies to a hop's old name: `status` is\n    // only reserved with draft and publish, and a legacy field may carry it.\n    if (\n      schemaAttribute?.configurable === false ||\n      contentTypesUtils.isReservedAttributeName(name, { draftAndPublish: false })\n    ) {\n      return false;\n    }\n\n    const model = schemaModelOf(uid);\n    return !contentTypesUtils.getNonVisibleAttributes(model as SchemaModel).includes(name);\n  };\n\n  const classify = (uid: string, oldName: string): Resolved => {\n    if (!schemaAttributeOf(uid, oldName)) {\n      return { kind: 'unsupported', reason: 'attribute-not-found' };\n    }\n\n    if (!isRenamableAttribute(uid, oldName)) {\n      return { kind: 'unsupported', reason: 'unsupported-type' };\n    }\n\n    const meta = db.metadata.get(uid);\n    const attribute = meta.attributes?.[oldName] as AttributeMeta | undefined;\n\n    if (!attribute) {\n      return { kind: 'unsupported', reason: 'attribute-not-found' };\n    }\n\n    const joinTable = attribute.joinTable;\n    const upload = resolveUploadMorphTable();\n    const media = classifyMedia(uid, oldName, joinTable, upload);\n    if (media) {\n      return media;\n    }\n\n    const component = classifyComponent(oldName, joinTable);\n    if (component) {\n      return component;\n    }\n\n    if (attribute.type === 'relation') {\n      return classifyRelation(meta, attribute, joinTable);\n    }\n\n    // Plain scalar column on the model's own table.\n    if ('columnName' in attribute && attribute.columnName) {\n      return { kind: 'scalarColumn', table: meta.tableName, from: attribute.columnName };\n    }\n\n    return { kind: 'unsupported', reason: 'unsupported-type' };\n  };\n\n  /**\n   * Computes the destination identifier for a resolved artifact given the new\n   * field name, and the next in-flight state (with `from` advanced to `to`).\n   */\n  const advance = (uid: string, resolved: Resolved, oldName: string, newName: string): Resolved => {\n    const meta = db.metadata.get(uid);\n    const comment = `${uid}: rename field \"${oldName}\" -> \"${newName}\"`;\n\n    switch (resolved.kind) {\n      case 'scalarColumn':\n      case 'joinColumn': {\n        const to =\n          resolved.kind === 'joinColumn'\n            ? naming.joinColumnName(newName)\n            : naming.columnName(newName);\n        if (resolved.from !== to) {\n          migrationFileBuilder.renameColumn({\n            table: resolved.table,\n            from: resolved.from,\n            to,\n            comment,\n          });\n        }\n        return { ...resolved, from: to };\n      }\n      case 'joinTable': {\n        const to = naming.joinTableName(meta.tableName, newName);\n        if (resolved.from !== to) {\n          migrationFileBuilder.renameTable({ from: resolved.from, to, comment });\n        }\n        return { ...resolved, from: to };\n      }\n      case 'component': {\n        const to = newName;\n        if (resolved.from !== to) {\n          migrationFileBuilder.updateRows({\n            table: resolved.table,\n            guardColumn: resolved.fieldColumn,\n            where: { [resolved.fieldColumn]: resolved.from },\n            set: { [resolved.fieldColumn]: to },\n            comment,\n          });\n        }\n        return { ...resolved, from: to };\n      }\n      case 'media': {\n        const to = newName;\n        if (resolved.from !== to) {\n          migrationFileBuilder.updateRows({\n            table: resolved.table,\n            guardColumn: resolved.fieldColumn,\n            where: {\n              [resolved.fieldColumn]: resolved.from,\n              [resolved.typeColumn]: resolved.typeValue,\n            },\n            set: { [resolved.fieldColumn]: to },\n            comment,\n          });\n        }\n        return { ...resolved, from: to };\n      }\n      default:\n        return resolved;\n    }\n  };\n\n  /**\n   * Records one rename hop exactly in the order the user performed it. Because the\n   * Content-Type Builder forbids two fields sharing a name at any instant, the\n   * recorded path is inherently collision-free: replaying each hop verbatim never\n   * targets an occupied artifact, so no synthetic temporary name is ever needed\n   * (a \"swap\" is already expressed by the user's own intermediate-name hop).\n   */\n  const addRename = (uid: string, { oldName, newName, newAttribute }: RenameNames): void => {\n    // `metadata.get` throws when the model is unknown, so guard with `has` first.\n    if (!db.metadata.has(uid)) {\n      unsupported.push({ uid, oldName, newName, reason: 'model-not-found' });\n      return;\n    }\n\n    trackOrigin(uid, oldName, newName);\n\n    if (isTargetOccupied(uid, newName)) {\n      unsupported.push({ uid, oldName, newName, reason: 'target-occupied' });\n      // Keep the chain consistent so a later continuation hop stays silent. The\n      // source is not vacated: its artifact was not moved.\n      markInFlight(uid, newName, { kind: 'unsupported', reason: 'target-occupied' });\n      return;\n    }\n\n    const entries = inFlight.get(uid);\n    const definitions = inFlightDefinitions.get(uid);\n    const oldAttribute = definitions?.get(oldName) ?? schemaAttributeOf(uid, oldName);\n    let resolved = entries?.get(oldName) ?? classify(uid, oldName);\n\n    // A rename that also changes the attribute's storage cannot be expressed as a\n    // rename of the physical artifact: leave it to the drop-and-recreate path.\n    if (\n      resolved.kind !== 'unsupported' &&\n      !isCompatibleRename(oldAttribute, newAttribute, storageTypeOf)\n    ) {\n      resolved = { kind: 'unsupported', reason: 'type-changed' };\n    }\n\n    if (newAttribute ?? oldAttribute) {\n      let byName = inFlightDefinitions.get(uid);\n      if (!byName) {\n        byName = new Map();\n        inFlightDefinitions.set(uid, byName);\n      }\n      byName.set(newName, (newAttribute ?? oldAttribute) as RenameAttributeDefinition);\n    }\n\n    if (resolved.kind === 'unsupported') {\n      unsupported.push({ uid, oldName, newName, reason: resolved.reason });\n      // Keep the chain consistent so a later continuation hop stays silent. The\n      // source keeps its in-flight entry and is not vacated: its physical\n      // artifact stays where it is until schema sync drops it.\n      markInFlight(uid, newName, resolved);\n      return;\n    }\n\n    // Accepted from here on: the source name is free and the field moves.\n    entries?.delete(oldName);\n    definitions?.delete(oldName);\n    trackVacated(uid, oldName, newName);\n\n    if (resolved.kind === 'skip') {\n      markInFlight(uid, newName, resolved);\n      return;\n    }\n\n    const next = advance(uid, resolved, oldName, newName);\n    markInFlight(uid, newName, next);\n  };\n\n  return {\n    addRenameAttribute(uid: string, names: RenameNames): void {\n      addRename(uid, names);\n    },\n\n    /**\n     * The composed `origin -> final` name of every schema attribute that\n     * received hops in this save, per uid. Identity entries (`a -> b -> a`) and\n     * origins that are not schema attributes are left out.\n     */\n    attributeRenamesMapping(): AttributeRenamesMapping {\n      const mapping: AttributeRenamesMapping = {};\n\n      for (const [uid, byOrigin] of origins) {\n        for (const [origin, final] of byOrigin) {\n          if (origin === final || !schemaAttributeOf(uid, origin)) {\n            continue;\n          }\n          mapping[uid] ??= {};\n          mapping[uid][origin] = final;\n        }\n      }\n\n      return mapping;\n    },\n\n    /**\n     * Adds the logical op that carries this save's renames to the stores keyed\n     * by attribute name (admin field permissions, via handlers registered on\n     * the database). Call it after every hop so it is the last operation.\n     */\n    addAttributeRenames(renames: AttributeRenamesMapping): void {\n      if (Object.keys(renames).length === 0) {\n        return;\n      }\n\n      migrationFileBuilder.attributeRenames({\n        renames,\n        comment:\n          \"Update stores keyed by attribute name (admin field permissions) for this save's renames\",\n      });\n    },\n\n    hasChanges(): boolean {\n      return migrationFileBuilder.hasChanges();\n    },\n\n    getUnsupported(): UnsupportedRename[] {\n      return [...unsupported];\n    },\n\n    getOperations() {\n      return migrationFileBuilder.getOperations();\n    },\n\n    build(): BuiltMigration | null {\n      return migrationFileBuilder.build({ name: MIGRATION_NAME, format: getFormat() });\n    },\n\n    async writeFiles(): Promise<string | null> {\n      // Always write to the app's *source* migrations dir, never the database's\n      // configured dir: when `useTypescriptMigrations` is enabled that points at\n      // build output (e.g. `dist/database/migrations`), which is gitignored and\n      // wiped on the next build, so the generated migration would not be a\n      // portable record.\n      const dir = sourceMigrationsDir();\n      return migrationFileBuilder.writeFiles({ name: MIGRATION_NAME, format: getFormat(), dir });\n    },\n  };\n};\n\nexport type MigrationBuilder = ReturnType<typeof createMigrationBuilder>;\n"],"names":["isBidirectionalRelation","attribute","Boolean","inversedBy","mappedBy","targetAttribute","isCompatibleRename","oldAttribute","newAttribute","resolveType","type","oldType","undefined","newType","customField","relation","target","component","repeatable","MIGRATION_NAME","createMigrationBuilder","strapi","db","migrationFileBuilder","migrations","createFileBuilder","unsupported","naming","metadata","sourceMigrationsDir","path","join","dirs","app","root","format","getFormat","useTSM","config","get","discoveryDir","settings","dir","discoversFromDist","resolve","log","warn","inFlight","Map","inFlightDefinitions","vacated","isTargetOccupied","uid","newName","has","schemaAttributeOf","trackVacated","oldName","names","Set","set","add","delete","markInFlight","name","resolved","entries","origins","trackOrigin","byOrigin","origin","current","isMorphRelation","startsWith","schemaModelOf","contentTypes","components","attributes","storageTypeOf","schemaTypeOf","resolveUploadMorphTable","fileMeta","related","joinTable","morphColumn","typeColumn","table","fieldColumn","identifiers","FIELD_COLUMN","classifyMedia","upload","isMedia","kind","reason","typeValue","from","classifyComponent","on","Object","keys","find","key","classifyRelation","meta","joinColumn","tableName","isRenamableAttribute","schemaAttribute","configurable","contentTypesUtils","isReservedAttributeName","draftAndPublish","model","getNonVisibleAttributes","includes","classify","media","columnName","advance","comment","to","joinColumnName","renameColumn","joinTableName","renameTable","updateRows","guardColumn","where","addRename","push","definitions","byName","next","addRenameAttribute","attributeRenamesMapping","mapping","final","addAttributeRenames","renames","length","attributeRenames","hasChanges","getUnsupported","getOperations","build","writeFiles"],"mappings":";;;AAmDA;;;;AAIC,IACD,MAAMA,uBAAAA,GAA0B,CAACC,SAAAA,GAC/BC,OAAAA,CAAQD,SAAAA,CAAUE,UAAU,IAAIF,SAAAA,CAAUG,QAAQ,IAAIH,SAAAA,CAAUI,eAAe,CAAA;AAEjF;;;;;;;;IASO,MAAMC,kBAAAA,GAAqB,CAChCC,YAAAA,EACAC,cACAC,WAAAA,GAA4E,CAACR,SAAAA,GAC3EA,SAAAA,CAAUS,IAAI,GAAA;IAEhB,MAAMC,OAAAA,GAAUJ,YAAAA,GAAeE,WAAAA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