@strapi/content-type-builder 5.55.1 → 5.57.0

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.
Files changed (152) hide show
  1. package/dist/admin/components/AIChat/lib/transforms/schemas/toCTB.js +117 -13
  2. package/dist/admin/components/AIChat/lib/transforms/schemas/toCTB.js.map +1 -1
  3. package/dist/admin/components/AIChat/lib/transforms/schemas/toCTB.mjs +118 -13
  4. package/dist/admin/components/AIChat/lib/transforms/schemas/toCTB.mjs.map +1 -1
  5. package/dist/admin/components/AIChat/providers/SchemaProvider.js +31 -19
  6. package/dist/admin/components/AIChat/providers/SchemaProvider.js.map +1 -1
  7. package/dist/admin/components/AIChat/providers/SchemaProvider.mjs +31 -19
  8. package/dist/admin/components/AIChat/providers/SchemaProvider.mjs.map +1 -1
  9. package/dist/admin/components/DataManager/DataManagerContext.js.map +1 -1
  10. package/dist/admin/components/DataManager/DataManagerContext.mjs.map +1 -1
  11. package/dist/admin/components/DataManager/DataManagerProvider.js +166 -6
  12. package/dist/admin/components/DataManager/DataManagerProvider.js.map +1 -1
  13. package/dist/admin/components/DataManager/DataManagerProvider.mjs +165 -7
  14. package/dist/admin/components/DataManager/DataManagerProvider.mjs.map +1 -1
  15. package/dist/admin/components/DataManager/RenameMigrationModal.js +285 -0
  16. package/dist/admin/components/DataManager/RenameMigrationModal.js.map +1 -0
  17. package/dist/admin/components/DataManager/RenameMigrationModal.mjs +257 -0
  18. package/dist/admin/components/DataManager/RenameMigrationModal.mjs.map +1 -0
  19. package/dist/admin/components/DataManager/reducer.js +107 -2
  20. package/dist/admin/components/DataManager/reducer.js.map +1 -1
  21. package/dist/admin/components/DataManager/reducer.mjs +106 -2
  22. package/dist/admin/components/DataManager/reducer.mjs.map +1 -1
  23. package/dist/admin/components/DataManager/utils/cleanData.js +8 -1
  24. package/dist/admin/components/DataManager/utils/cleanData.js.map +1 -1
  25. package/dist/admin/components/DataManager/utils/cleanData.mjs +8 -1
  26. package/dist/admin/components/DataManager/utils/cleanData.mjs.map +1 -1
  27. package/dist/admin/components/DataManager/utils/groupRenameChains.js +86 -0
  28. package/dist/admin/components/DataManager/utils/groupRenameChains.js.map +1 -0
  29. package/dist/admin/components/DataManager/utils/groupRenameChains.mjs +84 -0
  30. package/dist/admin/components/DataManager/utils/groupRenameChains.mjs.map +1 -0
  31. package/dist/admin/components/DataManager/utils/isStorageCompatibleRename.js +29 -0
  32. package/dist/admin/components/DataManager/utils/isStorageCompatibleRename.js.map +1 -0
  33. package/dist/admin/components/DataManager/utils/isStorageCompatibleRename.mjs +27 -0
  34. package/dist/admin/components/DataManager/utils/isStorageCompatibleRename.mjs.map +1 -0
  35. package/dist/admin/components/DataManager/utils/resolveAfterEditRenameConsent.js +35 -0
  36. package/dist/admin/components/DataManager/utils/resolveAfterEditRenameConsent.js.map +1 -0
  37. package/dist/admin/components/DataManager/utils/resolveAfterEditRenameConsent.mjs +33 -0
  38. package/dist/admin/components/DataManager/utils/resolveAfterEditRenameConsent.mjs.map +1 -0
  39. package/dist/admin/components/DataManager/utils/splitChainsByInheritedConsent.js +48 -0
  40. package/dist/admin/components/DataManager/utils/splitChainsByInheritedConsent.js.map +1 -0
  41. package/dist/admin/components/DataManager/utils/splitChainsByInheritedConsent.mjs +45 -0
  42. package/dist/admin/components/DataManager/utils/splitChainsByInheritedConsent.mjs.map +1 -0
  43. package/dist/admin/components/FormModal/FormModal.js +143 -9
  44. package/dist/admin/components/FormModal/FormModal.js.map +1 -1
  45. package/dist/admin/components/FormModal/FormModal.mjs +144 -10
  46. package/dist/admin/components/FormModal/FormModal.mjs.map +1 -1
  47. package/dist/admin/components/FormModal/attributes/validation/common.js +6 -5
  48. package/dist/admin/components/FormModal/attributes/validation/common.js.map +1 -1
  49. package/dist/admin/components/FormModal/attributes/validation/common.mjs +1 -1
  50. package/dist/admin/components/FormModal/attributes/validation/common.mjs.map +1 -1
  51. package/dist/admin/components/FormModal/component/createComponentSchema.js +10 -7
  52. package/dist/admin/components/FormModal/component/createComponentSchema.js.map +1 -1
  53. package/dist/admin/components/FormModal/component/createComponentSchema.mjs +1 -1
  54. package/dist/admin/components/FormModal/component/createComponentSchema.mjs.map +1 -1
  55. package/dist/admin/components/FormModal/contentType/createContentTypeSchema.js +24 -21
  56. package/dist/admin/components/FormModal/contentType/createContentTypeSchema.js.map +1 -1
  57. package/dist/admin/components/FormModal/contentType/createContentTypeSchema.mjs +1 -1
  58. package/dist/admin/components/FormModal/contentType/createContentTypeSchema.mjs.map +1 -1
  59. package/dist/admin/components/FormModal/forms/utils/createCollectionName.js +3 -2
  60. package/dist/admin/components/FormModal/forms/utils/createCollectionName.js.map +1 -1
  61. package/dist/admin/components/FormModal/forms/utils/createCollectionName.mjs +1 -1
  62. package/dist/admin/components/FormModal/forms/utils/createCollectionName.mjs.map +1 -1
  63. package/dist/admin/components/FormModal/utils/getRenameStorageChange.js +73 -0
  64. package/dist/admin/components/FormModal/utils/getRenameStorageChange.js.map +1 -0
  65. package/dist/admin/components/FormModal/utils/getRenameStorageChange.mjs +70 -0
  66. package/dist/admin/components/FormModal/utils/getRenameStorageChange.mjs.map +1 -0
  67. package/dist/admin/src/components/AIChat/components/AnimatedBox.d.ts +2 -2
  68. package/dist/admin/src/components/AIChat/components/Input.d.ts +2 -2
  69. package/dist/admin/src/components/AIChat/lib/transforms/schemas/toCTB.d.ts +4 -3
  70. package/dist/admin/src/components/AIChat/lib/types/schema.d.ts +6 -1
  71. package/dist/admin/src/components/AttributeOptions/OptionBoxWrapper.d.ts +2 -2
  72. package/dist/admin/src/components/ComponentRow.d.ts +2 -2
  73. package/dist/admin/src/components/DataManager/DataManagerContext.d.ts +28 -2
  74. package/dist/admin/src/components/DataManager/RenameMigrationModal.d.ts +73 -0
  75. package/dist/admin/src/components/DataManager/reducer.d.ts +17 -2
  76. package/dist/admin/src/components/DataManager/utils/cleanData.d.ts +16 -0
  77. package/dist/admin/src/components/DataManager/utils/groupRenameChains.d.ts +31 -0
  78. package/dist/admin/src/components/DataManager/utils/isStorageCompatibleRename.d.ts +10 -0
  79. package/dist/admin/src/components/DataManager/utils/resolveAfterEditRenameConsent.d.ts +24 -0
  80. package/dist/admin/src/components/DataManager/utils/splitChainsByInheritedConsent.d.ts +26 -0
  81. package/dist/admin/src/components/FormModal/utils/getRenameStorageChange.d.ts +40 -0
  82. package/dist/admin/src/components/List.d.ts +2 -2
  83. package/dist/admin/src/components/Relation/RelationNaturePicker/Components.d.ts +4 -4
  84. package/dist/admin/src/types.d.ts +23 -0
  85. package/dist/admin/translations/en.json.js +12 -0
  86. package/dist/admin/translations/en.json.js.map +1 -1
  87. package/dist/admin/translations/en.json.mjs +12 -0
  88. package/dist/admin/translations/en.json.mjs.map +1 -1
  89. package/dist/server/config.js +24 -3
  90. package/dist/server/config.js.map +1 -1
  91. package/dist/server/config.mjs +21 -3
  92. package/dist/server/config.mjs.map +1 -1
  93. package/dist/server/controllers/schema.js +2 -2
  94. package/dist/server/controllers/schema.js.map +1 -1
  95. package/dist/server/controllers/schema.mjs +1 -1
  96. package/dist/server/controllers/schema.mjs.map +1 -1
  97. package/dist/server/controllers/validation/content-type.js +9 -11
  98. package/dist/server/controllers/validation/content-type.js.map +1 -1
  99. package/dist/server/controllers/validation/content-type.mjs +7 -9
  100. package/dist/server/controllers/validation/content-type.mjs.map +1 -1
  101. package/dist/server/controllers/validation/model-schema.js +2 -3
  102. package/dist/server/controllers/validation/model-schema.js.map +1 -1
  103. package/dist/server/controllers/validation/model-schema.mjs +1 -2
  104. package/dist/server/controllers/validation/model-schema.mjs.map +1 -1
  105. package/dist/server/controllers/validation/relations.js +1 -2
  106. package/dist/server/controllers/validation/relations.js.map +1 -1
  107. package/dist/server/controllers/validation/relations.mjs +1 -2
  108. package/dist/server/controllers/validation/relations.mjs.map +1 -1
  109. package/dist/server/controllers/validation/schema.js +42 -23
  110. package/dist/server/controllers/validation/schema.js.map +1 -1
  111. package/dist/server/controllers/validation/schema.mjs +43 -24
  112. package/dist/server/controllers/validation/schema.mjs.map +1 -1
  113. package/dist/server/index.js +1 -1
  114. package/dist/server/index.js.map +1 -1
  115. package/dist/server/services/content-types.js +1 -2
  116. package/dist/server/services/content-types.js.map +1 -1
  117. package/dist/server/services/content-types.mjs +2 -3
  118. package/dist/server/services/content-types.mjs.map +1 -1
  119. package/dist/server/services/migration-builder/index.js +580 -0
  120. package/dist/server/services/migration-builder/index.js.map +1 -0
  121. package/dist/server/services/migration-builder/index.mjs +573 -0
  122. package/dist/server/services/migration-builder/index.mjs.map +1 -0
  123. package/dist/server/services/schema-builder/content-type-builder.js +31 -1
  124. package/dist/server/services/schema-builder/content-type-builder.js.map +1 -1
  125. package/dist/server/services/schema-builder/content-type-builder.mjs +31 -1
  126. package/dist/server/services/schema-builder/content-type-builder.mjs.map +1 -1
  127. package/dist/server/services/schema-mutation.js +30 -2
  128. package/dist/server/services/schema-mutation.js.map +1 -1
  129. package/dist/server/services/schema-mutation.mjs +10 -2
  130. package/dist/server/services/schema-mutation.mjs.map +1 -1
  131. package/dist/server/services/schema.js +259 -15
  132. package/dist/server/services/schema.js.map +1 -1
  133. package/dist/server/services/schema.mjs +252 -9
  134. package/dist/server/services/schema.mjs.map +1 -1
  135. package/dist/server/src/config.d.ts +23 -2
  136. package/dist/server/src/config.d.ts.map +1 -1
  137. package/dist/server/src/controllers/validation/content-type.d.ts +0 -1
  138. package/dist/server/src/controllers/validation/content-type.d.ts.map +1 -1
  139. package/dist/server/src/controllers/validation/relations.d.ts.map +1 -1
  140. package/dist/server/src/controllers/validation/schema.d.ts +28 -0
  141. package/dist/server/src/controllers/validation/schema.d.ts.map +1 -1
  142. package/dist/server/src/index.d.ts +10 -2
  143. package/dist/server/src/index.d.ts.map +1 -1
  144. package/dist/server/src/services/content-types.d.ts.map +1 -1
  145. package/dist/server/src/services/migration-builder/index.d.ts +83 -0
  146. package/dist/server/src/services/migration-builder/index.d.ts.map +1 -0
  147. package/dist/server/src/services/schema-builder/content-type-builder.d.ts.map +1 -1
  148. package/dist/server/src/services/schema-mutation.d.ts +4 -2
  149. package/dist/server/src/services/schema-mutation.d.ts.map +1 -1
  150. package/dist/server/src/services/schema.d.ts +19 -0
  151. package/dist/server/src/services/schema.d.ts.map +1 -1
  152. package/package.json +11 -10
@@ -0,0 +1 @@
1
+ {"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> }\n | 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 }\n | 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 }\n | 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'] })\n | 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,CAAYF,YAAAA,CAAAA,GAAgBK,SAAAA;IAC3D,MAAMC,OAAAA,GAAUL,YAAAA,GAAeC,WAAAA,CAAYD,YAAAA,CAAAA,GAAgBI,SAAAA;;;AAI3D,IAAA,IAAI,CAACL,YAAAA,IAAgB,CAACC,gBAAgB,CAACG,OAAAA,IAAW,CAACE,OAAAA,EAAS;QAC1D,OAAO,IAAA;AACT,IAAA;AAEA,IAAA,IAAIF,YAAYE,OAAAA,EAAS;QACvB,OAAO,KAAA;AACT,IAAA;;;AAIA,IAAA,IACE,CAACN,YAAAA,CAAaO,WAAW,IAAIN,YAAAA,CAAaM,WAAW,KACrDP,YAAAA,CAAaO,WAAW,KAAKN,YAAAA,CAAaM,WAAW,EACrD;QACA,OAAO,KAAA;AACT,IAAA;IAEA,OAAQD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ps each attribute name produced by this save's rename hops to the name it
30
+ * had before the save, by folding the hops in order (`a -> tmp, tmp -> b`
31
+ * gives `b -> a`).
32
+ */ const getRenameOrigins = (renames)=>{
33
+ const originOf = new Map();
34
+ if (!Array.isArray(renames)) {
35
+ return originOf;
36
+ }
37
+ for (const { oldName, newName } of renames){
38
+ if (!oldName || !newName || oldName === newName) {
39
+ continue;
40
+ }
41
+ const origin = originOf.get(oldName) ?? oldName;
42
+ originOf.delete(oldName);
43
+ originOf.set(newName, origin);
44
+ }
45
+ return originOf;
46
+ };
28
47
  function createComponentBuilder() {
29
48
  return {
30
49
  setRelation ({ key, uid, attribute }) {
@@ -146,6 +165,7 @@ function createComponentBuilder() {
146
165
  const newKeys = ___default.default.difference(Object.keys(newAttributes), Object.keys(oldAttributes));
147
166
  const deletedKeys = ___default.default.difference(Object.keys(oldAttributes), Object.keys(newAttributes));
148
167
  const remainingKeys = ___default.default.intersection(Object.keys(oldAttributes), Object.keys(newAttributes));
168
+ const renameOrigins = getRenameOrigins(infos.renames);
149
169
  // remove old relations
150
170
  deletedKeys.forEach((key)=>{
151
171
  const attribute = oldAttributes[key];
@@ -218,7 +238,17 @@ function createComponentBuilder() {
218
238
  'manyToMany',
219
239
  'oneToOne'
220
240
  ].includes(relationAttribute.relation)) {
221
- if (relationAttribute.target === uid && relationAttribute.targetAttribute !== undefined) {
241
+ // A renamed relation keeps the ownership of the attribute it was
242
+ // renamed from (same rule as a remaining key), so the join table
243
+ // stays with its owner and the rename migration can carry it.
244
+ const origin = renameOrigins.get(key);
245
+ const originAttribute = origin !== undefined && ___default.default.has(oldAttributes, origin) ? oldAttributes[origin] : undefined;
246
+ const originOwnership = originAttribute !== undefined && attributes.isRelation(originAttribute) && originAttribute.relation === relationAttribute.relation && originAttribute.target === relationAttribute.target ? originAttribute : undefined;
247
+ if (originOwnership?.inversedBy) {
248
+ relationAttribute.dominant = true;
249
+ } else if (originOwnership?.mappedBy) {
250
+ relationAttribute.dominant = false;
251
+ } else if (relationAttribute.target === uid && relationAttribute.targetAttribute !== undefined) {
222
252
  // self referencing relation
223
253
  const targetAttribute = newAttributes[relationAttribute.targetAttribute];
224
254
  if (targetAttribute.dominant === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"content-type-builder.js","sources":["../../../../server/src/services/schema-builder/content-type-builder.ts"],"sourcesContent":["import path from 'path';\nimport _ from 'lodash';\n\nimport { strings, errors } from '@strapi/utils';\nimport type { Schema, Internal } from '@strapi/types';\nimport { isRelation, isConfigurable } from '../../utils/attributes';\nimport { typeKinds } from '../constants';\nimport createSchemaHandler from './schema-handler';\nimport { CreateContentTypeInput } from '../../controllers/validation/content-type';\nimport type { InternalRelationAttribute, InternalAttribute } from './types';\n\nconst { ApplicationError } = errors;\n\nconst reuseUnsetPreviousProperties = (\n newAttribute: Schema.Attribute.AnyAttribute,\n oldAttribute: Schema.Attribute.AnyAttribute\n) => {\n _.defaults(\n newAttribute,\n _.omit(oldAttribute, [\n 'configurable',\n 'required',\n 'private',\n 'unique',\n 'pluginOptions',\n 'inversedBy',\n 'mappedBy',\n 'conditions', // Don't automatically preserve conditions\n ])\n );\n};\n\nexport default function createComponentBuilder() {\n return {\n setRelation(\n this: any,\n { key, uid, attribute }: { key: string; uid: string; attribute: InternalRelationAttribute }\n ) {\n if (!_.has(attribute, 'target')) {\n return;\n }\n\n const targetCT = this.contentTypes.get(attribute.target);\n\n if (!targetCT) {\n throw new ApplicationError(`Content type ${attribute.target} not found`);\n }\n\n const targetAttribute = targetCT.getAttribute(attribute.targetAttribute);\n\n if (!attribute.targetAttribute) {\n return;\n }\n\n // When generating the inverse relation, preserve existing conditions if they exist\n // If the target attribute already exists and has conditions, preserve them\n const targetAttributeData = targetAttribute || {};\n\n // If the source doesn't have conditions but the target does, preserve target's conditions\n\n targetCT.setAttribute(\n attribute.targetAttribute,\n generateRelation({ key, attribute, uid, targetAttribute: targetAttributeData })\n );\n },\n\n unsetRelation(\n this: any,\n attribute: Schema.Attribute.Relation<Schema.Attribute.RelationKind.Any>\n ) {\n if (!('target' in attribute) || !attribute.target) {\n return;\n }\n\n const targetCT = this.contentTypes.get(attribute.target);\n\n const relationAttribute = attribute as InternalRelationAttribute;\n const targetAttributeName = relationAttribute.inversedBy || relationAttribute.mappedBy;\n const targetAttribute = targetCT.getAttribute(targetAttributeName);\n\n if (!targetAttribute) return;\n\n return targetCT.deleteAttribute(targetAttributeName);\n },\n\n createContentTypeAttributes(\n this: any,\n uid: string,\n attributes: CreateContentTypeInput['attributes']\n ) {\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n const contentType = this.contentTypes.get(uid);\n\n // support self referencing content type relation\n Object.keys(attributes).forEach((key) => {\n const { target } = attributes[key];\n if (target === '__self__') {\n attributes[key].target = uid;\n }\n });\n\n contentType.setAttributes(this.convertAttributes(attributes));\n\n Object.keys(attributes).forEach((key) => {\n const attribute = attributes[key] as InternalAttribute;\n\n if (isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n if (['manyToMany', 'oneToOne'].includes(relationAttribute.relation)) {\n if (\n relationAttribute.target === uid &&\n relationAttribute.targetAttribute !== undefined\n ) {\n // self referencing relation\n const targetAttribute = attributes[\n relationAttribute.targetAttribute\n ] as InternalRelationAttribute;\n\n if (targetAttribute.dominant === undefined) {\n relationAttribute.dominant = true;\n } else {\n relationAttribute.dominant = false;\n }\n } else {\n relationAttribute.dominant = true;\n }\n }\n\n this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n return contentType;\n },\n\n /**\n * Creates a content type in memory to be written to files later on\n */\n createContentType(this: any, infos: CreateContentTypeInput) {\n // TODO:: check for unique uid / singularName & pluralName & collectionName\n\n if (infos.uid && infos.uid !== createContentTypeUID(infos)) {\n throw new ApplicationError('contentType.invalidUID');\n }\n\n const uid = infos.uid ?? createContentTypeUID(infos);\n\n if (this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.alreadyExists');\n }\n\n const dir = infos.plugin\n ? path.join(strapi.dirs.app.extensions, infos.plugin, 'content-types', infos.singularName)\n : path.join(strapi.dirs.app.api, infos.singularName, 'content-types', infos.singularName);\n\n const contentType = createSchemaHandler({\n modelName: infos.singularName,\n dir,\n filename: `schema.json`,\n });\n\n this.contentTypes.set(uid, contentType);\n\n contentType\n .setUID(uid)\n .set('kind', infos.kind || typeKinds.COLLECTION_TYPE)\n .set(\n 'collectionName',\n infos.collectionName || strings.nameToCollectionName(infos.pluralName)\n )\n .set('info', {\n singularName: infos.singularName,\n pluralName: infos.pluralName,\n displayName: infos.displayName,\n description: infos.description,\n })\n .set('options', {\n ...infos.options,\n draftAndPublish: infos.draftAndPublish,\n })\n .set('pluginOptions', infos.pluginOptions)\n .set('config', infos.config);\n\n this.createContentTypeAttributes(uid, infos.attributes);\n\n return contentType;\n },\n\n editContentType(this: any, infos: any) {\n const { uid } = infos;\n\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n const contentType = this.contentTypes.get(uid);\n\n const oldAttributes = contentType.schema.attributes;\n\n const newAttributes = _.omitBy(infos.attributes, (attr, key) => {\n return _.has(oldAttributes, key) && !isConfigurable(oldAttributes[key]);\n });\n\n const newKeys = _.difference(Object.keys(newAttributes), Object.keys(oldAttributes));\n const deletedKeys = _.difference(Object.keys(oldAttributes), Object.keys(newAttributes));\n const remainingKeys = _.intersection(Object.keys(oldAttributes), Object.keys(newAttributes));\n\n // remove old relations\n deletedKeys.forEach((key) => {\n const attribute = oldAttributes[key];\n\n // if the old relation has a target attribute. we need to remove it in the target type\n if (isConfigurable(attribute) && isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n const targetAttributeName = relationAttribute.inversedBy || relationAttribute.mappedBy;\n\n if (targetAttributeName !== null && targetAttributeName !== undefined) {\n this.unsetRelation(attribute);\n }\n }\n });\n\n remainingKeys.forEach((key) => {\n const oldAttribute = oldAttributes[key];\n const newAttribute = newAttributes[key] as InternalAttribute;\n\n if (!isRelation(oldAttribute) && isRelation(newAttribute)) {\n return this.setRelation({\n key,\n uid,\n attribute: newAttribute as InternalRelationAttribute,\n });\n }\n\n if (isRelation(oldAttribute) && !isRelation(newAttribute)) {\n return this.unsetRelation(oldAttribute);\n }\n\n if (isRelation(oldAttribute) && isRelation(newAttribute)) {\n const relationAttribute = newAttribute as InternalRelationAttribute;\n const oldRelationAttribute = oldAttribute as InternalRelationAttribute;\n const oldTargetAttributeName =\n oldRelationAttribute.inversedBy || oldRelationAttribute.mappedBy;\n\n const sameRelation = oldAttribute.relation === relationAttribute.relation;\n const targetAttributeHasChanged =\n oldTargetAttributeName !== relationAttribute.targetAttribute;\n\n if (!sameRelation || targetAttributeHasChanged) {\n this.unsetRelation(oldAttribute);\n }\n\n // keep extra options that were set manually on oldAttribute\n reuseUnsetPreviousProperties(relationAttribute, oldAttribute);\n\n // Handle conditions explicitly - only preserve if present and not undefined in new attribute\n const newAttributeFromInfos = newAttributes[key];\n const hasNewConditions =\n newAttributeFromInfos.conditions !== undefined &&\n newAttributeFromInfos.conditions !== null;\n\n if (oldAttribute.conditions) {\n if (hasNewConditions) {\n // Conditions are still present, keep them\n relationAttribute.conditions = newAttributeFromInfos.conditions;\n } else {\n // Conditions were removed (undefined or null), ensure they're not preserved\n delete relationAttribute.conditions;\n }\n } else if (hasNewConditions) {\n // New conditions added\n relationAttribute.conditions = newAttributeFromInfos.conditions;\n }\n\n if (oldRelationAttribute.inversedBy) {\n relationAttribute.dominant = true;\n } else if (oldRelationAttribute.mappedBy) {\n relationAttribute.dominant = false;\n }\n\n return this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n // add new relations\n newKeys.forEach((key) => {\n const attribute = newAttributes[key] as InternalAttribute;\n\n if (isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n if (['manyToMany', 'oneToOne'].includes(relationAttribute.relation)) {\n if (\n relationAttribute.target === uid &&\n relationAttribute.targetAttribute !== undefined\n ) {\n // self referencing relation\n const targetAttribute = newAttributes[\n relationAttribute.targetAttribute\n ] as InternalRelationAttribute;\n\n if (targetAttribute.dominant === undefined) {\n relationAttribute.dominant = true;\n } else {\n relationAttribute.dominant = false;\n }\n } else {\n relationAttribute.dominant = true;\n }\n }\n\n this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n contentType\n .set('kind', infos.kind || contentType.schema.kind)\n .set(['info', 'displayName'], infos.displayName)\n .set(['info', 'description'], infos.description)\n .set('options', {\n ...infos.options,\n draftAndPublish: infos.draftAndPublish,\n })\n .set('pluginOptions', infos.pluginOptions)\n .setAttributes(this.convertAttributes(newAttributes));\n\n return contentType;\n },\n\n deleteContentType(this: any, uid: string) {\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n this.components.forEach((compo: any) => {\n compo.removeContentType(uid);\n });\n\n this.contentTypes.forEach((ct: any) => {\n ct.removeContentType(uid);\n });\n\n return this.contentTypes.get(uid).delete();\n },\n };\n}\n\n/**\n * Returns a uid from a content type infos\n *\n * @param {object} options options\n * @param {string} options.singularName content-type singularName\n * @returns {string} uid\n */\nconst createContentTypeUID = ({\n plugin,\n singularName,\n}: {\n plugin?: string;\n singularName: string;\n}): Internal.UID.ContentType =>\n `${plugin ? `plugin` : `api`}::${plugin || singularName}.${singularName}`;\n\nconst generateRelation = ({\n key,\n attribute,\n uid,\n targetAttribute = {},\n}: {\n key: string;\n attribute: InternalRelationAttribute;\n uid: string;\n targetAttribute?: Partial<InternalRelationAttribute>;\n}) => {\n const opts: any = {\n type: 'relation',\n target: uid,\n required: targetAttribute.required || undefined,\n private: targetAttribute.private || undefined,\n pluginOptions: targetAttribute.pluginOptions || undefined,\n // Preserve conditions from targetAttribute if they exist\n // This allows each side of the relation to maintain its own conditions\n ...(targetAttribute.conditions && { conditions: targetAttribute.conditions }),\n };\n\n switch (attribute.relation) {\n case 'oneToOne': {\n opts.relation = 'oneToOne';\n\n if (attribute.dominant) {\n opts.mappedBy = key;\n } else {\n opts.inversedBy = key;\n }\n break;\n }\n case 'oneToMany': {\n opts.relation = 'manyToOne';\n opts.inversedBy = key;\n break;\n }\n case 'manyToOne': {\n opts.relation = 'oneToMany';\n opts.mappedBy = key;\n break;\n }\n case 'manyToMany': {\n opts.relation = 'manyToMany';\n\n if (attribute.dominant) {\n opts.mappedBy = key;\n } else {\n opts.inversedBy = key;\n }\n\n break;\n }\n default:\n }\n\n // we do this just to make sure we have the same key order when writing to files\n const { type, relation, target, ...restOptions } = opts;\n\n const result = {\n type,\n relation,\n target,\n ...restOptions,\n };\n\n return result;\n};\n"],"names":["ApplicationError","errors","reuseUnsetPreviousProperties","newAttribute","oldAttribute","_","defaults","omit","createComponentBuilder","setRelation","key","uid","attribute","has","targetCT","contentTypes","get","target","targetAttribute","getAttribute","targetAttributeData","setAttribute","generateRelation","unsetRelation","relationAttribute","targetAttributeName","inversedBy","mappedBy","deleteAttribute","createContentTypeAttributes","attributes","contentType","Object","keys","forEach","setAttributes","convertAttributes","isRelation","includes","relation","undefined","dominant","createContentType","infos","createContentTypeUID","dir","plugin","path","join","strapi","dirs","app","extensions","singularName","api","createSchemaHandler","modelName","filename","set","setUID","kind","typeKinds","COLLECTION_TYPE","collectionName","strings","nameToCollectionName","pluralName","displayName","description","options","draftAndPublish","pluginOptions","config","editContentType","oldAttributes","schema","newAttributes","omitBy","attr","isConfigurable","newKeys","difference","deletedKeys","remainingKeys","intersection","oldRelationAttribute","oldTargetAttributeName","sameRelation","targetAttributeHasChanged","newAttributeFromInfos","hasNewConditions","conditions","deleteContentType","components","compo","removeContentType","ct","delete","opts","type","required","private","restOptions","result"],"mappings":";;;;;;;;;;;;;;AAWA,MAAM,EAAEA,gBAAgB,EAAE,GAAGC,YAAAA;AAE7B,MAAMC,4BAAAA,GAA+B,CACnCC,YAAAA,EACAC,YAAAA,GAAAA;AAEAC,IAAAA,kBAAAA,CAAEC,QAAQ,CACRH,YAAAA,EACAE,kBAAAA,CAAEE,IAAI,CAACH,Y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GAAGhB,GAAAA;AAClB,gBAAA;AACF,YAAA;QACA,KAAK,WAAA;AAAa,YAAA;AAChBwF,gBAAAA,IAAAA,CAAK3D,QAAQ,GAAG,WAAA;AAChB2D,gBAAAA,IAAAA,CAAKvE,QAAQ,GAAGjB,GAAAA;AAChB,gBAAA;AACF,YAAA;QACA,KAAK,YAAA;AAAc,YAAA;AACjBwF,gBAAAA,IAAAA,CAAK3D,QAAQ,GAAG,YAAA;gBAEhB,IAAI3B,SAAAA,CAAU6B,QAAQ,EAAE;AACtByD,oBAAAA,IAAAA,CAAKvE,QAAQ,GAAGjB,GAAAA;gBAClB,CAAA,MAAO;AACLwF,oBAAAA,IAAAA,CAAKxE,UAAU,GAAGhB,GAAAA;AACpB,gBAAA;AAEA,gBAAA;AACF,YAAA;AAEF;;IAGA,MAAM,EAAEyF,IAAI,EAAE5D,QAAQ,EAAEtB,MAAM,EAAE,GAAGqF,WAAAA,EAAa,GAAGJ,IAAAA;AAEnD,IAAA,MAAMK,MAAAA,GAAS;AACbJ,QAAAA,IAAAA;AACA5D,QAAAA,QAAAA;AACAtB,QAAAA,MAAAA;AACA,QAAA,GAAGqF;AACL,KAAA;IAEA,OAAOC,MAAAA;AACT,CAAA;;;;"}
1
+ {"version":3,"file":"content-type-builder.js","sources":["../../../../server/src/services/schema-builder/content-type-builder.ts"],"sourcesContent":["import path from 'path';\nimport _ from 'lodash';\n\nimport { strings, errors } from '@strapi/utils';\nimport type { Schema, Internal } from '@strapi/types';\nimport { isRelation, isConfigurable } from '../../utils/attributes';\nimport { typeKinds } from '../constants';\nimport createSchemaHandler from './schema-handler';\nimport { CreateContentTypeInput } from '../../controllers/validation/content-type';\nimport type { InternalRelationAttribute, InternalAttribute } from './types';\n\nconst { ApplicationError } = errors;\n\nconst reuseUnsetPreviousProperties = (\n newAttribute: Schema.Attribute.AnyAttribute,\n oldAttribute: Schema.Attribute.AnyAttribute\n) => {\n _.defaults(\n newAttribute,\n _.omit(oldAttribute, [\n 'configurable',\n 'required',\n 'private',\n 'unique',\n 'pluginOptions',\n 'inversedBy',\n 'mappedBy',\n 'conditions', // Don't automatically preserve conditions\n ])\n );\n};\n\n/**\n * Maps each attribute name produced by this save's rename hops to the name it\n * had before the save, by folding the hops in order (`a -> tmp, tmp -> b`\n * gives `b -> a`).\n */\nconst getRenameOrigins = (renames: unknown): Map<string, string> => {\n const originOf = new Map<string, string>();\n\n if (!Array.isArray(renames)) {\n return originOf;\n }\n\n for (const { oldName, newName } of renames as { oldName?: string; newName?: string }[]) {\n if (!oldName || !newName || oldName === newName) {\n continue;\n }\n\n const origin = originOf.get(oldName) ?? oldName;\n originOf.delete(oldName);\n originOf.set(newName, origin);\n }\n\n return originOf;\n};\n\nexport default function createComponentBuilder() {\n return {\n setRelation(\n this: any,\n { key, uid, attribute }: { key: string; uid: string; attribute: InternalRelationAttribute }\n ) {\n if (!_.has(attribute, 'target')) {\n return;\n }\n\n const targetCT = this.contentTypes.get(attribute.target);\n\n if (!targetCT) {\n throw new ApplicationError(`Content type ${attribute.target} not found`);\n }\n\n const targetAttribute = targetCT.getAttribute(attribute.targetAttribute);\n\n if (!attribute.targetAttribute) {\n return;\n }\n\n // When generating the inverse relation, preserve existing conditions if they exist\n // If the target attribute already exists and has conditions, preserve them\n const targetAttributeData = targetAttribute || {};\n\n // If the source doesn't have conditions but the target does, preserve target's conditions\n\n targetCT.setAttribute(\n attribute.targetAttribute,\n generateRelation({ key, attribute, uid, targetAttribute: targetAttributeData })\n );\n },\n\n unsetRelation(\n this: any,\n attribute: Schema.Attribute.Relation<Schema.Attribute.RelationKind.Any>\n ) {\n if (!('target' in attribute) || !attribute.target) {\n return;\n }\n\n const targetCT = this.contentTypes.get(attribute.target);\n\n const relationAttribute = attribute as InternalRelationAttribute;\n const targetAttributeName = relationAttribute.inversedBy || relationAttribute.mappedBy;\n const targetAttribute = targetCT.getAttribute(targetAttributeName);\n\n if (!targetAttribute) return;\n\n return targetCT.deleteAttribute(targetAttributeName);\n },\n\n createContentTypeAttributes(\n this: any,\n uid: string,\n attributes: CreateContentTypeInput['attributes']\n ) {\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n const contentType = this.contentTypes.get(uid);\n\n // support self referencing content type relation\n Object.keys(attributes).forEach((key) => {\n const { target } = attributes[key];\n if (target === '__self__') {\n attributes[key].target = uid;\n }\n });\n\n contentType.setAttributes(this.convertAttributes(attributes));\n\n Object.keys(attributes).forEach((key) => {\n const attribute = attributes[key] as InternalAttribute;\n\n if (isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n if (['manyToMany', 'oneToOne'].includes(relationAttribute.relation)) {\n if (\n relationAttribute.target === uid &&\n relationAttribute.targetAttribute !== undefined\n ) {\n // self referencing relation\n const targetAttribute = attributes[\n relationAttribute.targetAttribute\n ] as InternalRelationAttribute;\n\n if (targetAttribute.dominant === undefined) {\n relationAttribute.dominant = true;\n } else {\n relationAttribute.dominant = false;\n }\n } else {\n relationAttribute.dominant = true;\n }\n }\n\n this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n return contentType;\n },\n\n /**\n * Creates a content type in memory to be written to files later on\n */\n createContentType(this: any, infos: CreateContentTypeInput) {\n // TODO:: check for unique uid / singularName & pluralName & collectionName\n\n if (infos.uid && infos.uid !== createContentTypeUID(infos)) {\n throw new ApplicationError('contentType.invalidUID');\n }\n\n const uid = infos.uid ?? createContentTypeUID(infos);\n\n if (this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.alreadyExists');\n }\n\n const dir = infos.plugin\n ? path.join(strapi.dirs.app.extensions, infos.plugin, 'content-types', infos.singularName)\n : path.join(strapi.dirs.app.api, infos.singularName, 'content-types', infos.singularName);\n\n const contentType = createSchemaHandler({\n modelName: infos.singularName,\n dir,\n filename: `schema.json`,\n });\n\n this.contentTypes.set(uid, contentType);\n\n contentType\n .setUID(uid)\n .set('kind', infos.kind || typeKinds.COLLECTION_TYPE)\n .set(\n 'collectionName',\n infos.collectionName || strings.nameToCollectionName(infos.pluralName)\n )\n .set('info', {\n singularName: infos.singularName,\n pluralName: infos.pluralName,\n displayName: infos.displayName,\n description: infos.description,\n })\n .set('options', {\n ...infos.options,\n draftAndPublish: infos.draftAndPublish,\n })\n .set('pluginOptions', infos.pluginOptions)\n .set('config', infos.config);\n\n this.createContentTypeAttributes(uid, infos.attributes);\n\n return contentType;\n },\n\n editContentType(this: any, infos: any) {\n const { uid } = infos;\n\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n const contentType = this.contentTypes.get(uid);\n\n const oldAttributes = contentType.schema.attributes;\n\n const newAttributes = _.omitBy(infos.attributes, (attr, key) => {\n return _.has(oldAttributes, key) && !isConfigurable(oldAttributes[key]);\n });\n\n const newKeys = _.difference(Object.keys(newAttributes), Object.keys(oldAttributes));\n const deletedKeys = _.difference(Object.keys(oldAttributes), Object.keys(newAttributes));\n const remainingKeys = _.intersection(Object.keys(oldAttributes), Object.keys(newAttributes));\n const renameOrigins = getRenameOrigins(infos.renames);\n\n // remove old relations\n deletedKeys.forEach((key) => {\n const attribute = oldAttributes[key];\n\n // if the old relation has a target attribute. we need to remove it in the target type\n if (isConfigurable(attribute) && isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n const targetAttributeName = relationAttribute.inversedBy || relationAttribute.mappedBy;\n\n if (targetAttributeName !== null && targetAttributeName !== undefined) {\n this.unsetRelation(attribute);\n }\n }\n });\n\n remainingKeys.forEach((key) => {\n const oldAttribute = oldAttributes[key];\n const newAttribute = newAttributes[key] as InternalAttribute;\n\n if (!isRelation(oldAttribute) && isRelation(newAttribute)) {\n return this.setRelation({\n key,\n uid,\n attribute: newAttribute as InternalRelationAttribute,\n });\n }\n\n if (isRelation(oldAttribute) && !isRelation(newAttribute)) {\n return this.unsetRelation(oldAttribute);\n }\n\n if (isRelation(oldAttribute) && isRelation(newAttribute)) {\n const relationAttribute = newAttribute as InternalRelationAttribute;\n const oldRelationAttribute = oldAttribute as InternalRelationAttribute;\n const oldTargetAttributeName =\n oldRelationAttribute.inversedBy || oldRelationAttribute.mappedBy;\n\n const sameRelation = oldAttribute.relation === relationAttribute.relation;\n const targetAttributeHasChanged =\n oldTargetAttributeName !== relationAttribute.targetAttribute;\n\n if (!sameRelation || targetAttributeHasChanged) {\n this.unsetRelation(oldAttribute);\n }\n\n // keep extra options that were set manually on oldAttribute\n reuseUnsetPreviousProperties(relationAttribute, oldAttribute);\n\n // Handle conditions explicitly - only preserve if present and not undefined in new attribute\n const newAttributeFromInfos = newAttributes[key];\n const hasNewConditions =\n newAttributeFromInfos.conditions !== undefined &&\n newAttributeFromInfos.conditions !== null;\n\n if (oldAttribute.conditions) {\n if (hasNewConditions) {\n // Conditions are still present, keep them\n relationAttribute.conditions = newAttributeFromInfos.conditions;\n } else {\n // Conditions were removed (undefined or null), ensure they're not preserved\n delete relationAttribute.conditions;\n }\n } else if (hasNewConditions) {\n // New conditions added\n relationAttribute.conditions = newAttributeFromInfos.conditions;\n }\n\n if (oldRelationAttribute.inversedBy) {\n relationAttribute.dominant = true;\n } else if (oldRelationAttribute.mappedBy) {\n relationAttribute.dominant = false;\n }\n\n return this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n // add new relations\n newKeys.forEach((key) => {\n const attribute = newAttributes[key] as InternalAttribute;\n\n if (isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n if (['manyToMany', 'oneToOne'].includes(relationAttribute.relation)) {\n // A renamed relation keeps the ownership of the attribute it was\n // renamed from (same rule as a remaining key), so the join table\n // stays with its owner and the rename migration can carry it.\n const origin = renameOrigins.get(key);\n const originAttribute =\n origin !== undefined && _.has(oldAttributes, origin)\n ? (oldAttributes[origin] as InternalRelationAttribute)\n : undefined;\n const originOwnership =\n originAttribute !== undefined &&\n isRelation(originAttribute) &&\n originAttribute.relation === relationAttribute.relation &&\n originAttribute.target === relationAttribute.target\n ? originAttribute\n : undefined;\n\n if (originOwnership?.inversedBy) {\n relationAttribute.dominant = true;\n } else if (originOwnership?.mappedBy) {\n relationAttribute.dominant = false;\n } else if (\n relationAttribute.target === uid &&\n relationAttribute.targetAttribute !== undefined\n ) {\n // self referencing relation\n const targetAttribute = newAttributes[\n relationAttribute.targetAttribute\n ] as InternalRelationAttribute;\n\n if (targetAttribute.dominant === undefined) {\n relationAttribute.dominant = true;\n } else {\n relationAttribute.dominant = false;\n }\n } else {\n relationAttribute.dominant = true;\n }\n }\n\n this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n contentType\n .set('kind', infos.kind || contentType.schema.kind)\n .set(['info', 'displayName'], infos.displayName)\n .set(['info', 'description'], infos.description)\n .set('options', {\n ...infos.options,\n draftAndPublish: infos.draftAndPublish,\n })\n .set('pluginOptions', infos.pluginOptions)\n .setAttributes(this.convertAttributes(newAttributes));\n\n return contentType;\n },\n\n deleteContentType(this: any, uid: string) {\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n this.components.forEach((compo: any) => {\n compo.removeContentType(uid);\n });\n\n this.contentTypes.forEach((ct: any) => {\n ct.removeContentType(uid);\n });\n\n return this.contentTypes.get(uid).delete();\n },\n };\n}\n\n/**\n * Returns a uid from a content type infos\n *\n * @param {object} options options\n * @param {string} options.singularName content-type singularName\n * @returns {string} uid\n */\nconst createContentTypeUID = ({\n plugin,\n singularName,\n}: {\n plugin?: string;\n singularName: string;\n}): Internal.UID.ContentType =>\n `${plugin ? `plugin` : `api`}::${plugin || singularName}.${singularName}`;\n\nconst generateRelation = ({\n key,\n attribute,\n uid,\n targetAttribute = {},\n}: {\n key: string;\n attribute: InternalRelationAttribute;\n uid: string;\n targetAttribute?: Partial<InternalRelationAttribute>;\n}) => {\n const opts: any = {\n type: 'relation',\n target: uid,\n required: targetAttribute.required || undefined,\n private: targetAttribute.private || undefined,\n pluginOptions: targetAttribute.pluginOptions || undefined,\n // Preserve conditions from targetAttribute if they exist\n // This allows each side of the relation to maintain its own conditions\n ...(targetAttribute.conditions && { conditions: targetAttribute.conditions }),\n };\n\n switch (attribute.relation) {\n case 'oneToOne': {\n opts.relation = 'oneToOne';\n\n if (attribute.dominant) {\n opts.mappedBy = key;\n } else {\n opts.inversedBy = key;\n }\n break;\n }\n case 'oneToMany': {\n opts.relation = 'manyToOne';\n opts.inversedBy = key;\n break;\n }\n case 'manyToOne': {\n opts.relation = 'oneToMany';\n opts.mappedBy = key;\n break;\n }\n case 'manyToMany': {\n opts.relation = 'manyToMany';\n\n if (attribute.dominant) {\n opts.mappedBy = key;\n } else {\n opts.inversedBy = key;\n }\n\n break;\n }\n default:\n }\n\n // we do this just to make sure we have the same key order when writing to files\n const { type, relation, target, ...restOptions } = opts;\n\n const result = {\n type,\n relation,\n target,\n ...restOptions,\n };\n\n return result;\n};\n"],"names":["ApplicationError","errors","reuseUnsetPreviousProperties","newAttribute","oldAttribute","_","defaults","omit","getRenameOrigins","renames","originOf","Map","Array","isArray","oldName","newName","origin","get","delete","set","createComponentBuilder","setRelation","key","uid","attribute","has","targetCT","contentTypes","target","targetAttribute","getAttribute","targetAttributeData","setAttribute","generateRelation","unsetRelation","relationAttribute","targetAttributeName","inversedBy","mappedBy","deleteAttribute","createContentTypeAttributes","attributes","contentType","Object","keys","forEach","setAttributes","convertAttributes","isRelation","includes","relation","undefined","dominant","createContentType","infos","createContentTypeUID","dir","plugin","path","join","strapi","dirs","app","extensions","singularName","api","createSchemaHandler","modelName","filename","setUID","kind","typeKinds","COLLECTION_TYPE","collectionName","strings","nameToCollectionName","pluralName","displayName","description","options","draftAndPublish","pluginOptions","config","editContentType","oldAttributes","schema","newAttributes","omitBy","attr","isConfigurable","newKeys","difference","deletedKeys","remainingKeys","intersection","renameOrigins","oldRelationAttribute","oldTargetAttributeName","sameRelation","targetAttributeHasChanged","newAttributeFromInfos","hasNewConditions","conditions","originAttribute","originOwnership","deleteContentType","components","compo","removeContentType","ct","opts","type","required","private","restOptions","result"],"mappings":";;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=>{
18
18
  'conditions'
19
19
  ]));
20
20
  };
21
+ /**
22
+ * Maps each attribute name produced by this save's rename hops to the name it
23
+ * had before the save, by folding the hops in order (`a -> tmp, tmp -> b`
24
+ * gives `b -> a`).
25
+ */ const getRenameOrigins = (renames)=>{
26
+ const originOf = new Map();
27
+ if (!Array.isArray(renames)) {
28
+ return originOf;
29
+ }
30
+ for (const { oldName, newName } of renames){
31
+ if (!oldName || !newName || oldName === newName) {
32
+ continue;
33
+ }
34
+ const origin = originOf.get(oldName) ?? oldName;
35
+ originOf.delete(oldName);
36
+ originOf.set(newName, origin);
37
+ }
38
+ return originOf;
39
+ };
21
40
  function createComponentBuilder() {
22
41
  return {
23
42
  setRelation ({ key, uid, attribute }) {
@@ -139,6 +158,7 @@ function createComponentBuilder() {
139
158
  const newKeys = _.difference(Object.keys(newAttributes), Object.keys(oldAttributes));
140
159
  const deletedKeys = _.difference(Object.keys(oldAttributes), Object.keys(newAttributes));
141
160
  const remainingKeys = _.intersection(Object.keys(oldAttributes), Object.keys(newAttributes));
161
+ const renameOrigins = getRenameOrigins(infos.renames);
142
162
  // remove old relations
143
163
  deletedKeys.forEach((key)=>{
144
164
  const attribute = oldAttributes[key];
@@ -211,7 +231,17 @@ function createComponentBuilder() {
211
231
  'manyToMany',
212
232
  'oneToOne'
213
233
  ].includes(relationAttribute.relation)) {
214
- if (relationAttribute.target === uid && relationAttribute.targetAttribute !== undefined) {
234
+ // A renamed relation keeps the ownership of the attribute it was
235
+ // renamed from (same rule as a remaining key), so the join table
236
+ // stays with its owner and the rename migration can carry it.
237
+ const origin = renameOrigins.get(key);
238
+ const originAttribute = origin !== undefined && _.has(oldAttributes, origin) ? oldAttributes[origin] : undefined;
239
+ const originOwnership = originAttribute !== undefined && isRelation(originAttribute) && originAttribute.relation === relationAttribute.relation && originAttribute.target === relationAttribute.target ? originAttribute : undefined;
240
+ if (originOwnership?.inversedBy) {
241
+ relationAttribute.dominant = true;
242
+ } else if (originOwnership?.mappedBy) {
243
+ relationAttribute.dominant = false;
244
+ } else if (relationAttribute.target === uid && relationAttribute.targetAttribute !== undefined) {
215
245
  // self referencing relation
216
246
  const targetAttribute = newAttributes[relationAttribute.targetAttribute];
217
247
  if (targetAttribute.dominant === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"content-type-builder.mjs","sources":["../../../../server/src/services/schema-builder/content-type-builder.ts"],"sourcesContent":["import path from 'path';\nimport _ from 'lodash';\n\nimport { strings, errors } from '@strapi/utils';\nimport type { Schema, Internal } from '@strapi/types';\nimport { isRelation, isConfigurable } from '../../utils/attributes';\nimport { typeKinds } from '../constants';\nimport createSchemaHandler from './schema-handler';\nimport { CreateContentTypeInput } from '../../controllers/validation/content-type';\nimport type { InternalRelationAttribute, InternalAttribute } from './types';\n\nconst { ApplicationError } = errors;\n\nconst reuseUnsetPreviousProperties = (\n newAttribute: Schema.Attribute.AnyAttribute,\n oldAttribute: Schema.Attribute.AnyAttribute\n) => {\n _.defaults(\n newAttribute,\n _.omit(oldAttribute, [\n 'configurable',\n 'required',\n 'private',\n 'unique',\n 'pluginOptions',\n 'inversedBy',\n 'mappedBy',\n 'conditions', // Don't automatically preserve conditions\n ])\n );\n};\n\nexport default function createComponentBuilder() {\n return {\n setRelation(\n this: any,\n { key, uid, attribute }: { key: string; uid: string; attribute: InternalRelationAttribute }\n ) {\n if (!_.has(attribute, 'target')) {\n return;\n }\n\n const targetCT = this.contentTypes.get(attribute.target);\n\n if (!targetCT) {\n throw new ApplicationError(`Content type ${attribute.target} not found`);\n }\n\n const targetAttribute = targetCT.getAttribute(attribute.targetAttribute);\n\n if (!attribute.targetAttribute) {\n return;\n }\n\n // When generating the inverse relation, preserve existing conditions if they exist\n // If the target attribute already exists and has conditions, preserve them\n const targetAttributeData = targetAttribute || {};\n\n // If the source doesn't have conditions but the target does, preserve target's conditions\n\n targetCT.setAttribute(\n attribute.targetAttribute,\n generateRelation({ key, attribute, uid, targetAttribute: targetAttributeData })\n );\n },\n\n unsetRelation(\n this: any,\n attribute: Schema.Attribute.Relation<Schema.Attribute.RelationKind.Any>\n ) {\n if (!('target' in attribute) || !attribute.target) {\n return;\n }\n\n const targetCT = this.contentTypes.get(attribute.target);\n\n const relationAttribute = attribute as InternalRelationAttribute;\n const targetAttributeName = relationAttribute.inversedBy || relationAttribute.mappedBy;\n const targetAttribute = targetCT.getAttribute(targetAttributeName);\n\n if (!targetAttribute) return;\n\n return targetCT.deleteAttribute(targetAttributeName);\n },\n\n createContentTypeAttributes(\n this: any,\n uid: string,\n attributes: CreateContentTypeInput['attributes']\n ) {\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n const contentType = this.contentTypes.get(uid);\n\n // support self referencing content type relation\n Object.keys(attributes).forEach((key) => {\n const { target } = attributes[key];\n if (target === '__self__') {\n attributes[key].target = uid;\n }\n });\n\n contentType.setAttributes(this.convertAttributes(attributes));\n\n Object.keys(attributes).forEach((key) => {\n const attribute = attributes[key] as InternalAttribute;\n\n if (isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n if (['manyToMany', 'oneToOne'].includes(relationAttribute.relation)) {\n if (\n relationAttribute.target === uid &&\n relationAttribute.targetAttribute !== undefined\n ) {\n // self referencing relation\n const targetAttribute = attributes[\n relationAttribute.targetAttribute\n ] as InternalRelationAttribute;\n\n if (targetAttribute.dominant === undefined) {\n relationAttribute.dominant = true;\n } else {\n relationAttribute.dominant = false;\n }\n } else {\n relationAttribute.dominant = true;\n }\n }\n\n this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n return contentType;\n },\n\n /**\n * Creates a content type in memory to be written to files later on\n */\n createContentType(this: any, infos: CreateContentTypeInput) {\n // TODO:: check for unique uid / singularName & pluralName & collectionName\n\n if (infos.uid && infos.uid !== createContentTypeUID(infos)) {\n throw new ApplicationError('contentType.invalidUID');\n }\n\n const uid = infos.uid ?? createContentTypeUID(infos);\n\n if (this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.alreadyExists');\n }\n\n const dir = infos.plugin\n ? path.join(strapi.dirs.app.extensions, infos.plugin, 'content-types', infos.singularName)\n : path.join(strapi.dirs.app.api, infos.singularName, 'content-types', infos.singularName);\n\n const contentType = createSchemaHandler({\n modelName: infos.singularName,\n dir,\n filename: `schema.json`,\n });\n\n this.contentTypes.set(uid, contentType);\n\n contentType\n .setUID(uid)\n .set('kind', infos.kind || typeKinds.COLLECTION_TYPE)\n .set(\n 'collectionName',\n infos.collectionName || strings.nameToCollectionName(infos.pluralName)\n )\n .set('info', {\n singularName: infos.singularName,\n pluralName: infos.pluralName,\n displayName: infos.displayName,\n description: infos.description,\n })\n .set('options', {\n ...infos.options,\n draftAndPublish: infos.draftAndPublish,\n })\n .set('pluginOptions', infos.pluginOptions)\n .set('config', infos.config);\n\n this.createContentTypeAttributes(uid, infos.attributes);\n\n return contentType;\n },\n\n editContentType(this: any, infos: any) {\n const { uid } = infos;\n\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n const contentType = this.contentTypes.get(uid);\n\n const oldAttributes = contentType.schema.attributes;\n\n const newAttributes = _.omitBy(infos.attributes, (attr, key) => {\n return _.has(oldAttributes, key) && !isConfigurable(oldAttributes[key]);\n });\n\n const newKeys = _.difference(Object.keys(newAttributes), Object.keys(oldAttributes));\n const deletedKeys = _.difference(Object.keys(oldAttributes), Object.keys(newAttributes));\n const remainingKeys = _.intersection(Object.keys(oldAttributes), Object.keys(newAttributes));\n\n // remove old relations\n deletedKeys.forEach((key) => {\n const attribute = oldAttributes[key];\n\n // if the old relation has a target attribute. we need to remove it in the target type\n if (isConfigurable(attribute) && isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n const targetAttributeName = relationAttribute.inversedBy || relationAttribute.mappedBy;\n\n if (targetAttributeName !== null && targetAttributeName !== undefined) {\n this.unsetRelation(attribute);\n }\n }\n });\n\n remainingKeys.forEach((key) => {\n const oldAttribute = oldAttributes[key];\n const newAttribute = newAttributes[key] as InternalAttribute;\n\n if (!isRelation(oldAttribute) && isRelation(newAttribute)) {\n return this.setRelation({\n key,\n uid,\n attribute: newAttribute as InternalRelationAttribute,\n });\n }\n\n if (isRelation(oldAttribute) && !isRelation(newAttribute)) {\n return this.unsetRelation(oldAttribute);\n }\n\n if (isRelation(oldAttribute) && isRelation(newAttribute)) {\n const relationAttribute = newAttribute as InternalRelationAttribute;\n const oldRelationAttribute = oldAttribute as InternalRelationAttribute;\n const oldTargetAttributeName =\n oldRelationAttribute.inversedBy || oldRelationAttribute.mappedBy;\n\n const sameRelation = oldAttribute.relation === relationAttribute.relation;\n const targetAttributeHasChanged =\n oldTargetAttributeName !== relationAttribute.targetAttribute;\n\n if (!sameRelation || targetAttributeHasChanged) {\n this.unsetRelation(oldAttribute);\n }\n\n // keep extra options that were set manually on oldAttribute\n reuseUnsetPreviousProperties(relationAttribute, oldAttribute);\n\n // Handle conditions explicitly - only preserve if present and not undefined in new attribute\n const newAttributeFromInfos = newAttributes[key];\n const hasNewConditions =\n newAttributeFromInfos.conditions !== undefined &&\n newAttributeFromInfos.conditions !== null;\n\n if (oldAttribute.conditions) {\n if (hasNewConditions) {\n // Conditions are still present, keep them\n relationAttribute.conditions = newAttributeFromInfos.conditions;\n } else {\n // Conditions were removed (undefined or null), ensure they're not preserved\n delete relationAttribute.conditions;\n }\n } else if (hasNewConditions) {\n // New conditions added\n relationAttribute.conditions = newAttributeFromInfos.conditions;\n }\n\n if (oldRelationAttribute.inversedBy) {\n relationAttribute.dominant = true;\n } else if (oldRelationAttribute.mappedBy) {\n relationAttribute.dominant = false;\n }\n\n return this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n // add new relations\n newKeys.forEach((key) => {\n const attribute = newAttributes[key] as InternalAttribute;\n\n if (isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n if (['manyToMany', 'oneToOne'].includes(relationAttribute.relation)) {\n if (\n relationAttribute.target === uid &&\n relationAttribute.targetAttribute !== undefined\n ) {\n // self referencing relation\n const targetAttribute = newAttributes[\n relationAttribute.targetAttribute\n ] as InternalRelationAttribute;\n\n if (targetAttribute.dominant === undefined) {\n relationAttribute.dominant = true;\n } else {\n relationAttribute.dominant = false;\n }\n } else {\n relationAttribute.dominant = true;\n }\n }\n\n this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n contentType\n .set('kind', infos.kind || contentType.schema.kind)\n .set(['info', 'displayName'], infos.displayName)\n .set(['info', 'description'], infos.description)\n .set('options', {\n ...infos.options,\n draftAndPublish: infos.draftAndPublish,\n })\n .set('pluginOptions', infos.pluginOptions)\n .setAttributes(this.convertAttributes(newAttributes));\n\n return contentType;\n },\n\n deleteContentType(this: any, uid: string) {\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n this.components.forEach((compo: any) => {\n compo.removeContentType(uid);\n });\n\n this.contentTypes.forEach((ct: any) => {\n ct.removeContentType(uid);\n });\n\n return this.contentTypes.get(uid).delete();\n },\n };\n}\n\n/**\n * Returns a uid from a content type infos\n *\n * @param {object} options options\n * @param {string} options.singularName content-type singularName\n * @returns {string} uid\n */\nconst createContentTypeUID = ({\n plugin,\n singularName,\n}: {\n plugin?: string;\n singularName: string;\n}): Internal.UID.ContentType =>\n `${plugin ? `plugin` : `api`}::${plugin || singularName}.${singularName}`;\n\nconst generateRelation = ({\n key,\n attribute,\n uid,\n targetAttribute = {},\n}: {\n key: string;\n attribute: InternalRelationAttribute;\n uid: string;\n targetAttribute?: Partial<InternalRelationAttribute>;\n}) => {\n const opts: any = {\n type: 'relation',\n target: uid,\n required: targetAttribute.required || undefined,\n private: targetAttribute.private || undefined,\n pluginOptions: targetAttribute.pluginOptions || undefined,\n // Preserve conditions from targetAttribute if they exist\n // This allows each side of the relation to maintain its own conditions\n ...(targetAttribute.conditions && { conditions: targetAttribute.conditions }),\n };\n\n switch (attribute.relation) {\n case 'oneToOne': {\n opts.relation = 'oneToOne';\n\n if (attribute.dominant) {\n opts.mappedBy = key;\n } else {\n opts.inversedBy = key;\n }\n break;\n }\n case 'oneToMany': {\n opts.relation = 'manyToOne';\n opts.inversedBy = key;\n break;\n }\n case 'manyToOne': {\n opts.relation = 'oneToMany';\n opts.mappedBy = key;\n break;\n }\n case 'manyToMany': {\n opts.relation = 'manyToMany';\n\n if (attribute.dominant) {\n opts.mappedBy = key;\n } else {\n opts.inversedBy = key;\n }\n\n break;\n }\n default:\n }\n\n // we do this just to make sure we have the same key order when writing to files\n const { type, relation, target, ...restOptions } = opts;\n\n const result = {\n type,\n relation,\n target,\n ...restOptions,\n };\n\n return result;\n};\n"],"names":["ApplicationError","errors","reuseUnsetPreviousProperties","newAttribute","oldAttribute","_","defaults","omit","createComponentBuilder","setRelation","key","uid","attribute","has","targetCT","contentTypes","get","target","targetAttribute","getAttribute","targetAttributeData","setAttribute","generateRelation","unsetRelation","relationAttribute","targetAttributeName","inversedBy","mappedBy","deleteAttribute","createContentTypeAttributes","attributes","contentType","Object","keys","forEach","setAttributes","convertAttributes","isRelation","includes","relation","undefined","dominant","createContentType","infos","createContentTypeUID","dir","plugin","path","join","strapi","dirs","app","extensions","singularName","api","createSchemaHandler","modelName","filename","set","setUID","kind","typeKinds","COLLECTION_TYPE","collectionName","strings","nameToCollectionName","pluralName","displayName","description","options","draftAndPublish","pluginOptions","config","editContentType","oldAttributes","schema","newAttributes","omitBy","attr","isConfigurable","newKeys","difference","deletedKeys","remainingKeys","intersection","oldRelationAttribute","oldTargetAttributeName","sameRelation","targetAttributeHasChanged","newAttributeFromInfos","hasNewConditions","conditions","deleteContentType","components","compo","removeContentType","ct","delete","opts","type","required","private","restOptions","result"],"mappings":";;;;;;;AAWA,MAAM,EAAEA,gBAAgB,EAAE,GAAGC,MAAAA;AAE7B,MAAMC,4BAAAA,GAA+B,CACnCC,YAAAA,EACAC,YAAAA,GAAAA;AAEAC,IAAAA,CAAAA,CAAEC,QAAQ,CACRH,YAAAA,EACAE,CAAAA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AAGhB,GAAAA;AAClB,gBAAA;AACF,YAAA;QACA,KAAK,WAAA;AAAa,YAAA;AAChBwF,gBAAAA,IAAAA,CAAK3D,QAAQ,GAAG,WAAA;AAChB2D,gBAAAA,IAAAA,CAAKvE,QAAQ,GAAGjB,GAAAA;AAChB,gBAAA;AACF,YAAA;QACA,KAAK,YAAA;AAAc,YAAA;AACjBwF,gBAAAA,IAAAA,CAAK3D,QAAQ,GAAG,YAAA;gBAEhB,IAAI3B,SAAAA,CAAU6B,QAAQ,EAAE;AACtByD,oBAAAA,IAAAA,CAAKvE,QAAQ,GAAGjB,GAAAA;gBAClB,CAAA,MAAO;AACLwF,oBAAAA,IAAAA,CAAKxE,UAAU,GAAGhB,GAAAA;AACpB,gBAAA;AAEA,gBAAA;AACF,YAAA;AAEF;;IAGA,MAAM,EAAEyF,IAAI,EAAE5D,QAAQ,EAAEtB,MAAM,EAAE,GAAGqF,WAAAA,EAAa,GAAGJ,IAAAA;AAEnD,IAAA,MAAMK,MAAAA,GAAS;AACbJ,QAAAA,IAAAA;AACA5D,QAAAA,QAAAA;AACAtB,QAAAA,MAAAA;AACA,QAAA,GAAGqF;AACL,KAAA;IAEA,OAAOC,MAAAA;AACT,CAAA;;;;"}
1
+ {"version":3,"file":"content-type-builder.mjs","sources":["../../../../server/src/services/schema-builder/content-type-builder.ts"],"sourcesContent":["import path from 'path';\nimport _ from 'lodash';\n\nimport { strings, errors } from '@strapi/utils';\nimport type { Schema, Internal } from '@strapi/types';\nimport { isRelation, isConfigurable } from '../../utils/attributes';\nimport { typeKinds } from '../constants';\nimport createSchemaHandler from './schema-handler';\nimport { CreateContentTypeInput } from '../../controllers/validation/content-type';\nimport type { InternalRelationAttribute, InternalAttribute } from './types';\n\nconst { ApplicationError } = errors;\n\nconst reuseUnsetPreviousProperties = (\n newAttribute: Schema.Attribute.AnyAttribute,\n oldAttribute: Schema.Attribute.AnyAttribute\n) => {\n _.defaults(\n newAttribute,\n _.omit(oldAttribute, [\n 'configurable',\n 'required',\n 'private',\n 'unique',\n 'pluginOptions',\n 'inversedBy',\n 'mappedBy',\n 'conditions', // Don't automatically preserve conditions\n ])\n );\n};\n\n/**\n * Maps each attribute name produced by this save's rename hops to the name it\n * had before the save, by folding the hops in order (`a -> tmp, tmp -> b`\n * gives `b -> a`).\n */\nconst getRenameOrigins = (renames: unknown): Map<string, string> => {\n const originOf = new Map<string, string>();\n\n if (!Array.isArray(renames)) {\n return originOf;\n }\n\n for (const { oldName, newName } of renames as { oldName?: string; newName?: string }[]) {\n if (!oldName || !newName || oldName === newName) {\n continue;\n }\n\n const origin = originOf.get(oldName) ?? oldName;\n originOf.delete(oldName);\n originOf.set(newName, origin);\n }\n\n return originOf;\n};\n\nexport default function createComponentBuilder() {\n return {\n setRelation(\n this: any,\n { key, uid, attribute }: { key: string; uid: string; attribute: InternalRelationAttribute }\n ) {\n if (!_.has(attribute, 'target')) {\n return;\n }\n\n const targetCT = this.contentTypes.get(attribute.target);\n\n if (!targetCT) {\n throw new ApplicationError(`Content type ${attribute.target} not found`);\n }\n\n const targetAttribute = targetCT.getAttribute(attribute.targetAttribute);\n\n if (!attribute.targetAttribute) {\n return;\n }\n\n // When generating the inverse relation, preserve existing conditions if they exist\n // If the target attribute already exists and has conditions, preserve them\n const targetAttributeData = targetAttribute || {};\n\n // If the source doesn't have conditions but the target does, preserve target's conditions\n\n targetCT.setAttribute(\n attribute.targetAttribute,\n generateRelation({ key, attribute, uid, targetAttribute: targetAttributeData })\n );\n },\n\n unsetRelation(\n this: any,\n attribute: Schema.Attribute.Relation<Schema.Attribute.RelationKind.Any>\n ) {\n if (!('target' in attribute) || !attribute.target) {\n return;\n }\n\n const targetCT = this.contentTypes.get(attribute.target);\n\n const relationAttribute = attribute as InternalRelationAttribute;\n const targetAttributeName = relationAttribute.inversedBy || relationAttribute.mappedBy;\n const targetAttribute = targetCT.getAttribute(targetAttributeName);\n\n if (!targetAttribute) return;\n\n return targetCT.deleteAttribute(targetAttributeName);\n },\n\n createContentTypeAttributes(\n this: any,\n uid: string,\n attributes: CreateContentTypeInput['attributes']\n ) {\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n const contentType = this.contentTypes.get(uid);\n\n // support self referencing content type relation\n Object.keys(attributes).forEach((key) => {\n const { target } = attributes[key];\n if (target === '__self__') {\n attributes[key].target = uid;\n }\n });\n\n contentType.setAttributes(this.convertAttributes(attributes));\n\n Object.keys(attributes).forEach((key) => {\n const attribute = attributes[key] as InternalAttribute;\n\n if (isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n if (['manyToMany', 'oneToOne'].includes(relationAttribute.relation)) {\n if (\n relationAttribute.target === uid &&\n relationAttribute.targetAttribute !== undefined\n ) {\n // self referencing relation\n const targetAttribute = attributes[\n relationAttribute.targetAttribute\n ] as InternalRelationAttribute;\n\n if (targetAttribute.dominant === undefined) {\n relationAttribute.dominant = true;\n } else {\n relationAttribute.dominant = false;\n }\n } else {\n relationAttribute.dominant = true;\n }\n }\n\n this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n return contentType;\n },\n\n /**\n * Creates a content type in memory to be written to files later on\n */\n createContentType(this: any, infos: CreateContentTypeInput) {\n // TODO:: check for unique uid / singularName & pluralName & collectionName\n\n if (infos.uid && infos.uid !== createContentTypeUID(infos)) {\n throw new ApplicationError('contentType.invalidUID');\n }\n\n const uid = infos.uid ?? createContentTypeUID(infos);\n\n if (this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.alreadyExists');\n }\n\n const dir = infos.plugin\n ? path.join(strapi.dirs.app.extensions, infos.plugin, 'content-types', infos.singularName)\n : path.join(strapi.dirs.app.api, infos.singularName, 'content-types', infos.singularName);\n\n const contentType = createSchemaHandler({\n modelName: infos.singularName,\n dir,\n filename: `schema.json`,\n });\n\n this.contentTypes.set(uid, contentType);\n\n contentType\n .setUID(uid)\n .set('kind', infos.kind || typeKinds.COLLECTION_TYPE)\n .set(\n 'collectionName',\n infos.collectionName || strings.nameToCollectionName(infos.pluralName)\n )\n .set('info', {\n singularName: infos.singularName,\n pluralName: infos.pluralName,\n displayName: infos.displayName,\n description: infos.description,\n })\n .set('options', {\n ...infos.options,\n draftAndPublish: infos.draftAndPublish,\n })\n .set('pluginOptions', infos.pluginOptions)\n .set('config', infos.config);\n\n this.createContentTypeAttributes(uid, infos.attributes);\n\n return contentType;\n },\n\n editContentType(this: any, infos: any) {\n const { uid } = infos;\n\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n const contentType = this.contentTypes.get(uid);\n\n const oldAttributes = contentType.schema.attributes;\n\n const newAttributes = _.omitBy(infos.attributes, (attr, key) => {\n return _.has(oldAttributes, key) && !isConfigurable(oldAttributes[key]);\n });\n\n const newKeys = _.difference(Object.keys(newAttributes), Object.keys(oldAttributes));\n const deletedKeys = _.difference(Object.keys(oldAttributes), Object.keys(newAttributes));\n const remainingKeys = _.intersection(Object.keys(oldAttributes), Object.keys(newAttributes));\n const renameOrigins = getRenameOrigins(infos.renames);\n\n // remove old relations\n deletedKeys.forEach((key) => {\n const attribute = oldAttributes[key];\n\n // if the old relation has a target attribute. we need to remove it in the target type\n if (isConfigurable(attribute) && isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n const targetAttributeName = relationAttribute.inversedBy || relationAttribute.mappedBy;\n\n if (targetAttributeName !== null && targetAttributeName !== undefined) {\n this.unsetRelation(attribute);\n }\n }\n });\n\n remainingKeys.forEach((key) => {\n const oldAttribute = oldAttributes[key];\n const newAttribute = newAttributes[key] as InternalAttribute;\n\n if (!isRelation(oldAttribute) && isRelation(newAttribute)) {\n return this.setRelation({\n key,\n uid,\n attribute: newAttribute as InternalRelationAttribute,\n });\n }\n\n if (isRelation(oldAttribute) && !isRelation(newAttribute)) {\n return this.unsetRelation(oldAttribute);\n }\n\n if (isRelation(oldAttribute) && isRelation(newAttribute)) {\n const relationAttribute = newAttribute as InternalRelationAttribute;\n const oldRelationAttribute = oldAttribute as InternalRelationAttribute;\n const oldTargetAttributeName =\n oldRelationAttribute.inversedBy || oldRelationAttribute.mappedBy;\n\n const sameRelation = oldAttribute.relation === relationAttribute.relation;\n const targetAttributeHasChanged =\n oldTargetAttributeName !== relationAttribute.targetAttribute;\n\n if (!sameRelation || targetAttributeHasChanged) {\n this.unsetRelation(oldAttribute);\n }\n\n // keep extra options that were set manually on oldAttribute\n reuseUnsetPreviousProperties(relationAttribute, oldAttribute);\n\n // Handle conditions explicitly - only preserve if present and not undefined in new attribute\n const newAttributeFromInfos = newAttributes[key];\n const hasNewConditions =\n newAttributeFromInfos.conditions !== undefined &&\n newAttributeFromInfos.conditions !== null;\n\n if (oldAttribute.conditions) {\n if (hasNewConditions) {\n // Conditions are still present, keep them\n relationAttribute.conditions = newAttributeFromInfos.conditions;\n } else {\n // Conditions were removed (undefined or null), ensure they're not preserved\n delete relationAttribute.conditions;\n }\n } else if (hasNewConditions) {\n // New conditions added\n relationAttribute.conditions = newAttributeFromInfos.conditions;\n }\n\n if (oldRelationAttribute.inversedBy) {\n relationAttribute.dominant = true;\n } else if (oldRelationAttribute.mappedBy) {\n relationAttribute.dominant = false;\n }\n\n return this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n // add new relations\n newKeys.forEach((key) => {\n const attribute = newAttributes[key] as InternalAttribute;\n\n if (isRelation(attribute)) {\n const relationAttribute = attribute as InternalRelationAttribute;\n if (['manyToMany', 'oneToOne'].includes(relationAttribute.relation)) {\n // A renamed relation keeps the ownership of the attribute it was\n // renamed from (same rule as a remaining key), so the join table\n // stays with its owner and the rename migration can carry it.\n const origin = renameOrigins.get(key);\n const originAttribute =\n origin !== undefined && _.has(oldAttributes, origin)\n ? (oldAttributes[origin] as InternalRelationAttribute)\n : undefined;\n const originOwnership =\n originAttribute !== undefined &&\n isRelation(originAttribute) &&\n originAttribute.relation === relationAttribute.relation &&\n originAttribute.target === relationAttribute.target\n ? originAttribute\n : undefined;\n\n if (originOwnership?.inversedBy) {\n relationAttribute.dominant = true;\n } else if (originOwnership?.mappedBy) {\n relationAttribute.dominant = false;\n } else if (\n relationAttribute.target === uid &&\n relationAttribute.targetAttribute !== undefined\n ) {\n // self referencing relation\n const targetAttribute = newAttributes[\n relationAttribute.targetAttribute\n ] as InternalRelationAttribute;\n\n if (targetAttribute.dominant === undefined) {\n relationAttribute.dominant = true;\n } else {\n relationAttribute.dominant = false;\n }\n } else {\n relationAttribute.dominant = true;\n }\n }\n\n this.setRelation({\n key,\n uid,\n attribute: relationAttribute,\n });\n }\n });\n\n contentType\n .set('kind', infos.kind || contentType.schema.kind)\n .set(['info', 'displayName'], infos.displayName)\n .set(['info', 'description'], infos.description)\n .set('options', {\n ...infos.options,\n draftAndPublish: infos.draftAndPublish,\n })\n .set('pluginOptions', infos.pluginOptions)\n .setAttributes(this.convertAttributes(newAttributes));\n\n return contentType;\n },\n\n deleteContentType(this: any, uid: string) {\n if (!this.contentTypes.has(uid)) {\n throw new ApplicationError('contentType.notFound');\n }\n\n this.components.forEach((compo: any) => {\n compo.removeContentType(uid);\n });\n\n this.contentTypes.forEach((ct: any) => {\n ct.removeContentType(uid);\n });\n\n return this.contentTypes.get(uid).delete();\n },\n };\n}\n\n/**\n * Returns a uid from a content type infos\n *\n * @param {object} options options\n * @param {string} options.singularName content-type singularName\n * @returns {string} uid\n */\nconst createContentTypeUID = ({\n plugin,\n singularName,\n}: {\n plugin?: string;\n singularName: string;\n}): Internal.UID.ContentType =>\n `${plugin ? `plugin` : `api`}::${plugin || singularName}.${singularName}`;\n\nconst generateRelation = ({\n key,\n attribute,\n uid,\n targetAttribute = {},\n}: {\n key: string;\n attribute: InternalRelationAttribute;\n uid: string;\n targetAttribute?: Partial<InternalRelationAttribute>;\n}) => {\n const opts: any = {\n type: 'relation',\n target: uid,\n required: targetAttribute.required || undefined,\n private: targetAttribute.private || undefined,\n pluginOptions: targetAttribute.pluginOptions || undefined,\n // Preserve conditions from targetAttribute if they exist\n // This allows each side of the relation to maintain its own conditions\n ...(targetAttribute.conditions && { conditions: targetAttribute.conditions }),\n };\n\n switch (attribute.relation) {\n case 'oneToOne': {\n opts.relation = 'oneToOne';\n\n if (attribute.dominant) {\n opts.mappedBy = key;\n } else {\n opts.inversedBy = key;\n }\n break;\n }\n case 'oneToMany': {\n opts.relation = 'manyToOne';\n opts.inversedBy = key;\n break;\n }\n case 'manyToOne': {\n opts.relation = 'oneToMany';\n opts.mappedBy = key;\n break;\n }\n case 'manyToMany': {\n opts.relation = 'manyToMany';\n\n if (attribute.dominant) {\n opts.mappedBy = key;\n } else {\n opts.inversedBy = key;\n }\n\n break;\n }\n default:\n }\n\n // we do this just to make sure we have the same key order when writing to files\n const { type, relation, target, ...restOptions } = opts;\n\n const result = {\n type,\n relation,\n target,\n ...restOptions,\n };\n\n return result;\n};\n"],"names":["ApplicationError","errors","reuseUnsetPreviousProperties","newAttribute","oldAttribute","_","defaults","omit","getRenameOrigins","renames","originOf","Map","Array","isArray","oldName","newName","origin","get","delete","set","createComponentBuilder","setRelation","key","uid","attribute","has","targetCT","contentTypes","target","targetAttribute","getAttribute","targetAttributeData","setAttribute","generateRelation","unsetRelation","relationAttribute","targetAttributeName","inversedBy","mappedBy","deleteAttribute","createContentTypeAttributes","attributes","contentType","Object","keys","forEach","setAttributes","convertAttributes","isRelation","includes","relation","undefined","dominant","createContentType","infos","createContentTypeUID","dir","plugin","path","join","strapi","dirs","app","extensions","singularName","api","createSchemaHandler","modelName","filename","setUID","kind","typeKinds","COLLECTION_TYPE","collectionName","strings","nameToCollectionName","pluralName","displayName","description","options","draftAndPublish","pluginOptions","config","editContentType","oldAttributes","schema","newAttributes","omitBy","attr","isConfigurable","newKeys","difference","deletedKeys","remainingKeys","intersection","renameOrigins","oldRelationAttribute","oldTargetAttributeName","sameRelation","targetAttributeHasChanged","newAttributeFromInfos","hasNewConditions","conditions","originAttribute","originOwnership","deleteContentType","components","compo","removeContentType","ct","opts","type","required","private","restOptions","result"],"mappings":";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if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n.default = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ var fse__namespace = /*#__PURE__*/_interopNamespace(fse);
24
+
3
25
  const finalizeSchemaMutation = async ({ apiHandler, backedUpApiUids = [] })=>{
4
26
  const errors = [];
5
27
  for (const uid of backedUpApiUids){
@@ -12,10 +34,11 @@ const finalizeSchemaMutation = async ({ apiHandler, backedUpApiUids = [] })=>{
12
34
  return errors;
13
35
  };
14
36
  /**
15
- * Restores the filesystem artifacts touched before content-structure reconciliation.
37
+ * Restores the filesystem artifacts touched before content-structure reconciliation: the
38
+ * generated rename migration, generated APIs, the schema files and API backups.
16
39
  * Folder reconciliation is deliberately the final mutation, so groups.json never needs a
17
40
  * compensating write when an earlier schema or API operation fails.
18
- */ const rollbackSchemaMutation = async ({ builder, apiHandler, backedUpApiUids = [], generatedApiNames = [], schemaAlreadyRolledBack = false })=>{
41
+ */ const rollbackSchemaMutation = async ({ builder, apiHandler, backedUpApiUids = [], generatedApiNames = [], schemaAlreadyRolledBack = false, migrationFilePath = null })=>{
19
42
  const errors = [];
20
43
  const attempt = async (operation)=>{
21
44
  try {
@@ -24,6 +47,11 @@ const finalizeSchemaMutation = async ({ apiHandler, backedUpApiUids = [] })=>{
24
47
  errors.push(error);
25
48
  }
26
49
  };
50
+ // The rename migration is written before the schema files. Remove it first so a rejected
51
+ // save never leaves a migration that would rename columns on the next boot.
52
+ if (migrationFilePath) {
53
+ await attempt(()=>fse__namespace.remove(migrationFilePath));
54
+ }
27
55
  // A generator can fail before a schema directory exists, so remove its partial API before
28
56
  // asking the schema handler to roll back. Every action is attempted even if an earlier one
29
57
  // fails, ensuring compensation is best-effort rather than short-circuiting.
@@ -1 +1 @@
1
- {"version":3,"file":"schema-mutation.js","sources":["../../../server/src/services/schema-mutation.ts"],"sourcesContent":["type SchemaBuilder = {\n rollback(): Promise<unknown>;\n};\n\ntype ApiHandler = {\n rollback(uid: string): Promise<void>;\n clearGenerated(apiName: string): Promise<void>;\n finalize(uid: string): Promise<void>;\n};\n\nexport const finalizeSchemaMutation = async ({\n apiHandler,\n backedUpApiUids = [],\n}: {\n apiHandler: ApiHandler;\n backedUpApiUids?: string[];\n}) => {\n const errors: unknown[] = [];\n\n for (const uid of backedUpApiUids) {\n try {\n await apiHandler.finalize(uid);\n } catch (error) {\n errors.push(error);\n }\n }\n\n return errors;\n};\n\n/**\n * Restores the filesystem artifacts touched before content-structure reconciliation.\n * Folder reconciliation is deliberately the final mutation, so groups.json never needs a\n * compensating write when an earlier schema or API operation fails.\n */\nexport const rollbackSchemaMutation = async ({\n builder,\n apiHandler,\n backedUpApiUids = [],\n generatedApiNames = [],\n schemaAlreadyRolledBack = false,\n}: {\n builder: SchemaBuilder;\n apiHandler: ApiHandler;\n backedUpApiUids?: string[];\n generatedApiNames?: string[];\n schemaAlreadyRolledBack?: boolean;\n}) => {\n const errors: unknown[] = [];\n const attempt = async (operation: () => Promise<unknown>) => {\n try {\n await operation();\n } catch (error) {\n errors.push(error);\n }\n };\n\n // A generator can fail before a schema directory exists, so remove its partial API before\n // asking the schema handler to roll back. Every action is attempted even if an earlier one\n // fails, ensuring compensation is best-effort rather than short-circuiting.\n for (const apiName of generatedApiNames) {\n await attempt(() => apiHandler.clearGenerated(apiName));\n }\n\n if (!schemaAlreadyRolledBack) {\n await attempt(() => builder.rollback());\n }\n\n for (const uid of backedUpApiUids) {\n await attempt(() => apiHandler.rollback(uid));\n }\n\n if (errors.length > 0) {\n throw errors[0];\n }\n};\n"],"names":["finalizeSchemaMutation","apiHandler","backedUpApiUids","errors","uid","finalize","error","push","rollbackSchemaMutation","builder","generatedApiNames","schemaAlreadyRol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AAC1C,IAAA;IAEA,IAAID,MAAAA,CAAOc,MAAM,GAAG,CAAA,EAAG;QACrB,MAAMd,MAAM,CAAC,CAAA,CAAE;AACjB,IAAA;AACF;;;;;"}
1
+ {"version":3,"file":"schema-mutation.js","sources":["../../../server/src/services/schema-mutation.ts"],"sourcesContent":["import * as fse from 'fs-extra';\n\ntype SchemaBuilder = {\n rollback(): Promise<unknown>;\n};\n\ntype ApiHandler = {\n rollback(uid: string): Promise<void>;\n clearGenerated(apiName: string): Promise<void>;\n finalize(uid: string): Promise<void>;\n};\n\nexport const finalizeSchemaMutation = async ({\n apiHandler,\n backedUpApiUids = [],\n}: {\n apiHandler: ApiHandler;\n backedUpApiUids?: string[];\n}) => {\n const errors: unknown[] = [];\n\n for (const uid of backedUpApiUids) {\n try {\n await apiHandler.finalize(uid);\n } catch (error) {\n errors.push(error);\n }\n }\n\n return errors;\n};\n\n/**\n * Restores the filesystem artifacts touched before content-structure reconciliation: the\n * generated rename migration, generated APIs, the schema files and API backups.\n * Folder reconciliation is deliberately the final mutation, so groups.json never needs a\n * compensating write when an earlier schema or API operation fails.\n */\nexport const rollbackSchemaMutation = async ({\n builder,\n apiHandler,\n backedUpApiUids = [],\n generatedApiNames = [],\n schemaAlreadyRolledBack = false,\n migrationFilePath = null,\n}: {\n builder: SchemaBuilder;\n apiHandler: ApiHandler;\n backedUpApiUids?: string[];\n generatedApiNames?: string[];\n schemaAlreadyRolledBack?: boolean;\n migrationFilePath?: string | null;\n}) => {\n const errors: unknown[] = [];\n const attempt = async (operation: () => Promise<unknown>) => {\n try {\n await operation();\n } catch (error) {\n errors.push(error);\n }\n };\n\n // The rename migration is written before the schema files. Remove it first so a rejected\n // save never leaves a migration that would rename columns on the next boot.\n if (migrationFilePath) {\n await attempt(() => fse.remove(migrationFilePath));\n }\n\n // A generator can fail before a schema directory exists, so remove its partial API before\n // asking the schema handler to roll back. Every action is attempted even if an earlier one\n // fails, ensuring compensation is best-effort rather than short-circuiting.\n for (const apiName of generatedApiNames) {\n await attempt(() => apiHandler.clearGenerated(apiName));\n }\n\n if (!schemaAlreadyRolledBack) {\n await attempt(() => builder.rollback());\n }\n\n for (const uid of backedUpApiUids) {\n await attempt(() => apiHandler.rollback(uid));\n }\n\n if (errors.length > 0) {\n throw errors[0];\n }\n};\n"],"names":["finalizeSchemaMutation","apiHandler","backedUpApiUids","errors","uid","finalize","error","push","rollbackSchemaMutation","builder","generatedApiNames","schemaAlreadyRolledBack","migrationFilePath","attempt","operation","fse","remove","apiName","clearGenerated","rollback","length"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAYO,MAAMA,yBAAyB,OAAO,EAC3CC,UAAU,EACVC,eAAAA,GAAkB,EAAE,EAIrB,GAAA;AACC,IAAA,MAAMC,SAAoB,EAAE;IAE5B,KAAK,MAAMC,OAAOF,eAAAA,CAAiB;QACjC,IAAI;YACF,MAAMD,UAAAA,CAAWI,QAAQ,CAACD,GAAAA,CAAAA;AAC5B,QAAA,CAAA,CAAE,OAAOE,KAAAA,EAAO;AACdH,YAAAA,MAAAA,CAAOI,IAAI,CAACD,KAAAA,CAAAA;AACd,QAAA;AACF,IAAA;IAEA,OAAOH,MAAAA;AACT;AAEA;;;;;UAMaK,sBAAAA,GAAyB,OAAO,EAC3CC,OAAO,EACPR,UAAU,EACVC,eAAAA,GAAkB,EAAE,EACpBQ,iBAAAA,GAAoB,EAAE,EACtBC,uBAAAA,GAA0B,KAAK,EAC/BC,iBAAAA,GAAoB,IAAI,EAQzB,GAAA;AACC,IAAA,MAAMT,SAAoB,EAAE;AAC5B,IAAA,MAAMU,UAAU,OAAOC,SAAAA,GAAAA;QACrB,IAAI;YACF,MAAMA,SAAAA,EAAAA;AACR,QAAA,CAAA,CAAE,OAAOR,KAAAA,EAAO;AACdH,YAAAA,MAAAA,CAAOI,IAAI,CAACD,KAAAA,CAAAA;AACd,QAAA;AACF,IAAA,CAAA;;;AAIA,IAAA,IAAIM,iBAAAA,EAAmB;AACrB,QAAA,MAAMC,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