import { a7 as getDefaultExportFromCjs } from './paths-2M_UxD_H.js';
import fs$2 from 'fs';
import crypto from 'node:crypto';
import path from 'path';
import require$$4 from 'util';

var lib = {exports: {}};

var cjs = {};

var signals = {};

var hasRequiredSignals;

function requireSignals () {
	if (hasRequiredSignals) return signals;
	hasRequiredSignals = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.signals = void 0;
		/**
		 * This is not the set of all possible signals.
		 *
		 * It IS, however, the set of all signals that trigger
		 * an exit on either Linux or BSD systems.  Linux is a
		 * superset of the signal names supported on BSD, and
		 * the unknown signals just fail to register, so we can
		 * catch that easily enough.
		 *
		 * Windows signals are a different set, since there are
		 * signals that terminate Windows processes, but don't
		 * terminate (or don't even exist) on Posix systems.
		 *
		 * Don't bother with SIGKILL.  It's uncatchable, which
		 * means that we can't fire any callbacks anyway.
		 *
		 * If a user does happen to register a handler on a non-
		 * fatal signal like SIGWINCH or something, and then
		 * exit, it'll end up firing `process.emit('exit')`, so
		 * the handler will be fired anyway.
		 *
		 * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
		 * artificially, inherently leave the process in a
		 * state from which it is not safe to try and enter JS
		 * listeners.
		 */
		exports$1.signals = [];
		exports$1.signals.push('SIGHUP', 'SIGINT', 'SIGTERM');
		if (process.platform !== 'win32') {
		    exports$1.signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'
		    // should detect profiler and enable/disable accordingly.
		    // see #21
		    // 'SIGPROF'
		    );
		}
		if (process.platform === 'linux') {
		    exports$1.signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');
		}
		
	} (signals));
	return signals;
}

var hasRequiredCjs;

function requireCjs () {
	if (hasRequiredCjs) return cjs;
	hasRequiredCjs = 1;
	(function (exports$1) {
		var _a;
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.unload = exports$1.load = exports$1.onExit = exports$1.signals = void 0;
		// Note: since nyc uses this module to output coverage, any lines
		// that are in the direct sync flow of nyc's outputCoverage are
		// ignored, since we can never get coverage for them.
		// grab a reference to node's real process object right away
		const signals_js_1 = requireSignals();
		Object.defineProperty(exports$1, "signals", { enumerable: true, get: function () { return signals_js_1.signals; } });
		const processOk = (process) => !!process &&
		    typeof process === 'object' &&
		    typeof process.removeListener === 'function' &&
		    typeof process.emit === 'function' &&
		    typeof process.reallyExit === 'function' &&
		    typeof process.listeners === 'function' &&
		    typeof process.kill === 'function' &&
		    typeof process.pid === 'number' &&
		    typeof process.on === 'function';
		const kExitEmitter = Symbol.for('signal-exit emitter');
		const global = globalThis;
		const ObjectDefineProperty = Object.defineProperty.bind(Object);
		// teeny special purpose ee
		class Emitter {
		    emitted = {
		        afterExit: false,
		        exit: false,
		    };
		    listeners = {
		        afterExit: [],
		        exit: [],
		    };
		    count = 0;
		    id = Math.random();
		    constructor() {
		        if (global[kExitEmitter]) {
		            return global[kExitEmitter];
		        }
		        ObjectDefineProperty(global, kExitEmitter, {
		            value: this,
		            writable: false,
		            enumerable: false,
		            configurable: false,
		        });
		    }
		    on(ev, fn) {
		        this.listeners[ev].push(fn);
		    }
		    removeListener(ev, fn) {
		        const list = this.listeners[ev];
		        const i = list.indexOf(fn);
		        /* c8 ignore start */
		        if (i === -1) {
		            return;
		        }
		        /* c8 ignore stop */
		        if (i === 0 && list.length === 1) {
		            list.length = 0;
		        }
		        else {
		            list.splice(i, 1);
		        }
		    }
		    emit(ev, code, signal) {
		        if (this.emitted[ev]) {
		            return false;
		        }
		        this.emitted[ev] = true;
		        let ret = false;
		        for (const fn of this.listeners[ev]) {
		            ret = fn(code, signal) === true || ret;
		        }
		        if (ev === 'exit') {
		            ret = this.emit('afterExit', code, signal) || ret;
		        }
		        return ret;
		    }
		}
		class SignalExitBase {
		}
		const signalExitWrap = (handler) => {
		    return {
		        onExit(cb, opts) {
		            return handler.onExit(cb, opts);
		        },
		        load() {
		            return handler.load();
		        },
		        unload() {
		            return handler.unload();
		        },
		    };
		};
		class SignalExitFallback extends SignalExitBase {
		    onExit() {
		        return () => { };
		    }
		    load() { }
		    unload() { }
		}
		class SignalExit extends SignalExitBase {
		    // "SIGHUP" throws an `ENOSYS` error on Windows,
		    // so use a supported signal instead
		    /* c8 ignore start */
		    #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP';
		    /* c8 ignore stop */
		    #emitter = new Emitter();
		    #process;
		    #originalProcessEmit;
		    #originalProcessReallyExit;
		    #sigListeners = {};
		    #loaded = false;
		    constructor(process) {
		        super();
		        this.#process = process;
		        // { <signal>: <listener fn>, ... }
		        this.#sigListeners = {};
		        for (const sig of signals_js_1.signals) {
		            this.#sigListeners[sig] = () => {
		                // If there are no other listeners, an exit is coming!
		                // Simplest way: remove us and then re-send the signal.
		                // We know that this will kill the process, so we can
		                // safely emit now.
		                const listeners = this.#process.listeners(sig);
		                let { count } = this.#emitter;
		                // This is a workaround for the fact that signal-exit v3 and signal
		                // exit v4 are not aware of each other, and each will attempt to let
		                // the other handle it, so neither of them do. To correct this, we
		                // detect if we're the only handler *except* for previous versions
		                // of signal-exit, and increment by the count of listeners it has
		                // created.
		                /* c8 ignore start */
		                const p = process;
		                if (typeof p.__signal_exit_emitter__ === 'object' &&
		                    typeof p.__signal_exit_emitter__.count === 'number') {
		                    count += p.__signal_exit_emitter__.count;
		                }
		                /* c8 ignore stop */
		                if (listeners.length === count) {
		                    this.unload();
		                    const ret = this.#emitter.emit('exit', null, sig);
		                    /* c8 ignore start */
		                    const s = sig === 'SIGHUP' ? this.#hupSig : sig;
		                    if (!ret)
		                        process.kill(process.pid, s);
		                    /* c8 ignore stop */
		                }
		            };
		        }
		        this.#originalProcessReallyExit = process.reallyExit;
		        this.#originalProcessEmit = process.emit;
		    }
		    onExit(cb, opts) {
		        /* c8 ignore start */
		        if (!processOk(this.#process)) {
		            return () => { };
		        }
		        /* c8 ignore stop */
		        if (this.#loaded === false) {
		            this.load();
		        }
		        const ev = opts?.alwaysLast ? 'afterExit' : 'exit';
		        this.#emitter.on(ev, cb);
		        return () => {
		            this.#emitter.removeListener(ev, cb);
		            if (this.#emitter.listeners['exit'].length === 0 &&
		                this.#emitter.listeners['afterExit'].length === 0) {
		                this.unload();
		            }
		        };
		    }
		    load() {
		        if (this.#loaded) {
		            return;
		        }
		        this.#loaded = true;
		        // This is the number of onSignalExit's that are in play.
		        // It's important so that we can count the correct number of
		        // listeners on signals, and don't wait for the other one to
		        // handle it instead of us.
		        this.#emitter.count += 1;
		        for (const sig of signals_js_1.signals) {
		            try {
		                const fn = this.#sigListeners[sig];
		                if (fn)
		                    this.#process.on(sig, fn);
		            }
		            catch (_) { }
		        }
		        this.#process.emit = (ev, ...a) => {
		            return this.#processEmit(ev, ...a);
		        };
		        this.#process.reallyExit = (code) => {
		            return this.#processReallyExit(code);
		        };
		    }
		    unload() {
		        if (!this.#loaded) {
		            return;
		        }
		        this.#loaded = false;
		        signals_js_1.signals.forEach(sig => {
		            const listener = this.#sigListeners[sig];
		            /* c8 ignore start */
		            if (!listener) {
		                throw new Error('Listener not defined for signal: ' + sig);
		            }
		            /* c8 ignore stop */
		            try {
		                this.#process.removeListener(sig, listener);
		                /* c8 ignore start */
		            }
		            catch (_) { }
		            /* c8 ignore stop */
		        });
		        this.#process.emit = this.#originalProcessEmit;
		        this.#process.reallyExit = this.#originalProcessReallyExit;
		        this.#emitter.count -= 1;
		    }
		    #processReallyExit(code) {
		        /* c8 ignore start */
		        if (!processOk(this.#process)) {
		            return 0;
		        }
		        this.#process.exitCode = code || 0;
		        /* c8 ignore stop */
		        this.#emitter.emit('exit', this.#process.exitCode, null);
		        return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
		    }
		    #processEmit(ev, ...args) {
		        const og = this.#originalProcessEmit;
		        if (ev === 'exit' && processOk(this.#process)) {
		            if (typeof args[0] === 'number') {
		                this.#process.exitCode = args[0];
		                /* c8 ignore start */
		            }
		            /* c8 ignore start */
		            const ret = og.call(this.#process, ev, ...args);
		            /* c8 ignore start */
		            this.#emitter.emit('exit', this.#process.exitCode, null);
		            /* c8 ignore stop */
		            return ret;
		        }
		        else {
		            return og.call(this.#process, ev, ...args);
		        }
		    }
		}
		const process = globalThis.process;
		// wrap so that we call the method on the actual handler, without
		// exporting it directly.
		_a = signalExitWrap(processOk(process) ? new SignalExit(process) : new SignalExitFallback()), 
		/**
		 * Called when the process is exiting, whether via signal, explicit
		 * exit, or running out of stuff to do.
		 *
		 * If the global process object is not suitable for instrumentation,
		 * then this will be a no-op.
		 *
		 * Returns a function that may be used to unload signal-exit.
		 */
		exports$1.onExit = _a.onExit, 
		/**
		 * Load the listeners.  Likely you never need to call this, unless
		 * doing a rather deep integration with signal-exit functionality.
		 * Mostly exposed for the benefit of testing.
		 *
		 * @internal
		 */
		exports$1.load = _a.load, 
		/**
		 * Unload the listeners.  Likely you never need to call this, unless
		 * doing a rather deep integration with signal-exit functionality.
		 * Mostly exposed for the benefit of testing.
		 *
		 * @internal
		 */
		exports$1.unload = _a.unload;
		
	} (cjs));
	return cjs;
}

var hasRequiredLib;

function requireLib () {
	if (hasRequiredLib) return lib.exports;
	hasRequiredLib = 1;
	lib.exports = writeFile;
	lib.exports.sync = writeFileSync;
	lib.exports._getTmpname = getTmpname; // for testing
	lib.exports._cleanupOnExit = cleanupOnExit;

	const fs = fs$2;
	const crypto$1 = crypto;
	const { onExit } = requireCjs();
	const path$1 = path;
	const { promisify } = require$$4;
	const activeFiles = {};

	// if we run inside of a worker_thread, `process.pid` is not unique
	/* istanbul ignore next */
	const threadId = (function getId () {
	  try {
	    const workerThreads = require('worker_threads');

	    /// if we are in main thread, this is set to `0`
	    return workerThreads.threadId
	  } catch (e) {
	    // worker_threads are not available, fallback to 0
	    return 0
	  }
	})();

	let invocations = 0;
	function getTmpname (filename) {
	  return filename + '.' +
	    crypto$1.createHash('sha1')
	      .update(__filename)
	      .update(String(process.pid))
	      .update(String(threadId))
	      .update(String(++invocations))
	      .digest()
	      .readUInt32BE(0)
	}

	function cleanupOnExit (tmpfile) {
	  return () => {
	    try {
	      fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile);
	    } catch {
	      // ignore errors
	    }
	  }
	}

	function serializeActiveFile (absoluteName) {
	  return new Promise(resolve => {
	    // make a queue if it doesn't already exist
	    if (!activeFiles[absoluteName]) {
	      activeFiles[absoluteName] = [];
	    }

	    activeFiles[absoluteName].push(resolve); // add this job to the queue
	    if (activeFiles[absoluteName].length === 1) {
	      resolve();
	    } // kick off the first one
	  })
	}

	// https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342
	function isChownErrOk (err) {
	  if (err.code === 'ENOSYS') {
	    return true
	  }

	  const nonroot = !process.getuid || process.getuid() !== 0;
	  if (nonroot) {
	    if (err.code === 'EINVAL' || err.code === 'EPERM') {
	      return true
	    }
	  }

	  return false
	}

	async function writeFileAsync (filename, data, options = {}) {
	  if (typeof options === 'string') {
	    options = { encoding: options };
	  }

	  let fd;
	  let tmpfile;
	  /* istanbul ignore next -- The closure only gets called when onExit triggers */
	  const removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile));
	  const absoluteName = path$1.resolve(filename);

	  try {
	    await serializeActiveFile(absoluteName);
	    const truename = await promisify(fs.realpath)(filename).catch(() => filename);
	    tmpfile = getTmpname(truename);

	    if (!options.mode || !options.chown) {
	      // Either mode or chown is not explicitly set
	      // Default behavior is to copy it from original file
	      const stats = await promisify(fs.stat)(truename).catch(() => {});
	      if (stats) {
	        if (options.mode == null) {
	          options.mode = stats.mode;
	        }

	        if (options.chown == null && process.getuid) {
	          options.chown = { uid: stats.uid, gid: stats.gid };
	        }
	      }
	    }

	    fd = await promisify(fs.open)(tmpfile, 'w', options.mode);
	    if (options.tmpfileCreated) {
	      await options.tmpfileCreated(tmpfile);
	    }
	    if (ArrayBuffer.isView(data)) {
	      await promisify(fs.write)(fd, data, 0, data.length, 0);
	    } else if (data != null) {
	      await promisify(fs.write)(fd, String(data), 0, String(options.encoding || 'utf8'));
	    }

	    if (options.fsync !== false) {
	      await promisify(fs.fsync)(fd);
	    }

	    await promisify(fs.close)(fd);
	    fd = null;

	    if (options.chown) {
	      await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid).catch(err => {
	        if (!isChownErrOk(err)) {
	          throw err
	        }
	      });
	    }

	    if (options.mode) {
	      await promisify(fs.chmod)(tmpfile, options.mode).catch(err => {
	        if (!isChownErrOk(err)) {
	          throw err
	        }
	      });
	    }

	    await promisify(fs.rename)(tmpfile, truename);
	  } finally {
	    if (fd) {
	      await promisify(fs.close)(fd).catch(
	        /* istanbul ignore next */
	        () => {}
	      );
	    }
	    removeOnExitHandler();
	    await promisify(fs.unlink)(tmpfile).catch(() => {});
	    activeFiles[absoluteName].shift(); // remove the element added by serializeSameFile
	    if (activeFiles[absoluteName].length > 0) {
	      activeFiles[absoluteName][0](); // start next job if one is pending
	    } else {
	      delete activeFiles[absoluteName];
	    }
	  }
	}

	async function writeFile (filename, data, options, callback) {
	  if (options instanceof Function) {
	    callback = options;
	    options = {};
	  }

	  const promise = writeFileAsync(filename, data, options);
	  if (callback) {
	    try {
	      const result = await promise;
	      return callback(result)
	    } catch (err) {
	      return callback(err)
	    }
	  }

	  return promise
	}

	function writeFileSync (filename, data, options) {
	  if (typeof options === 'string') {
	    options = { encoding: options };
	  } else if (!options) {
	    options = {};
	  }
	  try {
	    filename = fs.realpathSync(filename);
	  } catch (ex) {
	    // it's ok, it'll happen on a not yet existing file
	  }
	  const tmpfile = getTmpname(filename);

	  if (!options.mode || !options.chown) {
	    // Either mode or chown is not explicitly set
	    // Default behavior is to copy it from original file
	    try {
	      const stats = fs.statSync(filename);
	      options = Object.assign({}, options);
	      if (!options.mode) {
	        options.mode = stats.mode;
	      }
	      if (!options.chown && process.getuid) {
	        options.chown = { uid: stats.uid, gid: stats.gid };
	      }
	    } catch (ex) {
	      // ignore stat errors
	    }
	  }

	  let fd;
	  const cleanup = cleanupOnExit(tmpfile);
	  const removeOnExitHandler = onExit(cleanup);

	  let threw = true;
	  try {
	    fd = fs.openSync(tmpfile, 'w', options.mode || 0o666);
	    if (options.tmpfileCreated) {
	      options.tmpfileCreated(tmpfile);
	    }
	    if (ArrayBuffer.isView(data)) {
	      fs.writeSync(fd, data, 0, data.length, 0);
	    } else if (data != null) {
	      fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8'));
	    }
	    if (options.fsync !== false) {
	      fs.fsyncSync(fd);
	    }

	    fs.closeSync(fd);
	    fd = null;

	    if (options.chown) {
	      try {
	        fs.chownSync(tmpfile, options.chown.uid, options.chown.gid);
	      } catch (err) {
	        if (!isChownErrOk(err)) {
	          throw err
	        }
	      }
	    }

	    if (options.mode) {
	      try {
	        fs.chmodSync(tmpfile, options.mode);
	      } catch (err) {
	        if (!isChownErrOk(err)) {
	          throw err
	        }
	      }
	    }

	    fs.renameSync(tmpfile, filename);
	    threw = false;
	  } finally {
	    if (fd) {
	      try {
	        fs.closeSync(fd);
	      } catch (ex) {
	        // ignore close errors at this stage, error may have closed fd already.
	      }
	    }
	    removeOnExitHandler();
	    if (threw) {
	      cleanup();
	    }
	  }
	}
	return lib.exports;
}

var libExports = requireLib();
var writeFileAtomic = /*@__PURE__*/getDefaultExportFromCjs(libExports);

export { writeFileAtomic as w };
//# sourceMappingURL=index-Ca4C2M45.js.map
