browser-debugger-cli
Version:
DevTools telemetry in your terminal. For humans and agents. Direct WebSocket to Chrome's debugging port.
89 lines • 2.81 kB
JavaScript
/**
* Session metadata management.
*
* Handles reading/writing session metadata (Chrome PID, CDP port, target info, etc).
* WHY: Metadata persistence enables `bdg status` and other commands to inspect active sessions.
*/
import * as fs from 'fs';
import { createLogger } from '../ui/logging/index.js';
import { AtomicFileWriter } from '../utils/atomicFile.js';
import { getErrorMessage } from '../utils/errors.js';
import { getSessionFilePath, ensureSessionDir } from './paths.js';
const log = createLogger('session');
/**
* Handle corrupted metadata file.
*
* @param metaPath - Path to metadata file
* @param error - Error that occurred during parsing
* @param options - Error handling options
*/
function handleCorruptedMetadata(metaPath, error, options) {
if (options?.warnOnCorruption) {
log.info(`Session metadata corrupted (cannot read details): ${getErrorMessage(error)}`);
log.info('Troubleshooting: Run "bdg cleanup" to remove corrupted files');
}
if (options?.selfHealOnCorruption) {
try {
fs.rmSync(metaPath, { force: true });
log.info('Removed corrupted session metadata file');
}
catch (deleteError) {
log.debug(`Failed to remove corrupted metadata: ${getErrorMessage(deleteError)}`);
}
}
}
/**
* Write session metadata atomically.
*
* Uses atomic write (tmp file + rename) to prevent corruption.
*
* @param metadata - Session metadata to write
*
* @example
* ```typescript
* writeSessionMetadata({
* bdgPid: process.pid,
* chromePid: 12345,
* startTime: Date.now(),
* port: 9222,
* activeCollectors: ['network', 'console', 'dom']
* });
* ```
*/
export function writeSessionMetadata(metadata) {
ensureSessionDir();
const metaPath = getSessionFilePath('METADATA');
AtomicFileWriter.writeSync(metaPath, JSON.stringify(metadata, null, 2));
}
/**
* Read session metadata.
*
* WHY: P1 Fix #2 - Now logs warnings when metadata is corrupted.
*
* @param options - Options for error handling
* @returns Session metadata if file exists and is valid, null otherwise
*
* @example
* ```typescript
* const metadata = readSessionMetadata({ warnOnCorruption: true });
* if (metadata) {
* console.log(`Session started at: ${new Date(metadata.startTime)}`);
* console.log(`Chrome PID: ${metadata.chromePid}`);
* }
* ```
*/
export function readSessionMetadata(options) {
const metaPath = getSessionFilePath('METADATA');
if (!fs.existsSync(metaPath)) {
return null;
}
try {
const content = fs.readFileSync(metaPath, 'utf-8');
return JSON.parse(content);
}
catch (error) {
handleCorruptedMetadata(metaPath, error, options);
return null;
}
}
//# sourceMappingURL=metadata.js.map