npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@statedelta-actions/events

v0.7.0

Published

Event processing engine with listener dispatch and JIT optimization

Readme

@statedelta-actions/events

EventProcessor — eventos como actions deferidas. Dispatcher de listeners sobre o ActionEngine: listeners reagem a eventos nomeados, executando diretivas via hidden actions. Dependências: core/ (tipos, slot analysis), actions/ (IActionEngine). Zero dependência de rules/.

Para arquitetura interna, pipelines e fluxos, ver docs/ARCHITECTURE.md. Para decisões arquiteturais, ver docs/DECISIONS.md.


O que é

O EventProcessor é um dispatcher de listeners sobre o ActionEngine. Quando o consumer emite { event: "save" }, o processor resolve quais listeners escutam "save", monta params, e delega a execução pro ActionEngine via invoke().

Evento = action deferida. A única diferença entre action e evento é quando executa. A infraestrutura é idêntica — registro, params, directives, invoke. O EventProcessor não executa diretivas ele mesmo.

Listeners viram hidden actions. Cada listener registrado cria uma action event:{id} no ActionEngine. Isso significa que listeners coexistem no mesmo grafo com actions diretas e rules (rule:{id}). O analyzer valida tudo junto — ciclos, capabilities, composition control.

Sem condição, sem cascade. Listeners não têm when() (match por nome, não por expressão) nem sub-rules (dispatch direto, sem recursão). Chegou evento, matched, executa.

Halt é scoped ao evento. Halt em um listener para apenas os listeners daquele evento. O próximo evento na fila continua normalmente.


EventListenerDefinition — O que o consumer fornece

interface EventListenerDefinition<TCtx> {
  readonly id: string;
  readonly priority: number;
  readonly on: string | string[];
  readonly then: readonly Directive<TCtx>[];
  readonly tags?: readonly string[];
  readonly declarations?: Record<string, unknown>;
  readonly metadata?: Record<string, unknown>;
}

| Campo | Semântica | |-------|-----------| | id | Identificador único do listener | | priority | Ordem de execução (desc — maior executa primeiro) | | on | Evento(s) que o listener escuta. String ou array | | then | Diretivas executadas quando matched | | tags | Tags extras (além de "event" que é injetado automaticamente) | | declarations | Contratos públicos passados pro grafo (trust boundaries) | | metadata | Dados opacos armazenados na definition |


API

Construction

import { createEventProcessor } from "@statedelta-actions/events";

const ep = createEventProcessor({
  actionEngine,                // IActionEngine — obrigatório
  eventHooks: { ... },         // EventHooks — opcional
  middleware: [ ... ],         // EventMiddleware[] — opcional
  mode: "auto",               // "interpret" | "jit" | "auto" (default: "auto")
  autoJitThreshold: 8,        // Chamadas antes de auto-promote (default: 8)
});

Registration

// Registrar listeners
const result = ep.register([
  {
    id: "on-save",
    priority: 100,
    on: "save",
    then: [{ type: "state", target: "hp", value: 10 }],
  },
  {
    id: "on-damage",
    priority: 200,
    on: ["damage", "combat"],   // multi-event
    then: [{ type: "state", target: "shield", value: -1 }],
  },
]);

// result: { registered: string[], errors: EventRegisterError[], warnings: RegisterWarning[] }

// Remover listener
ep.unregister("on-save");  // true se existia, false se não

Throw vs collected errors

register e defineEvents são atômicos: o registro local só é aplicado depois que o ActionEngine aceita todas as hidden actions. Comportamento por tipo de erro:

| Erro | Comportamento | |------|---------------| | Handler ausente para um tipo de diretiva em then (qualquer profundidade, inclusive catch) | Lança Error propagado do actionEngine.register. Estado local intocado. | | Listener/event duplicado, missing required field, tier violation contra EventDefinition | Coletado em errors[]. Outros itens válidos no mesmo call ainda registram. | | validate() de handler retorna invalid ou lança | Coletado em errors[]. |

Throw é reservado pra erros estruturais que não viram válidos em runtime — typo, handler esquecido, refactor incompleto. Soft errors são domain-level e merecem inspeção pelo consumer.

Processing

// Sync (throws se algum listener é async ou interactive transitivamente)
const result = ep.processEvents(
  [{ event: "save" }, { event: "damage", data: { amount: 10 } }],
  ctx,
);

// Async (throws se algum listener é interactive transitivamente)
const result = await ep.processEventsAsync(
  [{ event: "save" }],
  ctx,
);

// Interactive — retorna iterator drenável (sync ou async generator)
const session = ep.processEventsInteractive([{ event: "save" }], ctx);
let step = session.next();
while (!step.done) {
  // step.value = payload do yield (PauseEvent ou payload de handler interactive)
  step = session.next(/* resposta do consumer */);
}
// step.value = EventProcessingResult

processEventsInteractive lança se nenhum listener registrado é interactive transitivamente. Pausas fluem via yield* em 3 níveis (consumer → events generator → actionEngine.invokeInteractive). Halt scoping preservado: pause/halt num listener para os listeners daquele evento; próximos eventos na fila continuam.

Contrato de ordenação (estável)

A ordem de avaliação dos listeners por evento é determinística e contratual — consumers podem depender; mudança = breaking:

  1. Priority descendente — maior priority avalia primeiro.
  2. FIFO entre prioridades iguais — empate resolve por ordem de registro. Inserção via binary insertion estável.
  3. Fonte únicaprocessEvents(), processEventsAsync() e processEventsInteractive() percorrem a mesma estrutura ordenada (_listenerIndex por evento). Ordem idêntica nos três.

Para obter essa ordem sem reconstruir (debug, devtools, tracing), use ep.getListenersOrdered() — snapshot imutável ReadonlyMap<string, readonly ListenerView[]> ({ id, event, priority }) na ordem canônica exata por evento. É function (não getter): materializa O(N) por chamada. Ver ADR-027.

const byEvent = ep.getListenersOrdered();
byEvent.get("save"); // [{ id, event:"save", priority }, ...] — ordem de processEvents

Event bridge — createEventBridge()

Glue canônico actions↔events: o handler emit (produz { event, data }) ↔ collectEvents() (drena pro processor). Opt-in — o consumer registra emitHandler no ActionEngine; o events não auto-registra (mesmo princípio de HALT_HANDLER/createActionHandler).

import { createEventBridge } from "@statedelta-actions/events";

const bridge = createEventBridge();
const engine = createActionEngine({ handlers: { emit: bridge.emitHandler } });
// drain loop:
ep.processEvents(bridge.collectEvents(), ctx);

O emitHandler já vem com o analyze canônico por default (createEmitAnalyzer — capability emit + dependency eventdef:{event}): é identidade do handler emit, não concern do consumer. Peça completa = execute + analyze; entregar só execute faria o consumer recablear, com erro silencioso (buraco no grafo do Analyzer). Custo zero com analyzer off.

Config: eventField/dataField (default "event"/"data"), suppressed?: () => boolean (no-op opt-in para execução especulativa), analyze?: false | fn (override do canônico). createEmitAnalyzer segue exportado avulso para handlers emit custom. Ver ADR-028.

Batch

ep.beginBatch();
ep.register(listeners1);
ep.register(listeners2);
const result = ep.endBatch();
// Suporta nesting — inner endBatch é no-op, outer processa tudo

Compilation

// Força promoção pra JIT (no-op se já em JIT ou mode = "interpret")
ep.compile();

// Consultar modo atual
ep.compilationMode;  // "interpret" | "jit"
ep.isAsync;          // true se hooks são async OU se algum listener é async transitivamente
ep.isInteractive;    // true se algum listener é interactive transitivamente

isAsync e isInteractive são per-listener transitivos. Engine híbrido (handler async + listener cuja sub-árvore é 100% sync) mantém processEvents (sync) viável — só listeners que invocam handler async transitivamente forçam processEventsAsync, só listeners interactive transitivamente forçam processEventsInteractive. Detecção via mini-graph do ActionEngine, refrescada em register/unregister/endBatch. O dispatcher interactive é lazy — só construído na primeira chamada de processEventsInteractive (custo zero pra engines sem nada interactive).


Hooks — EventHooks

interface EventHooks<TCtx> {
  beforeEvent?: (listener, evalCtx) => "skip" | "abort" | void;
  afterEvent?:  (listener, result, evalCtx) => "abort" | void;
  onEventsComplete?: (result) => void;
}

| Hook | Quando | Retornos | |------|--------|----------| | beforeEvent | Antes de cada listener | "skip" pula listener, "abort" para evento | | afterEvent | Após invoke de cada listener | "abort" para evento | | onEventsComplete | Após processar todos os eventos | fire-and-forget |

Hooks ausentes não têm custo — nem no interpreter nem no JIT.

Exemplo: disable via hook

const disabled = new Set<string>();

const ep = createEventProcessor({
  actionEngine,
  eventHooks: {
    beforeEvent: (listener) => {
      if (disabled.has(listener.id)) return "skip";
    },
  },
});

disabled.add("on-save");   // "disable"
disabled.delete("on-save"); // "enable"

Middleware

type EventMiddleware<TCtx> = (
  listener: EventListenerDefinition<TCtx>,
  ctx: TCtx,
  params: Record<string, unknown>,
) => Record<string, unknown>;

Middleware é pipeline de enriquecimento de dados. Não afeta fluxo de controle (sem "skip", sem "abort"). Cada middleware recebe e retorna params.

const ep = createEventProcessor({
  actionEngine,
  middleware: [
    (listener, ctx, params) => ({
      ...params,
      timestamp: Date.now(),
      source: listener.id,
    }),
  ],
});

Sem middleware, $event chega direto no scope da action. Com middleware, $event entra como base e o middleware enriquece.


$event Injection

Todo listener recebe automaticamente no scope:

{ $event: { type: "save", data: eventData } }

Acessível dentro de handlers via frame.scope.$event.


Results

interface EventProcessingResult {
  readonly eventResults: readonly SingleEventResult[];
  readonly unprocessedEvents: readonly string[];   // eventos sem listeners
  readonly errors: readonly RuleError[];
  readonly counters: FrameCounters;
  readonly totalEvents: number;
  readonly processedEvents: number;
}

interface SingleEventResult {
  readonly event: string;
  readonly matched: readonly number[];
  readonly skipped: readonly number[];
  readonly notMatched: readonly number[];
  readonly errors: readonly RuleError[];
  readonly halted: boolean;
  readonly haltedBy?: string;
  readonly counters: FrameCounters;
}

interface EventRegisterResult {
  readonly registered: readonly string[];
  readonly errors: readonly EventRegisterError[];
  readonly warnings: readonly RegisterWarning[];
}

Compilation — 3 Modos

| Modo | Comportamento | |------|--------------| | "interpret" | Interpreter sempre. Sem promoção | | "jit" | JIT imediato no constructor | | "auto" (default) | Interpreter inicial. Promove pra JIT após autoJitThreshold chamadas |

O JIT gera código equivalente ao interpreter via new Function(), eliminando branches de hooks/middleware ausentes em compile-time. O consumer não precisa se preocupar — "auto" é o default e promove transparentemente.