{"version":3,"file":"relations-orderer.mjs","sources":["../../src/entity-manager/relations-orderer.ts"],"sourcesContent":["import _, { castArray, maxBy } from 'lodash';\n\nimport { InvalidRelationError } from '../errors';\nimport type { ID } from '../types';\n\ninterface Link {\n  id: ID;\n  position?: { before?: ID; after?: ID; start?: true; end?: true };\n  order?: number;\n  __component?: string;\n}\n\ninterface OrderedLink extends Link {\n  init?: boolean;\n  order: number;\n}\n\n/**\n * When connecting relations, the order you connect them matters.\n *\n * Example, if you connect the following relations:\n *   { id: 5, position: { before: 1 } }\n *   { id: 1, position: { before: 2 } }\n *   { id: 2, position: { end: true } }\n *\n * Going through the connect array, id 5 has to be connected before id 1,\n * so the order of id5 = id1 - 1. But the order value of id 1 is unknown.\n * The only way to know the order of id 1 is to connect it first.\n *\n * This function makes sure the relations are connected in the right order:\n *   { id: 2, position: { end: true } }\n *   { id: 1, position: { before: 2 } }\n *   { id: 5, position: { before: 1 } }\n *\n */\nconst sortConnectArray = (connectArr: Link[], initialArr: Link[] = [], strictSort = true) => {\n  const sortedConnect: Link[] = [];\n  // Boolean to know if we have to recalculate the order of the relations\n  let needsSorting = false;\n  // Map to validate if relation is already in sortedConnect or DB.\n  const relationInInitialArray: Record<ID, boolean> = {};\n  initialArr.forEach((rel) => {\n    relationInInitialArray[rel.id] = true;\n  });\n  // Map to store the first index where a relation id is connected\n  // Mutated in place: spreading the accumulator on every item is O(n^2)\n  const mappedRelations = connectArr.reduce(\n    (mapper, relation: Link) => {\n      const adjacentRelId = relation.position?.before || relation.position?.after;\n\n      if (!adjacentRelId || (!relationInInitialArray[adjacentRelId] && !mapper[adjacentRelId])) {\n        needsSorting = true;\n      }\n\n      /**\n       * We do not allow duplicate relations to be connected, so we need to check for uniqueness with components\n       * Note that the id here includes the uid for polymorphic relations\n       *\n       * So for normal relations, the same id means the same relation\n       * For component relations, it means the unique combo of (id, component name)\n       */\n\n      // Check if there's an existing relation with this id\n      const existingRelation = mapper[relation.id];\n\n      // Check if existing relation has a component or not\n      const hasNoComponent = existingRelation && !('__component' in existingRelation);\n\n      // Check if the existing relation has the same component as the new relation\n      const hasSameComponent =\n        existingRelation && existingRelation.__component === relation.__component;\n\n      // If we have an existing relation that is not unique (no component or same component) we won't accept it\n      if (existingRelation && (hasNoComponent || hasSameComponent)) {\n        throw new InvalidRelationError(\n          `The relation with id ${relation.id} is already connected. ` +\n            'You cannot connect the same relation twice.'\n        );\n      }\n\n      // The first occurrence of an id wins\n      if (!existingRelation) {\n        mapper[relation.id] = { ...relation, computed: false };\n      }\n\n      return mapper;\n    },\n    {} as Record<ID, Link & { computed: boolean }>\n  );\n\n  // If we don't need to sort the connect array, we can return it as is\n  if (!needsSorting) return connectArr;\n\n  // Compute in which order the relation should be connected. Walks the chain of adjacent\n  // relations iteratively: a recursive walk overflows the stack on long before/after chains.\n  const computeRelation = (startRelation: Link) => {\n    // Relations of the current branch, waiting for their adjacent relation to be connected first\n    const branch: Link[] = [];\n    const relationsSeenInBranch: Record<ID, boolean> = {};\n    let relation = startRelation;\n\n    for (;;) {\n      const adjacentRelId = relation.position?.before || relation.position?.after;\n\n      // If the relation has already been seen in the current branch,\n      // it means there is a circular reference\n      if (adjacentRelId && relationsSeenInBranch[adjacentRelId]) {\n        throw new InvalidRelationError(\n          'A circular reference was found in the connect array. ' +\n            'One relation is trying to connect before/after another one that is trying to connect before/after it'\n        );\n      }\n\n      // This relation has already been computed\n      if (mappedRelations[relation.id]?.computed) {\n        break;\n      }\n\n      mappedRelations[relation.id].computed = true;\n\n      // Relation does not have a before or after attribute or is in the initial array\n      if (!adjacentRelId || relationInInitialArray[adjacentRelId]) {\n        sortedConnect.push(relation);\n        break;\n      }\n\n      // Look if id is referenced elsewhere in the array\n      if (mappedRelations[adjacentRelId]) {\n        relationsSeenInBranch[relation.id] = true;\n        branch.push(relation);\n        relation = mappedRelations[adjacentRelId];\n      } else if (strictSort) {\n        // If we reach this point, it means that the adjacent relation is not in the connect array\n        // and it is not in the database.\n        throw new InvalidRelationError(\n          `There was a problem connecting relation with id ${\n            relation.id\n          } at position ${JSON.stringify(\n            relation.position\n          )}. The relation with id ${adjacentRelId} needs to be connected first.`\n        );\n      } else {\n        // We are in non-strict mode so we can push the relation.\n        sortedConnect.push({ id: relation.id, position: { end: true } });\n        break;\n      }\n    }\n\n    // Each relation of the branch is connected after its adjacent relation\n    for (let i = branch.length - 1; i >= 0; i -= 1) {\n      sortedConnect.push(branch[i]);\n    }\n  };\n\n  // Iterate over connectArr and populate sortedConnect\n  connectArr.forEach((relation) => computeRelation(relation));\n\n  return sortedConnect;\n};\n\n/**\n * Responsible for calculating the relations order when connecting them.\n *\n * The connect method takes an array of relations with positional attributes:\n * - before: the id of the relation to connect before\n * - after: the id of the relation to connect after\n * - end: it should be at the end\n * - start: it should be at the start\n *\n * Example:\n *  - Having a connect array like:\n *      [ { id: 4, before: 2 }, { id: 4, before: 3}, {id: 5, before: 4} ]\n * - With the initial relations:\n *      [ { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * - Step by step, going through the connect array, the array of relations would be:\n *      [ { id: 4, order: 3.5 }, { id: 2, order: 4 }, { id: 3, order: 10 } ]\n *      [ { id: 2, order: 4 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n *      [ { id: 2, order: 4 }, { id: 5, order: 3.5 },  { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * - The final step would be to recalculate fractional order values.\n *      [ { id: 2, order: 4 }, { id: 5, order: 3.33 },  { id: 4, order: 3.66 }, { id: 3, order: 10 } ]\n *\n * `initArr` is not the full relation list. For an ordered connect, `updateRelations` loads only\n * the rows named as anchors by the payload plus the lowest- and highest-ordered rows, so entries\n * that are adjacent in `computedRelations` are not adjacent in the stored list. Placement must be\n * computed from the anchor's own order, never from its neighbours in this array.\n *\n * @param {Array<*>} initArr - array of relations to initialize the class with\n * @param {string} idColumn - the column name of the id\n * @param {string} orderColumn - the column name of the order\n * @param {boolean} strict - if true, will throw an error if a relation is connected adjacent to\n *                               another one that does not exist\n * @return {*}\n */\nconst relationsOrderer = <TRelation extends Record<string, ID | number | null>>(\n  initArr: TRelation[],\n  idColumn: keyof TRelation,\n  orderColumn: keyof TRelation,\n  strict?: boolean\n) => {\n  const initialRelations: OrderedLink[] = _.sortBy(\n    castArray(initArr ?? []).map((r) => ({\n      init: true,\n      id: r[idColumn] as ID,\n      order: r[orderColumn] !== null && r[orderColumn] !== undefined ? Number(r[orderColumn]) : 1,\n    })),\n    'order'\n  );\n\n  const maxOrder = maxBy(initialRelations, 'order')?.order || 0;\n\n  // The relations are kept in a doubly linked list indexed by id, so that finding, removing and\n  // inserting a relation next to another one does not scan or shift an array: an array made\n  // connecting n positioned relations O(n^2).\n  interface RelationNode {\n    relation: OrderedLink;\n    prev: RelationNode | null;\n    next: RelationNode | null;\n  }\n\n  let head: RelationNode | null = null;\n  let tail: RelationNode | null = null;\n  const nodesById = new Map<ID, RelationNode[]>();\n\n  const linkNode = (relation: OrderedLink, before: RelationNode | null) => {\n    const node: RelationNode = { relation, prev: null, next: before };\n\n    if (before) {\n      node.prev = before.prev;\n      before.prev = node;\n    } else {\n      node.prev = tail;\n      tail = node;\n    }\n\n    if (node.prev) {\n      node.prev.next = node;\n    } else {\n      head = node;\n    }\n\n    const nodes = nodesById.get(relation.id);\n    if (nodes) {\n      nodes.push(node);\n    } else {\n      nodesById.set(relation.id, [node]);\n    }\n  };\n\n  const unlinkNode = (node: RelationNode) => {\n    if (node.prev) {\n      node.prev.next = node.next;\n    } else {\n      head = node.next;\n    }\n\n    if (node.next) {\n      node.next.prev = node.prev;\n    } else {\n      tail = node.prev;\n    }\n\n    const nodes = nodesById.get(node.relation.id)!;\n    nodes.splice(nodes.indexOf(node), 1);\n    if (nodes.length === 0) {\n      nodesById.delete(node.relation.id);\n    }\n  };\n\n  // The first node holding this id, in list order\n  const findNode = (id: ID): RelationNode | undefined => {\n    const nodes = nodesById.get(id);\n\n    if (!nodes || nodes.length <= 1) {\n      return nodes?.[0];\n    }\n\n    // Only reached when the same id is in the list more than once\n    for (let node = head; node; node = node.next) {\n      if (node.relation.id === id) {\n        return node;\n      }\n    }\n\n    return undefined;\n  };\n\n  const toArray = () => {\n    const relations: OrderedLink[] = [];\n    for (let node = head; node; node = node.next) {\n      relations.push(node.relation);\n    }\n    return relations;\n  };\n\n  initialRelations.forEach((relation) => linkNode(relation, null));\n\n  const removeRelation = (r: Link) => {\n    const node = findNode(r.id);\n    if (node) {\n      unlinkNode(node);\n    }\n  };\n\n  const insertRelation = (r: Link) => {\n    // The node the relation is inserted before, null to insert it at the end\n    let beforeNode: RelationNode | null;\n\n    if (r.position?.before) {\n      const node = findNode(r.position.before);\n      if (!node) {\n        throw new Error(`Relation ${r.position.before} is not connected`);\n      }\n\n      const { relation } = node;\n      if (relation.init) {\n        r.order = relation.order - 0.5;\n      } else {\n        r.order = relation.order;\n      }\n      beforeNode = node;\n    } else if (r.position?.after) {\n      const node = findNode(r.position.after);\n      if (!node) {\n        throw new Error(`Relation ${r.position.after} is not connected`);\n      }\n\n      const { relation } = node;\n      if (relation.init) {\n        r.order = relation.order + 0.5;\n      } else {\n        r.order = relation.order;\n      }\n      beforeNode = node.next;\n    } else if (r.position?.start) {\n      if (head) {\n        const firstRelation = head.relation;\n        r.order = firstRelation.init ? firstRelation.order - 0.5 : firstRelation.order;\n      } else {\n        r.order = 0.5;\n      }\n      beforeNode = head;\n    } else {\n      r.order = maxOrder + 0.5;\n      beforeNode = null;\n    }\n\n    linkNode(r as OrderedLink, beforeNode);\n  };\n\n  return {\n    disconnect(relations: Link | Link[]) {\n      castArray(relations).forEach((relation) => {\n        removeRelation(relation);\n      });\n      return this;\n    },\n    connect(relations: Link | Link[]) {\n      sortConnectArray(castArray(relations), toArray(), strict).forEach((relation) => {\n        this.disconnect(relation);\n\n        try {\n          insertRelation(relation);\n        } catch {\n          throw new Error(\n            `There was a problem connecting relation with id ${\n              relation.id\n            } at position ${JSON.stringify(\n              relation.position\n            )}. The list of connect relations is not valid`\n          );\n        }\n      });\n      return this;\n    },\n    get() {\n      return toArray();\n    },\n    /**\n     * Get a map between the relation id and its order\n     */\n    getOrderMap() {\n      const map: Record<ID, number> = {};\n      const chunks = _(toArray()).groupBy('order').value();\n      const sortedKeys = Object.keys(chunks).sort((a, b) => parseFloat(a) - parseFloat(b));\n\n      for (const orderStr of sortedKeys) {\n        const relations = chunks[orderStr];\n        let offset = 1;\n        relations.forEach((relation) => {\n          if (!relation.init) {\n            map[relation.id] = parseFloat(orderStr) + (offset / (relations.length + 1)) * 0.49;\n            offset += 1;\n          }\n        });\n      }\n\n      return map;\n    },\n  };\n};\n\nexport { relationsOrderer, sortConnectArray };\n"],"names":["sortConnectArray","connectArr","initialArr","strictSort","sortedConnect","needsSorting","relationInInitialArray","forEach","rel","id","mappedRelations","reduce","mapper","relation","adjacentRelId","position","before","after","existingRelation","hasNoComponent","hasSameComponent","__component","InvalidRelationError","computed","computeRelation","startRelation","branch","relationsSeenInBranch","push","JSON","stringify","end","i","length","relationsOrderer","initArr","idColumn","orderColumn","strict","initialRelations","_","sortBy","castArray","map","r","init","order","undefined","Number","maxOrder","maxBy","head","tail","nodesById","Map","linkNode","node","prev","next","nodes","get","set","unlinkNode","splice","indexOf","delete","findNode","toArray","relations","removeRelation","insertRelation","beforeNode","Error","start","firstRelation","disconnect","connect","getOrderMap","chunks","groupBy","value","sortedKeys","Object","keys","sort","a","b","parseFloat","orderStr","offset"],"mappings":";;;AAiBA;;;;;;;;;;;;;;;;;IAkBA,MAAMA,mBAAmB,CAACC,UAAAA,EAAoBC,aAAqB,EAAE,EAAEC,aAAa,IAAI,GAAA;AACtF,IAAA,MAAMC,gBAAwB,EAAE;;AAEhC,IAAA,IAAIC,YAAAA,GAAe,KAAA;;AAEnB,IAAA,MAAMC,yBAA8C,EAAC;IACrDJ,UAAAA,CAAWK,OAAO,CAAC,CAACC,GAAAA,GAAAA;AAClBF,QAAAA,sBAAsB,CAACE,GAAAA,CAAIC,EAAE,CAAC,GAAG,IAAA;AACnC,IAAA,CAAA,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