@noy-db/to-cloudflare-d1 0.1.0-pre.3

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 vLannaAi
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,33 @@
1
+ # @noy-db/to-cloudflare-d1
2
+
3
+ [![npm](https://img.shields.io/npm/v/%40noy-db/to-cloudflare-d1.svg)](https://www.npmjs.com/package/@noy-db/to-cloudflare-d1)
4
+
5
+ > Cloudflare D1 adapter for noy-db
6
+
7
+ Part of [**`@noy-db/hub`**](https://www.npmjs.com/package/@noy-db/hub) — the zero-knowledge, offline-first, encrypted document store.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pnpm add @noy-db/hub @noy-db/to-cloudflare-d1
13
+ ```
14
+
15
+ ## What it is
16
+
17
+ Cloudflare D1 adapter for noy-db — SQLite at the edge, running inside Cloudflare Workers. Accepts a D1Database binding and speaks the noy-db store contract via D1's prepare/bind API.
18
+
19
+ ## Status
20
+
21
+ **Pre-release** (`0.1.0-pre.1`). API may change before `1.0`.
22
+
23
+ ## Documentation
24
+
25
+ See the [main repository](https://github.com/vLannaAi/noy-db#readme) for setup, examples, and the full subsystem catalog.
26
+
27
+ - Source — [`packages/to-cloudflare-d1`](https://github.com/vLannaAi/noy-db/tree/main/packages/to-cloudflare-d1)
28
+ - Issues — [github.com/vLannaAi/noy-db/issues](https://github.com/vLannaAi/noy-db/issues)
29
+ - Spec — [`SPEC.md`](https://github.com/vLannaAi/noy-db/blob/main/SPEC.md)
30
+
31
+ ## License
32
+
33
+ [MIT](./LICENSE) © vLannaAi
package/dist/index.cjs ADDED
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ d1: () => d1
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+ var import_hub = require("@noy-db/hub");
27
+ function d1(options) {
28
+ const { db, tableName = "noydb_envelopes", autoMigrate = true } = options;
29
+ let schemaReady = null;
30
+ async function ensureSchema() {
31
+ if (!autoMigrate) return;
32
+ if (!schemaReady) {
33
+ schemaReady = (async () => {
34
+ await db.prepare(
35
+ `CREATE TABLE IF NOT EXISTS ${tableName} (
36
+ vault TEXT NOT NULL,
37
+ collection TEXT NOT NULL,
38
+ id TEXT NOT NULL,
39
+ v INTEGER NOT NULL,
40
+ ts TEXT NOT NULL,
41
+ iv TEXT NOT NULL,
42
+ data TEXT NOT NULL,
43
+ by TEXT,
44
+ tier INTEGER,
45
+ elevated_by TEXT,
46
+ det TEXT,
47
+ PRIMARY KEY (vault, collection, id)
48
+ )`
49
+ ).run();
50
+ await db.prepare(`CREATE INDEX IF NOT EXISTS idx_${tableName}_vc ON ${tableName} (vault, collection)`).run();
51
+ })();
52
+ }
53
+ await schemaReady;
54
+ }
55
+ function rowToEnvelope(row) {
56
+ const by = row.by;
57
+ const tier = row.tier;
58
+ const elevatedBy = row.elevated_by;
59
+ const detRaw = row.det;
60
+ return {
61
+ _noydb: 1,
62
+ _v: row.v,
63
+ _ts: row.ts,
64
+ _iv: row.iv,
65
+ _data: row.data,
66
+ ...by !== null && { _by: by },
67
+ ...tier !== null && { _tier: tier },
68
+ ...elevatedBy !== null && { _elevatedBy: elevatedBy },
69
+ ...detRaw !== null && { _det: JSON.parse(detRaw) }
70
+ };
71
+ }
72
+ function upsertStatement(vault, collection, id, envelope) {
73
+ return db.prepare(
74
+ `INSERT INTO ${tableName} (vault, collection, id, v, ts, iv, data, by, tier, elevated_by, det)
75
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
76
+ ON CONFLICT(vault, collection, id) DO UPDATE SET
77
+ v = excluded.v, ts = excluded.ts, iv = excluded.iv, data = excluded.data,
78
+ by = excluded.by, tier = excluded.tier, elevated_by = excluded.elevated_by, det = excluded.det`
79
+ ).bind(
80
+ vault,
81
+ collection,
82
+ id,
83
+ envelope._v,
84
+ envelope._ts,
85
+ envelope._iv,
86
+ envelope._data,
87
+ envelope._by ?? null,
88
+ envelope._tier ?? null,
89
+ envelope._elevatedBy ?? null,
90
+ envelope._det ? JSON.stringify(envelope._det) : null
91
+ );
92
+ }
93
+ async function upsert(vault, collection, id, envelope, expectedVersion) {
94
+ await ensureSchema();
95
+ if (expectedVersion !== void 0) {
96
+ const existing = await db.prepare(`SELECT v FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`).bind(vault, collection, id).first();
97
+ if (existing && existing.v !== expectedVersion) {
98
+ throw new import_hub.ConflictError(existing.v, `Version conflict: expected ${expectedVersion}, found ${existing.v}`);
99
+ }
100
+ }
101
+ await upsertStatement(vault, collection, id, envelope).run();
102
+ }
103
+ const store = {
104
+ name: "cloudflare-d1",
105
+ async get(vault, collection, id) {
106
+ await ensureSchema();
107
+ const row = await db.prepare(`SELECT * FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`).bind(vault, collection, id).first();
108
+ return row ? rowToEnvelope(row) : null;
109
+ },
110
+ async put(vault, collection, id, envelope, expectedVersion) {
111
+ await upsert(vault, collection, id, envelope, expectedVersion);
112
+ },
113
+ async delete(vault, collection, id) {
114
+ await ensureSchema();
115
+ await db.prepare(`DELETE FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`).bind(vault, collection, id).run();
116
+ },
117
+ async list(vault, collection) {
118
+ await ensureSchema();
119
+ const res = await db.prepare(`SELECT id FROM ${tableName} WHERE vault = ? AND collection = ? ORDER BY id`).bind(vault, collection).all();
120
+ return (res.results ?? []).map((r) => r.id);
121
+ },
122
+ async loadAll(vault) {
123
+ await ensureSchema();
124
+ const res = await db.prepare(`SELECT * FROM ${tableName} WHERE vault = ?`).bind(vault).all();
125
+ const snap = {};
126
+ for (const row of res.results ?? []) {
127
+ const collection = row.collection;
128
+ const id = row.id;
129
+ const bucket = snap[collection] ?? (snap[collection] = {});
130
+ bucket[id] = rowToEnvelope(row);
131
+ }
132
+ return snap;
133
+ },
134
+ async saveAll(vault, data) {
135
+ await ensureSchema();
136
+ const statements = [
137
+ db.prepare(`DELETE FROM ${tableName} WHERE vault = ?`).bind(vault)
138
+ ];
139
+ for (const [collection, recs] of Object.entries(data)) {
140
+ for (const [id, envelope] of Object.entries(recs)) {
141
+ statements.push(upsertStatement(vault, collection, id, envelope));
142
+ }
143
+ }
144
+ await db.batch(statements);
145
+ },
146
+ async ping() {
147
+ try {
148
+ await db.prepare("SELECT 1").run();
149
+ return true;
150
+ } catch {
151
+ return false;
152
+ }
153
+ },
154
+ async listPage(vault, collection, cursor, limit = 100) {
155
+ await ensureSchema();
156
+ const afterId = cursor ?? "";
157
+ const res = await db.prepare(
158
+ `SELECT id, v, ts, iv, data, by, tier, elevated_by, det FROM ${tableName}
159
+ WHERE vault = ? AND collection = ? AND id > ?
160
+ ORDER BY id LIMIT ?`
161
+ ).bind(vault, collection, afterId, limit + 1).all();
162
+ const rows = res.results ?? [];
163
+ const hasMore = rows.length > limit;
164
+ const trimmed = hasMore ? rows.slice(0, limit) : rows;
165
+ const items = trimmed.map((r) => ({ id: r.id, envelope: rowToEnvelope(r) }));
166
+ const out = {
167
+ items,
168
+ nextCursor: hasMore ? trimmed[trimmed.length - 1].id : null
169
+ };
170
+ return out;
171
+ },
172
+ async tx(ops) {
173
+ await ensureSchema();
174
+ const statements = [];
175
+ for (const op of ops) {
176
+ if (op.type === "put") {
177
+ if (!op.envelope) throw new Error(`tx put op missing envelope for ${op.id}`);
178
+ statements.push(upsertStatement(op.vault, op.collection, op.id, op.envelope));
179
+ } else {
180
+ statements.push(
181
+ db.prepare(`DELETE FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`).bind(op.vault, op.collection, op.id)
182
+ );
183
+ }
184
+ }
185
+ await db.batch(statements);
186
+ }
187
+ };
188
+ return store;
189
+ }
190
+ // Annotate the CommonJS export names for ESM import in node:
191
+ 0 && (module.exports = {
192
+ d1
193
+ });
194
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/to-cloudflare-d1** — Cloudflare D1 adapter for noy-db.\n *\n * D1 is Cloudflare's edge SQLite. Inside a Worker, the `env.DB` binding\n * exposes a `D1Database` whose API is `prepare(sql).bind(...args).run()`\n * — different from node-postgres or libSQL but easy to adapt.\n *\n * ```ts\n * import { d1 } from '@noy-db/to-cloudflare-d1'\n *\n * export default {\n * async fetch(request: Request, env: { DB: D1Database }) {\n * const store = d1({ db: env.DB })\n * const db = await createNoydb({ store })\n * // …\n * },\n * }\n * ```\n *\n * ## Capabilities\n *\n * | Capability | Value |\n * |-------------|-------|\n * | `casAtomic` | `true` — `UPDATE … WHERE v = ?` inside a D1 batch |\n * | `txAtomic` | `true` — `D1Database.batch()` is atomic per-session |\n * | `listPage` | ✓ — keyset pagination by id |\n * | `ping` | ✓ — `SELECT 1` |\n *\n * @packageDocumentation\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot, TxOp, ListPageResult } from '@noy-db/hub'\nimport { ConflictError } from '@noy-db/hub'\n\n/** Duck-typed subset of the `D1Database` binding. */\nexport interface D1Database {\n prepare(sql: string): D1PreparedStatement\n batch<T = unknown>(statements: readonly D1PreparedStatement[]): Promise<D1Result<T>[]>\n exec?(sql: string): Promise<unknown>\n}\n\nexport interface D1PreparedStatement {\n bind(...args: readonly unknown[]): D1PreparedStatement\n first<T = unknown>(): Promise<T | null>\n all<T = unknown>(): Promise<D1Result<T>>\n run<T = unknown>(): Promise<D1Result<T>>\n}\n\nexport interface D1Result<T = unknown> {\n readonly results?: readonly T[]\n readonly success?: boolean\n}\n\nexport interface D1StoreOptions {\n readonly db: D1Database\n readonly tableName?: string\n readonly autoMigrate?: boolean\n}\n\nexport function d1(options: D1StoreOptions): NoydbStore {\n const { db, tableName = 'noydb_envelopes', autoMigrate = true } = options\n let schemaReady: Promise<void> | null = null\n\n async function ensureSchema(): Promise<void> {\n if (!autoMigrate) return\n if (!schemaReady) {\n schemaReady = (async () => {\n await db\n .prepare(\n `CREATE TABLE IF NOT EXISTS ${tableName} (\n vault TEXT NOT NULL,\n collection TEXT NOT NULL,\n id TEXT NOT NULL,\n v INTEGER NOT NULL,\n ts TEXT NOT NULL,\n iv TEXT NOT NULL,\n data TEXT NOT NULL,\n by TEXT,\n tier INTEGER,\n elevated_by TEXT,\n det TEXT,\n PRIMARY KEY (vault, collection, id)\n )`,\n )\n .run()\n await db\n .prepare(`CREATE INDEX IF NOT EXISTS idx_${tableName}_vc ON ${tableName} (vault, collection)`)\n .run()\n })()\n }\n await schemaReady\n }\n\n function rowToEnvelope(row: Record<string, unknown>): EncryptedEnvelope {\n const by = row.by as string | null\n const tier = row.tier as number | null\n const elevatedBy = row.elevated_by as string | null\n const detRaw = row.det as string | null\n return {\n _noydb: 1,\n _v: row.v as number,\n _ts: row.ts as string,\n _iv: row.iv as string,\n _data: row.data as string,\n ...(by !== null && { _by: by }),\n ...(tier !== null && { _tier: tier }),\n ...(elevatedBy !== null && { _elevatedBy: elevatedBy }),\n ...(detRaw !== null && { _det: JSON.parse(detRaw) as Record<string, string> }),\n }\n }\n\n function upsertStatement(\n vault: string,\n collection: string,\n id: string,\n envelope: EncryptedEnvelope,\n ): D1PreparedStatement {\n return db\n .prepare(\n `INSERT INTO ${tableName} (vault, collection, id, v, ts, iv, data, by, tier, elevated_by, det)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(vault, collection, id) DO UPDATE SET\n v = excluded.v, ts = excluded.ts, iv = excluded.iv, data = excluded.data,\n by = excluded.by, tier = excluded.tier, elevated_by = excluded.elevated_by, det = excluded.det`,\n )\n .bind(\n vault, collection, id,\n envelope._v, envelope._ts, envelope._iv, envelope._data,\n envelope._by ?? null,\n envelope._tier ?? null,\n envelope._elevatedBy ?? null,\n envelope._det ? JSON.stringify(envelope._det) : null,\n )\n }\n\n async function upsert(\n vault: string,\n collection: string,\n id: string,\n envelope: EncryptedEnvelope,\n expectedVersion?: number,\n ): Promise<void> {\n await ensureSchema()\n if (expectedVersion !== undefined) {\n const existing = await db\n .prepare(`SELECT v FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`)\n .bind(vault, collection, id)\n .first<{ v: number }>()\n if (existing && existing.v !== expectedVersion) {\n throw new ConflictError(existing.v, `Version conflict: expected ${expectedVersion}, found ${existing.v}`)\n }\n }\n await upsertStatement(vault, collection, id, envelope).run()\n }\n\n const store: NoydbStore = {\n name: 'cloudflare-d1',\n\n async get(vault, collection, id) {\n await ensureSchema()\n const row = await db\n .prepare(`SELECT * FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`)\n .bind(vault, collection, id)\n .first<Record<string, unknown>>()\n return row ? rowToEnvelope(row) : null\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n await upsert(vault, collection, id, envelope, expectedVersion)\n },\n\n async delete(vault, collection, id) {\n await ensureSchema()\n await db\n .prepare(`DELETE FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`)\n .bind(vault, collection, id)\n .run()\n },\n\n async list(vault, collection) {\n await ensureSchema()\n const res = await db\n .prepare(`SELECT id FROM ${tableName} WHERE vault = ? AND collection = ? ORDER BY id`)\n .bind(vault, collection)\n .all<{ id: string }>()\n return (res.results ?? []).map(r => r.id)\n },\n\n async loadAll(vault) {\n await ensureSchema()\n const res = await db\n .prepare(`SELECT * FROM ${tableName} WHERE vault = ?`)\n .bind(vault)\n .all<Record<string, unknown>>()\n const snap: VaultSnapshot = {}\n for (const row of res.results ?? []) {\n const collection = row.collection as string\n const id = row.id as string\n const bucket = snap[collection] ?? (snap[collection] = {})\n bucket[id] = rowToEnvelope(row)\n }\n return snap\n },\n\n async saveAll(vault, data) {\n await ensureSchema()\n const statements: D1PreparedStatement[] = [\n db.prepare(`DELETE FROM ${tableName} WHERE vault = ?`).bind(vault),\n ]\n for (const [collection, recs] of Object.entries(data)) {\n for (const [id, envelope] of Object.entries(recs)) {\n statements.push(upsertStatement(vault, collection, id, envelope))\n }\n }\n await db.batch(statements)\n },\n\n async ping() {\n try {\n await db.prepare('SELECT 1').run()\n return true\n } catch {\n return false\n }\n },\n\n async listPage(vault, collection, cursor, limit = 100) {\n await ensureSchema()\n const afterId = cursor ?? ''\n const res = await db\n .prepare(\n `SELECT id, v, ts, iv, data, by, tier, elevated_by, det FROM ${tableName}\n WHERE vault = ? AND collection = ? AND id > ?\n ORDER BY id LIMIT ?`,\n )\n .bind(vault, collection, afterId, limit + 1)\n .all<Record<string, unknown>>()\n const rows = res.results ?? []\n const hasMore = rows.length > limit\n const trimmed = hasMore ? rows.slice(0, limit) : rows\n const items = trimmed.map(r => ({ id: r.id as string, envelope: rowToEnvelope(r) }))\n const out: ListPageResult = {\n items,\n nextCursor: hasMore ? (trimmed[trimmed.length - 1]!.id as string) : null,\n }\n return out\n },\n\n async tx(ops: readonly TxOp[]) {\n await ensureSchema()\n const statements: D1PreparedStatement[] = []\n for (const op of ops) {\n if (op.type === 'put') {\n if (!op.envelope) throw new Error(`tx put op missing envelope for ${op.id}`)\n statements.push(upsertStatement(op.vault, op.collection, op.id, op.envelope))\n } else {\n statements.push(\n db\n .prepare(`DELETE FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`)\n .bind(op.vault, op.collection, op.id),\n )\n }\n }\n await db.batch(statements)\n },\n }\n\n return store\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgCA,iBAA8B;AA2BvB,SAAS,GAAG,SAAqC;AACtD,QAAM,EAAE,IAAI,YAAY,mBAAmB,cAAc,KAAK,IAAI;AAClE,MAAI,cAAoC;AAExC,iBAAe,eAA8B;AAC3C,QAAI,CAAC,YAAa;AAClB,QAAI,CAAC,aAAa;AAChB,qBAAe,YAAY;AACzB,cAAM,GACH;AAAA,UACC,8BAA8B,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAczC,EACC,IAAI;AACP,cAAM,GACH,QAAQ,kCAAkC,SAAS,UA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,KAAK;AACpB,YAAI,GAAG,SAAS,OAAO;AACrB,cAAI,CAAC,GAAG,SAAU,OAAM,IAAI,MAAM,kCAAkC,GAAG,EAAE,EAAE;AAC3E,qBAAW,KAAK,gBAAgB,GAAG,OAAO,GAAG,YAAY,GAAG,IAAI,GAAG,QAAQ,CAAC;AAAA,QAC9E,OAAO;AACL,qBAAW;AAAA,YACT,GACG,QAAQ,eAAe,SAAS,gDAAgD,EAChF,KAAK,GAAG,OAAO,GAAG,YAAY,GAAG,EAAE;AAAA,UACxC;AAAA,QACF;AAAA,MACF;AACA,YAAM,GAAG,MAAM,UAAU;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,57 @@
1
+ import { NoydbStore } from '@noy-db/hub';
2
+
3
+ /**
4
+ * **@noy-db/to-cloudflare-d1** — Cloudflare D1 adapter for noy-db.
5
+ *
6
+ * D1 is Cloudflare's edge SQLite. Inside a Worker, the `env.DB` binding
7
+ * exposes a `D1Database` whose API is `prepare(sql).bind(...args).run()`
8
+ * — different from node-postgres or libSQL but easy to adapt.
9
+ *
10
+ * ```ts
11
+ * import { d1 } from '@noy-db/to-cloudflare-d1'
12
+ *
13
+ * export default {
14
+ * async fetch(request: Request, env: { DB: D1Database }) {
15
+ * const store = d1({ db: env.DB })
16
+ * const db = await createNoydb({ store })
17
+ * // …
18
+ * },
19
+ * }
20
+ * ```
21
+ *
22
+ * ## Capabilities
23
+ *
24
+ * | Capability | Value |
25
+ * |-------------|-------|
26
+ * | `casAtomic` | `true` — `UPDATE … WHERE v = ?` inside a D1 batch |
27
+ * | `txAtomic` | `true` — `D1Database.batch()` is atomic per-session |
28
+ * | `listPage` | ✓ — keyset pagination by id |
29
+ * | `ping` | ✓ — `SELECT 1` |
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+
34
+ /** Duck-typed subset of the `D1Database` binding. */
35
+ interface D1Database {
36
+ prepare(sql: string): D1PreparedStatement;
37
+ batch<T = unknown>(statements: readonly D1PreparedStatement[]): Promise<D1Result<T>[]>;
38
+ exec?(sql: string): Promise<unknown>;
39
+ }
40
+ interface D1PreparedStatement {
41
+ bind(...args: readonly unknown[]): D1PreparedStatement;
42
+ first<T = unknown>(): Promise<T | null>;
43
+ all<T = unknown>(): Promise<D1Result<T>>;
44
+ run<T = unknown>(): Promise<D1Result<T>>;
45
+ }
46
+ interface D1Result<T = unknown> {
47
+ readonly results?: readonly T[];
48
+ readonly success?: boolean;
49
+ }
50
+ interface D1StoreOptions {
51
+ readonly db: D1Database;
52
+ readonly tableName?: string;
53
+ readonly autoMigrate?: boolean;
54
+ }
55
+ declare function d1(options: D1StoreOptions): NoydbStore;
56
+
57
+ export { type D1Database, type D1PreparedStatement, type D1Result, type D1StoreOptions, d1 };
@@ -0,0 +1,57 @@
1
+ import { NoydbStore } from '@noy-db/hub';
2
+
3
+ /**
4
+ * **@noy-db/to-cloudflare-d1** — Cloudflare D1 adapter for noy-db.
5
+ *
6
+ * D1 is Cloudflare's edge SQLite. Inside a Worker, the `env.DB` binding
7
+ * exposes a `D1Database` whose API is `prepare(sql).bind(...args).run()`
8
+ * — different from node-postgres or libSQL but easy to adapt.
9
+ *
10
+ * ```ts
11
+ * import { d1 } from '@noy-db/to-cloudflare-d1'
12
+ *
13
+ * export default {
14
+ * async fetch(request: Request, env: { DB: D1Database }) {
15
+ * const store = d1({ db: env.DB })
16
+ * const db = await createNoydb({ store })
17
+ * // …
18
+ * },
19
+ * }
20
+ * ```
21
+ *
22
+ * ## Capabilities
23
+ *
24
+ * | Capability | Value |
25
+ * |-------------|-------|
26
+ * | `casAtomic` | `true` — `UPDATE … WHERE v = ?` inside a D1 batch |
27
+ * | `txAtomic` | `true` — `D1Database.batch()` is atomic per-session |
28
+ * | `listPage` | ✓ — keyset pagination by id |
29
+ * | `ping` | ✓ — `SELECT 1` |
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+
34
+ /** Duck-typed subset of the `D1Database` binding. */
35
+ interface D1Database {
36
+ prepare(sql: string): D1PreparedStatement;
37
+ batch<T = unknown>(statements: readonly D1PreparedStatement[]): Promise<D1Result<T>[]>;
38
+ exec?(sql: string): Promise<unknown>;
39
+ }
40
+ interface D1PreparedStatement {
41
+ bind(...args: readonly unknown[]): D1PreparedStatement;
42
+ first<T = unknown>(): Promise<T | null>;
43
+ all<T = unknown>(): Promise<D1Result<T>>;
44
+ run<T = unknown>(): Promise<D1Result<T>>;
45
+ }
46
+ interface D1Result<T = unknown> {
47
+ readonly results?: readonly T[];
48
+ readonly success?: boolean;
49
+ }
50
+ interface D1StoreOptions {
51
+ readonly db: D1Database;
52
+ readonly tableName?: string;
53
+ readonly autoMigrate?: boolean;
54
+ }
55
+ declare function d1(options: D1StoreOptions): NoydbStore;
56
+
57
+ export { type D1Database, type D1PreparedStatement, type D1Result, type D1StoreOptions, d1 };
package/dist/index.js ADDED
@@ -0,0 +1,169 @@
1
+ // src/index.ts
2
+ import { ConflictError } from "@noy-db/hub";
3
+ function d1(options) {
4
+ const { db, tableName = "noydb_envelopes", autoMigrate = true } = options;
5
+ let schemaReady = null;
6
+ async function ensureSchema() {
7
+ if (!autoMigrate) return;
8
+ if (!schemaReady) {
9
+ schemaReady = (async () => {
10
+ await db.prepare(
11
+ `CREATE TABLE IF NOT EXISTS ${tableName} (
12
+ vault TEXT NOT NULL,
13
+ collection TEXT NOT NULL,
14
+ id TEXT NOT NULL,
15
+ v INTEGER NOT NULL,
16
+ ts TEXT NOT NULL,
17
+ iv TEXT NOT NULL,
18
+ data TEXT NOT NULL,
19
+ by TEXT,
20
+ tier INTEGER,
21
+ elevated_by TEXT,
22
+ det TEXT,
23
+ PRIMARY KEY (vault, collection, id)
24
+ )`
25
+ ).run();
26
+ await db.prepare(`CREATE INDEX IF NOT EXISTS idx_${tableName}_vc ON ${tableName} (vault, collection)`).run();
27
+ })();
28
+ }
29
+ await schemaReady;
30
+ }
31
+ function rowToEnvelope(row) {
32
+ const by = row.by;
33
+ const tier = row.tier;
34
+ const elevatedBy = row.elevated_by;
35
+ const detRaw = row.det;
36
+ return {
37
+ _noydb: 1,
38
+ _v: row.v,
39
+ _ts: row.ts,
40
+ _iv: row.iv,
41
+ _data: row.data,
42
+ ...by !== null && { _by: by },
43
+ ...tier !== null && { _tier: tier },
44
+ ...elevatedBy !== null && { _elevatedBy: elevatedBy },
45
+ ...detRaw !== null && { _det: JSON.parse(detRaw) }
46
+ };
47
+ }
48
+ function upsertStatement(vault, collection, id, envelope) {
49
+ return db.prepare(
50
+ `INSERT INTO ${tableName} (vault, collection, id, v, ts, iv, data, by, tier, elevated_by, det)
51
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
52
+ ON CONFLICT(vault, collection, id) DO UPDATE SET
53
+ v = excluded.v, ts = excluded.ts, iv = excluded.iv, data = excluded.data,
54
+ by = excluded.by, tier = excluded.tier, elevated_by = excluded.elevated_by, det = excluded.det`
55
+ ).bind(
56
+ vault,
57
+ collection,
58
+ id,
59
+ envelope._v,
60
+ envelope._ts,
61
+ envelope._iv,
62
+ envelope._data,
63
+ envelope._by ?? null,
64
+ envelope._tier ?? null,
65
+ envelope._elevatedBy ?? null,
66
+ envelope._det ? JSON.stringify(envelope._det) : null
67
+ );
68
+ }
69
+ async function upsert(vault, collection, id, envelope, expectedVersion) {
70
+ await ensureSchema();
71
+ if (expectedVersion !== void 0) {
72
+ const existing = await db.prepare(`SELECT v FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`).bind(vault, collection, id).first();
73
+ if (existing && existing.v !== expectedVersion) {
74
+ throw new ConflictError(existing.v, `Version conflict: expected ${expectedVersion}, found ${existing.v}`);
75
+ }
76
+ }
77
+ await upsertStatement(vault, collection, id, envelope).run();
78
+ }
79
+ const store = {
80
+ name: "cloudflare-d1",
81
+ async get(vault, collection, id) {
82
+ await ensureSchema();
83
+ const row = await db.prepare(`SELECT * FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`).bind(vault, collection, id).first();
84
+ return row ? rowToEnvelope(row) : null;
85
+ },
86
+ async put(vault, collection, id, envelope, expectedVersion) {
87
+ await upsert(vault, collection, id, envelope, expectedVersion);
88
+ },
89
+ async delete(vault, collection, id) {
90
+ await ensureSchema();
91
+ await db.prepare(`DELETE FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`).bind(vault, collection, id).run();
92
+ },
93
+ async list(vault, collection) {
94
+ await ensureSchema();
95
+ const res = await db.prepare(`SELECT id FROM ${tableName} WHERE vault = ? AND collection = ? ORDER BY id`).bind(vault, collection).all();
96
+ return (res.results ?? []).map((r) => r.id);
97
+ },
98
+ async loadAll(vault) {
99
+ await ensureSchema();
100
+ const res = await db.prepare(`SELECT * FROM ${tableName} WHERE vault = ?`).bind(vault).all();
101
+ const snap = {};
102
+ for (const row of res.results ?? []) {
103
+ const collection = row.collection;
104
+ const id = row.id;
105
+ const bucket = snap[collection] ?? (snap[collection] = {});
106
+ bucket[id] = rowToEnvelope(row);
107
+ }
108
+ return snap;
109
+ },
110
+ async saveAll(vault, data) {
111
+ await ensureSchema();
112
+ const statements = [
113
+ db.prepare(`DELETE FROM ${tableName} WHERE vault = ?`).bind(vault)
114
+ ];
115
+ for (const [collection, recs] of Object.entries(data)) {
116
+ for (const [id, envelope] of Object.entries(recs)) {
117
+ statements.push(upsertStatement(vault, collection, id, envelope));
118
+ }
119
+ }
120
+ await db.batch(statements);
121
+ },
122
+ async ping() {
123
+ try {
124
+ await db.prepare("SELECT 1").run();
125
+ return true;
126
+ } catch {
127
+ return false;
128
+ }
129
+ },
130
+ async listPage(vault, collection, cursor, limit = 100) {
131
+ await ensureSchema();
132
+ const afterId = cursor ?? "";
133
+ const res = await db.prepare(
134
+ `SELECT id, v, ts, iv, data, by, tier, elevated_by, det FROM ${tableName}
135
+ WHERE vault = ? AND collection = ? AND id > ?
136
+ ORDER BY id LIMIT ?`
137
+ ).bind(vault, collection, afterId, limit + 1).all();
138
+ const rows = res.results ?? [];
139
+ const hasMore = rows.length > limit;
140
+ const trimmed = hasMore ? rows.slice(0, limit) : rows;
141
+ const items = trimmed.map((r) => ({ id: r.id, envelope: rowToEnvelope(r) }));
142
+ const out = {
143
+ items,
144
+ nextCursor: hasMore ? trimmed[trimmed.length - 1].id : null
145
+ };
146
+ return out;
147
+ },
148
+ async tx(ops) {
149
+ await ensureSchema();
150
+ const statements = [];
151
+ for (const op of ops) {
152
+ if (op.type === "put") {
153
+ if (!op.envelope) throw new Error(`tx put op missing envelope for ${op.id}`);
154
+ statements.push(upsertStatement(op.vault, op.collection, op.id, op.envelope));
155
+ } else {
156
+ statements.push(
157
+ db.prepare(`DELETE FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`).bind(op.vault, op.collection, op.id)
158
+ );
159
+ }
160
+ }
161
+ await db.batch(statements);
162
+ }
163
+ };
164
+ return store;
165
+ }
166
+ export {
167
+ d1
168
+ };
169
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/to-cloudflare-d1** — Cloudflare D1 adapter for noy-db.\n *\n * D1 is Cloudflare's edge SQLite. Inside a Worker, the `env.DB` binding\n * exposes a `D1Database` whose API is `prepare(sql).bind(...args).run()`\n * — different from node-postgres or libSQL but easy to adapt.\n *\n * ```ts\n * import { d1 } from '@noy-db/to-cloudflare-d1'\n *\n * export default {\n * async fetch(request: Request, env: { DB: D1Database }) {\n * const store = d1({ db: env.DB })\n * const db = await createNoydb({ store })\n * // …\n * },\n * }\n * ```\n *\n * ## Capabilities\n *\n * | Capability | Value |\n * |-------------|-------|\n * | `casAtomic` | `true` — `UPDATE … WHERE v = ?` inside a D1 batch |\n * | `txAtomic` | `true` — `D1Database.batch()` is atomic per-session |\n * | `listPage` | ✓ — keyset pagination by id |\n * | `ping` | ✓ — `SELECT 1` |\n *\n * @packageDocumentation\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot, TxOp, ListPageResult } from '@noy-db/hub'\nimport { ConflictError } from '@noy-db/hub'\n\n/** Duck-typed subset of the `D1Database` binding. */\nexport interface D1Database {\n prepare(sql: string): D1PreparedStatement\n batch<T = unknown>(statements: readonly D1PreparedStatement[]): Promise<D1Result<T>[]>\n exec?(sql: string): Promise<unknown>\n}\n\nexport interface D1PreparedStatement {\n bind(...args: readonly unknown[]): D1PreparedStatement\n first<T = unknown>(): Promise<T | null>\n all<T = unknown>(): Promise<D1Result<T>>\n run<T = unknown>(): Promise<D1Result<T>>\n}\n\nexport interface D1Result<T = unknown> {\n readonly results?: readonly T[]\n readonly success?: boolean\n}\n\nexport interface D1StoreOptions {\n readonly db: D1Database\n readonly tableName?: string\n readonly autoMigrate?: boolean\n}\n\nexport function d1(options: D1StoreOptions): NoydbStore {\n const { db, tableName = 'noydb_envelopes', autoMigrate = true } = options\n let schemaReady: Promise<void> | null = null\n\n async function ensureSchema(): Promise<void> {\n if (!autoMigrate) return\n if (!schemaReady) {\n schemaReady = (async () => {\n await db\n .prepare(\n `CREATE TABLE IF NOT EXISTS ${tableName} (\n vault TEXT NOT NULL,\n collection TEXT NOT NULL,\n id TEXT NOT NULL,\n v INTEGER NOT NULL,\n ts TEXT NOT NULL,\n iv TEXT NOT NULL,\n data TEXT NOT NULL,\n by TEXT,\n tier INTEGER,\n elevated_by TEXT,\n det TEXT,\n PRIMARY KEY (vault, collection, id)\n )`,\n )\n .run()\n await db\n .prepare(`CREATE INDEX IF NOT EXISTS idx_${tableName}_vc ON ${tableName} (vault, collection)`)\n .run()\n })()\n }\n await schemaReady\n }\n\n function rowToEnvelope(row: Record<string, unknown>): EncryptedEnvelope {\n const by = row.by as string | null\n const tier = row.tier as number | null\n const elevatedBy = row.elevated_by as string | null\n const detRaw = row.det as string | null\n return {\n _noydb: 1,\n _v: row.v as number,\n _ts: row.ts as string,\n _iv: row.iv as string,\n _data: row.data as string,\n ...(by !== null && { _by: by }),\n ...(tier !== null && { _tier: tier }),\n ...(elevatedBy !== null && { _elevatedBy: elevatedBy }),\n ...(detRaw !== null && { _det: JSON.parse(detRaw) as Record<string, string> }),\n }\n }\n\n function upsertStatement(\n vault: string,\n collection: string,\n id: string,\n envelope: EncryptedEnvelope,\n ): D1PreparedStatement {\n return db\n .prepare(\n `INSERT INTO ${tableName} (vault, collection, id, v, ts, iv, data, by, tier, elevated_by, det)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(vault, collection, id) DO UPDATE SET\n v = excluded.v, ts = excluded.ts, iv = excluded.iv, data = excluded.data,\n by = excluded.by, tier = excluded.tier, elevated_by = excluded.elevated_by, det = excluded.det`,\n )\n .bind(\n vault, collection, id,\n envelope._v, envelope._ts, envelope._iv, envelope._data,\n envelope._by ?? null,\n envelope._tier ?? null,\n envelope._elevatedBy ?? null,\n envelope._det ? JSON.stringify(envelope._det) : null,\n )\n }\n\n async function upsert(\n vault: string,\n collection: string,\n id: string,\n envelope: EncryptedEnvelope,\n expectedVersion?: number,\n ): Promise<void> {\n await ensureSchema()\n if (expectedVersion !== undefined) {\n const existing = await db\n .prepare(`SELECT v FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`)\n .bind(vault, collection, id)\n .first<{ v: number }>()\n if (existing && existing.v !== expectedVersion) {\n throw new ConflictError(existing.v, `Version conflict: expected ${expectedVersion}, found ${existing.v}`)\n }\n }\n await upsertStatement(vault, collection, id, envelope).run()\n }\n\n const store: NoydbStore = {\n name: 'cloudflare-d1',\n\n async get(vault, collection, id) {\n await ensureSchema()\n const row = await db\n .prepare(`SELECT * FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`)\n .bind(vault, collection, id)\n .first<Record<string, unknown>>()\n return row ? rowToEnvelope(row) : null\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n await upsert(vault, collection, id, envelope, expectedVersion)\n },\n\n async delete(vault, collection, id) {\n await ensureSchema()\n await db\n .prepare(`DELETE FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`)\n .bind(vault, collection, id)\n .run()\n },\n\n async list(vault, collection) {\n await ensureSchema()\n const res = await db\n .prepare(`SELECT id FROM ${tableName} WHERE vault = ? AND collection = ? ORDER BY id`)\n .bind(vault, collection)\n .all<{ id: string }>()\n return (res.results ?? []).map(r => r.id)\n },\n\n async loadAll(vault) {\n await ensureSchema()\n const res = await db\n .prepare(`SELECT * FROM ${tableName} WHERE vault = ?`)\n .bind(vault)\n .all<Record<string, unknown>>()\n const snap: VaultSnapshot = {}\n for (const row of res.results ?? []) {\n const collection = row.collection as string\n const id = row.id as string\n const bucket = snap[collection] ?? (snap[collection] = {})\n bucket[id] = rowToEnvelope(row)\n }\n return snap\n },\n\n async saveAll(vault, data) {\n await ensureSchema()\n const statements: D1PreparedStatement[] = [\n db.prepare(`DELETE FROM ${tableName} WHERE vault = ?`).bind(vault),\n ]\n for (const [collection, recs] of Object.entries(data)) {\n for (const [id, envelope] of Object.entries(recs)) {\n statements.push(upsertStatement(vault, collection, id, envelope))\n }\n }\n await db.batch(statements)\n },\n\n async ping() {\n try {\n await db.prepare('SELECT 1').run()\n return true\n } catch {\n return false\n }\n },\n\n async listPage(vault, collection, cursor, limit = 100) {\n await ensureSchema()\n const afterId = cursor ?? ''\n const res = await db\n .prepare(\n `SELECT id, v, ts, iv, data, by, tier, elevated_by, det FROM ${tableName}\n WHERE vault = ? AND collection = ? AND id > ?\n ORDER BY id LIMIT ?`,\n )\n .bind(vault, collection, afterId, limit + 1)\n .all<Record<string, unknown>>()\n const rows = res.results ?? []\n const hasMore = rows.length > limit\n const trimmed = hasMore ? rows.slice(0, limit) : rows\n const items = trimmed.map(r => ({ id: r.id as string, envelope: rowToEnvelope(r) }))\n const out: ListPageResult = {\n items,\n nextCursor: hasMore ? (trimmed[trimmed.length - 1]!.id as string) : null,\n }\n return out\n },\n\n async tx(ops: readonly TxOp[]) {\n await ensureSchema()\n const statements: D1PreparedStatement[] = []\n for (const op of ops) {\n if (op.type === 'put') {\n if (!op.envelope) throw new Error(`tx put op missing envelope for ${op.id}`)\n statements.push(upsertStatement(op.vault, op.collection, op.id, op.envelope))\n } else {\n statements.push(\n db\n .prepare(`DELETE FROM ${tableName} WHERE vault = ? AND collection = ? AND id = ?`)\n .bind(op.vault, op.collection, op.id),\n )\n }\n }\n await db.batch(statements)\n },\n }\n\n return store\n}\n"],"mappings":";AAgCA,SAAS,qBAAqB;AA2BvB,SAAS,GAAG,SAAqC;AACtD,QAAM,EAAE,IAAI,YAAY,mBAAmB,cAAc,KAAK,IAAI;AAClE,MAAI,cAAoC;AAExC,iBAAe,eAA8B;AAC3C,QAAI,CAAC,YAAa;AAClB,QAAI,CAAC,aAAa;AAChB,qBAAe,YAAY;AACzB,cAAM,GACH;AAAA,UACC,8BAA8B,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAczC,EACC,IAAI;AACP,cAAM,GACH,QAAQ,kCAAkC,SAAS,UAAU,SAAS,sBAAsB,EAC5F,IAAI;AAAA,MACT,GAAG;AAAA,IACL;AACA,UAAM;AAAA,EACR;AAEA,WAAS,cAAc,KAAiD;AACtE,UAAM,KAAK,IAAI;AACf,UAAM,OAAO,IAAI;AACjB,UAAM,aAAa,IAAI;AACvB,UAAM,SAAS,IAAI;AACnB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,IAAI,IAAI;AAAA,MACR,KAAK,IAAI;AAAA,MACT,KAAK,IAAI;AAAA,MACT,OAAO,IAAI;AAAA,MACX,GAAI,OAAO,QAAQ,EAAE,KAAK,GAAG;AAAA,MAC7B,GAAI,SAAS,QAAQ,EAAE,OAAO,KAAK;AAAA,MACnC,GAAI,eAAe,QAAQ,EAAE,aAAa,WAAW;AAAA,MACrD,GAAI,WAAW,QAAQ,EAAE,MAAM,KAAK,MAAM,MAAM,EAA4B;AAAA,IAC9E;AAAA,EACF;AAEA,WAAS,gBACP,OACA,YACA,IACA,UACqB;AACrB,WAAO,GACJ;AAAA,MACC,eAAe,SAAS;AAAA;AAAA;AA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C1B,YAAM,MAAM,MAAM,GACf;AAAA,QACC,+DAA+D,SAAS;AAAA;AAAA;AAAA,MAG1E,EACC,KAAK,OAAO,YAAY,SAAS,QAAQ,CAAC,EAC1C,IAA6B;AAChC,YAAM,OAAO,IAAI,WAAW,CAAC;AAC7B,YAAM,UAAU,KAAK,SAAS;AAC9B,YAAM,UAAU,UAAU,KAAK,MAAM,GAAG,KAAK,IAAI;AACjD,YAAM,QAAQ,QAAQ,IAAI,QAAM,EAAE,IAAI,EAAE,IAAc,UAAU,cAAc,CAAC,EAAE,EAAE;AACnF,YAAM,MAAsB;AAAA,QAC1B;AAAA,QACA,YAAY,UAAW,QAAQ,QAAQ,SAAS,CAAC,EAAG,KAAgB;AAAA,MACtE;AACA,aAAO;AAAA,IACT;AAAA,IAEA,MAAM,GAAG,KAAsB;AAC7B,YAAM,aAAa;AACnB,YAAM,aAAoC,CAAC;AAC3C,iBAAW,MAAM,KAAK;AACpB,YAAI,GAAG,SAAS,OAAO;AACrB,cAAI,CAAC,GAAG,SAAU,OAAM,IAAI,MAAM,kCAAkC,GAAG,EAAE,EAAE;AAC3E,qBAAW,KAAK,gBAAgB,GAAG,OAAO,GAAG,YAAY,GAAG,IAAI,GAAG,QAAQ,CAAC;AAAA,QAC9E,OAAO;AACL,qBAAW;AAAA,YACT,GACG,QAAQ,eAAe,SAAS,gDAAgD,EAChF,KAAK,GAAG,OAAO,GAAG,YAAY,GAAG,EAAE;AAAA,UACxC;AAAA,QACF;AAAA,MACF;AACA,YAAM,GAAG,MAAM,UAAU;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@noy-db/to-cloudflare-d1",
3
+ "version": "0.1.0-pre.3",
4
+ "description": "Cloudflare D1 adapter for noy-db — SQLite at the edge, running inside Cloudflare Workers. Accepts a D1Database binding and speaks the noy-db store contract via D1's prepare/bind API.",
5
+ "license": "MIT",
6
+ "author": "vLannaAi <vicio@lanna.ai>",
7
+ "homepage": "https://github.com/vLannaAi/noy-db/tree/main/packages/to-cloudflare-d1#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/vLannaAi/noy-db.git",
11
+ "directory": "packages/to-cloudflare-d1"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/vLannaAi/noy-db/issues"
15
+ },
16
+ "type": "module",
17
+ "sideEffects": false,
18
+ "exports": {
19
+ ".": {
20
+ "import": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "require": {
25
+ "types": "./dist/index.d.cts",
26
+ "default": "./dist/index.cjs"
27
+ }
28
+ }
29
+ },
30
+ "main": "./dist/index.cjs",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "files": [
34
+ "dist",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "engines": {
39
+ "node": ">=18.0.0"
40
+ },
41
+ "peerDependencies": {
42
+ "@noy-db/hub": "0.1.0-pre.3"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^22.0.0",
46
+ "@noy-db/hub": "0.1.0-pre.3"
47
+ },
48
+ "keywords": [
49
+ "noy-db",
50
+ "to-cloudflare-d1",
51
+ "cloudflare",
52
+ "d1",
53
+ "sqlite",
54
+ "edge",
55
+ "workers"
56
+ ],
57
+ "publishConfig": {
58
+ "access": "public",
59
+ "tag": "latest"
60
+ },
61
+ "scripts": {
62
+ "build": "tsup",
63
+ "test": "vitest run",
64
+ "lint": "eslint src/",
65
+ "typecheck": "tsc --noEmit"
66
+ }
67
+ }