import { m as ModulesMap, n as CreateSystemOptionsNamed, q as Requirement, M as ModuleSchema, k as CreateSystemOptionsSingle, N as NamespacedSystem, R as RequirementWithId, l as SingleModuleSystem, Z as ObservationEvent, ac as SystemInspection } from './plugins-BIzXaYbg.cjs';

/**
 * Flush all pending microtasks by awaiting multiple rounds of `Promise.resolve()`.
 *
 * Call this after advancing fake timers to ensure all Promise callbacks
 * (including nested microtasks) have run before making assertions.
 *
 * @returns A promise that resolves after all pending microtasks have been drained.
 *
 * @example
 * ```typescript
 * vi.useFakeTimers();
 * system.start();
 * system.facts.userId = 1; // Triggers constraint
 * await flushMicrotasks(); // Let reconciliation start
 * vi.advanceTimersByTime(100); // Advance resolver delay
 * await flushMicrotasks(); // Let resolver complete
 * ```
 *
 * @public
 */
declare function flushMicrotasks(): Promise<void>;
/**
 * Drain a full constraint → resolver → effect pipeline, including macrotasks.
 *
 * Performs a 3-pass / 2-`setTimeout(0)` sequence that empties microtask queues
 * twice across two macrotask boundaries. Use this when a single
 * {@link flushMicrotasks} pass is not enough to reach quiescence — typically
 * when constraints schedule resolvers that schedule further constraints, or
 * when test code uses `queueMicrotask` / `Promise.resolve()` chains that
 * cross a `setTimeout(..., 0)` boundary inside the engine.
 *
 * @remarks
 * **When to use which:**
 * - {@link flushMicrotasks}: Fast path for a single microtask drain (e.g.
 *   waiting for one Promise chain to settle).
 * - `flushAsync`: Heavier pass for full constraint+resolver pipelines where
 *   reconciliation may emit follow-up requirements, retries, or batched
 *   resolver flushes that span a macrotask.
 *
 * The exact shape (3 microtask rounds → setTimeout 0 → 3 microtask rounds →
 * setTimeout 0 → 3 microtask rounds) was extracted from a helper duplicated
 * across 50+ migration tests; centralizing it here keeps the drain semantics
 * consistent and lets the engine evolve without fan-out edits.
 *
 * @returns A promise that resolves after the full drain completes.
 *
 * @example
 * ```typescript
 * system.facts.userId = 1; // triggers constraint → resolver chain
 * await flushAsync();      // drains constraint + resolver + follow-up effects
 * expect(system.facts.user).toEqual({ id: 1, ... });
 * ```
 *
 * @public
 */
declare function flushAsync(): Promise<void>;
/**
 * Wait for the system to settle with fake timers enabled.
 *
 * Repeatedly advances fake timers in discrete steps while flushing microtasks,
 * until no resolvers remain inflight or the time budget is exhausted.
 *
 * @param system - The Directive system to wait on (must expose {@link SystemInspection} via `inspect()`).
 * @param advanceTime - Function that advances fake timers by a given number of milliseconds (e.g., `vi.advanceTimersByTime`).
 * @param options - Configuration for total time budget, step size, and iteration limit.
 * @returns A promise that resolves once the system is idle.
 *
 * @throws Error if the system does not settle within the configured time budget.
 *
 * @example
 * ```typescript
 * vi.useFakeTimers();
 * const system = createSystem({ modules: [myModule] });
 * system.start();
 * system.dispatch({ type: "triggerAsync" });
 *
 * await settleWithFakeTimers(system, vi.advanceTimersByTime, {
 *   totalTime: 1000,
 *   stepSize: 10,
 * });
 *
 * expect(system.facts.result).toBe("done");
 * ```
 *
 * @public
 */
declare function settleWithFakeTimers(system: {
    inspect(): SystemInspection;
}, advanceTime: (ms: number) => void, options?: {
    /** Total time to advance (default: 5000ms) */
    totalTime?: number;
    /** Time to advance each step (default: 10ms) */
    stepSize?: number;
    /** Maximum iterations before giving up (default: 1000) */
    maxIterations?: number;
}): Promise<void>;
/**
 * Standalone fake timer controller for tests that do not use Vitest/Jest fake timers.
 *
 * @remarks
 * For most tests, prefer Vitest's `vi.useFakeTimers()` paired with
 * {@link settleWithFakeTimers} for better integration. Use this interface
 * only when you need a lightweight, framework-independent timer mock.
 *
 * @public
 */
interface FakeTimers {
    /** Advance time by a number of milliseconds, firing any timers that fall within the window. */
    advance(ms: number): Promise<void>;
    /** Advance to the next scheduled timer and fire its callback. */
    next(): Promise<void>;
    /** Run all pending timers in chronological order. */
    runAll(): Promise<void>;
    /** Get the current fake time in milliseconds. */
    now(): number;
    /** Reset the clock to time 0 and discard all scheduled timers. */
    reset(): void;
}
/**
 * Create standalone fake timers for testing without a framework timer mock.
 *
 * @remarks
 * For most tests, prefer Vitest's `vi.useFakeTimers()` paired with
 * {@link settleWithFakeTimers}. This factory is useful when you need an
 * isolated timer that does not interfere with global timer state.
 *
 * @returns A {@link FakeTimers} controller with `advance`, `next`, `runAll`, `now`, and `reset` methods.
 *
 * @example
 * ```typescript
 * const timers = createFakeTimers();
 * // schedule work, then:
 * await timers.advance(500);
 * expect(timers.now()).toBe(500);
 * ```
 *
 * @public
 */
declare function createFakeTimers(): FakeTimers;
/**
 * Context passed to mock resolver resolve functions.
 *
 * @public
 */
interface MockResolverContext {
    /** Facts object (use type assertion for specific facts) */
    facts: any;
    /** Abort signal for cancellation */
    signal: AbortSignal;
}
/**
 * Configuration for a simple mock resolver created via {@link createMockResolver}.
 *
 * @typeParam R - The requirement type this resolver handles.
 *
 * @public
 */
interface MockResolverOptions<R extends Requirement = Requirement> {
    /** Predicate to check if this resolver handles a given requirement. */
    requirement?: (req: Requirement) => req is R;
    /** Mock implementation invoked when the resolver runs. */
    resolve?: (req: R, ctx: MockResolverContext) => void | Promise<void>;
    /** Artificial delay in milliseconds before the resolver completes. */
    delay?: number;
    /** Error (or message string) to throw, simulating a resolver failure. */
    error?: Error | string;
    /** Array that receives every requirement passed to this resolver. */
    calls?: R[];
}
/** Internal resolver definition type for mock resolvers */
interface MockResolverDef {
    requirement: (req: Requirement) => boolean;
    resolve: (req: Requirement, ctx: MockResolverContext) => Promise<void>;
}
/**
 * Create a simple mock resolver that matches requirements by type and optionally
 * records calls, injects delays, or throws errors.
 *
 * @param typeOrOptions - A requirement type string, or a full {@link MockResolverOptions} object.
 * @returns A resolver definition that can be spread into a module's `resolvers` map.
 *
 * @example
 * ```typescript
 * const calls: Requirement[] = [];
 * const mock = createMockResolver({ requirement: (r): r is MyReq => r.type === "LOAD", calls });
 * ```
 *
 * @public
 */
declare function createMockResolver<R extends Requirement = Requirement>(typeOrOptions: string | MockResolverOptions<R>): MockResolverDef;
/**
 * A mock resolver that captures requirements for manual resolution.
 *
 * @remarks
 * Use this when you need fine-grained control over when and how requirements
 * resolve. Requirements are queued in `pending` and stay unresolved until you
 * explicitly call `resolve()` or `reject()`.
 *
 * @typeParam R - The requirement type this resolver handles.
 *
 * @public
 */
interface MockResolver<R extends Requirement = Requirement> {
    /** All requirements received by this resolver */
    readonly calls: R[];
    /** Pending requirements waiting to be resolved/rejected */
    readonly pending: Array<{
        requirement: R;
        resolve: (result?: unknown) => void;
        reject: (error: Error) => void;
    }>;
    /** Resolve the next pending requirement */
    resolve(result?: unknown): void;
    /** Reject the next pending requirement */
    reject(error: Error): void;
    /** Resolve all pending requirements */
    resolveAll(result?: unknown): void;
    /** Reject all pending requirements */
    rejectAll(error: Error): void;
    /** Clear call history and pending queue */
    reset(): void;
}
/**
 * Create a mock resolver that captures requirements instead of resolving them,
 * giving you manual control over when and how each requirement completes.
 *
 * @param _requirementType - The requirement `type` string this mock handles (used for documentation; matching is done by the test harness).
 * @returns A {@link MockResolver} with a `handler` function suitable for passing to {@link createTestSystem} mocks.
 *
 * @example
 * ```typescript
 * const fetchMock = mockResolver<{ type: "FETCH_USER"; id: string }>("FETCH_USER");
 *
 * const system = createTestSystem({
 *   modules: [userModule],
 *   mocks: {
 *     resolvers: {
 *       FETCH_USER: { resolve: fetchMock.handler },
 *     },
 *   },
 * });
 *
 * system.facts.userId = "123";
 * await flushMicrotasks();
 *
 * // Requirement is pending
 * expect(fetchMock.calls).toHaveLength(1);
 * expect(fetchMock.calls[0].id).toBe("123");
 *
 * // Manually resolve it
 * fetchMock.resolve({ name: "John" });
 * await flushMicrotasks();
 *
 * expect(system.facts.user).toEqual({ name: "John" });
 * ```
 *
 * @public
 */
declare function mockResolver<R extends Requirement = Requirement>(_requirementType: string): MockResolver<R> & {
    /** Handler that can be passed to createTestSystem mocks */
    handler: (req: Requirement, ctx: MockResolverContext) => Promise<void>;
};
/**
 * Record of a single fact change captured by the test tracking plugin.
 *
 * @public
 */
interface FactChangeRecord {
    /** The fact key that changed (without namespace prefix for namespaced systems) */
    key: string;
    /** The full key including namespace prefix (e.g., "test::value") */
    fullKey: string;
    /** The namespace (e.g., "test") - undefined for single-module systems */
    namespace?: string;
    /** The previous value */
    previousValue: unknown;
    /** The new value */
    newValue: unknown;
    /** Timestamp of the change */
    timestamp: number;
}
/** Common testing utilities shared by both single-module and namespaced test systems. */
interface TestSystemBase {
    /**
     * Wait for all pending operations to complete.
     * @param maxWait - Maximum time to wait in ms (default: 5000)
     * @throws Error if timeout is exceeded with resolvers still inflight
     */
    waitForIdle(maxWait?: number): Promise<void>;
    /** Get the history of dispatched events */
    eventHistory: Array<{
        type: string;
        [key: string]: unknown;
    }>;
    /** Get resolver call history */
    resolverCalls: Map<string, Requirement[]>;
    /**
     * Get all requirements that have been generated (both resolved and pending).
     * Unlike `inspect().unmet`, this includes requirements that have already been handled.
     */
    readonly allRequirements: RequirementWithId[];
    /**
     * Get all fact changes since system start or last reset.
     */
    getFactsHistory(): FactChangeRecord[];
    /**
     * Reset the facts history tracking.
     */
    resetFactsHistory(): void;
    /** Assert that a requirement was created */
    assertRequirement(type: string): void;
    /** Assert that a resolver was called */
    assertResolverCalled(type: string, times?: number): void;
    /**
     * Assert that a fact was set to a specific value.
     */
    assertFactSet(key: string, value?: unknown): void;
    /**
     * Assert the number of times a fact was changed.
     */
    assertFactChanges(key: string, times: number): void;
}
/**
 * A single-module Directive system augmented with testing utilities.
 *
 * @remarks
 * Extends {@link SingleModuleSystem} with event/resolver/fact tracking, idle
 * waiting, and assertion helpers. Created via {@link createTestSystem}.
 *
 * @typeParam S - The module schema.
 *
 * @public
 */
interface TestSystemSingle<S extends ModuleSchema> extends SingleModuleSystem<S>, TestSystemBase {
}
/**
 * A Directive system augmented with testing utilities.
 *
 * @remarks
 * Extends {@link NamespacedSystem} with event/resolver/fact tracking, idle
 * waiting, and assertion helpers. Created via {@link createTestSystem}.
 *
 * @typeParam Modules - The modules map that defines the system's schema.
 *
 * @public
 */
interface TestSystem<Modules extends ModulesMap> extends NamespacedSystem<Modules>, TestSystemBase {
}
/**
 * Options for {@link createTestSystem}, extending the standard system options
 * with mock resolver injection and automatic tracking.
 *
 * @typeParam Modules - The modules map that defines the system's schema.
 *
 * @public
 */
interface CreateTestSystemOptions<Modules extends ModulesMap> extends Omit<CreateSystemOptionsNamed<Modules>, "plugins"> {
    /** Mock resolvers by type */
    mocks?: {
        resolvers?: Record<string, MockResolverOptions>;
    };
    /** Additional plugins (tracking plugin is added automatically) */
    plugins?: any[];
}
/**
 * Options for {@link createTestSystem} with a single module (no namespacing).
 *
 * @typeParam S - The module schema.
 *
 * @public
 */
interface CreateTestSystemOptionsSingle<S extends ModuleSchema> extends Omit<CreateSystemOptionsSingle<S>, "plugins"> {
    /** Mock resolvers by type */
    mocks?: {
        resolvers?: Record<string, MockResolverOptions>;
    };
    /** Additional plugins (tracking plugin is added automatically) */
    plugins?: any[];
}
/**
 * Create a Directive system instrumented for testing.
 *
 * Wraps {@link createSystem} with an automatic tracking plugin that records
 * dispatched events, resolver calls, fact changes, and generated requirements.
 * Mock resolvers can be injected via `options.mocks.resolvers` to replace
 * real resolvers by requirement type.
 *
 * @param options - System configuration with optional mock resolvers and additional plugins.
 * @returns A {@link TestSystem} or {@link TestSystemSingle} with assertion helpers, idle waiting, and history tracking.
 *
 * @example
 * ```typescript
 * // Namespaced (multiple modules)
 * const system = createTestSystem({
 *   modules: { counter: counterModule },
 *   mocks: { resolvers: { INCREMENT: { resolve: (req, context) => { context.facts.count++; } } } },
 * });
 *
 * // Single module
 * const system = createTestSystem({
 *   module: counterModule,
 * });
 * system.start();
 * ```
 *
 * @public
 */
declare function createTestSystem<S extends ModuleSchema>(options: CreateTestSystemOptionsSingle<S>): TestSystemSingle<S>;
declare function createTestSystem<Modules extends ModulesMap>(options: CreateTestSystemOptions<Modules>): TestSystem<Modules>;
/**
 * Assert that a definition was dynamically registered on the system.
 *
 * @param system - The Directive system to check.
 * @param type - The definition type: "constraint", "resolver", "derivation", or "effect".
 * @param id - The definition ID.
 * @throws Error if the definition is not dynamic.
 *
 * @example
 * ```typescript
 * system.constraints.register("myRule", { when: () => true, require: { type: "DO" } });
 * assertDynamic(system, "constraint", "myRule"); // passes
 * assertDynamic(system, "constraint", "staticRule"); // throws
 * ```
 *
 * @public
 */
declare function assertDynamic(system: {
    constraints: {
        isDynamic(id: string): boolean;
    };
    effects: {
        isDynamic(id: string): boolean;
    };
    resolvers: {
        isDynamic(id: string): boolean;
    };
    derive: {
        isDynamic(id: string): boolean;
    };
}, type: "constraint" | "resolver" | "derivation" | "effect", id: string): void;
/**
 * Assert that a definition is NOT dynamically registered (i.e., is static or does not exist).
 *
 * @param system - The Directive system to check.
 * @param type - The definition type: "constraint", "resolver", "derivation", or "effect".
 * @param id - The definition ID.
 * @throws Error if the definition is dynamic.
 *
 * @example
 * ```typescript
 * assertNotDynamic(system, "constraint", "staticRule"); // passes
 * system.constraints.register("myRule", def);
 * assertNotDynamic(system, "constraint", "myRule"); // throws
 * ```
 *
 * @public
 */
declare function assertNotDynamic(system: {
    constraints: {
        isDynamic(id: string): boolean;
    };
    effects: {
        isDynamic(id: string): boolean;
    };
    resolvers: {
        isDynamic(id: string): boolean;
    };
    derive: {
        isDynamic(id: string): boolean;
    };
}, type: "constraint" | "resolver" | "derivation" | "effect", id: string): void;
/** Coverage report for a Directive system. */
interface CoverageReport {
    /** Constraints that evaluated to true at least once. */
    constraintsHit: Set<string>;
    /** Constraints that never evaluated to true. */
    constraintsMissed: Set<string>;
    /** Resolvers that started at least once. */
    resolversRun: Set<string>;
    /** Resolvers that never started. */
    resolversMissed: Set<string>;
    /** Effects that ran at least once. */
    effectsRun: Set<string>;
    /** Derivations that recomputed at least once. */
    derivationsComputed: Set<string>;
    /** Coverage percentage (constraintsHit / total constraints). */
    constraintCoverage: number;
    /** Coverage percentage (resolversRun / total resolvers). */
    resolverCoverage: number;
    /** Coverage percentage (effectsRun / total effects). */
    effectCoverage: number;
    /** Coverage percentage (derivationsComputed / total derivations). */
    derivationCoverage: number;
}
/**
 * Track which constraints, resolvers, effects, and derivations are exercised
 * during a test scenario. Returns a coverage report after the scenario runs.
 *
 * @example
 * ```typescript
 * const { run, report } = createCoverageTracker(system);
 *
 * await run(async () => {
 *   system.facts.userId = 123;
 *   await system.settle();
 *   system.facts.userId = 0;
 *   await system.settle();
 * });
 *
 * const coverage = report();
 * expect(coverage.constraintCoverage).toBe(1); // All constraints hit
 * expect(coverage.constraintsMissed.size).toBe(0);
 * ```
 */
declare function createCoverageTracker(system: SingleModuleSystem<any> | NamespacedSystem<any>): {
    /** Run a test scenario while tracking coverage. */
    run: (scenario: () => Promise<void> | void) => Promise<void>;
    /** Get the coverage report. */
    report: () => CoverageReport;
};
/**
 * Create a test observer that collects all observation events.
 * Useful for assertion-based testing of system behavior.
 *
 * @example
 * ```typescript
 * const observer = createTestObserver(system);
 *
 * system.facts.count = 5;
 * await system.settle();
 *
 * expect(observer.events.filter(e => e.type === "constraint.evaluate")).toHaveLength(1);
 * expect(observer.ofType("resolver.complete")).toHaveLength(1);
 *
 * observer.clear();
 * observer.dispose();
 * ```
 */
declare function createTestObserver(system: SingleModuleSystem<any> | NamespacedSystem<any>): {
    /** All collected events. */
    events: ObservationEvent[];
    /** Filter events by type. */
    ofType: <T extends ObservationEvent["type"]>(type: T) => Extract<ObservationEvent, {
        type: T;
    }>[];
    /** Clear collected events. */
    clear: () => void;
    /** Stop observing. */
    dispose: () => void;
};

export { type CoverageReport, type CreateTestSystemOptions, type CreateTestSystemOptionsSingle, type FactChangeRecord, type FakeTimers, type MockResolver, type MockResolverContext, type MockResolverOptions, type TestSystem, type TestSystemBase, type TestSystemSingle, assertDynamic, assertNotDynamic, createCoverageTracker, createFakeTimers, createMockResolver, createTestObserver, createTestSystem, flushAsync, flushMicrotasks, mockResolver, settleWithFakeTimers };
