"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 edit_exports = {};
__export(edit_exports, {
  getEditableJsonClass: () => getEditableJsonClass,
  readFile: () => readFile,
  retryWrite: () => retryWrite
});
module.exports = __toCommonJS(edit_exports);
var import_node_process = __toESM(require("node:process"));
var import_promises = require("node:timers/promises");
var import_predicates = require("../errors/predicates");
var import_fs = require("../node/fs");
var import_error = require("../primordials/error");
var import_json = require("../primordials/json");
var import_format = require("./format");
const identSymbol = import_format.INDENT_SYMBOL;
const newlineSymbol = import_format.NEWLINE_SYMBOL;
let _EditableJsonClass;
// @__NO_SIDE_EFFECTS__
function getEditableJsonClass() {
  if (_EditableJsonClass === void 0) {
    _EditableJsonClass = class EditableJson {
      _canSave = true;
      _content = {};
      _path = void 0;
      _readFileContent = "";
      _readFileJson = void 0;
      get content() {
        return this._content;
      }
      get filename() {
        const path = this._path;
        if (!path) {
          return "";
        }
        return path;
      }
      get path() {
        return this._path;
      }
      static async create(path, opts = {
        __proto__: null
      }) {
        const instance = new EditableJson();
        instance.create(path);
        return opts.data ? instance.update(opts.data) : instance;
      }
      static async load(path, opts = {
        __proto__: null
      }) {
        const instance = new EditableJson();
        if (!opts.create) {
          return await instance.load(path);
        }
        try {
          return await instance.load(path);
        } catch (err) {
          if (!(0, import_predicates.isErrnoException)(err) || err.code !== "ENOENT") {
            throw err;
          }
          return instance.create(path);
        }
      }
      create(path) {
        this._path = path;
        this._content = {};
        this._canSave = true;
        return this;
      }
      fromContent(data) {
        this._content = data;
        this._canSave = false;
        return this;
      }
      fromJSON(data) {
        const parsed = (0, import_json.JSONParse)(data);
        const indent = (0, import_format.detectIndent)(data);
        const newline = (0, import_format.detectNewline)(data);
        parsed[identSymbol] = indent;
        parsed[newlineSymbol] = newline;
        this._content = parsed;
        return this;
      }
      async load(path) {
        this._path = path;
        this._readFileContent = await readFile(this.filename);
        this.fromJSON(this._readFileContent);
        this._readFileJson = (0, import_json.JSONParse)(this._readFileContent);
        return this;
      }
      async save(options) {
        if (!this._canSave || this.content === void 0) {
          throw new import_error.ErrorCtor("No file path to save to");
        }
        if (!(0, import_format.shouldSave)(
          this.content,
          this._readFileJson,
          this._readFileContent,
          options
        )) {
          return false;
        }
        const content = (0, import_format.stripFormattingSymbols)(
          this.content
        );
        const sortedContent = options?.sort ? (0, import_format.sortKeys)(content) : content;
        const formatting = (0, import_format.getFormattingFromContent)(
          this.content
        );
        const fileContent = (0, import_format.stringifyWithFormatting)(sortedContent, formatting);
        await retryWrite(this.filename, fileContent);
        this._readFileContent = fileContent;
        this._readFileJson = (0, import_json.JSONParse)(fileContent);
        return true;
      }
      saveSync(options) {
        if (!this._canSave || this.content === void 0) {
          throw new import_error.ErrorCtor("No file path to save to");
        }
        if (!(0, import_format.shouldSave)(
          this.content,
          this._readFileJson,
          this._readFileContent,
          options
        )) {
          return false;
        }
        const content = (0, import_format.stripFormattingSymbols)(
          this.content
        );
        const sortedContent = options?.sort ? (0, import_format.sortKeys)(content) : content;
        const formatting = (0, import_format.getFormattingFromContent)(
          this.content
        );
        const fileContent = (0, import_format.stringifyWithFormatting)(sortedContent, formatting);
        const fs = (0, import_fs.getNodeFs)();
        fs.writeFileSync(this.filename, fileContent);
        this._readFileContent = fileContent;
        this._readFileJson = (0, import_json.JSONParse)(fileContent);
        return true;
      }
      update(content) {
        this._content = {
          ...this._content,
          ...content
        };
        return this;
      }
      willSave(options) {
        if (!this._canSave || this.content === void 0) {
          return false;
        }
        return (0, import_format.shouldSave)(
          this.content,
          this._readFileJson,
          this._readFileContent,
          options
        );
      }
    };
  }
  return _EditableJsonClass;
}
async function readFile(filepath) {
  const { promises: fsPromises } = (0, import_fs.getNodeFs)();
  const maxRetries = import_node_process.default.platform === "win32" ? 5 : 1;
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fsPromises.readFile(filepath, "utf8");
    } catch (e) {
      const isLastAttempt = attempt === maxRetries;
      const isEnoent = (0, import_predicates.isErrnoException)(e) && e.code === "ENOENT";
      if (!isEnoent || isLastAttempt) {
        throw e;
      }
      const delay = import_node_process.default.platform === "win32" ? 50 * (attempt + 1) : 20;
      await (0, import_promises.setTimeout)(delay);
    }
  }
  throw new import_error.ErrorCtor(
    `readFile: exhausted ${maxRetries + 1} attempts reading ${filepath}`
  );
}
async function retryWrite(filepath, content, retries = 3, baseDelay = 10) {
  const fs = (0, import_fs.getNodeFs)();
  const { promises: fsPromises } = fs;
  for (let attempt = 0; attempt <= retries; attempt++) {
    try {
      await fsPromises.writeFile(filepath, content);
      if (import_node_process.default.platform === "win32") {
        await (0, import_promises.setTimeout)(50);
        let accessRetries = 0;
        const maxAccessRetries = 5;
        while (accessRetries < maxAccessRetries) {
          if (fs.existsSync(filepath)) {
            await (0, import_promises.setTimeout)(10);
            break;
          }
          const delay = 20 * (accessRetries + 1);
          await (0, import_promises.setTimeout)(delay);
          accessRetries++;
        }
      }
      return;
    } catch (e) {
      const isLastAttempt = attempt === retries;
      const isRetriableError = (0, import_predicates.isErrnoException)(e) && (e.code === "EPERM" || e.code === "EBUSY" || e.code === "ENOENT");
      if (!isRetriableError || isLastAttempt) {
        throw e;
      }
      const delay = baseDelay * 2 ** attempt;
      await (0, import_promises.setTimeout)(delay);
    }
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getEditableJsonClass,
  readFile,
  retryWrite
});
