@lostgradient/weft 0.10.0 → 0.11.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.
Files changed (34) hide show
  1. package/README.md +10 -2
  2. package/dist/cli-main.js +62 -62
  3. package/dist/core/checkpoint/serialization.js +2 -2
  4. package/dist/core/engine/disposal.js +4 -0
  5. package/dist/core/engine/engine-leak-warnings.d.ts +2 -0
  6. package/dist/core/engine/engine-leak-warnings.js +7 -1
  7. package/dist/core/engine/index.d.ts +6 -3
  8. package/dist/core/engine/index.js +19 -3
  9. package/dist/core/engine/inline-parking.js +14 -1
  10. package/dist/core/engine/internals.d.ts +21 -0
  11. package/dist/core/engine/operations-time.js +8 -28
  12. package/dist/core/engine/sleep-timer-acknowledgements.d.ts +15 -0
  13. package/dist/core/engine/sleep-timer-acknowledgements.js +144 -0
  14. package/dist/core/engine/termination/cleanup.js +3 -0
  15. package/dist/mcp/cli.js +17 -17
  16. package/dist/server/handler.js +12 -12
  17. package/dist/server/index.js +17 -17
  18. package/dist/service-worker/index.js +12 -12
  19. package/dist/service-worker/scheduler.js +1 -0
  20. package/dist/storage/lazy-postgres-pool.d.ts +38 -0
  21. package/dist/storage/lazy-postgres-pool.js +38 -0
  22. package/dist/storage/neon-batch.d.ts +8 -8
  23. package/dist/storage/neon.d.ts +26 -79
  24. package/dist/storage/neon.js +3 -3
  25. package/dist/storage/postgres-key-value-queries.d.ts +1 -1
  26. package/dist/storage/postgres-key-value-queries.js +1 -1
  27. package/dist/storage/postgres-key-value-storage.d.ts +110 -0
  28. package/dist/storage/postgres-key-value-storage.js +204 -0
  29. package/dist/storage/postgres.d.ts +59 -0
  30. package/dist/storage/postgres.js +15 -0
  31. package/dist/testing/index.js +26 -26
  32. package/dist/version.d.ts +1 -1
  33. package/dist/version.js +1 -1
  34. package/package.json +16 -3
@@ -58,6 +58,7 @@ export class ServiceWorkerScheduler {
58
58
  await this.#onTimerFired(entry);
59
59
  } catch (error) {
60
60
  console.error(`Timer callback failed for timer ${entry.id}:`, error);
61
+ continue;
61
62
  }
62
63
  const indexKey = `timer-idx:${entry.id}`;
63
64
  await this.#storage.batch([
@@ -0,0 +1,38 @@
1
+ import type { PostgresPool } from './postgres-key-value-storage.ts';
2
+ /**
3
+ * Options for {@link createLazyPostgresPool}.
4
+ */
5
+ export type LazyPostgresPoolOptions = {
6
+ /** npm package name of the driver, used in the missing-dependency error. */
7
+ readonly driverName: string;
8
+ /** Adapter class name, used in the missing-dependency error. */
9
+ readonly storageName: string;
10
+ /**
11
+ * Import the driver and construct its connection pool for `url`. Called at most
12
+ * once, on first use. Kept as a callback so this module never imports a specific
13
+ * driver — Neon and Postgres pass their own.
14
+ */
15
+ readonly loadPool: (url: string) => Promise<PostgresPool>;
16
+ };
17
+ /**
18
+ * Build a {@link PostgresPool} whose driver module is imported lazily on first use
19
+ * and whose owned connection pool is torn down exactly once. Shared by
20
+ * `NeonStorage` and `PostgresStorage`: both differ only in WHICH driver they load,
21
+ * so the lazy-import memoization, the dispose-before/after-use guards, and the
22
+ * actionable "optional peer dependency" error live here once instead of being
23
+ * copy-pasted into each factory.
24
+ *
25
+ * Behavior:
26
+ * - **Lazy + memoized:** `loadPool` runs at most once, on the first
27
+ * `query`/`connect`. The injected-pool path never reaches here, so it never
28
+ * imports the driver.
29
+ * - **Disposed is terminal:** after `end()`, any further `query`/`connect` throws
30
+ * rather than silently building a fresh, unreachable pool (which would leak
31
+ * connections and keep the process alive — the bug a naive
32
+ * `if (poolPromise === undefined) return` guard introduces).
33
+ * - **End is safe:** `end()` before first use is a no-op (nothing was built); a
34
+ * failed import leaves nothing to close.
35
+ * - **Missing driver is actionable:** a module-resolution failure is rewrapped as
36
+ * an install hint naming the package, matching the SQLite adapters' DX.
37
+ */
38
+ export declare function createLazyPostgresPool(url: string, options: LazyPostgresPoolOptions): PostgresPool;
@@ -0,0 +1,38 @@
1
+ export function createLazyPostgresPool(url, options) {
2
+ let poolPromise, endPromise, disposed = !1;
3
+ const resolvePool = () => {
4
+ if (disposed)
5
+ throw Error(`${options.storageName} pool has been disposed and cannot be reused. Construct a new adapter.`);
6
+ poolPromise ??= options.loadPool(url).catch((error) => {
7
+ poolPromise = void 0;
8
+ throw asDriverLoadError(error, options);
9
+ });
10
+ return poolPromise;
11
+ };
12
+ return {
13
+ query: async (sql, parameters) => {
14
+ return (await resolvePool()).query(sql, parameters);
15
+ },
16
+ connect: async () => {
17
+ return (await resolvePool()).connect();
18
+ },
19
+ end: async () => {
20
+ disposed = !0;
21
+ endPromise ??= (async () => {
22
+ if (poolPromise === void 0)
23
+ return;
24
+ await (await poolPromise.catch(() => {
25
+ return;
26
+ }))?.end();
27
+ })();
28
+ return endPromise;
29
+ }
30
+ };
31
+ }
32
+ const MODULE_NOT_FOUND = /cannot find module|module_not_found|failed to resolve|could not resolve/i;
33
+ function asDriverLoadError(error, options) {
34
+ const message = error instanceof Error ? error.message : String(error);
35
+ if (MODULE_NOT_FOUND.test(message))
36
+ return Error(`${options.storageName} requires the optional peer dependency "${options.driverName}". Install it in your application with: bun add ${options.driverName} (or npm install ${options.driverName}).`, { cause: error });
37
+ return error instanceof Error ? error : Error(message);
38
+ }
@@ -1,13 +1,13 @@
1
1
  import { type ConditionalBatchCondition } from './interface.ts';
2
2
  import { type BatchNetEffect } from './neon-value-mapping.ts';
3
- import type { NeonPoolClient } from './neon.ts';
4
3
  import type { PostgresKeyValueQueries } from './postgres-key-value-queries.ts';
4
+ import type { PostgresPoolClient } from './postgres-key-value-storage.ts';
5
5
  /**
6
- * The collapsed transaction-phase helpers for {@link NeonStorage}'s `batch()` and
7
- * `conditionalBatch()`. Each phase runs as ONE statement regardless of operation
8
- * count, so a checkpoint commit no longer pays one WebSocket round trip per key.
9
- * Split out of `neon.ts` to keep that module under the size ceiling; all run on a
10
- * caller-supplied pinned-transaction `client`.
6
+ * The collapsed transaction-phase helpers for the Postgres storage adapters'
7
+ * `batch()` and `conditionalBatch()`. Each phase runs as ONE statement regardless
8
+ * of operation count, so a checkpoint commit no longer pays one round trip per
9
+ * key. Split out of the storage class to keep that module under the size ceiling;
10
+ * all run on a caller-supplied pinned-transaction `client`.
11
11
  *
12
12
  * @module storage/neon-batch
13
13
  */
@@ -19,7 +19,7 @@ import type { PostgresKeyValueQueries } from './postgres-key-value-queries.ts';
19
19
  * when every condition holds. With no conditions, holds vacuously and issues no
20
20
  * query.
21
21
  */
22
- export declare function conditionsHold(client: NeonPoolClient, queries: PostgresKeyValueQueries, conditions: ConditionalBatchCondition[]): Promise<boolean>;
22
+ export declare function conditionsHold(client: PostgresPoolClient, queries: PostgresKeyValueQueries, conditions: ConditionalBatchCondition[]): Promise<boolean>;
23
23
  /**
24
24
  * Write a resolved batch net effect with at most one upsert and one delete
25
25
  * statement — the put-set as a single `unnest`-driven multi-row upsert, the
@@ -27,4 +27,4 @@ export declare function conditionsHold(client: NeonPoolClient, queries: Postgres
27
27
  * (see {@link resolveBatchNetEffect}), so the statements commute; each is
28
28
  * skipped when its set is empty.
29
29
  */
30
- export declare function writeBatchNetEffect(client: NeonPoolClient, queries: PostgresKeyValueQueries, netEffect: BatchNetEffect): Promise<void>;
30
+ export declare function writeBatchNetEffect(client: PostgresPoolClient, queries: PostgresKeyValueQueries, netEffect: BatchNetEffect): Promise<void>;
@@ -1,32 +1,20 @@
1
- import { type DeleteRangeOptions } from './delete-range.ts';
2
- import { type BatchOperation, type ConditionalBatchCondition, type ScanOptions, type Storage, type StorageCapabilities } from './interface.ts';
3
- import { type NeonQueryResult } from './neon-value-mapping.ts';
1
+ import { PostgresKeyValueStorage, type PostgresKeyValueStorageOptions, type PostgresPool, type PostgresPoolClient } from './postgres-key-value-storage.ts';
4
2
  /**
5
- * A connection that can run a single interactive transaction. Obtained from
6
- * {@link NeonPool.connect}; `release()` returns it to the pool. Both
7
- * `batch()` and `conditionalBatch()` drive `BEGIN`/`COMMIT`/`ROLLBACK` over one
8
- * of these so every statement in a transaction lands on the same connection —
9
- * `pool.query()` alone may scatter statements across pooled connections, which
10
- * would make a multi-statement batch non-atomic.
3
+ * A connection that can run a single interactive transaction, obtained from
4
+ * {@link NeonPool.connect}. Alias of the driver-agnostic
5
+ * {@link PostgresPoolClient}; kept for backward-compatible imports.
11
6
  */
12
- export type NeonPoolClient = {
13
- query(sql: string, parameters?: unknown[]): Promise<NeonQueryResult>;
14
- release(): void;
15
- };
7
+ export type NeonPoolClient = PostgresPoolClient;
16
8
  /**
17
- * Minimal structural view of a node-postgres `Pool`. The real Neon serverless
18
- * `Pool` satisfies this; the PGlite test backend is wrapped to satisfy it too.
19
- * `query()` runs a single statement on a pooled connection (used for the
20
- * single-statement hot paths); `connect()` pins a connection for an interactive
21
- * transaction; `end()` tears the pool down.
9
+ * Minimal structural view of a node-postgres `Pool`. The Neon serverless `Pool`
10
+ * satisfies this; the PGlite test backend is wrapped to satisfy it too. Alias of
11
+ * the driver-agnostic {@link PostgresPool}; kept for backward-compatible imports.
22
12
  */
23
- export type NeonPool = {
24
- query(sql: string, parameters?: unknown[]): Promise<NeonQueryResult>;
25
- connect(): Promise<NeonPoolClient>;
26
- end(): Promise<void>;
27
- };
13
+ export type NeonPool = PostgresPool;
28
14
  /**
29
- * Configuration for connecting to a Neon (or any Postgres) database.
15
+ * Configuration for connecting to a Neon (or any Postgres) database. Alias of the
16
+ * shared {@link PostgresKeyValueStorageOptions}; `url` is optional and required
17
+ * only when no `pool` is supplied.
30
18
  *
31
19
  * @example
32
20
  * ```ts
@@ -38,41 +26,16 @@ export type NeonPool = {
38
26
  * await using storage = new NeonStorage(options);
39
27
  * ```
40
28
  */
41
- export type NeonStorageOptions = {
42
- /** Postgres connection string for the primary endpoint. */
43
- url: string;
44
- /**
45
- * Optional pre-built pool. Pass this to reuse a pool you manage (for example a
46
- * test backend such as PGlite, or a shared application pool), instead of having
47
- * the adapter construct its own from `url`. When supplied, `url` is ignored and
48
- * **ownership stays with the caller**: disposing the `NeonStorage` does NOT
49
- * close an injected pool, so it can be shared across adapters and the caller
50
- * remains responsible for ending it. A pool the adapter constructs itself (from
51
- * `url`) IS closed on disposal.
52
- */
53
- pool?: NeonPool;
54
- /**
55
- * Postgres schema to contain the kv table. Default: unqualified — the table
56
- * resolves through `search_path` (in practice `public`). When set, the adapter
57
- * creates the schema if absent (`CREATE SCHEMA IF NOT EXISTS`) and qualifies
58
- * every statement as `"schema"."table"`. Lets Weft live in its own schema
59
- * alongside the application's tables in one database — one PITR line, no Drizzle
60
- * drift/drop risk. Validated as a strict Postgres identifier at construction.
61
- */
62
- schema?: string;
63
- /**
64
- * Table name. Default: `'kv'`. Validated as a strict Postgres identifier at
65
- * construction. With neither `schema` nor `table` set, the adapter emits
66
- * byte-identical SQL against the unqualified `kv` table (existing deployments
67
- * are unaffected).
68
- */
69
- table?: string;
70
- };
29
+ export type NeonStorageOptions = PostgresKeyValueStorageOptions;
71
30
  /**
72
31
  * Storage adapter backed by Neon serverless Postgres for durable, remote
73
- * deployments. Implements the same `Storage` interface as the SQLite adapters
74
- * over a single `kv(key TEXT COLLATE "C", value BYTEA)` table, so switching from
75
- * a local SQLite store to Neon is a configuration change, not a code change.
32
+ * deployments. A thin {@link PostgresKeyValueStorage} subclass whose only job is
33
+ * to supply the Neon serverless default pool factory; all storage behavior (SQL,
34
+ * value mapping, transactions/retry, schema/table qualification) lives in the
35
+ * driver-agnostic base. Implements the same `Storage` interface as the SQLite
36
+ * adapters over a single `kv(key TEXT COLLATE "C", value BYTEA)` table, so
37
+ * switching from a local SQLite store to Neon is a configuration change, not a
38
+ * code change.
76
39
  *
77
40
  * **Endpoint assumption.** `capabilities()` reports `readAfterWrite:
78
41
  * 'linearizable'`, which holds for the **primary** Neon endpoint. A read-replica
@@ -95,30 +58,14 @@ export type NeonStorageOptions = {
95
58
  * await using engine = new Engine({ storage });
96
59
  * ```
97
60
  */
98
- export declare class NeonStorage implements Storage {
99
- #private;
61
+ export declare class NeonStorage extends PostgresKeyValueStorage {
100
62
  /**
101
63
  * @param options Connection configuration ({@link NeonStorageOptions}).
102
64
  * @param poolFactory Internal seam for constructing the owned pool from `url`.
103
- * Defaults to the real driver `Pool`; tests inject a fake (for example one
104
- * whose `end()` rejects) to exercise owned-pool teardown without a network.
105
- * Used only when no `pool` is supplied; an injected `pool` stays caller-owned.
65
+ * Defaults to lazily importing the real Neon driver `Pool`; tests inject a
66
+ * fake (for example one whose `end()` rejects) to exercise owned-pool teardown
67
+ * without a network. Used only when no `pool` is supplied; an injected `pool`
68
+ * stays caller-owned.
106
69
  */
107
- constructor(options: NeonStorageOptions, poolFactory?: (url: string) => NeonPool);
108
- capabilities(): StorageCapabilities;
109
- get(key: string): Promise<Uint8Array | null>;
110
- put(key: string, value: Uint8Array): Promise<void>;
111
- delete(key: string): Promise<void>;
112
- has(key: string): Promise<boolean>;
113
- deletePrefix(prefix: string): Promise<number>;
114
- deleteRange(prefix: string, options: DeleteRangeOptions): Promise<number>;
115
- scan(prefix: string, options?: ScanOptions): AsyncIterable<[string, Uint8Array]>;
116
- keys(prefix: string, options?: ScanOptions): AsyncIterable<string>;
117
- count(prefix: string): Promise<number>;
118
- scoped(prefix: string): Storage;
119
- batch(operations: BatchOperation[]): Promise<void>;
120
- conditionalBatch(conditions: ConditionalBatchCondition[], operations: BatchOperation[]): Promise<boolean>;
121
- query<T>(sql: string, parameters?: unknown[]): Promise<T[]>;
122
- [Symbol.dispose](): void;
123
- [Symbol.asyncDispose](): Promise<void>;
70
+ constructor(options: NeonStorageOptions, poolFactory?: (url: string) => PostgresPool);
124
71
  }
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- var U_=Object.defineProperty;var Z_=(_)=>_;function G_(_,E){this[_]=Z_.bind(null,E)}var z_=(_,E)=>{for(var F in E)U_(_,F,{get:E[F],enumerable:!0,configurable:!0,set:G_.bind(E,F)})};var M=(_,E)=>()=>(_&&(E=_(_=0)),E);var v_=import.meta.require,P_=(_,E,F)=>{if(E!=null){if(typeof E!=="object"&&typeof E!=="function")throw TypeError('Object expected to be assigned to "using" declaration');let W;if(F)W=E[Symbol.asyncDispose];if(W===void 0)W=E[Symbol.dispose];if(typeof W!=="function")throw TypeError("Object not disposable");_.push([F,W,E])}else if(F)_.push([F]);return E},R_=(_,E,F)=>{let W=(Y)=>E=F?new SuppressedError(Y,E,"An error was suppressed during disposal"):(F=!0,Y),J=(Y)=>{while(Y=_.pop())try{var Q=Y[1]&&Y[1].call(Y[2]);if(Y[0])return Promise.resolve(Q).then(J,(U)=>(W(U),J()))}catch(U){W(U)}if(F)throw E};return J()};function N(_,E,F){if(!_.capabilities()[E])throw Error(`Feature "${F}" requires storage capability "${E}", but this storage backend does not provide it.`)}function M_(_){let E=_.capabilities(),F=[];if(E.persistence!=="local"&&E.persistence!=="remote")F.push(`persistence must be "local" or "remote" (got "${E.persistence}")`);if(E.readAfterWrite!=="linearizable")F.push(`readAfterWrite must be "linearizable" (got "${E.readAfterWrite}")`);if(E.scanConsistency!=="snapshot")F.push(`scanConsistency must be "snapshot" (got "${E.scanConsistency}")`);if(!E.atomicBatch)F.push("atomicBatch must be true");if(!E.conditionalBatch)F.push("conditionalBatch must be true");if(F.length>0)throw Error(`Storage is not durable enough for recovery: ${F.join("; ")}.`)}var C="default";async function q(_,E){return await _.get(E)!==null}async function*H(_,E,F){for await(let[W]of _.scan(E,F))yield W}async function h(_,E){let F=0;for await(let W of H(_,E))F++;return F}async function b(_,E){let F=[];for await(let W of H(_,E))F.push({type:"delete",key:W});if(F.length===0)return 0;return await _.batch(F),F.length}async function x(_,E,F){let W=[];for await(let J of H(_,E,F))W.push({type:"delete",key:J});if(W.length===0)return 0;return await _.batch(W),W.length}var $_;var y=M(()=>{$_=["actrec:","archive:","async-act:","attr:","audit:bulk:","blob:","budget:","budget-charged:","ev:","fleet-event-by-workflow:","fleet-event:","fleet-event-tail","idx:","lease:","liveness:","offload:","op:","review:","schedule:","schedule-due:","schedule-run:","sig:","sigres:","sigseq:","start-idem:","state:","tag:","tool-effect:","upd:","upk:","upr:","wf:","wf-cleanup:","wf-cleanup-needed:","wf-concurrency:","wf-concurrency-holder:","wf-deadline:","wf-delayed:","wf-finalizer-state:","wf-has-services:","wf-headers:","wf-idx-","wf-teardown:","wf-teardown-deadletter:","wf-teardown-needed:","wf-terminal:"]});function G(_,E){if(E>A)throw new I(_,E)}function g(_){return _.length>0?_.slice(0,-1)+String.fromCharCode(_.charCodeAt(_.length-1)+1):"\xFF"}function c_(_,E={}){if(E.gt!==void 0&&_<=E.gt)return!1;if(E.gte!==void 0&&_<E.gte)return!1;if(E.lt!==void 0&&_>=E.lt)return!1;if(E.lte!==void 0&&_>E.lte)return!1;return!0}function u(_,E){if(_===null||E===null)return _===E;if(_.byteLength!==E.byteLength)return!1;for(let F=0;F<_.byteLength;F++)if(_[F]!==E[F])return!1;return!0}async function c(_,E){if(_.has)return _.has(E);return q(_,E)}function k(_,E,F){if(_.keys)return _.keys(E,F);return H(_,E,F)}async function w(_,E){if(_.count)return _.count(E);return h(_,E)}async function f(_,E){if(_.deletePrefix)return _.deletePrefix(E);return b(_,E)}async function k_(_,E){G("batch operations",E.length),await _.batch(E)}async function d(_,E,F){if(G("conditionalBatch conditions",E.length),G("conditionalBatch operations",F.length),N(_,"conditionalBatch","storageConditionalBatch"),!_.conditionalBatch)throw Error("This storage backend reports conditionalBatch capability but does not implement the conditionalBatch() method.");return _.conditionalBatch(E,F)}function X(_){return encodeURIComponent(_)}function w_(_){return decodeURIComponent(_)}function f_(_){try{return decodeURIComponent(_)}catch{return null}}var A=1e4,u_=1e4,I,Z=(_)=>String(_).padStart(16,"0"),H_="0",V_="1",m=(_,E,F,W)=>`sig:${X(_)}:${X(E)}:${W}:${X(F)}`,d_;var V=M(()=>{y();I=class I extends Error{code="StorageBatchOperationLimitExceededError";cap=A;count;target;constructor(_,E){super(`${_} count ${E} exceeds MAX_BATCH_OPERATIONS (${A}).`);this.name="StorageBatchOperationLimitExceededError",this.target=_,this.count=E}};d_={workflow:(_)=>`wf:${X(_)}`,checkpoint:(_)=>`wf:${X(_)}:ckpt`,checkpointHistory:(_,E)=>`wf:${X(_)}:ckpt:${String(E).padStart(10,"0")}`,timelinePrefix:(_)=>`wf:${X(_)}:timeline:`,timeline:(_,E)=>`wf:${X(_)}:timeline:${String(E).padStart(10,"0")}`,schedule:(_)=>`schedule:${X(_)}`,scheduleTick:(_,E)=>`schedule-due:${String(_).padStart(16,"0")}:${X(E)}`,scheduleRun:(_)=>`schedule-run:${X(_)}`,operation:(_,E,F)=>`op:${_}:${Z(E)}:${F}`,operationInflight:(_)=>`op:inflight:${_}`,operationQueued:(_)=>`op:queued:${_}`,operationResolved:(_)=>`op:resolved:${_}`,operationDeadLetterPrefix:()=>"op:dead-letter:",operationDeadLetter:(_)=>`op:dead-letter:${_}`,bulkOperationAuditPrefix:()=>"audit:bulk:",bulkOperationAudit:(_,E,F)=>`audit:bulk:${Z(_)}:${X(E)}:${X(F)}`,operationResolvedByTimePrefix:()=>"op:resolved-by-time:",operationResolvedByTime:(_,E)=>`op:resolved-by-time:${Z(_)}:${X(E)}`,asyncActivity:(_,E)=>`async-act:v1:${X(_)}:${X(E)}`,asyncActivityResolution:(_,E)=>`async-act:v1:${X(_)}:${X(E)}:resolution`,activityReconciliationPrefix:(_)=>`actrec:v1:${X(_)}:`,activityReconciliation:(_,E,F)=>`actrec:v1:${X(_)}:${X(E)}:${F}`,eventPrefix:(_)=>`ev:${X(_)}:`,event:(_,E)=>`ev:${X(_)}:${String(E).padStart(10,"0")}`,eventHead:(_)=>`ev:${X(_)}:head`,eventWatermark:(_)=>`ev:${X(_)}:watermark`,fleetEventPrefix:()=>"fleet-event:",fleetEvent:(_)=>`fleet-event:${String(_).padStart(10,"0")}`,fleetEventTail:()=>"fleet-event-tail",fleetEventByWorkflowPrefix:(_)=>`fleet-event-by-workflow:${X(_)}:`,fleetEventByWorkflow:(_,E)=>`fleet-event-by-workflow:${X(_)}:${String(E).padStart(10,"0")}`,signal:(_,E,F)=>m(_,E,F,V_),startSignal:(_,E,F)=>m(_,E,F,H_),signalSequence:(_)=>`sigseq:v1:${X(_)}`,signalAcceptedResponsePrefix:(_)=>`sigres:v1:${X(_)}:`,signalAcceptedResponse:(_,E,F)=>`sigres:v1:${X(_)}:${X(E)}:${X(F)}`,deadline:(_,E)=>`wf-deadline:${Z(_)}:${X(E)}`,terminalCleanup:(_,E)=>`wf-cleanup:${Z(_)}:${X(E)}`,teardownTimer:(_,E)=>`wf-teardown:${Z(_)}:${X(E)}`,delayedStart:(_,E)=>`wf-delayed:${Z(_)}:${X(E)}`,terminalWorkflowPrefix:()=>"wf-terminal:",terminalWorkflow:(_,E)=>`wf-terminal:${Z(_)}:${X(E)}`,attribute:(_)=>`attr:${X(_)}`,attributeIndex:(_,E,F)=>`idx:${_}:${E}:${X(F)}`,tagIndex:(_,E)=>`tag:${X(_)}:${X(E)}`,updatePrefix:(_)=>`upd:${X(_)}:`,update:(_,E)=>`upd:${X(_)}:${E}`,updateResponse:(_)=>`upr:${_}`,updateIdempotency:(_,E)=>`upk:${X(_)}:${E}`,startIdempotency:(_)=>`start-idem:${X(_)}`,startIdempotencySignalId:(_)=>`start-idem:${_}`,livenessPrefix:()=>"liveness:",liveness:(_)=>`liveness:${X(_)}`,leasePrefix:()=>"lease:",leaseEpoch:()=>"lease:epoch",leaseHolder:()=>"lease:holder",budget:(_,E,F)=>`budget:${_}:${E}:${F}`,review:(_,E)=>`review:${X(_)}:${E}`,workflowHeaders:(_)=>`wf-headers:${X(_)}`,childCancellationPrefix:(_)=>`child-cancel:${X(_)}:`,childCancellation:(_,E)=>`child-cancel:${X(_)}:${X(E)}`,terminalCleanupNeeded:(_)=>`wf-cleanup-needed:${X(_)}`,workflowConcurrency:(_,E)=>`wf-concurrency:${X(_)}:${X(E)}`,workflowConcurrencyHolder:(_)=>`wf-concurrency-holder:${X(_)}`,workflowHasServices:(_)=>`wf-has-services:${X(_)}`,finalizerState:(_)=>`wf-finalizer-state:${X(_)}`,teardownOwed:(_)=>`wf-teardown-needed:${X(_)}`,teardownDeadLetter:(_)=>`wf-teardown-deadletter:${X(_)}`,offload:(_,E)=>`offload:${X(_)}:${E}`,archive:(_,E)=>`archive:${X(_)}:${E}`,stateExecution:(_,E)=>`state:execution:${X(_)}:${X(E)}`,stateWorkflow:(_,E)=>`state:workflow-scope:${C}:${X(_)}:${X(E)}`,streamChunkPrefix:(_,E)=>`blob:${X(_)}:${E}:chunk:`,streamChunk:(_,E,F)=>`blob:${X(_)}:${E}:chunk:${String(F).padStart(10,"0")}`,streamTail:(_,E)=>`blob:${X(_)}:${E}:tail`,streamMetadata:(_,E)=>`blob:${X(_)}:${E}:meta`,budgetCharged:(_)=>`budget-charged:${_}`,toolEffect:(_,E,F)=>`tool-effect:${X(_)}:${E}:${F}`,workflowVisibilityStatus:(_,E)=>`wf-idx-status:${X(_)}:${X(E)}`,workflowVisibilityType:(_,E)=>`wf-idx-type:${X(_)}:${X(E)}`,workflowVisibilityCreated:(_,E)=>`wf-idx-created:${Z(_)}:${X(E)}`,workflowVisibilityUpdated:(_,E)=>`wf-idx-updated:${Z(_)}:${X(E)}`,workflowVisibilityDeadline:(_,E)=>`wf-idx-deadline:${Z(_)}:${X(E)}`,workflowVisibilityManifest:(_)=>`wf-idx-manifest:${X(_)}`,workflowVisibilityMetaVersion:()=>"wf-idx-meta:version",workflowVisibilityMetaBuiltAt:()=>"wf-idx-meta:built-at",workflowVisibilityMetaCursor:()=>"wf-idx-meta:cursor"}});function j_(_){if(_===void 0)return;if(typeof _!=="number"||!Number.isInteger(_)||_<0)throw Error("deleteRange limit must be a finite non-negative integer");return _===0?0:_}function j(_){let E={},F=!1;for(let J of["gt","gte","lt","lte"]){let Y=_[J];if(Y===void 0)continue;if(typeof Y!=="string")throw Error("deleteRange bounds must be strings");E[J]=Y,F=!0}if(!F)throw Error("deleteRange requires at least one of gt/gte/lt/lte; use deletePrefix to delete a whole prefix");let W=j_(_.limit);if(W!==void 0)E.limit=W;return E}async function l(_,E,F){let W=j(F);if(_.deleteRange)return _.deleteRange(E,W);return x(_,E,W)}var S=()=>{};function T(_){return _.replaceAll(/:+$/g,"")}function L_(_,E){let F=T(_),W=T(E);if(F.length===0)return W;if(W.length===0)return F;return`${F}:${W}`}function p(_,E){return new K(_,E)}var K;var a=M(()=>{S();V();K=class K{#_;#E;constructor(_,E){this.#_=_,this.#E=T(E)}#F(_){if(this.#E.length===0)return _;return _.length===0?`${this.#E}:`:`${this.#E}:${_}`}#X(_){if(this.#E.length===0)return _;return _.slice(this.#E.length+1)}#Y(_={}){let E={};if(_.limit!==void 0)E.limit=_.limit;if(_.reverse!==void 0)E.reverse=_.reverse;if(_.gt!==void 0)E.gt=this.#F(_.gt);if(_.gte!==void 0)E.gte=this.#F(_.gte);if(_.lt!==void 0)E.lt=this.#F(_.lt);if(_.lte!==void 0)E.lte=this.#F(_.lte);return E}#J(_){let E={};if(_.limit!==void 0)E.limit=_.limit;if(_.gt!==void 0)E.gt=this.#F(_.gt);if(_.gte!==void 0)E.gte=this.#F(_.gte);if(_.lt!==void 0)E.lt=this.#F(_.lt);if(_.lte!==void 0)E.lte=this.#F(_.lte);return E}capabilities(){return this.#_.capabilities()}scoped(_){return new K(this.#_,L_(this.#E,_))}async get(_){return this.#_.get(this.#F(_))}async put(_,E){await this.#_.put(this.#F(_),E)}async delete(_){await this.#_.delete(this.#F(_))}async*scan(_,E){for await(let[F,W]of this.#_.scan(this.#F(_),this.#Y(E)))yield[this.#X(F),W]}async batch(_){G("batch operations",_.length),await this.#_.batch(_.map((E)=>{if(E.type==="put")return{type:"put",key:this.#F(E.key),value:E.value};return{type:"delete",key:this.#F(E.key)}}))}async conditionalBatch(_,E){return d(this.#_,_.map((F)=>({key:this.#F(F.key),expectedValue:F.expectedValue})),E.map((F)=>{if(F.type==="put")return{type:"put",key:this.#F(F.key),value:F.value};return{type:"delete",key:this.#F(F.key)}}))}async has(_){return c(this.#_,this.#F(_))}async deletePrefix(_){return f(this.#_,this.#F(_))}async deleteRange(_,E){let F=this.#J(j(E));return l(this.#_,this.#F(_),F)}async*keys(_,E){for await(let F of k(this.#_,this.#F(_),this.#Y(E)))yield this.#X(F)}async count(_){return w(this.#_,this.#F(_))}[Symbol.dispose](){this.#_[Symbol.dispose]()}}});function C_(_){return _.trim().replace(/;+\s*$/u,"").trim()}function A_(_){return B_.test(_)}function Y_(_){let E=C_(_);if(E.length===0)throw Error("Storage query must not be empty.");if(E.includes(";"))throw Error("Storage query must contain exactly one read-only statement.");if(N_.test(E))return;if(D_.test(E)&&A_(E))return;throw Error("Storage query only supports read-only SELECT and PRAGMA statements.")}var D_,B_,N_;var J_=M(()=>{D_=/^PRAGMA\b/iu,B_=/^PRAGMA\s+(?:[A-Z_][A-Z0-9_]*\.)?[A-Z_][A-Z0-9_]*\s*$/iu,N_=/^SELECT\b/iu});S();V();import{Pool as S_}from"@neondatabase/serverless";V();function O(_){return _.rowCount??_.affectedRows??_.rows.length}function L(_){if(_ instanceof Uint8Array)return new Uint8Array(_);return new Uint8Array(_)}function D(_){return Buffer.from(_)}function z(_){let E=new Map,F=new Set;for(let W of _)if(W.type==="put")F.delete(W.key),E.set(W.key,W.value);else E.delete(W.key),F.add(W.key);return{puts:E,deletes:F}}async function s(_,E,F){if(F.length===0)return!0;let W=F.map((Q)=>Q.key),J=await _.query(E.selectValuesByKeys,[W]),Y=new Map;for(let Q of J.rows){let U=Q.value;if(U!==null&&U!==void 0)Y.set(Q.key,L(U))}for(let Q of F){let U=Y.get(Q.key)??null;if(!u(U,Q.expectedValue))return!1}return!0}async function v(_,E,F){if(F.puts.size>0){let W=[],J=[];for(let[Y,Q]of F.puts)W.push(Y),J.push(D(Q));await _.query(E.upsertValuesByKeys,[W,J])}if(F.deletes.size>0)await _.query(E.deleteValuesByKeys,[[...F.deletes]])}V();var n="kv",i=/^[a-z_][a-z0-9_]*$/i;function P(_,E){if(!i.test(_))throw Error(`NeonStorage ${E} name "${_}" is not a valid Postgres identifier. Use only letters, digits, and underscores, starting with a letter or underscore (matching ${i.source}).`)}function t(_){let{schema:E,table:F}=_;if(E===void 0&&F===void 0)return n;let W=F??n;if(P(W,"table"),E===void 0)return`"${W}"`;return P(E,"schema"),`"${E}"."${W}"`}function B(_){return[_,g(_)]}function o(_,E){let{gt:F,gte:W,lt:J,lte:Y}=E,Q=B(_),U=["key >= $1 AND key < $2"];if(F!==void 0)Q.push(F),U.push(`key > $${Q.length}`);if(W!==void 0)Q.push(W),U.push(`key >= $${Q.length}`);if(J!==void 0)Q.push(J),U.push(`key < $${Q.length}`);if(Y!==void 0)Q.push(Y),U.push(`key <= $${Q.length}`);return{conditions:U,parameters:Q}}function r(_,E={}){let{limit:F,reverse:W}=E,{conditions:J,parameters:Y}=o(_,E),Q=W?"DESC":"ASC",U="";if(F!==void 0)Y.push(F),U=` LIMIT $${Y.length}`;return{parameters:Y,whereOrderLimit:`WHERE ${J.join(" AND ")} ORDER BY key ${Q}${U}`}}function e(_){let E=`CREATE TABLE IF NOT EXISTS ${_} (
2
+ var $_=Object.defineProperty;var M_=(_)=>_;function H_(_,E){this[_]=M_.bind(null,E)}var b_=(_,E)=>{for(var W in E)$_(_,W,{get:E[W],enumerable:!0,configurable:!0,set:H_.bind(E,W)})};var M=(_,E)=>()=>(_&&(E=_(_=0)),E);var U_=import.meta.require,x_=(_,E,W)=>{if(E!=null){if(typeof E!=="object"&&typeof E!=="function")throw TypeError('Object expected to be assigned to "using" declaration');let X;if(W)X=E[Symbol.asyncDispose];if(X===void 0)X=E[Symbol.dispose];if(typeof X!=="function")throw TypeError("Object not disposable");_.push([W,X,E])}else if(W)_.push([W]);return E},I_=(_,E,W)=>{let X=(F)=>E=W?new SuppressedError(F,E,"An error was suppressed during disposal"):(W=!0,F),J=(F)=>{while(F=_.pop())try{var Q=F[1]&&F[1].call(F[2]);if(F[0])return Promise.resolve(Q).then(J,(Z)=>(X(Z),J()))}catch(Z){X(Z)}if(W)throw E};return J()};function C(_,E,W){if(!_.capabilities()[E])throw Error(`Feature "${W}" requires storage capability "${E}", but this storage backend does not provide it.`)}function V_(_){let E=_.capabilities(),W=[];if(E.persistence!=="local"&&E.persistence!=="remote")W.push(`persistence must be "local" or "remote" (got "${E.persistence}")`);if(E.readAfterWrite!=="linearizable")W.push(`readAfterWrite must be "linearizable" (got "${E.readAfterWrite}")`);if(E.scanConsistency!=="snapshot")W.push(`scanConsistency must be "snapshot" (got "${E.scanConsistency}")`);if(!E.atomicBatch)W.push("atomicBatch must be true");if(!E.conditionalBatch)W.push("conditionalBatch must be true");if(W.length>0)throw Error(`Storage is not durable enough for recovery: ${W.join("; ")}.`)}var N="default";async function h(_,E){return await _.get(E)!==null}async function*U(_,E,W){for await(let[X]of _.scan(E,W))yield X}async function b(_,E){let W=0;for await(let X of U(_,E))W++;return W}async function x(_,E){let W=[];for await(let X of U(_,E))W.push({type:"delete",key:X});if(W.length===0)return 0;return await _.batch(W),W.length}async function I(_,E,W){let X=[];for await(let J of U(_,E,W))X.push({type:"delete",key:J});if(X.length===0)return 0;return await _.batch(X),X.length}var j_;var y=M(()=>{j_=["actrec:","archive:","async-act:","attr:","audit:bulk:","blob:","budget:","budget-charged:","ev:","fleet-event-by-workflow:","fleet-event:","fleet-event-tail","idx:","lease:","liveness:","offload:","op:","review:","schedule:","schedule-due:","schedule-run:","sig:","sigres:","sigseq:","start-idem:","state:","tag:","tool-effect:","upd:","upk:","upr:","wf:","wf-cleanup:","wf-cleanup-needed:","wf-concurrency:","wf-concurrency-holder:","wf-deadline:","wf-delayed:","wf-finalizer-state:","wf-has-services:","wf-headers:","wf-idx-","wf-teardown:","wf-teardown-deadletter:","wf-teardown-needed:","wf-terminal:"]});function $(_,E){if(E>A)throw new g(_,E)}function u(_){return _.length>0?_.slice(0,-1)+String.fromCharCode(_.charCodeAt(_.length-1)+1):"\xFF"}function l_(_,E={}){if(E.gt!==void 0&&_<=E.gt)return!1;if(E.gte!==void 0&&_<E.gte)return!1;if(E.lt!==void 0&&_>=E.lt)return!1;if(E.lte!==void 0&&_>E.lte)return!1;return!0}function k(_,E){if(_===null||E===null)return _===E;if(_.byteLength!==E.byteLength)return!1;for(let W=0;W<_.byteLength;W++)if(_[W]!==E[W])return!1;return!0}async function c(_,E){if(_.has)return _.has(E);return h(_,E)}function w(_,E,W){if(_.keys)return _.keys(E,W);return U(_,E,W)}async function f(_,E){if(_.count)return _.count(E);return b(_,E)}async function d(_,E){if(_.deletePrefix)return _.deletePrefix(E);return x(_,E)}async function p_(_,E){$("batch operations",E.length),await _.batch(E)}async function l(_,E,W){if($("conditionalBatch conditions",E.length),$("conditionalBatch operations",W.length),C(_,"conditionalBatch","storageConditionalBatch"),!_.conditionalBatch)throw Error("This storage backend reports conditionalBatch capability but does not implement the conditionalBatch() method.");return _.conditionalBatch(E,W)}function Y(_){return encodeURIComponent(_)}function a_(_){return decodeURIComponent(_)}function s_(_){try{return decodeURIComponent(_)}catch{return null}}var A=1e4,d_=1e4,g,G=(_)=>String(_).padStart(16,"0"),B_="0",L_="1",m=(_,E,W,X)=>`sig:${Y(_)}:${Y(E)}:${X}:${Y(W)}`,n_;var V=M(()=>{y();g=class g extends Error{code="StorageBatchOperationLimitExceededError";cap=A;count;target;constructor(_,E){super(`${_} count ${E} exceeds MAX_BATCH_OPERATIONS (${A}).`);this.name="StorageBatchOperationLimitExceededError",this.target=_,this.count=E}};n_={workflow:(_)=>`wf:${Y(_)}`,checkpoint:(_)=>`wf:${Y(_)}:ckpt`,checkpointHistory:(_,E)=>`wf:${Y(_)}:ckpt:${String(E).padStart(10,"0")}`,timelinePrefix:(_)=>`wf:${Y(_)}:timeline:`,timeline:(_,E)=>`wf:${Y(_)}:timeline:${String(E).padStart(10,"0")}`,schedule:(_)=>`schedule:${Y(_)}`,scheduleTick:(_,E)=>`schedule-due:${String(_).padStart(16,"0")}:${Y(E)}`,scheduleRun:(_)=>`schedule-run:${Y(_)}`,operation:(_,E,W)=>`op:${_}:${G(E)}:${W}`,operationInflight:(_)=>`op:inflight:${_}`,operationQueued:(_)=>`op:queued:${_}`,operationResolved:(_)=>`op:resolved:${_}`,operationDeadLetterPrefix:()=>"op:dead-letter:",operationDeadLetter:(_)=>`op:dead-letter:${_}`,bulkOperationAuditPrefix:()=>"audit:bulk:",bulkOperationAudit:(_,E,W)=>`audit:bulk:${G(_)}:${Y(E)}:${Y(W)}`,operationResolvedByTimePrefix:()=>"op:resolved-by-time:",operationResolvedByTime:(_,E)=>`op:resolved-by-time:${G(_)}:${Y(E)}`,asyncActivity:(_,E)=>`async-act:v1:${Y(_)}:${Y(E)}`,asyncActivityResolution:(_,E)=>`async-act:v1:${Y(_)}:${Y(E)}:resolution`,activityReconciliationPrefix:(_)=>`actrec:v1:${Y(_)}:`,activityReconciliation:(_,E,W)=>`actrec:v1:${Y(_)}:${Y(E)}:${W}`,eventPrefix:(_)=>`ev:${Y(_)}:`,event:(_,E)=>`ev:${Y(_)}:${String(E).padStart(10,"0")}`,eventHead:(_)=>`ev:${Y(_)}:head`,eventWatermark:(_)=>`ev:${Y(_)}:watermark`,fleetEventPrefix:()=>"fleet-event:",fleetEvent:(_)=>`fleet-event:${String(_).padStart(10,"0")}`,fleetEventTail:()=>"fleet-event-tail",fleetEventByWorkflowPrefix:(_)=>`fleet-event-by-workflow:${Y(_)}:`,fleetEventByWorkflow:(_,E)=>`fleet-event-by-workflow:${Y(_)}:${String(E).padStart(10,"0")}`,signal:(_,E,W)=>m(_,E,W,L_),startSignal:(_,E,W)=>m(_,E,W,B_),signalSequence:(_)=>`sigseq:v1:${Y(_)}`,signalAcceptedResponsePrefix:(_)=>`sigres:v1:${Y(_)}:`,signalAcceptedResponse:(_,E,W)=>`sigres:v1:${Y(_)}:${Y(E)}:${Y(W)}`,deadline:(_,E)=>`wf-deadline:${G(_)}:${Y(E)}`,terminalCleanup:(_,E)=>`wf-cleanup:${G(_)}:${Y(E)}`,teardownTimer:(_,E)=>`wf-teardown:${G(_)}:${Y(E)}`,delayedStart:(_,E)=>`wf-delayed:${G(_)}:${Y(E)}`,terminalWorkflowPrefix:()=>"wf-terminal:",terminalWorkflow:(_,E)=>`wf-terminal:${G(_)}:${Y(E)}`,attribute:(_)=>`attr:${Y(_)}`,attributeIndex:(_,E,W)=>`idx:${_}:${E}:${Y(W)}`,tagIndex:(_,E)=>`tag:${Y(_)}:${Y(E)}`,updatePrefix:(_)=>`upd:${Y(_)}:`,update:(_,E)=>`upd:${Y(_)}:${E}`,updateResponse:(_)=>`upr:${_}`,updateIdempotency:(_,E)=>`upk:${Y(_)}:${E}`,startIdempotency:(_)=>`start-idem:${Y(_)}`,startIdempotencySignalId:(_)=>`start-idem:${_}`,livenessPrefix:()=>"liveness:",liveness:(_)=>`liveness:${Y(_)}`,leasePrefix:()=>"lease:",leaseEpoch:()=>"lease:epoch",leaseHolder:()=>"lease:holder",budget:(_,E,W)=>`budget:${_}:${E}:${W}`,review:(_,E)=>`review:${Y(_)}:${E}`,workflowHeaders:(_)=>`wf-headers:${Y(_)}`,childCancellationPrefix:(_)=>`child-cancel:${Y(_)}:`,childCancellation:(_,E)=>`child-cancel:${Y(_)}:${Y(E)}`,terminalCleanupNeeded:(_)=>`wf-cleanup-needed:${Y(_)}`,workflowConcurrency:(_,E)=>`wf-concurrency:${Y(_)}:${Y(E)}`,workflowConcurrencyHolder:(_)=>`wf-concurrency-holder:${Y(_)}`,workflowHasServices:(_)=>`wf-has-services:${Y(_)}`,finalizerState:(_)=>`wf-finalizer-state:${Y(_)}`,teardownOwed:(_)=>`wf-teardown-needed:${Y(_)}`,teardownDeadLetter:(_)=>`wf-teardown-deadletter:${Y(_)}`,offload:(_,E)=>`offload:${Y(_)}:${E}`,archive:(_,E)=>`archive:${Y(_)}:${E}`,stateExecution:(_,E)=>`state:execution:${Y(_)}:${Y(E)}`,stateWorkflow:(_,E)=>`state:workflow-scope:${N}:${Y(_)}:${Y(E)}`,streamChunkPrefix:(_,E)=>`blob:${Y(_)}:${E}:chunk:`,streamChunk:(_,E,W)=>`blob:${Y(_)}:${E}:chunk:${String(W).padStart(10,"0")}`,streamTail:(_,E)=>`blob:${Y(_)}:${E}:tail`,streamMetadata:(_,E)=>`blob:${Y(_)}:${E}:meta`,budgetCharged:(_)=>`budget-charged:${_}`,toolEffect:(_,E,W)=>`tool-effect:${Y(_)}:${E}:${W}`,workflowVisibilityStatus:(_,E)=>`wf-idx-status:${Y(_)}:${Y(E)}`,workflowVisibilityType:(_,E)=>`wf-idx-type:${Y(_)}:${Y(E)}`,workflowVisibilityCreated:(_,E)=>`wf-idx-created:${G(_)}:${Y(E)}`,workflowVisibilityUpdated:(_,E)=>`wf-idx-updated:${G(_)}:${Y(E)}`,workflowVisibilityDeadline:(_,E)=>`wf-idx-deadline:${G(_)}:${Y(E)}`,workflowVisibilityManifest:(_)=>`wf-idx-manifest:${Y(_)}`,workflowVisibilityMetaVersion:()=>"wf-idx-meta:version",workflowVisibilityMetaBuiltAt:()=>"wf-idx-meta:built-at",workflowVisibilityMetaCursor:()=>"wf-idx-meta:cursor"}});function D_(_){if(_===void 0)return;if(typeof _!=="number"||!Number.isInteger(_)||_<0)throw Error("deleteRange limit must be a finite non-negative integer");return _===0?0:_}function j(_){let E={},W=!1;for(let J of["gt","gte","lt","lte"]){let F=_[J];if(F===void 0)continue;if(typeof F!=="string")throw Error("deleteRange bounds must be strings");E[J]=F,W=!0}if(!W)throw Error("deleteRange requires at least one of gt/gte/lt/lte; use deletePrefix to delete a whole prefix");let X=D_(_.limit);if(X!==void 0)E.limit=X;return E}async function p(_,E,W){let X=j(W);if(_.deleteRange)return _.deleteRange(E,X);return I(_,E,X)}var S=()=>{};function T(_){return _.replaceAll(/:+$/g,"")}function C_(_,E){let W=T(_),X=T(E);if(W.length===0)return X;if(X.length===0)return W;return`${W}:${X}`}function a(_,E){return new K(_,E)}var K;var s=M(()=>{S();V();K=class K{#_;#E;constructor(_,E){this.#_=_,this.#E=T(E)}#W(_){if(this.#E.length===0)return _;return _.length===0?`${this.#E}:`:`${this.#E}:${_}`}#Y(_){if(this.#E.length===0)return _;return _.slice(this.#E.length+1)}#F(_={}){let E={};if(_.limit!==void 0)E.limit=_.limit;if(_.reverse!==void 0)E.reverse=_.reverse;if(_.gt!==void 0)E.gt=this.#W(_.gt);if(_.gte!==void 0)E.gte=this.#W(_.gte);if(_.lt!==void 0)E.lt=this.#W(_.lt);if(_.lte!==void 0)E.lte=this.#W(_.lte);return E}#J(_){let E={};if(_.limit!==void 0)E.limit=_.limit;if(_.gt!==void 0)E.gt=this.#W(_.gt);if(_.gte!==void 0)E.gte=this.#W(_.gte);if(_.lt!==void 0)E.lt=this.#W(_.lt);if(_.lte!==void 0)E.lte=this.#W(_.lte);return E}capabilities(){return this.#_.capabilities()}scoped(_){return new K(this.#_,C_(this.#E,_))}async get(_){return this.#_.get(this.#W(_))}async put(_,E){await this.#_.put(this.#W(_),E)}async delete(_){await this.#_.delete(this.#W(_))}async*scan(_,E){for await(let[W,X]of this.#_.scan(this.#W(_),this.#F(E)))yield[this.#Y(W),X]}async batch(_){$("batch operations",_.length),await this.#_.batch(_.map((E)=>{if(E.type==="put")return{type:"put",key:this.#W(E.key),value:E.value};return{type:"delete",key:this.#W(E.key)}}))}async conditionalBatch(_,E){return l(this.#_,_.map((W)=>({key:this.#W(W.key),expectedValue:W.expectedValue})),E.map((W)=>{if(W.type==="put")return{type:"put",key:this.#W(W.key),value:W.value};return{type:"delete",key:this.#W(W.key)}}))}async has(_){return c(this.#_,this.#W(_))}async deletePrefix(_){return d(this.#_,this.#W(_))}async deleteRange(_,E){let W=this.#J(j(E));return p(this.#_,this.#W(_),W)}async*keys(_,E){for await(let W of w(this.#_,this.#W(_),this.#F(E)))yield this.#Y(W)}async count(_){return f(this.#_,this.#W(_))}[Symbol.dispose](){this.#_[Symbol.dispose]()}}});function z_(_){return _.trim().replace(/;+\s*$/u,"").trim()}function O_(_){return T_.test(_)}function Q_(_){let E=z_(_);if(E.length===0)throw Error("Storage query must not be empty.");if(E.includes(";"))throw Error("Storage query must contain exactly one read-only statement.");if(K_.test(E))return;if(S_.test(E)&&O_(E))return;throw Error("Storage query only supports read-only SELECT and PRAGMA statements.")}var S_,T_,K_;var Z_=M(()=>{S_=/^PRAGMA\b/iu,T_=/^PRAGMA\s+(?:[A-Z_][A-Z0-9_]*\.)?[A-Z_][A-Z0-9_]*\s*$/iu,K_=/^SELECT\b/iu});function n(_,E){let W,X,J=!1,F=()=>{if(J)throw Error(`${E.storageName} pool has been disposed and cannot be reused. Construct a new adapter.`);return W??=E.loadPool(_).catch((Q)=>{throw W=void 0,A_(Q,E)}),W};return{query:async(Q,Z)=>{return(await F()).query(Q,Z)},connect:async()=>{return(await F()).connect()},end:async()=>{return J=!0,X??=(async()=>{if(W===void 0)return;await(await W.catch(()=>{return}))?.end()})(),X}}}var N_=/cannot find module|module_not_found|failed to resolve|could not resolve/i;function A_(_,E){let W=_ instanceof Error?_.message:String(_);if(N_.test(W))return Error(`${E.storageName} requires the optional peer dependency "${E.driverName}". Install it in your application with: bun add ${E.driverName} (or npm install ${E.driverName}).`,{cause:_});return _ instanceof Error?_:Error(W)}S();V();V();function z(_){return _.rowCount??_.affectedRows??_.rows.length}function B(_){if(_ instanceof Uint8Array)return new Uint8Array(_);return new Uint8Array(_)}function L(_){return Buffer.from(_)}function O(_){let E=new Map,W=new Set;for(let X of _)if(X.type==="put")W.delete(X.key),E.set(X.key,X.value);else E.delete(X.key),W.add(X.key);return{puts:E,deletes:W}}async function i(_,E,W){if(W.length===0)return!0;let X=W.map((Q)=>Q.key),J=await _.query(E.selectValuesByKeys,[X]),F=new Map;for(let Q of J.rows){let Z=Q.value;if(Z!==null&&Z!==void 0)F.set(Q.key,B(Z))}for(let Q of W){let Z=F.get(Q.key)??null;if(!k(Z,Q.expectedValue))return!1}return!0}async function R(_,E,W){if(W.puts.size>0){let X=[],J=[];for(let[F,Q]of W.puts)X.push(F),J.push(L(Q));await _.query(E.upsertValuesByKeys,[X,J])}if(W.deletes.size>0)await _.query(E.deleteValuesByKeys,[[...W.deletes]])}V();var r="kv",t=/^[a-z_][a-z0-9_]*$/i;function v(_,E){if(!t.test(_))throw Error(`Postgres storage ${E} name "${_}" is not a valid Postgres identifier. Use only letters, digits, and underscores, starting with a letter or underscore (matching ${t.source}).`)}function e(_){let{schema:E,table:W}=_;if(E===void 0&&W===void 0)return r;let X=W??r;if(v(X,"table"),E===void 0)return`"${X}"`;return v(E,"schema"),`"${E}"."${X}"`}function D(_){return[_,u(_)]}function __(_,E){let{gt:W,gte:X,lt:J,lte:F}=E,Q=D(_),Z=["key >= $1 AND key < $2"];if(W!==void 0)Q.push(W),Z.push(`key > $${Q.length}`);if(X!==void 0)Q.push(X),Z.push(`key >= $${Q.length}`);if(J!==void 0)Q.push(J),Z.push(`key < $${Q.length}`);if(F!==void 0)Q.push(F),Z.push(`key <= $${Q.length}`);return{conditions:Z,parameters:Q}}function o(_,E={}){let{limit:W,reverse:X}=E,{conditions:J,parameters:F}=__(_,E),Q=X?"DESC":"ASC",Z="";if(W!==void 0)F.push(W),Z=` LIMIT $${F.length}`;return{parameters:F,whereOrderLimit:`WHERE ${J.join(" AND ")} ORDER BY key ${Q}${Z}`}}function E_(_){let E=`CREATE TABLE IF NOT EXISTS ${_} (
3
3
  key TEXT COLLATE "C" PRIMARY KEY,
4
4
  value BYTEA NOT NULL
5
- )`,F=`
5
+ )`,W=`
6
6
  SELECT COALESCE(co.collname, 'default') AS collation
7
7
  FROM pg_attribute a
8
8
  LEFT JOIN pg_collation co ON co.oid = a.attcollation
@@ -12,4 +12,4 @@ var U_=Object.defineProperty;var Z_=(_)=>_;function G_(_,E){this[_]=Z_.bind(null
12
12
  FROM pg_attribute a
13
13
  LEFT JOIN pg_collation co ON co.oid = a.attcollation
14
14
  WHERE a.attrelid = to_regclass($1) AND a.attname = 'key' AND a.attnum > 0
15
- `,selectValueByKey:`SELECT value FROM ${_} WHERE key = $1`,upsertValueByKey:`INSERT INTO ${_} (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,deleteValueByKey:`DELETE FROM ${_} WHERE key = $1`,selectKeyPresence:`SELECT 1 AS present FROM ${_} WHERE key = $1 LIMIT 1`,countKeysByPrefix:`SELECT COUNT(*) AS count FROM ${_} WHERE key >= $1 AND key < $2`,deleteKeysByPrefix:`DELETE FROM ${_} WHERE key >= $1 AND key < $2`,selectValuesByKeys:`SELECT key, value FROM ${_} WHERE key = ANY($1)`,upsertValuesByKeys:`INSERT INTO ${_} (key, value) SELECT * FROM unnest($1::text[], $2::bytea[]) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,deleteValuesByKeys:`DELETE FROM ${_} WHERE key = ANY($1)`,keyValueRangeSelect(W,J={}){let{parameters:Y,whereOrderLimit:Q}=r(W,J);return{parameters:Y,sql:`SELECT key, value FROM ${_} ${Q}`}},keyRangeSelect(W,J={}){let{parameters:Y,whereOrderLimit:Q}=r(W,J);return{parameters:Y,sql:`SELECT key FROM ${_} ${Q}`}},keyRangeDelete(W,J){let{conditions:Y,parameters:Q}=o(W,J),U=Y.join(" AND ");if(J.limit===void 0)return{parameters:Q,sql:`DELETE FROM ${_} WHERE ${U}`};return Q.push(J.limit),{parameters:Q,sql:`DELETE FROM ${_} WHERE key IN (SELECT key FROM ${_} WHERE ${U} ORDER BY key ASC LIMIT $${Q.length})`}}}}var __="BEGIN ISOLATION LEVEL SERIALIZABLE",E_="BEGIN ISOLATION LEVEL READ COMMITTED",F_="BEGIN READ ONLY",W_="COMMIT",R="ROLLBACK";function X_(_){return P(_,"schema"),`CREATE SCHEMA IF NOT EXISTS "${_}"`}J_();a();var T_=new Set(["40001","40P01"]),Q_=5;function K_(_){if(typeof _!=="object"||_===null||!("code"in _))return!1;let E=_.code;return typeof E==="string"&&T_.has(E)}class O_{#_;#E;#F;#X;#Y;#J;constructor(_,E=(F)=>new S_({connectionString:F})){this.#Y=_.pool===void 0,this.#_=_.pool??E(_.url),this.#F=_.schema;let F=t({schema:_.schema,table:_.table});this.#E=e(F)}capabilities(){return{persistence:"remote",readAfterWrite:"linearizable",scanConsistency:"snapshot",atomicBatch:!0,conditionalBatch:!0,boundedRangeDelete:!0}}#W(){return this.#X??=this.#Z().catch((_)=>{throw this.#X=void 0,_}),this.#X}async#Z(){if(this.#F!==void 0)await this.#_.query(X_(this.#F));await this.#_.query(this.#E.createTable),await this.#G()}async#G(){let E=(await this.#_.query(this.#E.selectKeyCollation,[this.#E.tableReference])).rows[0]?.collation;if(E==="C")return;let F=E===void 0?"no such table":typeof E==="string"?`"${E}"`:"an unexpected collation value";throw Error(`NeonStorage requires the ${this.#E.tableReference} table's "key" column to use COLLATE "C" (found ${F}). A table created without COLLATE "C" sorts keys by the database locale, which breaks Weft's lexicographic prefix scans. Use a fresh table, or recreate it as: CREATE TABLE ${this.#E.tableReference} (key TEXT COLLATE "C" PRIMARY KEY, value BYTEA NOT NULL).`)}async get(_){await this.#W();let F=(await this.#_.query(this.#E.selectValueByKey,[_])).rows[0];if(F===void 0)return null;let W=F.value;if(W===null||W===void 0)return null;return L(W)}async put(_,E){await this.#W(),await this.#_.query(this.#E.upsertValueByKey,[_,D(E)])}async delete(_){await this.#W(),await this.#_.query(this.#E.deleteValueByKey,[_])}async has(_){return await this.#W(),(await this.#_.query(this.#E.selectKeyPresence,[_])).rows.length>0}async deletePrefix(_){await this.#W();let[E,F]=B(_),W=await this.#_.query(this.#E.deleteKeysByPrefix,[E,F]);return O(W)}async deleteRange(_,E){await this.#W();let F=j(E),{parameters:W,sql:J}=this.#E.keyRangeDelete(_,F),Y=await this.#_.query(J,W);return O(Y)}async*scan(_,E={}){await this.#W();let{parameters:F,sql:W}=this.#E.keyValueRangeSelect(_,E),J=await this.#_.query(W,F);for(let Y of J.rows)yield[Y.key,L(Y.value)]}async*keys(_,E={}){await this.#W();let{parameters:F,sql:W}=this.#E.keyRangeSelect(_,E),J=await this.#_.query(W,F);for(let Y of J.rows)yield Y.key}async count(_){await this.#W();let[E,F]=B(_),W=await this.#_.query(this.#E.countKeysByPrefix,[E,F]);return Number(W.rows[0]?.count??0)}scoped(_){return p(this,_)}async#Q(_,E,F=()=>!0){let W=await this.#_.connect();try{await W.query(_);try{let J=await E(W);return await W.query(F(J)?W_:R),J}catch(J){throw await W.query(R).catch(()=>{}),J}}finally{W.release()}}async batch(_){if(G("batch operations",_.length),_.length===0)return;await this.#W(),await this.#Q(E_,async(E)=>{await v(E,this.#E,z(_))})}async conditionalBatch(_,E){G("conditionalBatch conditions",_.length),G("conditionalBatch operations",E.length),await this.#W();let F=z(E),W;for(let J=0;J<Q_;J+=1)try{return await this.#Q(__,async(Y)=>{if(!await s(Y,this.#E,_))return!1;return await v(Y,this.#E,F),!0},(Y)=>Y)}catch(Y){if(!K_(Y))throw Y;W=Y}throw Error(`conditionalBatch exhausted ${Q_} attempts after retryable transaction failures`,{cause:W})}async query(_,E){return await this.#W(),Y_(_),this.#Q(F_,async(F)=>{return(await F.query(_,E??[])).rows})}#U(){if(!this.#Y)return Promise.resolve();return this.#J??=this.#_.end(),this.#J}[Symbol.dispose](){this.#U().catch(()=>{})}async[Symbol.asyncDispose](){await this.#U()}}export{O_ as NeonStorage};
15
+ `,selectValueByKey:`SELECT value FROM ${_} WHERE key = $1`,upsertValueByKey:`INSERT INTO ${_} (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,deleteValueByKey:`DELETE FROM ${_} WHERE key = $1`,selectKeyPresence:`SELECT 1 AS present FROM ${_} WHERE key = $1 LIMIT 1`,countKeysByPrefix:`SELECT COUNT(*) AS count FROM ${_} WHERE key >= $1 AND key < $2`,deleteKeysByPrefix:`DELETE FROM ${_} WHERE key >= $1 AND key < $2`,selectValuesByKeys:`SELECT key, value FROM ${_} WHERE key = ANY($1)`,upsertValuesByKeys:`INSERT INTO ${_} (key, value) SELECT * FROM unnest($1::text[], $2::bytea[]) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,deleteValuesByKeys:`DELETE FROM ${_} WHERE key = ANY($1)`,keyValueRangeSelect(X,J={}){let{parameters:F,whereOrderLimit:Q}=o(X,J);return{parameters:F,sql:`SELECT key, value FROM ${_} ${Q}`}},keyRangeSelect(X,J={}){let{parameters:F,whereOrderLimit:Q}=o(X,J);return{parameters:F,sql:`SELECT key FROM ${_} ${Q}`}},keyRangeDelete(X,J){let{conditions:F,parameters:Q}=__(X,J),Z=F.join(" AND ");if(J.limit===void 0)return{parameters:Q,sql:`DELETE FROM ${_} WHERE ${Z}`};return Q.push(J.limit),{parameters:Q,sql:`DELETE FROM ${_} WHERE key IN (SELECT key FROM ${_} WHERE ${Z} ORDER BY key ASC LIMIT $${Q.length})`}}}}var W_="BEGIN ISOLATION LEVEL SERIALIZABLE",X_="BEGIN ISOLATION LEVEL READ COMMITTED",Y_="BEGIN READ ONLY",F_="COMMIT",q="ROLLBACK";function J_(_){return v(_,"schema"),`CREATE SCHEMA IF NOT EXISTS "${_}"`}Z_();s();var R_=new Set(["40001","40P01"]),G_=5;function v_(_){if(typeof _!=="object"||_===null||!("code"in _))return!1;let E=_.code;return typeof E==="string"&&R_.has(E)}class P{#_;#E;#W;#Y;#F;#J;constructor(_,E){if(this.#F=_.pool===void 0,_.pool===void 0){if(_.url===void 0)throw Error("PostgresKeyValueStorage requires either a `url` to build a pool from, or a pre-built `pool`; neither was provided.");this.#_=E(_.url)}else this.#_=_.pool;this.#W=_.schema;let W=e({schema:_.schema,table:_.table});this.#E=E_(W)}capabilities(){return{persistence:"remote",readAfterWrite:"linearizable",scanConsistency:"snapshot",atomicBatch:!0,conditionalBatch:!0,boundedRangeDelete:!0}}#X(){return this.#Y??=this.#G().catch((_)=>{throw this.#Y=void 0,_}),this.#Y}async#G(){if(this.#W!==void 0)await this.#_.query(J_(this.#W));await this.#_.query(this.#E.createTable),await this.#$()}async#$(){let E=(await this.#_.query(this.#E.selectKeyCollation,[this.#E.tableReference])).rows[0]?.collation;if(E==="C")return;let W=E===void 0?"no such table":typeof E==="string"?`"${E}"`:"an unexpected collation value";throw Error(`Postgres storage requires the ${this.#E.tableReference} table's "key" column to use COLLATE "C" (found ${W}). A table created without COLLATE "C" sorts keys by the database locale, which breaks Weft's lexicographic prefix scans. Use a fresh table, or recreate it as: CREATE TABLE ${this.#E.tableReference} (key TEXT COLLATE "C" PRIMARY KEY, value BYTEA NOT NULL).`)}async get(_){await this.#X();let W=(await this.#_.query(this.#E.selectValueByKey,[_])).rows[0];if(W===void 0)return null;let X=W.value;if(X===null||X===void 0)return null;return B(X)}async put(_,E){await this.#X(),await this.#_.query(this.#E.upsertValueByKey,[_,L(E)])}async delete(_){await this.#X(),await this.#_.query(this.#E.deleteValueByKey,[_])}async has(_){return await this.#X(),(await this.#_.query(this.#E.selectKeyPresence,[_])).rows.length>0}async deletePrefix(_){await this.#X();let[E,W]=D(_),X=await this.#_.query(this.#E.deleteKeysByPrefix,[E,W]);return z(X)}async deleteRange(_,E){await this.#X();let W=j(E),{parameters:X,sql:J}=this.#E.keyRangeDelete(_,W),F=await this.#_.query(J,X);return z(F)}async*scan(_,E={}){await this.#X();let{parameters:W,sql:X}=this.#E.keyValueRangeSelect(_,E),J=await this.#_.query(X,W);for(let F of J.rows)yield[F.key,B(F.value)]}async*keys(_,E={}){await this.#X();let{parameters:W,sql:X}=this.#E.keyRangeSelect(_,E),J=await this.#_.query(X,W);for(let F of J.rows)yield F.key}async count(_){await this.#X();let[E,W]=D(_),X=await this.#_.query(this.#E.countKeysByPrefix,[E,W]);return Number(X.rows[0]?.count??0)}scoped(_){return a(this,_)}async#Q(_,E,W=()=>!0){let X=await this.#_.connect();try{await X.query(_);try{let J=await E(X);return await X.query(W(J)?F_:q),J}catch(J){throw await X.query(q).catch(()=>{}),J}}finally{X.release()}}async batch(_){if($("batch operations",_.length),_.length===0)return;await this.#X(),await this.#Q(X_,async(E)=>{await R(E,this.#E,O(_))})}async conditionalBatch(_,E){$("conditionalBatch conditions",_.length),$("conditionalBatch operations",E.length),await this.#X();let W=O(E),X;for(let J=0;J<G_;J+=1)try{return await this.#Q(W_,async(F)=>{if(!await i(F,this.#E,_))return!1;return await R(F,this.#E,W),!0},(F)=>F)}catch(F){if(!v_(F))throw F;X=F}throw Error(`conditionalBatch exhausted ${G_} attempts after retryable transaction failures`,{cause:X})}async query(_,E){return await this.#X(),Q_(_),this.#Q(Y_,async(W)=>{return(await W.query(_,E??[])).rows})}#Z(){if(!this.#F)return Promise.resolve();return this.#J??=this.#_.end(),this.#J}[Symbol.dispose](){this.#Z().catch(()=>{})}async[Symbol.asyncDispose](){await this.#Z()}}function q_(_){return n(_,{driverName:"@neondatabase/serverless",storageName:"NeonStorage",loadPool:(E)=>import("@neondatabase/serverless").then(({Pool:W})=>new W({connectionString:E}))})}class P_ extends P{constructor(_,E=q_){super(_,E)}}export{P_ as NeonStorage};
@@ -51,7 +51,7 @@ export type PostgresBuiltQuery = {
51
51
  export declare function buildPostgresPrefixRangeParameters(prefix: string): [string, string];
52
52
  /**
53
53
  * The complete set of SQL statements an adapter instance runs, all bound to one
54
- * `tableReference`. Built once per {@link NeonStorage} via
54
+ * `tableReference`. Built once per storage instance via
55
55
  * {@link buildPostgresKeyValueQueries}; the range builders close over the
56
56
  * reference so callers never re-pass it.
57
57
  */
@@ -3,7 +3,7 @@ export const DEFAULT_POSTGRES_TABLE_REFERENCE = "kv";
3
3
  const POSTGRES_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_]*$/i;
4
4
  export function assertPostgresIdentifier(value, role) {
5
5
  if (!POSTGRES_IDENTIFIER_PATTERN.test(value))
6
- throw Error(`NeonStorage ${role} name "${value}" is not a valid Postgres identifier. Use only letters, digits, and underscores, starting with a letter or underscore (matching ${POSTGRES_IDENTIFIER_PATTERN.source}).`);
6
+ throw Error(`Postgres storage ${role} name "${value}" is not a valid Postgres identifier. Use only letters, digits, and underscores, starting with a letter or underscore (matching ${POSTGRES_IDENTIFIER_PATTERN.source}).`);
7
7
  }
8
8
  export function resolvePostgresTableReference(options) {
9
9
  const { schema, table } = options;
@@ -0,0 +1,110 @@
1
+ import { type DeleteRangeOptions } from './delete-range.ts';
2
+ import { type BatchOperation, type ConditionalBatchCondition, type ScanOptions, type Storage, type StorageCapabilities } from './interface.ts';
3
+ import { type NeonQueryResult } from './neon-value-mapping.ts';
4
+ /**
5
+ * A connection that can run a single interactive transaction. Obtained from
6
+ * {@link PostgresPool.connect}; `release()` returns it to the pool. Both
7
+ * `batch()` and `conditionalBatch()` drive `BEGIN`/`COMMIT`/`ROLLBACK` over one
8
+ * of these so every statement in a transaction lands on the same connection —
9
+ * `pool.query()` alone may scatter statements across pooled connections, which
10
+ * would make a multi-statement batch non-atomic.
11
+ */
12
+ export type PostgresPoolClient = {
13
+ query(sql: string, parameters?: unknown[]): Promise<NeonQueryResult>;
14
+ release(): void;
15
+ };
16
+ /**
17
+ * Minimal structural view of a node-postgres `Pool`. Both the `pg` `Pool` and
18
+ * the Neon serverless `Pool` satisfy this; the PGlite test backend is wrapped to
19
+ * satisfy it too. `query()` runs a single statement on a pooled connection (used
20
+ * for the single-statement hot paths); `connect()` pins a connection for an
21
+ * interactive transaction; `end()` tears the pool down.
22
+ */
23
+ export type PostgresPool = {
24
+ query(sql: string, parameters?: unknown[]): Promise<NeonQueryResult>;
25
+ connect(): Promise<PostgresPoolClient>;
26
+ end(): Promise<void>;
27
+ };
28
+ /**
29
+ * Configuration shared by every Postgres-wire storage adapter (the native `pg`
30
+ * {@link PostgresPool}-backed adapter and the Neon serverless one).
31
+ */
32
+ export type PostgresKeyValueStorageOptions = {
33
+ /**
34
+ * Postgres connection string. Required only when no `pool` is supplied — the
35
+ * adapter builds its own pool from this via the subclass's `poolFactory`. When
36
+ * `pool` is given, `url` is ignored and may be omitted entirely.
37
+ */
38
+ url?: string;
39
+ /**
40
+ * Optional pre-built pool. Pass this to reuse a pool you manage (for example a
41
+ * test backend such as PGlite, or a shared application pool), instead of having
42
+ * the adapter construct its own from `url`. When supplied, `url` is ignored and
43
+ * **ownership stays with the caller**: disposing the adapter does NOT close an
44
+ * injected pool, so it can be shared across adapters and the caller remains
45
+ * responsible for ending it. A pool the adapter constructs itself (from `url`)
46
+ * IS closed on disposal.
47
+ */
48
+ pool?: PostgresPool;
49
+ /**
50
+ * Postgres schema to contain the kv table. Default: unqualified — the table
51
+ * resolves through `search_path` (in practice `public`). When set, the adapter
52
+ * creates the schema if absent (`CREATE SCHEMA IF NOT EXISTS`) and qualifies
53
+ * every statement as `"schema"."table"`. Lets Weft live in its own schema
54
+ * alongside the application's tables in one database — one PITR line, no Drizzle
55
+ * drift/drop risk. Validated as a strict Postgres identifier at construction.
56
+ */
57
+ schema?: string;
58
+ /**
59
+ * Table name. Default: `'kv'`. Validated as a strict Postgres identifier at
60
+ * construction. With neither `schema` nor `table` set, the adapter emits
61
+ * byte-identical SQL against the unqualified `kv` table (existing deployments
62
+ * are unaffected).
63
+ */
64
+ table?: string;
65
+ };
66
+ /**
67
+ * Driver-agnostic base for Weft's Postgres-wire storage adapters. Implements the
68
+ * full `Storage` interface over a single `kv(key TEXT COLLATE "C", value BYTEA)`
69
+ * table using the structural {@link PostgresPool} seam, so switching between the
70
+ * native `pg` driver and the Neon serverless driver is a subclass choice, not a
71
+ * behavior change. Everything driver-specific — the driver import and the default
72
+ * connection-pool construction — lives in the concrete subclass, which passes a
73
+ * `poolFactory` to this constructor; the base itself carries no driver dependency.
74
+ *
75
+ * **Endpoint assumption.** `capabilities()` reports `readAfterWrite:
76
+ * 'linearizable'`, which holds for the **primary** endpoint. A read-replica
77
+ * connection string would violate that guarantee — point this adapter at the
78
+ * primary.
79
+ *
80
+ * @see {@link PostgresStorage} for the native `pg` adapter and {@link NeonStorage}
81
+ * for the Neon serverless adapter.
82
+ */
83
+ export declare class PostgresKeyValueStorage implements Storage {
84
+ #private;
85
+ /**
86
+ * @param options Connection configuration ({@link PostgresKeyValueStorageOptions}).
87
+ * @param poolFactory Constructs the owned pool from `url`. Required — the
88
+ * concrete subclass injects its driver's pool constructor here (lazily loaded)
89
+ * so the base module never imports a driver. Used only when no `pool` is
90
+ * supplied; an injected `pool` stays caller-owned. Throws if neither `pool`
91
+ * nor `url` is provided.
92
+ */
93
+ constructor(options: PostgresKeyValueStorageOptions, poolFactory: (url: string) => PostgresPool);
94
+ capabilities(): StorageCapabilities;
95
+ get(key: string): Promise<Uint8Array | null>;
96
+ put(key: string, value: Uint8Array): Promise<void>;
97
+ delete(key: string): Promise<void>;
98
+ has(key: string): Promise<boolean>;
99
+ deletePrefix(prefix: string): Promise<number>;
100
+ deleteRange(prefix: string, options: DeleteRangeOptions): Promise<number>;
101
+ scan(prefix: string, options?: ScanOptions): AsyncIterable<[string, Uint8Array]>;
102
+ keys(prefix: string, options?: ScanOptions): AsyncIterable<string>;
103
+ count(prefix: string): Promise<number>;
104
+ scoped(prefix: string): Storage;
105
+ batch(operations: BatchOperation[]): Promise<void>;
106
+ conditionalBatch(conditions: ConditionalBatchCondition[], operations: BatchOperation[]): Promise<boolean>;
107
+ query<T>(sql: string, parameters?: unknown[]): Promise<T[]>;
108
+ [Symbol.dispose](): void;
109
+ [Symbol.asyncDispose](): Promise<void>;
110
+ }