"use strict";
/* Socket Lib - Built with esbuild */
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var fs_exports = {};
__export(fs_exports, {
  findUp: () => findUp,
  findUpSync: () => findUpSync,
  invalidatePathCache: () => invalidatePathCache,
  isDir: () => isDir,
  isDirEmptySync: () => isDirEmptySync,
  isDirSync: () => isDirSync,
  isSymLinkSync: () => isSymLinkSync,
  normalizeEncoding: () => normalizeEncoding,
  normalizeEncodingSlow: () => normalizeEncodingSlow,
  readDirNames: () => readDirNames,
  readDirNamesSync: () => readDirNamesSync,
  readFileBinary: () => readFileBinary,
  readFileBinarySync: () => readFileBinarySync,
  readFileUtf8: () => readFileUtf8,
  readFileUtf8Sync: () => readFileUtf8Sync,
  readJson: () => readJson,
  readJsonSync: () => readJsonSync,
  safeDelete: () => safeDelete,
  safeDeleteSync: () => safeDeleteSync,
  safeMkdir: () => safeMkdir,
  safeMkdirSync: () => safeMkdirSync,
  safeReadFile: () => safeReadFile,
  safeReadFileSync: () => safeReadFileSync,
  safeStats: () => safeStats,
  safeStatsSync: () => safeStatsSync,
  uniqueSync: () => uniqueSync,
  validateFiles: () => validateFiles,
  writeJson: () => writeJson,
  writeJsonSync: () => writeJsonSync
});
module.exports = __toCommonJS(fs_exports);
var import_process = require("./constants/process");
var import_arrays = require("./arrays");
var import_del = require("./external/del");
var import_globs = require("./globs");
var import_json = require("./json");
var import_objects = require("./objects");
var import_normalize = require("./paths/normalize");
var import_rewire = require("./paths/rewire");
var import_socket = require("./paths/socket");
var import_sorts = require("./sorts");
const abortSignal = (0, import_process.getAbortSignal)();
const defaultRemoveOptions = (0, import_objects.objectFreeze)({
  __proto__: null,
  force: true,
  maxRetries: 3,
  recursive: true,
  retryDelay: 200
});
let _cachedAllowedDirs;
function getAllowedDirectories() {
  if (_cachedAllowedDirs === void 0) {
    const path = /* @__PURE__ */ getPath();
    _cachedAllowedDirs = [
      path.resolve((0, import_socket.getOsTmpDir)()),
      path.resolve((0, import_socket.getSocketCacacheDir)()),
      path.resolve((0, import_socket.getSocketUserDir)())
    ];
  }
  return _cachedAllowedDirs;
}
let _buffer;
// @__NO_SIDE_EFFECTS__
function getBuffer() {
  if (_buffer === void 0) {
    _buffer = require("node:buffer");
  }
  return _buffer;
}
let _fs;
// @__NO_SIDE_EFFECTS__
function getFs() {
  if (_fs === void 0) {
    _fs = require("node:fs");
  }
  return _fs;
}
let _path;
// @__NO_SIDE_EFFECTS__
function getPath() {
  if (_path === void 0) {
    _path = require("node:path");
  }
  return _path;
}
// @__NO_SIDE_EFFECTS__
function innerReadDirNames(dirents, dirname, options) {
  const {
    ignore,
    includeEmpty = true,
    sort = true
  } = { __proto__: null, ...options };
  const path = /* @__PURE__ */ getPath();
  const names = dirents.filter(
    (d) => d.isDirectory() && (includeEmpty || !/* @__PURE__ */ isDirEmptySync(path.join(dirname || d.parentPath, d.name), {
      ignore
    }))
  ).map((d) => d.name);
  return sort ? names.sort(import_sorts.naturalCompare) : names;
}
// @__NO_SIDE_EFFECTS__
function stringify(json, EOL, finalEOL, replacer, spaces = 2) {
  const EOF = finalEOL ? EOL : "";
  const str = JSON.stringify(json, replacer, spaces);
  return `${str.replace(/\n/g, EOL)}${EOF}`;
}
// @__NO_SIDE_EFFECTS__
async function findUp(name, options) {
  const { cwd = process.cwd(), signal = abortSignal } = {
    __proto__: null,
    ...options
  };
  let { onlyDirectories = false, onlyFiles = true } = {
    __proto__: null,
    ...options
  };
  if (onlyDirectories) {
    onlyFiles = false;
  }
  if (onlyFiles) {
    onlyDirectories = false;
  }
  const fs = /* @__PURE__ */ getFs();
  const path = /* @__PURE__ */ getPath();
  let dir = path.resolve(cwd);
  const { root } = path.parse(dir);
  const names = (0, import_arrays.isArray)(name) ? name : [name];
  while (dir && dir !== root) {
    for (const n of names) {
      if (signal?.aborted) {
        return void 0;
      }
      const thePath = path.join(dir, n);
      try {
        const stats = await fs.promises.stat(thePath);
        if (!onlyDirectories && stats.isFile()) {
          return (0, import_normalize.normalizePath)(thePath);
        }
        if (!onlyFiles && stats.isDirectory()) {
          return (0, import_normalize.normalizePath)(thePath);
        }
      } catch {
      }
    }
    dir = path.dirname(dir);
  }
  return void 0;
}
// @__NO_SIDE_EFFECTS__
function findUpSync(name, options) {
  const { cwd = process.cwd(), stopAt } = {
    __proto__: null,
    ...options
  };
  let { onlyDirectories = false, onlyFiles = true } = {
    __proto__: null,
    ...options
  };
  if (onlyDirectories) {
    onlyFiles = false;
  }
  if (onlyFiles) {
    onlyDirectories = false;
  }
  const fs = /* @__PURE__ */ getFs();
  const path = /* @__PURE__ */ getPath();
  let dir = path.resolve(cwd);
  const { root } = path.parse(dir);
  const stopDir = stopAt ? path.resolve(stopAt) : void 0;
  const names = (0, import_arrays.isArray)(name) ? name : [name];
  while (dir && dir !== root) {
    if (stopDir && dir === stopDir) {
      for (const n of names) {
        const thePath = path.join(dir, n);
        try {
          const stats = fs.statSync(thePath);
          if (!onlyDirectories && stats.isFile()) {
            return (0, import_normalize.normalizePath)(thePath);
          }
          if (!onlyFiles && stats.isDirectory()) {
            return (0, import_normalize.normalizePath)(thePath);
          }
        } catch {
        }
      }
      return void 0;
    }
    for (const n of names) {
      const thePath = path.join(dir, n);
      try {
        const stats = fs.statSync(thePath);
        if (!onlyDirectories && stats.isFile()) {
          return (0, import_normalize.normalizePath)(thePath);
        }
        if (!onlyFiles && stats.isDirectory()) {
          return (0, import_normalize.normalizePath)(thePath);
        }
      } catch {
      }
    }
    dir = path.dirname(dir);
  }
  return void 0;
}
function invalidatePathCache() {
  _cachedAllowedDirs = void 0;
}
(0, import_rewire.registerCacheInvalidation)(invalidatePathCache);
// @__NO_SIDE_EFFECTS__
async function isDir(filepath) {
  return !!(await /* @__PURE__ */ safeStats(filepath))?.isDirectory();
}
// @__NO_SIDE_EFFECTS__
function isDirSync(filepath) {
  return !!(/* @__PURE__ */ safeStatsSync(filepath))?.isDirectory();
}
// @__NO_SIDE_EFFECTS__
function isDirEmptySync(dirname, options) {
  const { ignore = import_globs.defaultIgnore } = {
    __proto__: null,
    ...options
  };
  const fs = /* @__PURE__ */ getFs();
  try {
    const files = fs.readdirSync(dirname);
    const { length } = files;
    if (length === 0) {
      return true;
    }
    const matcher = (0, import_globs.getGlobMatcher)(
      ignore,
      {
        cwd: (0, import_normalize.pathLikeToString)(dirname)
      }
    );
    let ignoredCount = 0;
    for (let i = 0; i < length; i += 1) {
      const file = files[i];
      if (file && matcher(file)) {
        ignoredCount += 1;
      }
    }
    return ignoredCount === length;
  } catch {
    return false;
  }
}
// @__NO_SIDE_EFFECTS__
function isSymLinkSync(filepath) {
  const fs = /* @__PURE__ */ getFs();
  try {
    return fs.lstatSync(filepath).isSymbolicLink();
  } catch {
  }
  return false;
}
// @__NO_SIDE_EFFECTS__
function normalizeEncoding(enc) {
  return enc == null || enc === "utf8" || enc === "utf-8" ? "utf8" : /* @__PURE__ */ normalizeEncodingSlow(enc);
}
// @__NO_SIDE_EFFECTS__
function normalizeEncodingSlow(enc) {
  const { length } = enc;
  if (length === 4) {
    if (enc === "ucs2" || enc === "UCS2") {
      return "utf16le";
    }
    if (enc.toLowerCase() === "ucs2") {
      return "utf16le";
    }
  } else if (length === 3 && enc === "hex" || enc === "HEX" || enc.toLowerCase() === "hex") {
    return "hex";
  } else if (length === 5) {
    if (enc === "ascii") {
      return "ascii";
    }
    if (enc === "ucs-2") {
      return "utf16le";
    }
    if (enc === "ASCII") {
      return "ascii";
    }
    if (enc === "UCS-2") {
      return "utf16le";
    }
    enc = enc.toLowerCase();
    if (enc === "ascii") {
      return "ascii";
    }
    if (enc === "ucs-2") {
      return "utf16le";
    }
  } else if (length === 6) {
    if (enc === "base64") {
      return "base64";
    }
    if (enc === "latin1" || enc === "binary") {
      return "latin1";
    }
    if (enc === "BASE64") {
      return "base64";
    }
    if (enc === "LATIN1" || enc === "BINARY") {
      return "latin1";
    }
    enc = enc.toLowerCase();
    if (enc === "base64") {
      return "base64";
    }
    if (enc === "latin1" || enc === "binary") {
      return "latin1";
    }
  } else if (length === 7) {
    if (enc === "utf16le" || enc === "UTF16LE" || enc.toLowerCase() === "utf16le") {
      return "utf16le";
    }
  } else if (length === 8) {
    if (enc === "utf-16le" || enc === "UTF-16LE" || enc.toLowerCase() === "utf-16le") {
      return "utf16le";
    }
  } else if (length === 9) {
    if (enc === "base64url" || enc === "BASE64URL" || enc.toLowerCase() === "base64url") {
      return "base64url";
    }
  }
  return "utf8";
}
// @__NO_SIDE_EFFECTS__
async function readDirNames(dirname, options) {
  const fs = /* @__PURE__ */ getFs();
  try {
    return /* @__PURE__ */ innerReadDirNames(
      await fs.promises.readdir(dirname, {
        __proto__: null,
        encoding: "utf8",
        withFileTypes: true
      }),
      String(dirname),
      options
    );
  } catch {
  }
  return [];
}
// @__NO_SIDE_EFFECTS__
function readDirNamesSync(dirname, options) {
  const fs = /* @__PURE__ */ getFs();
  try {
    return /* @__PURE__ */ innerReadDirNames(
      fs.readdirSync(dirname, {
        __proto__: null,
        encoding: "utf8",
        withFileTypes: true
      }),
      String(dirname),
      options
    );
  } catch {
  }
  return [];
}
// @__NO_SIDE_EFFECTS__
async function readFileBinary(filepath, options) {
  const opts = typeof options === "string" ? { encoding: options } : options;
  const fs = /* @__PURE__ */ getFs();
  return await fs.promises.readFile(filepath, {
    signal: abortSignal,
    ...opts,
    encoding: null
  });
}
// @__NO_SIDE_EFFECTS__
async function readFileUtf8(filepath, options) {
  const opts = typeof options === "string" ? { encoding: options } : options;
  const fs = /* @__PURE__ */ getFs();
  return await fs.promises.readFile(filepath, {
    signal: abortSignal,
    ...opts,
    encoding: "utf8"
  });
}
// @__NO_SIDE_EFFECTS__
function readFileBinarySync(filepath, options) {
  const opts = typeof options === "string" ? { encoding: options } : options;
  const fs = /* @__PURE__ */ getFs();
  return fs.readFileSync(filepath, {
    ...opts,
    encoding: null
  });
}
// @__NO_SIDE_EFFECTS__
function readFileUtf8Sync(filepath, options) {
  const opts = typeof options === "string" ? { encoding: options } : options;
  const fs = /* @__PURE__ */ getFs();
  return fs.readFileSync(filepath, {
    ...opts,
    encoding: "utf8"
  });
}
// @__NO_SIDE_EFFECTS__
async function readJson(filepath, options) {
  const opts = typeof options === "string" ? { encoding: options } : options;
  const { reviver, throws, ...fsOptions } = {
    __proto__: null,
    ...opts
  };
  const shouldThrow = throws === void 0 || !!throws;
  const fs = /* @__PURE__ */ getFs();
  let content = "";
  try {
    content = await fs.promises.readFile(filepath, {
      __proto__: null,
      ...fsOptions,
      encoding: "utf8"
    });
  } catch (e) {
    if (shouldThrow) {
      const code = e.code;
      if (code === "ENOENT") {
        throw new Error(
          `JSON file not found: ${filepath}
Ensure the file exists or create it with the expected structure.`,
          { cause: e }
        );
      }
      if (code === "EACCES" || code === "EPERM") {
        throw new Error(
          `Permission denied reading JSON file: ${filepath}
Check file permissions or run with appropriate access.`,
          { cause: e }
        );
      }
      throw e;
    }
    return void 0;
  }
  return (0, import_json.jsonParse)(content, {
    filepath: String(filepath),
    reviver,
    throws: shouldThrow
  });
}
// @__NO_SIDE_EFFECTS__
function readJsonSync(filepath, options) {
  const opts = typeof options === "string" ? { encoding: options } : options;
  const { reviver, throws, ...fsOptions } = {
    __proto__: null,
    ...opts
  };
  const shouldThrow = throws === void 0 || !!throws;
  const fs = /* @__PURE__ */ getFs();
  let content = "";
  try {
    content = fs.readFileSync(filepath, {
      __proto__: null,
      ...fsOptions,
      encoding: "utf8"
    });
  } catch (e) {
    if (shouldThrow) {
      const code = e.code;
      if (code === "ENOENT") {
        throw new Error(
          `JSON file not found: ${filepath}
Ensure the file exists or create it with the expected structure.`,
          { cause: e }
        );
      }
      if (code === "EACCES" || code === "EPERM") {
        throw new Error(
          `Permission denied reading JSON file: ${filepath}
Check file permissions or run with appropriate access.`,
          { cause: e }
        );
      }
      throw e;
    }
    return void 0;
  }
  return (0, import_json.jsonParse)(content, {
    filepath: String(filepath),
    reviver,
    throws: shouldThrow
  });
}
async function safeDelete(filepath, options) {
  const opts = { __proto__: null, ...options };
  const patterns = (0, import_arrays.isArray)(filepath) ? filepath.map(import_normalize.pathLikeToString) : [(0, import_normalize.pathLikeToString)(filepath)];
  let shouldForce = opts.force !== false;
  if (!shouldForce && patterns.length > 0) {
    const path = /* @__PURE__ */ getPath();
    const allowedDirs = getAllowedDirectories();
    const allInAllowedDirs = patterns.every((pattern) => {
      const resolvedPath = path.resolve(pattern);
      for (const allowedDir of allowedDirs) {
        const isInAllowedDir = resolvedPath.startsWith(allowedDir + path.sep) || resolvedPath === allowedDir;
        const relativePath = path.relative(allowedDir, resolvedPath);
        const isGoingBackward = relativePath.startsWith("..");
        if (isInAllowedDir && !isGoingBackward) {
          return true;
        }
      }
      return false;
    });
    if (allInAllowedDirs) {
      shouldForce = true;
    }
  }
  await (0, import_del.deleteAsync)(patterns, {
    concurrency: opts.maxRetries || defaultRemoveOptions.maxRetries,
    dryRun: false,
    force: shouldForce,
    onlyFiles: false
  });
}
function safeDeleteSync(filepath, options) {
  const opts = { __proto__: null, ...options };
  const patterns = (0, import_arrays.isArray)(filepath) ? filepath.map(import_normalize.pathLikeToString) : [(0, import_normalize.pathLikeToString)(filepath)];
  let shouldForce = opts.force !== false;
  if (!shouldForce && patterns.length > 0) {
    const path = /* @__PURE__ */ getPath();
    const allowedDirs = getAllowedDirectories();
    const allInAllowedDirs = patterns.every((pattern) => {
      const resolvedPath = path.resolve(pattern);
      for (const allowedDir of allowedDirs) {
        const isInAllowedDir = resolvedPath.startsWith(allowedDir + path.sep) || resolvedPath === allowedDir;
        const relativePath = path.relative(allowedDir, resolvedPath);
        const isGoingBackward = relativePath.startsWith("..");
        if (isInAllowedDir && !isGoingBackward) {
          return true;
        }
      }
      return false;
    });
    if (allInAllowedDirs) {
      shouldForce = true;
    }
  }
  (0, import_del.deleteSync)(patterns, {
    concurrency: opts.maxRetries || defaultRemoveOptions.maxRetries,
    dryRun: false,
    force: shouldForce,
    onlyFiles: false
  });
}
async function safeMkdir(path, options) {
  const fs = /* @__PURE__ */ getFs();
  const opts = { __proto__: null, recursive: true, ...options };
  try {
    await fs.promises.mkdir(path, opts);
  } catch (e) {
    if (typeof e === "object" && e !== null && "code" in e && e.code !== "EEXIST") {
      throw e;
    }
  }
}
function safeMkdirSync(path, options) {
  const fs = /* @__PURE__ */ getFs();
  const opts = { __proto__: null, recursive: true, ...options };
  try {
    fs.mkdirSync(path, opts);
  } catch (e) {
    if (typeof e === "object" && e !== null && "code" in e && e.code !== "EEXIST") {
      throw e;
    }
  }
}
// @__NO_SIDE_EFFECTS__
async function safeReadFile(filepath, options) {
  const opts = typeof options === "string" ? { __proto__: null, encoding: options } : { __proto__: null, ...options };
  const { defaultValue, ...rawReadOpts } = opts;
  const readOpts = { __proto__: null, ...rawReadOpts };
  const shouldReturnBuffer = readOpts.encoding === null;
  const encoding = shouldReturnBuffer ? null : /* @__PURE__ */ normalizeEncoding(readOpts.encoding);
  const fs = /* @__PURE__ */ getFs();
  try {
    return await fs.promises.readFile(filepath, {
      __proto__: null,
      signal: abortSignal,
      ...readOpts,
      encoding
    });
  } catch {
  }
  if (defaultValue === void 0) {
    return void 0;
  }
  if (shouldReturnBuffer) {
    const { Buffer: Buffer2 } = /* @__PURE__ */ getBuffer();
    return Buffer2.isBuffer(defaultValue) ? defaultValue : void 0;
  }
  return typeof defaultValue === "string" ? defaultValue : String(defaultValue);
}
// @__NO_SIDE_EFFECTS__
function safeReadFileSync(filepath, options) {
  const opts = typeof options === "string" ? { __proto__: null, encoding: options } : { __proto__: null, ...options };
  const { defaultValue, ...rawReadOpts } = opts;
  const readOpts = { __proto__: null, ...rawReadOpts };
  const shouldReturnBuffer = readOpts.encoding === null;
  const encoding = shouldReturnBuffer ? null : /* @__PURE__ */ normalizeEncoding(readOpts.encoding);
  const fs = /* @__PURE__ */ getFs();
  try {
    return fs.readFileSync(filepath, {
      __proto__: null,
      ...readOpts,
      encoding
    });
  } catch {
  }
  if (defaultValue === void 0) {
    return void 0;
  }
  if (shouldReturnBuffer) {
    const { Buffer: Buffer2 } = /* @__PURE__ */ getBuffer();
    return Buffer2.isBuffer(defaultValue) ? defaultValue : void 0;
  }
  return typeof defaultValue === "string" ? defaultValue : String(defaultValue);
}
// @__NO_SIDE_EFFECTS__
async function safeStats(filepath) {
  const fs = /* @__PURE__ */ getFs();
  try {
    return await fs.promises.stat(filepath);
  } catch {
  }
  return void 0;
}
// @__NO_SIDE_EFFECTS__
function safeStatsSync(filepath, options) {
  const opts = typeof options === "string" ? { encoding: options } : options;
  const fs = /* @__PURE__ */ getFs();
  try {
    return fs.statSync(filepath, {
      __proto__: null,
      throwIfNoEntry: false,
      ...opts
    });
  } catch {
  }
  return void 0;
}
// @__NO_SIDE_EFFECTS__
function uniqueSync(filepath) {
  const fs = /* @__PURE__ */ getFs();
  const path = /* @__PURE__ */ getPath();
  const filepathStr = String(filepath);
  if (!fs.existsSync(filepathStr)) {
    return (0, import_normalize.normalizePath)(filepathStr);
  }
  const dirname = path.dirname(filepathStr);
  const ext = path.extname(filepathStr);
  const basename = path.basename(filepathStr, ext);
  let counter = 1;
  let uniquePath;
  do {
    uniquePath = path.join(dirname, `${basename}-${counter}${ext}`);
    counter++;
  } while (fs.existsSync(uniquePath));
  return (0, import_normalize.normalizePath)(uniquePath);
}
// @__NO_SIDE_EFFECTS__
function validateFiles(filepaths) {
  const fs = /* @__PURE__ */ getFs();
  const validPaths = [];
  const invalidPaths = [];
  const { R_OK } = fs.constants;
  for (const filepath of filepaths) {
    try {
      fs.accessSync(filepath, R_OK);
      validPaths.push(filepath);
    } catch {
      invalidPaths.push(filepath);
    }
  }
  return { __proto__: null, validPaths, invalidPaths };
}
async function writeJson(filepath, jsonContent, options) {
  const opts = typeof options === "string" ? { encoding: options } : options;
  const { EOL, finalEOL, replacer, spaces, ...fsOptions } = {
    __proto__: null,
    ...opts
  };
  const fs = /* @__PURE__ */ getFs();
  const jsonString = /* @__PURE__ */ stringify(
    jsonContent,
    EOL || "\n",
    finalEOL !== void 0 ? finalEOL : true,
    replacer,
    spaces
  );
  await fs.promises.writeFile(filepath, jsonString, {
    encoding: "utf8",
    ...fsOptions,
    __proto__: null
  });
}
function writeJsonSync(filepath, jsonContent, options) {
  const opts = typeof options === "string" ? { encoding: options } : options;
  const { EOL, finalEOL, replacer, spaces, ...fsOptions } = {
    __proto__: null,
    ...opts
  };
  const fs = /* @__PURE__ */ getFs();
  const jsonString = /* @__PURE__ */ stringify(
    jsonContent,
    EOL || "\n",
    finalEOL !== void 0 ? finalEOL : true,
    replacer,
    spaces
  );
  fs.writeFileSync(filepath, jsonString, {
    encoding: "utf8",
    ...fsOptions,
    __proto__: null
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  findUp,
  findUpSync,
  invalidatePathCache,
  isDir,
  isDirEmptySync,
  isDirSync,
  isSymLinkSync,
  normalizeEncoding,
  normalizeEncodingSlow,
  readDirNames,
  readDirNamesSync,
  readFileBinary,
  readFileBinarySync,
  readFileUtf8,
  readFileUtf8Sync,
  readJson,
  readJsonSync,
  safeDelete,
  safeDeleteSync,
  safeMkdir,
  safeMkdirSync,
  safeReadFile,
  safeReadFileSync,
  safeStats,
  safeStatsSync,
  uniqueSync,
  validateFiles,
  writeJson,
  writeJsonSync
});
