pipework 0.84.0 → 0.84.1

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,1477 @@
1
+ # Pipework API Reference
2
+
3
+ > Auto-generated from source JSDoc. Do not edit manually.
4
+ > Generated: 2026-10-09
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
+ - [accessLinks](#accesslinks)
28
+ - [alerts](#alerts)
29
+ - [audit — Audit Logging](#audit-audit-logging)
30
+ - [cache — Caching](#cache-caching)
31
+ - [credits](#credits)
32
+ - [mail](#mail)
33
+ - [storage](#storage)
34
+ - [webhook — Inbound & Outbound Webhooks](#webhook-inbound-outbound-webhooks)
35
+ - [behavior — Resource Decorators](#behavior-resource-decorators)
36
+ - [fitting — Dependency Injection](#fitting-dependency-injection)
37
+ - [fixture — REST Resources](#fixture-rest-resources)
38
+ - [flow — Context (AsyncLocalStorage)](#flow-context-asynclocalstorage)
39
+ - [http — Server](#http-server)
40
+ - [openapi — API Documentation](#openapi-api-documentation)
41
+ - [test](#test)
42
+ - [trace](#trace)
43
+ - [data](#data)
44
+ - [request](#request)
45
+
46
+ ## Core
47
+
48
+ Application instance and foundational types.
49
+
50
+ ### `createManifold`
51
+
52
+ Creates the Pipework application instance. This is the entry point for every Pipework app.
53
+ Define in `pipework.config.ts` and export as default.
54
+
55
+ The `env` field declares the app's environment variables — the canonical
56
+ home for runtime config (ports, service tokens, bucket names, flags) in
57
+ place of scattered `process.env` reads. Each variable is read once at config
58
+ load, validated and coerced to its declared type (loud error on a bad or
59
+ missing-required value), and exposed typed on `manifold.env`.
60
+
61
+
62
+ ```typescript
63
+ const manifold = createManifold({
64
+ databases: { app: { url: 'DATABASE_URL', testUrl: 'DATABASE_URL_TEST' } },
65
+ env: {
66
+ PORT: { type: 'number', defaults: { development: '3000', test: '0' } },
67
+ S3_BUCKET: { type: 'string', required: true },
68
+ API_TOKEN: { type: 'string', required: true, sensitive: true },
69
+ },
70
+ })
71
+ manifold.env.PORT // number — from process.env.PORT, or the per-environment default
72
+ manifold.env.S3_BUCKET // string — startup fails loudly if unset
73
+ export default manifold
74
+ ```
75
+
76
+ ```typescript
77
+ function createManifold<const TEnv extends EnvDefs = EnvDefs>( raw: Omit<BlueprintInput, 'env'> &
78
+ ```
79
+
80
+ ### Types
81
+
82
+ **`Manifold`** — The application instance — holds config, connection pools, surfaces, and lifecycle.
83
+
84
+ ```typescript
85
+ interface Manifold<TEnv extends EnvDefs = EnvDefs>
86
+ ```
87
+
88
+ **`SeedOptions`** — ALS context the {@link Manifold.seed} callback runs under — tenant scope, auth principal, and job type.
89
+
90
+ ```typescript
91
+ interface SeedOptions
92
+ ```
93
+
94
+ **`PoolState`** — Manages database connection pools keyed by database name.
95
+
96
+ ```typescript
97
+ interface PoolState
98
+ ```
99
+
100
+ **`IsolationState`** — Tracks test isolation lifecycle — detects leaked isolation contexts.
101
+
102
+ ```typescript
103
+ interface IsolationState
104
+ ```
105
+
106
+ **`ConnectionTracker`** — Tracks active database connections for leak detection.
107
+
108
+ ```typescript
109
+ interface ConnectionTracker
110
+ ```
111
+
112
+ ## env — Environment Variables
113
+
114
+ 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.
115
+
116
+ ### Types
117
+
118
+ **`StringEnvVar`**
119
+
120
+ A string environment variable — resolved verbatim.
121
+
122
+
123
+ ```typescript
124
+ S3_BUCKET: { type: 'string', required: true }
125
+ ```
126
+
127
+ ```typescript
128
+ interface StringEnvVar extends EnvVarBase
129
+ ```
130
+
131
+ **`NumberEnvVar`**
132
+
133
+ A number environment variable — parsed with a loud error on a non-numeric value.
134
+
135
+
136
+ ```typescript
137
+ PORT: { type: 'number', default: 3000 }
138
+ ```
139
+
140
+ ```typescript
141
+ interface NumberEnvVar extends EnvVarBase
142
+ ```
143
+
144
+ **`BooleanEnvVar`**
145
+
146
+ A boolean environment variable — accepts true/false/1/0, loud error otherwise.
147
+
148
+
149
+ ```typescript
150
+ FEATURE_GRAPH: { type: 'boolean', default: false }
151
+ ```
152
+
153
+ ```typescript
154
+ interface BooleanEnvVar extends EnvVarBase
155
+ ```
156
+
157
+ **`StringArrayEnvVar`**
158
+
159
+ A string-array environment variable — the raw value split on `separator`
160
+ (default `,`), each element trimmed.
161
+
162
+
163
+ ```typescript
164
+ CORS_ORIGINS: { type: 'string[]', separator: ',', default: [] }
165
+ ```
166
+
167
+ ```typescript
168
+ interface StringArrayEnvVar extends EnvVarBase
169
+ ```
170
+
171
+ **`EnvVarDef`**
172
+
173
+ One declared environment variable: its type, whether it is required, its
174
+ fallbacks, and whether the value is sensitive. Declared under the `env`
175
+ blueprint field; resolved once at config load and exposed typed on
176
+ `manifold.env` — the canonical replacement for ad-hoc `process.env` reads.
177
+
178
+ ```typescript
179
+ type EnvVarDef = StringEnvVar | NumberEnvVar | BooleanEnvVar | StringArrayEnvVar
180
+ ```
181
+
182
+ **`EnvDefs`**
183
+
184
+ The `env` blueprint field: environment-variable declarations keyed by
185
+ variable name. Passing this map to `createManifold` is what types
186
+ `manifold.env`.
187
+
188
+
189
+ ```typescript
190
+ export default createManifold({
191
+ databases: { app: { url: 'DATABASE_URL', testUrl: 'DATABASE_URL_TEST' } },
192
+ env: {
193
+ PORT: { type: 'number', defaults: { development: '3000', test: '0' } },
194
+ S3_BUCKET: { type: 'string', required: true },
195
+ API_TOKEN: { type: 'string', required: true, sensitive: true },
196
+ CORS_ORIGINS: { type: 'string[]', default: [] },
197
+ },
198
+ })
199
+ // manifold.env.PORT → number
200
+ // manifold.env.S3_BUCKET → string
201
+ // manifold.env.CORS_ORIGINS → string[]
202
+ ```
203
+
204
+ ```typescript
205
+ type EnvDefs = Record<string, EnvVarDef>
206
+ ```
207
+
208
+ **`ResolvedEnvType`** — The resolved runtime type of one declaration: 'string' → string, 'number' → number, 'boolean' → boolean, 'string[]' → string[].
209
+
210
+ ```typescript
211
+ type ResolvedEnvType<T extends EnvVarDef> =
212
+ ```
213
+
214
+ **`ResolveEnvDefs`** — Maps a declaration map to the shape of `manifold.env` — each key typed by its declared `type`.
215
+
216
+ ```typescript
217
+ type ResolveEnvDefs<T extends EnvDefs> =
218
+ ```
219
+
220
+ ## jobs — Background Jobs
221
+
222
+ Background job queue namespace — Postgres-backed with SKIP LOCKED, LISTEN/NOTIFY, cron scheduling.
223
+
224
+ ### `jobs.createQueue`
225
+
226
+ Creates a job queue with claim/complete/fail lifecycle, heartbeat, and dead letter requeue.
227
+
228
+ ### `jobs.execute`
229
+
230
+ Executes a fitting handler as a background job with its own Flow context.
231
+
232
+ ### `jobs.parseCron`
233
+
234
+ Parses a 5-field cron expression into a CronSchedule (minute, hour, dom, month, dow).
235
+
236
+ ### `jobs.nextTick`
237
+
238
+ Computes the next fire time for a CronSchedule after a given date, with optional timezone.
239
+
240
+ ## pipeline — Multi-Step Pipelines
241
+
242
+ Multi-step pipeline namespace — define, execute, pause, and resume ordered step sequences.
243
+
244
+ ### `pipeline.define`
245
+
246
+ Defines a pipeline from a config of named steps with handlers. Returns a Pipeline with execute/resume/getStatus.
247
+
248
+ ### `pipeline.PipelineStepError`
249
+
250
+ Thrown when an individual pipeline step fails.
251
+
252
+ ### `pipeline.PipelineResumeError`
253
+
254
+ Thrown when resuming a pipeline from an invalid state.
255
+
256
+ ## state — State Machines
257
+
258
+ State machine namespace — define valid transitions with guards and side effects.
259
+
260
+ ### `state.define`
261
+
262
+ Defines a state machine from states, transitions, guards, and effects. Returns a StateMachine with transition/canTransition.
263
+
264
+ ### `state.InvalidTransitionError`
265
+
266
+ Thrown when a transition is not allowed from the current state.
267
+
268
+ ### `state.InvalidStateMachineError`
269
+
270
+ Thrown when the state machine definition is internally inconsistent.
271
+
272
+ ## auth — Authentication
273
+
274
+ Authentication namespace — session management, multi-org support, auth chain resolution.
275
+
276
+ ### `auth.createSessions`
277
+
278
+ Creates a Sessions manager with JWT access/refresh tokens, rotation, and reuse detection.
279
+
280
+ ### `auth.createMultiOrg`
281
+
282
+ Creates multi-org session management — org selection, switching, membership CRUD.
283
+
284
+ ### `auth.passwords`
285
+
286
+ Hashes and verifies passwords with scrypt; reports when a stored hash needs rehashing.
287
+
288
+ ### `auth.signIn`
289
+
290
+ Guarded password sign-in that slows, then refuses, repeated failures per account and per client.
291
+
292
+ ### `auth.runChain`
293
+
294
+ Executes an auth chain (strategy pipeline) to resolve auth + tenant from a request.
295
+
296
+ ### `auth.resolveCookie`
297
+
298
+ Resolves CookieConfig with defaults for secure cookie-based token delivery.
299
+
300
+ ### `auth.parseCookie`
301
+
302
+ Parses a Cookie header string into key-value pairs.
303
+
304
+ ### `auth.buildSetCookie`
305
+
306
+ Builds a Set-Cookie header string from name, value, and CookieConfig.
307
+
308
+ ### `auth.buildClearCookie`
309
+
310
+ Builds a Set-Cookie header that clears (expires) a cookie.
311
+
312
+ ### Types
313
+
314
+ **`AuthContext`** — Runtime auth context passed to strategies — carries the resolved DB and request metadata.
315
+
316
+ ```typescript
317
+ interface AuthContext
318
+ ```
319
+
320
+ **`AuthStrategy`** — Pluggable auth strategy — implement authenticate() to extract auth from a request.
321
+
322
+ ```typescript
323
+ interface AuthStrategy<TAuth>
324
+ ```
325
+
326
+ **`AuthRequest`** — Normalized request shape passed to auth strategies — headers, cookies, method, url.
327
+
328
+ ```typescript
329
+ interface AuthRequest
330
+ ```
331
+
332
+ **`BaseAuth`** — Minimum auth shape — userId and tenantId. Extend for app-specific auth fields.
333
+
334
+ ```typescript
335
+ interface BaseAuth
336
+ ```
337
+
338
+ **`AuthEnricher`** — Post-authentication hook — enrich the resolved auth with additional data (roles, permissions, etc.).
339
+
340
+ ```typescript
341
+ interface AuthEnricher<TAuth>
342
+ ```
343
+
344
+ **`TenantResolver`** — Resolves tenant ID from auth context — called after authentication in the chain.
345
+
346
+ ```typescript
347
+ interface TenantResolver<TAuth>
348
+ ```
349
+
350
+ **`AuthChainConfig`** — Configuration for the auth chain — strategies, enrichers, tenant resolver.
351
+
352
+ ```typescript
353
+ interface AuthChainConfig<TAuth>
354
+ ```
355
+
356
+ **`SessionConfig`** — Session configuration — signing keys, issuer, audience, token TTLs, refresh rotation.
357
+
358
+ ```typescript
359
+ interface SessionConfig
360
+ ```
361
+
362
+ **`TokenPair`** — Access + refresh token pair returned by issueTokens().
363
+
364
+ ```typescript
365
+ interface TokenPair
366
+ ```
367
+
368
+ **`TokenPayload`** — Decoded JWT payload — userId, tenantId, roles, version.
369
+
370
+ ```typescript
371
+ interface TokenPayload
372
+ ```
373
+
374
+ **`HttpTokenResult`** — Result from HTTP token operations — the token pair plus whether cookies were set.
375
+
376
+ ```typescript
377
+ interface HttpTokenResult
378
+ ```
379
+
380
+ **`Sessions`** — Session manager with JWT issue/refresh/revoke lifecycle and cookie-based HTTP helpers.
381
+
382
+ ```typescript
383
+ interface Sessions
384
+ ```
385
+
386
+ **`CookieConfig`** — Cookie configuration for token delivery — name, domain, path, secure, sameSite, httpOnly.
387
+
388
+ ```typescript
389
+ interface CookieConfig
390
+ ```
391
+
392
+ **`ScryptParams`**
393
+
394
+ ```typescript
395
+ interface ScryptParams
396
+ ```
397
+
398
+ **`PasswordsConfig`**
399
+
400
+ ```typescript
401
+ interface PasswordsConfig
402
+ ```
403
+
404
+ **`VerifyResult`**
405
+
406
+ ```typescript
407
+ interface VerifyResult
408
+ ```
409
+
410
+ **`Passwords`**
411
+
412
+ ```typescript
413
+ interface Passwords
414
+ ```
415
+
416
+ **`SignInConfig`**
417
+
418
+ ```typescript
419
+ interface SignInConfig
420
+ ```
421
+
422
+ **`SignInAttempt`**
423
+
424
+ ```typescript
425
+ interface SignInAttempt
426
+ ```
427
+
428
+ **`SignInResult`**
429
+
430
+ ```typescript
431
+ type SignInResult =
432
+ ```
433
+
434
+ **`SignIn`**
435
+
436
+ ```typescript
437
+ interface SignIn
438
+ ```
439
+
440
+ **`MultiOrgConfig`** — Configuration for multi-org sessions — base sessions, signing keys, org-select token TTL.
441
+
442
+ ```typescript
443
+ interface MultiOrgConfig
444
+ ```
445
+
446
+ **`OrgMembership`** — A user's membership in an organization — userId, orgId, role.
447
+
448
+ ```typescript
449
+ interface OrgMembership
450
+ ```
451
+
452
+ **`OrgInfo`** — Basic organization info — id and display name.
453
+
454
+ ```typescript
455
+ interface OrgInfo
456
+ ```
457
+
458
+ **`OrgMembershipDetail`** — Organization membership with display name — extends OrgMembership with org info.
459
+
460
+ ```typescript
461
+ interface OrgMembershipDetail
462
+ ```
463
+
464
+ **`AuthenticatedResult`** — Result when user has exactly one org — direct authentication, no org selection needed.
465
+
466
+ ```typescript
467
+ interface AuthenticatedResult
468
+ ```
469
+
470
+ **`OrgSelectResult`** — Result when user has multiple orgs — returns a session token for org selection.
471
+
472
+ ```typescript
473
+ interface OrgSelectResult
474
+ ```
475
+
476
+ **`ResolveLoginResult`** — Union result from resolveLogin() — either AuthenticatedResult or OrgSelectResult.
477
+
478
+ ```typescript
479
+ type ResolveLoginResult = AuthenticatedResult | OrgSelectResult
480
+ ```
481
+
482
+ **`MultiOrgSessions`** — Multi-org session manager — login resolution, org selection, switching, membership CRUD.
483
+
484
+ ```typescript
485
+ interface MultiOrgSessions
486
+ ```
487
+
488
+ ## rbac — Access Control
489
+
490
+ Role-based access control namespace — permission checking, enforcement, scope hierarchy.
491
+
492
+ ### `rbac.create`
493
+
494
+ Creates an Rbac instance from config (roles, permissions, hierarchy).
495
+
496
+ ### `rbac.check`
497
+
498
+ Checks if a permission set includes the required resource/action/scope. Pure function, no DB.
499
+
500
+ ### `rbac.enforce`
501
+
502
+ Checks permission and throws ForbiddenError if denied. Loads permissions from DB with caching.
503
+
504
+ ### `rbac.satisfies`
505
+
506
+ Checks if a granted scope satisfies a required scope given a hierarchy (e.g. org > team > self).
507
+
508
+ ### `rbac.PermissionCache`
509
+
510
+ LRU cache for resolved permissions — avoids repeated DB lookups within a request.
511
+
512
+ ## tenant — Multi-Tenancy
513
+
514
+ Multi-tenant isolation namespace — RLS policies, tenant extraction, Postgres-side verification.
515
+
516
+ ### `tenant.validate`
517
+
518
+ Validates a tenant ID format (non-empty string, safe characters).
519
+
520
+ ### `tenant.rls`
521
+
522
+ Enables RLS on a table and creates the tenant isolation policy in Postgres.
523
+
524
+ ### `tenant.policy`
525
+
526
+ Returns the SQL string for a tenant isolation RLS policy — use in migrations.
527
+
528
+ ### `tenant.verify`
529
+
530
+ Cross-checks the ALS principal (tenant, user, asOf) against the Postgres session GUCs — defense-in-depth.
531
+
532
+ ### `tenant.propagate`
533
+
534
+ Sets pipework.tenant_id on the Postgres connection via set_config().
535
+
536
+ ### `tenant.extract`
537
+
538
+ Extracts tenant ID from auth context using the configured extraction strategy.
539
+
540
+ ### `tenant.isTenantScoped`
541
+
542
+ Returns true if a table has been marked as tenant-scoped (via .tenant() field metadata).
543
+
544
+ ## config — Configuration
545
+
546
+ Configuration namespace — loads and resolves Blueprint configs, discovers pipework.config.ts.
547
+
548
+ ### `config.load`
549
+
550
+ Parses and resolves a raw Blueprint into a ResolvedConfig with environment detection.
551
+
552
+ ### `config.discover`
553
+
554
+ Walks up from cwd to find pipework.config.ts, imports it, and returns the Manifold.
555
+
556
+ ### `config.configSchema`
557
+
558
+ The zod schema for Blueprint validation — useful for custom config tooling.
559
+
560
+ ### `config.ConfigError`
561
+
562
+ Thrown for configuration problems — includes a suggestion for how to fix.
563
+
564
+ ### Types
565
+
566
+ **`StatementEvent`**
567
+
568
+ One statement as it is handed to the driver for writing to the wire —
569
+ including the transaction-control statements the driver issues on its own
570
+ (`BEGIN`, `SAVEPOINT`, `COMMIT`, `ROLLBACK`), which no application-level hook
571
+ can see.
572
+
573
+ ```typescript
574
+ interface StatementEvent
575
+ ```
576
+
577
+ **`StatementObserver`**
578
+
579
+ Caller-supplied per-statement observer. Fires once per statement written to
580
+ the wire, on every connection the manifold owns — pooled connections and the
581
+ test harness's own connections alike.
582
+
583
+ Pure observation: the return value is discarded and the statement is never
584
+ mutated. It runs synchronously on the driver's write path, so it must be
585
+ cheap and must not throw.
586
+
587
+ Counts wire truth, not application intent. Two consequences worth knowing
588
+ before you assert on a total: the driver issues its own transaction control
589
+ (`BEGIN`/`SAVEPOINT`/`COMMIT`/`ROLLBACK`), and it issues one `pg_catalog.pg_type`
590
+ lookup per connection the first time that connection is used.
591
+
592
+ Adds no leak surface. Installing an observer requires turning on the driver's
593
+ `debug` hook, which would otherwise start serializing bind parameters onto
594
+ every query error; pipework's driver error boundary puts those errors back to
595
+ their unobserved shape, so **every statement path pipework mediates —
596
+ `pipe()`, every `pipe.*` write, `connection.drizzle`, transactions and
597
+ savepoints — exposes exactly what it exposed before**. The single exception
598
+ is the raw `ManagedConnection.client` door: queries issued through it are
599
+ outside the boundary and their errors do serialize bind parameters. Reading
600
+ `.client` on an observed connection logs a warning saying so, once per
601
+ database.
602
+
603
+ ```typescript
604
+ type StatementObserver = (event: StatementEvent) => void
605
+ ```
606
+
607
+ ## errors — Error Classes
608
+
609
+ Standard error classes — all extend PipeworkError with structured error codes and actionable messages.
610
+
611
+ ### `errors.Base`
612
+
613
+ Base error class with code, statusCode, and suggestion fields.
614
+
615
+ ### `errors.NotFound`
616
+
617
+ 404 — resource not found.
618
+
619
+ ### `errors.Unauthorized`
620
+
621
+ 401 — missing or invalid authentication.
622
+
623
+ ### `errors.Forbidden`
624
+
625
+ 403 — authenticated but insufficient permissions.
626
+
627
+ ### `errors.Validation`
628
+
629
+ 422 — input validation failed, carries field-level details.
630
+
631
+ ### `errors.Conflict`
632
+
633
+ 409 — resource state conflict (duplicate, version mismatch).
634
+
635
+ ### `errors.TooManyRequests`
636
+
637
+ 429 — too many attempts; carries `retryAfterSeconds`, sent as a `Retry-After` header.
638
+
639
+ ### `errors.PayloadTooLarge`
640
+
641
+ 413 — request body over the route's size limit.
642
+
643
+ ### `errors.UnsupportedMediaType`
644
+
645
+ 415 — request body media type not accepted by the route.
646
+
647
+ ## lifecycle — Startup & Shutdown
648
+
649
+ Application lifecycle namespace — startup orchestration with hooks and timeouts.
650
+
651
+ ### `lifecycle.orchestrate`
652
+
653
+ Runs pre-start hooks (DB readiness checks, migrations, etc.) with a configurable timeout.
654
+
655
+ ## log — Structured Logging
656
+
657
+ Structured logger (Pino) — auto-binds requestId, tenantId, userId, sessionId from ALS context on every log call.
658
+
659
+ ### `log.create`
660
+
661
+ Creates a new PipeworkLogger instance with custom config (level, redaction, transport).
662
+
663
+ ### `log.get`
664
+
665
+ Returns the context-aware logger proxy (same as the log export itself).
666
+
667
+ ### `log.getBase`
668
+
669
+ Returns the raw Pino logger without ALS context binding.
670
+
671
+ ### `log.configure`
672
+
673
+ Sets global logging config (level, redaction paths, custom context fields).
674
+
675
+ ### `log.REDACT_PATHS`
676
+
677
+ Default redaction paths — password, secret, token, authorization, cookie, etc.
678
+
679
+ ## surface — Entry Points
680
+
681
+ Surface namespace — declarative entry points that define how the app runs (HTTP server, background worker, one-shot script).
682
+
683
+ ### `surface.http`
684
+
685
+ 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.
686
+
687
+ ### `surface.worker`
688
+
689
+ Creates a worker surface — a long-running process that claims and executes jobs from queues.
690
+
691
+ ### `surface.script`
692
+
693
+ Creates a script surface — a one-shot process that runs and exits (migrations, seeds, CLI tools).
694
+
695
+ ## pipe — Database
696
+
697
+ Database accessor — returns a Drizzle DB instance scoped to the current request/job/test context. Requires active AsyncLocalStorage context.
698
+
699
+ ### `pipe.system`
700
+
701
+ 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.
702
+
703
+ ### `pipe.filter`
704
+
705
+ Query operators and aggregates — eq, gt, lt, and, or, count, sum, etc.
706
+
707
+ ### `pipe.sql`
708
+
709
+ Raw statement tag — for a statement pipework does not model. Interpolated values are parameters; `sql.raw` is not. Runs on the caller's connection, so inside a request it is the request transaction. Writes still go through pipe.update / insert / delete, which is what audit hooks.
710
+
711
+ ### `pipe.aliasedRelation`
712
+
713
+
714
+ ### `pipe.aliasedTable`
715
+
716
+
717
+ ### `pipe.aliasedTableColumn`
718
+
719
+
720
+ ### `pipe.getTableColumns`
721
+
722
+
723
+ ### `pipe.getTableName`
724
+
725
+
726
+ ### `pipe.getViewName`
727
+
728
+
729
+ ### `pipe.getViewSelectedFields`
730
+
731
+
732
+ ### `pipe.isTable`
733
+
734
+
735
+ ### `pipe.createMany`
736
+
737
+
738
+ ### `pipe.createOne`
739
+
740
+
741
+ ### `pipe.relations`
742
+
743
+
744
+ ### `pipe.migrate`
745
+
746
+ Runs migrations for all configured databases.
747
+
748
+ ### `pipe.migrateOne`
749
+
750
+ Runs migrations for a single named database.
751
+
752
+ ### `pipe.excluded`
753
+
754
+ Returns excluded-column references for onConflictDoUpdate set clauses.
755
+
756
+ ### `pipe.advisoryLock`
757
+
758
+ Acquires a transaction-scoped advisory lock. Released at commit/rollback.
759
+
760
+ ### `pipe.serializable`
761
+
762
+ Runs a function in a SERIALIZABLE transaction with automatic retry on serialization failures and deadlocks.
763
+
764
+ ### `pipe.bulkSet`
765
+
766
+ Bulk UPDATE ... FROM (VALUES ...) — updates multiple rows with per-row values in a single statement.
767
+
768
+ ### `pipe.values`
769
+
770
+ Produces a typed VALUES clause for bulk operations — the base primitive for bulkSet and bulkUpsert.
771
+
772
+ ### `pipe.field`
773
+
774
+ Field builders for domain definitions — uuid(), text(), integer(), etc.
775
+
776
+ ### `pipe.define`
777
+
778
+ Registers a domain definition with table, validators, and factory projections. The `auditEntity` option names the `@touches` entity writes to this table are audited under (see `__flowStep`).
779
+
780
+ ### `pipe.definitions`
781
+
782
+ Returns the global registry of all domain definitions.
783
+
784
+ ### `pipe.update`
785
+
786
+ Pipework-owned UPDATE builder — the only consumer-facing way to update pipework-managed tables (Q8).
787
+
788
+ ### `pipe.insert`
789
+
790
+ Pipework-owned INSERT builder — the only consumer-facing way to insert into pipework-managed tables (Q8).
791
+
792
+ ### `pipe.delete`
793
+
794
+ Pipework-owned DELETE builder — the only consumer-facing way to delete from pipework-managed tables (Q8).
795
+
796
+ ### `pipe.upsert`
797
+
798
+ Pipework-owned UPSERT builder — insert with conflict resolution (Q8).
799
+
800
+ ### Types
801
+
802
+ **`WindowSpec`** — A window-frame specification — the `PARTITION BY` / `ORDER BY` clauses applied by {@link over}.
803
+
804
+ ```typescript
805
+ interface WindowSpec
806
+ ```
807
+
808
+ **`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}.
809
+
810
+ ```typescript
811
+ interface ValueColumnDef
812
+ ```
813
+
814
+ **`SerializableOptions`** — Retry policy for {@link serializable}: how many attempts on a serialization failure / deadlock, and the base backoff between them.
815
+
816
+ ```typescript
817
+ interface SerializableOptions
818
+ ```
819
+
820
+ **`ManagedConnection`** — A standalone pooled connection: the raw postgres.js client, its drizzle handle, and a `close()` that ends the pool.
821
+
822
+ ```typescript
823
+ interface ManagedConnection
824
+ ```
825
+
826
+ **`ConnectOptions`** — Options for `tap()` — pool size (default 1) and idle timeout in seconds.
827
+
828
+ ```typescript
829
+ interface ConnectOptions
830
+ ```
831
+
832
+ ## jsonb — JSONB Column Helpers
833
+
834
+ JSONB query operators — typed helpers for PostgreSQL JSONB containment, key checks, and field extraction.
835
+
836
+ ### `jsonb.contains`
837
+
838
+ The @> containment operator — tests whether a JSONB column contains the given value.
839
+
840
+ ### `jsonb.containedBy`
841
+
842
+ The <@ contained-by operator — tests whether a JSONB column is contained by the given value.
843
+
844
+ ### `jsonb.hasKey`
845
+
846
+ The ? key-existence operator — tests whether a JSONB column has the given top-level key.
847
+
848
+ ### `jsonb.text`
849
+
850
+ Extracts a text value: `column->>'key'`. Composable with pipe.filter operators.
851
+
852
+ ### `jsonb.json`
853
+
854
+ Extracts a JSONB value: `column->'key'`. Returns JSONB — use with jsonb.contains() etc.
855
+
856
+ ### `jsonb.path`
857
+
858
+ Extracts a nested JSONB value: `column->'a'->'b'`. Returns JSONB.
859
+
860
+ ### `jsonb.pathText`
861
+
862
+ Extracts a nested text value: `column->'a'->>'b'`. Intermediate keys use `->`, final uses `->>`.
863
+
864
+ ### `jsonb.boolean`
865
+
866
+ Extracts a boolean: `(column->>'key')::boolean`. Supports nested paths.
867
+
868
+ ### `jsonb.number`
869
+
870
+ Extracts a number: `(column->>'key')::numeric`. Supports nested paths.
871
+
872
+ ### `jsonb.integer`
873
+
874
+ Extracts an integer: `(column->>'key')::integer`. Supports nested paths.
875
+
876
+ ## schema — Validation & Schema
877
+
878
+ Schema definition and validation namespace — wraps zod for validation, drizzle for table/column/index definitions.
879
+
880
+ ### `schema.check`
881
+
882
+ Validation sub-namespace — type constructors, combinators, formats, coerce, parse, tryParse, toJsonSchema, branded.
883
+
884
+ ### `schema.col`
885
+
886
+ Column type builders for table definitions — text, uuid, integer, timestamp, jsonb, boolean, varchar, etc.
887
+
888
+ ### `schema.idx`
889
+
890
+ Index and constraint builders — index, uniqueIndex, primaryKey, foreignKey, unique, check.
891
+
892
+ ### Types
893
+
894
+ **`Schema`** — Any validation schema — the base type accepted by .input(), .query(), .params() in the fitting builder.
895
+
896
+ ```typescript
897
+ type Schema<T = unknown> = z.ZodType<T>
898
+ ```
899
+
900
+ **`Infer`** — Extracts the TypeScript type from a Schema — Infer<typeof mySchema> gives you the validated type.
901
+
902
+ ```typescript
903
+ type Infer<T extends Schema> = z.infer<T>
904
+ ```
905
+
906
+ ## temporal — Bitemporal Data
907
+
908
+ Temporal (bitemporal) data namespace — version history with effective date ranges.
909
+
910
+ ### `temporal.columns`
911
+
912
+ Returns the standard temporal column definitions (effectiveFrom, effectiveTo, version, createdBy) for table schemas.
913
+
914
+ ### `temporal.revise`
915
+
916
+ Creates a new version of a temporal record, closing the previous version's effectiveTo.
917
+
918
+ ### `temporal.close`
919
+
920
+ Closes a temporal record by setting effectiveTo to now. Returns number of rows affected.
921
+
922
+ ### `temporal.current`
923
+
924
+ Fetches the currently-effective version of a temporal record (effectiveTo IS NULL).
925
+
926
+ ### `temporal.atTime`
927
+
928
+ Returns a SQL condition for records effective at a specific point in time.
929
+
930
+ ### `temporal.between`
931
+
932
+ Returns a SQL condition for records overlapping a date range.
933
+
934
+ ### `temporal.TemporalIntegrityError`
935
+
936
+ Thrown when a temporal operation would violate version continuity.
937
+
938
+ ### `temporal.asOf`
939
+
940
+ Query records effective at a specific date, using a domain definition with .effectiveDated() trait.
941
+
942
+ ### `temporal.allVersions`
943
+
944
+ Query all versions of temporal records (no date filter).
945
+
946
+ ### `temporal.effectiveUpdate`
947
+
948
+ Close the current version and create a new one with updated data.
949
+
950
+ ## valve
951
+
952
+ Valve namespace — typed, directional, gated boundaries between code silos.
953
+
954
+ ### `valve.supply`
955
+
956
+ Declare a handoff valve — the producer side of a payload crossing.
957
+
958
+ ### `valve.gate`
959
+
960
+ Declare a transition-gate valve — the producer side of a gated state change.
961
+
962
+ ### `valve.faucet`
963
+
964
+ Declare a faucet — the consumer side of a `supply -> faucet` edge.
965
+
966
+ ### `valve.cross`
967
+
968
+ Decision outcome: cross the valve, delivering the payload.
969
+
970
+ ### `valve.held`
971
+
972
+ Decision outcome: hold the crossing in a provisional, reviewable state.
973
+
974
+ ### `valve.failed`
975
+
976
+ Decision outcome: evaluation failed — retryable, never a thrown exception.
977
+
978
+ ### `valve.crossSupply`
979
+
980
+ Execute a handoff crossing in the caller's transaction (unrecorded mechanics).
981
+
982
+ ### `valve.crossGate`
983
+
984
+ Execute a transition-gate crossing (unrecorded mechanics).
985
+
986
+ ### `valve.executeSupplyCrossing`
987
+
988
+ Execute a handoff crossing with idempotency and provenance recording.
989
+
990
+ ### `valve.executeGateCrossing`
991
+
992
+ Execute a transition-gate crossing with provenance recording.
993
+
994
+ ### `valve.enqueueCrossing`
995
+
996
+ Enqueue a handoff crossing to run durably as a retried, dead-letterable job.
997
+
998
+ ### `valve.runCrossingJob`
999
+
1000
+ The durable-crossing job-handler body — wire into a worker.
1001
+
1002
+ ### `valve.VALVE_CROSSING_JOB_TYPE`
1003
+
1004
+ Job type for a durable valve crossing.
1005
+
1006
+ ### `valve.graph`
1007
+
1008
+ Assemble the directional valve graph from every registered valve and faucet.
1009
+
1010
+ ### `valve.downstreamFaucets`
1011
+
1012
+ The faucet nodes a valve feeds.
1013
+
1014
+ ### `valve.contextDependents`
1015
+
1016
+ The gates whose enrichment context depends on a valve.
1017
+
1018
+ ### `valve.diffContract`
1019
+
1020
+ Diff a valve contract between two versions.
1021
+
1022
+ ### `valve.emitArtifact`
1023
+
1024
+ Project a handoff supply to its lightweight contract artifact.
1025
+
1026
+ ### `valve.valves`
1027
+
1028
+ All registered producer valves, keyed by name.
1029
+
1030
+ ### `valve.getValve`
1031
+
1032
+ Look up a registered valve by name.
1033
+
1034
+ ### `valve.faucetsOf`
1035
+
1036
+ The faucets consuming a named valve.
1037
+
1038
+ ## vector — Vector & Full-Text Search
1039
+
1040
+ Vector and full-text search namespace — pgvector column types, similarity queries, and FTS operators.
1041
+
1042
+ ### `vector.column`
1043
+
1044
+ Defines a vector(N) column for embeddings.
1045
+
1046
+ ### `vector.tsvector`
1047
+
1048
+ Defines a tsvector column for full-text search.
1049
+
1050
+ ### `vector.cosine`
1051
+
1052
+ Cosine distance between a column and a query vector (lower = more similar).
1053
+
1054
+ ### `vector.cosineSimilarity`
1055
+
1056
+ Cosine similarity (higher = more similar) — 1 - cosineDistance.
1057
+
1058
+ ### `vector.l2`
1059
+
1060
+ L2 (Euclidean) distance between a column and a query vector.
1061
+
1062
+ ### `vector.innerProduct`
1063
+
1064
+ Inner product between a column and a query vector.
1065
+
1066
+ ### `vector.toTsvector`
1067
+
1068
+ Converts text to a tsvector for full-text indexing.
1069
+
1070
+ ### `vector.toTsquery`
1071
+
1072
+ Converts a search query string to a tsquery using to_tsquery (supports operators like &, |, !).
1073
+
1074
+ ### `vector.plainToTsquery`
1075
+
1076
+ Converts natural language text to a tsquery using plainto_tsquery (no operator syntax required).
1077
+
1078
+ ### `vector.matches`
1079
+
1080
+ The @@ match operator — tests whether a tsvector column matches a tsquery.
1081
+
1082
+ ### `vector.headline`
1083
+
1084
+ Generates a ts_headline search snippet with highlighted matches.
1085
+
1086
+ ### `vector.rank`
1087
+
1088
+ Computes ts_rank for full-text search result ordering. Accepts a pre-built tsquery SQL or a raw query string.
1089
+
1090
+ ### `vector.validate`
1091
+
1092
+ Verifies the pgvector extension is installed and accessible.
1093
+
1094
+ ## accessLinks
1095
+
1096
+ Access links namespace — short revocable bearer links to a tenant's resource.
1097
+
1098
+ ### `accessLinks.create`
1099
+
1100
+ Creates an access-link handle: tenant-scoped management plus the public resolve / beginUse / completeUse / abandonUse.
1101
+
1102
+ ### `accessLinks.personCheck`
1103
+
1104
+ A self-hosted person check for `requireChecks`: ALTCHA-format proof-of-work challenges bound to a link code
1105
+ and an expiry, HMAC-signed with `secret` (32 bytes or more, the same in every process). A solution is accepted
1106
+ once across all processes (`access_link_check_spent`, in the `accessLinks` tables) and yields a short-lived
1107
+ signed pass that is the proof for the link's check at `beginUse`. `personCheck.solve(challenge)` solves a
1108
+ challenge in code, for tests.
1109
+
1110
+ The app writes two public routes: GET returns `check.challenge(code)` for the widget (`challengeurl`, or
1111
+ `challengejson`); POST gives `check.verify(code, payload)` the widget's payload and returns the pass, or refuses
1112
+ when it is `null`. The page carries the ALTCHA widget (MIT; serve its script yourself, no third party sees the
1113
+ visitor), which solves in the background and falls back to a keyboard and screen-reader checkbox. pipework
1114
+ does not ship the widget.
1115
+
1116
+ ```ts
1117
+ const person = accessLinks.personCheck({ secret: config.linkSecret })
1118
+ const links = accessLinks.create({ permissions: ['view'], checks: { person: person.check } })
1119
+ await links.link({ target, permissions: ['view'], requireChecks: ['person'] })
1120
+ // public route: begin with the pass the visitor got from POST
1121
+ await links.beginUse(code, { kind: 'view', proof: { person: pass } })
1122
+ ```
1123
+
1124
+ ## alerts
1125
+
1126
+ Alerts namespace — raise and resolve keyed conditions, grouped, delivered to sinks through an outbox, traced.
1127
+
1128
+ ### `alerts.create`
1129
+
1130
+ Creates an alerts handle.
1131
+
1132
+ ### `alerts.webhook`
1133
+
1134
+ A sink that POSTs the alert as signed JSON to a URL.
1135
+
1136
+ ### `alerts.memory`
1137
+
1138
+ A sink that keeps deliveries in `.delivered`, for tests.
1139
+
1140
+ ## audit — Audit Logging
1141
+
1142
+ Audit logging namespace — structured audit trail for data changes.
1143
+
1144
+ ### `audit.create`
1145
+
1146
+ Creates an Audit instance that writes audit records to a Postgres table.
1147
+
1148
+ ### `audit.query`
1149
+
1150
+ Queries the framework-managed `audit_record` table. Tenant-scoped via the active Flow. `{ entity, entityId }` returns one row's history from an index; build a composite key's `entityId` with `audit.entityId`.
1151
+
1152
+ ### `audit.entityId`
1153
+
1154
+ The `entityId` filter text for a written table's row: the primary key's value as text, or for a composite key a compact JSON array of the key values as strings in key order (`["a","7"]`). Pass the table and a row (or just its key fields). Dates become ISO strings.
1155
+
1156
+ ### `audit.chainHead`
1157
+
1158
+ The newest record's `{ seq, hash }` in the tenant's audit hash chain (blueprint `audit.chain`), to store outside the database; `null` when empty.
1159
+
1160
+ ### `audit.verify`
1161
+
1162
+ Walks the tenant's audit hash chain and reports the first break (hash-mismatch, prev-mismatch, missing, head-mismatch, anchor-mismatch), or `{ ok: true }`.
1163
+
1164
+ ## cache — Caching
1165
+
1166
+ In-memory caching namespace — TTL-based with stats, preload, and tenant-aware variants.
1167
+
1168
+ ### `cache.create`
1169
+
1170
+ Creates a single-key cache with TTL, a loader function, and invalidation.
1171
+
1172
+ ### `cache.createTenant`
1173
+
1174
+ Creates a per-tenant cache — each tenant gets its own TTL and loader keyed by tenant ID.
1175
+
1176
+ ## credits
1177
+
1178
+ Credits namespace — prepaid usage credits per tenant: expiring grants, reserve / settle / release by job.
1179
+
1180
+ ### `credits.create`
1181
+
1182
+ Creates a credits handle.
1183
+
1184
+ ## mail
1185
+
1186
+ Mail namespace — email through a job queue, SES v2 or a dev stand-in, bounce and complaint suppression, and receiving.
1187
+
1188
+ ### `mail.create`
1189
+
1190
+ Creates the mail interface: `send(db, { to, template, data, key })` in the caller's transaction, and the `jobs` that deliver.
1191
+
1192
+ ### `mail.ses`
1193
+
1194
+ Amazon SES v2 provider, SigV4-signed without the AWS SDK.
1195
+
1196
+ ### `mail.devStandIn`
1197
+
1198
+ Development provider that writes each message to a file instead of sending; refused in production.
1199
+
1200
+ ### `mail.snsWebhook`
1201
+
1202
+ Inbound handler for SES bounce and complaint events delivered through SNS; suppresses the address.
1203
+
1204
+ ### `mail.inbound`
1205
+
1206
+ Receiving email: `inbound({ source, queue, onMessage, ... })` returns `{ webhook, jobs, scan, sweep, get }`; messages arrive parsed, threaded into conversations, attachments stored as tenant files.
1207
+
1208
+ ### `mail.sesReceipt`
1209
+
1210
+ Inbound source: SES receipt rule storing raw messages in S3 and notifying a signed SNS topic.
1211
+
1212
+ ### `mail.inboundFolder`
1213
+
1214
+ Inbound development source: `.eml` files dropped in a folder, received by `scan()`; refused in production.
1215
+
1216
+ ## storage
1217
+
1218
+ Storage namespace — tenant-scoped, content-addressed file storage with signed URLs and retention.
1219
+
1220
+ ### `storage.create`
1221
+
1222
+ Creates a storage handle over a backend.
1223
+
1224
+ ### `storage.s3`
1225
+
1226
+ S3-compatible backend (AWS S3, MinIO, R2): SigV4 over `fetch`, multipart streaming upload, optional server-side encryption.
1227
+
1228
+ ### `storage.local`
1229
+
1230
+ Local-disk backend for development and tests; refused in production.
1231
+
1232
+ ## webhook — Inbound & Outbound Webhooks
1233
+
1234
+ Webhook namespace — inbound verification, outbound delivery with retries, HMAC signing.
1235
+
1236
+ ### `webhook.defineInbound`
1237
+
1238
+ Defines an inbound webhook handler with signature verification and optional idempotency.
1239
+
1240
+ ### `webhook.createOutbound`
1241
+
1242
+ Creates an outbound webhook system — endpoint registration, payload signing, delivery with retries.
1243
+
1244
+ ### `webhook.sign`
1245
+
1246
+ Signs a payload with HMAC for outbound delivery — returns body, signature, timestamp, messageId.
1247
+
1248
+ ## behavior — Resource Decorators
1249
+
1250
+ Resource behavior decorators — compose versioning, audit trails, and cache invalidation onto CRUD operations.
1251
+
1252
+ ### `behavior.compose`
1253
+
1254
+ Applies multiple behaviors to a ResourceOperations set in order.
1255
+
1256
+ ### `behavior.versioned`
1257
+
1258
+ Adds optimistic concurrency control via a version column — rejects stale updates.
1259
+
1260
+ ### `behavior.audited`
1261
+
1262
+ Wraps operations to emit audit records on create/update/delete.
1263
+
1264
+ ### `behavior.invalidate`
1265
+
1266
+ Wraps operations to invalidate a cache on mutations. Returns ops with an attached .cache handle.
1267
+
1268
+ ## fitting — Dependency Injection
1269
+
1270
+ ## fixture — REST Resources
1271
+
1272
+ REST resource builder namespace — declarative CRUD with cursor pagination and batch operations.
1273
+
1274
+ ### `fixture.toHandlers`
1275
+
1276
+ Converts a Resource into fitted Handler[] that go through the standard handler pipeline.
1277
+
1278
+ ### `fixture.build`
1279
+
1280
+ Builds a Resource from a name, operations map, and builder state — used internally by fitting().fixture().
1281
+
1282
+ ### `fixture.encodeCursor`
1283
+
1284
+ Encodes pagination cursor values into an opaque base64 string.
1285
+
1286
+ ### `fixture.decodeCursor`
1287
+
1288
+ Decodes an opaque pagination cursor back into its values.
1289
+
1290
+ ### `fixture.buildPage`
1291
+
1292
+ Builds a PageResult from rows, limit, and cursor extractor — handles hasMore detection.
1293
+
1294
+ ### `fixture.validateBatch`
1295
+
1296
+ Validates a batch request body (preview/execute mode, targets, actions).
1297
+
1298
+ ### `fixture.MethodNotAllowedError`
1299
+
1300
+ Thrown when a resource doesn't support the requested HTTP method.
1301
+
1302
+ ## flow — Context (AsyncLocalStorage)
1303
+
1304
+ AsyncLocalStorage context namespace — manages request/job/test contexts that carry auth, tenant, transactions.
1305
+
1306
+ ### `flow.run`
1307
+
1308
+ Executes a function within a Flow context (AsyncLocalStorage). All pipe() calls inside will use this context.
1309
+
1310
+ ### `flow.require`
1311
+
1312
+ Returns the current Flow or throws — use in code that must run inside a managed context.
1313
+
1314
+ ### `flow.get`
1315
+
1316
+ Returns the current Flow or undefined — use for optional context detection.
1317
+
1318
+ ### `flow.createTest`
1319
+
1320
+ Creates a Flow for test isolation with optional auth and tenant overrides.
1321
+
1322
+ ## http — Server
1323
+
1324
+ HTTP namespace: `http.file()` builds a file response; the server itself is managed by manifold.start().
1325
+
1326
+ ### Types
1327
+
1328
+ **`CorsConfig`** — CORS configuration — origin, methods, headers, credentials, maxAge.
1329
+
1330
+ ```typescript
1331
+ interface CorsConfig
1332
+ ```
1333
+
1334
+ **`SecurityConfig`** — Security header configuration — passed to @fastify/helmet.
1335
+
1336
+ ```typescript
1337
+ interface SecurityConfig
1338
+ ```
1339
+
1340
+ **`RateLimitConfig`** — Rate limiting configuration — max requests, time window, key generator.
1341
+
1342
+ ```typescript
1343
+ interface RateLimitConfig
1344
+ ```
1345
+
1346
+ **`InjectOptions`** — Options for server.inject() — method, url, headers, payload for testing without HTTP.
1347
+
1348
+ ```typescript
1349
+ interface InjectOptions
1350
+ ```
1351
+
1352
+ **`InjectResponse`** — Response from server.inject() — statusCode, headers, body, rawPayload, json() helper.
1353
+
1354
+ ```typescript
1355
+ interface InjectResponse
1356
+ ```
1357
+
1358
+ **`ServerConfig`** — Configuration for http.createServer() — CORS, security headers, rate limiting, transaction timeout.
1359
+
1360
+ ```typescript
1361
+ interface ServerConfig
1362
+ ```
1363
+
1364
+ **`HandlerResponse`** — Standard handler response shape — statusCode, headers, body.
1365
+
1366
+ ```typescript
1367
+ interface HandlerResponse
1368
+ ```
1369
+
1370
+ **`ErrorResponse`** — Standard error response shape — { error: { code, message }, statusCode }.
1371
+
1372
+ ```typescript
1373
+ interface ErrorResponse
1374
+ ```
1375
+
1376
+ **`PipeworkServer`** — Fastify server wrapper with route registration, handler auto-wiring, and inject() for testing.
1377
+
1378
+ ```typescript
1379
+ interface PipeworkServer
1380
+ ```
1381
+
1382
+ **`FileResponseInit`** — What `http.file()` takes.
1383
+
1384
+ ```typescript
1385
+ interface FileResponseInit
1386
+ ```
1387
+
1388
+ **`FileResponse`**
1389
+
1390
+ A file for a route to answer with, made by `http.file()`. Return it from a
1391
+ handler declared with `.file()`; it is sent as the response body, streamed
1392
+ when `body` is a Readable.
1393
+
1394
+ ```typescript
1395
+ interface FileResponse
1396
+ ```
1397
+
1398
+ **`HttpRequest`** — Fastify request with pipework extensions — req.id (UUID), typed headers, client address (`ip`, `ips`).
1399
+
1400
+ ```typescript
1401
+ interface HttpRequest
1402
+ ```
1403
+
1404
+ **`HttpResponse`** — Fastify reply with pipework extensions.
1405
+
1406
+ ```typescript
1407
+ interface HttpResponse
1408
+ ```
1409
+
1410
+ ## openapi — API Documentation
1411
+
1412
+ OpenAPI spec generation namespace.
1413
+
1414
+ ### `openapi.generate`
1415
+
1416
+ Generates an OpenAPI 3.1 document from route registrations — schemas derived from fitting() input/output.
1417
+
1418
+ ## test
1419
+
1420
+ ## trace
1421
+
1422
+ Trace namespace — hand the current trace to a process outside Node and record the steps it reports back.
1423
+
1424
+ ### `trace.traceparent`
1425
+
1426
+ W3C `traceparent` for the current trace and open step; `null` outside a traced flow or when the trace is truncated.
1427
+
1428
+ ### `trace.env`
1429
+
1430
+ `{ TRACEPARENT }` for a child process's environment, or `{}` when there is no traceparent.
1431
+
1432
+ ### `trace.record`
1433
+
1434
+ Records steps reported as JSON lines (or objects) by an outside process under the step open now. Synchronous; never throws.
1435
+
1436
+ ### Types
1437
+
1438
+ **`FlowStepMeta`** — Trace metadata for one documented flow-step: its `path:symbol` graph node id and the per-argument capture projections.
1439
+
1440
+ ```typescript
1441
+ interface FlowStepMeta
1442
+ ```
1443
+
1444
+ **`ExternalStepReport`** — One step reported by an outside process.
1445
+
1446
+ ```typescript
1447
+ type ExternalStepReport = z.infer<typeof externalStepReportSchema>
1448
+ ```
1449
+
1450
+ **`ExternalRecordResult`** — What `trace.record` did with a report.
1451
+
1452
+ ```typescript
1453
+ interface ExternalRecordResult
1454
+ ```
1455
+
1456
+ ## data
1457
+
1458
+ ### `tap`
1459
+
1460
+ Opens a standalone managed connection outside the manifold's pools — the
1461
+ sanctioned door for contexts where `pipe()` structurally cannot resolve:
1462
+ `worker_threads`, detached monitors, one-off scripts. Callers own the
1463
+ lifecycle: always `await conn.close()`.
1464
+
1465
+ ```typescript
1466
+ function tap(url: string, options?: ConnectOptions): ManagedConnection
1467
+ ```
1468
+
1469
+ ## request
1470
+
1471
+ ### `createServer`
1472
+
1473
+ Creates a PipeworkServer — wraps Fastify with auto request IDs, CORS, rate limiting, and transaction-per-request.
1474
+
1475
+ ```typescript
1476
+ function createServer(instance: Manifold, config: ServerConfig = if (instance.config.environment === 'production')
1477
+ ```