@postgresx/noredis 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/README.md ADDED
@@ -0,0 +1,360 @@
1
+ # pgredis
2
+
3
+ PostgreSQL-only application infrastructure toolkit for projects that want to
4
+ replace a Redis + PostgreSQL stack with PostgreSQL alone.
5
+
6
+ `pgredis` is not a Redis protocol-compatible client and is not a drop-in
7
+ replacement for `ioredis`, `node-redis`, Bull, or Redis Cluster. It replaces the
8
+ Redis infrastructure use cases with PostgreSQL-friendly primitives.
9
+
10
+ It provides:
11
+
12
+ - KV/TTL cache
13
+ - atomic counters
14
+ - hash, set, list, and sorted-set helpers
15
+ - cursor-style scans and structure-level TTL for collection helpers
16
+ - Pub/Sub helpers via PostgreSQL `LISTEN/NOTIFY`
17
+ - transaction-scoped advisory locks
18
+ - fixed-window, sliding-window, and token-bucket rate limiting
19
+ - a simple `pg-boss` queue adapter for background jobs and long tasks
20
+ - a `createPgredis()` facade for one-shot initialization, health, stats, and cleanup
21
+
22
+ ## Installation
23
+
24
+ `@postgresx/noredis` itself has no required runtime dependencies. Install runtime-specific
25
+ packages only for the adapters or features you use.
26
+
27
+ ### Bun.js
28
+
29
+ Base toolkit with `Bun.SQL`:
30
+
31
+ ```bash
32
+ bun add @postgresx/noredis
33
+ ```
34
+
35
+ ```ts
36
+ import { SQL } from "bun";
37
+ import { createPgredis } from "@postgresx/noredis";
38
+ import { createBunSqlAdapter } from "@postgresx/noredis/adapters/bun";
39
+
40
+ const sql = createBunSqlAdapter(new SQL(process.env.DATABASE_URL!));
41
+ const pg = createPgredis({ sql, namespace: "app" });
42
+ ```
43
+
44
+ Bun realtime `LISTEN/NOTIFY`:
45
+
46
+ ```bash
47
+ bun add @postgresx/noredis @postgresx/bun-listen
48
+ ```
49
+
50
+ ```ts
51
+ import { createBunPgListener, publishPgNotify } from "@postgresx/noredis";
52
+
53
+ const listener = createBunPgListener(process.env.DATABASE_URL!, {
54
+ channels: ["cache_invalidate"],
55
+ onNotify(channel, payload) {
56
+ console.log(channel, payload);
57
+ }
58
+ });
59
+
60
+ await publishPgNotify(sql, "cache_invalidate", { key: "token:abc" });
61
+ listener.close();
62
+ ```
63
+
64
+ Install only the Bun-native listener when you do not need the rest of the
65
+ toolkit:
66
+
67
+ ```bash
68
+ bun add @postgresx/bun-listen
69
+ ```
70
+
71
+ ```ts
72
+ import { createPgListener } from "@postgresx/bun-listen";
73
+
74
+ const listener = createPgListener(process.env.DATABASE_URL!, ["events"], (_channel, payload) => {
75
+ console.log(payload);
76
+ });
77
+ ```
78
+
79
+ ### Node.js
80
+
81
+ Base toolkit with `pg`:
82
+
83
+ ```bash
84
+ npm install @postgresx/noredis pg
85
+ ```
86
+
87
+ ```ts
88
+ import { createPgredis } from "@postgresx/noredis";
89
+ import { createPgAdapter } from "@postgresx/noredis/adapters/node";
90
+
91
+ const sql = createPgAdapter(process.env.DATABASE_URL!);
92
+ const pg = createPgredis({ sql, namespace: "app" });
93
+ ```
94
+
95
+ Node.js `LISTEN/NOTIFY`:
96
+
97
+ ```ts
98
+ import { createPgNodeListener } from "@postgresx/noredis/adapters/node";
99
+
100
+ const listener = createPgNodeListener(process.env.DATABASE_URL!, {
101
+ channels: ["cache_invalidate"],
102
+ onNotify(channel, payload) {
103
+ console.log(channel, payload);
104
+ }
105
+ });
106
+ ```
107
+
108
+ Queues with `pg-boss`:
109
+
110
+ ```bash
111
+ npm install @postgresx/noredis pg pg-boss
112
+ ```
113
+
114
+ ## KV/TTL Cache
115
+
116
+ ```ts
117
+ import { createPgKvCache } from "@postgresx/noredis";
118
+
119
+ const cache = createPgKvCache({
120
+ sql,
121
+ namespace: "auth",
122
+ l1: { max: 10_000, ttlMs: 60_000 }
123
+ });
124
+
125
+ await cache.ensureSchema();
126
+ await cache.set("token:abc", { userId: 1 }, { ttlMs: 60_000 });
127
+ const value = await cache.get<{ userId: number }>("token:abc");
128
+ ```
129
+
130
+ ## Unified client
131
+
132
+ ```ts
133
+ import { createPgredis } from "@postgresx/noredis";
134
+
135
+ const pg = createPgredis({
136
+ sql,
137
+ namespace: "app",
138
+ rateLimit: { limit: 60, windowMs: 60_000 },
139
+ queue: {
140
+ connectionString: process.env.DATABASE_URL,
141
+ schema: "pgboss"
142
+ }
143
+ });
144
+
145
+ await pg.ensureSchema();
146
+
147
+ await pg.cache.set("token:abc", { userId: 1 }, { ttlMs: 60_000 });
148
+ await pg.counter.incr("daily:requests");
149
+ await pg.hash.hset("session:abc", "userId", 1);
150
+ await pg.set.sadd("online-users", "1");
151
+ await pg.list.rpush("recent-events", { id: "evt_1" });
152
+ await pg.sortedSet.zadd("leaderboard", 100, "user:1");
153
+ await pg.hash.expire("session:abc", 60_000);
154
+ await pg.hash.hscan("session:abc", null, 100);
155
+ await pg.health();
156
+ await pg.stats();
157
+ const stopCleanup = pg.startCleanupWorker({ intervalMs: 60_000 });
158
+ ```
159
+
160
+ ## Pub/Sub
161
+
162
+ Publishing uses only the configured SQL adapter. Bun LISTEN/NOTIFY consumption
163
+ uses the separate `@postgresx/bun-listen` package and loads it dynamically.
164
+
165
+ ```bash
166
+ bun add @postgresx/bun-listen
167
+ ```
168
+
169
+ ```ts
170
+ import { createBunPgListener, publishPgNotify } from "@postgresx/noredis";
171
+
172
+ createBunPgListener(databaseUrl, ["cache_invalidate"], (_channel, payload) => {
173
+ console.log(payload);
174
+ });
175
+
176
+ await publishPgNotify(sql, "cache_invalidate", { key: "token:abc" });
177
+ ```
178
+
179
+ Node.js can use the `pg`-based listener from the adapter subpath:
180
+
181
+ ```ts
182
+ import { createPgNodeListener } from "@postgresx/noredis/adapters/node";
183
+
184
+ createPgNodeListener(process.env.DATABASE_URL!, {
185
+ channels: ["cache_invalidate"],
186
+ onNotify(_channel, payload) {
187
+ console.log(payload);
188
+ }
189
+ });
190
+ ```
191
+
192
+ ## Advisory lock
193
+
194
+ `withPgAdvisoryLock` uses transaction-scoped locks, so locks are released by
195
+ PostgreSQL when the transaction ends.
196
+
197
+ ```ts
198
+ import { withPgAdvisoryLock } from "@postgresx/noredis";
199
+
200
+ await withPgAdvisoryLock(sql, "billing:flush", async (tx) => {
201
+ await tx.unsafe("SELECT 1");
202
+ });
203
+ ```
204
+
205
+ ## Rate limit
206
+
207
+ ```ts
208
+ import { createPgFixedWindowRateLimiter } from "@postgresx/noredis";
209
+
210
+ const limiter = createPgFixedWindowRateLimiter({
211
+ sql,
212
+ namespace: "api",
213
+ limit: 60,
214
+ windowMs: 60_000
215
+ });
216
+
217
+ await limiter.ensureSchema();
218
+ const result = await limiter.hit("user:1");
219
+ ```
220
+
221
+ ## Queue
222
+
223
+ ```ts
224
+ import { createPgBossJobQueue } from "@postgresx/noredis";
225
+
226
+ const queue = createPgBossJobQueue({
227
+ connectionString: process.env.DATABASE_URL,
228
+ schema: "pgboss",
229
+ queues: {
230
+ "webhook.deliver": { retryLimit: 5, retryBackoff: true }
231
+ }
232
+ });
233
+
234
+ await queue.start();
235
+ await queue.send("webhook.deliver", { event: "created" });
236
+ await queue.work("webhook.deliver", { batchSize: 1 }, async (jobs) => {
237
+ for (const job of jobs) console.log(job.data);
238
+ });
239
+ ```
240
+
241
+ `pg-boss` is loaded dynamically and is not a runtime dependency of `@postgresx/noredis`.
242
+ Install it only when queue features are used:
243
+
244
+ ```bash
245
+ npm install @postgresx/noredis pg-boss
246
+ ```
247
+
248
+ `@postgresx/noredis` intentionally keeps the queue API close to `pg-boss`:
249
+
250
+ - `start()` starts `pg-boss` and creates configured queues.
251
+ - `ensureQueue()` creates or updates queue metadata.
252
+ - `send()` enqueues jobs.
253
+ - `work()` registers workers.
254
+ - `getBoss()` returns the underlying `PgBoss` instance for advanced cases.
255
+
256
+ This covers Redis-backed background job use cases such as Bull-style async
257
+ webhooks, billing flushes, retries, and long tasks. It does not emulate Redis
258
+ Streams commands.
259
+
260
+ ## Launch readiness
261
+
262
+ Current local verification:
263
+
264
+ - `bun run build` passes for `@postgresx/bun-listen` and `@postgresx/noredis`.
265
+ - `bun test packages/` passes the package test suite.
266
+ - `bun run check` passes TypeScript checks.
267
+
268
+ Remaining gates before a production or 1.0 launch:
269
+
270
+ | Area | Status | Why it matters | Recommended action |
271
+ | --- | --- | --- | --- |
272
+ | Real database coverage | Added in CI | PostgreSQL DDL, indexes, transactions, JSONB behavior, and LISTEN/NOTIFY reconnect behavior need real database coverage. | CI runs `bun run test:integration` against PostgreSQL 16. Run locally with `TEST_DATABASE_URL` when debugging. |
273
+ | Benchmark baseline | Pending CI run | `benchmark.md` has not been generated yet, so there is no measured Redis vs PostgreSQL baseline to set user expectations. | Run the manual benchmark workflow before release; local benchmark runs are optional. |
274
+ | Install smoke test | Added in CI | Build output exists, but the published package shape should be verified from a packed tarball, including subpath exports. | CI runs `bun run smoke:pack` to import packed tarballs from clean Node and Bun entrypoints. |
275
+ | Release credentials | Guarded in workflows | Release Please and npm publish depend on repository secrets and npm provenance setup. | Workflows fail early when `RELEASE_PAT` or `NPM_TOKEN` is missing; still verify package access before the first release. |
276
+ | Runtime operations | Documented | Cleanup, table growth, queue lag, and listener health are app-operational concerns. | See `docs/production-runbook.md` for cleanup, bloat checks, listener health, queue monitoring, and rollback guidance. |
277
+
278
+ The package is suitable for an early beta once CI passes and the benchmark
279
+ workflow has produced a baseline. It should not be described as a drop-in Redis
280
+ or ioredis replacement.
281
+
282
+ ## ioredis comparison
283
+
284
+ `ioredis` is a Redis protocol client. `pgredis` is a PostgreSQL-native toolkit
285
+ that replaces common Redis-backed application primitives without speaking the
286
+ Redis protocol or supporting every Redis command.
287
+
288
+ | Capability | ioredis | pgredis | Launch implication |
289
+ | --- | --- | --- | --- |
290
+ | Protocol and command surface | Sends Redis commands and supports arbitrary Redis command methods. | Exposes typed PostgreSQL-backed primitives only. | Migration requires code changes. Redis command compatibility is intentionally out of scope. |
291
+ | Runtime dependency | Requires Redis, Redis-compatible service, or Redis Cluster/Sentinel. | Requires PostgreSQL; optional `pg`, `pg-boss`, or `@postgresx/bun-listen` only for selected features. | Good fit for teams removing a separate Redis tier. |
292
+ | Strings / KV / TTL | Full Redis string command surface. | JSONB KV cache with TTL, batch get/set, prefix clear, optional local L1 cache, and notification invalidation. | Covers cache/session-style values, but not byte-string commands such as `APPEND`, `GETRANGE`, or `SETRANGE`. |
293
+ | Hashes, lists, sets, sorted sets | Native Redis data structures and command coverage. | PostgreSQL table-backed helpers for common hash/list/set/zset operations. | Covers common app usage; advanced/blocking/list mutation and full command parity are not complete. |
294
+ | Pub/Sub | Redis Pub/Sub, pattern subscriptions, binary messages, cluster behavior. | PostgreSQL `LISTEN/NOTIFY` publisher and Node/Bun listeners. | Good for lightweight invalidation/events; not durable and limited by PostgreSQL NOTIFY payload size. |
295
+ | Streams / consumer groups | Redis Streams commands such as `XADD` and consumer groups. | No Redis Streams API; queues are delegated to `pg-boss`. | Add a durable outbox/stream API if event-log semantics are required. |
296
+ | Pipelining / transactions | `pipeline`, `multi`, `exec`, and cluster-aware behavior. | Batch helpers exist for some primitives; no generic pipeline or Redis-style transaction facade. | Add a pgredis batch/pipeline facade for migration ergonomics. |
297
+ | Lua scripting / Redis Functions | Supports scripting commands and custom command definitions. | Out of scope; use SQL, stored procedures, or application code. | Do not port Lua directly; rewrite as SQL/app logic. |
298
+ | Cluster / Sentinel / NAT mapping | Built into ioredis. | Inherited from PostgreSQL HA, pooling, and networking. | Document PostgreSQL deployment assumptions instead of Redis HA options. |
299
+ | TLS / ACL / auth | Redis connection, TLS, and ACL options. | Delegated to PostgreSQL driver, DSN, and database roles. | Use PostgreSQL credentials and transport settings. |
300
+ | Redis Stack modules | Can send module commands, depending on Redis server support. | No RedisJSON, RediSearch, RedisTimeSeries, RedisBloom facade. | Prefer PostgreSQL JSONB, full-text search, pgvector, PostGIS, or extensions. |
301
+ | Offline queue / reconnect strategy | Client-level offline queue, retry, ready checks, auto-resubscribe. | Node/Bun listeners include reconnect and health state; SQL operations depend on the database adapter/pool behavior. | Add operation-level retry guidance and adapter smoke tests. |
302
+
303
+ ## Redis feature coverage
304
+
305
+ Redis has a broad surface area across core data types, server operations,
306
+ programmability, clustering, modules, and observability. `pgredis` targets
307
+ feature replacement, not command compatibility.
308
+
309
+ | Redis capability | pgredis status | Replacement strategy | Gap |
310
+ | --- | --- | --- | --- |
311
+ | String `GET`/`SET`/`DEL`/TTL | Covered | `PgKvCache` stores JSONB values with optional TTL and L1 cache | No byte-level Redis string ops such as `APPEND`, `GETRANGE`, `SETRANGE` |
312
+ | Key expiration | Covered | `expires_at`, `cleanupExpired`, L1 TTL | No Redis passive/active eviction semantics or keyspace notifications |
313
+ | Batch get/set | Covered | `mget`, `mset` | No pipelining API yet |
314
+ | Atomic counters | Covered | `PgCounter` over BIGINT UPSERT | Integer counters only |
315
+ | Pub/Sub | Covered | `LISTEN/NOTIFY` plus `createPgListener` | Not durable, payload size is limited by PostgreSQL NOTIFY |
316
+ | Distributed locks | Covered | Transaction-scoped advisory locks | No Redlock-compatible lease renewal model |
317
+ | Fixed-window rate limit | Covered | UPSERT counter table with window reset metadata | Covered for coarse windows |
318
+ | Sliding-window rate limit | Covered | Bucketed moving-window counters | Precision depends on configured bucket size |
319
+ | Token-bucket rate limit | Covered | PostgreSQL row state with refill calculation | Designed for app-level API throttling |
320
+ | Queues / delayed jobs / retries | Covered via adapter | `pg-boss` wrapper | Not Redis Streams compatible |
321
+ | Hashes | Covered | `PgHash` over `(namespace, key, field)` rows | `HSCAN`-style cursor scan and key TTL covered; no per-field TTL |
322
+ | Lists | Covered | `PgList` over ordered rows | Cursor scan and key TTL covered; no blocking pop; use pg-boss for real job queues |
323
+ | Sets | Covered | `PgSet` over unique-indexed rows | `SINTER`, `SUNION`, `SDIFF`, cursor scan, and key TTL covered |
324
+ | Sorted sets | Covered | `PgSortedSet` over `(member, score)` rows | Rank, score range, count, pop-min, scan, and key TTL covered |
325
+ | Streams / consumer groups | Delegated / missing | Use `pg-boss` for jobs; application table for event logs | No `XADD`, `XREADGROUP`, pending-entry list |
326
+ | Transactions / optimistic watch | Missing | Use PostgreSQL transactions and row locks directly | No Redis `MULTI`/`EXEC`/`WATCH` facade |
327
+ | Lua scripting / functions | Out of scope | Use SQL, stored procedures, or app code | No Redis Lua/function runtime |
328
+ | Bitmaps / bitfields | Missing | Use `bytea`, roaring bitmap extension, or SQL tables | No bit operation API |
329
+ | HyperLogLog | Missing | Use PostgreSQL extensions or approximate-count tables | No `PFADD`/`PFCOUNT` |
330
+ | Geospatial | Missing | Use PostGIS | No Redis GEO command facade |
331
+ | JSON document commands | Partial | KV values are JSONB | No RedisJSON path mutation/query API |
332
+ | Search / vector search | Missing | Use PostgreSQL full-text search, `pg_trgm`, `pgvector` | No RediSearch-compatible query API |
333
+ | Time series | Missing | Use hypertables/partitioned tables/TimescaleDB | No RedisTimeSeries API |
334
+ | Bloom / Cuckoo / Count-Min | Missing | Use PostgreSQL extensions or app tables | No RedisBloom-compatible API |
335
+ | ACL/auth | Out of scope | Use PostgreSQL credentials and application auth | No Redis ACL facade |
336
+ | Persistence/replication/cluster | Out of scope | Inherited from PostgreSQL deployment | No Redis Cluster slot/hash semantics |
337
+ | Server introspection | Partial | `createPgredis().health()` and `stats()` expose basic health/cache/queue stats | No Redis `INFO`, `MONITOR`, command stats facade |
338
+
339
+ ## Missing pieces to consider next
340
+
341
+ The highest-value additions for Redis replacement are now:
342
+
343
+ 1. PostgreSQL integration test suite and tarball install smoke tests.
344
+ 2. Generic `batch()` or `pipeline()` facade for grouping pgredis operations.
345
+ 3. Durable outbox/stream API for applications that currently use Redis Streams.
346
+ 4. Blocking list pop or explicit queue-first migration guidance for worker pulls.
347
+ 5. Production metrics for table sizes, cleanup counts, TTL backlog, listener reconnects, and queue lag.
348
+ 6. Redis-style migration aliases for the most common commands, without claiming protocol compatibility.
349
+ 7. Framework adapters such as session stores for Express/Fastify/Elysia and cache helpers for common web stacks.
350
+ 8. More KV options: `set` NX/XX semantics, compare-and-swap, touch/expire helpers, and configurable serialization.
351
+
352
+ ## Design notes
353
+
354
+ This is a toolkit, not a Redis-compatible client. It intentionally exposes
355
+ PostgreSQL-friendly semantics:
356
+
357
+ - locks are transaction-scoped advisory locks
358
+ - pub/sub is `LISTEN/NOTIFY`, not durable messaging
359
+ - queues are delegated to `pg-boss`
360
+ - KV values are JSONB rows with optional local L1 caching
@@ -0,0 +1,13 @@
1
+ import { P as PgSqlLike } from '../sql-DKf2TDlu.js';
2
+
3
+ interface BunSqlAdapterInput {
4
+ unsafe<T = Record<string, unknown>>(query: string, params?: readonly unknown[]): Promise<T[]>;
5
+ begin?<T>(callback: (tx: PgSqlLike) => Promise<T>): Promise<T>;
6
+ }
7
+ interface BunSqlAdapter extends PgSqlLike {
8
+ readonly raw: BunSqlAdapterInput;
9
+ }
10
+ declare function createBunSqlAdapter(sql: BunSqlAdapterInput): BunSqlAdapter;
11
+ declare const createBunPostgresAdapter: typeof createBunSqlAdapter;
12
+
13
+ export { type BunSqlAdapter, type BunSqlAdapterInput, createBunPostgresAdapter, createBunSqlAdapter };
@@ -0,0 +1,15 @@
1
+ // src/adapters/bun.ts
2
+ function createBunSqlAdapter(sql) {
3
+ return {
4
+ raw: sql,
5
+ unsafe(query, params) {
6
+ return sql.unsafe(query, params);
7
+ },
8
+ begin: sql.begin ? (callback) => sql.begin((tx) => callback(createBunSqlAdapter(tx))) : void 0
9
+ };
10
+ }
11
+ var createBunPostgresAdapter = createBunSqlAdapter;
12
+ export {
13
+ createBunPostgresAdapter,
14
+ createBunSqlAdapter
15
+ };
@@ -0,0 +1,22 @@
1
+ import { Pool, ClientConfig, PoolConfig } from 'pg';
2
+ import { N as NotifyHandler, a as PgListenerHandle } from '../pubsub-CHGs5dXU.js';
3
+ import { P as PgSqlLike } from '../sql-DKf2TDlu.js';
4
+
5
+ type PgConnectionInput = string | PoolConfig | Pool;
6
+ interface NodePgAdapter extends PgSqlLike {
7
+ getPool(): Promise<Pool>;
8
+ close(): Promise<void>;
9
+ }
10
+ declare function createPgAdapter(input: PgConnectionInput): NodePgAdapter;
11
+ declare const createNodePostgresAdapter: typeof createPgAdapter;
12
+ type ListenerLogger = Partial<Pick<typeof console, "debug" | "info" | "warn" | "error">>;
13
+ interface NodePgListenerOptions extends ClientConfig {
14
+ channels?: string[];
15
+ onNotify?: NotifyHandler;
16
+ reconnectDelayMs?: number | ((attempt: number) => number);
17
+ healthCheckIntervalMs?: number;
18
+ logger?: ListenerLogger | false;
19
+ }
20
+ declare function createPgNodeListener(input: string | ClientConfig, options?: NodePgListenerOptions): PgListenerHandle;
21
+
22
+ export { type NodePgAdapter, type NodePgListenerOptions, type PgConnectionInput, createNodePostgresAdapter, createPgAdapter, createPgNodeListener };
@@ -0,0 +1,258 @@
1
+ // src/adapters/node.ts
2
+ var PgClientSql = class {
3
+ constructor(client) {
4
+ this.client = client;
5
+ }
6
+ client;
7
+ async unsafe(query, params = []) {
8
+ const result = await this.client.query(query, [...params]);
9
+ return result.rows;
10
+ }
11
+ };
12
+ var PgPoolSql = class {
13
+ constructor(input) {
14
+ this.input = input;
15
+ this.pool = isPool(input) ? input : null;
16
+ this.ownsPool = !isPool(input);
17
+ }
18
+ input;
19
+ pool;
20
+ ownsPool;
21
+ async getPool() {
22
+ if (this.pool) return this.pool;
23
+ const { Pool } = await loadPg();
24
+ if (typeof this.input === "string") {
25
+ this.pool = new Pool({ connectionString: this.input });
26
+ } else if (isPool(this.input)) {
27
+ this.pool = this.input;
28
+ } else {
29
+ this.pool = new Pool(this.input);
30
+ }
31
+ return this.pool;
32
+ }
33
+ async unsafe(query, params = []) {
34
+ const pool = await this.getPool();
35
+ const result = await pool.query(query, [...params]);
36
+ return result.rows;
37
+ }
38
+ async begin(callback) {
39
+ const pool = await this.getPool();
40
+ const client = await pool.connect();
41
+ try {
42
+ await client.query("BEGIN");
43
+ const result = await callback(new PgClientSql(client));
44
+ await client.query("COMMIT");
45
+ return result;
46
+ } catch (error) {
47
+ await client.query("ROLLBACK").catch(() => void 0);
48
+ throw error;
49
+ } finally {
50
+ client.release();
51
+ }
52
+ }
53
+ async close() {
54
+ if (this.ownsPool && this.pool) await this.pool.end();
55
+ this.pool = null;
56
+ }
57
+ };
58
+ async function loadPg() {
59
+ try {
60
+ const specifier = "pg";
61
+ return await import(specifier);
62
+ } catch (error) {
63
+ throw new Error("pg is required for pgredis Node.js adapters. Install it with `npm install pg`.", {
64
+ cause: error
65
+ });
66
+ }
67
+ }
68
+ function isPool(input) {
69
+ return typeof input === "object" && input !== null && "connect" in input && "query" in input && "end" in input;
70
+ }
71
+ function createPgAdapter(input) {
72
+ return new PgPoolSql(input);
73
+ }
74
+ var createNodePostgresAdapter = createPgAdapter;
75
+ var TypedEventEmitter = class {
76
+ listeners = /* @__PURE__ */ new Map();
77
+ on(event, handler) {
78
+ const bucket = this.listeners.get(event) ?? /* @__PURE__ */ new Set();
79
+ bucket.add(handler);
80
+ this.listeners.set(event, bucket);
81
+ return () => this.off(event, handler);
82
+ }
83
+ off(event, handler) {
84
+ const bucket = this.listeners.get(event);
85
+ if (!bucket) return;
86
+ bucket.delete(handler);
87
+ if (bucket.size === 0) this.listeners.delete(event);
88
+ }
89
+ emit(event, payload) {
90
+ const bucket = this.listeners.get(event);
91
+ if (!bucket) return;
92
+ for (const handler of [...bucket]) handler(payload);
93
+ }
94
+ };
95
+ function quoteListenIdentifier(identifier) {
96
+ if (!identifier || identifier.includes("\0")) {
97
+ throw new Error("PostgreSQL identifier must be non-empty and cannot contain null bytes");
98
+ }
99
+ return `"${identifier.replace(/"/g, '""')}"`;
100
+ }
101
+ function toError(error) {
102
+ return error instanceof Error ? error : new Error(String(error));
103
+ }
104
+ function resolveDelay(delay, attempt) {
105
+ return typeof delay === "function" ? delay(attempt) : delay;
106
+ }
107
+ function buildClientConfig(input, options) {
108
+ const { channels: _channels, onNotify: _onNotify, reconnectDelayMs: _reconnectDelayMs, healthCheckIntervalMs: _healthCheckIntervalMs, logger: _logger, ...clientOptions } = options;
109
+ if (typeof input === "string") return { ...clientOptions, connectionString: input };
110
+ return { ...input, ...clientOptions };
111
+ }
112
+ function createPgNodeListener(input, options = {}) {
113
+ const subscribedChannels = new Set(options.channels ?? []);
114
+ const logger = options.logger === false ? null : options.logger ?? console;
115
+ const emitter = new TypedEventEmitter();
116
+ const reconnectDelay = options.reconnectDelayMs ?? 3e3;
117
+ const healthCheckIntervalMs = options.healthCheckIntervalMs ?? 3e4;
118
+ let status = "connecting";
119
+ let closed = false;
120
+ let client = null;
121
+ let reconnectTimer = null;
122
+ let healthTimer = null;
123
+ let reconnectAttempts = 0;
124
+ let lastConnectedAt = null;
125
+ let lastMessageAt = null;
126
+ let lastNotificationAt = null;
127
+ let lastError = null;
128
+ let connecting = null;
129
+ function getHealth() {
130
+ return {
131
+ status,
132
+ connected: status === "connected",
133
+ listeningChannels: [...subscribedChannels],
134
+ queuedQueries: 0,
135
+ activeQuery: false,
136
+ reconnectAttempts,
137
+ lastConnectedAt,
138
+ lastMessageAt,
139
+ lastNotificationAt,
140
+ lastError
141
+ };
142
+ }
143
+ function emitHealth() {
144
+ emitter.emit("health", getHealth());
145
+ }
146
+ function setStatus(next) {
147
+ status = next;
148
+ emitHealth();
149
+ }
150
+ function reportError(error) {
151
+ lastError = error.message;
152
+ logger?.error?.("[pgredis-node-listen]", error);
153
+ emitter.emit("error", error);
154
+ emitHealth();
155
+ }
156
+ function startHealthTimer() {
157
+ stopHealthTimer();
158
+ if (healthCheckIntervalMs <= 0) return;
159
+ healthTimer = setInterval(() => {
160
+ if (closed || !client || status !== "connected") return;
161
+ void client.query("SELECT 1").catch((error) => {
162
+ reportError(toError(error));
163
+ void client?.end().catch(() => void 0);
164
+ });
165
+ }, healthCheckIntervalMs);
166
+ }
167
+ function stopHealthTimer() {
168
+ if (healthTimer) clearInterval(healthTimer);
169
+ healthTimer = null;
170
+ }
171
+ function scheduleReconnect(error) {
172
+ if (closed) return;
173
+ stopHealthTimer();
174
+ reconnectAttempts += 1;
175
+ const delayMs = resolveDelay(reconnectDelay, reconnectAttempts);
176
+ setStatus("reconnecting");
177
+ emitter.emit("reconnect", { attempt: reconnectAttempts, delayMs });
178
+ if (error) reportError(error);
179
+ if (reconnectTimer) clearTimeout(reconnectTimer);
180
+ reconnectTimer = setTimeout(() => void connect(), delayMs);
181
+ }
182
+ function handleNotification(message) {
183
+ lastMessageAt = Date.now();
184
+ lastNotificationAt = lastMessageAt;
185
+ const payload = message.payload ?? "";
186
+ try {
187
+ options.onNotify?.(message.channel, payload);
188
+ } catch (error) {
189
+ reportError(toError(error));
190
+ }
191
+ emitter.emit("notification", { channel: message.channel, payload });
192
+ emitHealth();
193
+ }
194
+ async function connect() {
195
+ if (closed || connecting) return connecting ?? void 0;
196
+ setStatus(reconnectAttempts > 0 ? "reconnecting" : "connecting");
197
+ const { Client } = await loadPg();
198
+ const pgClient = new Client(buildClientConfig(input, options));
199
+ client = pgClient;
200
+ pgClient.on("notification", handleNotification);
201
+ pgClient.on("error", (error) => {
202
+ if (client === pgClient) scheduleReconnect(error);
203
+ });
204
+ pgClient.on("end", () => {
205
+ if (client === pgClient && !closed) scheduleReconnect();
206
+ });
207
+ connecting = pgClient.connect().then(async () => {
208
+ for (const channel of subscribedChannels) {
209
+ await pgClient.query(`LISTEN ${quoteListenIdentifier(channel)}`);
210
+ }
211
+ reconnectAttempts = 0;
212
+ lastConnectedAt = Date.now();
213
+ setStatus("connected");
214
+ startHealthTimer();
215
+ emitter.emit("connected", getHealth());
216
+ }).catch((error) => {
217
+ reportError(toError(error));
218
+ if (!closed) scheduleReconnect();
219
+ }).finally(() => {
220
+ connecting = null;
221
+ });
222
+ return connecting;
223
+ }
224
+ void connect();
225
+ return {
226
+ close() {
227
+ if (closed) return;
228
+ closed = true;
229
+ if (reconnectTimer) clearTimeout(reconnectTimer);
230
+ reconnectTimer = null;
231
+ stopHealthTimer();
232
+ const activeClient = client;
233
+ client = null;
234
+ void activeClient?.end().catch(() => void 0);
235
+ setStatus("closed");
236
+ emitter.emit("close", { willReconnect: false });
237
+ },
238
+ async notify(channel, payload = "") {
239
+ const activeClient = client;
240
+ if (!activeClient || status !== "connected") {
241
+ throw new Error("PostgreSQL listener is not connected");
242
+ }
243
+ await activeClient.query("SELECT pg_notify($1, $2)", [channel, payload]);
244
+ },
245
+ getHealth,
246
+ on(event, handler) {
247
+ return emitter.on(event, handler);
248
+ },
249
+ off(event, handler) {
250
+ emitter.off(event, handler);
251
+ }
252
+ };
253
+ }
254
+ export {
255
+ createNodePostgresAdapter,
256
+ createPgAdapter,
257
+ createPgNodeListener
258
+ };