All files / src/pack/collectPathEntries index.ts

100% Statements 163/163
100% Branches 43/43
100% Functions 8/8
100% Lines 163/163

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 1641x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 5x 32x 2x 2x 2x 2x 2x 30x 30x 30x 30x 32x 31x 31x 31x 27x 26x 26x 26x 26x 95x 93x 95x 1x 1x 1x 1x 1x 92x 95x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 65x 65x 65x 65x 65x 43x 43x 43x 49x 95x 1x 1x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 26x 26x 95x 95x 95x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 95x 26x 26x 43x 43x 43x 26x 26x 48x 48x 26x 1x 5x 5x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 31x 31x 2x 2x 29x 29x 29x 31x 1x 1x 28x 31x 1x 1x 1x 1x 1x 27x 27x 27x 1x 32x 32x 1x 1x 31x 32x 32x  
/**
 * 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 { lstat, readFile, readdir } from 'node:fs/promises'
import path from 'node:path'
import { NodearchiveError } from '../../.errors/class.js'
import type { ArchiveEntry } from '../../.types/ArchiveEntry/type.js'
import type { PackArgs } from '../../.types/PackArgs/type.js'
 
export async function collectPathEntries(
  args: Pick<PackArgs, 'path' | 'literalPath'>
): Promise<ArchiveEntry[]> {
  const sources = args.literalPath
    ? toList(args.literalPath)
    : await expandGlobs(toList(args.path))
 
  if (sources.length === 0) {
    throw new NodearchiveError(
      'ARCHIVE_SOURCE_MISSING',
      'No source paths matched'
    )
  }
 
  const entries: ArchiveEntry[] = []
  const seen = new Set<string>()
 
  for (const source of sources) {
    const absoluteSource = path.resolve(source)
    const root = toArchiveRoot(source, absoluteSource)
    await visit(absoluteSource, root)
  }
 
  return entries.sort((left, right) => left.path.localeCompare(right.path))
 
  async function visit(absoluteTarget: string, archivePath: string) {
    const stats = await inspect(absoluteTarget)
 
    if (stats.isSymbolicLink()) {
      throw new NodearchiveError(
        'ARCHIVE_UNSUPPORTED_ENTRY',
        `Symbolic links are not supported: ${archivePath}`
      )
    }
 
    if (stats.isDirectory()) {
      if (!seen.has(archivePath)) {
        seen.add(archivePath)
        entries.push({
          kind: 'directory',
          mode: stats.mode & 0o777,
          path: archivePath,
        })
      }
 
      const children = await readChildren(absoluteTarget)
 
      for (const child of children) {
        await visit(
          path.join(absoluteTarget, child),
          `${archivePath}/${child.replaceAll('\\', '/')}`
        )
      }
 
      return
    }
 
    if (seen.has(archivePath)) {
      return
    }
 
    const bytes = await readSource(absoluteTarget)
    seen.add(archivePath)
    entries.push({
      data: Buffer.from(bytes).toString('base64'),
      kind: 'file',
      mode: stats.mode & 0o777,
      path: archivePath,
    })
  }
 
  async function inspect(target: string) {
    try {
      return await lstat(target)
    } catch (error) {
      if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
        throw new NodearchiveError(
          'ARCHIVE_SOURCE_MISSING',
          `Source not found: ${target}`,
          { cause: error }
        )
      }
 
      throw error
    }
  }
 
  async function readChildren(target: string) {
    const children = await readdir(target)
    return children.sort((left, right) => left.localeCompare(right))
  }
 
  async function readSource(target: string) {
    return readFile(target)
  }
}
 
async function expandGlobs(values: string[]): Promise<string[]> {
  if (values.length === 0) {
    return []
  }
 
  const { default: fg } = (await import('fast-glob')) as {
    default: typeof import('fast-glob')
  }
  return fg(values, {
    cwd: process.cwd(),
    dot: true,
    followSymbolicLinks: false,
    onlyFiles: false,
    unique: true,
  })
}
 
function toArchiveRoot(source: string, absoluteSource: string): string {
  if (path.isAbsolute(source)) {
    return path.basename(absoluteSource)
  }
 
  const relative = path.relative(process.cwd(), absoluteSource)
 
  if (relative === '' || relative === '.') {
    return path.basename(absoluteSource)
  }
 
  if (relative.startsWith('..') || path.isAbsolute(relative)) {
    throw new NodearchiveError(
      'ARCHIVE_SOURCE_OUTSIDE_CWD',
      `Relative source must stay inside the current working directory: ${source}`
    )
  }
 
  return relative.replaceAll('\\', '/')
}
 
function toList(value?: string | string[]): string[] {
  if (value === undefined) {
    return []
  }
 
  return Array.isArray(value) ? value : [value]
}