@cardonjs/db 0.0.0-stage → 0.2.1

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 Matias Terradas
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 CHANGED
@@ -1,3 +1,197 @@
1
- # Temporary Holding Version
1
+ # @cardonjs/db
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The database interface of Cardón: the `Database<Client>` type every database adapter returns, a
4
+ `/ready` health check that pings it, the query wrapper that keeps database errors free of values
5
+ (`storeQueries`), and the shared contract suite adapters must pass
6
+ (`@cardonjs/db/contract`). It is not an ORM or a SQL abstraction: `client` is the query builder
7
+ itself (Drizzle), used directly by repositories. Adapters such as `@cardonjs/db-d1` build the
8
+ `Database`; business logic receives repositories through the context and never touches a
9
+ provider SDK or binding. Standard web APIs only (Workers, Node, Bun, Deno).
10
+
11
+ Peer dependencies: `@cardonjs/core`, `hono`. `@cardonjs/testing` is an optional peer, only needed by
12
+ `@cardonjs/db/contract` (in adapter tests).
13
+
14
+ For coding agents: `llms.txt`, shipped next to this README in the package, is a compact usage guide (public API, a minimal example, common mistakes).
15
+
16
+ ## Example
17
+
18
+ ```ts
19
+ import { type CardonEnv, createApp, defineModule } from "@cardonjs/core";
20
+ import { databaseHealthCheck } from "@cardonjs/db";
21
+ import { d1Database } from "@cardonjs/db-d1";
22
+
23
+ type Bindings = { DB: D1Database };
24
+ const adapters = (env: Bindings) => ({ db: d1Database(env.DB) });
25
+ type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
26
+
27
+ const ordersModule = defineModule<AppEnv>({
28
+ name: "orders",
29
+ prefix: "/v1/orders",
30
+ healthChecks: { db: databaseHealthCheck((c) => c.var.adapters.db) },
31
+ });
32
+
33
+ export default createApp(adapters).register(ordersModule);
34
+ // GET /ready → { data: { status: "ok", checks: { "core.adapters": ..., "orders.db": { status: "ok" } } } }
35
+ ```
36
+
37
+ ## API
38
+
39
+ ### `Database<Client>`
40
+
41
+ ```ts
42
+ interface Database<Client> {
43
+ readonly client: Client;
44
+ ping(signal?: AbortSignal): Promise<void>;
45
+ }
46
+ ```
47
+
48
+ - `client`: the query builder (e.g. `DrizzleD1Database`). Used by repositories, never by business
49
+ logic directly. There is no batch or transaction wrapper: use the client's own (with
50
+ Drizzle, `client.batch([...])` for atomic writes where the driver supports it). Run each query
51
+ or batch through [`storeQueries`](#store-errors-storequeriesstore-options-and-storeerror) so a
52
+ failure carries no values.
53
+ - `ping(signal?)`: resolves when the database answers and rejects otherwise. Rejects right away,
54
+ with `signal.reason` and without touching the database, when `signal` is already aborted, and
55
+ as soon as it aborts while waiting. Never writes.
56
+
57
+ There is no `migrate`: migrations are generated and applied by tooling in CI (for D1, Drizzle Kit
58
+ and Wrangler), never by the running Worker.
59
+
60
+ ### `databaseHealthCheck(select)`
61
+
62
+ Returns a core `HealthCheck` that pings the database `select(c)` returns, passing `/ready`'s
63
+ per-check abort signal. Register it under a module's `healthChecks`; it is reported as
64
+ `<module>.<key>`. It fails (503, `degraded`) when the ping rejects, when `select` throws, or when
65
+ the ping outlives the `/ready` per-check timeout (`createApp({ ready: { timeoutMs } })`, 3 s by
66
+ default), which also aborts the signal. Errors are logged by core (`health check failed`), never
67
+ returned in the response.
68
+
69
+ ### Store errors: `storeQueries(store, options?)` and `StoreError`
70
+
71
+ **The rule: a repository never lets a driver's error out.** Drizzle's `DrizzleQueryError` has the
72
+ message `Failed query: <sql>\nparams: <every bound value>` and keeps the driver's error (which may
73
+ quote the conflicting value) as `cause`. Thrown from a route, it reaches core's `request failed`
74
+ log line with a note's title, an id, a URL. Run every query through `query` instead:
75
+
76
+ ```ts
77
+ import { storeQueries } from "@cardonjs/db";
78
+
79
+ export function notesRepository({ db }: { db: Db }) {
80
+ const { client } = db;
81
+ const query = storeQueries("notes");
82
+ return {
83
+ async get(id: string) {
84
+ const [note] = await query("get", () => client.select().from(notes).where(eq(notes.id, id)));
85
+ return note ?? null;
86
+ },
87
+ async create(note: Note, extra: BatchItem<"sqlite">[]) {
88
+ // A batch is one operation.
89
+ await query("create", () => client.batch([client.insert(notes).values(note), ...extra]));
90
+ },
91
+ };
92
+ }
93
+ ```
94
+
95
+ ```ts
96
+ type StoreQuery = <T>(operation: string, run: () => T | PromiseLike<T>) => Promise<T>;
97
+ function storeQueries(store: string, options?: { label?: string }): StoreQuery;
98
+
99
+ class StoreError extends Error {
100
+ readonly store: string; // "notes"
101
+ readonly operation: string; // "get"
102
+ readonly reason: string; // the failed error's name: "Error", "TypeError", ...
103
+ readonly code?: string; // a driver code, when there is a valid one: "SQLITE_BUSY", "23505"
104
+ constructor(init: StoreErrorInit); // { store, operation, reason, code?, label? }
105
+ }
106
+ ```
107
+
108
+ - `query(operation, run)` awaits `run()` (a Drizzle builder, a batch, any promise) and resolves
109
+ with its result. A failure is rethrown as a `StoreError` named for the store
110
+ (`storeQueries("notes")` throws `NotesStoreError`), with the message
111
+ `notes store: get failed (Error).` (`label` replaces `notes store`). It is built only from:
112
+ - `store` and `operation`, which you write: fixed names. The check only limits the characters
113
+ (an identifier; letters, digits, spaces and `_.:/-`, else a `TypeError` thrown before
114
+ `run`): it cannot tell a value from a name, so `` query(`update ${id}`, ...) `` passes and
115
+ logs the id. **Write the operation as a string literal**, never built from a value (the
116
+ starter, `db-d1` and the CLI's template have a test that every `query(` call starts with
117
+ one).
118
+ - `reason`: the failed error's `name` when it is a plain identifier (up to 64 characters),
119
+ `UnnamedError` otherwise, `NonError` for something that is not an `Error`. Note that
120
+ Drizzle's `DrizzleQueryError` is named `Error`.
121
+ - `code`: the first `code` on the failed error or its causes (three errors deep) that is an
122
+ upper-case identifier (`SQLITE_CONSTRAINT_UNIQUE`) or a five-character SQLSTATE (`23505`).
123
+ Only the string is kept. D1's errors carry no `code` (observed in Miniflare): on D1 there
124
+ is none.
125
+
126
+ `reason` and `code` are read from the failed error, so code inside `run` must never set an
127
+ error's `name` or `code` from data (a key, an email, a value): they would be logged.
128
+
129
+ Never the failed error's message, stack, other fields or cause: a `StoreError` has no `cause`.
130
+ `operation`, `reason` and `code` are on core's logger allowlist, so the log line reads
131
+ `{ name: "NotesStoreError", message: "notes store: get failed (Error).", fields: { operation:
132
+ "get", reason: "Error" } }`. The client still gets the generic `500`.
133
+ - **Pass-through**: an `AppError` (core) or a `StoreError` thrown inside `run` is rethrown
134
+ unchanged. To turn a database error into a client error, decide inside `run`, on the raw
135
+ error, and throw the `AppError` there:
136
+
137
+ ```ts
138
+ await query("create", async () => {
139
+ try {
140
+ await client.insert(handles).values(row);
141
+ } catch (error) {
142
+ // Never `{ cause: error }` with a driver's error: its message lists the values.
143
+ if (isUniqueViolation(error)) throw new ConflictError("Handle taken."); // a 409, unchanged
144
+ throw error; // becomes a HandlesStoreError
145
+ }
146
+ });
147
+ ```
148
+
149
+ Never pass `{ cause: error }` of a driver error to that `AppError`. If one does carry a
150
+ `cause` that is not itself an `AppError` or `StoreError` (without such a cause of its own),
151
+ `query` throws a copy without the cause instead: the same class, status, message and details
152
+ (a 404 stays a 404), the caller's error untouched, the cause never logged.
153
+
154
+ Better still, decide in SQL (`onConflictDoNothing().returning()`, a conditional `UPDATE`, a
155
+ `transition` from `@cardonjs/state`) and read the result outside `query`.
156
+ - `new StoreError({ store, operation, reason })` builds one directly for a store's own failure
157
+ (`reason: "MalformedRecord"`), with the same checks.
158
+ - Driver-neutral: it knows nothing of Drizzle or D1.
159
+
160
+ ## Contract suite (`@cardonjs/db/contract`)
161
+
162
+ Every adapter runs `databaseContract` in its tests against a real database. It provides a harness:
163
+
164
+ ```ts
165
+ interface DatabaseContractHarness<Client> {
166
+ /** A healthy database with an empty probe table (`id` text primary key). Fresh per call. */
167
+ create(): Database<Client> | Promise<Database<Client>>;
168
+ /** A database whose connection is broken: `ping` must reject. */
169
+ createBroken(): Database<Client> | Promise<Database<Client>>;
170
+ /** Inserts one probe row through `client`. */
171
+ writeProbe(db: Database<Client>, id: string): Promise<void>;
172
+ /** Reads every probe id through `client`. */
173
+ readProbes(db: Database<Client>): Promise<string[]>;
174
+ /** One atomic batch through `client`: insert probe `id`, then a failing statement. Must reject. */
175
+ batchWithFailure(db: Database<Client>, id: string): Promise<void>;
176
+ }
177
+ ```
178
+
179
+ The cases, each failing with an `AssertionError` that says which rule broke:
180
+
181
+ 1. `ping` resolves on a healthy database.
182
+ 2. `ping` rejects on a broken database.
183
+ 3. `ping` rejects with the signal's reason when the signal is already aborted, on a healthy and on
184
+ a broken database (touching the broken one first would reject with its connection error).
185
+ 4. `ping` does not write (the probe table is unchanged after two pings).
186
+ 5. `client` reads its own writes (and `create()` starts with an empty probe table).
187
+ 6. A batch whose second statement fails rejects and leaves nothing written.
188
+
189
+ ```ts
190
+ import { databaseContract } from "@cardonjs/db/contract";
191
+ import { it } from "vitest";
192
+
193
+ it.each(databaseContract.map((c) => [c.name, c] as const))("%s", (_, c) => c.run(harness));
194
+ ```
195
+
196
+ Rejecting when the signal aborts *while waiting* cannot be forced generically, so each adapter
197
+ tests it on its own.
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The shared contract every `Database` adapter must pass. Import it from `@cardonjs/db/contract`
3
+ * in the adapter's tests (it needs `@cardonjs/testing`) and run each case with the adapter's own
4
+ * runner against a harness over a real database.
5
+ *
6
+ * The harness writes, reads and batches through `client` itself (the interface does not wrap
7
+ * queries), so the batch and write cases check the adapter's client together with the harness:
8
+ * keep the harness a thin, honest use of the client. "Ping does not write" only watches the
9
+ * probe table.
10
+ */
11
+ import { type ContractCase } from "@cardonjs/testing";
12
+ import type { Database } from "./database.js";
13
+ export interface DatabaseContractHarness<Client> {
14
+ /** A healthy database with an empty probe table (`id` text primary key). Fresh per call. */
15
+ create(): Database<Client> | Promise<Database<Client>>;
16
+ /** A database whose connection is broken: `ping` must reject. */
17
+ createBroken(): Database<Client> | Promise<Database<Client>>;
18
+ /** Inserts one probe row through `client`. */
19
+ writeProbe(db: Database<Client>, id: string): Promise<void>;
20
+ /** Reads every probe id through `client`. */
21
+ readProbes(db: Database<Client>): Promise<string[]>;
22
+ /**
23
+ * Runs one atomic batch through `client`: insert probe `id`, then a statement that fails.
24
+ * Must reject.
25
+ */
26
+ batchWithFailure(db: Database<Client>, id: string): Promise<void>;
27
+ }
28
+ export declare const databaseContract: readonly ContractCase<DatabaseContractHarness<unknown>>[];
29
+ //# sourceMappingURL=contract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,KAAK,YAAY,EAAwB,MAAM,mBAAmB,CAAC;AAC5E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,MAAM,WAAW,uBAAuB,CAAC,MAAM;IAC7C,4FAA4F;IAC5F,MAAM,IAAI,QAAQ,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IACvD,iEAAiE;IACjE,YAAY,IAAI,QAAQ,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAC7D,8CAA8C;IAC9C,UAAU,CAAC,EAAE,EAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,6CAA6C;IAC7C,UAAU,CAAC,EAAE,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IACpD;;;OAGG;IACH,gBAAgB,CAAC,EAAE,EAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACnE;AA8CD,eAAO,MAAM,gBAAgB,EAAE,SAAS,YAAY,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC,EAyFlF,CAAC"}
@@ -0,0 +1,137 @@
1
+ /**
2
+ * The shared contract every `Database` adapter must pass. Import it from `@cardonjs/db/contract`
3
+ * in the adapter's tests (it needs `@cardonjs/testing`) and run each case with the adapter's own
4
+ * runner against a harness over a real database.
5
+ *
6
+ * The harness writes, reads and batches through `client` itself (the interface does not wrap
7
+ * queries), so the batch and write cases check the adapter's client together with the harness:
8
+ * keep the harness a thin, honest use of the client. "Ping does not write" only watches the
9
+ * probe table.
10
+ */
11
+ import { defineContract, fail } from "@cardonjs/testing";
12
+ /** Calls `run` and reports how it settled; a synchronous throw counts as a rejection. */
13
+ async function settle(run) {
14
+ try {
15
+ await run();
16
+ return { ok: true };
17
+ }
18
+ catch (error) {
19
+ return { ok: false, error };
20
+ }
21
+ }
22
+ function describeError(error) {
23
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
24
+ }
25
+ function sorted(ids) {
26
+ return [...ids].sort();
27
+ }
28
+ function sameIds(actual, expected) {
29
+ return JSON.stringify(sorted(actual)) === JSON.stringify(sorted(expected));
30
+ }
31
+ /** Pings with an already aborted signal; fails unless it rejects with the signal's reason. */
32
+ async function expectAbortedPingRejects(db, which) {
33
+ const controller = new AbortController();
34
+ const reason = new Error("contract: aborted before ping");
35
+ controller.abort(reason);
36
+ const result = await settle(() => db.ping(controller.signal));
37
+ if (result.ok) {
38
+ fail(`ping must reject when the signal is already aborted (${which} database)`, [
39
+ "it resolved",
40
+ ]);
41
+ }
42
+ if (result.error !== reason) {
43
+ fail(`ping must reject with the signal's reason when it is already aborted (${which} database), ` +
44
+ "before touching the database", [`rejected with ${describeError(result.error)}`]);
45
+ }
46
+ }
47
+ export const databaseContract = defineContract([
48
+ {
49
+ name: "ping resolves on a healthy database",
50
+ run: async (h) => {
51
+ const db = await h.create();
52
+ const result = await settle(() => db.ping());
53
+ if (!result.ok) {
54
+ fail("ping must resolve on a healthy database", [
55
+ `rejected with ${describeError(result.error)}`,
56
+ ]);
57
+ }
58
+ // `/ready` always passes a live signal, so ping must also resolve with one.
59
+ const withSignal = await settle(() => db.ping(new AbortController().signal));
60
+ if (!withSignal.ok) {
61
+ fail("ping must resolve on a healthy database when given a live signal", [
62
+ `rejected with ${describeError(withSignal.error)}`,
63
+ ]);
64
+ }
65
+ },
66
+ },
67
+ {
68
+ name: "ping rejects on a broken database",
69
+ run: async (h) => {
70
+ const db = await h.createBroken();
71
+ const result = await settle(() => db.ping());
72
+ if (result.ok)
73
+ fail("ping must reject on a broken database", ["it resolved"]);
74
+ },
75
+ },
76
+ {
77
+ name: "ping rejects when the signal is already aborted, without touching the database",
78
+ run: async (h) => {
79
+ // On a broken database, touching it first would reject with the connection error
80
+ // instead of the signal's reason.
81
+ await expectAbortedPingRejects(await h.create(), "healthy");
82
+ await expectAbortedPingRejects(await h.createBroken(), "broken");
83
+ },
84
+ },
85
+ {
86
+ name: "ping does not write",
87
+ run: async (h) => {
88
+ const db = await h.create();
89
+ await h.writeProbe(db, "before-ping");
90
+ await db.ping();
91
+ await db.ping();
92
+ const ids = await h.readProbes(db);
93
+ if (!sameIds(ids, ["before-ping"])) {
94
+ fail("ping must not write: the probe table changed", [
95
+ `expected ["before-ping"], got ${JSON.stringify(sorted(ids))}`,
96
+ ]);
97
+ }
98
+ },
99
+ },
100
+ {
101
+ name: "client reads its own writes",
102
+ run: async (h) => {
103
+ const db = await h.create();
104
+ const before = await h.readProbes(db);
105
+ if (before.length > 0) {
106
+ fail("create() must return a database with an empty probe table", [
107
+ `found ${JSON.stringify(sorted(before))}`,
108
+ ]);
109
+ }
110
+ await h.writeProbe(db, "probe-1");
111
+ await h.writeProbe(db, "probe-2");
112
+ const ids = await h.readProbes(db);
113
+ if (!sameIds(ids, ["probe-1", "probe-2"])) {
114
+ fail("client must read its own writes", [
115
+ `expected ["probe-1","probe-2"], got ${JSON.stringify(sorted(ids))}`,
116
+ ]);
117
+ }
118
+ },
119
+ },
120
+ {
121
+ name: "a batch whose second statement fails rejects and writes nothing",
122
+ run: async (h) => {
123
+ const db = await h.create();
124
+ const result = await settle(() => h.batchWithFailure(db, "batched"));
125
+ if (result.ok) {
126
+ fail("a batch whose second statement fails must reject", ["it resolved"]);
127
+ }
128
+ const ids = await h.readProbes(db);
129
+ if (ids.length > 0) {
130
+ fail("a failed batch must be atomic and write nothing", [
131
+ `probe table: ${JSON.stringify(sorted(ids))}`,
132
+ ]);
133
+ }
134
+ },
135
+ },
136
+ ]);
137
+ //# sourceMappingURL=contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.js","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAqB,cAAc,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAqB5E,yFAAyF;AACzF,KAAK,UAAU,MAAM,CAAC,GAA2B;IAC/C,IAAI,CAAC;QACH,MAAM,GAAG,EAAE,CAAC;QACZ,OA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"@cardonjs/core";
2
+ import type { Context, Env } from "hono";
3
+ /**
4
+ * A database connection as the app sees it. `Client` is the query builder (Drizzle).
5
+ * Adapters (e.g. `@cardonjs/db-d1`) build it; every adapter passes `databaseContract`.
6
+ */
7
+ export interface Database<Client> {
8
+ /** Used by repositories. Never used by business logic directly. */
9
+ readonly client: Client;
10
+ /**
11
+ * Resolves when the database answers; rejects otherwise. Rejects right away when `signal`
12
+ * is already aborted, and when it aborts while waiting. Never writes.
13
+ */
14
+ ping(signal?: AbortSignal): Promise<void>;
15
+ }
16
+ /**
17
+ * A `/ready` health check that pings the database chosen from the context, passing the
18
+ * per-check abort signal, e.g.
19
+ * `healthChecks: { db: databaseHealthCheck((c) => c.var.adapters.db) }`.
20
+ */
21
+ export declare function databaseHealthCheck<E extends Env>(select: (c: Context<E>) => Database<unknown>): HealthCheck<E>;
22
+ //# sourceMappingURL=database.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAEzC;;;GAGG;AACH,MAAM,WAAW,QAAQ,CAAC,MAAM;IAC9B,mEAAmE;IACnE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3C;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,GAAG,EAC/C,MAAM,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,OAAO,CAAC,GAC3C,WAAW,CAAC,CAAC,CAAC,CAIhB"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A `/ready` health check that pings the database chosen from the context, passing the
3
+ * per-check abort signal, e.g.
4
+ * `healthChecks: { db: databaseHealthCheck((c) => c.var.adapters.db) }`.
5
+ */
6
+ export function databaseHealthCheck(select) {
7
+ return async (c, signal) => {
8
+ await select(c).ping(signal);
9
+ };
10
+ }
11
+ //# sourceMappingURL=database.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.js","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAiBA;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAA4C;IAE5C,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE;QACzB,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC/B,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { type Database, databaseHealthCheck } from "./database.js";
2
+ export { NON_ERROR_REASON, StoreError, type StoreErrorInit, type StoreQueriesOptions, type StoreQuery, storeQueries, UNNAMED_REASON, } from "./store-error.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EACL,gBAAgB,EAChB,UAAU,EACV,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,UAAU,EACf,YAAY,EACZ,cAAc,GACf,MAAM,kBAAkB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { databaseHealthCheck } from "./database.js";
2
+ export { NON_ERROR_REASON, StoreError, storeQueries, UNNAMED_REASON, } from "./store-error.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EACL,gBAAgB,EAChB,UAAU,EAIV,YAAY,EACZ,cAAc,GACf,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,54 @@
1
+ /** The reason when the failure is not an `Error`. */
2
+ export declare const NON_ERROR_REASON = "NonError";
3
+ /** The reason when the failed error's `name` is not a plain identifier (or cannot be read). */
4
+ export declare const UNNAMED_REASON = "UnnamedError";
5
+ export interface StoreErrorInit {
6
+ /** The store, a plain identifier: the error is named `<Store>StoreError` (`NotesStoreError`). */
7
+ readonly store: string;
8
+ /** What failed, a fixed string the author writes (`"update"`, `"payments apply"`). */
9
+ readonly operation: string;
10
+ /**
11
+ * Why, as an identifier: the failed error's name, or a fixed word of the store's own
12
+ * (`"MalformedRecord"`). Anything else is replaced by {@link UNNAMED_REASON}.
13
+ */
14
+ readonly reason: string;
15
+ /** A driver error code; kept only when it is an upper-case identifier or a SQLSTATE. */
16
+ readonly code?: string | undefined;
17
+ /** The message's prefix. Default: `<store> store`. */
18
+ readonly label?: string | undefined;
19
+ }
20
+ /**
21
+ * A store's query failed. Its message is `<label>: <operation> failed (<reason>).` and its fields
22
+ * are `store`, `operation`, `reason` and, when the driver exposed one, `code`; `operation`,
23
+ * `reason` and `code` are on core's logger allowlist, so `request failed` shows them. It has no
24
+ * `cause`: the failed error is dropped. Throws a `TypeError` when `store`, `operation` or `label`
25
+ * is not a fixed name (they are the author's, never a value).
26
+ */
27
+ export declare class StoreError extends Error {
28
+ readonly store: string;
29
+ readonly operation: string;
30
+ readonly reason: string;
31
+ readonly code?: string;
32
+ constructor(init: StoreErrorInit);
33
+ }
34
+ /** Runs one query (or one batch) of a store; see {@link storeQueries}. */
35
+ export type StoreQuery = <T>(operation: string, run: () => T | PromiseLike<T>) => Promise<T>;
36
+ export interface StoreQueriesOptions {
37
+ /** The prefix of every error's message. Default: `<store> store`. */
38
+ readonly label?: string;
39
+ }
40
+ /**
41
+ * The query wrapper of one store: `query(operation, run)` awaits `run()` and resolves with its
42
+ * result. A failure is rethrown as a {@link StoreError} for `store` and `operation`, with the
43
+ * failed error's name as `reason` and its driver code (or its causes') when valid, never the
44
+ * error itself. An `AppError` (core) or a `StoreError` thrown inside `run` is rethrown unchanged,
45
+ * so an `AppError` decided there (a 404, a 409 from a constraint) keeps its status; when it
46
+ * carries a `cause` that is not itself such an error without one (e.g. `{ cause: driverError }`),
47
+ * a copy without the cause is thrown instead (same class and fields; the original is not
48
+ * touched). Wrap a batch (`client.batch([...])`) as one operation.
49
+ *
50
+ * Throws a `TypeError` right away for an invalid `store` or label, and when a call's
51
+ * `operation` is not a fixed name (before running anything).
52
+ */
53
+ export declare function storeQueries(store: string, options?: StoreQueriesOptions): StoreQuery;
54
+ //# sourceMappingURL=store-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-error.d.ts","sourceRoot":"","sources":["../src/store-error.ts"],"names":[],"mappings":"AA0BA,qDAAqD;AACrD,eAAO,MAAM,gBAAgB,aAAa,CAAC;AAC3C,+FAA+F;AAC/F,eAAO,MAAM,cAAc,iBAAiB,CAAC;AAE7C,MAAM,WAAW,cAAc;IAC7B,iGAAiG;IACjG,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,sFAAsF;IACtF,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,wFAAwF;IACxF,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,sDAAsD;IACtD,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAED;;;;;;GAMG;AACH,qBAAa,UAAW,SAAQ,KAAK;IACnC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,SAAiB,IAAI,CAAC,EAAE,MAAM,CAAC;IAE/B,YAAY,IAAI,EAAE,cAAc,EAY/B;CACF;AAED,0EAA0E;AAC1E,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;AAE7F,MAAM,WAAW,mBAAmB;IAClC,qEAAqE;IACrE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,UAAU,CAuBzF"}
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Errors of a store's queries that carry no values. A database driver's own error is not safe to
3
+ * log: Drizzle's message is `Failed query: <sql>\nparams: <every bound value>`, and drivers keep
4
+ * the conflicting value in fields or in the cause. `storeQueries` turns such a failure into a
5
+ * `StoreError` built only from fixed or validated parts: the store, the operation the author
6
+ * wrote, the failed error's `name` when it is a plain identifier, and a driver code when it has
7
+ * the form of one. Never its message, stack, fields or cause. Driver-neutral: it knows nothing
8
+ * of Drizzle or D1.
9
+ */
10
+ import { AppError } from "@cardonjs/core";
11
+ /** A store name: it becomes the error's name (`notes` → `NotesStoreError`). */
12
+ const STORE = /^[A-Za-z][A-Za-z0-9]{0,63}$/;
13
+ /** An operation or a label: written by the author, never built from a value. */
14
+ const TEXT = /^[A-Za-z0-9][A-Za-z0-9 _.:/-]{0,99}$/;
15
+ /** A reason: an error's `name` (`Error`, `TypeError`, `DrizzleQueryError`), nothing else. */
16
+ const REASON = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
17
+ /**
18
+ * A driver error code: an upper-case identifier (`SQLITE_CONSTRAINT_UNIQUE`, `SQLITE_BUSY`) or a
19
+ * five-character SQLSTATE (Postgres' `23505`). Nothing longer, lower-case or free-form, and no
20
+ * long run of digits (which could be a value).
21
+ */
22
+ const CODE = /^(?:[A-Z][A-Z0-9_]{2,39}|[0-9A-Z]{5})$/;
23
+ /** Errors searched for a code: the failed one and its causes, this many in all. */
24
+ const CODE_DEPTH = 3;
25
+ /** The reason when the failure is not an `Error`. */
26
+ export const NON_ERROR_REASON = "NonError";
27
+ /** The reason when the failed error's `name` is not a plain identifier (or cannot be read). */
28
+ export const UNNAMED_REASON = "UnnamedError";
29
+ /**
30
+ * A store's query failed. Its message is `<label>: <operation> failed (<reason>).` and its fields
31
+ * are `store`, `operation`, `reason` and, when the driver exposed one, `code`; `operation`,
32
+ * `reason` and `code` are on core's logger allowlist, so `request failed` shows them. It has no
33
+ * `cause`: the failed error is dropped. Throws a `TypeError` when `store`, `operation` or `label`
34
+ * is not a fixed name (they are the author's, never a value).
35
+ */
36
+ export class StoreError extends Error {
37
+ store;
38
+ operation;
39
+ reason;
40
+ constructor(init) {
41
+ const store = checkStore(init.store);
42
+ const operation = checkText(init.operation, "operation");
43
+ const label = init.label === undefined ? `${store} store` : checkText(init.label, "label");
44
+ const reason = typeof init.reason === "string" && REASON.test(init.reason) ? init.reason : UNNAMED_REASON;
45
+ super(`${label}: ${operation} failed (${reason}).`);
46
+ this.name = `${store[0]?.toUpperCase()}${store.slice(1)}StoreError`;
47
+ this.store = store;
48
+ this.operation = operation;
49
+ this.reason = reason;
50
+ if (typeof init.code === "string" && CODE.test(init.code))
51
+ this.code = init.code;
52
+ }
53
+ }
54
+ /**
55
+ * The query wrapper of one store: `query(operation, run)` awaits `run()` and resolves with its
56
+ * result. A failure is rethrown as a {@link StoreError} for `store` and `operation`, with the
57
+ * failed error's name as `reason` and its driver code (or its causes') when valid, never the
58
+ * error itself. An `AppError` (core) or a `StoreError` thrown inside `run` is rethrown unchanged,
59
+ * so an `AppError` decided there (a 404, a 409 from a constraint) keeps its status; when it
60
+ * carries a `cause` that is not itself such an error without one (e.g. `{ cause: driverError }`),
61
+ * a copy without the cause is thrown instead (same class and fields; the original is not
62
+ * touched). Wrap a batch (`client.batch([...])`) as one operation.
63
+ *
64
+ * Throws a `TypeError` right away for an invalid `store` or label, and when a call's
65
+ * `operation` is not a fixed name (before running anything).
66
+ */
67
+ export function storeQueries(store, options = {}) {
68
+ const name = checkStore(store);
69
+ const label = options.label === undefined ? undefined : checkText(options.label, "label");
70
+ return async (operation, run) => {
71
+ checkText(operation, "operation");
72
+ try {
73
+ return await run();
74
+ }
75
+ catch (error) {
76
+ if (error instanceof StoreError || error instanceof AppError) {
77
+ if (!hasUnsafeCause(error))
78
+ throw error;
79
+ // Its status stays (a 404 is still a 404), never the cause: a copy without it.
80
+ const copy = withoutCause(error);
81
+ if (copy !== undefined)
82
+ throw copy;
83
+ }
84
+ throw new StoreError({
85
+ store: name,
86
+ operation,
87
+ reason: reasonOf(error),
88
+ code: codeOf(error),
89
+ label,
90
+ });
91
+ }
92
+ };
93
+ }
94
+ /** Errors whose cause chain is checked before it is passed through; deeper is unsafe. */
95
+ const CAUSE_DEPTH = 3;
96
+ /**
97
+ * Whether an `AppError` or `StoreError` carries a cause that could hold values: anything but
98
+ * another `AppError` or `StoreError` without one (a driver error passed as `{ cause }`).
99
+ */
100
+ function hasUnsafeCause(error) {
101
+ let current = error;
102
+ for (let depth = 0; depth <= CAUSE_DEPTH; depth++) {
103
+ let cause;
104
+ try {
105
+ cause = current.cause;
106
+ }
107
+ catch {
108
+ return true;
109
+ }
110
+ if (cause === undefined)
111
+ return false;
112
+ if (!(cause instanceof StoreError || cause instanceof AppError))
113
+ return true;
114
+ current = cause;
115
+ }
116
+ return true;
117
+ }
118
+ /**
119
+ * A copy of `error` without `cause`: same prototype (so `instanceof NotFoundError` and the status
120
+ * hold) and every other own property, the stack included. The caller's error is not touched.
121
+ * `undefined` when it cannot be copied.
122
+ */
123
+ function withoutCause(error) {
124
+ try {
125
+ const descriptors = Object.getOwnPropertyDescriptors(error);
126
+ delete descriptors.cause;
127
+ // A real `Error` (its internal brand, for `Error.isError`) on the original's prototype,
128
+ // without running the subclass's constructor.
129
+ const copy = new Error();
130
+ Object.setPrototypeOf(copy, Object.getPrototypeOf(error));
131
+ Object.defineProperties(copy, descriptors);
132
+ return copy.cause === undefined ? copy : undefined;
133
+ }
134
+ catch {
135
+ return undefined;
136
+ }
137
+ }
138
+ function checkStore(store) {
139
+ if (typeof store !== "string" || !STORE.test(store)) {
140
+ throw new TypeError('storeQueries: store must be a plain identifier (e.g. "notes").');
141
+ }
142
+ return store;
143
+ }
144
+ function checkText(value, field) {
145
+ if (typeof value !== "string" || !TEXT.test(value)) {
146
+ throw new TypeError(`storeQueries: ${field} must be a fixed name (letters, digits, spaces and _.:/-, up to 100).`);
147
+ }
148
+ return value;
149
+ }
150
+ function isError(value) {
151
+ try {
152
+ return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
153
+ }
154
+ catch {
155
+ return false;
156
+ }
157
+ }
158
+ /** The failed error's `name` when it is a plain identifier; otherwise a fixed word. */
159
+ function reasonOf(error) {
160
+ if (!isError(error))
161
+ return NON_ERROR_REASON;
162
+ try {
163
+ const name = error.name;
164
+ return typeof name === "string" && REASON.test(name) ? name : UNNAMED_REASON;
165
+ }
166
+ catch {
167
+ return UNNAMED_REASON;
168
+ }
169
+ }
170
+ /**
171
+ * The first `code` that looks like a driver code on the error or its causes (Drizzle wraps the
172
+ * driver's error as `cause`). Only the matching string is kept; the causes are not.
173
+ */
174
+ function codeOf(error) {
175
+ let current = error;
176
+ for (let depth = 0; depth < CODE_DEPTH; depth++) {
177
+ if (typeof current !== "object" || current === null)
178
+ return undefined;
179
+ try {
180
+ const code = current.code;
181
+ if (typeof code === "string" && CODE.test(code))
182
+ return code;
183
+ current = current.cause;
184
+ }
185
+ catch {
186
+ return undefined;
187
+ }
188
+ }
189
+ return undefined;
190
+ }
191
+ //# sourceMappingURL=store-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-error.js","sourceRoot":"","sources":["../src/store-error.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,QAAQ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GAAG,CAAC,EAAE,KAAK,GAAG,UAAU,EAAE,KAAK,EAAE,EAAE,CAAC;QAChD,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI;YAAE,OAAO,SAAS,CAAC;QACtE,IAAI,CAAC;YACH,MAAM,IAAI,GAAa,OAA8B,CAAC,IAAI,CAAC;YAC3D,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;gBAAE,OAAO,IAAI,CAAC;YAC7D,OAAO,GAAI,OAA+B,CAAC,KAAK,CAAC;QACnD,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC"}
package/llms.txt ADDED
@@ -0,0 +1,130 @@
1
+ # @cardonjs/db
2
+
3
+ The database interface of Cardón: the `Database<Client>` type every database adapter returns, a
4
+ `/ready` health check that pings it, `storeQueries` (database errors without values), and the
5
+ shared contract suite adapters must pass. It is not
6
+ an ORM or a SQL abstraction: `client` is the query builder itself (Drizzle), used directly by
7
+ repositories. Standard web APIs only (Workers, Node, Bun, Deno).
8
+
9
+ Full documentation: README.md in this package.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ pnpm add @cardonjs/db @cardonjs/core hono
15
+ ```
16
+
17
+ Required peers: `@cardonjs/core`, `hono`. `@cardonjs/testing` is an optional peer, only needed by
18
+ `@cardonjs/db/contract` (in adapter tests). An app also needs an adapter, e.g. `@cardonjs/db-d1`.
19
+
20
+ ## Exports
21
+
22
+ ### `@cardonjs/db`
23
+
24
+ - `Database<Client>` (type):
25
+
26
+ ```ts
27
+ interface Database<Client> {
28
+ readonly client: Client;
29
+ ping(signal?: AbortSignal): Promise<void>;
30
+ }
31
+ ```
32
+
33
+ `client` is the query builder (e.g. `DrizzleD1Database`). `ping` resolves when the database
34
+ answers and rejects otherwise; it rejects right away with `signal.reason`, without touching the
35
+ database, when the signal is already aborted, and as soon as it aborts while waiting. It never
36
+ writes.
37
+ - `databaseHealthCheck(select)`: returns a core `HealthCheck` that pings the database
38
+ `select(c)` returns, passing `/ready`'s per-check abort signal. Register it under a module's
39
+ `healthChecks`; it is reported as `<module>.<key>`.
40
+ - `storeQueries(store, options?)`: returns `query(operation, run)`, which awaits `run()` (a
41
+ query builder, a batch, any promise) and resolves with its result. A failure is rethrown as a
42
+ `StoreError` named `<Store>StoreError` (`storeQueries("notes")` → `NotesStoreError`), message
43
+ `notes store: <operation> failed (<reason>).` (`options.label` replaces `notes store`). An
44
+ `AppError` or a `StoreError` thrown inside `run` passes through unchanged. `store` and
45
+ `operation` must be fixed names (identifier; letters, digits, spaces, `_.:/-`), else
46
+ `TypeError` before running.
47
+ - `StoreError` (class): fields `store`, `operation`, `reason` (the failed error's `name` when a
48
+ plain identifier, else `UnnamedError`, or `NonError` for a non-Error) and, only when found,
49
+ `code` (an upper-case identifier such as `SQLITE_CONSTRAINT_UNIQUE`, or a SQLSTATE such as
50
+ `23505`, from the error or its causes). No `cause`, never the driver's message, stack or
51
+ fields. `new StoreError({ store, operation, reason, code?, label? })` for a store's own
52
+ failure. `NON_ERROR_REASON`, `UNNAMED_REASON` (constants), `StoreQuery`, `StoreErrorInit`,
53
+ `StoreQueriesOptions` (types).
54
+
55
+ ### `@cardonjs/db/contract`
56
+
57
+ - `databaseContract`: the six cases every `Database` adapter must pass (a list of
58
+ `{ name, run(harness) }`).
59
+ - `DatabaseContractHarness<Client>` (type): `create()` (a healthy database with an empty probe
60
+ table, `id` text primary key, fresh per call), `createBroken()` (its `ping` must reject),
61
+ `writeProbe(db, id)`, `readProbes(db)`, `batchWithFailure(db, id)` (one atomic batch: insert
62
+ the probe, then a failing statement; must reject).
63
+
64
+ ## Minimal example
65
+
66
+ ```ts
67
+ import { type CardonEnv, createApp, defineModule } from "@cardonjs/core";
68
+ import { databaseHealthCheck } from "@cardonjs/db";
69
+ import { d1Database } from "@cardonjs/db-d1";
70
+
71
+ type Bindings = { DB: D1Database };
72
+ const adapters = (env: Bindings) => ({ db: d1Database(env.DB) });
73
+ type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
74
+
75
+ const ordersModule = defineModule<AppEnv>({
76
+ name: "orders",
77
+ prefix: "/v1/orders",
78
+ healthChecks: { db: databaseHealthCheck((c) => c.var.adapters.db) },
79
+ });
80
+
81
+ export default createApp(adapters).register(ordersModule);
82
+ // GET /ready reports the check as "orders.db".
83
+ ```
84
+
85
+ In an adapter's tests:
86
+
87
+ ```ts
88
+ import { databaseContract } from "@cardonjs/db/contract";
89
+ import { it } from "vitest";
90
+
91
+ it.each(databaseContract.map((c) => [c.name, c] as const))("%s", (_, c) => c.run(harness));
92
+ ```
93
+
94
+ ## Rules and common mistakes
95
+
96
+ - `client` is used by repositories, never by business logic directly. Business logic receives
97
+ repositories through `c.var.adapters` and never touches a provider SDK or a binding.
98
+ - There is no batch or transaction wrapper: use the client's own. With Drizzle,
99
+ `client.batch([...])` for writes that must succeed together, where the driver supports it.
100
+ - **Every query and batch of a repository runs through `query` from `storeQueries`.** A bare
101
+ Drizzle query that fails throws `DrizzleQueryError`, whose message is the SQL plus every bound
102
+ value, with the driver's error as `cause`: it reaches the `request failed` log line. Wrap a
103
+ batch as one operation. Never attach a driver error as `cause` of your own error.
104
+ - To turn a database error into a client error (a unique constraint → 409), decide inside `run`
105
+ on the raw error and throw the `AppError` there (it passes through), or decide in SQL
106
+ (`onConflictDoNothing().returning()`, a conditional update, `transition`) and read the result
107
+ outside `query`. Throw errors about results (a lost race) outside `query`.
108
+ - Operation names are string literals you write (`"update"`, `"applyPayment insert"`), never
109
+ built from a value: the check only limits characters, so `` `update ${id}` `` passes and is
110
+ logged.
111
+ - `reason` and `code` are read from the failed error: never set an error's `name` or `code` from
112
+ data inside `run`. D1's errors carry no `code`.
113
+ - Never pass `{ cause: driverError }` to an `AppError` thrown inside `run`. If one carries such a
114
+ cause, `query` throws a copy without it (same class, status, message, details; the original
115
+ untouched).
116
+ - There is no `migrate`: migrations are generated and applied by tooling in CI (for D1, Drizzle
117
+ Kit and Wrangler), never by the running Worker.
118
+ - The health check fails (`503`, `degraded`) when the ping rejects, when `select` throws, or when
119
+ the ping outlives the `/ready` per-check timeout (`createApp({ ready: { timeoutMs } })`, 3 s by
120
+ default). Errors are logged by core, never returned in the response.
121
+ - A new adapter runs `databaseContract` against a real database, with a thin harness that uses
122
+ `client` honestly. Rejecting when the signal aborts while waiting cannot be forced generically:
123
+ each adapter tests it on its own.
124
+
125
+ ## Out of scope
126
+
127
+ - An ORM, a SQL abstraction or a repository layer.
128
+ - Interactive transactions in the shared interface (adapters may add them as an extra).
129
+ - Runtime migrations.
130
+ - An in-memory fake: this package has no `./testing` entry.
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@cardonjs/db",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.1",
4
+ "description": "Database interface for Cardón apps: the Database type, a /ready health check, store errors without values and the shared adapter contract suite.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/cardonjs/cardon.git",
9
+ "directory": "packages/db"
10
+ },
11
+ "homepage": "https://github.com/cardonjs/cardon/tree/main/packages/db#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/cardonjs/cardon/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./contract": {
23
+ "types": "./dist/contract.d.ts",
24
+ "default": "./dist/contract.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "llms.txt"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "peerDependencies": {
35
+ "hono": "^4.13.18",
36
+ "@cardonjs/core": "^0.5.1",
37
+ "@cardonjs/testing": "^0.6.0"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "@cardonjs/testing": {
41
+ "optional": true
42
+ }
43
+ },
44
+ "devDependencies": {
45
+ "@hono/zod-openapi": "1.6.3",
46
+ "@scalar/hono-api-reference": "0.12.20",
47
+ "hono": "4.13.18",
48
+ "typescript": "7.0.2",
49
+ "vitest": "5.1.0",
50
+ "zod": "4.6.7",
51
+ "@cardonjs/config": "0.0.0",
52
+ "@cardonjs/core": "0.5.1",
53
+ "@cardonjs/testing": "0.6.0"
54
+ },
55
+ "scripts": {
56
+ "build": "tsc -p tsconfig.build.json",
57
+ "typecheck": "tsc -p tsconfig.json --noEmit",
58
+ "test": "vitest run"
59
+ }
6
60
  }