@archildata/sqlite 0.0.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 Archil, Inc.
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,48 @@
1
+ # @archildata/sqlite
2
+
3
+ Run SQLite statements against an Archil disk through serverless execution.
4
+
5
+ ```ts
6
+ import { createDatabase, getDatabase } from "@archildata/sqlite";
7
+
8
+ const db = await createDatabase(disk, "apps/app-1/main.sqlite");
9
+
10
+ const userName = "archil";
11
+
12
+ const user = await db.write<{ id: number; name: string }>`
13
+ INSERT INTO users(name) VALUES (${userName})
14
+ RETURNING id, name
15
+ `.get();
16
+
17
+ const users = await db.read`SELECT * FROM users WHERE name = ${userName}`.all();
18
+
19
+ const update = await db.write`
20
+ UPDATE users SET last_seen_at = ${new Date().toISOString()} WHERE name = ${userName}
21
+ `.run();
22
+
23
+ await db.transaction([
24
+ db.write`INSERT INTO audit_log(user_name, action) VALUES (${userName}, ${"login"})`.run(),
25
+ db.read`SELECT * FROM users WHERE name = ${userName}`.get(),
26
+ ]);
27
+
28
+ const existing = await getDatabase(disk, "apps/app-1/main.sqlite");
29
+ ```
30
+
31
+ Each database is addressed by its file path on the Archil disk. `createDatabase`
32
+ creates the parent directory and initializes the file with a queued writable
33
+ root mount. `getDatabase` assumes that the
34
+ database file already exists; missing databases surface as query-time errors.
35
+
36
+ `read` and `write` create query objects. Use `get()` for one row, `all()` for all
37
+ rows, and `run()` for SQLite's write result (`changes` and `lastInsertRowid`).
38
+ The `read` or `write` tag controls the remote mount mode, so use `write` for
39
+ mutating statements, including statements with `RETURNING`.
40
+
41
+ `transaction([...])` runs query executions from `get()`, `all()`, and `run()` in
42
+ a single remote SQLite transaction. If every execution came from `read`, the
43
+ database is opened read-only; otherwise it is opened read-write.
44
+
45
+ The package always uses `disk`'s top-level multi-disk `exec({ disks, command })`
46
+ for remote execution, mounting the whole disk at `/mnt/archil/disk`. Writable
47
+ query executions request a short mount queue; nested database paths checkout the
48
+ database's parent directory so SQLite can safely create journal/WAL sidecars.
package/dist/index.cjs ADDED
@@ -0,0 +1,457 @@
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
+ ArchilSQLiteError: () => ArchilSQLiteError,
24
+ createDatabase: () => createDatabase,
25
+ getDatabase: () => getDatabase
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+ var import_disk = require("disk");
29
+
30
+ // src/adapter.ts
31
+ var import_node_buffer = require("buffer");
32
+ var DEFAULT_TIMEOUT_MS = 5e3;
33
+ var WRITE_MOUNT_QUEUE_MS = 5e3;
34
+ var RESULT_PREFIX = "ARCHIL_SQLITE_RESULT:";
35
+ var DISK_EXEC_MOUNT_PATH = "/mnt/archil/disk";
36
+ var REMOTE_RUNNER = `
37
+ const { Buffer } = require("node:buffer");
38
+ const { DatabaseSync } = require("node:sqlite");
39
+ const fs = require("node:fs");
40
+
41
+ const RESULT_PREFIX = ${JSON.stringify(RESULT_PREFIX)};
42
+
43
+ function emit(payload) {
44
+ const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
45
+ console.log(RESULT_PREFIX + encoded);
46
+ }
47
+
48
+ function decodeValue(value) {
49
+ switch (value.type) {
50
+ case "null":
51
+ return null;
52
+ case "number":
53
+ case "string":
54
+ return value.value;
55
+ case "bigint":
56
+ return BigInt(value.value);
57
+ case "bytes":
58
+ return Buffer.from(value.value, "base64");
59
+ default:
60
+ throw new TypeError("unsupported SQLite parameter type: " + value.type);
61
+ }
62
+ }
63
+
64
+ function encodeValue(value) {
65
+ if (value === undefined) return { type: "undefined" };
66
+ if (value === null) return { type: "null" };
67
+ if (typeof value === "number") return { type: "number", value };
68
+ if (typeof value === "string") return { type: "string", value };
69
+ if (typeof value === "bigint") return { type: "bigint", value: value.toString() };
70
+ if (value instanceof Uint8Array) {
71
+ return { type: "bytes", value: Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString("base64") };
72
+ }
73
+ if (Array.isArray(value)) return { type: "array", value: value.map(encodeValue) };
74
+ if (typeof value === "object") {
75
+ return {
76
+ type: "object",
77
+ value: Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, encodeValue(entry)])),
78
+ };
79
+ }
80
+ throw new TypeError("unsupported SQLite result type: " + typeof value);
81
+ }
82
+
83
+ function executeOperation(db, operation) {
84
+ const statement = db.prepare(operation.sql);
85
+ const params = operation.params.map(decodeValue);
86
+ switch (operation.method) {
87
+ case "get":
88
+ return statement.get(...params);
89
+ case "all":
90
+ return statement.all(...params);
91
+ case "run":
92
+ return statement.run(...params);
93
+ }
94
+ }
95
+
96
+ function run(payload) {
97
+ if (!fs.existsSync(payload.databasePath)) {
98
+ const err = new Error("SQLite database does not exist at " + payload.displayPath);
99
+ err.code = "SQLITE_DATABASE_NOT_FOUND";
100
+ throw err;
101
+ }
102
+
103
+ const db = new DatabaseSync(payload.databasePath, {
104
+ readOnly: payload.readOnly,
105
+ timeout: payload.timeoutMs,
106
+ readBigInts: payload.readBigInts,
107
+ returnArrays: payload.returnArrays,
108
+ });
109
+
110
+ try {
111
+ if (!payload.transaction) {
112
+ return executeOperation(db, payload.operations[0]);
113
+ }
114
+
115
+ db.exec(payload.readOnly ? "BEGIN" : "BEGIN IMMEDIATE");
116
+ try {
117
+ const results = payload.operations.map((operation) => executeOperation(db, operation));
118
+ db.exec("COMMIT");
119
+ return results;
120
+ } catch (err) {
121
+ try {
122
+ db.exec("ROLLBACK");
123
+ } catch {}
124
+ throw err;
125
+ }
126
+ } finally {
127
+ db.close();
128
+ }
129
+ }
130
+
131
+ try {
132
+ const payload = JSON.parse(Buffer.from(process.argv[1], "base64").toString("utf8"));
133
+ emit({ ok: true, result: encodeValue(run(payload)) });
134
+ } catch (err) {
135
+ emit({
136
+ ok: false,
137
+ error: {
138
+ name: err && err.name,
139
+ message: err && err.message,
140
+ stack: err && err.stack,
141
+ code: err && err.code,
142
+ },
143
+ });
144
+ }
145
+ `;
146
+ var ArchilSQLiteError = class extends Error {
147
+ code;
148
+ remoteStack;
149
+ constructor(message, opts = {}) {
150
+ super(message);
151
+ this.name = "ArchilSQLiteError";
152
+ this.code = opts.code;
153
+ this.remoteStack = opts.remoteStack;
154
+ }
155
+ };
156
+ var operationStates = /* @__PURE__ */ new WeakMap();
157
+ function deferredPromise() {
158
+ let resolve;
159
+ let reject;
160
+ const promise = new Promise((promiseResolve, promiseReject) => {
161
+ resolve = promiseResolve;
162
+ reject = promiseReject;
163
+ });
164
+ promise.catch(() => {
165
+ });
166
+ return { promise, resolve, reject };
167
+ }
168
+ var SQLiteOperationImpl = class {
169
+ constructor(executeRequest, request) {
170
+ this.executeRequest = executeRequest;
171
+ operationStates.set(this, {
172
+ executeRequest,
173
+ request
174
+ });
175
+ }
176
+ executeRequest;
177
+ execute() {
178
+ const state = operationStates.get(this);
179
+ if (!state) {
180
+ throw new TypeError("unknown SQLite operation");
181
+ }
182
+ state.promise ??= this.executeRequest(state.request);
183
+ return state.promise;
184
+ }
185
+ then(onfulfilled, onrejected) {
186
+ return this.execute().then(onfulfilled, onrejected);
187
+ }
188
+ };
189
+ var SQLiteQueryImpl = class {
190
+ constructor(executeRequest, request) {
191
+ this.executeRequest = executeRequest;
192
+ this.request = request;
193
+ }
194
+ executeRequest;
195
+ request;
196
+ get() {
197
+ return new SQLiteOperationImpl(this.executeRequest, {
198
+ ...this.request,
199
+ method: "get"
200
+ });
201
+ }
202
+ all() {
203
+ return new SQLiteOperationImpl(this.executeRequest, {
204
+ ...this.request,
205
+ method: "all"
206
+ });
207
+ }
208
+ run() {
209
+ return new SQLiteOperationImpl(this.executeRequest, {
210
+ ...this.request,
211
+ method: "run"
212
+ });
213
+ }
214
+ };
215
+ var SQLiteAdapter = class {
216
+ constructor(exec, disk, database, options = {}) {
217
+ this.exec = exec;
218
+ this.disk = disk;
219
+ this.database = database;
220
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
221
+ this.readBigInts = options.readBigInts ?? false;
222
+ this.returnArrays = options.returnArrays ?? false;
223
+ }
224
+ exec;
225
+ disk;
226
+ database;
227
+ timeoutMs;
228
+ readBigInts;
229
+ returnArrays;
230
+ read(strings, ...values) {
231
+ return new SQLiteQueryImpl((request) => this.executeSingle(request), {
232
+ kind: "read",
233
+ sql: templateToSql(strings),
234
+ params: values.map(encodeParameter)
235
+ });
236
+ }
237
+ write(strings, ...values) {
238
+ return new SQLiteQueryImpl((request) => this.executeSingle(request), {
239
+ kind: "write",
240
+ sql: templateToSql(strings),
241
+ params: values.map(encodeParameter)
242
+ });
243
+ }
244
+ async transaction(operations) {
245
+ const states = operations.map((operation) => {
246
+ const state = operationStates.get(operation);
247
+ if (!state) {
248
+ throw new TypeError("unknown SQLite operation");
249
+ }
250
+ return state;
251
+ });
252
+ const seen = /* @__PURE__ */ new Set();
253
+ for (const state of states) {
254
+ if (state.promise) {
255
+ throw new TypeError("SQLite operation has already started");
256
+ }
257
+ if (seen.has(state)) {
258
+ throw new TypeError("SQLite operation cannot be used more than once in a transaction");
259
+ }
260
+ seen.add(state);
261
+ }
262
+ const requests = states.map((state) => state.request);
263
+ const readOnly = requests.every((request) => request.kind === "read");
264
+ const deferreds = states.map(() => deferredPromise());
265
+ states.forEach((state, index) => {
266
+ state.promise = deferreds[index].promise;
267
+ });
268
+ try {
269
+ const results = await this.executeRemote(requests, { transaction: true, readOnly });
270
+ results.forEach((result, index) => {
271
+ deferreds[index].resolve(result);
272
+ });
273
+ return results;
274
+ } catch (err) {
275
+ deferreds.forEach((deferred) => {
276
+ deferred.reject(err);
277
+ });
278
+ throw err;
279
+ }
280
+ }
281
+ executeSingle(request) {
282
+ return this.executeRemote([request], {
283
+ transaction: false,
284
+ readOnly: request.kind === "read"
285
+ }).then((results) => results[0]);
286
+ }
287
+ async executeRemote(operations, opts) {
288
+ const payload = {
289
+ databasePath: `${DISK_EXEC_MOUNT_PATH}/${this.database.path}`,
290
+ displayPath: this.database.path,
291
+ timeoutMs: this.timeoutMs,
292
+ readBigInts: this.readBigInts,
293
+ returnArrays: this.returnArrays,
294
+ readOnly: opts.readOnly,
295
+ transaction: opts.transaction,
296
+ operations
297
+ };
298
+ const checkoutPaths = opts.readOnly || !this.database.directory ? void 0 : [this.database.directory];
299
+ const queueMs = opts.readOnly ? void 0 : WRITE_MOUNT_QUEUE_MS;
300
+ const mount = {
301
+ disk: this.disk.id,
302
+ readOnly: opts.readOnly,
303
+ checkoutPaths,
304
+ queueMs
305
+ };
306
+ const command = buildCommand(payload);
307
+ const result = await this.exec({
308
+ command,
309
+ disks: { disk: mount }
310
+ });
311
+ const decoded = parseExecResult(result);
312
+ return opts.transaction ? decoded : [decoded];
313
+ }
314
+ };
315
+ function createSQLiteAdapter(exec) {
316
+ return {
317
+ async createDatabase(disk, databasePath, options = {}) {
318
+ const database = normalizeDatabasePath(databasePath);
319
+ const rootDirectory = database.directory ? `${DISK_EXEC_MOUNT_PATH}/${database.directory}` : DISK_EXEC_MOUNT_PATH;
320
+ const mountedDatabasePath = `${rootDirectory}/${database.filename}`;
321
+ const command = `mkdir -p ${shellQuote(rootDirectory)} && node --no-warnings -e ${shellQuote(CREATE_DATABASE_RUNNER)} ${shellQuote(mountedDatabasePath)}`;
322
+ const result = await exec({
323
+ command,
324
+ disks: {
325
+ disk: {
326
+ disk: disk.id,
327
+ readOnly: false,
328
+ queueMs: WRITE_MOUNT_QUEUE_MS
329
+ }
330
+ }
331
+ });
332
+ if (result.exitCode !== 0) {
333
+ throw new ArchilSQLiteError(
334
+ `SQLite database creation failed with exit code ${result.exitCode}: ${result.stderr || result.stdout}`
335
+ );
336
+ }
337
+ return new SQLiteAdapter(exec, disk, database, options);
338
+ },
339
+ async getDatabase(disk, databasePath, options = {}) {
340
+ const database = normalizeDatabasePath(databasePath);
341
+ return new SQLiteAdapter(exec, disk, database, options);
342
+ }
343
+ };
344
+ }
345
+ function templateToSql(strings) {
346
+ let sql = strings[0] ?? "";
347
+ for (let i = 1; i < strings.length; i++) {
348
+ sql += "?" + strings[i];
349
+ }
350
+ return sql;
351
+ }
352
+ function normalizeDatabasePath(path) {
353
+ if (path.endsWith("/")) {
354
+ throw new TypeError("database path must include a file name and not end with '/'");
355
+ }
356
+ const segments = path.split("/").filter((segment) => segment.length > 0 && segment !== ".");
357
+ if (segments.length === 0 || segments.some((segment) => segment === "..")) {
358
+ throw new TypeError("database path must be a non-empty relative file path without '..'");
359
+ }
360
+ const filename = segments[segments.length - 1];
361
+ const directorySegments = segments.slice(0, -1);
362
+ return {
363
+ path: segments.join("/"),
364
+ directory: directorySegments.length > 0 ? directorySegments.join("/") : void 0,
365
+ filename
366
+ };
367
+ }
368
+ var CREATE_DATABASE_RUNNER = `
369
+ const { DatabaseSync } = require("node:sqlite");
370
+ const db = new DatabaseSync(process.argv[1]);
371
+ db.close();
372
+ `;
373
+ function encodeParameter(value) {
374
+ if (value === null) return { type: "null" };
375
+ if (typeof value === "number") return { type: "number", value };
376
+ if (typeof value === "string") return { type: "string", value };
377
+ if (typeof value === "bigint") return { type: "bigint", value: value.toString() };
378
+ if (value instanceof Uint8Array) {
379
+ return {
380
+ type: "bytes",
381
+ value: import_node_buffer.Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString("base64")
382
+ };
383
+ }
384
+ if (value instanceof ArrayBuffer) {
385
+ return { type: "bytes", value: import_node_buffer.Buffer.from(value).toString("base64") };
386
+ }
387
+ throw new TypeError(`unsupported SQLite parameter type: ${typeof value}`);
388
+ }
389
+ function decodeWireValue(value) {
390
+ switch (value.type) {
391
+ case "undefined":
392
+ return void 0;
393
+ case "null":
394
+ return null;
395
+ case "number":
396
+ case "string":
397
+ return value.value;
398
+ case "bigint":
399
+ return BigInt(value.value);
400
+ case "bytes":
401
+ return Uint8Array.from(import_node_buffer.Buffer.from(value.value, "base64"));
402
+ case "array":
403
+ return value.value.map(decodeWireValue);
404
+ case "object":
405
+ return Object.fromEntries(
406
+ Object.entries(value.value).map(([key, entry]) => [key, decodeWireValue(entry)])
407
+ );
408
+ }
409
+ }
410
+ function buildCommand(payload) {
411
+ const encodedPayload = import_node_buffer.Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
412
+ return `node --no-warnings -e ${shellQuote(REMOTE_RUNNER)} ${shellQuote(encodedPayload)}`;
413
+ }
414
+ function shellQuote(value) {
415
+ return `'${value.replace(/'/g, "'\\''")}'`;
416
+ }
417
+ function parseExecResult(result) {
418
+ if (result.exitCode !== 0) {
419
+ throw new ArchilSQLiteError(
420
+ `SQLite serverless execution failed with exit code ${result.exitCode}: ${result.stderr || result.stdout}`
421
+ );
422
+ }
423
+ const line = result.stdout.split(/\r?\n/).reverse().find((entry) => entry.startsWith(RESULT_PREFIX));
424
+ if (!line) {
425
+ throw new ArchilSQLiteError("SQLite serverless execution did not return a result payload");
426
+ }
427
+ let parsed;
428
+ try {
429
+ parsed = JSON.parse(
430
+ import_node_buffer.Buffer.from(line.slice(RESULT_PREFIX.length), "base64").toString("utf8")
431
+ );
432
+ } catch (err) {
433
+ throw new ArchilSQLiteError(`SQLite serverless execution returned invalid JSON: ${err}`);
434
+ }
435
+ if (!parsed.ok) {
436
+ throw new ArchilSQLiteError(parsed.error.message ?? "SQLite serverless execution failed", {
437
+ code: parsed.error.code,
438
+ remoteStack: parsed.error.stack
439
+ });
440
+ }
441
+ return decodeWireValue(parsed.result);
442
+ }
443
+
444
+ // src/index.ts
445
+ var sqlite = createSQLiteAdapter((opts) => (0, import_disk.exec)(opts));
446
+ function createDatabase(disk, databasePath, options) {
447
+ return sqlite.createDatabase(disk, databasePath, options);
448
+ }
449
+ function getDatabase(disk, databasePath, options) {
450
+ return sqlite.getDatabase(disk, databasePath, options);
451
+ }
452
+ // Annotate the CommonJS export names for ESM import in node:
453
+ 0 && (module.exports = {
454
+ ArchilSQLiteError,
455
+ createDatabase,
456
+ getDatabase
457
+ });
@@ -0,0 +1,44 @@
1
+ interface SQLiteDisk {
2
+ id: string;
3
+ }
4
+ interface SQLiteDatabaseOptions {
5
+ timeoutMs?: number;
6
+ readBigInts?: boolean;
7
+ returnArrays?: boolean;
8
+ }
9
+ type SQLiteValue = null | number | bigint | string | Uint8Array | ArrayBuffer;
10
+ type SQLiteRow = Record<string, SQLiteValue>;
11
+ interface SQLiteWriteResult {
12
+ changes: number | bigint;
13
+ lastInsertRowid: number | bigint;
14
+ }
15
+ declare class ArchilSQLiteError extends Error {
16
+ readonly code?: string | number;
17
+ readonly remoteStack?: string;
18
+ constructor(message: string, opts?: {
19
+ code?: string | number;
20
+ remoteStack?: string;
21
+ });
22
+ }
23
+ interface SQLiteOperation<Result> extends PromiseLike<Result> {
24
+ execute(): Promise<Result>;
25
+ }
26
+ interface SQLiteQuery<Row = SQLiteRow> {
27
+ get(): SQLiteOperation<Row | undefined>;
28
+ all(): SQLiteOperation<Row[]>;
29
+ run(): SQLiteOperation<SQLiteWriteResult>;
30
+ }
31
+ type SQLiteOperationResult<Operation> = Operation extends SQLiteOperation<infer Result> ? Result : never;
32
+ type SQLiteTransactionResult<Operations extends readonly SQLiteOperation<unknown>[]> = {
33
+ -readonly [Index in keyof Operations]: SQLiteOperationResult<Operations[Index]>;
34
+ };
35
+ interface SQLiteDatabase {
36
+ read<Row = SQLiteRow>(strings: TemplateStringsArray, ...values: SQLiteValue[]): SQLiteQuery<Row>;
37
+ write<Row = SQLiteRow>(strings: TemplateStringsArray, ...values: SQLiteValue[]): SQLiteQuery<Row>;
38
+ transaction<const Operations extends readonly SQLiteOperation<unknown>[]>(operations: Operations): Promise<SQLiteTransactionResult<Operations>>;
39
+ }
40
+
41
+ declare function createDatabase(disk: SQLiteDisk, databasePath: string, options?: SQLiteDatabaseOptions): Promise<SQLiteDatabase>;
42
+ declare function getDatabase(disk: SQLiteDisk, databasePath: string, options?: SQLiteDatabaseOptions): Promise<SQLiteDatabase>;
43
+
44
+ export { ArchilSQLiteError, type SQLiteDatabase, type SQLiteDatabaseOptions, type SQLiteDisk, type SQLiteOperation, type SQLiteQuery, type SQLiteRow, type SQLiteTransactionResult, type SQLiteValue, type SQLiteWriteResult, createDatabase, getDatabase };
@@ -0,0 +1,44 @@
1
+ interface SQLiteDisk {
2
+ id: string;
3
+ }
4
+ interface SQLiteDatabaseOptions {
5
+ timeoutMs?: number;
6
+ readBigInts?: boolean;
7
+ returnArrays?: boolean;
8
+ }
9
+ type SQLiteValue = null | number | bigint | string | Uint8Array | ArrayBuffer;
10
+ type SQLiteRow = Record<string, SQLiteValue>;
11
+ interface SQLiteWriteResult {
12
+ changes: number | bigint;
13
+ lastInsertRowid: number | bigint;
14
+ }
15
+ declare class ArchilSQLiteError extends Error {
16
+ readonly code?: string | number;
17
+ readonly remoteStack?: string;
18
+ constructor(message: string, opts?: {
19
+ code?: string | number;
20
+ remoteStack?: string;
21
+ });
22
+ }
23
+ interface SQLiteOperation<Result> extends PromiseLike<Result> {
24
+ execute(): Promise<Result>;
25
+ }
26
+ interface SQLiteQuery<Row = SQLiteRow> {
27
+ get(): SQLiteOperation<Row | undefined>;
28
+ all(): SQLiteOperation<Row[]>;
29
+ run(): SQLiteOperation<SQLiteWriteResult>;
30
+ }
31
+ type SQLiteOperationResult<Operation> = Operation extends SQLiteOperation<infer Result> ? Result : never;
32
+ type SQLiteTransactionResult<Operations extends readonly SQLiteOperation<unknown>[]> = {
33
+ -readonly [Index in keyof Operations]: SQLiteOperationResult<Operations[Index]>;
34
+ };
35
+ interface SQLiteDatabase {
36
+ read<Row = SQLiteRow>(strings: TemplateStringsArray, ...values: SQLiteValue[]): SQLiteQuery<Row>;
37
+ write<Row = SQLiteRow>(strings: TemplateStringsArray, ...values: SQLiteValue[]): SQLiteQuery<Row>;
38
+ transaction<const Operations extends readonly SQLiteOperation<unknown>[]>(operations: Operations): Promise<SQLiteTransactionResult<Operations>>;
39
+ }
40
+
41
+ declare function createDatabase(disk: SQLiteDisk, databasePath: string, options?: SQLiteDatabaseOptions): Promise<SQLiteDatabase>;
42
+ declare function getDatabase(disk: SQLiteDisk, databasePath: string, options?: SQLiteDatabaseOptions): Promise<SQLiteDatabase>;
43
+
44
+ export { ArchilSQLiteError, type SQLiteDatabase, type SQLiteDatabaseOptions, type SQLiteDisk, type SQLiteOperation, type SQLiteQuery, type SQLiteRow, type SQLiteTransactionResult, type SQLiteValue, type SQLiteWriteResult, createDatabase, getDatabase };
package/dist/index.js ADDED
@@ -0,0 +1,430 @@
1
+ // src/index.ts
2
+ import { exec as archilExec } from "disk";
3
+
4
+ // src/adapter.ts
5
+ import { Buffer } from "buffer";
6
+ var DEFAULT_TIMEOUT_MS = 5e3;
7
+ var WRITE_MOUNT_QUEUE_MS = 5e3;
8
+ var RESULT_PREFIX = "ARCHIL_SQLITE_RESULT:";
9
+ var DISK_EXEC_MOUNT_PATH = "/mnt/archil/disk";
10
+ var REMOTE_RUNNER = `
11
+ const { Buffer } = require("node:buffer");
12
+ const { DatabaseSync } = require("node:sqlite");
13
+ const fs = require("node:fs");
14
+
15
+ const RESULT_PREFIX = ${JSON.stringify(RESULT_PREFIX)};
16
+
17
+ function emit(payload) {
18
+ const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
19
+ console.log(RESULT_PREFIX + encoded);
20
+ }
21
+
22
+ function decodeValue(value) {
23
+ switch (value.type) {
24
+ case "null":
25
+ return null;
26
+ case "number":
27
+ case "string":
28
+ return value.value;
29
+ case "bigint":
30
+ return BigInt(value.value);
31
+ case "bytes":
32
+ return Buffer.from(value.value, "base64");
33
+ default:
34
+ throw new TypeError("unsupported SQLite parameter type: " + value.type);
35
+ }
36
+ }
37
+
38
+ function encodeValue(value) {
39
+ if (value === undefined) return { type: "undefined" };
40
+ if (value === null) return { type: "null" };
41
+ if (typeof value === "number") return { type: "number", value };
42
+ if (typeof value === "string") return { type: "string", value };
43
+ if (typeof value === "bigint") return { type: "bigint", value: value.toString() };
44
+ if (value instanceof Uint8Array) {
45
+ return { type: "bytes", value: Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString("base64") };
46
+ }
47
+ if (Array.isArray(value)) return { type: "array", value: value.map(encodeValue) };
48
+ if (typeof value === "object") {
49
+ return {
50
+ type: "object",
51
+ value: Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, encodeValue(entry)])),
52
+ };
53
+ }
54
+ throw new TypeError("unsupported SQLite result type: " + typeof value);
55
+ }
56
+
57
+ function executeOperation(db, operation) {
58
+ const statement = db.prepare(operation.sql);
59
+ const params = operation.params.map(decodeValue);
60
+ switch (operation.method) {
61
+ case "get":
62
+ return statement.get(...params);
63
+ case "all":
64
+ return statement.all(...params);
65
+ case "run":
66
+ return statement.run(...params);
67
+ }
68
+ }
69
+
70
+ function run(payload) {
71
+ if (!fs.existsSync(payload.databasePath)) {
72
+ const err = new Error("SQLite database does not exist at " + payload.displayPath);
73
+ err.code = "SQLITE_DATABASE_NOT_FOUND";
74
+ throw err;
75
+ }
76
+
77
+ const db = new DatabaseSync(payload.databasePath, {
78
+ readOnly: payload.readOnly,
79
+ timeout: payload.timeoutMs,
80
+ readBigInts: payload.readBigInts,
81
+ returnArrays: payload.returnArrays,
82
+ });
83
+
84
+ try {
85
+ if (!payload.transaction) {
86
+ return executeOperation(db, payload.operations[0]);
87
+ }
88
+
89
+ db.exec(payload.readOnly ? "BEGIN" : "BEGIN IMMEDIATE");
90
+ try {
91
+ const results = payload.operations.map((operation) => executeOperation(db, operation));
92
+ db.exec("COMMIT");
93
+ return results;
94
+ } catch (err) {
95
+ try {
96
+ db.exec("ROLLBACK");
97
+ } catch {}
98
+ throw err;
99
+ }
100
+ } finally {
101
+ db.close();
102
+ }
103
+ }
104
+
105
+ try {
106
+ const payload = JSON.parse(Buffer.from(process.argv[1], "base64").toString("utf8"));
107
+ emit({ ok: true, result: encodeValue(run(payload)) });
108
+ } catch (err) {
109
+ emit({
110
+ ok: false,
111
+ error: {
112
+ name: err && err.name,
113
+ message: err && err.message,
114
+ stack: err && err.stack,
115
+ code: err && err.code,
116
+ },
117
+ });
118
+ }
119
+ `;
120
+ var ArchilSQLiteError = class extends Error {
121
+ code;
122
+ remoteStack;
123
+ constructor(message, opts = {}) {
124
+ super(message);
125
+ this.name = "ArchilSQLiteError";
126
+ this.code = opts.code;
127
+ this.remoteStack = opts.remoteStack;
128
+ }
129
+ };
130
+ var operationStates = /* @__PURE__ */ new WeakMap();
131
+ function deferredPromise() {
132
+ let resolve;
133
+ let reject;
134
+ const promise = new Promise((promiseResolve, promiseReject) => {
135
+ resolve = promiseResolve;
136
+ reject = promiseReject;
137
+ });
138
+ promise.catch(() => {
139
+ });
140
+ return { promise, resolve, reject };
141
+ }
142
+ var SQLiteOperationImpl = class {
143
+ constructor(executeRequest, request) {
144
+ this.executeRequest = executeRequest;
145
+ operationStates.set(this, {
146
+ executeRequest,
147
+ request
148
+ });
149
+ }
150
+ executeRequest;
151
+ execute() {
152
+ const state = operationStates.get(this);
153
+ if (!state) {
154
+ throw new TypeError("unknown SQLite operation");
155
+ }
156
+ state.promise ??= this.executeRequest(state.request);
157
+ return state.promise;
158
+ }
159
+ then(onfulfilled, onrejected) {
160
+ return this.execute().then(onfulfilled, onrejected);
161
+ }
162
+ };
163
+ var SQLiteQueryImpl = class {
164
+ constructor(executeRequest, request) {
165
+ this.executeRequest = executeRequest;
166
+ this.request = request;
167
+ }
168
+ executeRequest;
169
+ request;
170
+ get() {
171
+ return new SQLiteOperationImpl(this.executeRequest, {
172
+ ...this.request,
173
+ method: "get"
174
+ });
175
+ }
176
+ all() {
177
+ return new SQLiteOperationImpl(this.executeRequest, {
178
+ ...this.request,
179
+ method: "all"
180
+ });
181
+ }
182
+ run() {
183
+ return new SQLiteOperationImpl(this.executeRequest, {
184
+ ...this.request,
185
+ method: "run"
186
+ });
187
+ }
188
+ };
189
+ var SQLiteAdapter = class {
190
+ constructor(exec, disk, database, options = {}) {
191
+ this.exec = exec;
192
+ this.disk = disk;
193
+ this.database = database;
194
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
195
+ this.readBigInts = options.readBigInts ?? false;
196
+ this.returnArrays = options.returnArrays ?? false;
197
+ }
198
+ exec;
199
+ disk;
200
+ database;
201
+ timeoutMs;
202
+ readBigInts;
203
+ returnArrays;
204
+ read(strings, ...values) {
205
+ return new SQLiteQueryImpl((request) => this.executeSingle(request), {
206
+ kind: "read",
207
+ sql: templateToSql(strings),
208
+ params: values.map(encodeParameter)
209
+ });
210
+ }
211
+ write(strings, ...values) {
212
+ return new SQLiteQueryImpl((request) => this.executeSingle(request), {
213
+ kind: "write",
214
+ sql: templateToSql(strings),
215
+ params: values.map(encodeParameter)
216
+ });
217
+ }
218
+ async transaction(operations) {
219
+ const states = operations.map((operation) => {
220
+ const state = operationStates.get(operation);
221
+ if (!state) {
222
+ throw new TypeError("unknown SQLite operation");
223
+ }
224
+ return state;
225
+ });
226
+ const seen = /* @__PURE__ */ new Set();
227
+ for (const state of states) {
228
+ if (state.promise) {
229
+ throw new TypeError("SQLite operation has already started");
230
+ }
231
+ if (seen.has(state)) {
232
+ throw new TypeError("SQLite operation cannot be used more than once in a transaction");
233
+ }
234
+ seen.add(state);
235
+ }
236
+ const requests = states.map((state) => state.request);
237
+ const readOnly = requests.every((request) => request.kind === "read");
238
+ const deferreds = states.map(() => deferredPromise());
239
+ states.forEach((state, index) => {
240
+ state.promise = deferreds[index].promise;
241
+ });
242
+ try {
243
+ const results = await this.executeRemote(requests, { transaction: true, readOnly });
244
+ results.forEach((result, index) => {
245
+ deferreds[index].resolve(result);
246
+ });
247
+ return results;
248
+ } catch (err) {
249
+ deferreds.forEach((deferred) => {
250
+ deferred.reject(err);
251
+ });
252
+ throw err;
253
+ }
254
+ }
255
+ executeSingle(request) {
256
+ return this.executeRemote([request], {
257
+ transaction: false,
258
+ readOnly: request.kind === "read"
259
+ }).then((results) => results[0]);
260
+ }
261
+ async executeRemote(operations, opts) {
262
+ const payload = {
263
+ databasePath: `${DISK_EXEC_MOUNT_PATH}/${this.database.path}`,
264
+ displayPath: this.database.path,
265
+ timeoutMs: this.timeoutMs,
266
+ readBigInts: this.readBigInts,
267
+ returnArrays: this.returnArrays,
268
+ readOnly: opts.readOnly,
269
+ transaction: opts.transaction,
270
+ operations
271
+ };
272
+ const checkoutPaths = opts.readOnly || !this.database.directory ? void 0 : [this.database.directory];
273
+ const queueMs = opts.readOnly ? void 0 : WRITE_MOUNT_QUEUE_MS;
274
+ const mount = {
275
+ disk: this.disk.id,
276
+ readOnly: opts.readOnly,
277
+ checkoutPaths,
278
+ queueMs
279
+ };
280
+ const command = buildCommand(payload);
281
+ const result = await this.exec({
282
+ command,
283
+ disks: { disk: mount }
284
+ });
285
+ const decoded = parseExecResult(result);
286
+ return opts.transaction ? decoded : [decoded];
287
+ }
288
+ };
289
+ function createSQLiteAdapter(exec) {
290
+ return {
291
+ async createDatabase(disk, databasePath, options = {}) {
292
+ const database = normalizeDatabasePath(databasePath);
293
+ const rootDirectory = database.directory ? `${DISK_EXEC_MOUNT_PATH}/${database.directory}` : DISK_EXEC_MOUNT_PATH;
294
+ const mountedDatabasePath = `${rootDirectory}/${database.filename}`;
295
+ const command = `mkdir -p ${shellQuote(rootDirectory)} && node --no-warnings -e ${shellQuote(CREATE_DATABASE_RUNNER)} ${shellQuote(mountedDatabasePath)}`;
296
+ const result = await exec({
297
+ command,
298
+ disks: {
299
+ disk: {
300
+ disk: disk.id,
301
+ readOnly: false,
302
+ queueMs: WRITE_MOUNT_QUEUE_MS
303
+ }
304
+ }
305
+ });
306
+ if (result.exitCode !== 0) {
307
+ throw new ArchilSQLiteError(
308
+ `SQLite database creation failed with exit code ${result.exitCode}: ${result.stderr || result.stdout}`
309
+ );
310
+ }
311
+ return new SQLiteAdapter(exec, disk, database, options);
312
+ },
313
+ async getDatabase(disk, databasePath, options = {}) {
314
+ const database = normalizeDatabasePath(databasePath);
315
+ return new SQLiteAdapter(exec, disk, database, options);
316
+ }
317
+ };
318
+ }
319
+ function templateToSql(strings) {
320
+ let sql = strings[0] ?? "";
321
+ for (let i = 1; i < strings.length; i++) {
322
+ sql += "?" + strings[i];
323
+ }
324
+ return sql;
325
+ }
326
+ function normalizeDatabasePath(path) {
327
+ if (path.endsWith("/")) {
328
+ throw new TypeError("database path must include a file name and not end with '/'");
329
+ }
330
+ const segments = path.split("/").filter((segment) => segment.length > 0 && segment !== ".");
331
+ if (segments.length === 0 || segments.some((segment) => segment === "..")) {
332
+ throw new TypeError("database path must be a non-empty relative file path without '..'");
333
+ }
334
+ const filename = segments[segments.length - 1];
335
+ const directorySegments = segments.slice(0, -1);
336
+ return {
337
+ path: segments.join("/"),
338
+ directory: directorySegments.length > 0 ? directorySegments.join("/") : void 0,
339
+ filename
340
+ };
341
+ }
342
+ var CREATE_DATABASE_RUNNER = `
343
+ const { DatabaseSync } = require("node:sqlite");
344
+ const db = new DatabaseSync(process.argv[1]);
345
+ db.close();
346
+ `;
347
+ function encodeParameter(value) {
348
+ if (value === null) return { type: "null" };
349
+ if (typeof value === "number") return { type: "number", value };
350
+ if (typeof value === "string") return { type: "string", value };
351
+ if (typeof value === "bigint") return { type: "bigint", value: value.toString() };
352
+ if (value instanceof Uint8Array) {
353
+ return {
354
+ type: "bytes",
355
+ value: Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString("base64")
356
+ };
357
+ }
358
+ if (value instanceof ArrayBuffer) {
359
+ return { type: "bytes", value: Buffer.from(value).toString("base64") };
360
+ }
361
+ throw new TypeError(`unsupported SQLite parameter type: ${typeof value}`);
362
+ }
363
+ function decodeWireValue(value) {
364
+ switch (value.type) {
365
+ case "undefined":
366
+ return void 0;
367
+ case "null":
368
+ return null;
369
+ case "number":
370
+ case "string":
371
+ return value.value;
372
+ case "bigint":
373
+ return BigInt(value.value);
374
+ case "bytes":
375
+ return Uint8Array.from(Buffer.from(value.value, "base64"));
376
+ case "array":
377
+ return value.value.map(decodeWireValue);
378
+ case "object":
379
+ return Object.fromEntries(
380
+ Object.entries(value.value).map(([key, entry]) => [key, decodeWireValue(entry)])
381
+ );
382
+ }
383
+ }
384
+ function buildCommand(payload) {
385
+ const encodedPayload = Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
386
+ return `node --no-warnings -e ${shellQuote(REMOTE_RUNNER)} ${shellQuote(encodedPayload)}`;
387
+ }
388
+ function shellQuote(value) {
389
+ return `'${value.replace(/'/g, "'\\''")}'`;
390
+ }
391
+ function parseExecResult(result) {
392
+ if (result.exitCode !== 0) {
393
+ throw new ArchilSQLiteError(
394
+ `SQLite serverless execution failed with exit code ${result.exitCode}: ${result.stderr || result.stdout}`
395
+ );
396
+ }
397
+ const line = result.stdout.split(/\r?\n/).reverse().find((entry) => entry.startsWith(RESULT_PREFIX));
398
+ if (!line) {
399
+ throw new ArchilSQLiteError("SQLite serverless execution did not return a result payload");
400
+ }
401
+ let parsed;
402
+ try {
403
+ parsed = JSON.parse(
404
+ Buffer.from(line.slice(RESULT_PREFIX.length), "base64").toString("utf8")
405
+ );
406
+ } catch (err) {
407
+ throw new ArchilSQLiteError(`SQLite serverless execution returned invalid JSON: ${err}`);
408
+ }
409
+ if (!parsed.ok) {
410
+ throw new ArchilSQLiteError(parsed.error.message ?? "SQLite serverless execution failed", {
411
+ code: parsed.error.code,
412
+ remoteStack: parsed.error.stack
413
+ });
414
+ }
415
+ return decodeWireValue(parsed.result);
416
+ }
417
+
418
+ // src/index.ts
419
+ var sqlite = createSQLiteAdapter((opts) => archilExec(opts));
420
+ function createDatabase(disk, databasePath, options) {
421
+ return sqlite.createDatabase(disk, databasePath, options);
422
+ }
423
+ function getDatabase(disk, databasePath, options) {
424
+ return sqlite.getDatabase(disk, databasePath, options);
425
+ }
426
+ export {
427
+ ArchilSQLiteError,
428
+ createDatabase,
429
+ getDatabase
430
+ };
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@archildata/sqlite",
3
+ "version": "0.0.0",
4
+ "description": "serverless SQLite databases on Archil disks",
5
+ "type": "module",
6
+ "main": "dist/index.cjs",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "peerDependencies": {
22
+ "disk": "^0.8.18"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^20.19.33",
26
+ "tsup": "^8.4.0",
27
+ "tsx": "^4.22.4",
28
+ "typescript": "^5.9.3"
29
+ },
30
+ "engines": {
31
+ "node": ">= 22"
32
+ },
33
+ "keywords": [
34
+ "archil",
35
+ "sqlite",
36
+ "serverless"
37
+ ],
38
+ "license": "MIT",
39
+ "scripts": {
40
+ "build": "tsup src/index.ts --format cjs,esm --dts",
41
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
42
+ "typecheck": "tsc --noEmit",
43
+ "test": "node --import tsx --test test/adapter.test.ts"
44
+ }
45
+ }