All files / src/utils entityExportBundle.ts

96.66% Statements 29/30
96.29% Branches 26/27
100% Functions 3/3
100% Lines 26/26

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                                      2x                                                                     9x 7x 7x   5x 5x 5x 5x 5x                                             6x 6x   1x     5x 5x 1x     4x   4x 4x   1x     3x 1x     2x 2x 5x 2x     2x    
/**
 * Parses a multi-entity export bundle downloaded from
 * `POST /v1/entities/export` (or selected for import): a `.zip` containing
 * `entity.json` (every entity in the bundle — the one exported plus any
 * private, same-flow `entity_ref` dependencies the backend auto-discovered)
 * alongside the actual bytes of every image/image_set value, under
 * `images/`.
 *
 * Building the bundle/zip itself is a backend concern (`entities/export.js`)
 * — direct DynamoDB/S3 access is faster than N HTTP round-trips, avoids
 * doing the zip work on the user's device, and this same server-side logic
 * will be reused by the Store's "Publish" flow (Phase 2). The client still
 * needs to *parse* a bundle on import though: it stages each embedded image
 * for upload (see Phase 1 section E) before submitting the parsed entities
 * to `POST /v1/entities/import`.
 */
import JSZip from 'jszip'
import type { Entity, EntityField } from '@/stores/entities'
 
export const ENTITY_BUNDLE_VERSION = 2
 
export interface ExportedEntitySchema {
  name: string | Record<string, string>
  fields: EntityField[]
  forms?: Entity['forms']
  commentsEnabled?: boolean
  description?: string | Record<string, string>
  picture?: string
  icon?: string
  defaultLanguage?: string
  enabledLanguages?: string[]
}
 
export interface ExportedEntityBundleEntry {
  tempId: string
  entity: ExportedEntitySchema
  items: Record<string, unknown>[]
}
 
export interface EntityExportBundle {
  bundleVersion: number
  exportedAt: string
  // The entity the user clicked "Export" on, when there is a single one (the
  // Store's future multi-select "Create Package" flow has no single primary).
  primaryTempId?: string
  entities: ExportedEntityBundleEntry[]
}
 
/**
 * Validates the parsed `entity.json` has the minimal shape the backend
 * produces — rejects unrelated/corrupted files early with a clear message
 * instead of a confusing 400 from the API.
 */
export function isValidEntityExportBundle(value: unknown): value is EntityExportBundle {
  if (!value || typeof value !== 'object') return false
  const candidate = value as Record<string, unknown>
  if (!Array.isArray(candidate.entities) || candidate.entities.length === 0) return false
 
  return candidate.entities.every((entry: unknown) => {
    Iif (!entry || typeof entry !== 'object') return false
    const e = entry as Record<string, unknown>
    const entity = e.entity as Record<string, unknown> | undefined
    return (
      typeof e.tempId === 'string' &&
      !!entity &&
      typeof entity === 'object' &&
      !!entity.name &&
      Array.isArray(entity.fields) &&
      (e.items === undefined || Array.isArray(e.items))
    )
  })
}
 
export interface ParsedEntityBundleZip {
  bundle: EntityExportBundle
  imageBlobs: Map<string, Blob>
}
 
/**
 * Unzips a bundle file: reads + validates `entity.json`, and extracts every
 * `images/*` entry into a path -> Blob map (raw material for the Import
 * Preview screen to re-upload — see Phase 1 section D/E — not wired in yet).
 */
export async function parseEntityBundleZip(file: File): Promise<ParsedEntityBundleZip> {
  let zip: JSZip
  try {
    zip = await JSZip.loadAsync(file)
  } catch {
    throw new Error('This file is not a valid zip archive')
  }
 
  const entityJsonFile = zip.file('entity.json')
  if (!entityJsonFile) {
    throw new Error('This file is not a valid entity export (missing entity.json)')
  }
 
  const text = await entityJsonFile.async('string')
  let parsed: unknown
  try {
    parsed = JSON.parse(text)
  } catch {
    throw new Error('This file is not valid JSON')
  }
 
  if (!isValidEntityExportBundle(parsed)) {
    throw new Error('This file is not a valid entity export')
  }
 
  const imageBlobs = new Map<string, Blob>()
  for (const [path, zipObject] of Object.entries(zip.files)) {
    if (zipObject.dir || !path.startsWith('images/')) continue
    imageBlobs.set(path, await zipObject.async('blob'))
  }
 
  return { bundle: parsed, imageBlobs }
}