All files / utils spacePages.js

99.44% Statements 361/363
99.21% Branches 380/383
100% Functions 63/63
99.3% Lines 286/288

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 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668                      12x 12x   12x   12x                 12x 12x     12x 11x   12x                                     12x 12x   12x         12x 12x   12x   12x           12x 12x 12x                     12x 12x   12x 598x     12x 93x     12x 61x       12x 10x 10x 9x 7x   1x           248x 85x 82x   163x 162x 162x 161x 161x 162x 161x 161x 159x 158x 157x   158x 3x 1x   155x           12x                 12x     24x 5x 1x   4x 6x 1x   5x 2x 2x 1x         72x 71x 70x 70x   69x 69x 25x 24x 24x 21x 21x   44x   43x 5x 5x 5x 5x   4x 4x 2x   3x 2x     40x 37x 36x 38x     27x         28x 1x   27x 1x   26x 34x   14x 14x         33x 3x 1x   30x 29x 28x 28x 30x 29x 28x 14x   13x 1x     12x           23x     32x 9x 7x   23x 23x             4x   19x       8x 7x 6x 3x 1x   2x   3x 2x 1x   1x       81x 18x 14x   63x 61x         24x 9x 2x   7x 7x 7x 6x 6x 1x   5x   7x     7x   2x         15x 3x 2x 2x 1x         10x             12x 387x   12x   9x               5x               26x     18x             5x 1x   4x 1x   3x   3x 3x 2x                   4x 4x 1x   3x 3x 1x   2x 2x 1x     11x     7x 1x   6x 1x   5x   6x 6x 5x         6x 3x   3x   6x 6x 5x     5x 5x 4x         31x 31x 3x   28x 28x 27x                           2x             2x     2x                 12x       58x 5x 5x 3x           2x       132x 113x 112x 133x 111x 1x   110x 110x 126x 126x 125x 124x 1x   123x 123x                             141x 141x 140x       58x 58x 57x 57x 56x 56x 1x   55x 55x 49x 49x 11x 10x   48x   93x               56x       58x 58x 56x 56x 4x     58x         29x               9x 9x 11x 11x   9x         20x 18x 18x 17x 17x 6x 6x   18x         7x 5x 2x               6x 6x 4x 2x         11x     21x   10x 13x                         26x 35x 16x 16x   26x   31x 31x 30x 29x         12x                                            
// @implements UC-SPACE-009.1, UC-SPACE-010.1, UC-SPACE-011.1, UC-SPACE-012.1, UC-SPACE-013.1, UC-SPACE-014.1, UC-SPACE-023.1
/**
 * The pages of a flow's public space, made of blocks (FlowPagesTable).
 * See docs/architecture/FLOW_SPACE.md "Pages and content blocks".
 *
 * Everything a page holds is validated and normalized here, unknown keys
 * dropped: pages are shown to anyone, so nothing but the known blocks, plain
 * texts and the rich text nodes below can ever be stored. Rich text is a
 * TipTap JSON document, never HTML.
 */
 
const PAGE_SLUG_REGEX = /^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/
const HOME_SLUG = 'home'
/** Taken by the join form (/space/{slug}/join) */
const RESERVED_SLUGS = ['join']
 
const VISIBILITIES = ['everyone', 'members']
 
/**
 * The icon a page can have in the space menu (UC-SPACE-015.1): the name of any
 * Font Awesome free solid icon (`trophy`, `calendar-days`). Only the shape of
 * the name is checked, so a new Font Awesome version brings its icons without
 * an API change; the UI loads each icon on demand and shows the default one
 * for a name it does not know.
 */
const PAGE_ICON_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
const PAGE_ICON_MAX_LENGTH = 50
 
/** Whether a value is a well-formed page icon name */
const isPageIcon = (icon) =>
  typeof icon === 'string' && icon.length <= PAGE_ICON_MAX_LENGTH && PAGE_ICON_REGEX.test(icon)
 
const LIMITS = {
  pagesPerFlow: 30,
  blocksPerPage: 40,
  faqEntries: 30,
  galleryImages: 30,
  dataBlocksPerPage: 6,
  listFilters: 5,
  filterValues: 10,
  filterValueLength: 200,
  listItems: 50,
  languages: 10,
  titleLength: 120,
  textLength: 2000,
  urlLength: 2000,
  richTextBytes: 20000,
  richTextDepth: 8,
  pageBytes: 300000
}
 
const LANGUAGE_REGEX = /^[a-z]{2}$/
const BLOCK_ID_REGEX = /^[A-Za-z0-9_-]{1,40}$/
/** Entity, form, field and item ids: UUIDs, or the short ids of older fields */
const REF_ID_REGEX = /^[A-Za-z0-9_-]{1,64}$/
/**
 * `agenda`: the items grouped by month and day of the date they are sorted on (UC-SPACE-019.1);
 * `map`: the items at the first place field of their form (UC-SPACE-022.1)
 */
const LIST_LAYOUTS = ['cards', 'list', 'agenda', 'map']
const DEFAULT_LIST_LIMIT = 12
/** Blocks showing a flow's items to visitors (UC-SPACE-011.1) */
const DATA_BLOCK_TYPES = ['itemList', 'itemCard']
/** Blocks naming an entity and one of its forms */
const ENTITY_BLOCK_TYPES = [...DATA_BLOCK_TYPES, 'itemForm']
/**
 * How a block's content is aligned (UC-SPACE-023.1), by the blocks that hold
 * text or a button; `justify` only where paragraphs are written. A block
 * without `align` keeps its own default look.
 */
const SIDE_ALIGNS = ['left', 'center', 'right']
const TEXT_ALIGNS = [...SIDE_ALIGNS, 'justify']
const BLOCK_ALIGNS = {
  hero: TEXT_ALIGNS,
  richText: TEXT_ALIGNS,
  image: SIDE_ALIGNS,
  faq: TEXT_ALIGNS,
  contact: SIDE_ALIGNS,
  join: SIDE_ALIGNS,
  columns: TEXT_ALIGNS,
  memberCount: SIDE_ALIGNS,
  itemForm: TEXT_ALIGNS
}
const EMAIL_REGEX = /^[^\s@<>()]+@[^\s@<>()]+\.[^\s@<>()]+$/
const PHONE_REGEX = /^[0-9+().\s-]{3,30}$/
 
const isPlainObject = (value) =>
  value !== null && typeof value === 'object' && !Array.isArray(value)
 
class PageError extends Error {}
const fail = (message) => {
  throw new PageError(message)
}
 
const isPageSlug = (slug) =>
  typeof slug === 'string' && PAGE_SLUG_REGEX.test(slug) && !RESERVED_SLUGS.includes(slug)
 
/** Only `https:` (and `mailto:`) links: no `javascript:`, no plain http, no relative trick */
function isSafeUrl(url) {
  if (typeof url !== 'string' || url.length > LIMITS.urlLength) return false
  try {
    const parsed = new URL(url)
    if (parsed.protocol === 'mailto:') return EMAIL_REGEX.test(decodeURIComponent(parsed.pathname))
    return parsed.protocol === 'https:' && !!parsed.hostname
  } catch {
    return false
  }
}
 
/** A `{ lang: text }` map, empty texts dropped; null when nothing is left */
function localizedText(value, path, maxLength, { required = false } = {}) {
  if (value === undefined || value === null) {
    if (required) fail(`${path} is required`)
    return null
  }
  if (!isPlainObject(value)) fail(`${path} must be an object of texts by language`)
  const languages = Object.keys(value)
  if (languages.length > LIMITS.languages) fail(`${path} has too many languages`)
  const result = {}
  for (const lang of languages) {
    if (!LANGUAGE_REGEX.test(lang)) fail(`${path}: invalid language "${lang}"`)
    const text = value[lang]
    if (text === null || text === undefined || text === '') continue
    if (typeof text !== 'string') fail(`${path}.${lang} must be a string`)
    if (text.length > maxLength) fail(`${path}.${lang} is longer than ${maxLength} characters`)
    if (text.trim()) result[lang] = text
  }
  if (Object.keys(result).length === 0) {
    if (required) fail(`${path} is required`)
    return null
  }
  return result
}
 
// ─── Rich text ──────────────────────────────────────────────────────────────
 
/** TipTap nodes and marks a page may hold, with the attributes kept for each */
const RICH_TEXT_NODES = {
  paragraph: { content: true },
  heading: { content: true, attrs: { level: [2, 3] } },
  bulletList: { content: true },
  orderedList: { content: true, attrs: { start: 'positiveInt' } },
  listItem: { content: true },
  hardBreak: {},
  text: {}
}
const RICH_TEXT_MARKS = ['bold', 'italic', 'underline', 'link']
 
function richTextMarks(marks, path) {
  if (marks === undefined) return undefined
  if (!Array.isArray(marks) || marks.length > RICH_TEXT_MARKS.length) {
    fail(`${path}.marks must be a list`)
  }
  return marks.map((mark, index) => {
    if (!isPlainObject(mark) || !RICH_TEXT_MARKS.includes(mark.type)) {
      fail(`${path}.marks[${index}]: unsupported mark`)
    }
    if (mark.type !== 'link') return { type: mark.type }
    const href = mark.attrs?.href
    if (!isSafeUrl(href)) fail(`${path}.marks[${index}]: links must be https: or mailto:`)
    return { type: 'link', attrs: { href } }
  })
}
 
function richTextNode(node, path, depth) {
  if (depth > LIMITS.richTextDepth) fail(`${path}: rich text is nested too deeply`)
  if (!isPlainObject(node)) fail(`${path} must be a node`)
  const spec = RICH_TEXT_NODES[node.type]
  if (!spec) fail(`${path}: unsupported node "${node.type}"`)
 
  const result = { type: node.type }
  if (node.type === 'text') {
    if (typeof node.text !== 'string' || node.text === '') fail(`${path}.text must be a string`)
    result.text = node.text
    const marks = richTextMarks(node.marks, path)
    if (marks?.length) result.marks = marks
    return result
  }
  if (node.marks !== undefined) fail(`${path}: only text can have marks`)
 
  if (spec.attrs) {
    const attrs = {}
    for (const [name, rule] of Object.entries(spec.attrs)) {
      const value = node.attrs?.[name]
      if (value === undefined || value === null) continue
      const ok =
        rule === 'positiveInt' ? Number.isInteger(value) && value > 0 : rule.includes(value)
      if (!ok) fail(`${path}.attrs.${name} is invalid`)
      attrs[name] = value
    }
    if (node.type === 'heading' && !attrs.level) fail(`${path}.attrs.level is required`)
    Eif (Object.keys(attrs).length) result.attrs = attrs
  }
 
  if (node.content !== undefined) {
    if (!spec.content || !Array.isArray(node.content)) fail(`${path}.content is invalid`)
    result.content = node.content.map((child, index) =>
      richTextNode(child, `${path}.content[${index}]`, depth + 1)
    )
  }
  return result
}
 
/** A TipTap document of the allowed nodes and marks; null when it holds no text */
function richTextDocument(doc, path) {
  if (!isPlainObject(doc) || doc.type !== 'doc' || !Array.isArray(doc.content)) {
    fail(`${path} must be a rich text document`)
  }
  if (Buffer.byteLength(JSON.stringify(doc)) > LIMITS.richTextBytes) {
    fail(`${path} is too long`)
  }
  const content = doc.content.map((node, index) =>
    richTextNode(node, `${path}.content[${index}]`, 1)
  )
  const hasText = JSON.stringify(content).includes('"type":"text"')
  return hasText ? { type: 'doc', content } : null
}
 
/** A `{ lang: document }` map of rich texts */
function localizedRichText(value, path, { required = false } = {}) {
  if (value === undefined || value === null) {
    if (required) fail(`${path} is required`)
    return null
  }
  if (!isPlainObject(value)) fail(`${path} must be an object of rich texts by language`)
  if (Object.keys(value).length > LIMITS.languages) fail(`${path} has too many languages`)
  const result = {}
  for (const [lang, doc] of Object.entries(value)) {
    if (!LANGUAGE_REGEX.test(lang)) fail(`${path}: invalid language "${lang}"`)
    if (doc === null || doc === undefined) continue
    const normalized = richTextDocument(doc, `${path}.${lang}`)
    if (normalized) result[lang] = normalized
  }
  if (Object.keys(result).length === 0) {
    Eif (required) fail(`${path} is required`)
    return null
  }
  return result
}
 
// ─── Blocks ─────────────────────────────────────────────────────────────────
 
/** Images live in the flow's own key space, so deleting the flow deletes them */
const pageImagePrefix = (flowId) => `flows/${flowId}/space-pages/`
 
function imageKey(value, path, flowId, { required = false } = {}) {
  if (value === undefined || value === null || value === '') {
    if (required) fail(`${path} is required`)
    return null
  }
  const prefix = pageImagePrefix(flowId)
  if (
    typeof value !== 'string' ||
    !value.startsWith(prefix) ||
    value.length > 500 ||
    value.includes('..') ||
    value.slice(prefix.length).includes('/')
  ) {
    fail(`${path} must be an image of this flow's pages`)
  }
  return value
}
 
function pageLink(value, path) {
  if (!isPlainObject(value)) fail(`${path} must be a link`)
  if (value.type === 'join') return { type: 'join' }
  if (value.type === 'page') {
    if (typeof value.slug !== 'string' || !PAGE_SLUG_REGEX.test(value.slug)) {
      fail(`${path}.slug is invalid`)
    }
    return { type: 'page', slug: value.slug }
  }
  if (value.type === 'url') {
    if (!isSafeUrl(value.url)) fail(`${path}.url must be an https: or mailto: link`)
    return { type: 'url', url: value.url }
  }
  return fail(`${path}.type must be page, join or url`)
}
 
function refId(value, path, { required = true } = {}) {
  if (value === undefined || value === null || value === '') {
    if (required) fail(`${path} is required`)
    return null
  }
  if (typeof value !== 'string' || !REF_ID_REGEX.test(value)) fail(`${path} is invalid`)
  return value
}
 
/** Exact-match filters of an item list: `[{ fieldId, values }]` */
function listFilters(value, path) {
  if (value === undefined || value === null) return []
  if (!Array.isArray(value) || value.length > LIMITS.listFilters) {
    fail(`${path} must be a list of at most ${LIMITS.listFilters} filters`)
  }
  return value.map((filter, index) => {
    const filterPath = `${path}[${index}]`
    if (!isPlainObject(filter)) fail(`${filterPath} must be an object`)
    const values = filter.values
    if (!Array.isArray(values) || values.length === 0 || values.length > LIMITS.filterValues) {
      fail(`${filterPath}.values must hold 1 to ${LIMITS.filterValues} values`)
    }
    for (const v of values) {
      const ok =
        typeof v === 'boolean' ||
        (typeof v === 'number' && Number.isFinite(v)) ||
        (typeof v === 'string' && v !== '' && v.length <= LIMITS.filterValueLength)
      if (!ok) fail(`${filterPath}.values: invalid value`)
    }
    return { fieldId: refId(filter.fieldId, `${filterPath}.fieldId`), values: [...values] }
  })
}
 
function listSort(value, path) {
  if (value === undefined || value === null) return null
  if (!isPlainObject(value)) fail(`${path} must be an object`)
  const direction = value.direction ?? 'asc'
  if (direction !== 'asc' && direction !== 'desc') fail(`${path}.direction must be asc or desc`)
  return { fieldId: refId(value.fieldId, `${path}.fieldId`), direction }
}
 
/** A gallery image or a column's image: key, alternative text, caption */
function pictureEntry(entry, path, flowId, { required }) {
  return {
    imageKey: imageKey(entry.imageKey, `${path}.imageKey`, flowId, { required }),
    alt: localizedText(entry.alt, `${path}.alt`, LIMITS.titleLength),
    caption: localizedText(entry.caption, `${path}.caption`, LIMITS.textLength)
  }
}
 
const withoutNulls = (object) =>
  Object.fromEntries(Object.entries(object).filter(([, value]) => value !== null))
 
const BLOCKS = {
  hero(block, path, flowId) {
    const button = block.button
      ? withoutNulls({
          label: localizedText(block.button.label, `${path}.button.label`, LIMITS.titleLength, {
            required: true
          }),
          link: pageLink(block.button.link, `${path}.button.link`)
        })
      : null
    return {
      title: localizedText(block.title, `${path}.title`, LIMITS.titleLength, { required: true }),
      text: localizedText(block.text, `${path}.text`, LIMITS.textLength),
      imageKey: imageKey(block.imageKey, `${path}.imageKey`, flowId),
      button
    }
  },
  richText(block, path) {
    return { content: localizedRichText(block.content, `${path}.content`, { required: true }) }
  },
  image(block, path, flowId) {
    return {
      imageKey: imageKey(block.imageKey, `${path}.imageKey`, flowId, { required: true }),
      alt: localizedText(block.alt, `${path}.alt`, LIMITS.titleLength),
      caption: localizedText(block.caption, `${path}.caption`, LIMITS.textLength)
    }
  },
  faq(block, path) {
    if (!Array.isArray(block.entries) || block.entries.length === 0) {
      fail(`${path}.entries must be a non-empty list`)
    }
    if (block.entries.length > LIMITS.faqEntries) {
      fail(`${path}.entries: at most ${LIMITS.faqEntries} questions`)
    }
    return {
      entries: block.entries.map((entry, index) => {
        const entryPath = `${path}.entries[${index}]`
        if (!isPlainObject(entry)) fail(`${entryPath} must be an object`)
        return {
          question: localizedText(entry.question, `${entryPath}.question`, LIMITS.titleLength * 2, {
            required: true
          }),
          answer: localizedRichText(entry.answer, `${entryPath}.answer`, { required: true })
        }
      })
    }
  },
  contact(block, path) {
    const email = block.email || null
    if (email !== null && (typeof email !== 'string' || !EMAIL_REGEX.test(email))) {
      fail(`${path}.email is invalid`)
    }
    const phone = block.phone || null
    if (phone !== null && (typeof phone !== 'string' || !PHONE_REGEX.test(phone))) {
      fail(`${path}.phone is invalid`)
    }
    const address = localizedText(block.address, `${path}.address`, LIMITS.textLength)
    if (!email && !phone && !address) fail(`${path} needs an email, a phone or an address`)
    return { email, phone, address }
  },
  join(block, path) {
    return { label: localizedText(block.label, `${path}.label`, LIMITS.titleLength) }
  },
  gallery(block, path, flowId) {
    if (!Array.isArray(block.images) || block.images.length === 0) {
      fail(`${path}.images must be a non-empty list`)
    }
    if (block.images.length > LIMITS.galleryImages) {
      fail(`${path}.images: at most ${LIMITS.galleryImages} images`)
    }
    return {
      images: block.images.map((entry, index) => {
        const entryPath = `${path}.images[${index}]`
        if (!isPlainObject(entry)) fail(`${entryPath} must be an object`)
        return withoutNulls(pictureEntry(entry, entryPath, flowId, { required: true }))
      })
    }
  },
  columns(block, path, flowId) {
    if (!Array.isArray(block.columns) || block.columns.length < 2 || block.columns.length > 3) {
      fail(`${path}.columns must hold 2 or 3 columns`)
    }
    return {
      columns: block.columns.map((column, index) => {
        const columnPath = `${path}.columns[${index}]`
        if (!isPlainObject(column)) fail(`${columnPath} must be an object`)
        const { imageKey: key, alt } = pictureEntry(column, columnPath, flowId, {
          required: false
        })
        const content = localizedRichText(column.content, `${columnPath}.content`)
        if (!key && !content) fail(`${columnPath} needs an image or a text`)
        return withoutNulls({ imageKey: key, alt: key ? alt : null, content })
      })
    }
  },
  itemList(block, path) {
    const limit = block.limit ?? DEFAULT_LIST_LIMIT
    if (!Number.isInteger(limit) || limit < 1 || limit > LIMITS.listItems) {
      fail(`${path}.limit must be an integer from 1 to ${LIMITS.listItems}`)
    }
    const layout = block.layout ?? 'cards'
    if (!LIST_LAYOUTS.includes(layout)) fail(`${path}.layout must be one of ${LIST_LAYOUTS}`)
    return {
      title: localizedText(block.title, `${path}.title`, LIMITS.titleLength),
      entityId: refId(block.entityId, `${path}.entityId`),
      formId: refId(block.formId, `${path}.formId`),
      filters: listFilters(block.filters, `${path}.filters`),
      upcomingFieldId: refId(block.upcomingFieldId, `${path}.upcomingFieldId`, {
        required: false
      }),
      sort: listSort(block.sort, `${path}.sort`),
      limit,
      layout
    }
  },
  itemCard(block, path) {
    return {
      entityId: refId(block.entityId, `${path}.entityId`),
      formId: refId(block.formId, `${path}.formId`),
      itemId: refId(block.itemId, `${path}.itemId`)
    }
  },
  memberCount(block, path) {
    return { label: localizedText(block.label, `${path}.label`, LIMITS.titleLength) }
  },
  itemForm(block, path) {
    return {
      entityId: refId(block.entityId, `${path}.entityId`),
      formId: refId(block.formId, `${path}.formId`),
      label: localizedText(block.label, `${path}.label`, LIMITS.titleLength, { required: true }),
      text: localizedText(block.text, `${path}.text`, LIMITS.textLength)
    }
  }
}
 
const BLOCK_TYPES = Object.keys(BLOCKS)
 
/** The block's alignment, if its type takes one and it is set */
function blockAlign(block, path) {
  if (block.align === undefined || block.align === null) return null
  const aligns = BLOCK_ALIGNS[block.type] || []
  if (!aligns.includes(block.align)) {
    fail(
      aligns.length
        ? `${path}.align must be one of ${aligns}`
        : `${path}: a ${block.type} block has no alignment`
    )
  }
  return block.align
}
 
function pageBlocks(blocks, flowId) {
  if (blocks === undefined) return []
  if (!Array.isArray(blocks)) fail('blocks must be a list')
  if (blocks.length > LIMITS.blocksPerPage) fail(`At most ${LIMITS.blocksPerPage} blocks a page`)
  const dataBlocks = blocks.filter((block) => DATA_BLOCK_TYPES.includes(block?.type)).length
  if (dataBlocks > LIMITS.dataBlocksPerPage) {
    fail(`At most ${LIMITS.dataBlocksPerPage} item lists and item cards a page`)
  }
  const ids = new Set()
  return blocks.map((block, index) => {
    const path = `blocks[${index}]`
    if (!isPlainObject(block)) fail(`${path} must be an object`)
    if (!BLOCK_TYPES.includes(block.type)) fail(`${path}.type must be one of ${BLOCK_TYPES}`)
    if (typeof block.id !== 'string' || !BLOCK_ID_REGEX.test(block.id) || ids.has(block.id)) {
      fail(`${path}.id must be a unique short id`)
    }
    ids.add(block.id)
    return withoutNulls({
      id: block.id,
      type: block.type,
      ...BLOCKS[block.type](block, path, flowId),
      align: blockAlign(block, path)
    })
  })
}
 
/**
 * Validates the body of PUT /v1/flows/{flowId}/pages/{pageSlug}.
 * @returns {{ valid: true, value: { draft, visibility, showInMenu, menuOrder, icon, slug? } }
 *   | { valid: false, error: string }}
 */
function validatePageInput(body, flowId) {
  try {
    if (!isPlainObject(body)) fail('The body must be an object')
    const draft = {
      title: localizedText(body.title, 'title', LIMITS.titleLength, { required: true }),
      blocks: pageBlocks(body.blocks, flowId)
    }
    const visibility = body.visibility ?? 'everyone'
    if (!VISIBILITIES.includes(visibility)) fail(`visibility must be one of ${VISIBILITIES}`)
    const showInMenu = body.showInMenu ?? true
    if (typeof showInMenu !== 'boolean') fail('showInMenu must be a boolean')
    const menuOrder = body.menuOrder ?? 0
    if (!Number.isInteger(menuOrder) || menuOrder < 0 || menuOrder > 1000) {
      fail('menuOrder must be an integer from 0 to 1000')
    }
    const icon = body.icon ?? null
    if (icon !== null && !isPageIcon(icon)) fail('icon must be a Font Awesome icon name')
    const value = { draft, visibility, showInMenu, menuOrder, icon }
    if (body.slug !== undefined) {
      if (!isPageSlug(body.slug)) fail('slug is invalid')
      value.slug = body.slug
    }
    return { valid: true, value }
  } catch (error) {
    Eif (error instanceof PageError) return { valid: false, error: error.message }
    throw error
  }
}
 
// ─── Reading ────────────────────────────────────────────────────────────────
 
/** The images of a block holding several (gallery, columns) */
const blockPictures = (block) => block.images || block.columns || []
 
/** Every image key a version (draft or published) uses */
function versionImageKeys(version) {
  const keys = new Set()
  for (const block of version?.blocks || []) {
    if (block.imageKey) keys.add(block.imageKey)
    for (const picture of blockPictures(block)) {
      if (picture.imageKey) keys.add(picture.imageKey)
    }
  }
  return keys
}
 
/** The image keys used by a page record, draft and published together */
function pageImageKeys(page) {
  return new Set([...versionImageKeys(page?.draft), ...versionImageKeys(page?.published)])
}
 
/**
 * The pages a version's buttons lead to (UC-SPACE-016.1): hero buttons
 * pointing to a page, without the home page, which always exists
 */
function linkedPageSlugs(version) {
  const slugs = new Set()
  for (const block of version?.blocks || []) {
    const link = block.button?.link
    if (link?.type === 'page' && link.slug !== HOME_SLUG) slugs.add(link.slug)
  }
  return slugs
}
 
/** A version whose buttons to page `from` lead to `to` instead (the same object when none does) */
function withPageLinksRenamed(version, from, to) {
  if (!version?.blocks) return version
  let changed = false
  const blocks = version.blocks.map((block) => {
    const link = block.button?.link
    if (link?.type !== 'page' || link.slug !== from) return block
    changed = true
    return { ...block, button: { ...block.button, link: { ...link, slug: to } } }
  })
  return changed ? { ...version, blocks } : version
}
 
/** The other pages whose published version links to `slug`, as `{ slug, title }` */
function pagesLinkingTo(pages, slug) {
  return pages
    .filter((page) => page.slug !== slug && linkedPageSlugs(page.published).has(slug))
    .map((page) => ({ slug: page.slug, title: page.published.title }))
}
 
/**
 * The pages `page`'s draft links to that are not published (or don't exist),
 * as `{ slug, title }` (the draft's title; null for a missing page)
 */
function unpublishedLinkedPages(pages, page) {
  const bySlug = new Map(pages.map((other) => [other.slug, other]))
  return [...linkedPageSlugs(page.draft)]
    .filter((slug) => slug !== page.slug && !bySlug.get(slug)?.published)
    .map((slug) => ({ slug, title: bySlug.get(slug)?.draft?.title || null }))
}
 
/** The menu entries of the published pages, in menu order (`members`: with members-only ones) */
function buildMenu(pages, { members = false } = {}) {
  return pages
    .filter(
      (page) =>
        page.published && page.showInMenu !== false && (members || page.visibility !== 'members')
    )
    .sort((a, b) => (a.menuOrder ?? 0) - (b.menuOrder ?? 0) || a.slug.localeCompare(b.slug))
    .map((page) => ({
      slug: page.slug,
      title: page.published.title,
      ...(page.visibility === 'members' && { membersOnly: true }),
      ...(page.icon && { icon: page.icon })
    }))
}
 
/**
 * The blocks of a version with a read URL next to each image key
 * (`sign(key)` returns a URL or undefined)
 */
async function withImageUrls(blocks, sign) {
  const signed = async (entry) => {
    if (!entry.imageKey) return entry
    const imageUrl = await sign(entry.imageKey)
    return imageUrl ? { ...entry, imageUrl } : entry
  }
  return Promise.all(
    (blocks || []).map(async (block) => {
      const result = await signed(block)
      if (block.images) return { ...result, images: await Promise.all(block.images.map(signed)) }
      if (block.columns) return { ...result, columns: await Promise.all(block.columns.map(signed)) }
      return result
    })
  )
}
 
module.exports = {
  HOME_SLUG,
  LIMITS,
  VISIBILITIES,
  isPageIcon,
  BLOCK_TYPES,
  BLOCK_ALIGNS,
  DATA_BLOCK_TYPES,
  ENTITY_BLOCK_TYPES,
  PAGE_SLUG_REGEX,
  isPageSlug,
  isSafeUrl,
  pageImagePrefix,
  validatePageInput,
  pageImageKeys,
  buildMenu,
  linkedPageSlugs,
  pagesLinkingTo,
  unpublishedLinkedPages,
  withPageLinksRenamed,
  withImageUrls
}