@logtape/windows-eventlog
Version:
Windows Event Log sink for LogTape
102 lines (100 loc) • 2.74 kB
JavaScript
import { getLogger } from "@logtape/logtape";
import { FFIType, dlopen, ptr } from "bun:ffi";
//#region ffi.bun.ts
/**
* Bun FFI implementation for Windows Event Log API
*/
var WindowsEventLogFFI = class {
eventSource = null;
lib = null;
sourceName;
initialized = false;
metaLogger = getLogger([
"logtape",
"meta",
"windows-eventlog"
]);
constructor(sourceName) {
this.sourceName = sourceName;
}
/**
* Initialize the FFI bindings and register event source
*/
initialize() {
if (this.initialized) return;
try {
this.lib = dlopen("advapi32.dll", {
RegisterEventSourceA: {
args: [FFIType.ptr, FFIType.cstring],
returns: FFIType.ptr
},
ReportEventA: {
args: [
FFIType.ptr,
FFIType.u16,
FFIType.u16,
FFIType.u32,
FFIType.ptr,
FFIType.u16,
FFIType.u32,
FFIType.ptr,
FFIType.ptr
],
returns: FFIType.bool
},
DeregisterEventSource: {
args: [FFIType.ptr],
returns: FFIType.bool
}
});
const encoder = new TextEncoder();
const sourceNameBuffer = encoder.encode(this.sourceName + "\0");
const result = this.lib.symbols.RegisterEventSourceA(null, sourceNameBuffer);
this.eventSource = typeof result === "number" ? result : null;
if (!this.eventSource || this.eventSource === 0) throw new Error(`Failed to register event source: ${this.sourceName}`);
this.initialized = true;
} catch (error) {
throw new Error(`Failed to initialize Windows Event Log FFI: ${error}`);
}
}
/**
* Write an event to Windows Event Log
*/
writeEvent(eventType, eventId, message) {
if (!this.initialized || !this.eventSource || !this.lib) return;
try {
const encoder = new TextEncoder();
const messageBuffer = encoder.encode(message + "\0");
const ptrArray = new BigUint64Array(2);
ptrArray[0] = BigInt(ptr(messageBuffer));
ptrArray[1] = 0n;
const success = this.lib.symbols.ReportEventA(this.eventSource, eventType, 0, eventId, null, 1, 0, ptrArray, null);
if (!success) throw new Error(`ReportEventA returned false`);
} catch (error) {
throw error;
}
}
/**
* Clean up resources
*/
dispose() {
if (this.initialized && this.eventSource && this.lib) {
try {
this.lib.symbols.DeregisterEventSource(this.eventSource);
} catch (error) {
this.metaLogger.error("Failed to deregister event source during cleanup: {error}", { error });
}
this.eventSource = null;
this.initialized = false;
try {
this.lib.close();
} catch (error) {
this.metaLogger.error("Failed to close FFI library during cleanup: {error}", { error });
}
this.lib = null;
}
}
};
//#endregion
export { WindowsEventLogFFI };
//# sourceMappingURL=ffi.bun.js.map