@datafn/server 0.0.3 → 0.1.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.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,9 @@
1
- import { DatafnSchema, DatafnPlugin } from '@datafn/core/types';
2
- import { Router } from '@superfunctions/http';
3
- import { Adapter, KVStoreAdapter, RedisAdapter, RowLevelNamespaceConfig } from '@superfunctions/db';
1
+ import { DatafnPlugin, DatafnSchema as DatafnSchema$1 } from '@datafn/core';
2
+ import { ObservationEvent, ObservabilityInput, ObservabilityConfigInput } from '@superfunctions/observability';
3
+ import { DatafnSchema, DatafnPlugin as DatafnPlugin$1 } from '@datafn/core/types';
4
+ import { Route, Router } from '@superfunctions/http';
5
+ import { ConditionalKVStoreAdapter, IndexedDirectoryStoreAdapter, Adapter, AtomicKVStoreAdapter, RuntimeStores, RowLevelNamespaceConfig } from '@superfunctions/db';
6
+ import { DatafnError } from '@datafn/core/errors';
4
7
 
5
8
  /**
6
9
  * SearchProvider interface for server-side search integration.
@@ -18,6 +21,8 @@ interface SearchProvider {
18
21
  prefix?: boolean;
19
22
  fuzzy?: boolean | number;
20
23
  fieldBoosts?: Record<string, number>;
24
+ namespaceFilter?: string[];
25
+ regionFilter?: string[];
21
26
  signal?: AbortSignal;
22
27
  }): Promise<string[]>;
23
28
  searchAll?(params: {
@@ -29,6 +34,8 @@ interface SearchProvider {
29
34
  prefix?: boolean;
30
35
  fuzzy?: boolean | number;
31
36
  fieldBoosts?: Record<string, number>;
37
+ namespaceFilter?: string[];
38
+ regionFilter?: string[];
32
39
  signal?: AbortSignal;
33
40
  }): Promise<Array<{
34
41
  resource: string;
@@ -60,6 +67,288 @@ interface DatafnLogger {
60
67
  debug(message: string, context?: Record<string, unknown>): void;
61
68
  }
62
69
 
70
+ type DatafnPlacementState = "active" | "moving" | "tombstoned";
71
+ interface DatafnNamespacePlacement {
72
+ namespace: string;
73
+ regionId: string;
74
+ epoch: number;
75
+ state: DatafnPlacementState;
76
+ updatedAt: string;
77
+ cacheExpiresAt?: string;
78
+ destinationRef?: string;
79
+ movingToRegionId?: string;
80
+ previousRegionId?: string;
81
+ migration?: DatafnNamespaceMigrationState;
82
+ }
83
+ interface DatafnNamespaceMigrationState {
84
+ phase: "moving" | "resume-source" | "resume-target";
85
+ sourceRegionId: string;
86
+ targetRegionId: string;
87
+ sourceEpoch: number;
88
+ movingEpoch: number;
89
+ recoveryFence?: number;
90
+ recoveryOwnerId?: string;
91
+ recoveryLeaseExpiresAt?: number;
92
+ sourceDestinationRef?: string;
93
+ targetDestinationRef?: string;
94
+ sourcePreviousRegionId?: string;
95
+ }
96
+ interface DatafnPlacementWriteResult {
97
+ updated: boolean;
98
+ placement: DatafnNamespacePlacement;
99
+ }
100
+ /**
101
+ * Authoritative namespace-placement directory.
102
+ *
103
+ * Implementations must make get, putIfAbsent, and compareAndSet linearizable
104
+ * for one namespace. Permission-directory projections deliberately use a
105
+ * separate adapter and never decide database ownership.
106
+ */
107
+ interface DatafnPlacementDirectoryAdapter {
108
+ get(namespace: string): Promise<DatafnNamespacePlacement | null>;
109
+ putIfAbsent(placement: DatafnNamespacePlacement): Promise<{
110
+ inserted: boolean;
111
+ placement: DatafnNamespacePlacement;
112
+ }>;
113
+ compareAndSet(input: {
114
+ namespace: string;
115
+ expectedEpoch: number;
116
+ expectedState?: DatafnPlacementState;
117
+ next: DatafnNamespacePlacement;
118
+ }): Promise<DatafnPlacementWriteResult>;
119
+ }
120
+ interface DatafnRoutingAssertionClaims {
121
+ version: 1;
122
+ namespace: string;
123
+ regionId: string;
124
+ epoch: number;
125
+ requestId: string;
126
+ method: string;
127
+ path: string;
128
+ audience: string;
129
+ issuedAt: number;
130
+ expiresAt: number;
131
+ nonce: string;
132
+ bodyDigest?: string;
133
+ }
134
+ interface DatafnRoutingAssertionSigner {
135
+ sign(claims: DatafnRoutingAssertionClaims): Promise<string> | string;
136
+ }
137
+ interface DatafnRoutingAssertionVerifier {
138
+ verify(assertion: string): Promise<DatafnRoutingAssertionClaims> | DatafnRoutingAssertionClaims;
139
+ }
140
+ /** Atomically claims a signed request nonce until the assertion expires. */
141
+ interface DatafnRoutingReplayStore {
142
+ claim(nonce: string, expiresAt: number): Promise<boolean> | boolean;
143
+ }
144
+ type DatafnRoutingEventType = "placement_lookup" | "cache_hit" | "forward" | "mismatch" | "retry" | "moving" | "directory_unavailable" | "destination_unavailable" | "epoch_conflict" | "assertion_invalid";
145
+ interface DatafnRoutingEvent {
146
+ type: DatafnRoutingEventType;
147
+ requestId?: string;
148
+ namespaceHash?: string;
149
+ sourceRegion?: string;
150
+ targetRegion?: string;
151
+ epoch?: number;
152
+ state?: DatafnPlacementState;
153
+ attempt?: number;
154
+ retryable?: boolean;
155
+ durationMs?: number;
156
+ outcome?: string;
157
+ }
158
+ interface DatafnPlacementRuntimeConfig {
159
+ directory: DatafnPlacementDirectoryAdapter;
160
+ requireRoutingAssertion?: boolean;
161
+ assertionVerifier?: DatafnRoutingAssertionVerifier;
162
+ replayStore?: DatafnRoutingReplayStore;
163
+ assertionAudience?: string;
164
+ assertionHeader?: string;
165
+ /** Maximum signed request body size. Defaults to 5 MiB. */
166
+ maxBodyBytes?: number;
167
+ now?: () => number;
168
+ onEvent?: (event: DatafnRoutingEvent) => void | Promise<void>;
169
+ }
170
+ declare const DATAFN_ROUTING_ASSERTION_HEADER = "x-datafn-routing-assertion";
171
+ declare const DATAFN_ROUTING_INTERNAL_HEADERS: readonly ["x-datafn-routing-assertion", "x-datafn-routing-namespace", "x-datafn-routing-region", "x-datafn-routing-epoch"];
172
+ declare class DatafnRoutingError extends Error {
173
+ readonly code: "DATAFN_PLACEMENT_NOT_FOUND" | "DATAFN_PLACEMENT_UNAVAILABLE" | "DATAFN_REGION_MISMATCH" | "DATAFN_NAMESPACE_MOVING" | "DATAFN_CELL_UNAVAILABLE" | "DATAFN_ROUTING_ASSERTION_INVALID" | "DATAFN_ROUTING_RETRY_EXHAUSTED" | "DATAFN_PAYLOAD_TOO_LARGE";
174
+ readonly status: number;
175
+ readonly retryable: boolean;
176
+ readonly executionStarted: boolean;
177
+ readonly placement?: DatafnNamespacePlacement;
178
+ readonly internal: boolean;
179
+ constructor(input: {
180
+ code: DatafnRoutingError["code"];
181
+ message: string;
182
+ status: number;
183
+ retryable: boolean;
184
+ placement?: DatafnNamespacePlacement;
185
+ internal?: boolean;
186
+ executionStarted?: boolean;
187
+ });
188
+ toResponse(): Response;
189
+ }
190
+ declare function createConditionalKvDatafnPlacementDirectory(store: ConditionalKVStoreAdapter, options: {
191
+ /** Explicit acknowledgement that authoritative reads are linearizable. */
192
+ consistencyModel: "linearizable";
193
+ keyPrefix?: string;
194
+ }): DatafnPlacementDirectoryAdapter;
195
+ declare function createMemoryDatafnPlacementDirectory(): DatafnPlacementDirectoryAdapter;
196
+ declare function claimDatafnNamespacePlacement(input: {
197
+ directory: DatafnPlacementDirectoryAdapter;
198
+ namespace: string;
199
+ regionId: string;
200
+ destinationRef?: string;
201
+ cacheExpiresAt?: string;
202
+ now?: () => number;
203
+ }): Promise<{
204
+ claimed: boolean;
205
+ placement: DatafnNamespacePlacement;
206
+ }>;
207
+ interface DatafnPlacementValidationResult {
208
+ placement: DatafnNamespacePlacement;
209
+ assertion?: DatafnRoutingAssertionClaims;
210
+ }
211
+ declare function validateDatafnPlacement(input: {
212
+ namespace: string;
213
+ regionId: string;
214
+ runtime: DatafnPlacementRuntimeConfig;
215
+ request?: Request;
216
+ /** Trusted in-process execution has no externally supplied assertion. */
217
+ trustedInternal?: boolean;
218
+ }): Promise<DatafnPlacementValidationResult>;
219
+ interface DatafnGatewayCellRegistry<TTarget> {
220
+ resolve(input: {
221
+ regionId: string;
222
+ destinationRef?: string;
223
+ placement: DatafnNamespacePlacement;
224
+ }): Promise<TTarget> | TTarget;
225
+ }
226
+ interface DatafnGatewayDispatcher<TTarget> {
227
+ dispatch(input: {
228
+ target: TTarget;
229
+ request: Request;
230
+ assertion: string;
231
+ placement: DatafnNamespacePlacement;
232
+ attempt: 0 | 1;
233
+ }): Promise<Response>;
234
+ }
235
+ interface DatafnGatewayRouterConfig<TTarget> {
236
+ directory: DatafnPlacementDirectoryAdapter;
237
+ deriveNamespace(request: Request): Promise<string> | string;
238
+ cellRegistry: DatafnGatewayCellRegistry<TTarget>;
239
+ dispatcher: DatafnGatewayDispatcher<TTarget>;
240
+ assertionSigner: DatafnRoutingAssertionSigner;
241
+ assertionAudience?: string;
242
+ assertionTtlMs?: number;
243
+ cacheTtlMs?: number;
244
+ /** Maximum namespace placements retained by a gateway. Defaults to 10,000. */
245
+ maxCacheEntries?: number;
246
+ /** Maximum request body size accepted before dispatch. Defaults to 5 MiB. */
247
+ maxBodyBytes?: number;
248
+ now?: () => number;
249
+ onEvent?: (event: DatafnRoutingEvent) => void | Promise<void>;
250
+ }
251
+ interface DatafnGatewayRouter {
252
+ handle(request: Request): Promise<Response>;
253
+ invalidate(namespace: string): void;
254
+ clear(): void;
255
+ }
256
+ declare function createDatafnGatewayRouter<TTarget>(config: DatafnGatewayRouterConfig<TTarget>): DatafnGatewayRouter;
257
+ interface DatafnNamespaceMigrationHooks {
258
+ quiesceSource(input: DatafnNamespaceMigrationContext): Promise<void>;
259
+ drainPermissionDirectory(input: DatafnNamespaceMigrationContext): Promise<void>;
260
+ copyTenantData(input: DatafnNamespaceMigrationContext): Promise<void>;
261
+ validateTenantData(input: DatafnNamespaceMigrationContext): Promise<void>;
262
+ rebuildPermissionDirectory(input: DatafnNamespaceMigrationContext): Promise<void>;
263
+ warmTarget(input: DatafnNamespaceMigrationContext): Promise<void>;
264
+ resumeTarget(input: DatafnNamespaceMigrationContext): Promise<void>;
265
+ rollbackSource(input: DatafnNamespaceMigrationContext & {
266
+ cause: unknown;
267
+ }): Promise<void>;
268
+ }
269
+ interface DatafnNamespaceMigrationContext {
270
+ namespace: string;
271
+ sourceRegionId: string;
272
+ targetRegionId: string;
273
+ sourceEpoch: number;
274
+ movingEpoch: number;
275
+ /**
276
+ * Monotonic token that every external side-effect boundary must atomically
277
+ * compare and persist, rejecting lower tokens before applying the effect.
278
+ */
279
+ recoveryFence: number;
280
+ /** Durable lease owner paired with the monotonic recovery fence. */
281
+ recoveryOwnerId: string;
282
+ /** Live lease deadline; renewal updates this value while the hook is running. */
283
+ recoveryLeaseExpiresAt: number;
284
+ /** True when replaying idempotent hooks for a persisted recovery state. */
285
+ recovery?: boolean;
286
+ }
287
+ /**
288
+ * Minimal fenced move protocol. The directory enters `moving` before hooks run,
289
+ * so every cell fails closed while source writes are quiesced and data/outbox
290
+ * state is copied. A second CAS activates the target with explicit recovery
291
+ * state and a final CAS clears that state after the idempotent resume hook.
292
+ */
293
+ declare function migrateDatafnNamespace(input: {
294
+ directory: DatafnPlacementDirectoryAdapter;
295
+ namespace: string;
296
+ targetRegionId: string;
297
+ targetDestinationRef?: string;
298
+ hooks: DatafnNamespaceMigrationHooks;
299
+ now?: () => number;
300
+ /** Exclusive recovery lease duration. Defaults to 30 seconds. */
301
+ recoveryLeaseMs?: number;
302
+ onEvent?: (event: DatafnRoutingEvent) => void | Promise<void>;
303
+ }): Promise<DatafnNamespacePlacement>;
304
+ declare function createDatafnHmacRoutingAssertions(input: {
305
+ activeKeyId: string;
306
+ keys: Record<string, string | Uint8Array>;
307
+ now?: () => number;
308
+ clockSkewMs?: number;
309
+ }): DatafnRoutingAssertionSigner & DatafnRoutingAssertionVerifier;
310
+ /** In-memory replay protection for tests and single-process deployments. */
311
+ declare function createMemoryDatafnRoutingReplayStore(options?: {
312
+ now?: () => number;
313
+ }): DatafnRoutingReplayStore;
314
+ declare function withDatafnRoutingAssertion(request: Request, assertion: string, header?: string): Request;
315
+ declare function validateDatafnRoutingBodyLimit(value: number | undefined): number;
316
+
317
+ declare const DATAFN_MULTI_REGION_CAPABILITY: unique symbol;
318
+ interface DatafnMultiRegionDirectory {
319
+ store: IndexedDirectoryStoreAdapter;
320
+ }
321
+ interface DatafnMultiRegionPluginConfig {
322
+ regionId: string;
323
+ directory: IndexedDirectoryStoreAdapter | DatafnMultiRegionDirectory;
324
+ /**
325
+ * Optional authoritative namespace-placement runtime. When omitted, the
326
+ * plugin retains its existing permission-directory-only behavior.
327
+ */
328
+ placement?: DatafnPlacementRuntimeConfig;
329
+ }
330
+ interface DatafnMultiRegionRuntimeConfig {
331
+ regionId: string;
332
+ directory: IndexedDirectoryStoreAdapter;
333
+ placement?: DatafnPlacementRuntimeConfig;
334
+ }
335
+ interface DatafnPermissionDirectoryGrant {
336
+ id: string;
337
+ resourceType: string;
338
+ resourceNs: string;
339
+ resourceId: string | null;
340
+ principalId: string;
341
+ level?: string;
342
+ grantKind?: string;
343
+ sourceRef?: unknown;
344
+ grantedBy?: string;
345
+ grantedAt?: number;
346
+ revokedAt?: number | null;
347
+ resourceRegion: string;
348
+ }
349
+ declare function datafnMultiRegionPlugin(config: DatafnMultiRegionPluginConfig): DatafnPlugin & DatafnMultiRegionRuntimeConfig;
350
+ declare const createDatafnMultiRegionPlugin: typeof datafnMultiRegionPlugin;
351
+
63
352
  interface SearchResultItem {
64
353
  id: string;
65
354
  resource: string;
@@ -80,6 +369,7 @@ interface CrossResourceSearchParams {
80
369
  fieldBoosts?: Record<string, number>;
81
370
  filters?: Record<string, Record<string, unknown>>;
82
371
  select?: string[];
372
+ actorId?: string;
83
373
  signal?: AbortSignal;
84
374
  }
85
375
 
@@ -101,6 +391,51 @@ interface ExecutionTimingEvent {
101
391
  timestamp: string;
102
392
  }
103
393
 
394
+ type DataFnEventType = 'datafn.authorization.denied' | 'datafn.payload.rejected' | 'datafn.rate_limited' | 'datafn.request.failed' | 'datafn.retention.pruned' | 'datafn.retention.prune_failed';
395
+ type DataFnAction = 'status' | 'query' | 'mutation' | 'transact' | 'seed' | 'clone' | 'pull' | 'push' | 'reconcile' | 'search';
396
+ interface DataFnRequestEventMetadata extends Record<string, unknown> {
397
+ action?: DataFnAction;
398
+ path?: string;
399
+ method?: string;
400
+ }
401
+ interface DataFnAuthorizationDeniedMetadata extends DataFnRequestEventMetadata {
402
+ reason: 'internal-resource' | 'plugin-authorize' | 'authorize-callback';
403
+ }
404
+ interface DataFnPayloadRejectedMetadata extends DataFnRequestEventMetadata {
405
+ reason: 'payload-too-large' | 'invalid-json';
406
+ code: string;
407
+ }
408
+ interface DataFnRateLimitedMetadata extends DataFnRequestEventMetadata {
409
+ reason: 'rate-limit';
410
+ }
411
+ interface DataFnRequestFailedMetadata extends DataFnRequestEventMetadata {
412
+ error: string;
413
+ }
414
+ interface DataFnRetentionPrunedMetadata extends Record<string, unknown> {
415
+ mode: 'startup' | 'periodic';
416
+ target: 'changes' | 'idempotency';
417
+ deleted: number;
418
+ }
419
+ interface DataFnRetentionPruneFailedMetadata extends Record<string, unknown> {
420
+ mode: 'startup' | 'periodic';
421
+ error: string;
422
+ }
423
+ type DataFnAuthorizationDeniedEvent = ObservationEvent<'datafn', 'datafn.authorization.denied', DataFnAuthorizationDeniedMetadata>;
424
+ type DataFnPayloadRejectedEvent = ObservationEvent<'datafn', 'datafn.payload.rejected', DataFnPayloadRejectedMetadata>;
425
+ type DataFnRateLimitedEvent = ObservationEvent<'datafn', 'datafn.rate_limited', DataFnRateLimitedMetadata>;
426
+ type DataFnRequestFailedEvent = ObservationEvent<'datafn', 'datafn.request.failed', DataFnRequestFailedMetadata>;
427
+ type DataFnRetentionPrunedEvent = ObservationEvent<'datafn', 'datafn.retention.pruned', DataFnRetentionPrunedMetadata>;
428
+ type DataFnRetentionPruneFailedEvent = ObservationEvent<'datafn', 'datafn.retention.prune_failed', DataFnRetentionPruneFailedMetadata>;
429
+ interface DataFnEventMap {
430
+ 'datafn.authorization.denied': DataFnAuthorizationDeniedEvent;
431
+ 'datafn.payload.rejected': DataFnPayloadRejectedEvent;
432
+ 'datafn.rate_limited': DataFnRateLimitedEvent;
433
+ 'datafn.request.failed': DataFnRequestFailedEvent;
434
+ 'datafn.retention.pruned': DataFnRetentionPrunedEvent;
435
+ 'datafn.retention.prune_failed': DataFnRetentionPruneFailedEvent;
436
+ }
437
+ type DataFnEvent = DataFnEventMap[DataFnEventType];
438
+
104
439
  interface RetentionConfig {
105
440
  /** Number of days to retain change log entries. Default: unlimited. */
106
441
  changeLogDays?: number;
@@ -114,31 +449,32 @@ interface RetentionConfig {
114
449
  interface RateLimitConfig<TContext = any> {
115
450
  /** Enable rate limiting. Default: false. */
116
451
  enabled: boolean;
452
+ /** Store guarantee for rate limiting. Default: "strict" when stores.atomicKv exists, otherwise "local". */
453
+ mode?: "strict" | "best-effort" | "local";
117
454
  /** Max requests per window per client. Default: 100. */
118
455
  maxRequests?: number;
119
456
  /** Window duration in seconds. Default: 60. */
120
457
  windowSeconds?: number;
121
458
  /** Per-endpoint overrides */
122
- endpoints?: Partial<Record<'query' | 'mutation' | 'transact' | 'push' | 'pull' | 'clone' | 'reconcile' | 'seed', {
459
+ endpoints?: Partial<Record<'query' | 'mutation' | 'transact' | 'push' | 'pull' | 'clone' | 'reconcile' | 'seed' | 'search', {
123
460
  maxRequests: number;
124
461
  windowSeconds: number;
125
462
  }>>;
126
463
  /** Key extractor for identifying clients. Default: uses authContext userId or "anonymous". */
127
464
  keyExtractor?: (ctx: TContext) => string | Promise<string>;
128
465
  }
129
- interface ObservabilityConfig {
466
+ type ObservabilityConfig = ObservabilityInput<DataFnEvent> | (ObservabilityConfigInput<DataFnEvent> & {
130
467
  /** Emit execution timing events. Default: false. */
131
468
  timing?: boolean;
132
469
  /** Custom timing event handler. Default: console.debug. */
133
470
  onTiming?: (event: ExecutionTimingEvent) => void;
134
- }
471
+ });
135
472
 
136
473
  /**
137
474
  * SequenceStore - Pluggable sequence generation for serverSeq
138
475
  *
139
476
  * Supports multiple backends:
140
- * - Redis: Uses atomic INCR for high-performance sequence generation
141
- * - KV Store: Uses atomic incr if available
477
+ * - Atomic store: Uses atomic INCR for high-performance sequence generation
142
478
  * - Database: Uses CAS retry loop
143
479
  */
144
480
 
@@ -146,40 +482,35 @@ interface ObservabilityConfig {
146
482
  * Interface for sequence generation stores
147
483
  */
148
484
  interface SequenceStore {
485
+ /** Initialize durable backing storage before an enclosing transaction. */
486
+ ensureReady?(): Promise<void>;
149
487
  /** Get and increment sequence atomically, returns the next value */
150
488
  getNext(namespace: string): Promise<number>;
151
489
  /** Get and increment sequence atomically by count, returns array of contiguous values */
152
490
  getNextN(namespace: string, count: number): Promise<number[]>;
153
491
  /** Get current sequence value (without incrementing) */
154
492
  getCurrent(namespace: string): Promise<number>;
493
+ /** Ensure the current sequence is at least minSeq. */
494
+ ensureMinSeq?(namespace: string, minSeq: number): Promise<void>;
495
+ /** Return an equivalent store bound to a transaction-scoped adapter. */
496
+ withDb?(db: Adapter): SequenceStore;
155
497
  /** Check if the store is healthy/available */
156
498
  isHealthy?(): Promise<boolean>;
157
499
  }
158
500
  /**
159
- * Redis-based sequence store using atomic INCR
501
+ * Atomic-store-based sequence store using atomic INCR
160
502
  */
161
- declare class RedisSequenceStore implements SequenceStore {
162
- private redis;
503
+ declare class AtomicSequenceStore implements SequenceStore {
504
+ private atomicStore;
163
505
  private keyPrefix;
164
- constructor(redis: RedisAdapter);
506
+ constructor(atomicStore: AtomicKVStoreAdapter);
165
507
  private getKey;
166
508
  getNext(namespace: string): Promise<number>;
167
509
  getNextN(namespace: string, count: number): Promise<number[]>;
168
510
  getCurrent(namespace: string): Promise<number>;
511
+ ensureMinSeq(namespace: string, minSeq: number): Promise<void>;
169
512
  isHealthy(): Promise<boolean>;
170
513
  }
171
- /**
172
- * KV Store-based sequence store using atomic incr
173
- */
174
- declare class KVSequenceStore implements SequenceStore {
175
- private kvStore;
176
- private keyPrefix;
177
- constructor(kvStore: KVStoreAdapter);
178
- private getKey;
179
- getNext(namespace: string): Promise<number>;
180
- getNextN(namespace: string, count: number): Promise<number[]>;
181
- getCurrent(namespace: string): Promise<number>;
182
- }
183
514
  /**
184
515
  * Database-based sequence store using CAS retry loop
185
516
  * Uses the main database adapter
@@ -188,7 +519,9 @@ declare class DatabaseSequenceStore implements SequenceStore {
188
519
  private db;
189
520
  private logger?;
190
521
  private ensured;
191
- constructor(db: Adapter, logger?: DatafnLogger | undefined);
522
+ constructor(db: Adapter, logger?: DatafnLogger | undefined, ensured?: boolean);
523
+ withDb(db: Adapter): SequenceStore;
524
+ ensureReady(): Promise<void>;
192
525
  /**
193
526
  * DI-003: Ensure next_server_seq in meta is at least (minSeq + 1).
194
527
  * Called by ChainedSequenceStore during primary→database failover to prevent duplicate sequences.
@@ -207,15 +540,19 @@ declare class ChainedSequenceStore implements SequenceStore {
207
540
  private primary;
208
541
  private secondary;
209
542
  private logger?;
210
- /** DI-003: Track last-issued seq per namespace from the primary store */
211
543
  private lastKnownPrimarySeq;
212
- constructor(primary: SequenceStore, secondary: SequenceStore, logger?: DatafnLogger | undefined);
544
+ /** DI-003: Track last-issued seq per namespace from the primary store */
545
+ constructor(primary: SequenceStore, secondary: SequenceStore, logger?: DatafnLogger | undefined, lastKnownPrimarySeq?: Map<string, number>);
546
+ withDb(db: Adapter): SequenceStore;
547
+ ensureReady(): Promise<void>;
213
548
  getNext(namespace: string): Promise<number>;
214
549
  /**
215
550
  * DI-003: Sync the secondary (DB) store to start from at least lastKnownPrimarySeq+1.
216
- * Prevents duplicate sequences after Redis→DB failover.
551
+ * Prevents duplicate sequences after atomic-store→DB failover.
217
552
  */
218
553
  private syncSecondaryOnFailover;
554
+ private syncPrimaryIfBehindSecondary;
555
+ private persistPrimaryHighWater;
219
556
  getNextN(namespace: string, count: number): Promise<number[]>;
220
557
  getCurrent(namespace: string): Promise<number>;
221
558
  isHealthy(): Promise<boolean>;
@@ -223,22 +560,16 @@ declare class ChainedSequenceStore implements SequenceStore {
223
560
  /**
224
561
  * Database mapping configuration for routing operations to different databases
225
562
  */
226
- interface DbMapping {
227
- /** Which database to use for serverSeq generation (default: "db") */
228
- serverseq?: "redis" | "kv" | "db";
229
- /** Which database to use for rate limiting (default: "db") */
230
- ratelimiting?: "redis" | "kv" | "db";
231
- /** Which database to use for caching (default: "db") */
232
- cache?: "redis" | "kv" | "db";
563
+ interface SequenceStorePolicy {
564
+ mode?: "strict" | "db";
233
565
  }
234
566
  /**
235
567
  * Create appropriate sequence store based on configuration
236
568
  */
237
569
  declare function createSequenceStore(config: {
238
570
  db?: Adapter;
239
- redis?: RedisAdapter;
240
- kvStore?: KVStoreAdapter;
241
- dbMapping?: DbMapping;
571
+ stores?: RuntimeStores;
572
+ policy?: SequenceStorePolicy;
242
573
  logger?: DatafnLogger;
243
574
  }): SequenceStore | undefined;
244
575
 
@@ -271,6 +602,10 @@ interface WsAuthContext {
271
602
  actorId?: string;
272
603
  /** Optional resolved principal IDs for principal-targeted invalidation. */
273
604
  principalIds?: string[];
605
+ /** Owning region pinned during a routed handshake. */
606
+ regionId?: string;
607
+ /** Placement epoch pinned during a routed handshake. */
608
+ routingEpoch?: number;
274
609
  }
275
610
  /** WebSocket manager configuration (sourced from DatafnServerConfig.ws). */
276
611
  interface WsManagerConfig {
@@ -284,6 +619,32 @@ interface WsManagerConfig {
284
619
  heartbeatTimeoutMs?: number;
285
620
  }
286
621
 
622
+ type DatafnExecutorAction = "query" | "mutation" | "transact" | "search";
623
+ declare class DatafnExecutorError extends Error {
624
+ readonly code: string;
625
+ readonly details?: unknown;
626
+ readonly status: number;
627
+ constructor(error: DatafnError | {
628
+ code: string;
629
+ message: string;
630
+ details?: unknown;
631
+ }, status?: number);
632
+ }
633
+ /**
634
+ * Transport-neutral DataFn execution surface.
635
+ *
636
+ * Every operation enters the same route handlers used by HTTP, including schema
637
+ * validation, field authorization, namespace/actor resolution, hooks,
638
+ * idempotency, limits, configured authorization, and rate limiting.
639
+ */
640
+ interface DatafnExecutor<TContext = unknown> {
641
+ readonly schema: DatafnSchema;
642
+ query<TResult = unknown>(payload: unknown, context?: TContext): Promise<TResult>;
643
+ mutate<TResult = unknown>(payload: unknown, context?: TContext): Promise<TResult>;
644
+ transact<TResult = unknown>(payload: unknown, context?: TContext): Promise<TResult>;
645
+ search(payload: CrossResourceSearchParams, context?: TContext): Promise<SearchResult>;
646
+ }
647
+
287
648
  type Spv2ReadMode = "v1" | "v2" | "dual";
288
649
  type Spv2WriteMode = "v2" | "dual";
289
650
  interface Spv2MigrationRuntimeConfig {
@@ -292,69 +653,224 @@ interface Spv2MigrationRuntimeConfig {
292
653
  warnOnLegacyApi?: boolean;
293
654
  }
294
655
 
656
+ type DatafnPublicLinkShareLevel = "viewer" | "editor" | "owner";
657
+ type DatafnPublicLinkShareScope = "record" | "resource";
658
+ interface DatafnPublicLinkRecord {
659
+ id: string;
660
+ principalId: string;
661
+ resource: string;
662
+ recordId?: string | null;
663
+ scope: DatafnPublicLinkShareScope;
664
+ level: DatafnPublicLinkShareLevel;
665
+ tokenHash: string;
666
+ expiresAt?: number | null;
667
+ revokedAt?: number | null;
668
+ resourceRegion?: string;
669
+ __ns?: string;
670
+ createdAt?: number;
671
+ createdBy?: string;
672
+ updatedAt?: number;
673
+ updatedBy?: string;
674
+ }
675
+ interface DatafnPublicLinkPrincipal {
676
+ linkId: string;
677
+ principalId: string;
678
+ actorId: string;
679
+ namespace: string;
680
+ resourceRegion?: string;
681
+ resource: string;
682
+ recordId?: string | null;
683
+ scope: DatafnPublicLinkShareScope;
684
+ level: DatafnPublicLinkShareLevel;
685
+ }
686
+ interface CreateDatafnPublicLinkInput {
687
+ resource: string;
688
+ recordId?: string | null;
689
+ scope?: DatafnPublicLinkShareScope;
690
+ level?: DatafnPublicLinkShareLevel;
691
+ expiresAt?: number | string | null;
692
+ }
693
+ interface DatafnPublicLinkGrant {
694
+ id: string;
695
+ token: string;
696
+ principalId: string;
697
+ resource: string;
698
+ recordId: string | null;
699
+ scope: DatafnPublicLinkShareScope;
700
+ level: DatafnPublicLinkShareLevel;
701
+ }
702
+ /** Authorization input accepted by the public-links plugin. */
703
+ interface DatafnPublicLinkAuthorizationInput {
704
+ action: DataFnAction;
705
+ context: unknown;
706
+ payload: unknown;
707
+ }
708
+ interface DatafnPublicLinksPluginConfig<TSession = unknown> {
709
+ authenticateOwner?: (request: Request) => Promise<TSession | null> | TSession | null;
710
+ getOwnerActorId(session: TSession): string | undefined;
711
+ getOwnerNamespace(actorId: string, session: TSession): string | Promise<string>;
712
+ modelName?: string;
713
+ principalPrefix?: string;
714
+ tokenHeader?: string;
715
+ directory?: IndexedDirectoryStoreAdapter;
716
+ resourceRegion?: string;
717
+ }
718
+ interface DatafnPublicLinksPlugin<TSession = unknown> extends DatafnPlugin {
719
+ readonly modelName: string;
720
+ readonly tokenHeader: string;
721
+ readonly internalResources: readonly string[];
722
+ readonly permissionDirectoryRuntime?: DatafnMultiRegionRuntimeConfig;
723
+ readToken(request: Request): string | null;
724
+ principalId(linkId: string): string;
725
+ withSchema(schema: DatafnSchema$1): DatafnSchema$1;
726
+ resolve(database: Adapter, token: string | null | undefined): Promise<DatafnPublicLinkPrincipal | null>;
727
+ authorize(input: DatafnPublicLinkAuthorizationInput): boolean | undefined;
728
+ routes(input: {
729
+ database: Adapter;
730
+ crossNamespaceDatabase?: Adapter;
731
+ schema: DatafnSchema$1;
732
+ }): Route[];
733
+ }
734
+ declare class DatafnPublicLinkInputError extends Error {
735
+ readonly path: string;
736
+ constructor(message: string, path: string);
737
+ }
295
738
  /**
296
- * Server configuration
739
+ * Adds the DataFn public-link storage resource to a schema for database codegen.
740
+ */
741
+ declare function withDatafnPublicLinksSchema(schema: DatafnSchema$1, options?: {
742
+ modelName?: string;
743
+ }): DatafnSchema$1;
744
+ /**
745
+ * Creates DataFn-native public-link route and principal resolution support.
746
+ */
747
+ declare function createDatafnPublicLinksPlugin<TSession = unknown>(config: DatafnPublicLinksPluginConfig<TSession>): DatafnPublicLinksPlugin<TSession>;
748
+ /**
749
+ * Reads the DataFn public-link credential from a request.
750
+ */
751
+ declare function readDatafnPublicLinkToken(request: Request, tokenHeader?: string): string | null;
752
+ /**
753
+ * Resolves a DataFn public-link token to its principal and namespace.
754
+ */
755
+ declare function resolveDatafnPublicLink(database: Adapter, token: string | null | undefined, options?: {
756
+ modelName?: string;
757
+ principalPrefix?: string;
758
+ directory?: IndexedDirectoryStoreAdapter;
759
+ }): Promise<DatafnPublicLinkPrincipal | null>;
760
+
761
+ /** Per-request data available to DataFn route response hooks. */
762
+ interface DatafnRouteHookInput<TContext = any> {
763
+ action: DataFnAction;
764
+ request: Request;
765
+ context: TContext & {
766
+ parsedBody?: unknown;
767
+ };
768
+ payload: unknown;
769
+ response: Response;
770
+ }
771
+ /** Transforms a DataFn HTTP response after route execution. */
772
+ type DatafnRouteResponseHook<TContext = any> = (input: DatafnRouteHookInput<TContext>) => Response | Promise<Response>;
773
+ /** Header tuple entries accepted by DataFn route header hooks. */
774
+ type DatafnRouteHeaderEntries = [string, string][];
775
+ /** Header input accepted by DataFn route header hooks. */
776
+ type DatafnRouteHeaderInput = Headers | Record<string, string> | DatafnRouteHeaderEntries;
777
+ /** Static or computed response headers applied after DataFn route hooks. */
778
+ type DatafnRouteHeaders<TContext = any> = DatafnRouteHeaderInput | ((input: DatafnRouteHookInput<TContext>) => DatafnRouteHeaderInput | null | undefined | Promise<DatafnRouteHeaderInput | null | undefined>);
779
+ /** Route lifecycle hooks for framework-level DataFn HTTP behavior. */
780
+ interface DatafnRouteHooks<TContext = any> {
781
+ afterResponse?: DatafnRouteResponseHook<TContext> | readonly DatafnRouteResponseHook<TContext>[];
782
+ headers?: DatafnRouteHeaders<TContext>;
783
+ }
784
+ type DatafnPluginRoutePlacementResult = string | Response;
785
+ /**
786
+ * Placement declaration required for custom plugin routes in regional-cell
787
+ * mode. Returning a Response lets authentication/not-found handling stop
788
+ * before any regional database access.
789
+ */
790
+ interface DatafnPluginRoutePlacement<TContext = any> {
791
+ resolveNamespace(request: Request, context: TContext): DatafnPluginRoutePlacementResult | Promise<DatafnPluginRoutePlacementResult>;
792
+ /** Transfers validated resolver state from the body-safe clone to the handler request. */
793
+ bindHandlerRequest?(placementRequest: Request, handlerRequest: Request, context: TContext): void | Promise<void>;
794
+ }
795
+ type DatafnComposableRoute<TContext = any> = Route<TContext> & {
796
+ meta?: Route<TContext>["meta"] & {
797
+ datafnPlacement?: "none" | DatafnPluginRoutePlacement<TContext>;
798
+ };
799
+ };
800
+ /** Data provided to server plugins before a DataFn action is authorized and executed. */
801
+ interface DatafnPluginAuthorizationInput<TContext = any> {
802
+ action: DataFnAction;
803
+ request: Request;
804
+ context: TContext & {
805
+ parsedBody?: unknown;
806
+ };
807
+ payload: unknown;
808
+ }
809
+ /** Server plugin authorization decisions are fail-closed only when false or an error is returned. */
810
+ type DatafnPluginAuthorizationResult = boolean | void;
811
+ /**
812
+ * Runtime configuration for a DataFn HTTP server.
297
813
  */
298
814
  interface DatafnServerConfig<TContext = any> {
299
- /** DataFn schema (will be validated at startup) */
815
+ /** DataFn schema used to validate resources, relations, fields, permissions, and generated routes at startup. */
300
816
  schema: DatafnSchema;
301
- /** Database adapter (required for persistence) */
817
+ /** Database adapter used for resource persistence, query execution, mutations, sync change logs, and internal tables. */
818
+ database?: Adapter;
819
+ /** @deprecated Use `database`. Retained for compatibility with the original DataFn server API. */
302
820
  db?: Adapter;
303
- /** Optional plugins */
304
- plugins?: DatafnPlugin[];
305
- /** Optional authorization callback */
821
+ /** Runtime plugins that extend schema, add internal resources, register routes, or provide DataFn capabilities. */
822
+ plugins?: DatafnPlugin$1[];
823
+ /** Public-link plugin instance used to register share-link routes and resolve link principals. */
824
+ publicLinks?: DatafnPublicLinksPlugin;
825
+ /** Authorizes each DataFn action after context creation and before route execution. */
306
826
  authorize?: (ctx: TContext, action: "status" | "query" | "mutation" | "transact" | "seed" | "clone" | "pull" | "push" | "reconcile" | "search", payload: unknown) => Promise<boolean> | boolean;
307
- /** Optional request context factory passed through to namespace, actor, auth, and route handlers. */
827
+ /** Static context or request-scoped context factory passed to authorization, namespace resolution, route handlers, and hooks. */
308
828
  context?: TContext | ((request: Request) => Promise<TContext> | TContext);
309
- /** Optional limits configuration */
829
+ /** Request, query, mutation, and validation limits enforced by DataFn routes. */
310
830
  limits?: {
831
+ /** Maximum number of records a query may request unless a route applies a stricter limit. */
311
832
  maxLimit?: number;
833
+ /** Maximum number of steps accepted in a single transact request. */
312
834
  maxTransactSteps?: number;
835
+ /** Maximum request body size in bytes before DataFn rejects the payload. */
313
836
  maxPayloadBytes?: number;
314
- /** Max changes returned per pull request. Default: 1000. */
837
+ /** Maximum number of changes returned by a pull request. Default: 1000. */
315
838
  maxPullLimit?: number;
316
- /** VAL-002: Max select tokens per query (default 50) */
839
+ /** Maximum number of select tokens accepted per query. Default: 50. */
317
840
  maxSelectTokens?: number;
318
- /** VAL-003: Max filter keys per nesting level (default 20) */
841
+ /** Maximum number of filter keys accepted at each nesting level. Default: 20. */
319
842
  maxFilterKeysPerLevel?: number;
320
- /** VAL-004: Max sort fields (default 10) */
843
+ /** Maximum number of sort fields accepted by a query. Default: 10. */
321
844
  maxSortFields?: number;
322
- /** VAL-005: Max aggregations (default 20) */
845
+ /** Maximum number of aggregate expressions accepted by a query. Default: 20. */
323
846
  maxAggregations?: number;
324
- /** VAL-006: Max ID length (default 255) */
847
+ /** Maximum resource or relation ID length accepted by routes. Default: 255. */
325
848
  maxIdLength?: number;
326
- /** FIX-SEC-006: Max batch size for push/mutation endpoints (default 500) */
849
+ /** Maximum number of items accepted by push and mutation batch endpoints. Default: 500. */
327
850
  maxBatchSize?: number;
328
- /** FIX-SRV-003: Max in-flight query concurrency for batch queries (default 20) */
851
+ /** Maximum number of concurrent query executions allowed inside a batch request. Default: 20. */
329
852
  maxBatchQueryConcurrency?: number;
330
853
  };
331
854
  /**
332
- * VAL-009: Debug mode for validation error messages.
333
- * When false, error messages are generic (no field names or schema details).
334
- * Default: process.env.NODE_ENV !== 'production'
855
+ * Enables detailed validation errors with field names and schema details.
856
+ * Defaults to true outside production and generic errors in production.
335
857
  */
336
858
  debug?: boolean;
337
859
  /**
338
- * VAL-001: Allow queries/mutations on resources with no authorization policy.
339
- * When false (default), resources without a policy return FORBIDDEN.
340
- * Set to true only for development/testing.
860
+ * Allows actions on resources that do not define authorization policies.
861
+ * When false, policy-less resources return FORBIDDEN.
341
862
  */
342
863
  allowUnknownResources?: boolean;
343
- /** Optional server time provider (for testing) */
864
+ /** Clock source used by server routes, sync, and retention logic; primarily useful for tests. */
344
865
  getServerTime?: () => number;
345
866
  /**
346
- * Optional flag to enable REST endpoint generation (default: false)
347
- * When true, generates REST wrappers:
348
- * - GET /datafn/resources/:resource (query wrapper)
349
- * - POST /datafn/resources/:resource (insert/merge wrapper)
350
- * - PATCH /datafn/resources/:resource/:id (merge wrapper)
351
- * - DELETE /datafn/resources/:resource/:id (delete wrapper)
867
+ * Enables REST wrappers around DataFn resources.
868
+ * Adds GET, POST, PATCH, and DELETE routes under /datafn/resources/:resource.
352
869
  */
353
870
  rest?: boolean;
354
871
  /**
355
- * Namespace provider for per-request data isolation.
356
- * Returns the namespace string used to scope all data operations.
357
- * Without this, all data shares the default "datafn" namespace.
872
+ * Resolves per-request namespace isolation and actor attribution.
873
+ * Without this, all data uses the default "datafn" namespace.
358
874
  *
359
875
  * @example
360
876
  * ```typescript
@@ -365,83 +881,44 @@ interface DatafnServerConfig<TContext = any> {
365
881
  * ```
366
882
  */
367
883
  namespaceProvider?: {
884
+ /** Returns the namespace that scopes all resource, relation, sync, and search operations for the request. */
368
885
  getNamespace: (ctx: TContext) => string | Promise<string>;
369
- /** Optional actor ID for audit attribution (separate from isolation). */
886
+ /** Returns the actor ID used for audit attribution and sync metadata, separate from namespace isolation. */
370
887
  getActorId?: (ctx: TContext) => string | undefined | Promise<string | undefined>;
371
888
  };
372
- /**
373
- * Optional Redis adapter for atomic operations (serverSeq, rate limiting, caching).
374
- * When provided with appropriate dbMapping, enables high-performance atomic operations.
375
- *
376
- * @example
377
- * ```typescript
378
- * redis: myRedisAdapter,
379
- * dbMapping: { serverseq: "redis" }
380
- * ```
381
- */
382
- redis?: RedisAdapter;
383
- /**
384
- * Optional KV store adapter for simple key-value operations.
385
- * Must support `incr()` to be used for serverSeq generation.
386
- *
387
- * @example
388
- * ```typescript
389
- * kvStore: myKVAdapter,
390
- * dbMapping: { serverseq: "kv" }
391
- * ```
392
- */
393
- kvStore?: KVStoreAdapter;
394
- /**
395
- * Database mapping configuration - specifies which database to use for each feature.
396
- * Defaults to using the main database ("db") for all features.
397
- *
398
- * @example
399
- * ```typescript
400
- * dbMapping: {
401
- * serverseq: "redis", // Use Redis for serverSeq (atomic INCR)
402
- * ratelimiting: "redis", // Use Redis for rate limiting
403
- * cache: "kv", // Use KV store for caching
404
- * }
405
- * ```
406
- */
407
- dbMapping?: DbMapping;
889
+ /** Runtime cache and atomic stores used for rate limiting, sync coordination, and optional server state. */
890
+ stores?: RuntimeStores;
891
+ /** Sequence-store policy used by sync to allocate and persist server sequence numbers. */
892
+ serverSeq?: SequenceStorePolicy;
408
893
  /**
409
894
  * Row-level namespace isolation configuration.
410
- * - Explicitly `false` → disabled.
411
- * - Object → used as-is for wrapping configuration.
895
+ * Pass false to disable database-level namespace wrapping, or an object to configure row-level scoping.
412
896
  */
413
897
  rowLevelNamespace?: false | RowLevelNamespaceConfig;
414
- /** Data retention configuration for __datafn_changes and __datafn_idempotency tables. */
898
+ /** Retention policy for __datafn_changes and __datafn_idempotency internal tables. */
415
899
  retention?: RetentionConfig;
416
- /** Rate limiting configuration (RATE-001 through RATE-005). */
900
+ /** Rate-limit policy for DataFn HTTP endpoints. */
417
901
  rateLimit?: RateLimitConfig<TContext>;
418
- /** Observability configuration (OBS-001 through OBS-004). */
902
+ /** HTTP route lifecycle hooks applied after context creation, authorization, and handler execution. */
903
+ routeHooks?: DatafnRouteHooks<TContext>;
904
+ /** Observability sink and options for DataFn request, rate-limit, authorization, sync, retention, and failure events. */
419
905
  observability?: ObservabilityConfig;
420
906
  /**
421
- * WebSocket limits and heartbeat configuration.
422
- * SCA-005: maxConnections / maxConnectionsPerNamespace
423
- * REL-007: heartbeatIntervalMs / heartbeatTimeoutMs
907
+ * WebSocket connection limits, per-namespace limits, and heartbeat timing used by the sync transport.
424
908
  */
425
909
  ws?: WsManagerConfig;
426
910
  /**
427
- * Graceful shutdown drain timeout in ms. Default: 10,000.
428
- * REL-009: Server waits up to this long for in-flight requests to complete.
911
+ * Graceful shutdown drain timeout in milliseconds.
912
+ * The server waits up to this long for in-flight requests to complete before closing.
429
913
  */
430
914
  shutdownTimeoutMs?: number;
431
915
  /**
432
- * LOG-001: Pluggable logger. Default: console-based (JSON in prod, pretty in dev).
433
- */
434
- logger?: DatafnLogger;
435
- /**
436
- * COMP-001: SPV2 migration compatibility flags.
437
- * - readMode: v2 (default), dual, or v1 (rollback mode)
438
- * - writeMode: v2 (default) or dual
439
- * - warnOnLegacyApi: emit deterministic deprecation warnings for shareWith.userId
916
+ * SPV2 migration compatibility settings for read mode, write mode, and legacy share API warnings.
440
917
  */
441
918
  spv2Migration?: Spv2MigrationRuntimeConfig;
442
919
  /**
443
- * Optional search provider for full-text and semantic search queries.
444
- * When provided, search queries are routed to this provider instead of requiring a searchfn plugin.
920
+ * Search provider for full-text and semantic search queries.
921
+ * When provided, search routes and mutation index updates use this provider.
445
922
  */
446
923
  searchProvider?: SearchProvider;
447
924
  }
@@ -450,6 +927,10 @@ interface DatafnServerConfig<TContext = any> {
450
927
  */
451
928
  interface DatafnServer<TContext = any> {
452
929
  router: Router<TContext>;
930
+ /** Validated schema used by both HTTP and in-process execution. */
931
+ readonly schema: DatafnSchema;
932
+ /** Transport-neutral execution surface for trusted adapters such as McpFn. */
933
+ readonly executor: DatafnExecutor<TContext>;
453
934
  search(params: CrossResourceSearchParams & {
454
935
  namespace?: string;
455
936
  }, ctx?: TContext): Promise<SearchResult>;
@@ -457,6 +938,10 @@ interface DatafnServer<TContext = any> {
457
938
  /** SEC-001: addClient requires auth context. Reject unauthenticated connections with close code 4401 before calling. */
458
939
  /** SCA-005: Returns false (and closes with code 4503) when connection limits are exceeded. */
459
940
  addClient(client: WebSocketClient, authContext: WsAuthContext): boolean;
941
+ /** Validates and pins namespace placement during a canonical-gateway handshake. */
942
+ addRoutedClient(client: WebSocketClient, authContext: WsAuthContext, handshakeRequest?: Request): Promise<boolean>;
943
+ /** Closes stale sessions so clients reconnect through the canonical gateway. */
944
+ fenceNamespace(namespace: string, minimumEpoch?: number): number;
460
945
  removeClient(client: WebSocketClient): void;
461
946
  handleMessage(client: WebSocketClient, data: string): void;
462
947
  /** REL-007: Called by WS transport on native pong frame receipt. */
@@ -477,6 +962,40 @@ interface DatafnServer<TContext = any> {
477
962
  */
478
963
  declare function createDatafnServer<TContext = any>(config: DatafnServerConfig<TContext>): Promise<DatafnServer<TContext>>;
479
964
 
965
+ /**
966
+ * DataFn app declaration shared by code generation and server runtime.
967
+ */
968
+ interface DatafnAppConfig {
969
+ schema: DatafnSchema$1;
970
+ plugins?: DatafnPlugin[];
971
+ }
972
+ /**
973
+ * Runtime server config accepted by DatafnApp.createServer.
974
+ */
975
+ interface DatafnAppServerConfig<TContext = any> extends Omit<DatafnServerConfig<TContext>, "schema" | "plugins"> {
976
+ /** Optional schema override; when omitted, the schema declared in datafn(...) is used. */
977
+ schema?: DatafnSchema$1;
978
+ /** Runtime plugins merged with declaration-time plugins, replacing plugins with the same identity. */
979
+ plugins?: DatafnPlugin[];
980
+ }
981
+ /**
982
+ * Side-effect-free DataFn app object that can expose schema or create a server.
983
+ */
984
+ interface DatafnApp {
985
+ readonly schema: DatafnSchema$1;
986
+ readonly plugins: readonly DatafnPlugin[];
987
+ getSchema(): DatafnSchema$1;
988
+ /**
989
+ * Creates a DataFn server runtime from the side-effect-free app declaration.
990
+ * The server config supplies persistence, context, authorization, namespace isolation, plugins, limits, hooks, search, and observability.
991
+ */
992
+ createServer<TContext = any>(config: DatafnAppServerConfig<TContext>): Promise<DatafnServer<TContext>>;
993
+ }
994
+ /**
995
+ * Creates a side-effect-free DataFn app definition for codegen and runtime use.
996
+ */
997
+ declare function datafn(config: DatafnAppConfig): DatafnApp;
998
+
480
999
  /**
481
1000
  * GET /datafn/status endpoint
482
1001
  * Returns server metadata, capabilities, limits, and schema hash
@@ -494,4 +1013,4 @@ interface StatusResult {
494
1013
  serverTimeMs: number;
495
1014
  }
496
1015
 
497
- export { ChainedSequenceStore, type CrossResourceSearchParams, DatabaseSequenceStore, type DatafnServer, type DatafnServerConfig, type DbMapping, KVSequenceStore, RedisSequenceStore, type SearchProvider, type SearchResult, type SearchResultItem, type SequenceStore, type StatusResult, createDatafnServer, createSequenceStore };
1016
+ export { AtomicSequenceStore, ChainedSequenceStore, type CreateDatafnPublicLinkInput, type CrossResourceSearchParams, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, type DataFnAction, type DataFnAuthorizationDeniedEvent, type DataFnAuthorizationDeniedMetadata, type DataFnEvent, type DataFnEventMap, type DataFnEventType, type DataFnPayloadRejectedEvent, type DataFnPayloadRejectedMetadata, type DataFnRateLimitedEvent, type DataFnRateLimitedMetadata, type DataFnRequestEventMetadata, type DataFnRequestFailedEvent, type DataFnRequestFailedMetadata, type DataFnRetentionPruneFailedEvent, type DataFnRetentionPruneFailedMetadata, type DataFnRetentionPrunedEvent, type DataFnRetentionPrunedMetadata, DatabaseSequenceStore, type DatafnApp, type DatafnAppConfig, type DatafnAppServerConfig, type DatafnComposableRoute, type DatafnExecutor, type DatafnExecutorAction, DatafnExecutorError, type DatafnGatewayCellRegistry, type DatafnGatewayDispatcher, type DatafnGatewayRouter, type DatafnGatewayRouterConfig, type DatafnMultiRegionDirectory, type DatafnMultiRegionPluginConfig, type DatafnMultiRegionRuntimeConfig, type DatafnNamespaceMigrationContext, type DatafnNamespaceMigrationHooks, type DatafnNamespaceMigrationState, type DatafnNamespacePlacement, type DatafnPermissionDirectoryGrant, type DatafnPlacementDirectoryAdapter, type DatafnPlacementRuntimeConfig, type DatafnPlacementState, type DatafnPluginAuthorizationInput, type DatafnPluginAuthorizationResult, type DatafnPluginRoutePlacement, type DatafnPluginRoutePlacementResult, type DatafnPublicLinkAuthorizationInput, type DatafnPublicLinkGrant, DatafnPublicLinkInputError, type DatafnPublicLinkPrincipal, type DatafnPublicLinkRecord, type DatafnPublicLinkShareLevel, type DatafnPublicLinkShareScope, type DatafnPublicLinksPlugin, type DatafnPublicLinksPluginConfig, type DatafnRouteHeaderEntries, type DatafnRouteHeaderInput, type DatafnRouteHeaders, type DatafnRouteHookInput, type DatafnRouteHooks, type DatafnRouteResponseHook, type DatafnRoutingAssertionClaims, type DatafnRoutingAssertionSigner, type DatafnRoutingAssertionVerifier, DatafnRoutingError, type DatafnRoutingEvent, type DatafnRoutingEventType, type DatafnRoutingReplayStore, type DatafnServer, type DatafnServerConfig, type RateLimitConfig, type SearchProvider, type SearchResult, type SearchResultItem, type SequenceStore, type SequenceStorePolicy, type StatusResult, claimDatafnNamespacePlacement, createConditionalKvDatafnPlacementDirectory, createDatafnGatewayRouter, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, migrateDatafnNamespace, readDatafnPublicLinkToken, resolveDatafnPublicLink, validateDatafnPlacement, validateDatafnRoutingBodyLimit, withDatafnPublicLinksSchema, withDatafnRoutingAssertion };