# @probitas/core > Version: 0.3.2 Core scenario definition types and utilities. This package provides the fundamental type definitions that represent scenario structures, along with utilities for loading scenario files and filtering scenarios using selectors. It serves as the foundation layer that other Probitas packages build upon. ## Links - [GitHub Repository](https://github.com/probitas-test/probitas) - [@probitas/probitas](https://jsr.io/@probitas/probitas) - Main package (recommended for most users) ## Related Packages | Package | Description | |---------|-------------| | [@probitas/builder](https://jsr.io/@probitas/builder) | Uses these types to build scenarios | | [@probitas/runner](https://jsr.io/@probitas/runner) | Executes scenario definitions | | [@probitas/discover](https://jsr.io/@probitas/discover) | Discovers scenario files to load | ## Type Definitions The type system is designed around immutable data structures: - {@linkcode ScenarioDefinition} - Complete scenario with name, options, and entries - {@linkcode StepDefinition} - Individual step with function, options, and source - {@linkcode SetupDefinition} - Setup hook with cleanup function support - {@linkcode ResourceDefinition} - Named resource with fn function - {@linkcode StepContext} - Context object passed to all functions - {@linkcode Entry} - Discriminated union of step, setup, or resource ## Options Types - {@linkcode ScenarioOptions} - Scenario-level configuration (tags, default step options) - {@linkcode StepOptions} - Step execution settings (timeout, retry strategy) - Import `Origin` from `@probitas/core/origin` for file and line information ## Function Types - {@linkcode StepFunction} - Signature for step execution functions - {@linkcode SetupFunction} - Signature for setup hooks (returns cleanup) - {@linkcode ResourceFunction} - Signature for resource creation functions - {@linkcode SetupCleanup} - Return type of setup functions ## Loader Utilities - {@linkcode loadScenarios} - Load scenario definitions from file paths - {@linkcode LoadScenariosOptions} - Options for the loader ## Selector Utilities Selectors provide powerful filtering capabilities: - {@linkcode applySelectors} - Filter scenarios using selector strings - {@linkcode parseSelector} - Parse selector string into Selector objects - {@linkcode matchesSelector} - Check if a scenario matches a single selector - {@linkcode Selector} - Parsed selector object - {@linkcode SelectorType} - Type of selector ("tag" or "name") ## Interfaces ### `ScenarioOptions` ```typescript interface ScenarioOptions ``` Configuration options for scenario execution. Defines metadata and default behavior for an entire scenario. **Properties:** - [readonly] `tags?`: `readonly string[]` — Tags for filtering and organizing scenarios. Tags can be used with the CLI to run specific subsets: ```bash probitas run -s "tag:api" # Run scenarios tagged "api" probitas run -s "tag:api,tag:fast" # Run scenarios with both tags probitas run -s "!tag:slow" # Exclude slow scenarios ``` - [readonly] `timeout?`: `number` — Maximum time in milliseconds for the entire scenario to complete. When specified, this timeout applies to the total execution time of all steps in the scenario. If the scenario exceeds this limit, a {@linkcode ScenarioTimeoutError} is thrown. Priority: scenario timeout > RunOptions timeout - [readonly] `stepOptions?`: `StepOptions` — Default options applied to all steps in this scenario. Individual steps can override these defaults by specifying their own options in the `.step()` call. **Example:** ```ts const options: ScenarioOptions = { tags: ["api", "integration", "slow"], timeout: 30000, stepOptions: { timeout: 60000, retry: { maxAttempts: 2, backoff: "linear" } } }; ``` --- ### `ScenarioDefinition` ```typescript interface ScenarioDefinition ``` Complete, immutable definition of a scenario. This is the core type produced by the builder and consumed by the runner. It contains everything needed to execute a scenario: its name, options, and ordered sequence of entries (steps, resources, setups). **Properties:** - [readonly] `name`: `string` — Human-readable scenario name (displayed in reports and CLI) - [readonly] `tags`: `readonly string[]` — Tags for filtering and organizing scenarios. Tags can be used with the CLI to run specific subsets: ```bash probitas run -s "tag:api" # Run scenarios tagged "api" probitas run -s "tag:api,tag:fast" # Run scenarios with both tags probitas run -s "!tag:slow" # Exclude slow scenarios ``` - [readonly] `timeout?`: `number` — Maximum time in milliseconds for the entire scenario to complete. When set, overrides the RunOptions timeout for this specific scenario. When timeout occurs, a {@linkcode ScenarioTimeoutError} is thrown. - [readonly] `steps`: `readonly StepDefinition[]` — Ordered sequence of entries (resources → setups → steps) - [readonly] `origin?`: `Origin` — Origin where the scenario was defined **Example:** Typical scenario structure ```ts import type { ScenarioDefinition } from "@probitas/core"; // Created by: scenario("Login Flow").step(...).build() const definition: ScenarioDefinition = { name: "Login Flow", tags: ["auth", "smoke"], steps: [ { kind: "resource", name: "api", fn: () => fetch, timeout: 30000, retry: { maxAttempts: 1, backoff: "linear" }, }, { kind: "step", name: "Login", fn: () => {}, timeout: 30000, retry: { maxAttempts: 1, backoff: "linear" }, }, { kind: "step", name: "Verify", fn: () => {}, timeout: 30000, retry: { maxAttempts: 1, backoff: "linear" }, }, ], origin: { path: "/tests/auth.probitas.ts", line: 5 }, }; console.log(definition); ``` --- ### `ScenarioMetadata` ```typescript interface ScenarioMetadata ``` Serializable scenario metadata (without executable functions). Used by the JSON reporter and tooling to output scenario information without including non-serializable function references. **Properties:** - [readonly] `name`: `string` — Scenario name - [readonly] `tags`: `readonly string[]` — Tags for filtering and organizing scenarios. Tags can be used with the CLI to run specific subsets: ```bash probitas run -s "tag:api" # Run scenarios tagged "api" probitas run -s "tag:api,tag:fast" # Run scenarios with both tags probitas run -s "!tag:slow" # Exclude slow scenarios ``` - [readonly] `timeout?`: `number` — Maximum time in milliseconds for the entire scenario to complete. When set, overrides the RunOptions timeout for this specific scenario. - [readonly] `steps`: `readonly StepMetadata[]` — Entry metadata (functions omitted for serialization) - [readonly] `origin?`: `Origin` — Origin where the scenario was defined **Example:** JSON reporter output ```json { "name": "Login Flow", "options": { "tags": ["auth"], "stepOptions": { ... } }, "entries": [ { "kind": "step", "value": { "name": "Login", "options": { ... } } } ], "origin": { "path": "/tests/auth.probitas.ts", "line": 5 } } ``` --- ### `StepOptions` ```typescript interface StepOptions ``` Configuration options for individual step execution. Controls timeout and retry behavior for a step. These options can be set at: 1. Step level (highest priority) 2. Scenario level (applies to all steps in scenario) 3. Default values (30s timeout, no retry) **Properties:** - [readonly] `timeout?`: `number` — Maximum execution time in milliseconds. If the step takes longer, a {@linkcode TimeoutError} is thrown. Default: 30000 (30 seconds) - [readonly] `retry?`: `{ maxAttempts?: number; backoff?: "linear" | "exponential" }` — Retry configuration for handling transient failures **Example:** ```ts const options: StepOptions = { timeout: 60000, // 60 seconds retry: { maxAttempts: 3, backoff: "exponential" // Waits 1s, 2s, 4s between retries } }; ``` --- ### `StepContext` ```typescript interface StepContext ``` Execution context provided to steps, resources, and setup hooks. The context provides access to: - Previous step results with full type inference - All accumulated results as a typed tuple - Named resources registered with `.resource()` - Shared storage for cross-step communication - Abort signal for timeout and cancellation handling **Properties:** - [readonly] `index`: `number` — Current step index (0-based). Useful for conditional logic based on position in the scenario. - [readonly] `previous`: `unknown` — Result from the previous step. Fully typed based on what the previous step returned. For the first step, this is `unknown`. - [readonly] `results`: `readonly unknown[]` — All accumulated results as a typed tuple. Allows accessing any previous result by index: ```ts import type { StepContext } from "@probitas/core"; const stepFn = (ctx: StepContext) => { ctx.results[0]; // First step's result ctx.results[1]; // Second step's result }; console.log(stepFn); ``` - [readonly] `store`: `Map` — Shared key-value storage for cross-step communication. Use this for data that doesn't fit the step result pattern, such as metadata or configuration set during setup. - [readonly] `resources`: `Record` — Named resources registered with `.resource()`. Resources are typed based on their registration: ```ts import type { StepContext } from "@probitas/core"; interface DbResource { query(sql: string): unknown; } // Access resources registered with .resource() const stepFn = (ctx: StepContext) => { const db = ctx.resources["db"] as DbResource; return db.query("SELECT 1"); }; console.log(stepFn); ``` - [readonly] `signal?`: `AbortSignal` — Abort signal that fires on timeout or manual cancellation. Pass this to fetch() or other APIs that support AbortSignal for proper timeout handling. **Example:** Accessing previous result ```ts import type { StepContext } from "@probitas/core"; // Steps receive context with the previous step's result const stepFn = (ctx: StepContext) => { // ctx.previous contains the result from the previous step const prev = ctx.previous as { id: number }; console.log(prev.id); // Access typed result }; console.log(stepFn); ``` Using shared store ```ts import type { StepContext } from "@probitas/core"; // The store is shared across all steps in a scenario const setupFn = (ctx: StepContext) => { ctx.store.set("startTime", Date.now()); }; const stepFn = (ctx: StepContext) => { const start = ctx.store.get("startTime") as number; console.log(`Elapsed: ${Date.now() - start}ms`); }; console.log(setupFn, stepFn); ``` --- ### `StepDefinition` ```typescript interface StepDefinition ``` Immutable definition of a scenario step. Contains all information needed to execute a single step: the step function, its options, and debugging metadata. **Properties:** - [readonly] `kind`: `"step" | "resource" | "setup"` - [readonly] `name`: `string` — Human-readable step name (displayed in reports) - [readonly] `fn`: `StepFunction` — Step function to execute - [readonly] `timeout?`: `number` — Maximum execution time in milliseconds. If the step takes longer, a {@linkcode TimeoutError} is thrown. Default: 30000 (30 seconds) - [readonly] `retry?`: `{ maxAttempts?: number; backoff?: "linear" | "exponential" }` — Retry configuration for handling transient failures - [readonly] `origin?`: `Origin` — Origin where the step was defined (for error messages) --- ## Types ### `SetupCleanup` ```typescript type SetupCleanup = void | unknown | Disposable | AsyncDisposable ``` Cleanup handler returned by setup functions. Setup functions can return various cleanup mechanisms that are automatically invoked after the scenario completes (regardless of success or failure). Supported cleanup patterns: - `void` / `undefined`: No cleanup needed - `() => void`: Synchronous cleanup function - `() => Promise`: Async cleanup function - `Disposable`: Object with `[Symbol.dispose]()` method - `AsyncDisposable`: Object with `[Symbol.asyncDispose]()` method --- ### `StepFunction` ```typescript type StepFunction = (ctx: StepContext) => unknown ``` Function signature for step execution. A step function receives the execution context and returns a value (sync or async) that becomes available to subsequent steps. --- ### `StepMetadata` ```typescript type StepMetadata = Omit ``` Serializable step metadata (without the function). Used for JSON output, tooling, and inspection without executing code. --- ## Related Links ### This Package - [`StepContext`](https://probitas-test.github.io/documents/api/core#StepContext) - [`StepDefinition`](https://probitas-test.github.io/documents/api/core#StepDefinition) - [`StepFunction`](https://probitas-test.github.io/documents/api/core#StepFunction) - [`StepMetadata`](https://probitas-test.github.io/documents/api/core#StepMetadata) - [`StepOptions`](https://probitas-test.github.io/documents/api/core#StepOptions) ### Built-in Types - [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) - [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys) - [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type) --- *Last updated: 2026-01-12*