// Pure parts of the feature measurement tool: arguments, safety refusals, statistics, the process tree, and the report table. import path from "node:path"; export const FEATURES = ["git", "background", "terminal", "pdf", "pm"]; export const MODES = ["plugin", "native"]; export const SCENARIOS = ["on-idle", "in-use", "after-off"]; /** The app that the owner installed. The tool never starts it, stops it, or touches its data. */ export const INSTALLED_EXE = "D:\\Users\\KnottyWyvern\\AppData\\Local\\RuneStone\\runestone.exe"; export const INSTALLED_IDENTIFIER = "com.runestone.app"; export const USAGE = "Usage: node scripts/measureFeatures.mjs --exe --identifier com.runestone. --stage --mode plugin|native --features git,background,terminal,pdf,pm [--runs 3] [--port 9241] [--fresh-fixture] [--only base,:,...] [--skip-base]"; /** Read the command line. Throw an error with the usage text for a missing or unknown argument. */ export function parseArguments(args) { const options = { exe: undefined, identifier: undefined, stage: undefined, mode: undefined, features: undefined, runs: 3, port: 9241, freshFixture: false, only: undefined, skipBase: false }; const values = { "--exe": "exe", "--identifier": "identifier", "--stage": "stage", "--mode": "mode", "--features": "features", "--runs": "runs", "--port": "port", "--only": "only" }; const seen = new Set(); for (let index = 0; index < args.length; index++) { const arg = args[index]; if (arg === "--fresh-fixture") { options.freshFixture = true; continue; } if (arg === "--skip-base") { options.skipBase = true; continue; } const key = values[arg]; if (!key) throw new Error(`Unknown argument ${arg}. ${USAGE}`); if (seen.has(arg)) throw new Error(`Give ${arg} one time only. ${USAGE}`); seen.add(arg); const value = args[++index]; if (value === undefined || value.startsWith("--")) throw new Error(`${arg} needs a value. ${USAGE}`); options[key] = value; } for (const key of ["exe", "identifier", "stage", "mode", "features"]) if (options[key] === undefined) throw new Error(`--${key} is required. ${USAGE}`); if (!MODES.includes(options.mode)) throw new Error(`--mode must be plugin or native. ${USAGE}`); if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(options.stage)) throw new Error("--stage must be a simple folder name."); const features = options.features.split(",").map(feature => feature.trim()).filter(Boolean); const unknown = features.filter(feature => !FEATURES.includes(feature)); if (!features.length || unknown.length) throw new Error(`Unknown feature ${unknown.join(", ") || "(none)"}. Use ${FEATURES.join(", ")}.`); options.features = [...new Set(features)]; for (const key of ["runs", "port"]) { const number = Number(options[key]); if (typeof options[key] === "string" && !/^\d+$/.test(options[key])) throw new Error(`--${key} must be a whole number.`); options[key] = number; } if (options.runs < 1 || options.runs > 20) throw new Error("--runs must be from 1 to 20."); if (options.port < 1024 || options.port > 65535) throw new Error("--port must be from 1024 to 65535."); if (options.only !== undefined) { options.only = options.only.split(",").map(item => item.trim()).filter(Boolean); for (const item of options.only) { const [feature, scenario] = item.split(":"); if (!(item === "base" || (options.features.includes(feature) && SCENARIOS.includes(scenario)))) throw new Error(`--only takes base or :, not ${item}.`); } } return options; } function samePath(a, b) { return path.win32.resolve(a).toLowerCase() === path.win32.resolve(b).toLowerCase(); } /** * Refuse an unsafe target. The executable must not be the installed app or be in its folder. * The identifier must start with `com.runestone.` and must not be the identifier of the installed app. * `env` supplies LOCALAPPDATA and APPDATA. Return the two data folders that the tool may reset. */ export function checkTarget({ exe, identifier }, env = process.env) { const installed = [INSTALLED_EXE]; if (env.LOCALAPPDATA) installed.push(path.win32.join(env.LOCALAPPDATA, "RuneStone", "runestone.exe")); const resolved = path.win32.resolve(exe); for (const target of installed) { if (samePath(resolved, target) || samePath(path.win32.dirname(resolved), path.win32.dirname(target))) throw new Error(`Refusing to run the installed RuneStone (${target}). Give a copy of a test build.`); } if (typeof identifier !== "string" || identifier.toLowerCase() === INSTALLED_IDENTIFIER) throw new Error(`Refusing the identifier ${identifier}. It belongs to the installed RuneStone.`); if (!/^com\.runestone\.[a-z0-9][a-z0-9-]*$/.test(identifier)) throw new Error(`Refusing the identifier ${identifier}. A test identifier starts with com.runestone. and has lowercase letters, digits, and hyphens.`); if (!env.APPDATA || !env.LOCALAPPDATA) throw new Error("APPDATA and LOCALAPPDATA must be set."); return { roaming: path.win32.join(env.APPDATA, identifier), local: path.win32.join(env.LOCALAPPDATA, identifier) }; } /** The median of the finite numbers in `values`, or null when there is none. */ export function median(values) { const numbers = values.filter(value => typeof value === "number" && Number.isFinite(value)).sort((a, b) => a - b); if (!numbers.length) return null; const middle = Math.floor(numbers.length / 2); return numbers.length % 2 ? numbers[middle] : (numbers[middle - 1] + numbers[middle]) / 2; } /** * Walk the descendants of `rootPid` in a process list from Win32_Process. * A child counts only when it started after its parent, so a reused parent process ID does not add a stranger. * Return the processes of the tree, with the root first, and the sums of the private bytes and the working sets. */ export function processTree(list, rootPid) { const byParent = new Map(); for (const item of list) { if (!byParent.has(item.ParentProcessId)) byParent.set(item.ParentProcessId, []); byParent.get(item.ParentProcessId).push(item); } const root = list.find(item => item.ProcessId === rootPid); if (!root) return { processes: [], privateBytes: 0, workingSet: 0, count: 0, names: {} }; const processes = [root]; const seen = new Set([rootPid]); for (let index = 0; index < processes.length; index++) { const parent = processes[index]; for (const child of byParent.get(parent.ProcessId) ?? []) { if (seen.has(child.ProcessId)) continue; if (typeof child.Created === "number" && typeof parent.Created === "number" && child.Created < parent.Created) continue; seen.add(child.ProcessId); processes.push(child); } } const names = {}; for (const item of processes) names[item.Name] = (names[item.Name] ?? 0) + 1; return { processes, privateBytes: processes.reduce((sum, item) => sum + Number(item.PrivatePageCount ?? 0), 0), workingSet: processes.reduce((sum, item) => sum + Number(item.WorkingSetSize ?? 0), 0), count: processes.length, names, }; } export const METRICS = ["privateMB", "workingSetMB", "heapMB", "startMs", "firstNeedMs", "longTaskCount", "longTaskMaxMs", "processCount"]; /** The median of each metric over the samples that did not fail. */ export function summarize(samples) { const good = samples.filter(sample => !sample.error); const result = { runs: samples.length, failed: samples.length - good.length }; for (const metric of METRICS) result[metric] = median(good.map(sample => sample[metric])); return result; } const fixed = (value, digits = 1) => value === null || value === undefined ? "–" : Number(value).toFixed(digits); /** The Markdown report: one table row for each feature and scenario. */ export function markdownTable(report) { const lines = [ `# Feature memory: ${report.stage}`, "", `Build: \`${report.build}\` (${report.identifier}), mode ${report.mode}, ${report.runs} runs for each scenario, ${report.date}.`, `Machine: ${report.machine.cpu}, ${fixed(report.machine.ramGB)} GB RAM, ${report.machine.windows}.`, "Each value is the median of the runs. Private and working set are sums over the process tree of the app.", "", "| Feature | Scenario | Private MB | Working set MB | JS heap MB | Start ms | First need ms | Long tasks (count / longest ms) |", "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |", ]; for (const row of report.rows) { const m = row.median; if (!m || m.runs === m.failed) { lines.push(`| ${row.feature} | ${row.scenario} | failed | | | | | ${row.reason ? row.reason.replace(/\|/g, "/").slice(0, 160) : ""} |`); continue; } const failed = m.failed ? ` (${m.failed} of ${m.runs} runs failed)` : ""; lines.push(`| ${row.feature} | ${row.scenario}${failed} | ${fixed(m.privateMB)} | ${fixed(m.workingSetMB)} | ${fixed(m.heapMB)} | ${fixed(m.startMs, 0)} | ${fixed(m.firstNeedMs, 0)} | ${fixed(m.longTaskCount, 0)} / ${fixed(m.longTaskMaxMs, 0)} |`); } if (report.notes?.length) lines.push("", "Notes:", "", ...report.notes.map(note => `- ${note}`)); return lines.join("\n") + "\n"; }