All files / utils nameUniqueness.js

93.33% Statements 42/45
76.59% Branches 36/47
100% Functions 12/12
100% Lines 37/37

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 19239x                   624x 122x 121x 121x   1x                     37x 37x   37x                 36x 36x 3x                         171x 171x   170x                 170x 170x 23x                                                       26x 26x   26x               26x   26x 25x                 25x   10x       25x     22x                           28x 28x   28x                     28x 28x   7x                       2x                   2x     39x                
const { QueryCommand } = require('@aws-sdk/lib-dynamodb')
 
/**
 * Normalizes a name (plain string or multilingual `{en, fr, ...}` object) into
 * a trimmed, lowercased string for case-insensitive uniqueness comparison.
 *
 * @param {string | Record<string, string> | undefined | null} name
 * @returns {string}
 */
function normalizeName(name) {
  if (typeof name === 'string') return name.trim().toLowerCase()
  if (name && typeof name === 'object') {
    const value = name.en || name.fr || Object.values(name)[0] || ''
    return String(value).trim().toLowerCase()
  }
  return ''
}
 
/**
 * Finds a flow owned by `ownerId` whose name conflicts with `name`, if any.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ tableName: string, ownerId: string, name: unknown, excludeFlowId?: string }} params
 * @returns {Promise<Record<string, unknown> | null>}
 */
async function findFlowNameConflict(docClient, { tableName, ownerId, name, excludeFlowId }) {
  const normalized = normalizeName(name)
  Iif (!normalized) return null
 
  const result = await docClient.send(
    new QueryCommand({
      TableName: tableName,
      IndexName: 'ownerIndex',
      KeyConditionExpression: 'ownerId = :ownerId',
      ExpressionAttributeValues: { ':ownerId': ownerId }
    })
  )
 
  const items = result.Items || []
  return (
    items.find((item) => item.id !== excludeFlowId && normalizeName(item.name) === normalized) ||
    null
  )
}
 
/**
 * Finds an entity in `flowId` whose name conflicts with `name`, if any.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ tableName: string, flowId: string, name: unknown, excludeEntityId?: string }} params
 * @returns {Promise<Record<string, unknown> | null>}
 */
async function findEntityNameConflict(docClient, { tableName, flowId, name, excludeEntityId }) {
  const normalized = normalizeName(name)
  if (!normalized) return null
 
  const result = await docClient.send(
    new QueryCommand({
      TableName: tableName,
      IndexName: 'flowIndex',
      KeyConditionExpression: 'flowId = :flowId',
      ExpressionAttributeValues: { ':flowId': flowId }
    })
  )
 
  const items = result.Items || []
  return (
    items.find((item) => item.id !== excludeEntityId && normalizeName(item.name) === normalized) ||
    null
  )
}
 
/**
 * Finds a public entity owned by any flow of `ownerId` (not just the current
 * flow) whose name conflicts with `name`, if any. Public entity names must be
 * unique across all of a user's flows: unlike private entities, a public
 * entity's name is shown in the catalog under the owner's identity, and an
 * entity can also change flowId via ownership transfer, so per-flow
 * uniqueness alone isn't enough to keep two of the same owner's public
 * entities from colliding.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{
 *   entitiesTableName: string,
 *   flowsTableName: string,
 *   ownerId: string,
 *   name: unknown,
 *   excludeEntityId?: string
 * }} params
 * @returns {Promise<Record<string, unknown> | null>}
 */
async function findPublicEntityNameConflictForOwner(
  docClient,
  { entitiesTableName, flowsTableName, ownerId, name, excludeEntityId }
) {
  const normalized = normalizeName(name)
  Iif (!normalized) return null
 
  const flowsResult = await docClient.send(
    new QueryCommand({
      TableName: flowsTableName,
      IndexName: 'ownerIndex',
      KeyConditionExpression: 'ownerId = :ownerId',
      ExpressionAttributeValues: { ':ownerId': ownerId }
    })
  )
  const ownerFlowIds = (flowsResult.Items || []).map((flow) => flow.id)
 
  for (const ownerFlowId of ownerFlowIds) {
    const entitiesResult = await docClient.send(
      new QueryCommand({
        TableName: entitiesTableName,
        IndexName: 'flowIndex',
        KeyConditionExpression: 'flowId = :flowId',
        ExpressionAttributeValues: { ':flowId': ownerFlowId }
      })
    )
 
    const conflict = (entitiesResult.Items || []).find(
      (item) =>
        item.id !== excludeEntityId &&
        item.visibility === 'public' &&
        normalizeName(item.name) === normalized
    )
    if (conflict) return conflict
  }
 
  return null
}
 
/**
 * Finds a role in `flowId` whose name conflicts with `name`, if any. Roles are
 * stored under a single `PK = FLOW#{flowId}` partition (`SK = ROLE#{roleId}`),
 * so this queries the main RolesTable directly rather than a GSI — the same
 * per-flow scoping already used by roles/list.js.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ tableName: string, flowId: string, name: unknown, excludeRoleId?: string }} params
 * @returns {Promise<Record<string, unknown> | null>}
 */
async function findRoleNameConflict(docClient, { tableName, flowId, name, excludeRoleId }) {
  const normalized = normalizeName(name)
  Iif (!normalized) return null
 
  const result = await docClient.send(
    new QueryCommand({
      TableName: tableName,
      KeyConditionExpression: 'PK = :pk AND begins_with(SK, :sk)',
      ExpressionAttributeValues: {
        ':pk': `FLOW#${flowId}`,
        ':sk': 'ROLE#'
      }
    })
  )
 
  const items = result.Items || []
  return (
    items.find(
      (item) => item.roleId !== excludeRoleId && normalizeName(item.name) === normalized
    ) || null
  )
}
 
/**
 * The names of the flow's entities, normalized: one Query on `flowIndex`, the
 * same page `findEntityNameConflict` reads, names only.
 *
 * @returns {Promise<Set<string>>}
 */
async function listEntityNames(docClient, { tableName, flowId }) {
  const result = await docClient.send(
    new QueryCommand({
      TableName: tableName,
      IndexName: 'flowIndex',
      KeyConditionExpression: 'flowId = :flowId',
      ProjectionExpression: '#name',
      ExpressionAttributeNames: { '#name': 'name' },
      ExpressionAttributeValues: { ':flowId': flowId }
    })
  )
  return new Set((result.Items || []).map((item) => normalizeName(item.name)).filter(Boolean))
}
 
module.exports = {
  normalizeName,
  listEntityNames,
  findFlowNameConflict,
  findEntityNameConflict,
  findPublicEntityNameConflictForOwner,
  findRoleNameConflict
}