mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-04 00:15:41 -08:00
72 lines
2.0 KiB
JavaScript
72 lines
2.0 KiB
JavaScript
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
function cleanFields(fields) {
|
|
const out = {};
|
|
for (const [key, value] of Object.entries(fields || {})) {
|
|
if (value !== undefined) out[key] = value;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function createTiming({ outputPath, ref, version, mode } = {}) {
|
|
const target = outputPath !== undefined ? outputPath : process.env.PLAN2CODE_BENCH_JSON || null;
|
|
const active = Boolean(target);
|
|
const base = cleanFields({ ref, version, mode });
|
|
|
|
function write(record) {
|
|
if (!active) return null;
|
|
try {
|
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
fs.appendFileSync(target, `${JSON.stringify(record)}\n`, 'utf8');
|
|
return record;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function timingEvent(name, extra = {}) {
|
|
if (!active || typeof name !== 'string' || !name) return null;
|
|
return write({ event: name, at: new Date().toISOString(), ...base, ...cleanFields(extra) });
|
|
}
|
|
|
|
function timingDuration(name, startMark, extra = {}) {
|
|
const durationMs = typeof startMark === 'number' ? Math.max(0, performance.now() - startMark) : 0;
|
|
return timingEvent(name, { ...extra, durationMs });
|
|
}
|
|
|
|
return { active, outputPath: target, timingEvent, timingDuration };
|
|
}
|
|
|
|
function timingEvent(name, extra = {}) {
|
|
return createTiming().timingEvent(name, extra);
|
|
}
|
|
|
|
function timingDuration(name, startMark, extra = {}) {
|
|
return createTiming().timingDuration(name, startMark, extra);
|
|
}
|
|
|
|
function readTimingEvents(file) {
|
|
let text;
|
|
try {
|
|
text = fs.readFileSync(file, 'utf8');
|
|
} catch {
|
|
return [];
|
|
}
|
|
const events = [];
|
|
for (const line of text.split(/\r?\n/)) {
|
|
if (!line.trim()) continue;
|
|
try {
|
|
const event = JSON.parse(line);
|
|
if (event && typeof event === 'object' && !Array.isArray(event)) events.push(event);
|
|
} catch {
|
|
// Malformed lines are ignored so one partial write does not hide later events.
|
|
}
|
|
}
|
|
return events;
|
|
}
|
|
|
|
module.exports = { createTiming, timingEvent, timingDuration, readTimingEvents };
|