All files / utils spaceData.js

99.35% Statements 306/308
93.11% Branches 284/305
100% Functions 69/69
100% Lines 246/246

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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601                                7x 7x 7x 7x 7x 7x 7x 7x     7x   7x                     7x 7x   7x 7x   7x       18x 18x 18x       346x       97x 97x 61x     60x   97x 69x 69x         7x     7x     105x             244x 35x 98x 34x 68x                         15x               8x 8x 14x 5x               6x       7x     146x 16x 4x 4x 3x     13x 1x   12x 6x 6x 2x       10x 2x   8x 1x                     43x 43x 47x 27x 27x 3x   24x 23x   22x 22x           22x 3x           19x 10x 3x 3x             5x 5x   9x 3x 3x             46x 46x 46x         7x       13x 13x 10x   10x 8x 7x 10x     38x     15x 15x 15x 12x 6x 6x               24x 24x 30x   12x 5x 5x 19x 19x 19x 15x           2x   2x 3x                       3x 3x   2x                 26x     26x 26x 26x       175x 26x 5x 13x   26x 1x 1x 3x 3x     26x 2x 9x   26x 1x 4x   26x 26x             5x 4x   5x 4x         29x 29x 55x 3x 3x 2x 2x 2x 2x 3x     2x 2x 2x       2x         2x 1x 1x       29x               132x 132x 120x 4x 3x 3x   120x 14x 10x   120x       49x       3x   2x   21x   5x   3x 3x     2x 2x     18x   2x 2x     3x   2x   3x       6x 10x 6x 3x     1x                 49x 49x 95x 95x   49x                           33x 239x 33x 65x 65x       47x             3x   3x 4x                       4x 4x   3x                         44x     44x 50x 4x 4x   46x   31x 30x 25x 25x   25x 21x 21x 21x 21x   4x 4x 3x 3x     44x   50x 50x 49x   1x   7x 2x     44x               36x 35x 31x 30x   30x     30x         55x 29x 29x 49x                     10x 9x 5x 5x 5x 5x 5x           7x                              
// @implements UC-SPACE-011.1, UC-SPACE-013.1, UC-SPACE-014.1, UC-SPACE-019.1
/**
 * The data blocks of the space pages (docs/architecture/FLOW_SPACE.md,
 * "Data blocks and more content blocks"): an entity's items shown to visitors, laid out by
 * one of its forms, and the member count.
 *
 * - `checkEntityBlocks`: on save and publish, the entity, form, fields and
 *   item of each block belong to the flow, and the member may list the items.
 * - `freezeForms`: on publish, each data block keeps the field list of its
 *   form, so a later change of the form (made for the app) never reaches
 *   visitors before the page is published again.
 * - `resolveBlocks`: on read, the items each block shows, reduced to the
 *   shown fields' display values: user fields never leave, images and files
 *   are signed URLs, options and states are labels, references are labels.
 * - `resolveListItems`: the next items of an item list ("load more").
 */
const { GetCommand, QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const { fetchAllItems, getSortValue } = require('../items/filtering')
const { getItemCount } = require('./entityItemCount')
const { isDeletedPlaceholder } = require('./deletedPlaceholder')
const { pickItemLabel } = require('./itemLabel')
const { permissionChecker } = require('./PermissionChecker')
const { LARGE_ENTITY_ITEM_THRESHOLD } = require('./constants')
const { DATA_BLOCK_TYPES, ENTITY_BLOCK_TYPES } = require('./spacePages')
 
/** Never shown on a page: who the members are, and secrets */
const HIDDEN_FIELD_TYPES = new Set(['user', 'password', 'relation'])
/** Fields an item list can filter on, by exact value */
const FILTER_FIELD_TYPES = new Set([
  'text',
  'email',
  'number',
  'date',
  'boolean',
  'select',
  'multiselect',
  'workflow',
  'entity_ref'
])
const SORT_FIELD_TYPES = new Set(['text', 'textarea', 'email', 'number', 'date'])
const CREATED_AT = 'createdAt'
/** Beyond LARGE_ENTITY_ITEM_THRESHOLD items, filters run on this many of the latest */
const LARGE_ENTITY_SCAN = 500
const BATCH_GET_SIZE = 100
/** How far "load more" goes into a list: the most items a read filters and sorts */
const MAX_LIST_OFFSET = 1000
 
class DataBlockError extends Error {
  constructor(statusCode, body) {
    super(body.error)
    this.statusCode = statusCode
    this.body = body
  }
}
 
const isShown = (field) => !!field?.fieldId && !HIDDEN_FIELD_TYPES.has(field.type)
 
/** A per-request reader of entities, each read once */
function entityReader(docClient) {
  const cache = new Map()
  const read = async (entityId) => {
    const result = await docClient.send(
      new GetCommand({ TableName: process.env.ENTITIES_TABLE_NAME, Key: { id: entityId } })
    )
    return result.Item || null
  }
  return (entityId) => {
    if (!cache.has(entityId)) cache.set(entityId, read(entityId))
    return cache.get(entityId)
  }
}
 
async function getItem(docClient, entityId, itemId) {
  const result = await docClient.send(
    new GetCommand({ TableName: process.env.TABLE_NAME, Key: { entityId, id: itemId } })
  )
  return result.Item || null
}
 
const formOf = (entity, formId) => (entity.forms || []).find((form) => form.id === formId)
 
/**
 * The placements of a form whose field exists and may be shown, in order:
 * `{ fieldId, x, y, w, h, labelOverride? }`
 */
function formPlacements(entity, form) {
  const fieldIds = new Set((entity.fields || []).filter(isShown).map((field) => field.fieldId))
  return [...(form?.fields || [])]
    .filter((placement) => fieldIds.has(placement.fieldId))
    .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
    .map((placement) => ({
      fieldId: placement.fieldId,
      ...(Number.isInteger(placement.x) && { x: placement.x }),
      ...(Number.isInteger(placement.y) && { y: placement.y }),
      ...(Number.isInteger(placement.w) && { w: placement.w }),
      ...(Number.isInteger(placement.h) && { h: placement.h }),
      ...(placement.labelOverride && { labelOverride: placement.labelOverride })
    }))
}
 
// ─── Save and publish ───────────────────────────────────────────────────────
 
function invalid(message, block) {
  return new DataBlockError(400, { error: 'DATA_BLOCK_INVALID', message, blockId: block.id })
}
 
/**
 * The date an agenda groups its items by: the sort's field, when it is the
 * creation date (CREATED_AT, the default sort) or a date field; else undefined
 */
function agendaDateField(block, entity) {
  const fieldId = block.sort?.fieldId || CREATED_AT
  if (fieldId === CREATED_AT) return CREATED_AT
  const field = (entity.fields || []).find((f) => f.fieldId === fieldId)
  return isShown(field) && field.type === 'date' ? fieldId : undefined
}
 
/**
 * The place field a map layout puts the items at: the first place field its
 * form shows (UC-SPACE-022.1), undefined when it shows none
 */
function mapPlaceField(block, entity) {
  return shownFields(entity, block).find(({ field }) => field.type === 'geo_location')?.field
    .fieldId
}
 
const hasPlace = (value) => typeof value?.lat === 'number' && typeof value?.lng === 'number'
 
function checkListSettings(block, entity) {
  const fieldsById = new Map((entity.fields || []).map((field) => [field.fieldId, field]))
  for (const filter of block.filters || []) {
    const field = fieldsById.get(filter.fieldId)
    if (!isShown(field) || !FILTER_FIELD_TYPES.has(field.type)) {
      throw invalid('A filter field cannot be used', block)
    }
  }
  if (block.upcomingFieldId && fieldsById.get(block.upcomingFieldId)?.type !== 'date') {
    throw invalid('"Upcoming only" needs a date field', block)
  }
  if (block.sort && block.sort.fieldId !== CREATED_AT) {
    const field = fieldsById.get(block.sort.fieldId)
    if (!isShown(field) || !SORT_FIELD_TYPES.has(field.type)) {
      throw invalid('The sort field cannot be used', block)
    }
  }
  // The agenda groups the items by the date they are sorted on
  if (block.layout === 'agenda' && agendaDateField(block, entity) === undefined) {
    throw invalid('The agenda needs a sort on a date', block)
  }
  if (block.layout === 'map' && mapPlaceField(block, entity) === undefined) {
    throw invalid('The map needs a place field in the form', block)
  }
}
 
/**
 * Checks the entity blocks of a version about to be saved or published.
 * Throws a DataBlockError (400: not the flow's, 403: the member may not list
 * the entity's items).
 * @param {object} access - `{ userId, flowId, membership }`
 */
async function checkEntityBlocks(docClient, access, blocks) {
  const readEntity = entityReader(docClient)
  for (const block of blocks || []) {
    if (!ENTITY_BLOCK_TYPES.includes(block.type)) continue
    const entity = await readEntity(block.entityId)
    if (!entity || entity.flowId !== access.flowId) {
      throw invalid('The entity is not one of this flow', block)
    }
    if (!formOf(entity, block.formId)) throw invalid('The form is not one of the entity', block)
    if (!DATA_BLOCK_TYPES.includes(block.type)) continue
 
    const permission = `entities-${entity.id}:items:list`
    const { hasPermission } = await permissionChecker.hasPermission(
      access.userId,
      access.flowId,
      permission,
      { membership: access.membership, entity }
    )
    if (!hasPermission) {
      throw new DataBlockError(403, {
        error: 'DATA_BLOCK_FORBIDDEN',
        required: permission,
        blockId: block.id
      })
    }
    if (block.type === 'itemList') checkListSettings(block, entity)
    if (block.type === 'itemCard') {
      const item = await getItem(docClient, entity.id, block.itemId)
      if (!item || item.flowId !== access.flowId) throw invalid('The item is not found', block)
    }
  }
}
 
/** The blocks to publish: each data block with its form's field list frozen */
async function freezeForms(docClient, blocks) {
  const readEntity = entityReader(docClient)
  return Promise.all(
    (blocks || []).map(async (block) => {
      if (!DATA_BLOCK_TYPES.includes(block.type)) return block
      const entity = await readEntity(block.entityId)
      return { ...block, fields: formPlacements(entity, formOf(entity, block.formId)) }
    })
  )
}
 
/** A published block without what publishing added, to compare it with the draft */
function withoutFrozenFields(block) {
  const rest = { ...block }
  delete rest.fields
  return rest
}
 
// ─── Reading ────────────────────────────────────────────────────────────────
 
const today = () => new Date().toISOString().slice(0, 10)
 
/** Exact match: AND across filters, OR within one filter's values */
function matchesFilter(item, filter, field) {
  const raw = item[field.fieldId]
  if (raw === undefined || raw === null || raw === '') return false
  const wanted = new Set(filter.values.map(String))
  let candidates
  if (Array.isArray(raw)) candidates = raw
  else if (typeof raw === 'object') candidates = Object.values(raw)
  else candidates = [raw]
  return candidates.some((value) => wanted.has(String(value)))
}
 
const isMissing = (value) => value === undefined || value === null || value === ''
 
function compareValues(field, a, b, entity) {
  const va = a[field.fieldId]
  const vb = b[field.fieldId]
  if (field.type === 'number') return Number(va) - Number(vb)
  if (field.type === 'date') return String(va).localeCompare(String(vb))
  const locale = entity.defaultLanguage || 'en'
  return getSortValue(field, a, entity).localeCompare(getSortValue(field, b, entity), locale, {
    sensitivity: 'base',
    numeric: true
  })
}
 
/** Sorts in place; items without a value come last, whatever the direction */
function sortList(items, sort, entity) {
  const direction = sort.direction === 'desc' ? -1 : 1
  if (sort.fieldId === CREATED_AT) {
    return items.sort((a, b) => direction * String(a.createdAt).localeCompare(String(b.createdAt)))
  }
  const field = (entity.fields || []).find((f) => f.fieldId === sort.fieldId)
  Iif (!field) return items
  return items.sort((a, b) => {
    const missingA = isMissing(a[field.fieldId])
    const missingB = isMissing(b[field.fieldId])
    if (missingA || missingB) return Number(missingA) - Number(missingB)
    return direction * compareValues(field, a, b, entity)
  })
}
 
/** The latest items (or the oldest, `ascending`), at most LARGE_ENTITY_SCAN */
async function latestItems(docClient, entity, ascending) {
  const items = []
  let ExclusiveStartKey
  do {
    const result = await docClient.send(
      new QueryCommand({
        TableName: process.env.TABLE_NAME,
        IndexName: 'createdAtIndex',
        KeyConditionExpression: 'entityId = :entityId',
        FilterExpression: 'flowId = :flowId',
        ExpressionAttributeValues: { ':entityId': entity.id, ':flowId': entity.flowId },
        ScanIndexForward: ascending,
        Limit: LARGE_ENTITY_SCAN,
        ExclusiveStartKey
      })
    )
    items.push(...(result.Items || []))
    ExclusiveStartKey = result.LastEvaluatedKey
  } while (ExclusiveStartKey && items.length < LARGE_ENTITY_SCAN)
  return items.slice(0, LARGE_ENTITY_SCAN)
}
 
/**
 * The items an item list shows, filtered and sorted, from `offset` and at
 * most its limit; `hasMore` when others follow. An agenda leaves out the
 * items without its date, a map those without a place.
 */
async function listItems(docClient, entity, block, offset = 0) {
  const count = process.env.ENTITY_ITEM_COUNT_TABLE_NAME
    ? await getItemCount(docClient, process.env.ENTITY_ITEM_COUNT_TABLE_NAME, entity.id)
    : 0
  const sort = block.sort || { fieldId: CREATED_AT, direction: 'desc' }
  const large = count > LARGE_ENTITY_ITEM_THRESHOLD
  let items = large
    ? await latestItems(docClient, entity, sort.fieldId === CREATED_AT && sort.direction === 'asc')
    : await fetchAllItems(docClient, process.env.TABLE_NAME, entity.id, entity.flowId)
 
  const fieldsById = new Map((entity.fields || []).map((field) => [field.fieldId, field]))
  for (const filter of block.filters || []) {
    const field = fieldsById.get(filter.fieldId)
    items = field ? items.filter((item) => matchesFilter(item, filter, field)) : []
  }
  if (block.upcomingFieldId) {
    const from = today()
    items = items.filter((item) => {
      const date = item[block.upcomingFieldId]
      return typeof date === 'string' && date >= from
    })
  }
  if (block.layout === 'agenda') {
    const dateField = agendaDateField(block, entity)
    items = items.filter((item) => typeof item[dateField] === 'string' && item[dateField])
  }
  if (block.layout === 'map') {
    const placeField = mapPlaceField(block, entity)
    items = placeField ? items.filter((item) => hasPlace(item[placeField])) : []
  }
  if (!large) sortList(items, sort, entity)
  return {
    items: items.slice(offset, offset + block.limit),
    hasMore: items.length > offset + block.limit
  }
}
 
function optionLabel(field, value) {
  const option = (field.options || []).find(
    (opt) => (typeof opt === 'string' ? opt : opt?.value) === value
  )
  if (option === undefined) return value
  return typeof option === 'string' ? option : (option.label ?? value)
}
 
/** Labels of referenced items, by id, for every entity_ref field shown */
async function referenceLabels(docClient, readEntity, fields, items, flowId) {
  const labels = new Map()
  for (const field of fields) {
    if (field.type !== 'entity_ref' || !field.reference?.entityId) continue
    const target = await readEntity(field.reference.entityId)
    if (!target || (target.flowId !== flowId && target.visibility !== 'public')) continue
    const ids = new Set()
    for (const item of items) {
      const raw = item[field.fieldId]
      for (const id of Array.isArray(raw) ? raw : [raw]) {
        if (typeof id === 'string' && id && !isDeletedPlaceholder(id)) ids.add(id)
      }
    }
    const idList = [...ids]
    for (let i = 0; i < idList.length; i += BATCH_GET_SIZE) {
      const result = await docClient.send(
        new BatchGetCommand({
          RequestItems: {
            [process.env.TABLE_NAME]: {
              Keys: idList.slice(i, i + BATCH_GET_SIZE).map((id) => ({ entityId: target.id, id }))
            }
          }
        })
      )
      for (const referenced of result.Responses?.[process.env.TABLE_NAME] || []) {
        const label = pickItemLabel(target, referenced)
        Eif (label) labels.set(`${field.fieldId}:${referenced.id}`, label)
      }
    }
  }
  return labels
}
 
/**
 * The display value of one field of an item, or undefined when nothing is
 * shown. `sign(key)` gives a URL for one of the item's files.
 */
async function displayValue(field, item, sign, labels) {
  const raw = item[field.fieldId]
  if (raw === undefined || raw === null || raw === '') return undefined
  const file = async (value) => {
    if (!value || typeof value.key !== 'string') return undefined
    const url = await sign(value.key)
    return url ? { name: String(value.name || ''), url } : undefined
  }
  const present = (values) => {
    const kept = values.filter((v) => v !== undefined)
    return kept.length ? kept : undefined
  }
  switch (field.type) {
    case 'text':
    case 'textarea':
    case 'email':
      return typeof raw === 'string' || (typeof raw === 'object' && !Array.isArray(raw))
        ? raw
        : undefined
    case 'number':
      return typeof raw === 'number' ? raw : undefined
    case 'boolean':
      return typeof raw === 'boolean' ? raw : undefined
    case 'date':
      return typeof raw === 'string' ? raw : undefined
    case 'select':
      return isDeletedPlaceholder(raw) ? undefined : optionLabel(field, raw)
    case 'multiselect':
      return Array.isArray(raw)
        ? present(raw.filter((v) => !isDeletedPlaceholder(v)).map((v) => optionLabel(field, v)))
        : undefined
    case 'workflow': {
      const state = field.workflowDefinition?.states?.find((s) => s.id === raw)
      return state ? state.label : undefined
    }
    case 'image':
      return typeof raw === 'string' ? sign(raw) : undefined
    case 'image_set':
      return Array.isArray(raw)
        ? present(await Promise.all(raw.map((key) => sign(key))))
        : undefined
    case 'file':
      return file(raw)
    case 'file_set':
      return Array.isArray(raw) ? present(await Promise.all(raw.map(file))) : undefined
    case 'geo_location':
      return typeof raw?.lat === 'number' && typeof raw?.lng === 'number'
        ? { lat: raw.lat, lng: raw.lng }
        : undefined
    case 'entity_ref': {
      const ids = Array.isArray(raw) ? raw : [raw]
      const found = present(ids.map((id) => labels.get(`${field.fieldId}:${id}`)))
      if (!found) return undefined
      return Array.isArray(raw) ? found : found[0]
    }
    default:
      return undefined
  }
}
 
/**
 * What a reader gets of an item: its id, creation date and shown values, and
 * in an agenda the date it is placed on (`dateField`)
 */
async function itemView(item, fields, sign, labels, dateField) {
  const values = {}
  for (const field of fields) {
    const value = await displayValue(field, item, sign, labels)
    if (value !== undefined) values[field.fieldId] = value
  }
  return {
    id: item.id,
    createdAt: item.createdAt,
    values,
    ...(dateField && { date: item[dateField] })
  }
}
 
/**
 * The fields a data block shows, with their placement: the frozen list of a
 * published block, else (draft) the form's current one. A field deleted since
 * is left out.
 */
function shownFields(entity, block) {
  const placements = block.fields || formPlacements(entity, formOf(entity, block.formId))
  const fieldsById = new Map((entity.fields || []).map((field) => [field.fieldId, field]))
  return placements
    .map((placement) => ({ placement, field: fieldsById.get(placement.fieldId) }))
    .filter(({ field }) => isShown(field))
}
 
/** How a field is described to a reader: name, type and placement, no settings */
const fieldView = ({ placement, field }) => ({
  ...placement,
  type: field.type,
  name: field.name
})
 
async function countActiveMembers(docClient, flowId) {
  let count = 0
  let ExclusiveStartKey
  do {
    const result = await docClient.send(
      new QueryCommand({
        TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
        IndexName: 'flowIndex',
        KeyConditionExpression: 'flowId = :flowId',
        FilterExpression: '#status = :active',
        ExpressionAttributeNames: { '#status': 'status' },
        ExpressionAttributeValues: { ':flowId': flowId, ':active': 'active' },
        Select: 'COUNT',
        ExclusiveStartKey
      })
    )
    count += result.Count || 0
    ExclusiveStartKey = result.LastEvaluatedKey
  } while (ExclusiveStartKey)
  return count
}
 
/**
 * The blocks of a version as a reader gets them: data blocks with their
 * items (`data: { fields, items, hasMore }` or `data: { fields, item }`), the member
 * count with its `count`. A data block whose entity, form or item is gone is
 * dropped, or kept as `unavailable` for the editor (`draft`).
 *
 * @param {object} options - `{ flowId, itemSigner, draft }`: `itemSigner(entityId)` gives
 *   the `sign(key)` of that entity's item files
 */
async function resolveBlocks(docClient, blocks, { flowId, itemSigner, draft = false }) {
  const readEntity = entityReader(docClient)
  let memberCount
 
  const resolveOne = async (block) => {
    if (block.type === 'memberCount') {
      if (memberCount === undefined) memberCount = countActiveMembers(docClient, flowId)
      return { ...block, count: await memberCount }
    }
    if (!DATA_BLOCK_TYPES.includes(block.type)) return block
 
    const source = await blockSource(readEntity, block, flowId)
    if (!source) return null
    const rest = withoutFrozenFields(block)
    const data = { fields: source.shown.map(fieldView) }
 
    if (block.type === 'itemList') {
      const { items, hasMore } = await listItems(docClient, source.entity, block)
      data.items = await itemViews(docClient, readEntity, source, items, { flowId, itemSigner })
      data.hasMore = hasMore
      return { ...rest, data }
    }
    const item = await getItem(docClient, source.entity.id, block.itemId)
    if (!item || item.flowId !== flowId) return null
    ;[data.item] = await itemViews(docClient, readEntity, source, [item], { flowId, itemSigner })
    return { ...rest, data }
  }
 
  const resolved = await Promise.all(
    (blocks || []).map(async (block) => {
      try {
        const result = await resolveOne(block)
        if (result) return result
      } catch (error) {
        console.error('Failed to resolve a space page block:', { flowId, id: block.id, error })
      }
      if (!draft) return null
      return { ...withoutFrozenFields(block), unavailable: true }
    })
  )
  return resolved.filter(Boolean)
}
 
/**
 * The entity a data block shows and its shown fields, or null when the
 * entity is not the flow's or the block's form is gone (and not frozen)
 */
async function blockSource(readEntity, block, flowId) {
  const entity = await readEntity(block.entityId)
  if (!entity || entity.flowId !== flowId) return null
  if (!block.fields && !formOf(entity, block.formId)) return null
  const shown = shownFields(entity, block)
  const dateField =
    block.type === 'itemList' && block.layout === 'agenda'
      ? agendaDateField(block, entity)
      : undefined
  return { entity, shown, dateField }
}
 
/** The reader's views of items of a block's entity */
async function itemViews(docClient, readEntity, source, items, { flowId, itemSigner }) {
  const fields = source.shown.map(({ field }) => field)
  const sign = itemSigner(source.entity.id)
  const labels = await referenceLabels(docClient, readEntity, fields, items, flowId)
  return Promise.all(items.map((item) => itemView(item, fields, sign, labels, source.dateField)))
}
 
/**
 * The items of an item list from `offset` ("load more", UC-SPACE-019.1):
 * `{ items, hasMore }`, or null when the block shows nothing (not an item
 * list, entity or form gone, offset out of range).
 *
 * @param {object} options - `{ flowId, itemSigner, offset }`
 */
async function resolveListItems(docClient, block, { flowId, itemSigner, offset }) {
  if (block?.type !== 'itemList') return null
  if (!Number.isInteger(offset) || offset < 0 || offset > MAX_LIST_OFFSET) return null
  const readEntity = entityReader(docClient)
  const source = await blockSource(readEntity, block, flowId)
  Iif (!source) return null
  const { items, hasMore } = await listItems(docClient, source.entity, block, offset)
  return {
    items: await itemViews(docClient, readEntity, source, items, { flowId, itemSigner }),
    hasMore: hasMore && offset + block.limit < MAX_LIST_OFFSET
  }
}
 
module.exports = {
  HIDDEN_FIELD_TYPES,
  FILTER_FIELD_TYPES,
  SORT_FIELD_TYPES,
  DataBlockError,
  checkEntityBlocks,
  freezeForms,
  withoutFrozenFields,
  resolveBlocks,
  resolveListItems,
  MAX_LIST_OFFSET,
  formPlacements,
  displayValue,
  countActiveMembers
}