"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var tar_exports = {};
__export(tar_exports, {
  extractTar: () => extractTar,
  extractTarGz: () => extractTarGz
});
module.exports = __toCommonJS(tar_exports);
var import_node_fs = require("node:fs");
var import_node_process = __toESM(require("node:process"));
var import_promises = require("node:stream/promises");
var import_node_zlib = require("node:zlib");
var import_safe = require("../fs/safe");
var import_normalize = require("../paths/normalize");
var import_error = require("../primordials/error");
var import_internal = require("./_internal");
async function extractTar(archivePath, outputDir, options = {}) {
  (0, import_internal.assertArchiveExists)(archivePath);
  const {
    maxEntries = import_internal.DEFAULT_MAX_ENTRIES,
    maxFileSize = import_internal.DEFAULT_MAX_FILE_SIZE,
    maxTotalSize = import_internal.DEFAULT_MAX_TOTAL_SIZE,
    strip = 0
  } = options;
  const normalizedOutputDir = (0, import_normalize.normalizePath)(outputDir);
  await (0, import_safe.safeMkdir)(normalizedOutputDir);
  let totalExtractedSize = 0;
  let entryCount = 0;
  let destroyScheduled = false;
  const tarFs = (0, import_internal.getTarFs)();
  const extractStream = tarFs.extract(normalizedOutputDir, {
    map: (header) => {
      if (destroyScheduled) {
        return header;
      }
      entryCount += 1;
      if (entryCount > maxEntries) {
        destroyScheduled = true;
        import_node_process.default.nextTick(() => {
          extractStream.destroy(
            new import_error.ErrorCtor(
              `Archive has too many entries: exceeded limit of ${maxEntries}`
            )
          );
        });
        return header;
      }
      if (header.name.includes("\0")) {
        destroyScheduled = true;
        import_node_process.default.nextTick(() => {
          extractStream.destroy(
            new import_error.ErrorCtor(
              `Invalid null byte in archive entry name: ${header.name}`
            )
          );
        });
        return header;
      }
      if (header.type === "symlink" || header.type === "link") {
        destroyScheduled = true;
        import_node_process.default.nextTick(() => {
          extractStream.destroy(
            new import_error.ErrorCtor(
              `Symlink detected in archive: ${header.name}. Symlinks are not supported for security reasons.`
            )
          );
        });
        return header;
      }
      if (header.size && header.size > maxFileSize) {
        destroyScheduled = true;
        import_node_process.default.nextTick(() => {
          extractStream.destroy(
            new import_error.ErrorCtor(
              `File size exceeds limit: ${header.name} (${header.size} bytes > ${maxFileSize} bytes)`
            )
          );
        });
        return header;
      }
      if (header.size) {
        totalExtractedSize += header.size;
        if (totalExtractedSize > maxTotalSize) {
          destroyScheduled = true;
          import_node_process.default.nextTick(() => {
            extractStream.destroy(
              new import_error.ErrorCtor(
                `Total extracted size exceeds limit: ${totalExtractedSize} bytes > ${maxTotalSize} bytes`
              )
            );
          });
          return header;
        }
      }
      return header;
    },
    strip
  });
  extractStream.on("error", () => {
  });
  const readStream = (0, import_node_fs.createReadStream)(archivePath);
  try {
    await (0, import_promises.pipeline)(readStream, extractStream);
  } catch (e) {
    readStream.destroy();
    throw e;
  }
}
async function extractTarGz(archivePath, outputDir, options = {}) {
  (0, import_internal.assertArchiveExists)(archivePath);
  const {
    maxEntries = import_internal.DEFAULT_MAX_ENTRIES,
    maxFileSize = import_internal.DEFAULT_MAX_FILE_SIZE,
    maxTotalSize = import_internal.DEFAULT_MAX_TOTAL_SIZE,
    strip = 0
  } = options;
  const normalizedOutputDir = (0, import_normalize.normalizePath)(outputDir);
  await (0, import_safe.safeMkdir)(normalizedOutputDir);
  let totalExtractedSize = 0;
  let entryCount = 0;
  let destroyScheduled = false;
  const tarFs = (0, import_internal.getTarFs)();
  const extractStream = tarFs.extract(normalizedOutputDir, {
    map: (header) => {
      if (destroyScheduled) {
        return header;
      }
      entryCount += 1;
      if (entryCount > maxEntries) {
        destroyScheduled = true;
        import_node_process.default.nextTick(() => {
          extractStream.destroy(
            new import_error.ErrorCtor(
              `Archive has too many entries: exceeded limit of ${maxEntries}`
            )
          );
        });
        return header;
      }
      if (header.name.includes("\0")) {
        destroyScheduled = true;
        import_node_process.default.nextTick(() => {
          extractStream.destroy(
            new import_error.ErrorCtor(
              `Invalid null byte in archive entry name: ${header.name}`
            )
          );
        });
        return header;
      }
      if (header.type === "symlink" || header.type === "link") {
        destroyScheduled = true;
        import_node_process.default.nextTick(() => {
          extractStream.destroy(
            new import_error.ErrorCtor(
              `Symlink detected in archive: ${header.name}. Symlinks are not supported for security reasons.`
            )
          );
        });
        return header;
      }
      if (header.size && header.size > maxFileSize) {
        destroyScheduled = true;
        import_node_process.default.nextTick(() => {
          extractStream.destroy(
            new import_error.ErrorCtor(
              `File size exceeds limit: ${header.name} (${header.size} bytes > ${maxFileSize} bytes)`
            )
          );
        });
        return header;
      }
      if (header.size) {
        totalExtractedSize += header.size;
        if (totalExtractedSize > maxTotalSize) {
          destroyScheduled = true;
          import_node_process.default.nextTick(() => {
            extractStream.destroy(
              new import_error.ErrorCtor(
                `Total extracted size exceeds limit: ${totalExtractedSize} bytes > ${maxTotalSize} bytes`
              )
            );
          });
          return header;
        }
      }
      return header;
    },
    strip
  });
  extractStream.on("error", () => {
  });
  const readStream = (0, import_node_fs.createReadStream)(archivePath);
  try {
    await (0, import_promises.pipeline)(readStream, (0, import_node_zlib.createGunzip)(), extractStream);
  } catch (e) {
    readStream.destroy();
    throw e;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  extractTar,
  extractTarGz
});
