import { stringify } from "./bigint-json.js";
import { LogContext } from "@rocicorp/logger";
import { pid } from "node:process";
import { styleText } from "node:util";
//#region ../shared/src/logging.ts
function style(color, args) {
	return styleText(color, args.join(" "));
}
var COLOR_DEBUG = "gray";
var COLOR_WARN = "yellow";
var COLOR_ERROR = "red";
/**
* Returns an object for writing colorized output to a provided console.
* Note this should only be used when console is a TTY (i.e., Node).
*/
var colorConsole = {
	log: (...args) => {
		console.log(...args);
	},
	debug: (...args) => {
		console.debug(style(COLOR_DEBUG, args));
	},
	info: (...args) => {
		console.info(...args);
	},
	warn: (...args) => {
		console.warn(style(COLOR_WARN, args));
	},
	error: (...args) => {
		console.error(style(COLOR_ERROR, args));
	}
};
var consoleSink = { log(level, context, ...args) {
	colorConsole[level](toLocalIsoString(), stringifyContext(context), ...args.map(stringifyValue));
} };
function toLocalIsoString(date = /* @__PURE__ */ new Date()) {
	const tzo = -date.getTimezoneOffset();
	const sign = tzo >= 0 ? "+" : "-";
	const pad = (n, len = 2) => String(Math.abs(n)).padStart(len, "0");
	return date.getFullYear() + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate()) + "T" + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds()) + "." + pad(date.getMilliseconds(), 3) + sign + pad(tzo / 60) + ":" + pad(tzo % 60);
}
function getLogSink(config) {
	return config.format === "json" ? consoleJsonLogSink : consoleSink;
}
function createLogContext({ log }, context = {}, sink = getLogSink(log)) {
	const ctx = {
		pid,
		...context
	};
	const lc = new LogContext(log.level, ctx, sink);
	lc.info?.("");
	return lc;
}
var consoleJsonLogSink = { log(level, context, ...args) {
	const lastObj = errorOrObject(args.at(-1));
	if (lastObj) args.pop();
	const message = args.length ? { message: args.map(stringifyValue).join(" ") } : void 0;
	console[level](stringify({
		level: level.toUpperCase(),
		...context,
		...lastObj,
		...message
	}));
} };
function errorOrObject(v) {
	if (v instanceof Error) return toErrorLogObject(v);
	if (v && typeof v === "object") return v;
}
function toErrorLogObject(v) {
	return {
		...v,
		name: v.name,
		errorMsg: v.message,
		stack: v.stack,
		..."cause" in v ? { cause: errorOrObject(v.cause) } : null
	};
}
function stringifyContext(context) {
	const args = [];
	for (const [k, v] of Object.entries(context ?? {})) {
		const arg = v === void 0 ? k : `${k}=${v}`;
		args.push(arg);
	}
	return args;
}
function stringifyValue(v) {
	if (typeof v === "string") return v;
	if (v instanceof Error) return stringify(toErrorLogObject(v));
	return stringify(v);
}
//#endregion
export { colorConsole, createLogContext, errorOrObject, getLogSink };

//# sourceMappingURL=logging.js.map