/** * @file packages/thread/src/zipjs.ts * @description This file contains zip.js utility functions. * @author Luca Liguori * @created 2026-03-11 * @version 1.0.1 * @license Apache-2.0 * * Copyright 2025, 2026, 2027 Luca Liguori. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { configure, Uint8ArrayReader, Uint8ArrayWriter, ZipReader, ZipWriter } from '@zip.js/zip.js'; import { AnsiLogger, LogLevel, TimestampFormat } from 'node-ansi-logger'; // Compress inline instead of in zip.js web workers. Bun has a global Worker, so zip.js would spawn codec workers and keep // them alive for terminateWorkerTimeout (5 s) after use, holding the calling thread open. Node has no global Worker and // always runs inline, so this also makes the two runtimes behave the same. We already run inside a worker thread. configure({ useWebWorkers: false }); export interface ZipContentEntry { filename: string; directory: boolean; compressedSize: number; uncompressedSize: number; lastModDate: Date; } /** * Creates a zip archive containing the provided files and directories. * * @param {string} zipPath - The output zip file path. * @param {string[]} sourcePaths - The files and directories to include in the archive. * @param {string[]} [archiveNames] - Optional names of the top-level entries in the archive, one per source path. Defaults to the basename of each source path. * @returns {Promise} The size of the generated zip file in bytes. */ export async function createZip(zipPath: string, sourcePaths: string[], archiveNames?: string[]): Promise { if (sourcePaths.length === 0) throw new Error('No files or directories provided to createZip.'); const log = createLogger(); const writer = new ZipWriter(new Uint8ArrayWriter()); let entryCount = 0; for (const [index, sourcePath] of sourcePaths.entries()) { const resolvedSourcePath = path.resolve(sourcePath); entryCount += await addZipEntry(writer, resolvedSourcePath, archiveNames?.[index] ?? path.basename(resolvedSourcePath), log); } const zipData = await writer.close(); await mkdir(path.dirname(zipPath), { recursive: true }); await writeFile(zipPath, zipData); log.info(`Created zip ${zipPath} with ${entryCount} entries (${zipData.byteLength} bytes).`); return zipData.byteLength; } /** * Reads a zip archive and logs its content. * * @param {string} zipPath - The zip file path. * @returns {Promise} The entries found in the archive. */ export async function readZip(zipPath: string): Promise { const log = createLogger(); const reader = new ZipReader(new Uint8ArrayReader(await readFile(zipPath))); try { const entries = await reader.getEntries(); const content = entries.map((entry) => ({ filename: entry.filename, directory: entry.directory, compressedSize: entry.compressedSize, uncompressedSize: entry.uncompressedSize, lastModDate: entry.lastModDate, })); if (content.length === 0) { log.info(`Zip ${zipPath} is empty.`); } else { for (const entry of content) { log.info(`${entry.directory ? 'dir ' : 'file'} ${entry.filename} (${entry.uncompressedSize} bytes)`); } } return content; } finally { await reader.close(); } } /** * Extracts a zip archive into a directory next to the zip file. * * @param {string} zipPath - The zip file path. * @param {string} [destinationPath] - Optional output directory path. * @returns {Promise} The extraction directory path. */ export async function unZip(zipPath: string, destinationPath: string = getDefaultDestinationPath(zipPath)): Promise { const log = createLogger(); const reader = new ZipReader(new Uint8ArrayReader(await readFile(zipPath))); let extractedEntries = 0; await mkdir(destinationPath, { recursive: true }); try { const entries = await reader.getEntries(); for (const entry of entries) { const entryPath = resolveEntryPath(destinationPath, entry.filename); if (entry.directory) { await mkdir(entryPath, { recursive: true }); extractedEntries++; continue; } await mkdir(path.dirname(entryPath), { recursive: true }); const fileData = await entry.getData(new Uint8ArrayWriter()); await writeFile(entryPath, fileData); extractedEntries++; } } finally { await reader.close(); } log.info(`Extracted ${extractedEntries} entries from ${zipPath} to ${destinationPath}.`); return destinationPath; } /** * Creates the logger used by the zip helpers. * * @returns {AnsiLogger} The configured logger instance. */ function createLogger(): AnsiLogger { return new AnsiLogger({ logName: 'ZipJs', logTimestampFormat: TimestampFormat.TIME_MILLIS, logLevel: LogLevel.INFO }); } /** * Adds a file system entry to the zip archive, recursing into directories. * * @param {ZipWriter>} writer - The zip writer receiving new entries. * @param {string} sourcePath - The absolute file system path to add. * @param {string} entryName - The relative archive entry name to write. * @param {AnsiLogger} log - The logger used to trace added entries. * @returns {Promise} The number of archive entries written for the source path. */ async function addZipEntry(writer: ZipWriter>, sourcePath: string, entryName: string, log: AnsiLogger): Promise { const sourceStats = await stat(sourcePath); const normalizedEntryName = normalizeEntryName(entryName); if (sourceStats.isDirectory()) { const directoryEntryName = normalizedEntryName.replace(/\/?$/, '/'); await writer.add(directoryEntryName, undefined, { directory: true, lastModDate: sourceStats.mtime, level: 9 }); const children = await readdir(sourcePath, { withFileTypes: true }); children.sort((left, right) => left.name.localeCompare(right.name)); let childEntries = 1; for (const child of children) { childEntries += await addZipEntry(writer, path.join(sourcePath, child.name), `${directoryEntryName}${child.name}`, log); } log.debug(`Added directory ${directoryEntryName}`); return childEntries; } if (sourceStats.isFile()) { await writer.add(normalizedEntryName, new Uint8ArrayReader(await readFile(sourcePath)), { lastModDate: sourceStats.mtime, level: 9 }); log.debug(`Added file ${normalizedEntryName}`); return 1; } throw new Error(`Unsupported source path type: ${sourcePath}`); } /** * Builds the default extraction directory from a zip file path. * * @param {string} zipPath - The zip archive path. * @returns {string} The sibling directory used for extraction. */ function getDefaultDestinationPath(zipPath: string): string { const zipExtension = path.extname(zipPath); const zipName = path.basename(zipPath, zipExtension); return path.join(path.dirname(zipPath), zipName); } /** * Normalizes archive entry names to forward-slash separators. * * @param {string} entryName - The archive entry name to normalize. * @returns {string} The normalized entry name. */ function normalizeEntryName(entryName: string): string { return entryName.replace(/\\/g, '/'); } /** * Resolves an archive entry path while preventing zip-slip traversal. * * @param {string} destinationPath - The extraction root directory. * @param {string} entryName - The archive entry name to resolve. * @returns {string} The safe absolute destination path for the entry. */ function resolveEntryPath(destinationPath: string, entryName: string): string { const resolvedDestinationPath = path.resolve(destinationPath); const resolvedEntryPath = path.resolve(resolvedDestinationPath, normalizeEntryName(entryName)); const relativeEntryPath = path.relative(resolvedDestinationPath, resolvedEntryPath); if (path.isAbsolute(relativeEntryPath) || relativeEntryPath.startsWith('..')) { throw new Error(`Refusing to extract zip entry outside destination: ${entryName}`); } return resolvedEntryPath; }