import * as _walkeros_core from '@walkeros/core'; import { Collector, WalkerOS, Elb, Mapping, Destination, On, StepKind, Logger, Context as Context$1, BreakerState, Ingest, Source, Transformer, Simulation, CompiledCache, Store } from '@walkeros/core'; interface RunState { consent?: WalkerOS.Consent; user?: WalkerOS.User; globals?: WalkerOS.Properties; custom?: WalkerOS.Properties; } type HandleCommandFn = (collector: T, action: string, data?: unknown, options?: unknown) => Promise; type CommandTypes = 'Action' | 'Actions' | 'Config' | 'Consent' | 'Context' | 'Custom' | 'Destination' | 'Elb' | 'Globals' | 'Hook' | 'Init' | 'Link' | 'On' | 'Prefix' | 'Ready' | 'Run' | 'Scoped' | 'Session' | 'Shutdown' | 'User' | 'Walker'; type StorageType = 'cookie' | 'local' | 'session'; interface CreateCollector { collector: Collector.Instance; elb: WalkerOS.Elb; } interface StartFlow { collector: Collector.Instance; elb: ElbPush; } interface Settings { scripts?: string[]; init?: string; on?: string; push?: string; pushBatch?: string; } interface CodeMapping extends Mapping.Rule { push?: string; pushBatch?: string; } type Types = Destination.Types; type Config = Destination.Config; type Context = Destination.Context; type PushContext = Destination.PushContext; type PushBatchContext = Destination.PushBatchContext; type InitFn = (context: Context) => void; type OnFn = (type: On.Types, context: Context) => void; type PushFn = (event: WalkerOS.Event, context: PushContext) => void; type PushBatchFn = (batch: Destination.Batch, context: PushBatchContext) => WalkerOS.PromiseOrValue; type code_CodeMapping = CodeMapping; type code_Config = Config; type code_Context = Context; type code_InitFn = InitFn; type code_OnFn = OnFn; type code_PushBatchContext = PushBatchContext; type code_PushBatchFn = PushBatchFn; type code_PushContext = PushContext; type code_PushFn = PushFn; type code_Settings = Settings; type code_Types = Types; declare namespace code { export type { code_CodeMapping as CodeMapping, code_Config as Config, code_Context as Context, code_InitFn as InitFn, code_OnFn as OnFn, code_PushBatchContext as PushBatchContext, code_PushBatchFn as PushBatchFn, code_PushContext as PushContext, code_PushFn as PushFn, code_Settings as Settings, code_Types as Types }; } declare const Commands: Record; declare const Const: { Commands: Record; Utils: { Storage: { [key: string]: StorageType; }; }; }; /** * Processes consent data: coerces to boolean, updates collector state. * Does NOT notify or process queues — caller handles that. */ declare function processConsent(collector: Collector.Instance, data: WalkerOS.Consent): { update: WalkerOS.Consent; }; declare function startFlow(initConfig?: Collector.InitConfig): Promise>; /** * Creates the push function for the collector. * Handles source mapping, event creation, and routing to destinations. * * @param collector - The walkerOS collector instance * @param prepareEvent - Function to enrich partial events * @returns The push function */ declare function createPush(collector: T, prepareEvent: (event: WalkerOS.DeepPartialEvent) => WalkerOS.PartialEvent): Collector.PushFn; /** * Maximum number of failed-push entries retained per destination DLQ before * FIFO drop-oldest. Mirrored by `Destination.Config.dlqMax`. */ declare const DEFAULT_DLQ_MAX = 100; /** * Ensure a per-destination status entry exists and return it. */ declare function ensureDestStatus(collector: Collector.Instance, destId: string): Collector.DestinationStatus; /** * Bump a drop counter under `status.dropped[stepId][buffer]`. Lazily * creates the per-step entry; returns the new counter value so callers * can pass it straight into the warn-once log payload. */ declare function bumpDropped(status: Collector.Status, id: string, buffer: 'queue' | 'dlq', n: number): number; /** * Builds the step-general `reportError` callback for one step's context. * * This is the runtime behind `Context.Base.reportError`. It is captured ONCE * when a step's context is built and closes over `(collector, kind, id, * logger, destination)`, so a long-lived connection that holds the reference * keeps a valid callback for its whole lifetime — it is never rebuilt per * push. It runs on a detached emitter tick, so every path is internally * try/catch-guarded; a throw inside it would reintroduce the very * uncaughtException it exists to contain. * * - orphan (`reportError(err)`): bump `status.connectionErrors[stepId]` and * `logger.error`. Does NOT bump `failed` (no event lost at this instant; * counting it against `failed` would double-count the next push that hits * the broken writer and gets DLQ'd). * - event-bearing (`reportError(err, event)`): route the event through the * same DLQ + failure accounting an in-band push failure uses (for a * destination). A step kind without a DLQ (or a destination not passed) * still gets `failed`-counted and logged, never silently dropped. * * The with-event path deliberately funnels through the normal failure * accounting so that when circuit-breaker accounting is later attached to that * path, `reportError(err, event)` picks it up with no further wiring here. */ declare function buildReportError(collector: Collector.Instance, kind: Exclude, id: string, logger: Logger.Instance, destination?: Destination.Instance): NonNullable; /** * Step-general circuit breaker. * * State lives in `collector.status.breakers`, keyed by `stepId()` so the * breaker is step-agnostic (destinations are the primary use today). All sites * — the skip gate, the per-event failure/success accounting, the batch flush — * drive their state changes through this one module so the gate and the * accounting can never disagree about a step's health. * * The breaker is presence-gated: a step with no `breaker` config never trips * (the caller skips this module entirely when {@link resolveBreakerConfig} * returns `undefined`). * * Time is read through an injectable `now()` so open→half-open transitions are * deterministic in tests without fake timers (mirrors `ErrorRing` in the cli). */ declare const DEFAULT_BREAKER_THRESHOLD = 5; declare const DEFAULT_BREAKER_COOLDOWN_MS = 30000; /** Resolved, presence-checked breaker tuning for one step. */ interface BreakerConfig { threshold: number; cooldown: number; } /** * The kind of transport outcome a step site reports. `transport-failure` * counts toward opening; `success` resets and closes; `partial` is a * deliberate no-op (row-level batch failures must not trip a healthy * destination). */ type StepOutcome = 'transport-failure' | 'success' | 'partial'; /** * Resolve a destination's `breaker` config into tuned values, or `undefined` * when no breaker is configured (presence-gating: the breaker stays inert). * A bare number is the threshold. */ declare function resolveBreakerConfig(breaker: Destination.Config['breaker']): BreakerConfig | undefined; /** * Predicate exposed for the BigQuery self-heal re-open (Task 4): true when a * probe would be permitted at `now` — the breaker is closed, half-open, or * open with its cooldown elapsed. Task 4 gates its re-open on this. */ declare function isBreakerProbePermitted(breaker: BreakerState | undefined, now: number): boolean; /** * Adds a new destination to the collector. * * @param collector - The walkerOS collector instance. * @param data - The destination's init data. * @returns The result of the push operation. */ declare function addDestination(collector: Collector.Instance, data: Destination.Init): Promise; /** * Pushes an event to all or a subset of destinations. * * @param collector - The walkerOS collector instance. * @param event - The event to push. * @param meta - Optional metadata with id and ingest. * @param destinations - The destinations to push to. * @returns The result of the push operation. */ declare function pushToDestinations(collector: Collector.Instance, event?: WalkerOS.Event, meta?: { id?: string; ingest?: Ingest; respond?: _walkeros_core.RespondFn; }, destinations?: Collector.Destinations): Promise; declare function destinationInit(collector: Collector.Instance, destination: Destination, destId: string, allowed?: boolean): Promise; /** * Pushes an event to a single destination. * Handles mapping, batching, and consent checks. * * @template Destination * @param collector - The walkerOS collector instance. * @param destination - The destination to push to. * @param destId - The destination ID. * @param event - The event to push. * @param ingest - Mutable ingest context flowing through the pipeline. * @returns Whether the event was pushed successfully. */ declare function destinationPush(collector: Collector.Instance, destination: Destination, destId: string, event: WalkerOS.Event, ingest?: Ingest, respond?: _walkeros_core.RespondFn): Promise; /** * Creates a standardized result object for push operations. * * @param partialResult - A partial result to merge with the default result. * @returns The push result. */ declare function createPushResult(partialResult?: Partial): Elb.PushResult; /** * Register a single destination from its init definition. * Merges code config, user config, and chain config. * Used by initDestinations and activatePending. */ declare function registerDestination(def: Destination.Init): Destination.Instance; /** * Initializes a map of destinations using ONLY the unified code/config/env pattern. * Does NOT call destination.init() - that happens later during push with proper consent checks. * * @param destinations - The destinations to initialize. * @param collector - The collector instance for destination init context. * @returns The initialized destinations. */ declare function initDestinations(collector: Collector.Instance, destinations?: Destination.InitDestinations): Promise; /** * Merges destination environment with config environment * Config env takes precedence over destination env for overrides */ declare function mergeEnvironments(destinationEnv?: Destination.Env, configEnv?: Destination.Env): Destination.Env; /** * Handles common commands. * * @param collector The walkerOS collector instance. * @param action The action to handle. * @param data The data to handle. * @returns A promise that resolves with the push result or undefined. */ declare function commonHandleCommand(collector: Collector.Instance, action: string, data?: unknown): Promise; /** * Builds the partial event handed to `createEvent`, injecting the default * `timing` (elapsed since the collector started) and the collector `source` * meta. Event-provided values override the defaults. * * @param collector The walkerOS collector instance. * @param event The incoming partial event. * @returns The partial event with defaults applied. */ declare function prepareEvent(collector: Collector.Instance, event: WalkerOS.DeepPartialEvent): WalkerOS.PartialEvent; /** * Creates a full event from a partial event. * * @param collector The walkerOS collector instance. * @param partialEvent The partial event to transform. * @returns The full event. */ declare function createEvent(collector: Collector.Instance, partialEvent: WalkerOS.PartialEvent): WalkerOS.Event; /** * Enriches a partial event into a full event by applying the collector defaults * (`prepareEvent`) and then building the complete event (`createEvent`). This is * the single enrichment entry point shared by the production push path and * simulation, so both produce identical events. * * @param collector The walkerOS collector instance. * @param event The incoming partial event. * @returns The full event. */ declare function enrichEvent(collector: Collector.Instance, event: WalkerOS.DeepPartialEvent): WalkerOS.Event; /** * Runs the collector by setting it to allowed state and processing queued events. * * @param collector The walkerOS collector instance. * @param state Optional state to merge with the collector (user, globals, consent, custom). * @returns A promise that resolves with the push result. */ declare function runCollector(collector: Collector.Instance, state?: RunState): Promise; /** * State-delivery event types: the reactive-state commands that bump * `collector.stateVersion` (see handle.ts). These are the only deliveries * subject to the per-subscriber high-water-mark + `allowed` gate. Lifecycle * types (ready/run/session) and non-reactive config keep their own gating * (onReady/onRun check `allowed`, onSession checks `session`). */ declare function isStateDelivery(type: On.Types): boolean; /** * Is a recorded state CELL present (non-empty)? The single source of truth for * "cell X has a value", shared by `isRequireSatisfied` (require gating) and * `redeliverStateAtRun` (run-barrier re-delivery) so the presence semantics * never drift between the two. PRESENCE, not grant: a denied consent * (`{marketing:false}`) counts as present. Non-cell types return `false` here; * their satisfaction (session/run/ready/arbitrary) is handled by the callers. * * Note: `globals` is seeded from `config.globalsStatic` at construction, so it * reads present whenever a static global exists, before any `command('globals')` * fires. That is intentional and presence-based. */ declare function isStatePresent(collector: Collector.Instance, type: On.Types): boolean; /** * Predicate: is a `require` entry satisfied by the collector's CURRENT recorded * state? This is the level-not-edge core of order-independent activation: a * step's gate is checked against the present state, not against whether the * required type fired before or after the step registered. * * Cell-backed types defer to `isStatePresent` (presence, not grant — the * destination send-gate `getGrantedConsent` remains a separate concern). * `run`/`ready` map to `allowed`. Any other type (including `session`) is * satisfied once it has been broadcast (recorded in `seenEvents`), which also * recovers a broadcast that fired before the requiring step registered. * * `session` deliberately uses the `seenEvents` path, not a cell check: * `collector.session` is vestigial (never written), so gating on it would park * a `require:["session"]` step forever. The session source signals via * `command('session', …)`, which records `session` in `seenEvents`, so this * keeps `session` order-independent like every other type. */ declare function isRequireSatisfied(collector: Collector.Instance, type: On.Types): boolean; /** * Advance a subscriber's mark for a cell to that cell's current version after * an invocation. Only the delivered cell's mark moves; other cells stay owed. */ declare function setMark(collector: Collector.Instance, subscriber: object, type: On.Types): void; /** * A subscriber is invoked for a state delivery iff that CELL has advanced past * its per-cell mark AND the collector is allowed. While `!allowed`, deliveries * are deferred (not fired, mark not advanced) so the subscriber stays "owed". */ declare function shouldDeliver(collector: Collector.Instance, subscriber: object, type: On.Types): boolean; /** * Open the cascade-tracking structure for the OUTERMOST top-level state command * and return a teardown that clears it. Nested commands emitted by reacting * callbacks find `collector.cascade` already set and reuse it (teardown is a * no-op for them), so the counters are scoped to the originating command and * reset when it returns. Re-entrancy is detected by the presence of * `collector.cascade`. * * Assumes top-level state commands run serially on a given collector; * concurrent overlapping state commands on one shared collector are not * supported (web is serial; the server per-request path is event push, not * state commands). */ declare function enterCascade(collector: Collector.Instance): () => void; /** * Registers a callback for a specific event type. * * @param collector The walkerOS collector instance. * @param type The type of the event to listen for. * @param option The callback function or an array of callback functions. */ declare function on(collector: Collector.Instance, type: On.Types, option: WalkerOS.SingleOrArray): Promise; /** * Calls a destination's on() handler with proper context. * Used by both onApply() for immediate calls and destinationInit() for flushing queued events. */ declare function callDestinationOn(collector: Collector.Instance, destination: Destination.Instance, destId: string, type: On.Types, data: unknown): void; /** * Fire a set of registered `on` callbacks against current collector state. * * Used by both `on()` (when registering a new callback, to fire it against * current state) and `onApply()` (when dispatching a state-change command to * every registered callback of that type). Separating this from `onApply` * ensures `on()` does NOT trigger `onApply`'s source/destination broadcast, * which would cause infinite recursion if a source's `on` handler registers * another callback of the same type. */ declare function fireCallbacks(collector: Collector.Instance, type: On.Types, options: Array, config?: unknown): void; /** * Run-barrier re-delivery. Called once from `runCollector` after the collector * becomes `allowed` and the RunState merge has bumped `stateVersion` for any * merged cells. Re-broadcasts each non-empty recorded state cell to its OWED * subscribers (mark < stateVersion) exactly once, so reactions deferred while * `!allowed` now emit into the open, consent-gated pipeline. * * Narrow path: it fires `collector.on` rules/fns via `fireCallbacks` and the * gated `source.on` loop via `deliverStateToSource`. It deliberately skips the * `require`-decrement and `queueOn`-flush machinery in `onApply` (those are * live-command concerns). Exactly-once is free from the `shouldDeliver` gate: * already-delivered subscribers (mark == stateVersion) are skipped. */ declare function redeliverStateAtRun(collector: Collector.Instance): Promise; /** * Applies all registered callbacks for a specific event type. * * @param collector The walkerOS collector instance. * @param type The type of the event to apply the callbacks for. * @param options The options for the callbacks. * @param config The consent configuration. */ declare function onApply(collector: Collector.Instance, type: On.Types, options?: Array, config?: unknown): Promise; /** * Flush a source's queueOn buffer. Called when the source becomes "started" * (config.init === true AND config.require is empty/absent). Idempotent: * the buffer is cleared before iteration, so re-entry from within an `on` * handler does not re-fire the same items. * * A throw inside `source.on` is treated as a pipeline failure: log via the * scoped 'source' logger and increment `status.failed`. The flush itself * is walkerOS-orchestrated startup; the throw represents the source's * inability to consume a buffered state-change event. * * State-delivery entries (consent/user/globals/custom) are gated through the * same per-source high-water mark as the direct `onApply` broadcast: while * `!allowed` they defer (not invoked, mark not advanced — the source stays * "owed" for the run-barrier re-delivery), and an allowed delivery advances * the source mark so a later broadcast at the same version does not double * deliver. Lifecycle/arbitrary entries (ready/run/session/config) flush with * their unchanged behavior. */ declare function flushSourceQueueOn(collector: Collector.Instance, source: Source.Instance, sourceId?: string): Promise; /** * A source is "started" — eligible to receive on() events directly — when * its init has run and any require gate is satisfied. */ declare function isSourceStarted(source: Source.Instance): boolean; /** * Initialize a single source. Extracted from the initSources loop body * so it can be reused by the pending-source activator. */ declare function initSource(collector: Collector.Instance, sourceId: string, sourceDefinition: Source.InitSource): Promise; /** * Initialize sources. Sources with `require` are deferred to collector.pending. */ declare function initSources(collector: Collector.Instance, sources?: Source.InitSources): Promise; /** * Extracts transformer next configuration for chain walking. * Maps transformer instances to their config.next values. * * This is the single source of truth for extracting chain links. * Used by both source.ts (pre-collector chains) and destination.ts (post-collector chains). * * @param transformers - Map of transformer instances * @returns Map of transformer IDs to their next configuration */ declare function extractTransformerNextMap(transformers: Transformer.Transformers): Record; /** * Walks a transformer chain starting from a given transformer ID. * Returns ordered array of transformer IDs in the chain. * * Used for on-demand chain resolution: * - Called from destination.ts with destination.config.before * - Called from source.ts with source.config.next * * @param startId - First transformer in chain, or explicit array of transformer IDs * @param transformers - Available transformer configs with optional `next` field * @returns Ordered array of transformer IDs to execute * * @example * // Single transformer * walkChain('redact', { redact: {} }) // ['redact'] * * @example * // Chain via next * walkChain('a', { a: { next: 'b' }, b: { next: 'c' }, c: {} }) // ['a', 'b', 'c'] * * @example * // Explicit array * walkChain(['x', 'y'], {}) // ['x', 'y'] */ declare function walkChain(startId: string | string[] | undefined, transformers?: Record): string[]; /** * Initializes a transformer if it hasn't been initialized yet. * Called lazily before first push. * * @param collector - The collector instance * @param transformer - The transformer to initialize * @param transformerId - The transformer ID * @returns Whether initialization succeeded */ declare function transformerInit(collector: Collector.Instance, transformer: Transformer.Instance, transformerId: string): Promise; /** * Pushes an event through a single transformer. * * @param collector - The collector instance * @param transformer - The transformer to push to * @param transformerId - The transformer ID * @param event - The event to process * @param ingest - Mutable ingest context flowing through the pipeline * @returns The processed event, void for passthrough, or false to stop chain */ declare function transformerPush(collector: Collector.Instance, transformer: Transformer.Instance, transformerId: string, event: WalkerOS.DeepPartialEvent, ingest?: Ingest, respond?: _walkeros_core.RespondFn): Promise; /** * Runs an event through a chain of transformers. * * @param collector - The collector instance with transformers * @param transformers - Map of transformer instances * @param chain - Ordered array of transformer IDs to execute * @param event - The event to process * @param ingest - Mutable ingest context flowing through the pipeline * @returns The processed event or null if chain was stopped */ declare function runTransformerChain(collector: Collector.Instance, transformers: Transformer.Transformers, chain: string[], event: WalkerOS.DeepPartialEvent, ingest?: Ingest, respond?: _walkeros_core.RespondFn, chainContext?: string): Promise; interface WrapResult { /** Env with tracked paths wrapped by recording functions */ wrappedEnv: Record; /** Mutable array — calls are pushed here during step execution */ calls: Simulation.Call[]; } /** * Wrap tracked paths in a destination env with recording wrappers. * * The env object must include a `simulation: string[]` declaring which * dot-paths to intercept. Returns a cloned env (without `simulation`) * where those paths record every call into the `calls` array. */ declare function wrapEnv(env: Record & { simulation: string[]; }): WrapResult; /** * Returns the store for a compiled cache config. * Uses the explicit store reference if provided, otherwise falls back to the * collector's default __cache store. */ declare function getCacheStore(compiled: CompiledCache, collector: Collector.Instance): Store.Instance | undefined; export { type BreakerConfig, code as Code, type CommandTypes, Commands, Const, type CreateCollector, DEFAULT_BREAKER_COOLDOWN_MS, DEFAULT_BREAKER_THRESHOLD, DEFAULT_DLQ_MAX, type HandleCommandFn, type RunState, type StartFlow, type StepOutcome, type StorageType, addDestination, buildReportError, bumpDropped, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, enrichEvent, ensureDestStatus, enterCascade, extractTransformerNextMap, fireCallbacks, flushSourceQueueOn, getCacheStore, initDestinations, initSource, initSources, isBreakerProbePermitted, isRequireSatisfied, isSourceStarted, isStateDelivery, isStatePresent, mergeEnvironments, on, onApply, prepareEvent, processConsent, pushToDestinations, redeliverStateAtRun, registerDestination, resolveBreakerConfig, runCollector, runTransformerChain, setMark, shouldDeliver, startFlow, transformerInit, transformerPush, walkChain, wrapEnv };