// --- API Key Masking Function ---
/**
* Masks API keys found in a string.
* Looks for patterns like "?key=XXX" or "&key=XXX" and replaces the key value.
* @param {string} text The string potentially containing an API key.
* @return {string} The string with the API key masked.
*/
function maskApiKey(text) {
if (typeof text !== "string") {
return text; // Return non-strings as is
}
// This regex looks for "?key=" or "&key=" followed by any characters
// that are NOT "&" or space (to avoid consuming subsequent parameters or parts of message)
// It replaces the key part with "REDACTED".
// The ($1) captures the preceding "?" or "&" and puts it back.
return text.replace(/([?&])key=[^&\s]+/, "$1key=REDACTED");
}
// --- Automatic Log Masking Setup ---
const originalConsoleLog = console.log;
// Redefine console.log to automatically mask API keys in string arguments
console.log = function (/** @type {any[]} */ ...args) {
const maskedArgs = args.map((arg) => maskApiKey(arg));
originalConsoleLog.apply(console, maskedArgs);
};
const originalConsoleError = console.error;
console.error = function (/** @type {any[]} */ ...args) {
const maskedArgs = args.map((arg) => maskApiKey(arg));
originalConsoleError.apply(console, maskedArgs);
};
const originalConsoleWarn = console.warn;
console.warn = function (/** @type {any[]} */ ...args) {
const maskedArgs = args.map((arg) => maskApiKey(arg));
originalConsoleWarn.apply(console, maskedArgs);
};
const originalConsoleInfo = console.info;
console.info = function (/** @type {any[]} */ ...args) {
const maskedArgs = args.map((arg) => maskApiKey(arg));
originalConsoleInfo.apply(console, maskedArgs);
};