// lib/util/is-main.mjs // Whether a module is the script node was started with, so a module can be both // a library and a CLI: `if (isMain(import.meta.url)) { ... }`. // // Real paths on both sides. The older guard, import.meta.url === `file://${argv[1]}`, // is false under a symlinked path (import.meta.url is the realpath) and under a // path with a space (URL-encoded), and the CLI then exits 0 having done nothing // (measured 2026-10-04). One helper instead of a copy per CLI (release review of // 6.3.0, round 7: 31 copies of the fixed guard and 20 of the old one). import { realpathSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; /** * @param {string} url - the calling module's import.meta.url * @param {string|undefined} [argv1] - the started script (process.argv[1]) * @returns {boolean} */ export function isMain(url, argv1 = process.argv[1]) { if (!argv1) return false; try { return realpathSync(argv1) === realpathSync(fileURLToPath(url)); } catch { return false; } }