All files / space-pages put.js

97.87% Statements 92/94
93.24% Branches 69/74
100% Functions 13/13
97.5% Lines 78/80

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                              3x         3x             3x 3x                 3x   3x   4x 3x   5x 3x 3x 4x 3x 5x       4x     4x 1x   3x 3x               1x     2x               6x 6x 5x   4x 4x 4x 3x                 11x 11x 11x 5x               4x     6x                                     3x                     2x   5x   4x 1x       3x 28x 28x 28x 26x 26x   25x 25x     24x 24x   1x   23x 23x 22x 22x 22x   2x       20x 19x 1x   18x 1x   17x         1x     16x 16x                             16x 16x 6x 6x 6x   16x 1x     15x 14x   8x 8x   2x 2x      
// @implements UC-SPACE-009.1, UC-SPACE-016.1
/**
 * PUT /v1/flows/{flowId}/pages/{pageSlug}  (`pages:update`)
 *
 * Creates the page, or saves its draft and settings. Body:
 * `{ title, blocks, visibility, showInMenu, menuOrder, icon?, slug?, expectedUpdatedAt? }`.
 * `slug` renames the page, and the buttons of the other pages leading to it
 * with it, drafts and published versions, in the same transaction
 * (UC-SPACE-016.1), except the home page, which stays the home page (409
 * HOME_PAGE, see utils/spaceHome.js); `expectedUpdatedAt` (the `updatedAt` the editor
 * loaded) refuses to overwrite a newer save (409 PAGE_MODIFIED). The published
 * version is never touched here (publish.js). Pages are free: they are capped
 * (utils/spacePages.js LIMITS). Data blocks must name the flow's own entities,
 * which the member may list (utils/spaceData.js).
 */
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  PutCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const {
  validatePageInput,
  isPageSlug,
  withPageLinksRenamed,
  HOME_SLUG,
  LIMITS
} = require('../utils/spacePages')
const { checkEntityBlocks, DataBlockError } = require('../utils/spaceData')
const {
  respond,
  getPage,
  listPages,
  memberAccess,
  forbidden,
  editorView,
  deleteUnusedImages
} = require('./shared')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const pageModified = () => respond(409, { error: 'PAGE_MODIFIED' })
const slugTaken = () => respond(409, { error: 'SLUG_TAKEN' })
 
const isConditionFailure = (error) => error.name === 'ConditionalCheckFailedException'
const isCancelledBy = (error) =>
  error.name === 'TransactionCanceledException' &&
  (error.CancellationReasons || []).some((reason) => reason?.Code === 'ConditionalCheckFailed')
const isCancelledAt = (error, index) =>
  error.name === 'TransactionCanceledException' &&
  error.CancellationReasons?.[index]?.Code === 'ConditionalCheckFailed'
 
async function createPage(record) {
  const pages = await listPages(docClient, record.flowId, {
    ProjectionExpression: 'slug'
  })
  if (pages.length >= LIMITS.pagesPerFlow) {
    return respond(400, { error: 'TOO_MANY_PAGES', max: LIMITS.pagesPerFlow })
  }
  try {
    await docClient.send(
      new PutCommand({
        TableName: process.env.FLOW_PAGES_TABLE_NAME,
        Item: record,
        ConditionExpression: 'attribute_not_exists(slug)'
      })
    )
  } catch (error) {
    Eif (isConditionFailure(error)) return slugTaken()
    throw error
  }
  return null
}
 
/**
 * The other pages with a button to page `from`, rewritten to lead to `to`,
 * each with the `updatedAt` read (`loaded`), which the transaction checks
 */
async function relinkedPages(flowId, from, to, now, userId) {
  const pages = await listPages(docClient, flowId)
  return pages
    .filter((page) => page.slug !== from)
    .map((page) => {
      const draft = withPageLinksRenamed(page.draft, from, to)
      const published = withPageLinksRenamed(page.published, from, to)
      if (draft === page.draft && published === page.published) return null
      return {
        loaded: page.updatedAt,
        page: { ...page, draft, published, updatedAt: now, updatedBy: userId }
      }
    })
    .filter(Boolean)
}
 
async function savePage(existing, record, relinked = []) {
  const renamed = record.slug !== existing.slug
  try {
    if (!renamed) {
      await docClient.send(
        new PutCommand({
          TableName: process.env.FLOW_PAGES_TABLE_NAME,
          Item: record,
          ConditionExpression: 'updatedAt = :loaded',
          ExpressionAttributeValues: { ':loaded': existing.updatedAt }
        })
      )
      return null
    }
    // Renamed: the old key goes and the new one comes in one transaction
    await docClient.send(
      new TransactWriteCommand({
        TransactItems: [
          {
            Delete: {
              TableName: process.env.FLOW_PAGES_TABLE_NAME,
              Key: { flowId: existing.flowId, slug: existing.slug },
              ConditionExpression: 'updatedAt = :loaded',
              ExpressionAttributeValues: { ':loaded': existing.updatedAt }
            }
          },
          {
            Put: {
              TableName: process.env.FLOW_PAGES_TABLE_NAME,
              Item: record,
              ConditionExpression: 'attribute_not_exists(slug)'
            }
          },
          // The other pages, their buttons now leading to the new slug
          ...relinked.map(({ page, loaded }) => ({
            Put: {
              TableName: process.env.FLOW_PAGES_TABLE_NAME,
              Item: page,
              ConditionExpression: 'updatedAt = :loaded',
              ExpressionAttributeValues: { ':loaded': loaded }
            }
          }))
        ]
      })
    )
    return null
  } catch (error) {
    if (isCancelledAt(error, 1)) return slugTaken()
    // This page, or one of those relinked, was saved meanwhile
    if (isConditionFailure(error) || isCancelledBy(error)) return pageModified()
    throw error
  }
}
 
exports.handler = async (event) => {
  try {
    const access = await memberAccess(event)
    if (access.response) return access.response
    const { flowId, userId, canEdit } = access
    if (!canEdit) return forbidden()
 
    const pageSlug = event.pathParameters?.pageSlug
    if (!isPageSlug(pageSlug)) return respond(400, { error: 'Invalid page slug' })
 
    let body
    try {
      body = JSON.parse(event.body || '{}')
    } catch {
      return respond(400, { error: 'Invalid JSON body' })
    }
    const input = validatePageInput(body, flowId)
    if (!input.valid) return respond(400, { error: input.error })
    const { draft, visibility, showInMenu, menuOrder, icon } = input.value
    try {
      await checkEntityBlocks(docClient, access, draft.blocks)
    } catch (error) {
      Eif (error instanceof DataBlockError) return respond(error.statusCode, error.body)
      throw error
    }
 
    const existing = await getPage(docClient, flowId, pageSlug)
    if (!existing && input.value.slug && input.value.slug !== pageSlug) {
      return respond(404, { error: 'Page not found' })
    }
    if (pageSlug === HOME_SLUG && input.value.slug && input.value.slug !== HOME_SLUG) {
      return respond(409, { error: 'HOME_PAGE' })
    }
    if (
      existing &&
      body.expectedUpdatedAt !== undefined &&
      body.expectedUpdatedAt !== existing.updatedAt
    ) {
      return pageModified()
    }
 
    const now = new Date().toISOString()
    const record = {
      flowId,
      slug: input.value.slug || pageSlug,
      visibility,
      showInMenu,
      menuOrder,
      ...(icon && { icon }),
      draft,
      published: existing?.published || null,
      createdAt: existing?.createdAt || now,
      createdBy: existing?.createdBy || userId,
      updatedAt: now,
      updatedBy: userId
    }
    // Renamed: the buttons leading to the page follow it, its own and the other pages'
    let relinked = []
    if (existing && record.slug !== pageSlug) {
      record.draft = withPageLinksRenamed(record.draft, pageSlug, record.slug)
      record.published = withPageLinksRenamed(record.published, pageSlug, record.slug)
      relinked = await relinkedPages(flowId, pageSlug, record.slug, now, userId)
    }
    if (Buffer.byteLength(JSON.stringify(record)) > LIMITS.pageBytes) {
      return respond(400, { error: 'PAGE_TOO_LARGE' })
    }
 
    const refused = existing ? await savePage(existing, record, relinked) : await createPage(record)
    if (refused) return refused
 
    if (existing) await deleteUnusedImages(flowId, existing, record)
    return respond(existing ? 200 : 201, await editorView(docClient, record))
  } catch (error) {
    console.error('Error saving a space page:', error)
    return respond(500, { error: 'Failed to save page' })
  }
}