{"version":3,"file":"index.mjs","sources":["../../../../server/src/services/schema-builder/index.ts"],"sourcesContent":["import { join } from 'path';\nimport _ from 'lodash';\nimport type { Internal } from '@strapi/types';\n\nimport { errors } from '@strapi/utils';\nimport createSchemaHandler, { type SchemaHandler } from './schema-handler';\nimport createComponentBuilder from './component-builder';\nimport createContentTypeBuilder from './content-type-builder';\nimport { renameComponentUIDs, type RenameComponentUIDsOptions } from './rename-component-uids';\n\n/**\n * Creates a content type schema builder instance\n */\nexport default function createBuilder() {\n  const components = Object.values(strapi.components).map((componentInput) => ({\n    category: componentInput.category,\n    modelName: componentInput.modelName,\n    uid: componentInput.uid,\n    filename: componentInput.__filename__,\n    dir: join(strapi.dirs.app.components, componentInput.category),\n    // The loader adds `__filename__` to the loaded schema; it is not part of the file, and a\n    // rollback writes this schema back to the file\n    schema: _.omit(componentInput.__schema__, '__filename__'),\n    config: componentInput.config,\n  }));\n\n  const contentTypes = Object.values<any>(strapi.contentTypes).map((contentTypeInput) => {\n    const dir = contentTypeInput.plugin\n      ? join(\n          strapi.dirs.app.extensions,\n          contentTypeInput.plugin,\n          'content-types',\n          contentTypeInput.info.singularName\n        )\n      : join(\n          strapi.dirs.app.api,\n          contentTypeInput.apiName,\n          'content-types',\n          contentTypeInput.info.singularName\n        );\n\n    return {\n      modelName: contentTypeInput.modelName,\n      plugin: contentTypeInput.plugin,\n      uid: contentTypeInput.uid,\n      filename: 'schema.json',\n      dir,\n      schema: contentTypeInput.__schema__,\n      config: contentTypeInput.config,\n    };\n  });\n\n  return createSchemaBuilder({\n    components,\n    contentTypes,\n  });\n}\n\ntype SchemaBuilderOptions = {\n  components: any;\n  contentTypes: any;\n};\n\nfunction createSchemaBuilder({ components, contentTypes }: SchemaBuilderOptions) {\n  const tmpComponents = new Map<Internal.UID.Component, SchemaHandler<Internal.UID.Component>>();\n  const tmpContentTypes = new Map();\n\n  // init temporary ContentTypes\n  Object.keys(contentTypes).forEach((key) => {\n    tmpContentTypes.set(contentTypes[key].uid, createSchemaHandler(contentTypes[key]));\n  });\n\n  // init temporary components\n  Object.keys(components).forEach((key) => {\n    tmpComponents.set(\n      components[key].uid,\n      createSchemaHandler<Internal.UID.Component>(components[key])\n    );\n  });\n\n  return {\n    get components() {\n      return tmpComponents;\n    },\n    get contentTypes() {\n      return tmpContentTypes;\n    },\n\n    /**\n     * Convert Attributes received from the API to the right syntax\n     */\n    convertAttributes(attributes: any) {\n      return Object.keys(attributes).reduce(\n        (acc, key) => {\n          acc[key] = this.convertAttribute(attributes[key]);\n          return acc;\n        },\n        {} as Record<string, unknown>\n      );\n    },\n\n    convertAttribute(attribute: any) {\n      const { configurable, private: isPrivate, conditions } = attribute;\n\n      const baseProperties = {\n        private: isPrivate === true ? true : undefined,\n        configurable: configurable === false ? false : undefined,\n        // IMPORTANT: Preserve conditions only if they exist and are not undefined/null\n        ...(conditions !== undefined && conditions !== null && { conditions }),\n      };\n\n      if (attribute.type === 'relation') {\n        const { target, relation, targetAttribute, dominant, ...restOfProperties } = attribute;\n\n        const attr = {\n          type: 'relation',\n          relation,\n          target,\n          ...restOfProperties,\n          ...baseProperties,\n        };\n\n        // TODO: uncomment this when we pre-create empty types and targets exists if we create multiple types at once\n        // if (target && !this.contentTypes.has(target)) {\n        //   throw new errors.ApplicationError(`target: ${target} does not exist`);\n        // }\n\n        if (_.isNil(targetAttribute)) {\n          return attr;\n        }\n\n        if (['oneToOne', 'manyToMany'].includes(relation) && dominant === true) {\n          attr.inversedBy = targetAttribute;\n        } else if (['oneToOne', 'manyToMany'].includes(relation) && dominant === false) {\n          attr.mappedBy = targetAttribute;\n        } else if (['oneToOne', 'manyToOne', 'manyToMany'].includes(relation)) {\n          attr.inversedBy = targetAttribute;\n        } else if (['oneToMany'].includes(relation)) {\n          attr.mappedBy = targetAttribute;\n        }\n\n        return attr;\n      }\n\n      return {\n        ...attribute,\n        ...baseProperties,\n      };\n    },\n\n    ...createComponentBuilder(),\n    ...createContentTypeBuilder(),\n\n    /**\n     * Write all type to files, then rewrite the database rows that store a renamed\n     * component uid (see `renameComponentRows`).\n     *\n     * Pass `{ renameComponentRows: false }` to only write the files. The caller must then\n     * call `renameComponentRows` itself, before the reload, and roll the files back if it\n     * throws. Do that when a later step must succeed together with the rows: run that\n     * step through `renameComponentRows({ beforeCommit })`, so that its failure rolls the\n     * rows back too.\n     *\n     * @returns boolean true if all files have been written correctly, false if an error\n     * occurred while writing them (the files are rolled back)\n     * @throws ApplicationError if the row rewrite failed (the files are rolled back) or if\n     * a rollback failed\n     */\n    async writeFiles({ renameComponentRows = true }: { renameComponentRows?: boolean } = {}) {\n      const schemas = [\n        ...Array.from(tmpComponents.values()),\n        ...Array.from(tmpContentTypes.values()),\n      ];\n\n      // Wait for every write to settle before rolling back, or a write still running would\n      // land after the rollback (e.g. leave a created file on disk)\n      const results = await Promise.allSettled(schemas.map((schema) => schema.flush()));\n      const failure = results.find(\n        (result): result is PromiseRejectedResult => result.status === 'rejected'\n      );\n\n      if (failure !== undefined) {\n        strapi.log.error('Error writing schema files');\n        strapi.log.error(failure.reason);\n\n        try {\n          await this.rollback();\n        } catch (error) {\n          strapi.log.error(\n            'Error rolling back schema files. You might need to fix your files manually'\n          );\n          strapi.log.error(error);\n\n          throw new errors.ApplicationError('Invalid schema edition');\n        }\n\n        return false;\n      }\n\n      if (renameComponentRows === false) {\n        return true;\n      }\n\n      try {\n        await this.renameComponentRows();\n      } catch (error) {\n        // The transaction already restored the rows. Restore the files too, or the next\n        // reload would load the new uids against rows still holding the old ones.\n        strapi.log.error('Error rewriting the rows of the renamed components');\n        strapi.log.error(error);\n\n        try {\n          await this.rollback();\n        } catch (rollbackError) {\n          strapi.log.error(\n            'Error rolling back schema files. You might need to fix your files manually'\n          );\n          strapi.log.error(rollbackError);\n        }\n\n        throw new errors.ApplicationError('Invalid schema edition');\n      }\n\n      return true;\n    },\n\n    /**\n     * A component uid change (category move or rename) is also stored in the database:\n     * as `component_type` in the `*_cmps` join tables and as the type column of the\n     * polymorphic join tables (e.g. media in `files_related_mph`). Rewrites those rows in\n     * one transaction. Must run while the running process still holds the pre-rename\n     * metadata that locates them, i.e. before the reload.\n     *\n     * `beforeCommit` runs inside that transaction, after the rewrite and before the\n     * commit (also when no uid changed). If it rejects, the rows are rolled back. It must\n     * not use the database (see `renameComponentUIDs`).\n     *\n     * @throws if the rewrite or `beforeCommit` failed; the transaction has then restored\n     * the rows\n     */\n    async renameComponentRows({ beforeCommit }: RenameComponentUIDsOptions = {}) {\n      const componentUIDRenames = Array.from(tmpComponents.values())\n        .filter((component) => component.initialUID && component.uid !== component.initialUID)\n        .map((component) => ({ oldUID: component.initialUID, newUID: component.uid }));\n\n      await renameComponentUIDs(strapi.db, componentUIDRenames, { beforeCommit });\n    },\n\n    /**\n     * rollback all files\n     */\n    rollback() {\n      return Promise.all(\n        [...Array.from(tmpComponents.values()), ...Array.from(tmpContentTypes.values())].map(\n          (schema) => schema.rollback()\n        )\n      );\n    },\n  };\n}\n"],"names":["createBuilder","components","Object","values","strapi","map","componentInput","category","modelName","uid","filename","__filename__","dir","join","dirs","app","schema","_","omit","__schema__","config","contentTypes","contentTypeInput","plugin","extensions","info","singularName","api","apiName","createSchemaBuilder","tmpComponents","Map","tmpContentTypes","keys","forEach","key","set","createSchemaHandler","convertAttributes","attributes","reduce","acc","convertAttribute","attribute","configurable","private","isPrivate","conditions","baseProperties","undefined","type","target","relation","targetAttribute","dominant","restOfProperties","attr","isNil","includes","inversedBy","mappedBy","createComponentBuilder","createContentTypeBuilder","writeFiles","renameComponentRows","schemas","Array","from","results","Promise","allSettled","flush","failure","find","result","status","log","error","reason","rollback","errors","ApplicationError","rollbackError","beforeCommit","componentUIDRenames","filter","component","initialUID","oldUID","newUID","renameComponentUIDs","db","all"],"mappings":";;;;;;;;AAUA;;AAEC,IACc,SAASA,aAAAA,GAAAA;IACtB,MAAMC,UAAAA,GAAaC,MAAAA,CAAOC,MAAM,CAACC,MAAAA,CAAOH,UAAU,CAAA,CAAEI,GAAG,CAAC,CAACC,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