UNPKG

@logtape/windows-eventlog

Version:

Windows Event Log sink for LogTape

102 lines (100 loc) 2.82 kB
import { getLogger } from "@logtape/logtape"; import { FFIType, dlopen, ptr } from "bun:ffi"; //#region src/ffi.bun.ts /** * Bun FFI implementation for Windows Event Log API */ var WindowsEventLogBunFFI = class { eventSource = null; lib = null; sourceName = ""; initialized = false; metaLogger = getLogger([ "logtape", "meta", "windows-eventlog" ]); /** * Initialize the FFI bindings and register event source */ initialize(sourceName) { this.sourceName = sourceName; 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, params) { if (!this.initialized || !this.eventSource || !this.lib) return; try { const ptrArray = new BigUint64Array(params.length + 1); const encoder = new TextEncoder(); for (let i = 0; i < params.length; i++) { const paramBuffer = encoder.encode(params[i] + "\0"); ptrArray[i] = BigInt(ptr(paramBuffer)); } ptrArray[params.length] = 0n; const success = this.lib.symbols.ReportEventA(this.eventSource, eventType, 0, eventId, null, params.length, 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 { WindowsEventLogBunFFI }; //# sourceMappingURL=ffi.bun.js.map