"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
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 safe_exports = {};
__export(safe_exports, {
  getDel: () => getDel,
  safeDelete: () => safeDelete,
  safeDeleteSync: () => safeDeleteSync,
  safeMkdir: () => safeMkdir,
  safeMkdirSync: () => safeMkdirSync
});
module.exports = __toCommonJS(safe_exports);
var import_predicates = require("../arrays/predicates");
var import_predicates2 = require("../errors/predicates");
var import_fs = require("../node/fs");
var import_path = require("../node/path");
var import_mutate = require("../objects/mutate");
var import_normalize = require("../paths/normalize");
var import_array = require("../primordials/array");
var import_globals = require("../primordials/globals");
var import_string = require("../primordials/string");
var import_retry = require("../promises/retry");
var import_internal = require("./_internal");
var import_path_cache = require("./path-cache");
const defaultRemoveOptions = (0, import_mutate.objectFreeze)({
  __proto__: null,
  force: true,
  maxRetries: 3,
  recursive: true,
  retryDelay: 200
});
let _del;
// @__NO_SIDE_EFFECTS__
function getDel() {
  if (_del === void 0) {
    _del = require("../external/del");
  }
  return _del;
}
async function safeDelete(filepath, options) {
  const opts = { __proto__: null, ...options };
  const patterns = (0, import_predicates.isArray)(filepath) ? filepath.map(import_normalize.pathLikeToString) : [(0, import_normalize.pathLikeToString)(filepath)];
  let shouldForce = opts.force !== false;
  if (!shouldForce && patterns.length > 0) {
    const path = (0, import_path.getNodePath)();
    const allowedDirs = (0, import_internal.getAllowedDirectories)();
    const allInAllowedDirs = patterns.every((pattern) => {
      const resolvedPath = path.resolve(pattern);
      for (const allowedDir of allowedDirs) {
        const isInAllowedDir = (0, import_string.StringPrototypeStartsWith)(resolvedPath, allowedDir + path.sep) || resolvedPath === allowedDir;
        const relativePath = path.relative(allowedDir, resolvedPath);
        const isGoingBackward = (0, import_string.StringPrototypeStartsWith)(relativePath, "..");
        if (isInAllowedDir && !isGoingBackward) {
          return true;
        }
      }
      return false;
    });
    if (allInAllowedDirs) {
      shouldForce = true;
    }
  }
  const maxRetries = opts.maxRetries ?? defaultRemoveOptions.maxRetries;
  const retryDelay = opts.retryDelay ?? defaultRemoveOptions.retryDelay;
  const del = /* @__PURE__ */ getDel();
  await (0, import_retry.pRetry)(
    async () => {
      await del.deleteAsync(patterns, {
        dryRun: false,
        force: shouldForce,
        onlyFiles: false
      });
    },
    {
      retries: maxRetries,
      baseDelayMs: retryDelay,
      backoffFactor: 2,
      signal: opts.signal
    }
  );
}
function safeDeleteSync(filepath, options) {
  const opts = { __proto__: null, ...options };
  const patterns = (0, import_predicates.isArray)(filepath) ? filepath.map(import_normalize.pathLikeToString) : [(0, import_normalize.pathLikeToString)(filepath)];
  let shouldForce = opts.force !== false;
  if (!shouldForce && patterns.length > 0) {
    const path = (0, import_path.getNodePath)();
    const allowedDirs = (0, import_internal.getAllowedDirectories)();
    const allInAllowedDirs = patterns.every((pattern) => {
      const resolvedPath = path.resolve(pattern);
      for (const allowedDir of allowedDirs) {
        const isInAllowedDir = (0, import_string.StringPrototypeStartsWith)(resolvedPath, allowedDir + path.sep) || resolvedPath === allowedDir;
        const relativePath = path.relative(allowedDir, resolvedPath);
        const isGoingBackward = (0, import_string.StringPrototypeStartsWith)(relativePath, "..");
        if (isInAllowedDir && !isGoingBackward) {
          return true;
        }
      }
      return false;
    });
    if (allInAllowedDirs) {
      shouldForce = true;
    }
  }
  const maxRetries = opts.maxRetries ?? defaultRemoveOptions.maxRetries;
  const retryDelay = opts.retryDelay ?? defaultRemoveOptions.retryDelay;
  const del = /* @__PURE__ */ getDel();
  let lastError;
  let delay = retryDelay;
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      del.deleteSync(patterns, {
        dryRun: false,
        force: shouldForce,
        onlyFiles: false
      });
      return;
    } catch (e) {
      lastError = e;
      if (attempt < maxRetries) {
        const waitMs = delay;
        (0, import_array.AtomicsWait)(
          new import_array.Int32ArrayCtor(new import_globals.SharedArrayBufferCtor(4)),
          0,
          0,
          waitMs
        );
        delay *= 2;
      }
    }
  }
  if (lastError) {
    throw lastError;
  }
}
async function safeMkdir(path, options) {
  const fs = (0, import_fs.getNodeFs)();
  const opts = { __proto__: null, recursive: true, ...options };
  try {
    await fs.promises.mkdir(path, opts);
  } catch (e) {
    if (!(0, import_predicates2.isErrnoException)(e) || e.code !== "EEXIST") {
      throw e;
    }
  }
}
function safeMkdirSync(path, options) {
  const fs = (0, import_fs.getNodeFs)();
  const opts = { __proto__: null, recursive: true, ...options };
  try {
    fs.mkdirSync(path, opts);
  } catch (e) {
    if (!(0, import_predicates2.isErrnoException)(e) || e.code !== "EEXIST") {
      throw e;
    }
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getDel,
  safeDelete,
  safeDeleteSync,
  safeMkdir,
  safeMkdirSync
});
