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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 25x 21x 19x 19x 20x 5x 5x 19x 5x 14x 4x 3x 5x 45x 33x 9x 15x 15x 20x 20x 20x 20x 5x 3x 3x 2x 2x 2x 15x 15x 20x 2x 20x 20x 20x 5x 3x 3x 2x 2x 1x 3x 3x 3x 4x 4x 3x 1x 1x 15x 20x 20x 5x 15x 15x 15x 15x 15x 15x 15x 4x 4x 3x 3x 3x 4x 15x 15x 15x 11x 11x 11x 11x 5x 5x 2x 4x 6x 6x 5x 6x 6x 3x 5x 5x 5x 6x 4x 4x 4x 4x 4x 6x 6x 6x 6x 1x 6x 6x 6x 4x 25x 25x 3x 22x 22x 22x 22x 21x 21x 21x 23x 23x 22x 1x 21x 19x 19x 19x 17x 19x 19x 19x 19x 19x 3x 3x 1x 25x 25x 25x | const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3')
const { randomUUID } = require('crypto')
const JSZip = require('jszip')
const { checkPermissionDirect } = require('../utils/requirePermission')
const { permissionChecker } = require('../utils/PermissionChecker')
const {
pickTranslation,
getDisplayName,
isAccessible,
fetchEntity,
discoverBundle
} = require('../utils/entityBundleDiscovery')
const {
getJob,
markJobProcessing,
markJobCompleted,
markJobFailed,
createThrottledProgressReporter
} = require('../utils/jobsTable')
const { BUNDLE_VERSION } = require('../utils/bundleFormat')
const s3Client = new S3Client({})
const ITEM_METADATA_KEYS = new Set([
'id',
'entityId',
'flowId',
'createdBy',
'createdAt',
'updatedAt'
])
function slugifyFilename(name) {
return (
name
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '') || 'entities'
)
}
function zipFilenameFor(entries, primaryTempId) {
const primary = entries.find((entry) => entry.tempId === primaryTempId) || entries[0]
const base = primary ? slugifyFilename(getDisplayName(primary.entity)) : 'entities'
return `${base}-export.zip`
}
function stripEntity(entity, { includeImages }) {
return {
name: entity.name,
fields: entity.fields,
...(entity.forms?.length && { forms: entity.forms }),
...(entity.emailTemplates?.length && { emailTemplates: entity.emailTemplates }),
...(entity.commentsEnabled === true && { commentsEnabled: true }),
...(entity.description && { description: entity.description }),
...(includeImages && entity.picture && { picture: entity.picture }),
...(includeImages && entity.icon && { icon: entity.icon }),
...(entity.defaultLanguage && { defaultLanguage: entity.defaultLanguage }),
...(entity.enabledLanguages && { enabledLanguages: entity.enabledLanguages })
}
}
// Keeps the item's original id (renamed to `originalId`, so it's clearly not
// a real id to import as-is) — needed so import-worker.js can remap
// `entity_ref` field *values* that point at another item bundled in the same
// export (e.g. an Invoice item referencing a specific Client item) onto the
// new item ids assigned at import time. Every other internal field is
// dropped — including image/image_set values when `includeImages` is false,
// so a lighter export never carries dangling S3 key references.
function stripItem(item, { imageFieldIdSet, includeImages }) {
const data = {}
for (const [key, value] of Object.entries(item)) {
if (key === 'id') {
data.originalId = value
} else if (!ITEM_METADATA_KEYS.has(key)) {
if (!includeImages && imageFieldIdSet.has(key)) continue
data[key] = value
}
}
return data
}
function imageFieldIds(fields) {
return new Set(
(fields || [])
.filter((field) => field.type === 'image' || field.type === 'image_set')
.map((field) => field.fieldId)
.filter(Boolean)
)
}
function collectImageKeys(bundle) {
const keys = new Set()
for (const entry of bundle.entities) {
if (entry.entity.picture) keys.add(entry.entity.picture)
Iif (entry.entity.icon) keys.add(entry.entity.icon)
const fieldIds = imageFieldIds(entry.entity.fields)
for (const item of entry.items) {
for (const fieldId of fieldIds) {
const value = item[fieldId]
if (!value) continue
Iif (Array.isArray(value)) {
for (const entry of value) {
if (typeof entry === 'string') keys.add(entry)
}
} else Eif (typeof value === 'string') {
keys.add(value)
}
}
}
}
return [...keys]
}
function rewriteImageKeys(bundle, keyToZipPath) {
for (const entry of bundle.entities) {
if (entry.entity.picture && keyToZipPath.has(entry.entity.picture)) {
entry.entity.picture = keyToZipPath.get(entry.entity.picture)
}
Iif (entry.entity.icon && keyToZipPath.has(entry.entity.icon)) {
entry.entity.icon = keyToZipPath.get(entry.entity.icon)
}
const fieldIds = imageFieldIds(entry.entity.fields)
for (const item of entry.items) {
for (const fieldId of fieldIds) {
const value = item[fieldId]
if (!value) continue
Iif (Array.isArray(value)) {
item[fieldId] = value.map((entry) =>
typeof entry === 'string' && keyToZipPath.has(entry) ? keyToZipPath.get(entry) : entry
)
} else if (typeof value === 'string' && keyToZipPath.has(value)) {
item[fieldId] = keyToZipPath.get(value)
}
}
}
}
}
function extensionFromKey(key) {
const last = key.split('/').pop() || ''
const dot = last.lastIndexOf('.')
return dot >= 0 ? last.slice(dot + 1) : 'bin'
}
async function readS3Object(key) {
try {
const result = await s3Client.send(
new GetObjectCommand({ Bucket: process.env.ATTACHMENTS_BUCKET_NAME, Key: key })
)
return await result.Body.transformToByteArray()
} catch (error) {
console.warn(`[export-worker] Could not read image ${key}:`, error.message)
return null
}
}
/**
* Builds the export zip: `entity.json` (the bundle, image values rewritten
* to `images/<n>.<ext>` paths) plus the actual image bytes, read directly
* from S3. An image that can't be read is left as its original live S3 key
* in the JSON rather than failing the whole export. `onProgress(done, total)`
* — the entity-stripping pass is synchronous/fast, so it's reported as done
* in one shot (`done: entries.length`) as soon as `total` becomes known (it
* depends on how many images the stripped bundle actually references); each
* subsequent image read then increments `done` by one.
*/
async function buildExportZip(entries, primaryTempId, { excludeImagesEntityIds, onProgress }) {
const bundleEntities = entries.map(({ tempId, entity, items }) => {
const includeImages = !excludeImagesEntityIds.has(entity.id)
return {
tempId,
entity: stripEntity(entity, { includeImages }),
items: items.map((item) =>
stripItem(item, { imageFieldIdSet: imageFieldIds(entity.fields), includeImages })
)
}
})
const bundle = {
bundleVersion: BUNDLE_VERSION,
exportedAt: new Date().toISOString(),
...(primaryTempId && { primaryTempId }),
entities: bundleEntities
}
const imageKeys = collectImageKeys(bundle)
const total = entries.length + imageKeys.length
await onProgress?.(entries.length, total)
const zip = new JSZip()
const keyToZipPath = new Map()
for (const [index, key] of imageKeys.entries()) {
const bytes = await readS3Object(key)
if (bytes) {
const zipPath = `images/${index}.${extensionFromKey(key)}`
zip.file(zipPath, Buffer.from(bytes))
keyToZipPath.set(key, zipPath)
}
await onProgress?.(entries.length + index + 1, total)
}
rewriteImageKeys(bundle, keyToZipPath)
zip.file('entity.json', JSON.stringify(bundle, null, 2))
return zip.generateAsync({ type: 'nodebuffer' })
}
function csvEscape(value) {
Iif (value === null || value === undefined) return ''
const str = Array.isArray(value) ? value.join('; ') : String(value)
Iif (/[",\n]/.test(str)) {
return `"${str.replace(/"/g, '""')}"`
}
return str
}
function fieldColumnHeaders(field, enabledLanguages) {
const label = pickTranslation(field.name, field.fieldId)
// Multilingual values get one column per configured language rather than
// a single column that can only hold one language's text.
if (enabledLanguages.length > 1) {
return enabledLanguages.map((lang) => ({
key: field.fieldId,
header: `${label} (${lang})`,
lang
}))
}
return [{ key: field.fieldId, header: label }]
}
// Flattens one entity's items into a CSV string — one row per item, one
// column per field (expanded per language for multilingual entities).
// Columns come from the entity's own field list, so internal item metadata
// (id/entityId/flowId/...) is naturally never included.
function itemsToCsv(entity, items) {
const enabledLanguages = entity.enabledLanguages?.length ? entity.enabledLanguages : ['en']
const columns = (entity.fields || []).flatMap((field) =>
fieldColumnHeaders(field, enabledLanguages)
)
const headerRow = columns.map((col) => csvEscape(col.header)).join(',')
const rows = items.map((item) =>
columns
.map((col) => {
const raw = item[col.key]
const value = col.lang && raw && typeof raw === 'object' ? raw[col.lang] : raw
return csvEscape(value)
})
.join(',')
)
return [headerRow, ...rows].join('\n')
}
/**
* Builds a zip of one `<entity-name>.csv` per bundled entity — items only,
* flattened, no schema/images. Names are deduped (a public entity from
* another flow could coincidentally share a name with one of the caller's
* own) by appending a counter suffix.
*/
async function buildCsvExportZip(entries, { onProgress }) {
const zip = new JSZip()
const usedNames = new Set()
const total = entries.length
let done = 0
for (const { entity, items } of entries) {
const base = slugifyFilename(getDisplayName(entity))
let filename = `${base}.csv`
let counter = 2
while (usedNames.has(filename)) {
filename = `${base}-${counter++}.csv`
}
usedNames.add(filename)
zip.file(filename, itemsToCsv(entity, items))
await onProgress?.(++done, total)
}
return zip.generateAsync({ type: 'nodebuffer' })
}
async function processExportJob(jobId) {
const job = await getJob(jobId)
// Only ever run a job from `pending` — if status is anything else (already
// `completed`/`failed`, or `processing` because a previous attempt got far
// enough to mark it so before crashing), skip rather than redo the work.
// Re-running from scratch on a redelivered message would re-run discovery/
// zip-build with a brand new zip key, harmless here but not a pattern worth
// relying on — see import-worker.js, where the equivalent re-run would
// risk creating duplicate entities.
if (!job || job.status !== 'pending') {
return
}
const { flowId, userId, request } = job
const { entityIds, format, excludeEntityIds, excludeItemsEntityIds, excludeImagesEntityIds } =
request
try {
await checkPermissionDirect(userId, flowId, 'entities:list')
// Re-resolved here rather than trusted from the request: access may have
// been revoked between the request and this job running.
const { permissions: callerPermissions = [] } = await permissionChecker.getUserPermissions(
userId,
flowId
)
const startingEntities = []
for (const id of entityIds) {
const entity = await fetchEntity(id)
if (!entity) throw new Error(`Entity not found: ${id}`)
if (!isAccessible(entity, flowId, callerPermissions))
throw new Error(`Access denied to entity: ${id}`)
startingEntities.push(entity)
}
await markJobProcessing(jobId)
const { entries, cyclesBroken } = await discoverBundle(startingEntities, flowId, {
itemsMode: 'full',
excludeEntityIds: new Set(excludeEntityIds),
excludeItemsEntityIds: new Set(excludeItemsEntityIds),
callerPermissions
})
const primaryTempId =
entityIds.length === 1
? entries.find((entry) => entry.entity.id === startingEntities[0].id)?.tempId
: undefined
const report = createThrottledProgressReporter(jobId)
const zipBuffer =
format === 'csv'
? await buildCsvExportZip(entries, { onProgress: report })
: await buildExportZip(entries, primaryTempId, {
excludeImagesEntityIds: new Set(excludeImagesEntityIds),
onProgress: report
})
const zipKey = `exports/${userId}/${randomUUID()}.zip`
await s3Client.send(
new PutObjectCommand({
Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
Key: zipKey,
Body: zipBuffer,
ContentType: 'application/zip',
ContentDisposition: `attachment; filename="${zipFilenameFor(entries, primaryTempId)}"`
})
)
await markJobCompleted(jobId, {
zipKey,
entityCount: entries.length,
cyclesBroken
})
} catch (error) {
console.error('[export-worker] Job failed:', jobId, error.message, error.stack)
await markJobFailed(jobId, error.message || 'Failed to export entities')
}
}
exports.handler = async (event) => {
for (const record of event.Records) {
const { jobId } = JSON.parse(record.body)
await processExportJob(jobId)
}
}
|