@super-line/store-pglite 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mert
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ pgliteStoreServer: () => pgliteStoreServer
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+ var import_pglite = require("@electric-sql/pglite");
37
+ var import_live = require("@electric-sql/pglite/live");
38
+ var import_pglite_sync = require("@electric-sql/pglite-sync");
39
+ var import_postgres = __toESM(require("postgres"), 1);
40
+ var import_core = require("@super-line/core");
41
+ var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
42
+ async function pgliteStoreServer(opts) {
43
+ const table = opts.table ?? "resources";
44
+ if (!IDENT.test(table)) throw new Error(`Invalid table name: ${table}`);
45
+ const ddl = `CREATE TABLE IF NOT EXISTS "${table}" (id text PRIMARY KEY, data jsonb NOT NULL, access jsonb NOT NULL, origin text)`;
46
+ const sql = (0, import_postgres.default)(opts.pgUrl, { prepare: false, onnotice: () => {
47
+ } });
48
+ try {
49
+ await sql.unsafe(ddl);
50
+ } catch (err) {
51
+ const code = err.code;
52
+ if (code !== "42P07" && code !== "23505") throw err;
53
+ }
54
+ const asJson = (v) => sql.json(v);
55
+ const ownsDb = !opts.db;
56
+ const db = opts.db ?? await import_pglite.PGlite.create({ extensions: { live: import_live.live, sync: (0, import_pglite_sync.electricSync)() } });
57
+ await db.exec(ddl);
58
+ const changeCbs = /* @__PURE__ */ new Set();
59
+ const deleteCbs = /* @__PURE__ */ new Set();
60
+ const liveSub = await db.live.changes(`SELECT id, data, origin FROM "${table}"`, [], "id", (changes) => {
61
+ for (const ch of changes) {
62
+ if (ch.__op__ === "DELETE") {
63
+ for (const cb of deleteCbs) cb(ch.id);
64
+ } else if (ch.__op__ === "INSERT" || ch.__op__ === "UPDATE") {
65
+ const change = { id: ch.id, update: ch.data, origin: ch.origin ?? "" };
66
+ for (const cb of changeCbs) cb(change);
67
+ }
68
+ }
69
+ });
70
+ const shape = opts.electricUrl && db.sync ? await db.sync.syncShapeToTable({
71
+ shape: { url: opts.electricUrl, params: { table } },
72
+ table,
73
+ primaryKey: ["id"],
74
+ shapeKey: null
75
+ }) : void 0;
76
+ return {
77
+ clustering: "self",
78
+ model: "lww",
79
+ async read(id) {
80
+ const rows = await sql`SELECT data::text AS data, access::text AS access FROM ${sql(table)} WHERE id = ${id}`;
81
+ const row = rows[0];
82
+ if (!row) return void 0;
83
+ return { id, data: JSON.parse(row.data), accessRules: JSON.parse(row.access) };
84
+ },
85
+ async create(id, data, accessRules) {
86
+ const res = await sql`INSERT INTO ${sql(table)} (id, data, access, origin)
87
+ VALUES (${id}, ${asJson(data ?? null)}, ${asJson(accessRules)}, ${null})
88
+ ON CONFLICT (id) DO NOTHING`;
89
+ if (res.count === 0) throw new import_core.SuperLineError("CONFLICT", `Resource already exists: ${id}`);
90
+ },
91
+ async apply(change) {
92
+ const res = await sql`UPDATE ${sql(table)} SET data = ${asJson(change.update ?? null)}, origin = ${change.origin} WHERE id = ${change.id}`;
93
+ if (res.count === 0) throw new import_core.SuperLineError("NOT_FOUND", `No resource: ${change.id}`);
94
+ },
95
+ async setAccess(id, accessRules) {
96
+ const res = await sql`UPDATE ${sql(table)} SET access = ${asJson(accessRules)} WHERE id = ${id}`;
97
+ if (res.count === 0) throw new import_core.SuperLineError("NOT_FOUND", `No resource: ${id}`);
98
+ },
99
+ async delete(id) {
100
+ await sql`DELETE FROM ${sql(table)} WHERE id = ${id}`;
101
+ },
102
+ async list() {
103
+ const rows = await sql`SELECT id FROM ${sql(table)}`;
104
+ return rows.map((r) => r.id);
105
+ },
106
+ onChange(cb) {
107
+ changeCbs.add(cb);
108
+ return () => changeCbs.delete(cb);
109
+ },
110
+ onDelete(cb) {
111
+ deleteCbs.add(cb);
112
+ return () => deleteCbs.delete(cb);
113
+ },
114
+ async close() {
115
+ try {
116
+ await liveSub.unsubscribe();
117
+ shape?.unsubscribe();
118
+ if (ownsDb) await db.close();
119
+ } finally {
120
+ await sql.end();
121
+ }
122
+ }
123
+ };
124
+ }
125
+ // Annotate the CommonJS export names for ESM import in node:
126
+ 0 && (module.exports = {
127
+ pgliteStoreServer
128
+ });
@@ -0,0 +1,35 @@
1
+ import { PGliteWithLive } from '@electric-sql/pglite/live';
2
+ import { ServerStore } from '@super-line/core';
3
+
4
+ /** Options for {@link pgliteStoreServer}. */
5
+ interface PgliteStoreOptions {
6
+ /**
7
+ * Connection string for the central Postgres — the source of truth for writes + strong reads + ACL.
8
+ * Accepts a real Postgres URL or a PGLiteSocketServer (both speak pg-wire).
9
+ */
10
+ pgUrl: string;
11
+ /**
12
+ * Electric shape endpoint (e.g. `http://localhost:3000/v1/shape`) that streams the central table into this
13
+ * node's local replica. Omit to disable incoming sync — useful for tests/manual feeding of the local replica.
14
+ */
15
+ electricUrl?: string;
16
+ /** Table this store owns on both the central DB and the local replica; defaults to `resources`. */
17
+ table?: string;
18
+ /**
19
+ * Advanced/testing: supply the local PGlite replica (must have the `live` extension; add `sync`/`electricSync`
20
+ * for real Electric sync). When omitted, an ephemeral in-memory PGlite with `live` + `electricSync` is created.
21
+ */
22
+ db?: PGliteWithLive;
23
+ }
24
+ /**
25
+ * The self-clustering, last-writer-wins **server half** — durable like {@link "@super-line/store-sqlite"}, but
26
+ * its cross-node sync is owned by the store, not super-line's adapter. Writes + strong reads + ACL hit a central
27
+ * Postgres; each node mirrors that table into an in-memory PGlite replica via **Electric** (one-way, read-only)
28
+ * and turns its `live.changes` feed into {@link ServerStore.onChange}/{@link ServerStore.onDelete} — which core
29
+ * fans to LOCAL subscribers only (`clustering: 'self'`). Postgres+Electric is the only fan-out infra. A write
30
+ * round-trips central PG → Electric → every node's `live.changes`; the `origin` column carries echo-break through
31
+ * the round-trip. Pair it with `memoryStoreClient()` on the client.
32
+ */
33
+ declare function pgliteStoreServer(opts: PgliteStoreOptions): Promise<ServerStore>;
34
+
35
+ export { type PgliteStoreOptions, pgliteStoreServer };
@@ -0,0 +1,35 @@
1
+ import { PGliteWithLive } from '@electric-sql/pglite/live';
2
+ import { ServerStore } from '@super-line/core';
3
+
4
+ /** Options for {@link pgliteStoreServer}. */
5
+ interface PgliteStoreOptions {
6
+ /**
7
+ * Connection string for the central Postgres — the source of truth for writes + strong reads + ACL.
8
+ * Accepts a real Postgres URL or a PGLiteSocketServer (both speak pg-wire).
9
+ */
10
+ pgUrl: string;
11
+ /**
12
+ * Electric shape endpoint (e.g. `http://localhost:3000/v1/shape`) that streams the central table into this
13
+ * node's local replica. Omit to disable incoming sync — useful for tests/manual feeding of the local replica.
14
+ */
15
+ electricUrl?: string;
16
+ /** Table this store owns on both the central DB and the local replica; defaults to `resources`. */
17
+ table?: string;
18
+ /**
19
+ * Advanced/testing: supply the local PGlite replica (must have the `live` extension; add `sync`/`electricSync`
20
+ * for real Electric sync). When omitted, an ephemeral in-memory PGlite with `live` + `electricSync` is created.
21
+ */
22
+ db?: PGliteWithLive;
23
+ }
24
+ /**
25
+ * The self-clustering, last-writer-wins **server half** — durable like {@link "@super-line/store-sqlite"}, but
26
+ * its cross-node sync is owned by the store, not super-line's adapter. Writes + strong reads + ACL hit a central
27
+ * Postgres; each node mirrors that table into an in-memory PGlite replica via **Electric** (one-way, read-only)
28
+ * and turns its `live.changes` feed into {@link ServerStore.onChange}/{@link ServerStore.onDelete} — which core
29
+ * fans to LOCAL subscribers only (`clustering: 'self'`). Postgres+Electric is the only fan-out infra. A write
30
+ * round-trips central PG → Electric → every node's `live.changes`; the `origin` column carries echo-break through
31
+ * the round-trip. Pair it with `memoryStoreClient()` on the client.
32
+ */
33
+ declare function pgliteStoreServer(opts: PgliteStoreOptions): Promise<ServerStore>;
34
+
35
+ export { type PgliteStoreOptions, pgliteStoreServer };
package/dist/index.js ADDED
@@ -0,0 +1,93 @@
1
+ // src/index.ts
2
+ import { PGlite } from "@electric-sql/pglite";
3
+ import { live } from "@electric-sql/pglite/live";
4
+ import { electricSync } from "@electric-sql/pglite-sync";
5
+ import postgres from "postgres";
6
+ import { SuperLineError } from "@super-line/core";
7
+ var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
8
+ async function pgliteStoreServer(opts) {
9
+ const table = opts.table ?? "resources";
10
+ if (!IDENT.test(table)) throw new Error(`Invalid table name: ${table}`);
11
+ const ddl = `CREATE TABLE IF NOT EXISTS "${table}" (id text PRIMARY KEY, data jsonb NOT NULL, access jsonb NOT NULL, origin text)`;
12
+ const sql = postgres(opts.pgUrl, { prepare: false, onnotice: () => {
13
+ } });
14
+ try {
15
+ await sql.unsafe(ddl);
16
+ } catch (err) {
17
+ const code = err.code;
18
+ if (code !== "42P07" && code !== "23505") throw err;
19
+ }
20
+ const asJson = (v) => sql.json(v);
21
+ const ownsDb = !opts.db;
22
+ const db = opts.db ?? await PGlite.create({ extensions: { live, sync: electricSync() } });
23
+ await db.exec(ddl);
24
+ const changeCbs = /* @__PURE__ */ new Set();
25
+ const deleteCbs = /* @__PURE__ */ new Set();
26
+ const liveSub = await db.live.changes(`SELECT id, data, origin FROM "${table}"`, [], "id", (changes) => {
27
+ for (const ch of changes) {
28
+ if (ch.__op__ === "DELETE") {
29
+ for (const cb of deleteCbs) cb(ch.id);
30
+ } else if (ch.__op__ === "INSERT" || ch.__op__ === "UPDATE") {
31
+ const change = { id: ch.id, update: ch.data, origin: ch.origin ?? "" };
32
+ for (const cb of changeCbs) cb(change);
33
+ }
34
+ }
35
+ });
36
+ const shape = opts.electricUrl && db.sync ? await db.sync.syncShapeToTable({
37
+ shape: { url: opts.electricUrl, params: { table } },
38
+ table,
39
+ primaryKey: ["id"],
40
+ shapeKey: null
41
+ }) : void 0;
42
+ return {
43
+ clustering: "self",
44
+ model: "lww",
45
+ async read(id) {
46
+ const rows = await sql`SELECT data::text AS data, access::text AS access FROM ${sql(table)} WHERE id = ${id}`;
47
+ const row = rows[0];
48
+ if (!row) return void 0;
49
+ return { id, data: JSON.parse(row.data), accessRules: JSON.parse(row.access) };
50
+ },
51
+ async create(id, data, accessRules) {
52
+ const res = await sql`INSERT INTO ${sql(table)} (id, data, access, origin)
53
+ VALUES (${id}, ${asJson(data ?? null)}, ${asJson(accessRules)}, ${null})
54
+ ON CONFLICT (id) DO NOTHING`;
55
+ if (res.count === 0) throw new SuperLineError("CONFLICT", `Resource already exists: ${id}`);
56
+ },
57
+ async apply(change) {
58
+ const res = await sql`UPDATE ${sql(table)} SET data = ${asJson(change.update ?? null)}, origin = ${change.origin} WHERE id = ${change.id}`;
59
+ if (res.count === 0) throw new SuperLineError("NOT_FOUND", `No resource: ${change.id}`);
60
+ },
61
+ async setAccess(id, accessRules) {
62
+ const res = await sql`UPDATE ${sql(table)} SET access = ${asJson(accessRules)} WHERE id = ${id}`;
63
+ if (res.count === 0) throw new SuperLineError("NOT_FOUND", `No resource: ${id}`);
64
+ },
65
+ async delete(id) {
66
+ await sql`DELETE FROM ${sql(table)} WHERE id = ${id}`;
67
+ },
68
+ async list() {
69
+ const rows = await sql`SELECT id FROM ${sql(table)}`;
70
+ return rows.map((r) => r.id);
71
+ },
72
+ onChange(cb) {
73
+ changeCbs.add(cb);
74
+ return () => changeCbs.delete(cb);
75
+ },
76
+ onDelete(cb) {
77
+ deleteCbs.add(cb);
78
+ return () => deleteCbs.delete(cb);
79
+ },
80
+ async close() {
81
+ try {
82
+ await liveSub.unsubscribe();
83
+ shape?.unsubscribe();
84
+ if (ownsDb) await db.close();
85
+ } finally {
86
+ await sql.end();
87
+ }
88
+ }
89
+ };
90
+ }
91
+ export {
92
+ pgliteStoreServer
93
+ };
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@super-line/store-pglite",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Self-clustering last-writer-wins Store for super-line — central Postgres + per-node Electric-synced PGlite replica (live.changes). Postgres is the only fan-out infra; no separate adapter.",
6
+ "license": "MIT",
7
+ "author": "Mert",
8
+ "keywords": [
9
+ "super-line",
10
+ "store",
11
+ "pglite",
12
+ "postgres",
13
+ "electric",
14
+ "sync",
15
+ "self",
16
+ "persistence",
17
+ "lww"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/mertdogar/super-line.git",
22
+ "directory": "packages/store-pglite"
23
+ },
24
+ "homepage": "https://mertdogar.github.io/super-line/",
25
+ "bugs": "https://github.com/mertdogar/super-line/issues",
26
+ "main": "./dist/index.cjs",
27
+ "module": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "import": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/index.d.cts",
37
+ "default": "./dist/index.cjs"
38
+ }
39
+ }
40
+ },
41
+ "files": [
42
+ "dist"
43
+ ],
44
+ "sideEffects": false,
45
+ "engines": {
46
+ "node": ">=18"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "dependencies": {
52
+ "@electric-sql/pglite": "^0.5.3",
53
+ "@electric-sql/pglite-sync": "^0.6.3",
54
+ "postgres": "^3.4.9",
55
+ "@super-line/core": "^0.8.0"
56
+ },
57
+ "devDependencies": {
58
+ "@electric-sql/pglite-socket": "^0.2.6"
59
+ },
60
+ "scripts": {
61
+ "build": "tsup"
62
+ }
63
+ }