Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

5.2 KB
Raw Blame
import type JSZipClass from "jszip";

import type { ShareBundleManifest } from "@editor/services/serverStorageBundle";

const MANIFEST_FILENAME = "stirling-share.json";

type HeaderLike = {
  get?: (name: string) => unknown;
  [key: string]: unknown;
};

function headerValueToString(value: unknown): string {
  if (typeof value === "string") return value;
  if (typeof value === "number" || typeof value === "boolean") {
    return String(value);
  }
  if (Array.isArray(value)) {
    const firstString = value.find(
      (entry): entry is string => typeof entry === "string",
    );
    return firstString ?? "";
  }
  return "";
}

function toHeaderKey(name: string): string {
  return name.replace(
    /(^|-)([a-z])/g,
    (_, prefix: string, char: string) => prefix + char.toUpperCase(),
  );
}

export function readResponseHeader(headers: unknown, name: string): string {
  if (!headers || typeof headers !== "object") {
    return "";
  }

  const typedHeaders = headers as HeaderLike;
  if (typeof typedHeaders.get === "function") {
    return headerValueToString(typedHeaders.get(name));
  }

  return (
    headerValueToString(typedHeaders[name]) ||
    headerValueToString(typedHeaders[toHeaderKey(name)])
  );
}

export function parseContentDispositionFilename(
  disposition?: string,
): string | null {
  if (!disposition) return null;
  const filenameMatch = /filename="([^"]+)"/i.exec(disposition);
  if (filenameMatch?.[1]) return filenameMatch[1];
  const utf8Match = /filename\*=UTF-8''([^;]+)/i.exec(disposition);
  if (utf8Match?.[1]) {
    try {
      return decodeURIComponent(utf8Match[1]);
    } catch {
      return utf8Match[1];
    }
  }
  return null;
}

export function isZipBundle(contentType: string, filename: string): boolean {
  return contentType.includes("zip") || filename.toLowerCase().endsWith(".zip");
}

export function getShareBundleEntryRootId(
  manifest: ShareBundleManifest,
  entry: ShareBundleManifest["entries"][number],
): string {
  return entry.rootLogicalId || manifest.rootLogicalId;
}

export function resolveShareBundleOrder(manifest: ShareBundleManifest): {
  rootOrder: string[];
  sortedEntries: ShareBundleManifest["entries"];
} {
  const entryRootId = (entry: ShareBundleManifest["entries"][number]) =>
    getShareBundleEntryRootId(manifest, entry);
  const rootOrder =
    manifest.rootLogicalIds && manifest.rootLogicalIds.length > 0
      ? manifest.rootLogicalIds
      : Array.from(new Set(manifest.entries.map(entryRootId)));
  const sortedEntries: ShareBundleManifest["entries"] = [];
  for (const rootId of rootOrder) {
    const rootEntries = manifest.entries
      .filter((entry) => entryRootId(entry) === rootId)
      .sort((a, b) => a.versionNumber - b.versionNumber);
    sortedEntries.push(...rootEntries);
  }
  return { rootOrder, sortedEntries };
}

// JSZip is ~140 KB and only needed to build or read a share bundle.
let jsZipPromise: Promise<typeof JSZipClass> | null = null;

function loadJSZip(): Promise<typeof JSZipClass> {
  jsZipPromise ??= import("jszip")
    .then((mod) => mod.default)
    .catch((cause) => {
      // Reset so a later caller can retry a failed load.
      jsZipPromise = null;
      throw cause;
    });
  return jsZipPromise;
}

export interface LoadedShareBundle {
  manifest: ShareBundleManifest;
  rootOrder: string[];
  sortedEntries: ShareBundleManifest["entries"];
  files: File[];
}

export async function loadShareBundleEntries(
  blob: Blob,
): Promise<LoadedShareBundle | null> {
  const JSZip = await loadJSZip();
  const zip = await JSZip.loadAsync(blob);
  const manifestEntry = zip.file(MANIFEST_FILENAME);
  if (!manifestEntry) {
    return null;
  }

  const manifestText = await manifestEntry.async("text");
  const manifest = JSON.parse(manifestText) as ShareBundleManifest;
  const { rootOrder, sortedEntries } = resolveShareBundleOrder(manifest);

  const files: File[] = [];
  for (const entry of sortedEntries) {
    const zipEntry = zip.file(entry.filePath);
    if (!zipEntry) {
      throw new Error(`Missing file entry ${entry.filePath}`);
    }
    const fileBlob = await zipEntry.async("blob");
    files.push(
      new File([fileBlob], entry.name, {
        type: entry.type,
        lastModified: entry.lastModified,
      }),
    );
  }

  return { manifest, rootOrder, sortedEntries, files };
}

export async function extractLatestFilesFromBundle(
  blob: Blob,
  filename: string,
  contentType: string,
): Promise<File[]> {
  if (!isZipBundle(contentType, filename)) {
    return [new File([blob], filename, { type: contentType || blob.type })];
  }

  const bundle = await loadShareBundleEntries(blob);
  if (!bundle) {
    return [new File([blob], filename, { type: contentType || blob.type })];
  }

  const { manifest, rootOrder, sortedEntries, files } = bundle;
  const latestByRoot = new Map<string, File>();
  for (let i = 0; i < sortedEntries.length; i += 1) {
    const entry = sortedEntries[i];
    latestByRoot.set(getShareBundleEntryRootId(manifest, entry), files[i]);
  }

  const latestFiles = rootOrder
    .map((rootId) => latestByRoot.get(rootId))
    .filter((file): file is File => Boolean(file));

  if (latestFiles.length > 0) {
    return latestFiles;
  }

  return [new File([blob], filename, { type: contentType || blob.type })];
}