All files / src/unpack/materializeArchive index.ts

100% Statements 142/142
100% Branches 41/41
100% Functions 5/5
100% Lines 142/142

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 1431x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 13x 13x 19x 19x 45x 45x 45x 45x 18x 18x 18x 11x 11x 11x 18x 18x 18x 25x 25x 25x 25x 24x 45x 1x 1x 1x 1x 1x 23x 45x 9x 2x 2x 2x 2x 2x 7x 7x 7x 14x 14x 14x 14x 14x 45x 45x 45x 3x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 10x 1x 22x 22x 4x 4x 18x 18x 18x 1x 38x 38x 38x 1x 25x 25x 25x 25x 25x 25x 25x 15x 14x 14x 1x 1x 1x 25x 1x 45x 45x 45x 45x 45x 45x 45x 43x 45x 2x 2x 2x 2x 2x 43x 43x 43x  
/**
 * Copyright 2026 nodearchive
 *
 * 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 { chmod, lstat, mkdir, writeFile } from 'node:fs/promises'
import path from 'node:path'
import type { ArchiveManifest } from '../../.types/ArchiveManifest/type.js'
import { NodearchiveError } from '../../.errors/class.js'
import { assertDirectoryPath } from '../../.helpers/assertDirectoryPath/index.js'
import { toNodearchiveError } from '../../.helpers/toNodearchiveError/index.js'
 
export async function materializeArchive(
  manifest: ArchiveManifest,
  destinationPath: string,
  force = false,
  dryRun = false
): Promise<void> {
  const root = path.resolve(destinationPath)
  await assertDirectoryPath(root)
 
  if (!dryRun) {
    await ensureDirectory(root)
  }
 
  for (const entry of manifest.entries) {
    const safePath = toSafePath(entry.path)
    const target = path.join(root, ...safePath.split('/'))
 
    if (entry.kind === 'directory') {
      await assertDirectoryPath(target)
 
      if (!dryRun) {
        await ensureDirectory(target)
        await applyMode(target, entry.mode)
      }
 
      continue
    }
 
    await assertDirectoryPath(path.dirname(target))
 
    const existingType = await readPathType(target)
 
    if (existingType === 'directory') {
      throw new NodearchiveError(
        'ARCHIVE_FILESYSTEM_WRITE_FAILED',
        `Failed to write file: ${target}`
      )
    }
 
    if (dryRun) {
      if (existingType !== undefined && !force) {
        throw new NodearchiveError(
          'ARCHIVE_DESTINATION_EXISTS',
          `Destination already exists: ${target}`
        )
      }
 
      continue
    }
 
    await ensureDirectory(path.dirname(target))
 
    try {
      await writeFile(target, Buffer.from(entry.data!, 'base64'), {
        flag: force ? 'w' : 'wx',
      })
    } catch (error) {
      if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
        throw new NodearchiveError(
          'ARCHIVE_DESTINATION_EXISTS',
          `Destination already exists: ${target}`,
          { cause: error }
        )
      }
 
      throw toNodearchiveError(
        error,
        'ARCHIVE_FILESYSTEM_WRITE_FAILED',
        `Failed to write file: ${target}`
      )
    }
 
    await applyMode(target, entry.mode)
  }
}
 
async function applyMode(target: string, mode?: number): Promise<void> {
  if (mode === undefined) {
    return
  }
 
  await chmod(target, mode)
}
 
async function ensureDirectory(target: string): Promise<void> {
  await mkdir(target, { recursive: true })
}
 
async function readPathType(
  target: string
): Promise<'directory' | 'file' | undefined> {
  try {
    const stats = await lstat(target)
    return stats.isDirectory() ? 'directory' : 'file'
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
      return undefined
    }
 
    throw error
  }
}
 
function toSafePath(value: string): string {
  const normalized = path.posix.normalize(value)
 
  if (
    normalized === '.' ||
    normalized.startsWith('../') ||
    normalized.startsWith('/') ||
    /^[A-Za-z]:/.test(normalized)
  ) {
    throw new NodearchiveError(
      'ARCHIVE_ENTRY_PATH_INVALID',
      `Archive entry path is not safe to extract: ${value}`
    )
  }
 
  return normalized
}