/** * vapor-chamber/vitest/pure - assert on a real bus through its own events. * * No side effects: importing this module registers no hook and no matcher. It * is what `vapor-chamber/vitest` re-exports after doing both, and what a suite * imports when it wants the helpers without the automatic behaviour. * * It imports NOTHING from the library at runtime, only types. That is a * measured requirement, not tidiness: a setup file that imported the root * barrel at load ran chamber.ts's one-shot Vue detection and consumed a * warn-once before any test had set its preconditions, and 4 tests of this * repository's suite failed for it. * * @example * import { expect } from 'vitest'; * import { matchers, tap } from 'vapor-chamber/vitest/pure'; * expect.extend(matchers); * * const bus = tap(createCommandBus()); * expect(bus.dispatch('cartAdd', { id: 1 }, { qty: 2 })).toSucceedWith(3); * expect(bus).toHaveBeenDispatchedWith('cartAdd', { qty: 2 }); */ import type { AsyncCommandBus, BusErrorCode, Command, CommandBus, CommandMap, CommandResult, PayloadOf } from './command-bus'; import type { McpTool } from './mcp'; /** * Codes of the misuse diagnostics this entry raises. A union of its own, so * the core `BusErrorCode` registry, and the bytes every app ships, do not move * for test tooling. * * - `test:missing:tap`: a bus matcher received a bus that was never passed to * `tap()`, so nothing it dispatched was recorded. Fix: `tap(bus)` where the * bus is created; the shared bus from `getCommandBus()` is tapped for you * when `vapor-chamber/vitest` is a setup file. * - `test:already:instance`: the bus came from a second copy of * vapor-chamber, not the one the setup file tapped. Every assertion would * otherwise report "nothing was dispatched". Fix: dedupe the install * (`npm ls vapor-chamber`) so one copy is loaded. * - `test:unexpected:version`: a warning, never a failure. This entry was released * against Vitest 5 and meets a major it does not know. Fix: none needed if * the suite passes; report a break if it does not. * - `test:lost:tap`: the bus was tapped, then `clear()` or `dispose()` * removed every hook, the tap's included, so later dispatches were not * recorded. Raised only where a missed record could change the outcome. * Fix: `tap(bus)` again after clearing. * - `test:invalid:files`: an MCP client passed `target.files` that is * not a list of up to 100 non-empty filters, or a filter starting with `-`. * Fix: pass file filters relative to the project root. * - `test:missing:run`: `getTestResults` before any `runTests`. Fix: call * `runTests` first. * - `test:missing:coverage`: the coverage run wrote no report. Fix: install * the provider the config names and check that the suite starts. */ export type VcTestDiagnostic = 'test:missing:tap' | 'test:already:instance' | 'test:unexpected:version' | 'test:lost:tap' | 'test:invalid:files' | 'test:missing:run' | 'test:missing:coverage'; /** A coded misuse diagnostic: `code` to switch on, `why`, `fix` and a `docs` link. */ export declare class VcTestError extends Error { readonly code: VcTestDiagnostic; readonly why: string; readonly fix: string; readonly docs: string; constructor(code: VcTestDiagnostic, detail?: string); } /** What `tap()` needs: the after-hook. Sync, async and schema buses all have it. */ export type Tappable = { onAfter(hook: (cmd: Command, result: CommandResult) => void): () => void; }; /** * Record every dispatch on `bus`, in order, through its own `onAfter` hook, * and return the same bus. Idempotent: a bus tapped twice records once. * * The bus is the real one - no double, no wrapper - so a test exercises what * production runs. The one observable difference is the hook itself * (`inspectBus(bus).afterHookCount` is 1 higher), measured to break nothing * across this repository's suite. A sealed bus refuses the hook with * `core:refused:bus`: tap before sealing. * * `clear()` and `dispose()` remove every hook, this one included. Tapping the * bus again re-attaches it to the same record; until then a matcher whose * outcome a missed dispatch could change throws `test:lost:tap`. * * The record grows for the life of the bus. What a matcher reads is the part * since the last {@link beginTest}, which is why a bus that outlives a test * needs one per test. */ export declare function tap(bus: B): B; /** * beginTest - open a new record boundary, so the bus matchers answer for the * dispatches that follow it and not for the ones before. * * `vapor-chamber/vitest` calls it before each test, where a fresh shared bus * makes it a formality. A suite using THIS entry on its own must call it in a * `beforeEach` whenever it taps a bus that outlives one test - an app's own * configured bus, published at module load and imported by every test file. * Without it the record is that bus's whole history, and a count or a `.not` * answers for earlier tests. * * @example * import { beforeEach, expect } from 'vitest'; * import { beginTest, matchers, tap } from 'vapor-chamber/vitest/pure'; * import { bus } from './bus'; * * expect.extend(matchers); * tap(bus); * beforeEach(beginTest); */ export declare function beginTest(): void; /** The part of Vitest's task an after-hook sees that a failure explanation needs. */ type FinishedTask = { result?: { state?: string; errors?: { message: string; stack?: string; }[]; }; }; /** The part of Vitest's `chai` export a failure explanation prints with. */ type Chai = { config: { truncateThreshold: number; }; util: { inspect(value: unknown): string; }; }; /** * @internal Run by `vapor-chamber/vitest` after each test. A test that failed, * on any assertion, gets the dispatches it made appended to its first error, * in the shape of Vitest's own "Received: ... Number of calls" block, printed * with Vitest's `chai.util.inspect`. `annotate()` is not an option: measured on * Vitest 5.0.1, it throws once the test has failed. A failure a bus matcher * already explained is left as it is. * * Printed untruncated, as Vitest prints its Received blocks: at the default * `truncateThreshold` (40, meant for assertion headers) a dispatch read * `{ action: 'cartAdd', ...(4) }`. The user's threshold is restored at once. * The stack gets the text too, the way Vitest rewrites an error's message * (`stack.replace(message, ...)`): the JSON reporter reads `stack`, not * `message`, and showed nothing without it. */ export declare function _explainFailure(task: FinishedTask, chai: Chai): void; /** @internal Set by `vapor-chamber/vitest` in each test's beforeEach. */ export declare function _setInstalledBus(bus: object | undefined): void; /** * What a stub returns: declare it with `using`, and the one name it stubbed is * restored at the end of the block, before `afterEach` runs, a throw included. * Vitest's own `vi.stubGlobal` / `vi.stubEnv` return nothing disposable, and * `unstubGlobals` / `unstubEnvs` restore at the start of the NEXT test, after * the current test's after-hooks. Every Vitest mock is already disposable * (`using spy = vi.spyOn(...)`), so spies need nothing from here. */ export interface Restore { /** @ts-ignore Symbol.dispose is absent from a lib older than esnext.disposable. Restores the stubbed name; a second call does nothing. */ [Symbol.dispose](): void; } /** @internal Run by `vapor-chamber/vitest` before each test: restores every stub still in place, newest first. */ export declare function _restoreStubs(): void; /** * Stub `globalThis[name]` for the block: `using _ = stubGlobal('fetch', fake)`. * Defined the way `vi.stubGlobal` defines it (writable, configurable, * enumerable). The restore puts back the own-property descriptor that was * there, getters included, or deletes the name if there was none. */ export declare function stubGlobal(name: string | symbol, value: unknown): Restore; /** The value `stubEnv` accepts for `name`: a boolean for Vite's DEV, PROD and SSR, as `vi.stubEnv` takes. */ export type EnvValue = N extends 'DEV' | 'PROD' | 'SSR' ? boolean : string | undefined; /** * Stub an environment variable for the block: `using _ = stubEnv('NODE_ENV', 'production')`. * Stored the way `vi.stubEnv` stores it: `undefined` unsets, DEV / PROD / SSR * become '1' or ''. It writes `process.env`, which `import.meta.env` reads in * every Node pool (Vitest's `metaEnv` there is a view of `process.env`). The * restore puts back the value that was there, or deletes the variable. */ export declare function stubEnv(name: N, value: EnvValue): Restore; /** A `tools/call` result: text content blocks, and `isError` when the tool failed. */ export type McpToolResult = { content: { type: string; text: string; }[]; isError?: boolean; }; /** A JSON-RPC 2.0 message handler, such as `createMcpHandler(bus, { actionFilter })` returns. */ export type McpMessageHandler = (message: unknown) => Promise; /** An MCP client for tests: what an agent does, without writing JSON-RPC envelopes. */ export interface McpClient { /** `initialize`, returning the server's result. */ initialize(params?: object): Promise<{ protocolVersion: string; capabilities: object; serverInfo: object; }>; /** `tools/list`: every tool the server exposes to this client. */ tools(): Promise; /** The names `tools/list` returns, in order. */ toolNames(): Promise; /** `tools/call`. A tool that fails is a result with `isError`; assert it with `toBeToolError`. A tool not listed is a protocol error: the call rejects with code -32602. */ call(name: string, args?: { target?: unknown; payload?: unknown; }): Promise; /** Any request, answered with the raw JSON-RPC reply, errors included: for testing the envelope itself. */ request(method: string, params?: unknown): Promise; /** A notification: no id, so a conforming server answers `null`. */ notify(method: string, params?: unknown): Promise; } /** * Drive an MCP server handler the way an agent does. Ids are numbered for you; * `initialize`, `tools`, `toolNames` and `call` throw on a JSON-RPC error (an * `Error` whose `code` is the JSON-RPC code), because a protocol error is never * what a tool test expects. Takes the handler, not the bus, so this entry * still imports nothing and any JSON-RPC MCP handler works. * * @example * const mcp = mcpClient(createMcpHandler(bus, { actionFilter: createActionFilter([{ prefix: { action: 'cart' } }]) })); * expect(await mcp.toolNames()).toEqual(['cartAdd']); * expect(await mcp.call('cartAdd', { target: { id: 1 }, payload: { qty: 2 } })).toBeToolResult({ count: 2 }); * await expect(mcp.call('orderDelete')).rejects.toMatchObject({ code: -32602 }); // not listed: a protocol error */ export declare function mcpClient(handler: McpMessageHandler): McpClient; /** * The utilities in one object, as Vitest keeps its own in `vi`: type `vc.` and * the editor lists them. Each member IS the named export (`vc.tap === tap`), * so both forms can be mixed and tree-shaking of the named imports is kept. * * @example * import { vc } from 'vapor-chamber/vitest'; * const bus = vc.tap(createCommandBus()); * using _env = vc.stubEnv('NODE_ENV', 'production'); * const mcp = vc.mcp(createMcpHandler(bus, { actionFilter: createActionFilter([{ prefix: { action: 'cart' } }]) })); */ export declare const vc: { tap: typeof tap; stubGlobal: typeof stubGlobal; stubEnv: typeof stubEnv; mcp: typeof mcpClient; }; /** The part of Vitest's matcher `this` these matchers use; structural, so this file names no vitest type. */ interface MatcherContext { isNot: boolean; customTesters: unknown[]; equals(a: unknown, b: unknown, testers?: unknown[]): boolean; utils: { stringify(value: unknown, maxDepth?: number, options?: { min?: boolean; }): string; diff(expected: unknown, received: unknown, options?: { omitAnnotationLines?: boolean; }): string | undefined; iterableEquality: unknown; }; } /** * The matcher implementations, for `expect.extend(matchers)`. The bus matchers * read what `tap()` recorded and throw a `VcTestError` on a bus it never saw, * `.not` included, so a negated assertion cannot pass vacuously. The result * matchers read a `CommandResult` and compare codes, never message text. */ export declare const matchers: { toHaveBeenDispatched(this: MatcherContext, bus: unknown, action: string): { pass: boolean; message: () => string; }; toHaveBeenDispatchedWith(this: MatcherContext, bus: unknown, action: string, payload: unknown): { pass: boolean; message: () => string; }; toHaveBeenDispatchedTimes(this: MatcherContext, bus: unknown, action: string, times: number): { pass: boolean; message: () => string; }; toHaveBeenDispatchedOnce(this: MatcherContext, bus: unknown, action: string): { pass: boolean; message: () => string; }; toHaveBeenNthDispatchedWith(this: MatcherContext, bus: unknown, nth: number, action: string, payload: unknown): { pass: boolean; message: () => string; }; toHaveBeenLastDispatchedWith(this: MatcherContext, bus: unknown, action: string, payload: unknown): { pass: boolean; message: () => string; }; toHaveFailedWith(this: MatcherContext, bus: unknown, action: string, code: string): { pass: boolean; message: () => string; }; toSucceedWith(this: MatcherContext, received: unknown, value_0?: unknown): { pass: boolean; message: () => string; }; toFailWith(this: MatcherContext, received: unknown, code: string): { pass: boolean; message: () => string; }; toBeToolResult(this: MatcherContext, received: unknown, value_0?: unknown): { pass: boolean; message: () => string; }; toBeToolError(this: MatcherContext, received: unknown, expected?: string | RegExp): { pass: boolean; message: () => string; }; }; type MapOf = T extends CommandBus ? M : T extends AsyncCommandBus ? M : CommandMap; /** The actions a matcher accepts for received value `T`: the bus's own names when typed, any string when not. */ export type ActionOf = string extends keyof MapOf ? string : keyof MapOf & string; /** The payload a matcher accepts for action `A` on received value `T`. */ export type ExpectedPayload = A extends keyof MapOf ? PayloadOf, A> : unknown; /** * An error code: the bus's own codes autocomplete, and a handler's domain code * is accepted too, because a handler's throw reaches `result.error` as thrown. */ export type ExpectedCode = BusErrorCode | (string & {}); /** * The matcher signatures, typed from the received value. `vapor-chamber/vitest` * merges this into Vitest's `Matchers`; this entry does not, so importing * it alone never types a matcher it did not register. */ export interface VaporChamberMatchers { /** The bus dispatched `action` at least once. Vitest's `toHaveBeenCalled`, for one action. */ toHaveBeenDispatched>(action: A): R; /** Some dispatch of `action` carried a payload equal to `payload` (toEqual's comparison). */ toHaveBeenDispatchedWith>(action: A, payload: ExpectedPayload): R; /** `action` was dispatched exactly `times` times. */ toHaveBeenDispatchedTimes>(action: A, times: number): R; /** `action` was dispatched exactly once. */ toHaveBeenDispatchedOnce>(action: A): R; /** The `nth` dispatch of `action` (1-based, counting that action only) carried `payload`. */ toHaveBeenNthDispatchedWith>(nth: number, action: A, payload: ExpectedPayload): R; /** The last dispatch of `action` carried `payload`. */ toHaveBeenLastDispatchedWith>(action: A, payload: ExpectedPayload): R; /** The bus dispatched `action` and it failed with `code`. */ toHaveFailedWith>(action: A, code: ExpectedCode): R; /** The result succeeded, and when given, with a value equal to `value`. */ toSucceedWith(value?: T extends CommandResult ? V : unknown): R; /** The result failed with `code`. */ toFailWith(code: ExpectedCode): R; /** An MCP tool result succeeded, and when given, its text parsed as JSON equals `value`. */ toBeToolResult(value?: unknown): R; /** An MCP tool result is an error, and when given, its text contains the string or matches the RegExp. */ toBeToolError(expected?: string | RegExp): R; } export {}; //# sourceMappingURL=vitest-pure.d.ts.map