import { networkInterfaces } from 'os'; import { createHash, randomBytes } from 'crypto'; import { promises, constants } from 'fs'; import { dirname } from "path"; /** * Check to see if the input is a valid JSON string * * @param {*} str The string to check for valud JSON * @returns {true|false} */ export const isJsonString = (str) => { try { JSON.parse(str); } catch (e) { return false; } return true; } /** * Check to see if a path exists, creating it if it does not * @returns {undefined} */ export const ensureDirectoryExists = async (filePath) => { const directory = dirname(filePath); try { await promises.access(directory, constants.F_OK); } catch (error) { await promises.mkdir(directory, { recursive: true }); } }; /** * Generate a unique ID for a given device, this will also be unique on the same device at a different time. * @returns {string} A generated unique ID */ export const generateUniqueID = () => { const netInterfaces = networkInterfaces(); let macAddress = ''; // Find the first non-internal MAC address for (const key in netInterfaces) { const iface = netInterfaces[key][0]; if (!iface.internal) { macAddress = iface.mac; break; } } // If no non-internal MAC address is found, fallback to a random value if (!macAddress) { macAddress = randomBytes(6).toString('hex').toUpperCase(); } // Use MAC address and current timestamp to create a unique ID const timestamp = Date.now(); const uniqueID = createHash('sha256') .update(macAddress + timestamp) .digest('hex'); return uniqueID; } /** * Extracts the value after a specific pattern from a string using regular expressions. * @param {string} input - The input string. * @param {string} pattern - The pattern to match. * @returns {string|null} The value found after the pattern, or null if not found. */ export const extractValue = (input, pattern) => { const regex = new RegExp(`${pattern}`); const match = input.match(regex); return match ? match : null; };