@ai2070/l0
Version:
L0: The Missing Reliability Substrate for AI
92 lines • 2.52 kB
JavaScript
import { uuidv7 } from "../utils/uuid";
function deepCloneAndFreeze(obj) {
if (obj === null || typeof obj !== "object") {
return obj;
}
if (Array.isArray(obj)) {
const cloned = obj.map((item) => deepCloneAndFreeze(item));
return Object.freeze(cloned);
}
const cloned = {};
for (const key of Object.keys(obj)) {
cloned[key] = deepCloneAndFreeze(obj[key]);
}
return Object.freeze(cloned);
}
export class EventDispatcher {
handlers = [];
streamId;
_context;
constructor(context = {}) {
this.streamId = uuidv7();
this._context = deepCloneAndFreeze(context);
}
onEvent(handler) {
this.handlers.push(handler);
}
offEvent(handler) {
const index = this.handlers.indexOf(handler);
if (index !== -1) {
this.handlers.splice(index, 1);
}
}
emit(type, payload) {
if (this.handlers.length === 0)
return;
const event = {
type,
ts: Date.now(),
streamId: this.streamId,
context: this._context,
...payload,
};
for (const handler of [...this.handlers]) {
queueMicrotask(() => {
try {
const result = handler(event);
if (result && typeof result === "object" && "catch" in result) {
result.catch(() => {
});
}
}
catch {
}
});
}
}
emitSync(type, payload) {
if (this.handlers.length === 0)
return;
const event = {
type,
ts: Date.now(),
streamId: this.streamId,
context: this._context,
...payload,
};
for (const handler of [...this.handlers]) {
try {
const result = handler(event);
if (result && typeof result === "object" && "catch" in result) {
result.catch(() => {
});
}
}
catch {
}
}
}
getStreamId() {
return this.streamId;
}
getContext() {
return this._context;
}
getHandlerCount() {
return this.handlers.length;
}
}
export function createEventDispatcher(context = {}) {
return new EventDispatcher(context);
}
//# sourceMappingURL=event-dispatcher.js.map