pipework 0.29.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1190 @@
1
+ # Pipework API Reference
2
+
3
+ > Auto-generated from source JSDoc. Do not edit manually.
4
+ > Generated: 2026-07-16
5
+
6
+ ## Contents
7
+
8
+ - [Core](#core)
9
+ - [env — Environment Variables](#env-environment-variables)
10
+ - [jobs — Background Jobs](#jobs-background-jobs)
11
+ - [pipeline — Multi-Step Pipelines](#pipeline-multi-step-pipelines)
12
+ - [state — State Machines](#state-state-machines)
13
+ - [auth — Authentication](#auth-authentication)
14
+ - [rbac — Access Control](#rbac-access-control)
15
+ - [tenant — Multi-Tenancy](#tenant-multi-tenancy)
16
+ - [config — Configuration](#config-configuration)
17
+ - [errors — Error Classes](#errors-error-classes)
18
+ - [lifecycle — Startup & Shutdown](#lifecycle-startup-shutdown)
19
+ - [log — Structured Logging](#log-structured-logging)
20
+ - [surface — Entry Points](#surface-entry-points)
21
+ - [pipe — Database](#pipe-database)
22
+ - [jsonb — JSONB Column Helpers](#jsonb-jsonb-column-helpers)
23
+ - [schema — Validation & Schema](#schema-validation-schema)
24
+ - [temporal — Bitemporal Data](#temporal-bitemporal-data)
25
+ - [valve](#valve)
26
+ - [vector — Vector & Full-Text Search](#vector-vector-full-text-search)
27
+ - [audit — Audit Logging](#audit-audit-logging)
28
+ - [cache — Caching](#cache-caching)
29
+ - [webhook — Inbound & Outbound Webhooks](#webhook-inbound-outbound-webhooks)
30
+ - [behavior — Resource Decorators](#behavior-resource-decorators)
31
+ - [fitting — Dependency Injection](#fitting-dependency-injection)
32
+ - [fixture — REST Resources](#fixture-rest-resources)
33
+ - [flow — Context (AsyncLocalStorage)](#flow-context-asynclocalstorage)
34
+ - [http — Server](#http-server)
35
+ - [openapi — API Documentation](#openapi-api-documentation)
36
+ - [test](#test)
37
+ - [data](#data)
38
+ - [trace](#trace)
39
+
40
+ ## Core
41
+
42
+ Application instance and foundational types.
43
+
44
+ ### `createManifold`
45
+
46
+ Creates the Pipework application instance. This is the entry point for every Pipework app.
47
+ Define in `pipework.config.ts` and export as default.
48
+
49
+ The `env` field declares the app's environment variables — the canonical
50
+ home for runtime config (ports, service tokens, bucket names, flags) in
51
+ place of scattered `process.env` reads. Each variable is read once at config
52
+ load, validated and coerced to its declared type (loud error on a bad or
53
+ missing-required value), and exposed typed on `manifold.env`.
54
+
55
+
56
+ ```typescript
57
+ const manifold = createManifold({
58
+ databases: { app: { url: 'DATABASE_URL', testUrl: 'DATABASE_URL_TEST' } },
59
+ env: {
60
+ PORT: { type: 'number', defaults: { development: '3000', test: '0' } },
61
+ S3_BUCKET: { type: 'string', required: true },
62
+ API_TOKEN: { type: 'string', required: true, sensitive: true },
63
+ },
64
+ })
65
+ manifold.env.PORT // number — from process.env.PORT, or the per-environment default
66
+ manifold.env.S3_BUCKET // string — startup fails loudly if unset
67
+ export default manifold
68
+ ```
69
+
70
+ ```typescript
71
+ function createManifold<const TEnv extends EnvDefs = EnvDefs>( raw: Omit<BlueprintInput, 'env'> &
72
+ ```
73
+
74
+ ### Types
75
+
76
+ **`Manifold`** — The application instance — holds config, connection pools, surfaces, and lifecycle.
77
+
78
+ ```typescript
79
+ interface Manifold<TEnv extends EnvDefs = EnvDefs>
80
+ ```
81
+
82
+ **`SeedOptions`** — ALS context the {@link Manifold.seed} callback runs under — tenant scope, auth principal, and job type.
83
+
84
+ ```typescript
85
+ interface SeedOptions
86
+ ```
87
+
88
+ **`PoolState`** — Manages database connection pools keyed by database name.
89
+
90
+ ```typescript
91
+ interface PoolState
92
+ ```
93
+
94
+ **`IsolationState`** — Tracks test isolation lifecycle — detects leaked isolation contexts.
95
+
96
+ ```typescript
97
+ interface IsolationState
98
+ ```
99
+
100
+ **`ConnectionTracker`** — Tracks active database connections for leak detection.
101
+
102
+ ```typescript
103
+ interface ConnectionTracker
104
+ ```
105
+
106
+ ## env — Environment Variables
107
+
108
+ 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.
109
+
110
+ ### Types
111
+
112
+ **`StringEnvVar`**
113
+
114
+ A string environment variable — resolved verbatim.
115
+
116
+
117
+ ```typescript
118
+ S3_BUCKET: { type: 'string', required: true }
119
+ ```
120
+
121
+ ```typescript
122
+ interface StringEnvVar extends EnvVarBase
123
+ ```
124
+
125
+ **`NumberEnvVar`**
126
+
127
+ A number environment variable — parsed with a loud error on a non-numeric value.
128
+
129
+
130
+ ```typescript
131
+ PORT: { type: 'number', default: 3000 }
132
+ ```
133
+
134
+ ```typescript
135
+ interface NumberEnvVar extends EnvVarBase
136
+ ```
137
+
138
+ **`BooleanEnvVar`**
139
+
140
+ A boolean environment variable — accepts true/false/1/0, loud error otherwise.
141
+
142
+
143
+ ```typescript
144
+ FEATURE_GRAPH: { type: 'boolean', default: false }
145
+ ```
146
+
147
+ ```typescript
148
+ interface BooleanEnvVar extends EnvVarBase
149
+ ```
150
+
151
+ **`StringArrayEnvVar`**
152
+
153
+ A string-array environment variable — the raw value split on `separator`
154
+ (default `,`), each element trimmed.
155
+
156
+
157
+ ```typescript
158
+ CORS_ORIGINS: { type: 'string[]', separator: ',', default: [] }
159
+ ```
160
+
161
+ ```typescript
162
+ interface StringArrayEnvVar extends EnvVarBase
163
+ ```
164
+
165
+ **`EnvVarDef`**
166
+
167
+ One declared environment variable: its type, whether it is required, its
168
+ fallbacks, and whether the value is sensitive. Declared under the `env`
169
+ blueprint field; resolved once at config load and exposed typed on
170
+ `manifold.env` — the canonical replacement for ad-hoc `process.env` reads.
171
+
172
+ ```typescript
173
+ type EnvVarDef = StringEnvVar | NumberEnvVar | BooleanEnvVar | StringArrayEnvVar
174
+ ```
175
+
176
+ **`EnvDefs`**
177
+
178
+ The `env` blueprint field: environment-variable declarations keyed by
179
+ variable name. Passing this map to `createManifold` is what types
180
+ `manifold.env`.
181
+
182
+
183
+ ```typescript
184
+ export default createManifold({
185
+ databases: { app: { url: 'DATABASE_URL', testUrl: 'DATABASE_URL_TEST' } },
186
+ env: {
187
+ PORT: { type: 'number', defaults: { development: '3000', test: '0' } },
188
+ S3_BUCKET: { type: 'string', required: true },
189
+ API_TOKEN: { type: 'string', required: true, sensitive: true },
190
+ CORS_ORIGINS: { type: 'string[]', default: [] },
191
+ },
192
+ })
193
+ // manifold.env.PORT → number
194
+ // manifold.env.S3_BUCKET → string
195
+ // manifold.env.CORS_ORIGINS → string[]
196
+ ```
197
+
198
+ ```typescript
199
+ type EnvDefs = Record<string, EnvVarDef>
200
+ ```
201
+
202
+ **`ResolvedEnvType`** — The resolved runtime type of one declaration: 'string' → string, 'number' → number, 'boolean' → boolean, 'string[]' → string[].
203
+
204
+ ```typescript
205
+ type ResolvedEnvType<T extends EnvVarDef> =
206
+ ```
207
+
208
+ **`ResolveEnvDefs`** — Maps a declaration map to the shape of `manifold.env` — each key typed by its declared `type`.
209
+
210
+ ```typescript
211
+ type ResolveEnvDefs<T extends EnvDefs> =
212
+ ```
213
+
214
+ ## jobs — Background Jobs
215
+
216
+ Background job queue namespace — Postgres-backed with SKIP LOCKED, LISTEN/NOTIFY, cron scheduling.
217
+
218
+ ### `jobs.createQueue`
219
+
220
+ Creates a job queue with claim/complete/fail lifecycle, heartbeat, and dead letter requeue.
221
+
222
+ ### `jobs.execute`
223
+
224
+ Executes a fitting handler as a background job with its own Flow context.
225
+
226
+ ### `jobs.parseCron`
227
+
228
+ Parses a 5-field cron expression into a CronSchedule (minute, hour, dom, month, dow).
229
+
230
+ ### `jobs.nextTick`
231
+
232
+ Computes the next fire time for a CronSchedule after a given date, with optional timezone.
233
+
234
+ ## pipeline — Multi-Step Pipelines
235
+
236
+ Multi-step pipeline namespace — define, execute, pause, and resume ordered step sequences.
237
+
238
+ ### `pipeline.define`
239
+
240
+ Defines a pipeline from a config of named steps with handlers. Returns a Pipeline with execute/resume/getStatus.
241
+
242
+ ### `pipeline.PipelineStepError`
243
+
244
+ Thrown when an individual pipeline step fails.
245
+
246
+ ### `pipeline.PipelineResumeError`
247
+
248
+ Thrown when resuming a pipeline from an invalid state.
249
+
250
+ ## state — State Machines
251
+
252
+ State machine namespace — define valid transitions with guards and side effects.
253
+
254
+ ### `state.define`
255
+
256
+ Defines a state machine from states, transitions, guards, and effects. Returns a StateMachine with transition/canTransition.
257
+
258
+ ### `state.InvalidTransitionError`
259
+
260
+ Thrown when a transition is not allowed from the current state.
261
+
262
+ ### `state.InvalidStateMachineError`
263
+
264
+ Thrown when the state machine definition is internally inconsistent.
265
+
266
+ ## auth — Authentication
267
+
268
+ Authentication namespace — session management, multi-org support, auth chain resolution.
269
+
270
+ ### `auth.createSessions`
271
+
272
+ Creates a Sessions manager with JWT access/refresh tokens, rotation, and reuse detection.
273
+
274
+ ### `auth.createMultiOrg`
275
+
276
+ Creates multi-org session management — org selection, switching, membership CRUD.
277
+
278
+ ### `auth.runChain`
279
+
280
+ Executes an auth chain (strategy pipeline) to resolve auth + tenant from a request.
281
+
282
+ ### `auth.resolveCookie`
283
+
284
+ Resolves CookieConfig with defaults for secure cookie-based token delivery.
285
+
286
+ ### `auth.parseCookie`
287
+
288
+ Parses a Cookie header string into key-value pairs.
289
+
290
+ ### `auth.buildSetCookie`
291
+
292
+ Builds a Set-Cookie header string from name, value, and CookieConfig.
293
+
294
+ ### `auth.buildClearCookie`
295
+
296
+ Builds a Set-Cookie header that clears (expires) a cookie.
297
+
298
+ ### Types
299
+
300
+ **`AuthContext`** — Runtime auth context passed to strategies — carries the resolved DB and request metadata.
301
+
302
+ ```typescript
303
+ interface AuthContext
304
+ ```
305
+
306
+ **`AuthStrategy`** — Pluggable auth strategy — implement authenticate() to extract auth from a request.
307
+
308
+ ```typescript
309
+ interface AuthStrategy<TAuth>
310
+ ```
311
+
312
+ **`AuthRequest`** — Normalized request shape passed to auth strategies — headers, cookies, method, url.
313
+
314
+ ```typescript
315
+ interface AuthRequest
316
+ ```
317
+
318
+ **`BaseAuth`** — Minimum auth shape — userId and tenantId. Extend for app-specific auth fields.
319
+
320
+ ```typescript
321
+ interface BaseAuth
322
+ ```
323
+
324
+ **`AuthEnricher`** — Post-authentication hook — enrich the resolved auth with additional data (roles, permissions, etc.).
325
+
326
+ ```typescript
327
+ interface AuthEnricher<TAuth>
328
+ ```
329
+
330
+ **`TenantResolver`** — Resolves tenant ID from auth context — called after authentication in the chain.
331
+
332
+ ```typescript
333
+ interface TenantResolver<TAuth>
334
+ ```
335
+
336
+ **`AuthChainConfig`** — Configuration for the auth chain — strategies, enrichers, tenant resolver.
337
+
338
+ ```typescript
339
+ interface AuthChainConfig<TAuth>
340
+ ```
341
+
342
+ **`SessionConfig`** — Session configuration — signing keys, issuer, audience, token TTLs, refresh rotation.
343
+
344
+ ```typescript
345
+ interface SessionConfig
346
+ ```
347
+
348
+ **`TokenPair`** — Access + refresh token pair returned by issueTokens().
349
+
350
+ ```typescript
351
+ interface TokenPair
352
+ ```
353
+
354
+ **`TokenPayload`** — Decoded JWT payload — userId, tenantId, roles, version.
355
+
356
+ ```typescript
357
+ interface TokenPayload
358
+ ```
359
+
360
+ **`HttpTokenResult`** — Result from HTTP token operations — the token pair plus whether cookies were set.
361
+
362
+ ```typescript
363
+ interface HttpTokenResult
364
+ ```
365
+
366
+ **`Sessions`** — Session manager with JWT issue/refresh/revoke lifecycle and cookie-based HTTP helpers.
367
+
368
+ ```typescript
369
+ interface Sessions
370
+ ```
371
+
372
+ **`CookieConfig`** — Cookie configuration for token delivery — name, domain, path, secure, sameSite, httpOnly.
373
+
374
+ ```typescript
375
+ interface CookieConfig
376
+ ```
377
+
378
+ **`MultiOrgConfig`** — Configuration for multi-org sessions — base sessions, signing keys, org-select token TTL.
379
+
380
+ ```typescript
381
+ interface MultiOrgConfig
382
+ ```
383
+
384
+ **`OrgMembership`** — A user's membership in an organization — userId, orgId, role.
385
+
386
+ ```typescript
387
+ interface OrgMembership
388
+ ```
389
+
390
+ **`OrgInfo`** — Basic organization info — id and display name.
391
+
392
+ ```typescript
393
+ interface OrgInfo
394
+ ```
395
+
396
+ **`OrgMembershipDetail`** — Organization membership with display name — extends OrgMembership with org info.
397
+
398
+ ```typescript
399
+ interface OrgMembershipDetail
400
+ ```
401
+
402
+ **`AuthenticatedResult`** — Result when user has exactly one org — direct authentication, no org selection needed.
403
+
404
+ ```typescript
405
+ interface AuthenticatedResult
406
+ ```
407
+
408
+ **`OrgSelectResult`** — Result when user has multiple orgs — returns a session token for org selection.
409
+
410
+ ```typescript
411
+ interface OrgSelectResult
412
+ ```
413
+
414
+ **`ResolveLoginResult`** — Union result from resolveLogin() — either AuthenticatedResult or OrgSelectResult.
415
+
416
+ ```typescript
417
+ type ResolveLoginResult = AuthenticatedResult | OrgSelectResult
418
+ ```
419
+
420
+ **`MultiOrgSessions`** — Multi-org session manager — login resolution, org selection, switching, membership CRUD.
421
+
422
+ ```typescript
423
+ interface MultiOrgSessions
424
+ ```
425
+
426
+ ## rbac — Access Control
427
+
428
+ Role-based access control namespace — permission checking, enforcement, scope hierarchy.
429
+
430
+ ### `rbac.create`
431
+
432
+ Creates an Rbac instance from config (roles, permissions, hierarchy).
433
+
434
+ ### `rbac.check`
435
+
436
+ Checks if a permission set includes the required resource/action/scope. Pure function, no DB.
437
+
438
+ ### `rbac.enforce`
439
+
440
+ Checks permission and throws ForbiddenError if denied. Loads permissions from DB with caching.
441
+
442
+ ### `rbac.satisfies`
443
+
444
+ Checks if a granted scope satisfies a required scope given a hierarchy (e.g. org > team > self).
445
+
446
+ ### `rbac.PermissionCache`
447
+
448
+ LRU cache for resolved permissions — avoids repeated DB lookups within a request.
449
+
450
+ ## tenant — Multi-Tenancy
451
+
452
+ Multi-tenant isolation namespace — RLS policies, tenant extraction, Postgres-side verification.
453
+
454
+ ### `tenant.validate`
455
+
456
+ Validates a tenant ID format (non-empty string, safe characters).
457
+
458
+ ### `tenant.rls`
459
+
460
+ Enables RLS on a table and creates the tenant isolation policy in Postgres.
461
+
462
+ ### `tenant.policy`
463
+
464
+ Returns the SQL string for a tenant isolation RLS policy — use in migrations.
465
+
466
+ ### `tenant.verify`
467
+
468
+ Cross-checks the ALS principal (tenant, user, asOf) against the Postgres session GUCs — defense-in-depth.
469
+
470
+ ### `tenant.propagate`
471
+
472
+ Sets pipework.tenant_id on the Postgres connection via set_config().
473
+
474
+ ### `tenant.extract`
475
+
476
+ Extracts tenant ID from auth context using the configured extraction strategy.
477
+
478
+ ### `tenant.isTenantScoped`
479
+
480
+ Returns true if a table has been marked as tenant-scoped (via .tenant() field metadata).
481
+
482
+ ## config — Configuration
483
+
484
+ Configuration namespace — loads and resolves Blueprint configs, discovers pipework.config.ts.
485
+
486
+ ### `config.load`
487
+
488
+ Parses and resolves a raw Blueprint into a ResolvedConfig with environment detection.
489
+
490
+ ### `config.discover`
491
+
492
+ Walks up from cwd to find pipework.config.ts, imports it, and returns the Manifold.
493
+
494
+ ### `config.configSchema`
495
+
496
+ The zod schema for Blueprint validation — useful for custom config tooling.
497
+
498
+ ### `config.ConfigError`
499
+
500
+ Thrown for configuration problems — includes a suggestion for how to fix.
501
+
502
+ ## errors — Error Classes
503
+
504
+ Standard error classes — all extend PipeworkError with structured error codes and actionable messages.
505
+
506
+ ### `errors.Base`
507
+
508
+ Base error class with code, statusCode, and suggestion fields.
509
+
510
+ ### `errors.NotFound`
511
+
512
+ 404 — resource not found.
513
+
514
+ ### `errors.Unauthorized`
515
+
516
+ 401 — missing or invalid authentication.
517
+
518
+ ### `errors.Forbidden`
519
+
520
+ 403 — authenticated but insufficient permissions.
521
+
522
+ ### `errors.Validation`
523
+
524
+ 422 — input validation failed, carries field-level details.
525
+
526
+ ### `errors.Conflict`
527
+
528
+ 409 — resource state conflict (duplicate, version mismatch).
529
+
530
+ ## lifecycle — Startup & Shutdown
531
+
532
+ Application lifecycle namespace — startup orchestration with hooks and timeouts.
533
+
534
+ ### `lifecycle.orchestrate`
535
+
536
+ Runs pre-start hooks (DB readiness checks, migrations, etc.) with a configurable timeout.
537
+
538
+ ## log — Structured Logging
539
+
540
+ Structured logger (Pino) — auto-binds requestId, tenantId, userId, sessionId from ALS context on every log call.
541
+
542
+ ### `log.create`
543
+
544
+ Creates a new PipeworkLogger instance with custom config (level, redaction, transport).
545
+
546
+ ### `log.get`
547
+
548
+ Returns the context-aware logger proxy (same as the log export itself).
549
+
550
+ ### `log.getBase`
551
+
552
+ Returns the raw Pino logger without ALS context binding.
553
+
554
+ ### `log.configure`
555
+
556
+ Sets global logging config (level, redaction paths, custom context fields).
557
+
558
+ ### `log.REDACT_PATHS`
559
+
560
+ Default redaction paths — password, secret, token, authorization, cookie, etc.
561
+
562
+ ## surface — Entry Points
563
+
564
+ Surface namespace — declarative entry points that define how the app runs (HTTP server, background worker, one-shot script).
565
+
566
+ ### `surface.http`
567
+
568
+ 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.
569
+
570
+ ### `surface.worker`
571
+
572
+ Creates a worker surface — a long-running process that claims and executes jobs from queues.
573
+
574
+ ### `surface.script`
575
+
576
+ Creates a script surface — a one-shot process that runs and exits (migrations, seeds, CLI tools).
577
+
578
+ ## pipe — Database
579
+
580
+ Database accessor — returns a Drizzle DB instance scoped to the current request/job/test context. Requires active AsyncLocalStorage context.
581
+
582
+ ### `pipe.system`
583
+
584
+ 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.
585
+
586
+ ### `pipe.filter`
587
+
588
+ Query operators and aggregates — eq, gt, lt, and, or, count, sum, etc.
589
+
590
+ ### `pipe.aliasedRelation`
591
+
592
+
593
+ ### `pipe.aliasedTable`
594
+
595
+
596
+ ### `pipe.aliasedTableColumn`
597
+
598
+
599
+ ### `pipe.getTableColumns`
600
+
601
+
602
+ ### `pipe.getTableName`
603
+
604
+
605
+ ### `pipe.getViewName`
606
+
607
+
608
+ ### `pipe.getViewSelectedFields`
609
+
610
+
611
+ ### `pipe.isTable`
612
+
613
+
614
+ ### `pipe.createMany`
615
+
616
+
617
+ ### `pipe.createOne`
618
+
619
+
620
+ ### `pipe.relations`
621
+
622
+
623
+ ### `pipe.migrate`
624
+
625
+ Runs migrations for all configured databases.
626
+
627
+ ### `pipe.migrateOne`
628
+
629
+ Runs migrations for a single named database.
630
+
631
+ ### `pipe.excluded`
632
+
633
+ Returns excluded-column references for onConflictDoUpdate set clauses.
634
+
635
+ ### `pipe.advisoryLock`
636
+
637
+ Acquires a transaction-scoped advisory lock. Released at commit/rollback.
638
+
639
+ ### `pipe.serializable`
640
+
641
+ Runs a function in a SERIALIZABLE transaction with automatic retry on serialization failures and deadlocks.
642
+
643
+ ### `pipe.bulkSet`
644
+
645
+ Bulk UPDATE ... FROM (VALUES ...) — updates multiple rows with per-row values in a single statement.
646
+
647
+ ### `pipe.values`
648
+
649
+ Produces a typed VALUES clause for bulk operations — the base primitive for bulkSet and bulkUpsert.
650
+
651
+ ### `pipe.field`
652
+
653
+ Field builders for domain definitions — uuid(), text(), integer(), etc.
654
+
655
+ ### `pipe.define`
656
+
657
+ Registers a domain definition with table, validators, and factory projections.
658
+
659
+ ### `pipe.definitions`
660
+
661
+ Returns the global registry of all domain definitions.
662
+
663
+ ### `pipe.update`
664
+
665
+ Pipework-owned UPDATE builder — the only consumer-facing way to update pipework-managed tables (Q8).
666
+
667
+ ### `pipe.insert`
668
+
669
+ Pipework-owned INSERT builder — the only consumer-facing way to insert into pipework-managed tables (Q8).
670
+
671
+ ### `pipe.delete`
672
+
673
+ Pipework-owned DELETE builder — the only consumer-facing way to delete from pipework-managed tables (Q8).
674
+
675
+ ### `pipe.upsert`
676
+
677
+ Pipework-owned UPSERT builder — insert with conflict resolution (Q8).
678
+
679
+ ### Types
680
+
681
+ **`WindowSpec`** — A window-frame specification — the `PARTITION BY` / `ORDER BY` clauses applied by {@link over}.
682
+
683
+ ```typescript
684
+ interface WindowSpec
685
+ ```
686
+
687
+ **`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}.
688
+
689
+ ```typescript
690
+ interface ValueColumnDef
691
+ ```
692
+
693
+ **`SerializableOptions`** — Retry policy for {@link serializable}: how many attempts on a serialization failure / deadlock, and the base backoff between them.
694
+
695
+ ```typescript
696
+ interface SerializableOptions
697
+ ```
698
+
699
+ **`ManagedConnection`** — A standalone pooled connection: the raw postgres.js client, its drizzle handle, and a `close()` that ends the pool.
700
+
701
+ ```typescript
702
+ interface ManagedConnection
703
+ ```
704
+
705
+ **`ConnectOptions`** — Options for `tap()` — pool size (default 1) and idle timeout in seconds.
706
+
707
+ ```typescript
708
+ interface ConnectOptions
709
+ ```
710
+
711
+ ## jsonb — JSONB Column Helpers
712
+
713
+ JSONB query operators — typed helpers for PostgreSQL JSONB containment, key checks, and field extraction.
714
+
715
+ ### `jsonb.contains`
716
+
717
+ The @> containment operator — tests whether a JSONB column contains the given value.
718
+
719
+ ### `jsonb.containedBy`
720
+
721
+ The <@ contained-by operator — tests whether a JSONB column is contained by the given value.
722
+
723
+ ### `jsonb.hasKey`
724
+
725
+ The ? key-existence operator — tests whether a JSONB column has the given top-level key.
726
+
727
+ ### `jsonb.text`
728
+
729
+ Extracts a text value: `column->>'key'`. Composable with pipe.filter operators.
730
+
731
+ ### `jsonb.json`
732
+
733
+ Extracts a JSONB value: `column->'key'`. Returns JSONB — use with jsonb.contains() etc.
734
+
735
+ ### `jsonb.path`
736
+
737
+ Extracts a nested JSONB value: `column->'a'->'b'`. Returns JSONB.
738
+
739
+ ### `jsonb.pathText`
740
+
741
+ Extracts a nested text value: `column->'a'->>'b'`. Intermediate keys use `->`, final uses `->>`.
742
+
743
+ ### `jsonb.boolean`
744
+
745
+ Extracts a boolean: `(column->>'key')::boolean`. Supports nested paths.
746
+
747
+ ### `jsonb.number`
748
+
749
+ Extracts a number: `(column->>'key')::numeric`. Supports nested paths.
750
+
751
+ ### `jsonb.integer`
752
+
753
+ Extracts an integer: `(column->>'key')::integer`. Supports nested paths.
754
+
755
+ ## schema — Validation & Schema
756
+
757
+ Schema definition and validation namespace — wraps zod for validation, drizzle for table/column/index definitions.
758
+
759
+ ### `schema.check`
760
+
761
+ Validation sub-namespace — type constructors, combinators, formats, coerce, parse, tryParse, toJsonSchema, branded.
762
+
763
+ ### `schema.col`
764
+
765
+ Column type builders for table definitions — text, uuid, integer, timestamp, jsonb, boolean, varchar, etc.
766
+
767
+ ### `schema.idx`
768
+
769
+ Index and constraint builders — index, uniqueIndex, primaryKey, foreignKey, unique, check.
770
+
771
+ ### Types
772
+
773
+ **`Schema`** — Any validation schema — the base type accepted by .input(), .query(), .params() in the fitting builder.
774
+
775
+ ```typescript
776
+ type Schema<T = unknown> = z.ZodType<T>
777
+ ```
778
+
779
+ **`Infer`** — Extracts the TypeScript type from a Schema — Infer<typeof mySchema> gives you the validated type.
780
+
781
+ ```typescript
782
+ type Infer<T extends Schema> = z.infer<T>
783
+ ```
784
+
785
+ ## temporal — Bitemporal Data
786
+
787
+ Temporal (bitemporal) data namespace — version history with effective date ranges.
788
+
789
+ ### `temporal.columns`
790
+
791
+ Returns the standard temporal column definitions (effectiveFrom, effectiveTo, version, createdBy) for table schemas.
792
+
793
+ ### `temporal.revise`
794
+
795
+ Creates a new version of a temporal record, closing the previous version's effectiveTo.
796
+
797
+ ### `temporal.close`
798
+
799
+ Closes a temporal record by setting effectiveTo to now. Returns number of rows affected.
800
+
801
+ ### `temporal.current`
802
+
803
+ Fetches the currently-effective version of a temporal record (effectiveTo IS NULL).
804
+
805
+ ### `temporal.atTime`
806
+
807
+ Returns a SQL condition for records effective at a specific point in time.
808
+
809
+ ### `temporal.between`
810
+
811
+ Returns a SQL condition for records overlapping a date range.
812
+
813
+ ### `temporal.TemporalIntegrityError`
814
+
815
+ Thrown when a temporal operation would violate version continuity.
816
+
817
+ ### `temporal.asOf`
818
+
819
+ Query records effective at a specific date, using a domain definition with .effectiveDated() trait.
820
+
821
+ ### `temporal.allVersions`
822
+
823
+ Query all versions of temporal records (no date filter).
824
+
825
+ ### `temporal.effectiveUpdate`
826
+
827
+ Close the current version and create a new one with updated data.
828
+
829
+ ## valve
830
+
831
+ Valve namespace — typed, directional, gated boundaries between code silos.
832
+
833
+ ### `valve.supply`
834
+
835
+ Declare a handoff valve — the producer side of a payload crossing.
836
+
837
+ ### `valve.gate`
838
+
839
+ Declare a transition-gate valve — the producer side of a gated state change.
840
+
841
+ ### `valve.faucet`
842
+
843
+ Declare a faucet — the consumer side of a `supply -> faucet` edge.
844
+
845
+ ### `valve.cross`
846
+
847
+ Decision outcome: cross the valve, delivering the payload.
848
+
849
+ ### `valve.held`
850
+
851
+ Decision outcome: hold the crossing in a provisional, reviewable state.
852
+
853
+ ### `valve.failed`
854
+
855
+ Decision outcome: evaluation failed — retryable, never a thrown exception.
856
+
857
+ ### `valve.crossSupply`
858
+
859
+ Execute a handoff crossing in the caller's transaction (unrecorded mechanics).
860
+
861
+ ### `valve.crossGate`
862
+
863
+ Execute a transition-gate crossing (unrecorded mechanics).
864
+
865
+ ### `valve.executeSupplyCrossing`
866
+
867
+ Execute a handoff crossing with idempotency and provenance recording.
868
+
869
+ ### `valve.executeGateCrossing`
870
+
871
+ Execute a transition-gate crossing with provenance recording.
872
+
873
+ ### `valve.enqueueCrossing`
874
+
875
+ Enqueue a handoff crossing to run durably as a retried, dead-letterable job.
876
+
877
+ ### `valve.runCrossingJob`
878
+
879
+ The durable-crossing job-handler body — wire into a worker.
880
+
881
+ ### `valve.VALVE_CROSSING_JOB_TYPE`
882
+
883
+ Job type for a durable valve crossing.
884
+
885
+ ### `valve.graph`
886
+
887
+ Assemble the directional valve graph from every registered valve and faucet.
888
+
889
+ ### `valve.downstreamFaucets`
890
+
891
+ The faucet nodes a valve feeds.
892
+
893
+ ### `valve.contextDependents`
894
+
895
+ The gates whose enrichment context depends on a valve.
896
+
897
+ ### `valve.diffContract`
898
+
899
+ Diff a valve contract between two versions.
900
+
901
+ ### `valve.emitArtifact`
902
+
903
+ Project a handoff supply to its lightweight contract artifact.
904
+
905
+ ### `valve.valves`
906
+
907
+ All registered producer valves, keyed by name.
908
+
909
+ ### `valve.getValve`
910
+
911
+ Look up a registered valve by name.
912
+
913
+ ### `valve.faucetsOf`
914
+
915
+ The faucets consuming a named valve.
916
+
917
+ ## vector — Vector & Full-Text Search
918
+
919
+ Vector and full-text search namespace — pgvector column types, similarity queries, and FTS operators.
920
+
921
+ ### `vector.column`
922
+
923
+ Defines a vector(N) column for embeddings.
924
+
925
+ ### `vector.tsvector`
926
+
927
+ Defines a tsvector column for full-text search.
928
+
929
+ ### `vector.cosine`
930
+
931
+ Cosine distance between a column and a query vector (lower = more similar).
932
+
933
+ ### `vector.cosineSimilarity`
934
+
935
+ Cosine similarity (higher = more similar) — 1 - cosineDistance.
936
+
937
+ ### `vector.l2`
938
+
939
+ L2 (Euclidean) distance between a column and a query vector.
940
+
941
+ ### `vector.innerProduct`
942
+
943
+ Inner product between a column and a query vector.
944
+
945
+ ### `vector.toTsvector`
946
+
947
+ Converts text to a tsvector for full-text indexing.
948
+
949
+ ### `vector.toTsquery`
950
+
951
+ Converts a search query string to a tsquery using to_tsquery (supports operators like &, |, !).
952
+
953
+ ### `vector.plainToTsquery`
954
+
955
+ Converts natural language text to a tsquery using plainto_tsquery (no operator syntax required).
956
+
957
+ ### `vector.matches`
958
+
959
+ The @@ match operator — tests whether a tsvector column matches a tsquery.
960
+
961
+ ### `vector.headline`
962
+
963
+ Generates a ts_headline search snippet with highlighted matches.
964
+
965
+ ### `vector.rank`
966
+
967
+ Computes ts_rank for full-text search result ordering. Accepts a pre-built tsquery SQL or a raw query string.
968
+
969
+ ### `vector.validate`
970
+
971
+ Verifies the pgvector extension is installed and accessible.
972
+
973
+ ## audit — Audit Logging
974
+
975
+ Audit logging namespace — structured audit trail for data changes.
976
+
977
+ ### `audit.create`
978
+
979
+ Creates an Audit instance that writes audit records to a Postgres table.
980
+
981
+ ### `audit.query`
982
+
983
+ Queries the framework-managed `audit_record` table. Tenant-scoped via the active Flow.
984
+
985
+ ## cache — Caching
986
+
987
+ In-memory caching namespace — TTL-based with stats, preload, and tenant-aware variants.
988
+
989
+ ### `cache.create`
990
+
991
+ Creates a single-key cache with TTL, a loader function, and invalidation.
992
+
993
+ ### `cache.createTenant`
994
+
995
+ Creates a per-tenant cache — each tenant gets its own TTL and loader keyed by tenant ID.
996
+
997
+ ## webhook — Inbound & Outbound Webhooks
998
+
999
+ Webhook namespace — inbound verification, outbound delivery with retries, HMAC signing.
1000
+
1001
+ ### `webhook.defineInbound`
1002
+
1003
+ Defines an inbound webhook handler with signature verification and optional idempotency.
1004
+
1005
+ ### `webhook.createOutbound`
1006
+
1007
+ Creates an outbound webhook system — endpoint registration, payload signing, delivery with retries.
1008
+
1009
+ ### `webhook.sign`
1010
+
1011
+ Signs a payload with HMAC for outbound delivery — returns body, signature, timestamp, messageId.
1012
+
1013
+ ## behavior — Resource Decorators
1014
+
1015
+ Resource behavior decorators — compose versioning, audit trails, and cache invalidation onto CRUD operations.
1016
+
1017
+ ### `behavior.compose`
1018
+
1019
+ Applies multiple behaviors to a ResourceOperations set in order.
1020
+
1021
+ ### `behavior.versioned`
1022
+
1023
+ Adds optimistic concurrency control via a version column — rejects stale updates.
1024
+
1025
+ ### `behavior.audited`
1026
+
1027
+ Wraps operations to emit audit records on create/update/delete.
1028
+
1029
+ ### `behavior.invalidate`
1030
+
1031
+ Wraps operations to invalidate a cache on mutations. Returns ops with an attached .cache handle.
1032
+
1033
+ ## fitting — Dependency Injection
1034
+
1035
+ ## fixture — REST Resources
1036
+
1037
+ REST resource builder namespace — declarative CRUD with cursor pagination and batch operations.
1038
+
1039
+ ### `fixture.toHandlers`
1040
+
1041
+ Converts a Resource into fitted Handler[] that go through the standard handler pipeline.
1042
+
1043
+ ### `fixture.build`
1044
+
1045
+ Builds a Resource from a name, operations map, and builder state — used internally by fitting().fixture().
1046
+
1047
+ ### `fixture.encodeCursor`
1048
+
1049
+ Encodes pagination cursor values into an opaque base64 string.
1050
+
1051
+ ### `fixture.decodeCursor`
1052
+
1053
+ Decodes an opaque pagination cursor back into its values.
1054
+
1055
+ ### `fixture.buildPage`
1056
+
1057
+ Builds a PageResult from rows, limit, and cursor extractor — handles hasMore detection.
1058
+
1059
+ ### `fixture.validateBatch`
1060
+
1061
+ Validates a batch request body (preview/execute mode, targets, actions).
1062
+
1063
+ ### `fixture.MethodNotAllowedError`
1064
+
1065
+ Thrown when a resource doesn't support the requested HTTP method.
1066
+
1067
+ ## flow — Context (AsyncLocalStorage)
1068
+
1069
+ AsyncLocalStorage context namespace — manages request/job/test contexts that carry auth, tenant, transactions.
1070
+
1071
+ ### `flow.run`
1072
+
1073
+ Executes a function within a Flow context (AsyncLocalStorage). All pipe() calls inside will use this context.
1074
+
1075
+ ### `flow.require`
1076
+
1077
+ Returns the current Flow or throws — use in code that must run inside a managed context.
1078
+
1079
+ ### `flow.get`
1080
+
1081
+ Returns the current Flow or undefined — use for optional context detection.
1082
+
1083
+ ### `flow.createTest`
1084
+
1085
+ Creates a Flow for test isolation with optional auth and tenant overrides.
1086
+
1087
+ ## http — Server
1088
+
1089
+ HTTP server namespace — managed by manifold.start(), not directly accessible.
1090
+
1091
+ ### Types
1092
+
1093
+ **`CorsConfig`** — CORS configuration — origin, methods, headers, credentials, maxAge.
1094
+
1095
+ ```typescript
1096
+ interface CorsConfig
1097
+ ```
1098
+
1099
+ **`SecurityConfig`** — Security header configuration — passed to @fastify/helmet.
1100
+
1101
+ ```typescript
1102
+ interface SecurityConfig
1103
+ ```
1104
+
1105
+ **`RateLimitConfig`** — Rate limiting configuration — max requests, time window, key generator.
1106
+
1107
+ ```typescript
1108
+ interface RateLimitConfig
1109
+ ```
1110
+
1111
+ **`InjectOptions`** — Options for server.inject() — method, url, headers, payload for testing without HTTP.
1112
+
1113
+ ```typescript
1114
+ interface InjectOptions
1115
+ ```
1116
+
1117
+ **`InjectResponse`** — Response from server.inject() — statusCode, headers, body, json() helper.
1118
+
1119
+ ```typescript
1120
+ interface InjectResponse
1121
+ ```
1122
+
1123
+ **`ServerConfig`** — Configuration for http.createServer() — CORS, security headers, rate limiting, transaction timeout.
1124
+
1125
+ ```typescript
1126
+ interface ServerConfig
1127
+ ```
1128
+
1129
+ **`HandlerResponse`** — Standard handler response shape — statusCode, headers, body.
1130
+
1131
+ ```typescript
1132
+ interface HandlerResponse
1133
+ ```
1134
+
1135
+ **`ErrorResponse`** — Standard error response shape — { error: { code, message }, statusCode }.
1136
+
1137
+ ```typescript
1138
+ interface ErrorResponse
1139
+ ```
1140
+
1141
+ **`PipeworkServer`** — Fastify server wrapper with route registration, handler auto-wiring, and inject() for testing.
1142
+
1143
+ ```typescript
1144
+ interface PipeworkServer
1145
+ ```
1146
+
1147
+ **`HttpRequest`** — Fastify request with pipework extensions — req.id (UUID), typed headers.
1148
+
1149
+ ```typescript
1150
+ interface HttpRequest
1151
+ ```
1152
+
1153
+ **`HttpResponse`** — Fastify reply with pipework extensions.
1154
+
1155
+ ```typescript
1156
+ interface HttpResponse
1157
+ ```
1158
+
1159
+ ## openapi — API Documentation
1160
+
1161
+ OpenAPI spec generation namespace.
1162
+
1163
+ ### `openapi.generate`
1164
+
1165
+ Generates an OpenAPI 3.1 document from route registrations — schemas derived from fitting() input/output.
1166
+
1167
+ ## test
1168
+
1169
+ ## data
1170
+
1171
+ ### `tap`
1172
+
1173
+ Opens a standalone managed connection outside the manifold's pools — the
1174
+ sanctioned door for contexts where `pipe()` structurally cannot resolve:
1175
+ `worker_threads`, detached monitors, one-off scripts. Callers own the
1176
+ lifecycle: always `await conn.close()`.
1177
+
1178
+ ```typescript
1179
+ function tap(url: string, options?: ConnectOptions): ManagedConnection
1180
+ ```
1181
+
1182
+ ## trace
1183
+
1184
+ ### `__flowStep`
1185
+
1186
+ Wraps `impl` so that, under an active traced Flow, each call records a `trace_step`.
1187
+
1188
+ ```typescript
1189
+ function __flowStep<F extends AnyFunction>(meta: FlowStepMeta, impl: F): F
1190
+ ```