All files / lib/attachment-archive archive-manifest.ts

96% Statements 72/75
79.66% Branches 47/59
100% Functions 29/29
95.77% Lines 68/71

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                                              7x       2x   2x       2x 2x 2x       31x   31x 35x 34x 34x     1x 1x   1x 1x 1x     1x 1x         101x       14x               224x   14x 56x         31x 35x               6x                     230x                   56x       29x                       28x                                 148x       148x 148x   148x 66x     82x       82x                 62x                       43x                       43x                   29x   29x 14x     15x 15x 15x           31x 31x 35x   35x           31x                 35x                     31x   31x                                               28x 28x                 28x                       28x                                                                                                   53x                                             8x                   8x                                                     44x 10x       34x 34x   1x     33x 33x    
import { createHash } from "crypto";
import { z } from "zod";
 
import {
  ATTACHMENT_ARCHIVE_BUILD_VERSION,
  ATTACHMENT_ARCHIVE_FAILURE_CODES,
  ATTACHMENT_ARCHIVE_NAMESPACES,
  ATTACHMENT_ARCHIVE_SCOPES,
  ATTACHMENT_ARCHIVE_STATUSES,
  AttachmentArchiveBlockedAttachment,
  AttachmentArchiveCurrent,
  AttachmentArchiveFailureCode,
  AttachmentArchiveNamespace,
  AttachmentArchivePackageManifest,
  AttachmentArchivePackageManifestSection,
  AttachmentArchiveScope,
  AttachmentArchiveSectionManifest,
  AttachmentArchiveSectionRequest,
  AttachmentArchiveSourceAttachment,
  AttachmentArchiveStatus,
} from "./types";
 
function compareStrings(left: string, right: string): number {
  return left.localeCompare(right);
}
 
function buildArchiveEntryFilename(filename: string, index: number): string {
  const lastDot = filename.lastIndexOf(".");
 
  Iif (lastDot <= 0) {
    return `${filename} (${index})`;
  }
 
  const basename = filename.slice(0, lastDot);
  const extension = filename.slice(lastDot);
  return `${basename} (${index})${extension}`;
}
 
function getUniqueArchiveEntryFilenames(filenames: string[]): string[] {
  const usedNames = new Set<string>();
 
  return filenames.map((filename) => {
    if (!usedNames.has(filename)) {
      usedNames.add(filename);
      return filename;
    }
 
    let duplicateIndex = 2;
    let candidate = buildArchiveEntryFilename(filename, duplicateIndex);
 
    while (usedNames.has(candidate)) {
      duplicateIndex += 1;
      candidate = buildArchiveEntryFilename(filename, duplicateIndex);
    }
 
    usedNames.add(candidate);
    return candidate;
  });
}
 
function sanitizeDownloadComponent(value: string): string {
  return value.replace(/[^A-Za-z0-9._-]+/g, "_");
}
 
function formatEasternDownloadDate(now = new Date()): string {
  const parts = new Intl.DateTimeFormat("en-US", {
    timeZone: "America/New_York",
    weekday: "short",
    month: "short",
    day: "numeric",
    year: "numeric",
  }).formatToParts(now);
 
  const getPart = (type: string) => parts.find((part) => part.type === type)?.value;
 
  return [getPart("weekday"), getPart("month"), getPart("day"), getPart("year")]
    .filter((value): value is string => Boolean(value))
    .join(" ");
}
 
function sortAttachments(attachments: AttachmentArchiveSourceAttachment[]) {
  return [...attachments]
    .map((attachment) => ({
      bucket: attachment.bucket,
      key: attachment.key,
      filename: attachment.filename,
      title: attachment.title,
      uploadDate: attachment.uploadDate,
    }))
    .sort((left, right) => {
      return (
        compareStrings(left.filename, right.filename) ||
        compareStrings(left.key, right.key) ||
        compareStrings(left.bucket, right.bucket) ||
        compareStrings(left.title, right.title) ||
        (left.uploadDate || 0) - (right.uploadDate || 0)
      );
    });
}
 
export function normalizeArchivePathComponent(value: string): string {
  return encodeURIComponent(value);
}
 
export function buildSectionArchiveFolderName({
  sectionNumber,
  sectionLabel,
}: {
  sectionNumber: number;
  sectionLabel: string;
}): string {
  return `section-${sectionNumber}-${sectionLabel}`;
}
 
export function getPackageArchiveRootFolderName(packageId: string): string {
  return `${sanitizeDownloadComponent(packageId)}-attachments`;
}
 
export function getSectionArchiveRootFolderName({
  packageId,
  sectionNumber,
  sectionLabel,
}: {
  packageId: string;
  sectionNumber: number;
  sectionLabel: string;
}): string {
  return `${sanitizeDownloadComponent(packageId)}-${buildSectionArchiveFolderName({
    sectionNumber,
    sectionLabel,
  })}`;
}
 
export function getArchiveBasePrefix({
  packageId,
  scope,
  sectionId,
  archiveNamespace = "main",
}: {
  packageId: string;
  scope: AttachmentArchiveScope;
  sectionId?: string;
  archiveNamespace?: AttachmentArchiveNamespace;
}): string {
  Iif (!ATTACHMENT_ARCHIVE_NAMESPACES.includes(archiveNamespace)) {
    throw new Error(`Unsupported attachment archive namespace: ${archiveNamespace}`);
  }
 
  const normalizedPackageId = normalizeArchivePathComponent(packageId);
  const namespacePrefix = archiveNamespace === "draft" ? "/draft" : "";
 
  if (scope === "all") {
    return `package/${normalizedPackageId}${namespacePrefix}/all`;
  }
 
  Iif (!sectionId) {
    throw new Error("sectionId is required for section-scoped archives");
  }
 
  return `package/${normalizedPackageId}${namespacePrefix}/section/${normalizeArchivePathComponent(sectionId)}`;
}
 
export function getArchiveCurrentKey(request: {
  packageId: string;
  scope: AttachmentArchiveScope;
  sectionId?: string;
  archiveNamespace?: AttachmentArchiveNamespace;
}): string {
  return `${getArchiveBasePrefix(request)}/current.json`;
}
 
export function getArchiveManifestKey(
  request: {
    packageId: string;
    scope: AttachmentArchiveScope;
    sectionId?: string;
    archiveNamespace?: AttachmentArchiveNamespace;
  },
  hash: string,
): string {
  return `${getArchiveBasePrefix(request)}/${hash}.manifest.json`;
}
 
export function getArchiveArtifactKey(
  request: {
    packageId: string;
    scope: AttachmentArchiveScope;
    sectionId?: string;
    archiveNamespace?: AttachmentArchiveNamespace;
  },
  hash: string,
): string {
  return `${getArchiveBasePrefix(request)}/${hash}.zip`;
}
 
export function getArchiveDownloadFilename(request: {
  packageId: string;
  scope: AttachmentArchiveScope;
  sectionNumber?: number;
  sectionLabel?: string;
  now?: Date;
}): string {
  const packageId = sanitizeDownloadComponent(request.packageId);
 
  if (request.scope === "all") {
    return `${packageId} - ${formatEasternDownloadDate(request.now)}.zip`;
  }
 
  const sectionNumber = request.sectionNumber || 1;
  const sectionLabel = sanitizeDownloadComponent(request.sectionLabel || "section");
  return `${packageId}-section-${sectionNumber}-${sectionLabel}-attachments.zip`;
}
 
export function buildSectionAttachmentArchiveManifest(
  request: AttachmentArchiveSectionRequest,
): AttachmentArchiveSectionManifest {
  const sortedAttachments = sortAttachments(request.attachments);
  const archiveFilenames = getUniqueArchiveEntryFilenames(
    sortedAttachments.map((attachment) => attachment.filename),
  );
  const attachments = sortedAttachments.map((attachment, index) => ({
    ...attachment,
    archiveFilename: archiveFilenames[index],
    archivePath: `${request.rootFolderName}/${archiveFilenames[index]}`,
  }));
 
  const canonicalPayload = JSON.stringify({
    buildVersion: ATTACHMENT_ARCHIVE_BUILD_VERSION,
    packageId: request.packageId,
    scope: request.scope,
    sectionId: request.sectionId,
    sectionNumber: request.sectionNumber,
    sectionLabel: request.sectionLabel,
    sectionFolderName: request.sectionFolderName,
    rootFolderName: request.rootFolderName,
    attachments: attachments.map((attachment) => ({
      archiveFilename: attachment.archiveFilename,
      archivePath: attachment.archivePath,
      bucket: attachment.bucket,
      filename: attachment.filename,
      key: attachment.key,
      title: attachment.title,
      uploadDate: attachment.uploadDate,
    })),
  });
 
  const hash = createHash("sha256").update(canonicalPayload).digest("hex");
 
  return {
    version: 2,
    buildVersion: ATTACHMENT_ARCHIVE_BUILD_VERSION,
    type: "section",
    packageId: request.packageId,
    scope: "section",
    sectionId: request.sectionId,
    sectionNumber: request.sectionNumber,
    sectionLabel: request.sectionLabel,
    sectionFolderName: request.sectionFolderName,
    rootFolderName: request.rootFolderName,
    hash,
    createdAt: new Date().toISOString(),
    attachments,
  };
}
 
export function buildPackageAttachmentArchiveManifest({
  packageId,
  sections,
}: {
  packageId: string;
  sections: AttachmentArchivePackageManifestSection[];
}): AttachmentArchivePackageManifest {
  const rootFolderName = getPackageArchiveRootFolderName(packageId);
  const canonicalSections = sections.map((section) => ({
    sectionId: section.sectionId,
    sectionNumber: section.sectionNumber,
    sectionLabel: section.sectionLabel,
    sectionFolderName: section.sectionFolderName,
    rootFolderName: section.rootFolderName,
    attachmentCount: section.attachmentCount,
    hash: section.hash,
  }));
  const hash = createHash("sha256")
    .update(
      JSON.stringify({
        buildVersion: ATTACHMENT_ARCHIVE_BUILD_VERSION,
        packageId,
        scope: "all",
        rootFolderName,
        sections: canonicalSections,
      }),
    )
    .digest("hex");
 
  return {
    version: 2,
    buildVersion: ATTACHMENT_ARCHIVE_BUILD_VERSION,
    type: "package",
    packageId,
    scope: "all",
    hash,
    createdAt: new Date().toISOString(),
    rootFolderName,
    sections,
  };
}
 
export function buildAttachmentArchiveCurrent({
  scope,
  hash,
  status,
  artifactKey,
  manifestKey,
  attachmentCount,
  appendedAttachmentCount,
  skippedAttachmentCount,
  executionArn,
  sectionId,
  sectionNumber,
  sectionLabel,
  sectionFolderName,
  failureCode,
  failureMessage,
  blockedAttachment,
  errorMessage,
}: {
  scope: AttachmentArchiveScope;
  hash: string;
  status: AttachmentArchiveStatus;
  artifactKey: string;
  manifestKey: string;
  attachmentCount: number;
  appendedAttachmentCount?: number;
  skippedAttachmentCount?: number;
  executionArn?: string;
  sectionId?: string;
  sectionNumber?: number;
  sectionLabel?: string;
  sectionFolderName?: string;
  failureCode?: AttachmentArchiveFailureCode;
  failureMessage?: string;
  blockedAttachment?: AttachmentArchiveBlockedAttachment;
  errorMessage?: string;
}): AttachmentArchiveCurrent {
  return {
    version: 2,
    scope,
    hash,
    status,
    artifactKey,
    manifestKey,
    attachmentCount,
    ...(typeof appendedAttachmentCount === "number" ? { appendedAttachmentCount } : {}),
    ...(typeof skippedAttachmentCount === "number" ? { skippedAttachmentCount } : {}),
    updatedAt: new Date().toISOString(),
    ...(executionArn ? { executionArn } : {}),
    ...(sectionId ? { sectionId } : {}),
    ...(sectionNumber ? { sectionNumber } : {}),
    ...(sectionLabel ? { sectionLabel } : {}),
    ...(sectionFolderName ? { sectionFolderName } : {}),
    ...(failureCode ? { failureCode } : {}),
    ...(failureMessage ? { failureMessage } : {}),
    ...(blockedAttachment ? { blockedAttachment } : {}),
    ...(errorMessage || failureMessage ? { errorMessage: errorMessage || failureMessage } : {}),
  };
}
 
export const AttachmentArchiveBlockedAttachmentSchema = z
  .object({
    bucket: z.string(),
    key: z.string(),
    filename: z.string(),
    title: z.string(),
    virusScanStatus: z.string().optional(),
  })
  .passthrough();
 
export const AttachmentArchiveCurrentSchema = z
  .object({
    version: z.literal(2),
    scope: z.enum(ATTACHMENT_ARCHIVE_SCOPES),
    hash: z.string(),
    status: z.enum(ATTACHMENT_ARCHIVE_STATUSES),
    artifactKey: z.string(),
    manifestKey: z.string(),
    attachmentCount: z.number(),
    appendedAttachmentCount: z.number().optional(),
    skippedAttachmentCount: z.number().optional(),
    updatedAt: z.string(),
    executionArn: z.string().optional(),
    sectionId: z.string().optional(),
    sectionNumber: z.number().optional(),
    sectionLabel: z.string().optional(),
    sectionFolderName: z.string().optional(),
    failureCode: z.enum(ATTACHMENT_ARCHIVE_FAILURE_CODES).optional(),
    failureMessage: z.string().optional(),
    blockedAttachment: AttachmentArchiveBlockedAttachmentSchema.optional(),
    errorMessage: z.string().optional(),
  })
  .passthrough();
 
export function parseAttachmentArchiveCurrent(
  value: string | undefined,
): AttachmentArchiveCurrent | undefined {
  if (!value) {
    return undefined;
  }
 
  let parsed: unknown;
  try {
    parsed = JSON.parse(value);
  } catch {
    return undefined;
  }
 
  const result = AttachmentArchiveCurrentSchema.safeParse(parsed);
  return result.success ? (result.data as AttachmentArchiveCurrent) : undefined;
}