//#region src/retry/retryable-errors.ts
const TIER_1_ALWAYS_RETRY = new Set(["40001", "40P01"]);
const TIER_2_CONNECTION = new Set([
	"08000",
	"08003",
	"08006",
	"08001",
	"08004",
	"57P01",
	"57P03"
]);
const TIER_3_RESOURCE = new Set([
	"53000",
	"53100",
	"53200",
	"53300",
	"55P03",
	"57014"
]);
const DEFAULT_RETRYABLE_CODES = new Set([
	...TIER_1_ALWAYS_RETRY,
	...TIER_2_CONNECTION,
	...TIER_3_RESOURCE
]);
const RETRYABLE_NODE_ERROR_CODES = new Set([
	"ECONNREFUSED",
	"ECONNRESET",
	"EPIPE",
	"ETIMEDOUT",
	"EHOSTUNREACH",
	"ENETUNREACH",
	"EAI_AGAIN"
]);
const RETRYABLE_POOL_MESSAGES = [
	"timeout exceeded when trying to connect",
	"Connection terminated due to connection timeout",
	"Connection terminated unexpectedly"
];
const NON_RETRYABLE_POOL_MESSAGES = ["Cannot use a pool after calling end on the pool"];
const SQLSTATE_PATTERN = /^[0-9A-Z]{5}$/;
function getPostgresErrorCode(error) {
	if (!error || typeof error !== "object") return void 0;
	const err = error;
	if (err.cause?.code && typeof err.cause.code === "string" && SQLSTATE_PATTERN.test(err.cause.code)) return err.cause.code;
	if (err.code && typeof err.code === "string" && SQLSTATE_PATTERN.test(err.code)) return err.code;
}
function isRetryableError(error, retryableCodes = DEFAULT_RETRYABLE_CODES) {
	if (!error || typeof error !== "object") return false;
	const err = error;
	const sqlstate = getPostgresErrorCode(error);
	if (sqlstate && retryableCodes.has(sqlstate)) return true;
	const nodeCode = err.code ?? err.cause?.code;
	if (typeof nodeCode === "string" && RETRYABLE_NODE_ERROR_CODES.has(nodeCode)) return true;
	const messages = [err.message, err.cause?.message].filter((m) => typeof m === "string");
	for (const message of messages) {
		if (NON_RETRYABLE_POOL_MESSAGES.some((m) => message.includes(m))) return false;
		if (RETRYABLE_POOL_MESSAGES.some((m) => message.includes(m))) return true;
	}
	return false;
}
function isForeignKeyViolation(error) {
	return getPostgresErrorCode(error) === "23503";
}
function isSerializationError(error) {
	if (!error || typeof error !== "object") return false;
	const err = error;
	const code = err?.cause?.code ?? err?.code;
	return code === "40001" || code === "40P01" || code === "XX000";
}

//#endregion
export { DEFAULT_RETRYABLE_CODES, RETRYABLE_NODE_ERROR_CODES, RETRYABLE_POOL_MESSAGES, getPostgresErrorCode, isForeignKeyViolation, isRetryableError, isSerializationError };