All files / entities export-discover.js

86.04% Statements 37/43
73.91% Branches 17/23
100% Functions 6/6
92.3% Lines 36/39

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 1121x 1x 1x           1x     15x                     15x 15x 15x   15x 15x   1x                   15x                         15x 15x 15x 1x     14x 14x 14x       14x 14x 1x     13x         13x 13x 15x 15x 1x   14x 2x   12x     10x         10x   10x 15x                               1x  
const { getActiveFlowId } = require('../shared/activeFlow')
const { requirePermission } = require('../utils/requirePermission')
const { permissionChecker } = require('../utils/PermissionChecker')
const {
  getDisplayName,
  isAccessible,
  fetchEntity,
  discoverBundle
} = require('../utils/entityBundleDiscovery')
 
function jsonResponse(statusCode, body) {
  return {
    statusCode,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    },
    body: JSON.stringify(body)
  }
}
 
function safeParseBody(rawBody) {
  Iif (!rawBody) return {}
  Iif (typeof rawBody === 'object') return rawBody
  Iif (typeof rawBody !== 'string') return {}
 
  try {
    return JSON.parse(rawBody)
  } catch {
    return null
  }
}
 
// Static proxy for "would this entity's export actually contain per-item
// images": true only when the schema has an image/image_set field — lets the
// sidebar hide the per-entity images checkbox for entities that have none.
// A lone entity picture/icon (with no image field) isn't enough to warrant
// the toggle — it's always included regardless.
function entityHasImages(entity) {
  return (entity.fields || []).some((field) => field.type === 'image' || field.type === 'image_set')
}
 
/**
 * Preview of what `POST /v1/entities/export` would bundle for the given
 * `entityIds`, without building a zip (no S3 reads, no image work, item
 * counts only) — powers the Export sidebar's dependency tree: which
 * entities would be bundled, whether each has items/images worth an
 * include toggle, and `dependsOn` so the frontend can recompute, on each
 * toggle, which entities are still reachable from the ones the user kept
 * checked.
 */
async function exportDiscoverHandler(event) {
  try {
    const body = safeParseBody(event.body)
    if (body === null) {
      return jsonResponse(400, { error: 'Invalid JSON body' })
    }
 
    const flowId = await getActiveFlowId(event)
    const userId = event.requestContext?.authorizer?.claims?.sub
    Iif (!flowId) {
      return jsonResponse(401, { error: 'Missing flow context' })
    }
 
    const entityIds = Array.isArray(body.entityIds) ? body.entityIds : []
    if (entityIds.length === 0) {
      return jsonResponse(400, { error: 'Missing entityIds' })
    }
 
    const { permissions: callerPermissions = [] } = await permissionChecker.getUserPermissions(
      userId,
      flowId
    )
 
    const startingEntities = []
    for (const id of entityIds) {
      const entity = await fetchEntity(id)
      if (!entity) {
        return jsonResponse(404, { error: `Entity not found: ${id}` })
      }
      if (!isAccessible(entity, flowId, callerPermissions)) {
        return jsonResponse(403, { error: `Access denied to entity: ${id}` })
      }
      startingEntities.push(entity)
    }
 
    const { entries, cyclesBroken } = await discoverBundle(startingEntities, flowId, {
      itemsMode: 'count',
      callerPermissions
    })
 
    const rootIds = new Set(entityIds)
 
    return jsonResponse(200, {
      entities: entries.map((entry) => ({
        id: entry.entity.id,
        name: getDisplayName(entry.entity),
        itemCount: entry.itemCount,
        hasImages: entityHasImages(entry.entity),
        isRoot: rootIds.has(entry.entity.id),
        dependsOn: entry.dependsOn
      })),
      cyclesBroken
    })
  } catch (error) {
    console.error('[export-discover] Exception:', error.message, error.stack)
    return jsonResponse(500, { error: 'Failed to discover export dependencies' })
  }
}
 
exports.handler = requirePermission(exportDiscoverHandler, { permission: 'entities:list' })