@porulle/adapter-neon 0.8.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 unified-commerce-engine contributors
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/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # @porulle/adapter-neon
2
+
3
+ Workers-grade Neon `DatabaseAdapter` for `@porulle/core`.
4
+
5
+ Two transports, picked by query type — the design proven in production by
6
+ porulle's first adopter (a live iPad POS on Cloudflare Workers + Neon):
7
+
8
+ 1. **Plain queries** go through `@neondatabase/serverless` HTTP — stateless,
9
+ no socket-reuse races across Workers isolates.
10
+ 2. **`transaction()`** creates a fresh WebSocket `Pool` per call, runs the
11
+ transaction, then ends the pool. `drizzle-orm/neon-http` cannot run
12
+ transactions, and isolate-shared WebSocket pools flake when reused across
13
+ requests; a short-lived pool per transaction gives atomicity without the
14
+ flake.
15
+
16
+ ## Usage
17
+
18
+ ```ts
19
+ import { defineConfig } from "@porulle/core";
20
+ import { neonAdapter } from "@porulle/adapter-neon";
21
+
22
+ export default defineConfig({
23
+ databaseAdapter: neonAdapter({
24
+ connectionString: env.DATABASE_URL, // direct Neon URL
25
+ // Optional: route per-transaction pools through Hyperdrive
26
+ hyperdrive: env.HYPERDRIVE,
27
+ }),
28
+ // ...
29
+ });
30
+ ```
31
+
32
+ - `connectionString` — direct Neon URL (`postgresql://...neon.tech/...`).
33
+ Used by the HTTP driver, and by transaction pools when no Hyperdrive
34
+ binding is given.
35
+ - `hyperdrive` — optional Cloudflare Hyperdrive binding (any object exposing
36
+ `connectionString`). When set, per-transaction pools connect through it;
37
+ plain queries keep using the Neon HTTP driver against `connectionString`.
38
+
39
+ `.execute()` results are normalized to the postgres-js shape (an array of
40
+ rows), matching what `@porulle/core` and custom routes expect.
@@ -0,0 +1,28 @@
1
+ import { type NeonHttpDatabase } from "drizzle-orm/neon-http";
2
+ import { type NeonDatabase } from "drizzle-orm/neon-serverless";
3
+ import type { DatabaseAdapter } from "@porulle/core";
4
+ type HttpClient = NeonHttpDatabase<Record<string, unknown>>;
5
+ type WsClient = NeonDatabase<Record<string, unknown>>;
6
+ type AnyDb = HttpClient | WsClient;
7
+ export interface NeonAdapterOptions {
8
+ /** Direct Neon connection string (postgresql://...neon.tech/...). */
9
+ connectionString: string;
10
+ /**
11
+ * Optional Cloudflare Hyperdrive binding (or any object exposing
12
+ * `connectionString`). When set, per-transaction pools connect through it;
13
+ * plain queries keep using the Neon HTTP driver against `connectionString`.
14
+ */
15
+ hyperdrive?: {
16
+ connectionString: string;
17
+ } | undefined;
18
+ }
19
+ export type NeonDatabaseAdapter = DatabaseAdapter<HttpClient, unknown>;
20
+ /**
21
+ * Normalizes `.execute()` to the postgres-js shape (array of rows). Core and
22
+ * custom routes iterate `.execute()` results directly; the raw neon drivers
23
+ * return `{ rows, command, rowCount }`, which breaks that contract.
24
+ */
25
+ export declare function normalizeExecuteShape<T extends AnyDb>(db: T): T;
26
+ export declare function neonAdapter(options: NeonAdapterOptions): NeonDatabaseAdapter;
27
+ export {};
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAqBA,OAAO,EAA0B,KAAK,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACtF,OAAO,EAAwB,KAAK,YAAY,EAAE,MAAM,6BAA6B,CAAC;AACtF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAMrD,KAAK,UAAU,GAAG,gBAAgB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAC5D,KAAK,QAAQ,GAAG,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AACtD,KAAK,KAAK,GAAG,UAAU,GAAG,QAAQ,CAAC;AAEnC,MAAM,WAAW,kBAAkB;IACjC,qEAAqE;IACrE,gBAAgB,EAAE,MAAM,CAAC;IACzB;;;;OAIG;IACH,UAAU,CAAC,EAAE;QAAE,gBAAgB,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACvD;AAED,MAAM,MAAM,mBAAmB,GAAG,eAAe,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;AAEvE;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,KAAK,EAAE,EAAE,EAAE,CAAC,GAAG,CAAC,CAsB/D;AAED,wBAAgB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,mBAAmB,CAsC5E"}
package/dist/index.js ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Workers-grade Neon DatabaseAdapter for @porulle/core (issue #55).
3
+ *
4
+ * Two transports, picked by query type — the design proven in production by
5
+ * porulle's first adopter (ordereka-fashion-pos, live on Cloudflare Workers):
6
+ *
7
+ * 1. Plain queries (select / insert / update / delete / raw execute) go
8
+ * through `@neondatabase/serverless` HTTP — stateless, no socket-reuse
9
+ * races across Workers isolates.
10
+ * 2. `transaction()` creates a FRESH WebSocket `Pool` per call, runs the
11
+ * transaction, then ends the pool. `drizzle-orm/neon-http` throws on
12
+ * `db.transaction()` ("No transactions support"), and isolate-shared
13
+ * WebSocket pools flake (~30% observed) when reused across requests —
14
+ * a short-lived pool per transaction gives atomicity without the flake.
15
+ *
16
+ * Hyperdrive-aware: pass the binding (`{ hyperdrive: env.HYPERDRIVE }`) and
17
+ * its connection string is used for the per-transaction pools, keeping pool
18
+ * setup on Cloudflare's fast path. The HTTP driver always speaks directly to
19
+ * Neon, so a direct `connectionString` is still required alongside it.
20
+ */
21
+ import { Pool, neon, neonConfig } from "@neondatabase/serverless";
22
+ import { drizzle as drizzleHttp } from "drizzle-orm/neon-http";
23
+ import { drizzle as drizzleWs } from "drizzle-orm/neon-serverless";
24
+ if (typeof WebSocket !== "undefined") {
25
+ neonConfig.webSocketConstructor = WebSocket;
26
+ }
27
+ /**
28
+ * Normalizes `.execute()` to the postgres-js shape (array of rows). Core and
29
+ * custom routes iterate `.execute()` results directly; the raw neon drivers
30
+ * return `{ rows, command, rowCount }`, which breaks that contract.
31
+ */
32
+ export function normalizeExecuteShape(db) {
33
+ const handler = {
34
+ get(target, prop, receiver) {
35
+ const orig = Reflect.get(target, prop, receiver);
36
+ if (prop === "execute" && typeof orig === "function") {
37
+ return async (...args) => {
38
+ const result = await orig.apply(target, args);
39
+ if (result &&
40
+ typeof result === "object" &&
41
+ "rows" in result &&
42
+ Array.isArray(result.rows)) {
43
+ return result.rows;
44
+ }
45
+ return result;
46
+ };
47
+ }
48
+ return orig;
49
+ },
50
+ };
51
+ return new Proxy(db, handler);
52
+ }
53
+ export function neonAdapter(options) {
54
+ const httpConnectionString = options.connectionString;
55
+ const poolConnectionString = options.hyperdrive?.connectionString ?? options.connectionString;
56
+ const sql = neon(httpConnectionString);
57
+ const httpDb = normalizeExecuteShape(drizzleHttp(sql));
58
+ const runInFreshPool = async (fn) => {
59
+ const pool = new Pool({ connectionString: poolConnectionString });
60
+ try {
61
+ const wsDb = normalizeExecuteShape(drizzleWs(pool));
62
+ return await wsDb.transaction(async (tx) => fn(normalizeExecuteShape(tx)));
63
+ }
64
+ finally {
65
+ // Best-effort: Pool.end() over WebSocket in Workers can be a no-op but
66
+ // never throws into the transaction result.
67
+ await pool.end().catch(() => { });
68
+ }
69
+ };
70
+ // Some core paths call `kernel.database.db.transaction(...)` directly —
71
+ // splice the pool-backed transaction onto the HTTP client so both entry
72
+ // points behave identically.
73
+ const dbWithTx = new Proxy(httpDb, {
74
+ get(target, prop, receiver) {
75
+ if (prop === "transaction") {
76
+ return runInFreshPool;
77
+ }
78
+ return Reflect.get(target, prop, receiver);
79
+ },
80
+ });
81
+ return {
82
+ provider: "postgresql",
83
+ db: dbWithTx,
84
+ async transaction(fn) {
85
+ return runInFreshPool(fn);
86
+ },
87
+ };
88
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@porulle/adapter-neon",
3
+ "version": "0.8.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "bun": "./src/index.ts",
9
+ "import": "./dist/index.js",
10
+ "types": "./src/index.ts"
11
+ }
12
+ },
13
+ "dependencies": {
14
+ "@neondatabase/serverless": "^1.0.1",
15
+ "drizzle-orm": "^0.45.1",
16
+ "@porulle/core": "0.8.0"
17
+ },
18
+ "devDependencies": {
19
+ "@types/node": "^24.5.2",
20
+ "eslint": "^9.39.1",
21
+ "typescript": "5.9.2",
22
+ "vitest": "^3.2.4",
23
+ "@porulle/eslint-config": "0.1.0",
24
+ "@porulle/typescript-config": "0.1.0"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "files": [
30
+ "src",
31
+ "dist",
32
+ "README.md"
33
+ ],
34
+ "description": "Workers-grade Neon DatabaseAdapter for @porulle/core: HTTP driver for plain queries, a fresh WebSocket Pool per transaction, Hyperdrive-aware.",
35
+ "homepage": "https://porulle-docs.vercel.app",
36
+ "bugs": {
37
+ "url": "https://github.com/asyncdotengineering/porulle/issues"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/asyncdotengineering/porulle.git",
42
+ "directory": "packages/adapters/adapter-neon"
43
+ },
44
+ "author": "Porulle contributors",
45
+ "scripts": {
46
+ "build": "rm -rf dist tsconfig.build.tsbuildinfo && tsc -p tsconfig.build.json",
47
+ "check-types": "tsc --noEmit",
48
+ "lint": "eslint . --max-warnings 1000",
49
+ "test": "vitest run"
50
+ }
51
+ }
package/src/index.ts ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Workers-grade Neon DatabaseAdapter for @porulle/core (issue #55).
3
+ *
4
+ * Two transports, picked by query type — the design proven in production by
5
+ * porulle's first adopter (ordereka-fashion-pos, live on Cloudflare Workers):
6
+ *
7
+ * 1. Plain queries (select / insert / update / delete / raw execute) go
8
+ * through `@neondatabase/serverless` HTTP — stateless, no socket-reuse
9
+ * races across Workers isolates.
10
+ * 2. `transaction()` creates a FRESH WebSocket `Pool` per call, runs the
11
+ * transaction, then ends the pool. `drizzle-orm/neon-http` throws on
12
+ * `db.transaction()` ("No transactions support"), and isolate-shared
13
+ * WebSocket pools flake (~30% observed) when reused across requests —
14
+ * a short-lived pool per transaction gives atomicity without the flake.
15
+ *
16
+ * Hyperdrive-aware: pass the binding (`{ hyperdrive: env.HYPERDRIVE }`) and
17
+ * its connection string is used for the per-transaction pools, keeping pool
18
+ * setup on Cloudflare's fast path. The HTTP driver always speaks directly to
19
+ * Neon, so a direct `connectionString` is still required alongside it.
20
+ */
21
+ import { Pool, neon, neonConfig } from "@neondatabase/serverless";
22
+ import { drizzle as drizzleHttp, type NeonHttpDatabase } from "drizzle-orm/neon-http";
23
+ import { drizzle as drizzleWs, type NeonDatabase } from "drizzle-orm/neon-serverless";
24
+ import type { DatabaseAdapter } from "@porulle/core";
25
+
26
+ if (typeof WebSocket !== "undefined") {
27
+ neonConfig.webSocketConstructor = WebSocket as unknown as typeof neonConfig.webSocketConstructor;
28
+ }
29
+
30
+ type HttpClient = NeonHttpDatabase<Record<string, unknown>>;
31
+ type WsClient = NeonDatabase<Record<string, unknown>>;
32
+ type AnyDb = HttpClient | WsClient;
33
+
34
+ export interface NeonAdapterOptions {
35
+ /** Direct Neon connection string (postgresql://...neon.tech/...). */
36
+ connectionString: string;
37
+ /**
38
+ * Optional Cloudflare Hyperdrive binding (or any object exposing
39
+ * `connectionString`). When set, per-transaction pools connect through it;
40
+ * plain queries keep using the Neon HTTP driver against `connectionString`.
41
+ */
42
+ hyperdrive?: { connectionString: string } | undefined;
43
+ }
44
+
45
+ export type NeonDatabaseAdapter = DatabaseAdapter<HttpClient, unknown>;
46
+
47
+ /**
48
+ * Normalizes `.execute()` to the postgres-js shape (array of rows). Core and
49
+ * custom routes iterate `.execute()` results directly; the raw neon drivers
50
+ * return `{ rows, command, rowCount }`, which breaks that contract.
51
+ */
52
+ export function normalizeExecuteShape<T extends AnyDb>(db: T): T {
53
+ const handler: ProxyHandler<T> = {
54
+ get(target, prop, receiver) {
55
+ const orig = Reflect.get(target, prop, receiver);
56
+ if (prop === "execute" && typeof orig === "function") {
57
+ return async (...args: unknown[]) => {
58
+ const result = await (orig as (...a: unknown[]) => Promise<unknown>).apply(target, args);
59
+ if (
60
+ result &&
61
+ typeof result === "object" &&
62
+ "rows" in result &&
63
+ Array.isArray((result as { rows: unknown[] }).rows)
64
+ ) {
65
+ return (result as { rows: unknown[] }).rows;
66
+ }
67
+ return result;
68
+ };
69
+ }
70
+ return orig;
71
+ },
72
+ };
73
+ return new Proxy(db, handler);
74
+ }
75
+
76
+ export function neonAdapter(options: NeonAdapterOptions): NeonDatabaseAdapter {
77
+ const httpConnectionString = options.connectionString;
78
+ const poolConnectionString = options.hyperdrive?.connectionString ?? options.connectionString;
79
+
80
+ const sql = neon(httpConnectionString);
81
+ const httpDb = normalizeExecuteShape(drizzleHttp(sql) as HttpClient);
82
+
83
+ const runInFreshPool = async (fn: (tx: unknown) => Promise<unknown>): Promise<unknown> => {
84
+ const pool = new Pool({ connectionString: poolConnectionString });
85
+ try {
86
+ const wsDb = normalizeExecuteShape(drizzleWs(pool) as WsClient);
87
+ return await wsDb.transaction(async (tx) => fn(normalizeExecuteShape(tx as WsClient)));
88
+ } finally {
89
+ // Best-effort: Pool.end() over WebSocket in Workers can be a no-op but
90
+ // never throws into the transaction result.
91
+ await pool.end().catch(() => {});
92
+ }
93
+ };
94
+
95
+ // Some core paths call `kernel.database.db.transaction(...)` directly —
96
+ // splice the pool-backed transaction onto the HTTP client so both entry
97
+ // points behave identically.
98
+ const dbWithTx = new Proxy(httpDb, {
99
+ get(target, prop, receiver) {
100
+ if (prop === "transaction") {
101
+ return runInFreshPool;
102
+ }
103
+ return Reflect.get(target, prop, receiver);
104
+ },
105
+ }) as HttpClient;
106
+
107
+ return {
108
+ provider: "postgresql",
109
+ db: dbWithTx,
110
+ async transaction<T>(fn: (tx: unknown) => Promise<T>): Promise<T> {
111
+ return runInFreshPool(fn) as Promise<T>;
112
+ },
113
+ };
114
+ }