"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../_virtual/_rolldown/runtime.js');
const require_node_fs = require('../node/fs.js');
const require_primordials_date = require('../primordials/date.js');
const require_primordials_json = require('../primordials/json.js');
const require_fs_safe = require('../fs/safe.js');
const require_ipc__internal = require('./_internal.js');
const require_ipc_directory = require('./directory.js');
const require_ipc_paths = require('./paths.js');
const require_schema_parse = require('../schema/parse.js');
let node_process = require("node:process");
node_process = require_runtime.__toESM(node_process);

//#region src/ipc/write.ts
/**
* @file Atomic stub write — `O_CREAT|O_WRONLY|O_EXCL| O_NOFOLLOW` so we refuse
*   to overwrite a pre-existing stub (collision with attacker-planted file or
*   PID reuse) and refuse to follow symlinks at the final path component. One
*   retry on EEXIST after `safeDelete` to handle the legitimate stale-stub case
*   where the previous owner exited ungracefully.
*/
/**
* Write IPC data to a stub file for inter-process data transfer.
*
* Creates a stub file containing data that needs to be passed between
* processes. The file is written with 0o600 permissions so only the invoking
* user can read it.
*
* ## File Structure:
*
* ```json
* {
*   "pid": 12345,
*   "timestamp": 1699564234567,
*   "data": { ... }
* }
* ```
*
* @example
*   ;```typescript
*   const stubPath = await writeIpcStub('socket-cli', {
*   apiToken: 'secret-token',
*   config: { ... }
*   })
*   // Pass stubPath to child process for reading
*   ```
*
* @param appName - The application identifier.
* @param data - The data to write to the stub file.
*
* @returns Promise resolving to the stub file path
*/
async function writeIpcStub(appName, data) {
	const stubPath = require_ipc_paths.getIpcStubPath(appName);
	await require_ipc_directory.ensureIpcDirectory(stubPath);
	const validated = require_schema_parse.parseSchema(require_ipc__internal.IpcStubSchema, {
		data,
		pid: node_process.default.pid,
		timestamp: require_primordials_date.DateNow()
	});
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	const flags = fs.constants.O_CREAT | fs.constants.O_WRONLY | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW;
	let handle;
	try {
		handle = await fs.promises.open(stubPath, flags, 384);
	} catch (e) {
		const err = e;
		if (err.code === "EEXIST") {
			await require_fs_safe.safeDelete(stubPath);
			handle = await fs.promises.open(stubPath, flags, 384);
		} else throw err;
	}
	try {
		await handle.writeFile(require_primordials_json.JSONStringify(validated, void 0, 2), "utf8");
	} finally {
		await handle.close();
	}
	return stubPath;
}

//#endregion
exports.writeIpcStub = writeIpcStub;