# Pipework API Reference

> Auto-generated from source JSDoc. Do not edit manually.
> Generated: 2026-07-19

## Contents

- [Core](#core)
- [env — Environment Variables](#env-environment-variables)
- [jobs — Background Jobs](#jobs-background-jobs)
- [pipeline — Multi-Step Pipelines](#pipeline-multi-step-pipelines)
- [state — State Machines](#state-state-machines)
- [auth — Authentication](#auth-authentication)
- [rbac — Access Control](#rbac-access-control)
- [tenant — Multi-Tenancy](#tenant-multi-tenancy)
- [config — Configuration](#config-configuration)
- [errors — Error Classes](#errors-error-classes)
- [lifecycle — Startup & Shutdown](#lifecycle-startup-shutdown)
- [log — Structured Logging](#log-structured-logging)
- [surface — Entry Points](#surface-entry-points)
- [pipe — Database](#pipe-database)
- [jsonb — JSONB Column Helpers](#jsonb-jsonb-column-helpers)
- [schema — Validation & Schema](#schema-validation-schema)
- [temporal — Bitemporal Data](#temporal-bitemporal-data)
- [valve](#valve)
- [vector — Vector & Full-Text Search](#vector-vector-full-text-search)
- [audit — Audit Logging](#audit-audit-logging)
- [cache — Caching](#cache-caching)
- [webhook — Inbound & Outbound Webhooks](#webhook-inbound-outbound-webhooks)
- [behavior — Resource Decorators](#behavior-resource-decorators)
- [fitting — Dependency Injection](#fitting-dependency-injection)
- [fixture — REST Resources](#fixture-rest-resources)
- [flow — Context (AsyncLocalStorage)](#flow-context-asynclocalstorage)
- [http — Server](#http-server)
- [openapi — API Documentation](#openapi-api-documentation)
- [test](#test)
- [data](#data)
- [trace](#trace)

## Core

Application instance and foundational types.

### `createManifold`

Creates the Pipework application instance. This is the entry point for every Pipework app.
Define in `pipework.config.ts` and export as default.

The `env` field declares the app's environment variables — the canonical
home for runtime config (ports, service tokens, bucket names, flags) in
place of scattered `process.env` reads. Each variable is read once at config
load, validated and coerced to its declared type (loud error on a bad or
missing-required value), and exposed typed on `manifold.env`.


```typescript
const manifold = createManifold({
  databases: { app: { url: 'DATABASE_URL', testUrl: 'DATABASE_URL_TEST' } },
  env: {
    PORT: { type: 'number', defaults: { development: '3000', test: '0' } },
    S3_BUCKET: { type: 'string', required: true },
    API_TOKEN: { type: 'string', required: true, sensitive: true },
  },
})
manifold.env.PORT       // number — from process.env.PORT, or the per-environment default
manifold.env.S3_BUCKET  // string — startup fails loudly if unset
export default manifold
```

```typescript
function createManifold<const TEnv extends EnvDefs = EnvDefs>( raw: Omit<BlueprintInput, 'env'> &
```

### Types

**`Manifold`** — The application instance — holds config, connection pools, surfaces, and lifecycle.

```typescript
interface Manifold<TEnv extends EnvDefs = EnvDefs>
```

**`SeedOptions`** — ALS context the {@link Manifold.seed} callback runs under — tenant scope, auth principal, and job type.

```typescript
interface SeedOptions
```

**`PoolState`** — Manages database connection pools keyed by database name.

```typescript
interface PoolState
```

**`IsolationState`** — Tracks test isolation lifecycle — detects leaked isolation contexts.

```typescript
interface IsolationState
```

**`ConnectionTracker`** — Tracks active database connections for leak detection.

```typescript
interface ConnectionTracker
```

## env — Environment Variables

Declared environment variables — the canonical home for runtime config (ports, service tokens, bucket names, feature flags). Declare them under the `env` blueprint field; each is read once at config load, validated and coerced to its declared type (loud error on a bad or missing-required value), and exposed typed on `manifold.env` — in place of scattered ad-hoc `process.env` reads.

### Types

**`StringEnvVar`**

A string environment variable — resolved verbatim.


```typescript
S3_BUCKET: { type: 'string', required: true }
```

```typescript
interface StringEnvVar extends EnvVarBase
```

**`NumberEnvVar`**

A number environment variable — parsed with a loud error on a non-numeric value.


```typescript
PORT: { type: 'number', default: 3000 }
```

```typescript
interface NumberEnvVar extends EnvVarBase
```

**`BooleanEnvVar`**

A boolean environment variable — accepts true/false/1/0, loud error otherwise.


```typescript
FEATURE_GRAPH: { type: 'boolean', default: false }
```

```typescript
interface BooleanEnvVar extends EnvVarBase
```

**`StringArrayEnvVar`**

A string-array environment variable — the raw value split on `separator`
(default `,`), each element trimmed.


```typescript
CORS_ORIGINS: { type: 'string[]', separator: ',', default: [] }
```

```typescript
interface StringArrayEnvVar extends EnvVarBase
```

**`EnvVarDef`**

One declared environment variable: its type, whether it is required, its
fallbacks, and whether the value is sensitive. Declared under the `env`
blueprint field; resolved once at config load and exposed typed on
`manifold.env` — the canonical replacement for ad-hoc `process.env` reads.

```typescript
type EnvVarDef = StringEnvVar | NumberEnvVar | BooleanEnvVar | StringArrayEnvVar
```

**`EnvDefs`**

The `env` blueprint field: environment-variable declarations keyed by
variable name. Passing this map to `createManifold` is what types
`manifold.env`.


```typescript
export default createManifold({
  databases: { app: { url: 'DATABASE_URL', testUrl: 'DATABASE_URL_TEST' } },
  env: {
    PORT: { type: 'number', defaults: { development: '3000', test: '0' } },
    S3_BUCKET: { type: 'string', required: true },
    API_TOKEN: { type: 'string', required: true, sensitive: true },
    CORS_ORIGINS: { type: 'string[]', default: [] },
  },
})
// manifold.env.PORT         → number
// manifold.env.S3_BUCKET    → string
// manifold.env.CORS_ORIGINS → string[]
```

```typescript
type EnvDefs = Record<string, EnvVarDef>
```

**`ResolvedEnvType`** — The resolved runtime type of one declaration: 'string' → string, 'number' → number, 'boolean' → boolean, 'string[]' → string[].

```typescript
type ResolvedEnvType<T extends EnvVarDef> =
```

**`ResolveEnvDefs`** — Maps a declaration map to the shape of `manifold.env` — each key typed by its declared `type`.

```typescript
type ResolveEnvDefs<T extends EnvDefs> =
```

## jobs — Background Jobs

Background job queue namespace — Postgres-backed with SKIP LOCKED, LISTEN/NOTIFY, cron scheduling.

### `jobs.createQueue`

Creates a job queue with claim/complete/fail lifecycle, heartbeat, and dead letter requeue.

### `jobs.execute`

Executes a fitting handler as a background job with its own Flow context.

### `jobs.parseCron`

Parses a 5-field cron expression into a CronSchedule (minute, hour, dom, month, dow).

### `jobs.nextTick`

Computes the next fire time for a CronSchedule after a given date, with optional timezone.

## pipeline — Multi-Step Pipelines

Multi-step pipeline namespace — define, execute, pause, and resume ordered step sequences.

### `pipeline.define`

Defines a pipeline from a config of named steps with handlers. Returns a Pipeline with execute/resume/getStatus.

### `pipeline.PipelineStepError`

Thrown when an individual pipeline step fails.

### `pipeline.PipelineResumeError`

Thrown when resuming a pipeline from an invalid state.

## state — State Machines

State machine namespace — define valid transitions with guards and side effects.

### `state.define`

Defines a state machine from states, transitions, guards, and effects. Returns a StateMachine with transition/canTransition.

### `state.InvalidTransitionError`

Thrown when a transition is not allowed from the current state.

### `state.InvalidStateMachineError`

Thrown when the state machine definition is internally inconsistent.

## auth — Authentication

Authentication namespace — session management, multi-org support, auth chain resolution.

### `auth.createSessions`

Creates a Sessions manager with JWT access/refresh tokens, rotation, and reuse detection.

### `auth.createMultiOrg`

Creates multi-org session management — org selection, switching, membership CRUD.

### `auth.runChain`

Executes an auth chain (strategy pipeline) to resolve auth + tenant from a request.

### `auth.resolveCookie`

Resolves CookieConfig with defaults for secure cookie-based token delivery.

### `auth.parseCookie`

Parses a Cookie header string into key-value pairs.

### `auth.buildSetCookie`

Builds a Set-Cookie header string from name, value, and CookieConfig.

### `auth.buildClearCookie`

Builds a Set-Cookie header that clears (expires) a cookie.

### Types

**`AuthContext`** — Runtime auth context passed to strategies — carries the resolved DB and request metadata.

```typescript
interface AuthContext
```

**`AuthStrategy`** — Pluggable auth strategy — implement authenticate() to extract auth from a request.

```typescript
interface AuthStrategy<TAuth>
```

**`AuthRequest`** — Normalized request shape passed to auth strategies — headers, cookies, method, url.

```typescript
interface AuthRequest
```

**`BaseAuth`** — Minimum auth shape — userId and tenantId. Extend for app-specific auth fields.

```typescript
interface BaseAuth
```

**`AuthEnricher`** — Post-authentication hook — enrich the resolved auth with additional data (roles, permissions, etc.).

```typescript
interface AuthEnricher<TAuth>
```

**`TenantResolver`** — Resolves tenant ID from auth context — called after authentication in the chain.

```typescript
interface TenantResolver<TAuth>
```

**`AuthChainConfig`** — Configuration for the auth chain — strategies, enrichers, tenant resolver.

```typescript
interface AuthChainConfig<TAuth>
```

**`SessionConfig`** — Session configuration — signing keys, issuer, audience, token TTLs, refresh rotation.

```typescript
interface SessionConfig
```

**`TokenPair`** — Access + refresh token pair returned by issueTokens().

```typescript
interface TokenPair
```

**`TokenPayload`** — Decoded JWT payload — userId, tenantId, roles, version.

```typescript
interface TokenPayload
```

**`HttpTokenResult`** — Result from HTTP token operations — the token pair plus whether cookies were set.

```typescript
interface HttpTokenResult
```

**`Sessions`** — Session manager with JWT issue/refresh/revoke lifecycle and cookie-based HTTP helpers.

```typescript
interface Sessions
```

**`CookieConfig`** — Cookie configuration for token delivery — name, domain, path, secure, sameSite, httpOnly.

```typescript
interface CookieConfig
```

**`MultiOrgConfig`** — Configuration for multi-org sessions — base sessions, signing keys, org-select token TTL.

```typescript
interface MultiOrgConfig
```

**`OrgMembership`** — A user's membership in an organization — userId, orgId, role.

```typescript
interface OrgMembership
```

**`OrgInfo`** — Basic organization info — id and display name.

```typescript
interface OrgInfo
```

**`OrgMembershipDetail`** — Organization membership with display name — extends OrgMembership with org info.

```typescript
interface OrgMembershipDetail
```

**`AuthenticatedResult`** — Result when user has exactly one org — direct authentication, no org selection needed.

```typescript
interface AuthenticatedResult
```

**`OrgSelectResult`** — Result when user has multiple orgs — returns a session token for org selection.

```typescript
interface OrgSelectResult
```

**`ResolveLoginResult`** — Union result from resolveLogin() — either AuthenticatedResult or OrgSelectResult.

```typescript
type ResolveLoginResult = AuthenticatedResult | OrgSelectResult
```

**`MultiOrgSessions`** — Multi-org session manager — login resolution, org selection, switching, membership CRUD.

```typescript
interface MultiOrgSessions
```

## rbac — Access Control

Role-based access control namespace — permission checking, enforcement, scope hierarchy.

### `rbac.create`

Creates an Rbac instance from config (roles, permissions, hierarchy).

### `rbac.check`

Checks if a permission set includes the required resource/action/scope. Pure function, no DB.

### `rbac.enforce`

Checks permission and throws ForbiddenError if denied. Loads permissions from DB with caching.

### `rbac.satisfies`

Checks if a granted scope satisfies a required scope given a hierarchy (e.g. org > team > self).

### `rbac.PermissionCache`

LRU cache for resolved permissions — avoids repeated DB lookups within a request.

## tenant — Multi-Tenancy

Multi-tenant isolation namespace — RLS policies, tenant extraction, Postgres-side verification.

### `tenant.validate`

Validates a tenant ID format (non-empty string, safe characters).

### `tenant.rls`

Enables RLS on a table and creates the tenant isolation policy in Postgres.

### `tenant.policy`

Returns the SQL string for a tenant isolation RLS policy — use in migrations.

### `tenant.verify`

Cross-checks the ALS principal (tenant, user, asOf) against the Postgres session GUCs — defense-in-depth.

### `tenant.propagate`

Sets pipework.tenant_id on the Postgres connection via set_config().

### `tenant.extract`

Extracts tenant ID from auth context using the configured extraction strategy.

### `tenant.isTenantScoped`

Returns true if a table has been marked as tenant-scoped (via .tenant() field metadata).

## config — Configuration

Configuration namespace — loads and resolves Blueprint configs, discovers pipework.config.ts.

### `config.load`

Parses and resolves a raw Blueprint into a ResolvedConfig with environment detection.

### `config.discover`

Walks up from cwd to find pipework.config.ts, imports it, and returns the Manifold.

### `config.configSchema`

The zod schema for Blueprint validation — useful for custom config tooling.

### `config.ConfigError`

Thrown for configuration problems — includes a suggestion for how to fix.

### Types

**`StatementEvent`**

One statement as it is handed to the driver for writing to the wire —
including the transaction-control statements the driver issues on its own
(`BEGIN`, `SAVEPOINT`, `COMMIT`, `ROLLBACK`), which no application-level hook
can see.

```typescript
interface StatementEvent
```

**`StatementObserver`**

Caller-supplied per-statement observer. Fires once per statement written to
the wire, on every connection the manifold owns — pooled connections and the
test harness's own connections alike.

Pure observation: the return value is discarded and the statement is never
mutated. It runs synchronously on the driver's write path, so it must be
cheap and must not throw.

Counts wire truth, not application intent. Two consequences worth knowing
before you assert on a total: the driver issues its own transaction control
(`BEGIN`/`SAVEPOINT`/`COMMIT`/`ROLLBACK`), and it issues one `pg_catalog.pg_type`
lookup per connection the first time that connection is used.

```typescript
type StatementObserver = (event: StatementEvent) => void
```

## errors — Error Classes

Standard error classes — all extend PipeworkError with structured error codes and actionable messages.

### `errors.Base`

Base error class with code, statusCode, and suggestion fields.

### `errors.NotFound`

404 — resource not found.

### `errors.Unauthorized`

401 — missing or invalid authentication.

### `errors.Forbidden`

403 — authenticated but insufficient permissions.

### `errors.Validation`

422 — input validation failed, carries field-level details.

### `errors.Conflict`

409 — resource state conflict (duplicate, version mismatch).

## lifecycle — Startup & Shutdown

Application lifecycle namespace — startup orchestration with hooks and timeouts.

### `lifecycle.orchestrate`

Runs pre-start hooks (DB readiness checks, migrations, etc.) with a configurable timeout.

## log — Structured Logging

Structured logger (Pino) — auto-binds requestId, tenantId, userId, sessionId from ALS context on every log call.

### `log.create`

Creates a new PipeworkLogger instance with custom config (level, redaction, transport).

### `log.get`

Returns the context-aware logger proxy (same as the log export itself).

### `log.getBase`

Returns the raw Pino logger without ALS context binding.

### `log.configure`

Sets global logging config (level, redaction paths, custom context fields).

### `log.REDACT_PATHS`

Default redaction paths — password, secret, token, authorization, cookie, etc.

## surface — Entry Points

Surface namespace — declarative entry points that define how the app runs (HTTP server, background worker, one-shot script).

### `surface.http`

Creates an HTTP surface — a Fastify server with routes, middleware, and production validation. Returns an HttpSurfaceBuilder with a .test() method for inject()-based integration tests.

### `surface.worker`

Creates a worker surface — a long-running process that claims and executes jobs from queues.

### `surface.script`

Creates a script surface — a one-shot process that runs and exits (migrations, seeds, CLI tools).

## pipe — Database

Database accessor — returns a Drizzle DB instance scoped to the current request/job/test context. Requires active AsyncLocalStorage context.

### `pipe.system`

The system channel — deliberate cross-tenant access for pre-tenant surfaces (auth membership resolution, public webhook ingress, admin tooling). Never tenant-scoped or tenant-guarded; runs on the owner-role connection outside the request transaction.

### `pipe.filter`

Query operators and aggregates — eq, gt, lt, and, or, count, sum, etc.

### `pipe.aliasedRelation`


### `pipe.aliasedTable`


### `pipe.aliasedTableColumn`


### `pipe.getTableColumns`


### `pipe.getTableName`


### `pipe.getViewName`


### `pipe.getViewSelectedFields`


### `pipe.isTable`


### `pipe.createMany`


### `pipe.createOne`


### `pipe.relations`


### `pipe.migrate`

Runs migrations for all configured databases.

### `pipe.migrateOne`

Runs migrations for a single named database.

### `pipe.excluded`

Returns excluded-column references for onConflictDoUpdate set clauses.

### `pipe.advisoryLock`

Acquires a transaction-scoped advisory lock. Released at commit/rollback.

### `pipe.serializable`

Runs a function in a SERIALIZABLE transaction with automatic retry on serialization failures and deadlocks.

### `pipe.bulkSet`

Bulk UPDATE ... FROM (VALUES ...) — updates multiple rows with per-row values in a single statement.

### `pipe.values`

Produces a typed VALUES clause for bulk operations — the base primitive for bulkSet and bulkUpsert.

### `pipe.field`

Field builders for domain definitions — uuid(), text(), integer(), etc.

### `pipe.define`

Registers a domain definition with table, validators, and factory projections.

### `pipe.definitions`

Returns the global registry of all domain definitions.

### `pipe.update`

Pipework-owned UPDATE builder — the only consumer-facing way to update pipework-managed tables (Q8).

### `pipe.insert`

Pipework-owned INSERT builder — the only consumer-facing way to insert into pipework-managed tables (Q8).

### `pipe.delete`

Pipework-owned DELETE builder — the only consumer-facing way to delete from pipework-managed tables (Q8).

### `pipe.upsert`

Pipework-owned UPSERT builder — insert with conflict resolution (Q8).

### Types

**`WindowSpec`** — A window-frame specification — the `PARTITION BY` / `ORDER BY` clauses applied by {@link over}.

```typescript
interface WindowSpec
```

**`ValueColumnDef`** — One column of a typed `VALUES` clause: its name and the PostgreSQL type each value in that column is cast to. See {@link values}.

```typescript
interface ValueColumnDef
```

**`SerializableOptions`** — Retry policy for {@link serializable}: how many attempts on a serialization failure / deadlock, and the base backoff between them.

```typescript
interface SerializableOptions
```

**`ManagedConnection`** — A standalone pooled connection: the raw postgres.js client, its drizzle handle, and a `close()` that ends the pool.

```typescript
interface ManagedConnection
```

**`ConnectOptions`** — Options for `tap()` — pool size (default 1) and idle timeout in seconds.

```typescript
interface ConnectOptions
```

## jsonb — JSONB Column Helpers

JSONB query operators — typed helpers for PostgreSQL JSONB containment, key checks, and field extraction.

### `jsonb.contains`

The @> containment operator — tests whether a JSONB column contains the given value.

### `jsonb.containedBy`

The <@ contained-by operator — tests whether a JSONB column is contained by the given value.

### `jsonb.hasKey`

The ? key-existence operator — tests whether a JSONB column has the given top-level key.

### `jsonb.text`

Extracts a text value: `column->>'key'`. Composable with pipe.filter operators.

### `jsonb.json`

Extracts a JSONB value: `column->'key'`. Returns JSONB — use with jsonb.contains() etc.

### `jsonb.path`

Extracts a nested JSONB value: `column->'a'->'b'`. Returns JSONB.

### `jsonb.pathText`

Extracts a nested text value: `column->'a'->>'b'`. Intermediate keys use `->`, final uses `->>`.

### `jsonb.boolean`

Extracts a boolean: `(column->>'key')::boolean`. Supports nested paths.

### `jsonb.number`

Extracts a number: `(column->>'key')::numeric`. Supports nested paths.

### `jsonb.integer`

Extracts an integer: `(column->>'key')::integer`. Supports nested paths.

## schema — Validation & Schema

Schema definition and validation namespace — wraps zod for validation, drizzle for table/column/index definitions.

### `schema.check`

Validation sub-namespace — type constructors, combinators, formats, coerce, parse, tryParse, toJsonSchema, branded.

### `schema.col`

Column type builders for table definitions — text, uuid, integer, timestamp, jsonb, boolean, varchar, etc.

### `schema.idx`

Index and constraint builders — index, uniqueIndex, primaryKey, foreignKey, unique, check.

### Types

**`Schema`** — Any validation schema — the base type accepted by .input(), .query(), .params() in the fitting builder.

```typescript
type Schema<T = unknown> = z.ZodType<T>
```

**`Infer`** — Extracts the TypeScript type from a Schema — Infer<typeof mySchema> gives you the validated type.

```typescript
type Infer<T extends Schema> = z.infer<T>
```

## temporal — Bitemporal Data

Temporal (bitemporal) data namespace — version history with effective date ranges.

### `temporal.columns`

Returns the standard temporal column definitions (effectiveFrom, effectiveTo, version, createdBy) for table schemas.

### `temporal.revise`

Creates a new version of a temporal record, closing the previous version's effectiveTo.

### `temporal.close`

Closes a temporal record by setting effectiveTo to now. Returns number of rows affected.

### `temporal.current`

Fetches the currently-effective version of a temporal record (effectiveTo IS NULL).

### `temporal.atTime`

Returns a SQL condition for records effective at a specific point in time.

### `temporal.between`

Returns a SQL condition for records overlapping a date range.

### `temporal.TemporalIntegrityError`

Thrown when a temporal operation would violate version continuity.

### `temporal.asOf`

Query records effective at a specific date, using a domain definition with .effectiveDated() trait.

### `temporal.allVersions`

Query all versions of temporal records (no date filter).

### `temporal.effectiveUpdate`

Close the current version and create a new one with updated data.

## valve

Valve namespace — typed, directional, gated boundaries between code silos.

### `valve.supply`

Declare a handoff valve — the producer side of a payload crossing.

### `valve.gate`

Declare a transition-gate valve — the producer side of a gated state change.

### `valve.faucet`

Declare a faucet — the consumer side of a `supply -> faucet` edge.

### `valve.cross`

Decision outcome: cross the valve, delivering the payload.

### `valve.held`

Decision outcome: hold the crossing in a provisional, reviewable state.

### `valve.failed`

Decision outcome: evaluation failed — retryable, never a thrown exception.

### `valve.crossSupply`

Execute a handoff crossing in the caller's transaction (unrecorded mechanics).

### `valve.crossGate`

Execute a transition-gate crossing (unrecorded mechanics).

### `valve.executeSupplyCrossing`

Execute a handoff crossing with idempotency and provenance recording.

### `valve.executeGateCrossing`

Execute a transition-gate crossing with provenance recording.

### `valve.enqueueCrossing`

Enqueue a handoff crossing to run durably as a retried, dead-letterable job.

### `valve.runCrossingJob`

The durable-crossing job-handler body — wire into a worker.

### `valve.VALVE_CROSSING_JOB_TYPE`

Job type for a durable valve crossing.

### `valve.graph`

Assemble the directional valve graph from every registered valve and faucet.

### `valve.downstreamFaucets`

The faucet nodes a valve feeds.

### `valve.contextDependents`

The gates whose enrichment context depends on a valve.

### `valve.diffContract`

Diff a valve contract between two versions.

### `valve.emitArtifact`

Project a handoff supply to its lightweight contract artifact.

### `valve.valves`

All registered producer valves, keyed by name.

### `valve.getValve`

Look up a registered valve by name.

### `valve.faucetsOf`

The faucets consuming a named valve.

## vector — Vector & Full-Text Search

Vector and full-text search namespace — pgvector column types, similarity queries, and FTS operators.

### `vector.column`

Defines a vector(N) column for embeddings.

### `vector.tsvector`

Defines a tsvector column for full-text search.

### `vector.cosine`

Cosine distance between a column and a query vector (lower = more similar).

### `vector.cosineSimilarity`

Cosine similarity (higher = more similar) — 1 - cosineDistance.

### `vector.l2`

L2 (Euclidean) distance between a column and a query vector.

### `vector.innerProduct`

Inner product between a column and a query vector.

### `vector.toTsvector`

Converts text to a tsvector for full-text indexing.

### `vector.toTsquery`

Converts a search query string to a tsquery using to_tsquery (supports operators like &, |, !).

### `vector.plainToTsquery`

Converts natural language text to a tsquery using plainto_tsquery (no operator syntax required).

### `vector.matches`

The @@ match operator — tests whether a tsvector column matches a tsquery.

### `vector.headline`

Generates a ts_headline search snippet with highlighted matches.

### `vector.rank`

Computes ts_rank for full-text search result ordering. Accepts a pre-built tsquery SQL or a raw query string.

### `vector.validate`

Verifies the pgvector extension is installed and accessible.

## audit — Audit Logging

Audit logging namespace — structured audit trail for data changes.

### `audit.create`

Creates an Audit instance that writes audit records to a Postgres table.

### `audit.query`

Queries the framework-managed `audit_record` table. Tenant-scoped via the active Flow.

## cache — Caching

In-memory caching namespace — TTL-based with stats, preload, and tenant-aware variants.

### `cache.create`

Creates a single-key cache with TTL, a loader function, and invalidation.

### `cache.createTenant`

Creates a per-tenant cache — each tenant gets its own TTL and loader keyed by tenant ID.

## webhook — Inbound & Outbound Webhooks

Webhook namespace — inbound verification, outbound delivery with retries, HMAC signing.

### `webhook.defineInbound`

Defines an inbound webhook handler with signature verification and optional idempotency.

### `webhook.createOutbound`

Creates an outbound webhook system — endpoint registration, payload signing, delivery with retries.

### `webhook.sign`

Signs a payload with HMAC for outbound delivery — returns body, signature, timestamp, messageId.

## behavior — Resource Decorators

Resource behavior decorators — compose versioning, audit trails, and cache invalidation onto CRUD operations.

### `behavior.compose`

Applies multiple behaviors to a ResourceOperations set in order.

### `behavior.versioned`

Adds optimistic concurrency control via a version column — rejects stale updates.

### `behavior.audited`

Wraps operations to emit audit records on create/update/delete.

### `behavior.invalidate`

Wraps operations to invalidate a cache on mutations. Returns ops with an attached .cache handle.

## fitting — Dependency Injection

## fixture — REST Resources

REST resource builder namespace — declarative CRUD with cursor pagination and batch operations.

### `fixture.toHandlers`

Converts a Resource into fitted Handler[] that go through the standard handler pipeline.

### `fixture.build`

Builds a Resource from a name, operations map, and builder state — used internally by fitting().fixture().

### `fixture.encodeCursor`

Encodes pagination cursor values into an opaque base64 string.

### `fixture.decodeCursor`

Decodes an opaque pagination cursor back into its values.

### `fixture.buildPage`

Builds a PageResult from rows, limit, and cursor extractor — handles hasMore detection.

### `fixture.validateBatch`

Validates a batch request body (preview/execute mode, targets, actions).

### `fixture.MethodNotAllowedError`

Thrown when a resource doesn't support the requested HTTP method.

## flow — Context (AsyncLocalStorage)

AsyncLocalStorage context namespace — manages request/job/test contexts that carry auth, tenant, transactions.

### `flow.run`

Executes a function within a Flow context (AsyncLocalStorage). All pipe() calls inside will use this context.

### `flow.require`

Returns the current Flow or throws — use in code that must run inside a managed context.

### `flow.get`

Returns the current Flow or undefined — use for optional context detection.

### `flow.createTest`

Creates a Flow for test isolation with optional auth and tenant overrides.

## http — Server

HTTP server namespace — managed by manifold.start(), not directly accessible.

### Types

**`CorsConfig`** — CORS configuration — origin, methods, headers, credentials, maxAge.

```typescript
interface CorsConfig
```

**`SecurityConfig`** — Security header configuration — passed to @fastify/helmet.

```typescript
interface SecurityConfig
```

**`RateLimitConfig`** — Rate limiting configuration — max requests, time window, key generator.

```typescript
interface RateLimitConfig
```

**`InjectOptions`** — Options for server.inject() — method, url, headers, payload for testing without HTTP.

```typescript
interface InjectOptions
```

**`InjectResponse`** — Response from server.inject() — statusCode, headers, body, json() helper.

```typescript
interface InjectResponse
```

**`ServerConfig`** — Configuration for http.createServer() — CORS, security headers, rate limiting, transaction timeout.

```typescript
interface ServerConfig
```

**`HandlerResponse`** — Standard handler response shape — statusCode, headers, body.

```typescript
interface HandlerResponse
```

**`ErrorResponse`** — Standard error response shape — { error: { code, message }, statusCode }.

```typescript
interface ErrorResponse
```

**`PipeworkServer`** — Fastify server wrapper with route registration, handler auto-wiring, and inject() for testing.

```typescript
interface PipeworkServer
```

**`HttpRequest`** — Fastify request with pipework extensions — req.id (UUID), typed headers.

```typescript
interface HttpRequest
```

**`HttpResponse`** — Fastify reply with pipework extensions.

```typescript
interface HttpResponse
```

## openapi — API Documentation

OpenAPI spec generation namespace.

### `openapi.generate`

Generates an OpenAPI 3.1 document from route registrations — schemas derived from fitting() input/output.

## test

## data

### `tap`

Opens a standalone managed connection outside the manifold's pools — the
sanctioned door for contexts where `pipe()` structurally cannot resolve:
`worker_threads`, detached monitors, one-off scripts. Callers own the
lifecycle: always `await conn.close()`.

```typescript
function tap(url: string, options?: ConnectOptions): ManagedConnection
```

## trace

### `__flowStep`

Wraps `impl` so that, under an active traced Flow, each call records a `trace_step`.

```typescript
function __flowStep<F extends AnyFunction>(meta: FlowStepMeta, impl: F): F
```
