flint-orm 0.4.1 → 0.4.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.
Files changed (48) hide show
  1. package/dist/config.d.ts +30 -0
  2. package/dist/drivers/better-sqlite3.d.ts +38 -0
  3. package/dist/drivers/bun-sqlite.d.ts +38 -0
  4. package/dist/drivers/libsql-web.d.ts +44 -0
  5. package/dist/drivers/libsql.d.ts +40 -0
  6. package/dist/drivers/turso-sync.d.ts +44 -0
  7. package/dist/drivers/turso.d.ts +38 -0
  8. package/dist/entries/better-sqlite3.d.ts +1 -0
  9. package/dist/entries/bun-sqlite.d.ts +1 -0
  10. package/dist/entries/config.d.ts +1 -0
  11. package/dist/entries/expressions.d.ts +5 -0
  12. package/dist/entries/libsql-web.d.ts +2 -0
  13. package/dist/entries/libsql.d.ts +2 -0
  14. package/dist/entries/table.d.ts +4 -0
  15. package/dist/entries/turso-sync.d.ts +2 -0
  16. package/dist/entries/turso.d.ts +1 -0
  17. package/dist/errors.d.ts +13 -0
  18. package/dist/executor.d.ts +16 -0
  19. package/dist/flint.d.ts +120 -0
  20. package/dist/index.d.ts +11 -0
  21. package/dist/migration/diff.d.ts +15 -0
  22. package/dist/migration/generate.d.ts +18 -0
  23. package/dist/migration/index.d.ts +11 -0
  24. package/dist/migration/migrate.d.ts +52 -0
  25. package/dist/migration/migration.d.ts +5 -0
  26. package/dist/migration/operations.d.ts +14 -0
  27. package/dist/migration/serialize.d.ts +3 -0
  28. package/dist/migration/sql.d.ts +2 -0
  29. package/dist/migration/types.d.ts +98 -0
  30. package/dist/query/aggregates.d.ts +47 -0
  31. package/dist/query/builder.d.ts +257 -0
  32. package/dist/query/conditions.d.ts +176 -0
  33. package/dist/schema/columns.d.ts +146 -0
  34. package/dist/schema/table.d.ts +74 -0
  35. package/dist/sqlite/introspect.d.ts +19 -0
  36. package/dist/src/cli.js +13818 -0
  37. package/dist/src/entries/better-sqlite3.js +2050 -0
  38. package/dist/src/entries/bun-sqlite.js +1284 -0
  39. package/dist/src/entries/config.js +55 -0
  40. package/dist/src/entries/expressions.js +1252 -0
  41. package/dist/src/entries/libsql-web.js +6065 -0
  42. package/dist/src/entries/libsql.js +7208 -0
  43. package/dist/src/entries/table.js +403 -0
  44. package/dist/src/entries/turso-sync.js +3504 -0
  45. package/dist/src/entries/turso.js +2379 -0
  46. package/dist/{index.js → src/index.js} +86 -22
  47. package/dist/src/migration/index.js +1066 -0
  48. package/package.json +1 -1
@@ -0,0 +1,3504 @@
1
+ // @bun
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
+ var __returnValue = (v) => v;
34
+ function __exportSetter(name, newValue) {
35
+ this[name] = __returnValue.bind(null, newValue);
36
+ }
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, {
40
+ get: all[name],
41
+ enumerable: true,
42
+ configurable: true,
43
+ set: __exportSetter.bind(all, name)
44
+ });
45
+ };
46
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
47
+ var __require = import.meta.require;
48
+
49
+ // node_modules/@tursodatabase/database-common/dist/bind.js
50
+ function bindParams(stmt, params) {
51
+ const len = params?.length;
52
+ if (len === 0) {
53
+ return;
54
+ }
55
+ if (len === 1) {
56
+ const param = params[0];
57
+ if (isPlainObject(param)) {
58
+ bindNamedParams(stmt, param);
59
+ return;
60
+ }
61
+ if (Array.isArray(param)) {
62
+ bindPositionalParams(stmt, [param]);
63
+ return;
64
+ }
65
+ bindValue(stmt, 1, param);
66
+ return;
67
+ }
68
+ bindPositionalParams(stmt, params);
69
+ }
70
+ function isPlainObject(obj) {
71
+ if (!obj || typeof obj !== "object")
72
+ return false;
73
+ const proto = Object.getPrototypeOf(obj);
74
+ return proto === Object.prototype || proto === null;
75
+ }
76
+ function bindNamedParams(stmt, paramObj) {
77
+ const paramCount = stmt.parameterCount();
78
+ for (let i = 1;i <= paramCount; i++) {
79
+ const paramName = stmt.parameterName(i);
80
+ if (paramName) {
81
+ const key = paramName.substring(1);
82
+ const value = paramObj[key];
83
+ if (value !== undefined) {
84
+ bindValue(stmt, i, value);
85
+ }
86
+ }
87
+ }
88
+ }
89
+ function bindPositionalParams(stmt, params) {
90
+ let bindIndex = 1;
91
+ for (let i = 0;i < params.length; i++) {
92
+ const param = params[i];
93
+ if (Array.isArray(param)) {
94
+ for (let j = 0;j < param.length; j++) {
95
+ bindValue(stmt, bindIndex++, param[j]);
96
+ }
97
+ } else {
98
+ bindValue(stmt, bindIndex++, param);
99
+ }
100
+ }
101
+ }
102
+ function bindValue(stmt, index, value) {
103
+ stmt.bindAt(index, value);
104
+ }
105
+
106
+ // node_modules/@tursodatabase/database-common/dist/sqlite-error.js
107
+ var SqliteError;
108
+ var init_sqlite_error = __esm(() => {
109
+ SqliteError = class SqliteError extends Error {
110
+ name;
111
+ code;
112
+ rawCode;
113
+ constructor(message, code, rawCode) {
114
+ super(message);
115
+ this.name = "SqliteError";
116
+ this.code = code;
117
+ this.rawCode = rawCode;
118
+ Error.captureStackTrace(this, SqliteError);
119
+ }
120
+ };
121
+ });
122
+
123
+ // node_modules/@tursodatabase/database-common/dist/types.js
124
+ var STEP_ROW = 1, STEP_DONE = 2, STEP_IO = 3;
125
+
126
+ // node_modules/@tursodatabase/database-common/dist/compat.js
127
+ var init_compat = __esm(() => {
128
+ init_sqlite_error();
129
+ });
130
+
131
+ // node_modules/@tursodatabase/database-common/dist/async-lock.js
132
+ class AsyncLock {
133
+ locked;
134
+ queue;
135
+ constructor() {
136
+ this.locked = false;
137
+ this.queue = [];
138
+ }
139
+ async acquire() {
140
+ if (!this.locked) {
141
+ this.locked = true;
142
+ return Promise.resolve();
143
+ } else {
144
+ const block = new Promise((resolve) => {
145
+ this.queue.push(resolve);
146
+ });
147
+ return block;
148
+ }
149
+ }
150
+ release() {
151
+ if (this.locked == false) {
152
+ throw new Error("invalid state: lock was already unlocked");
153
+ }
154
+ const item = this.queue.shift();
155
+ if (item != null) {
156
+ this.locked = true;
157
+ item();
158
+ } else {
159
+ this.locked = false;
160
+ }
161
+ }
162
+ }
163
+
164
+ // node_modules/@tursodatabase/database-common/dist/promise.js
165
+ function convertError(err) {
166
+ if ((err.code ?? "").startsWith(CONVERTIBLE_ERROR_PREFIX)) {
167
+ return createErrorByName(err.code.substring(CONVERTIBLE_ERROR_PREFIX.length), err.message);
168
+ }
169
+ return new SqliteError(err.message, err.code, err.rawCode);
170
+ }
171
+ function createErrorByName(name, message) {
172
+ const ErrorConstructor = convertibleErrorTypes[name];
173
+ if (!ErrorConstructor) {
174
+ throw new Error(`unknown error type ${name} from Turso`);
175
+ }
176
+ return new ErrorConstructor(message);
177
+ }
178
+ function isQueryOptions(value) {
179
+ return value != null && typeof value === "object" && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "queryTimeout");
180
+ }
181
+ function splitBindParameters(bindParameters) {
182
+ if (bindParameters.length === 0) {
183
+ return { params: undefined, queryOptions: undefined };
184
+ }
185
+ if (bindParameters.length > 1 && isQueryOptions(bindParameters[bindParameters.length - 1])) {
186
+ return {
187
+ params: bindParameters.length === 2 ? bindParameters[0] : bindParameters.slice(0, -1),
188
+ queryOptions: bindParameters[bindParameters.length - 1]
189
+ };
190
+ }
191
+ return { params: bindParameters.length === 1 ? bindParameters[0] : bindParameters, queryOptions: undefined };
192
+ }
193
+ function toBindArgs(params) {
194
+ if (params === undefined) {
195
+ return [];
196
+ }
197
+ return [params];
198
+ }
199
+
200
+ class Database {
201
+ name;
202
+ readonly;
203
+ open;
204
+ memory;
205
+ inTransaction;
206
+ db;
207
+ ioStep;
208
+ execLock;
209
+ _inTransaction = false;
210
+ connected = false;
211
+ constructor(db, ioStep) {
212
+ this.db = db;
213
+ this.execLock = new AsyncLock;
214
+ this.ioStep = ioStep ?? (async () => {});
215
+ Object.defineProperties(this, {
216
+ name: { get: () => this.db.path },
217
+ readonly: { get: () => this.db.readonly },
218
+ open: { get: () => this.db.open },
219
+ memory: { get: () => this.db.memory },
220
+ inTransaction: { get: () => this._inTransaction }
221
+ });
222
+ }
223
+ async connect() {
224
+ if (this.connected) {
225
+ return;
226
+ }
227
+ await this.db.connectAsync();
228
+ this.connected = true;
229
+ }
230
+ prepare(sql) {
231
+ if (this.connected && !this.open) {
232
+ throw new TypeError("The database connection is not open");
233
+ }
234
+ if (!sql) {
235
+ throw new RangeError("The supplied SQL string contains no statements");
236
+ }
237
+ try {
238
+ if (this.connected) {
239
+ return new Statement(maybeValue(this.db.prepare(sql)), this.db, this.execLock, this.ioStep);
240
+ } else {
241
+ return new Statement(maybePromise(() => this.connect().then(() => this.db.prepare(sql))), this.db, this.execLock, this.ioStep);
242
+ }
243
+ } catch (err) {
244
+ throw convertError(err);
245
+ }
246
+ }
247
+ transaction(fn) {
248
+ if (typeof fn !== "function")
249
+ throw new TypeError("Expected first argument to be a function");
250
+ const db = this;
251
+ const wrapTxn = (mode) => {
252
+ return async (...bindParameters) => {
253
+ await db.exec("BEGIN " + mode);
254
+ db._inTransaction = true;
255
+ try {
256
+ const result = await fn(...bindParameters);
257
+ await db.exec("COMMIT");
258
+ db._inTransaction = false;
259
+ return result;
260
+ } catch (err) {
261
+ await db.exec("ROLLBACK");
262
+ db._inTransaction = false;
263
+ throw err;
264
+ }
265
+ };
266
+ };
267
+ const properties = {
268
+ default: { value: wrapTxn("") },
269
+ deferred: { value: wrapTxn("DEFERRED") },
270
+ immediate: { value: wrapTxn("IMMEDIATE") },
271
+ exclusive: { value: wrapTxn("EXCLUSIVE") },
272
+ database: { value: this, enumerable: true }
273
+ };
274
+ Object.defineProperties(properties.default.value, properties);
275
+ Object.defineProperties(properties.deferred.value, properties);
276
+ Object.defineProperties(properties.immediate.value, properties);
277
+ Object.defineProperties(properties.exclusive.value, properties);
278
+ return properties.default.value;
279
+ }
280
+ async run(sql, ...bindParameters) {
281
+ const stmt = await this.prepare(sql);
282
+ try {
283
+ return await stmt.run(...bindParameters);
284
+ } finally {
285
+ await stmt.close();
286
+ }
287
+ }
288
+ async get(sql, ...bindParameters) {
289
+ const stmt = await this.prepare(sql);
290
+ try {
291
+ return await stmt.get(...bindParameters);
292
+ } finally {
293
+ await stmt.close();
294
+ }
295
+ }
296
+ async all(sql, ...bindParameters) {
297
+ const stmt = await this.prepare(sql);
298
+ try {
299
+ return await stmt.all(...bindParameters);
300
+ } finally {
301
+ await stmt.close();
302
+ }
303
+ }
304
+ async* iterate(sql, ...bindParameters) {
305
+ const stmt = await this.prepare(sql);
306
+ try {
307
+ yield* stmt.iterate(...bindParameters);
308
+ } finally {
309
+ await stmt.close();
310
+ }
311
+ }
312
+ async pragma(source, options) {
313
+ if (options == null)
314
+ options = {};
315
+ if (typeof source !== "string")
316
+ throw new TypeError("Expected first argument to be a string");
317
+ if (typeof options !== "object")
318
+ throw new TypeError("Expected second argument to be an options object");
319
+ const pragma = `PRAGMA ${source}`;
320
+ const stmt = await this.prepare(pragma);
321
+ try {
322
+ const results = await stmt.all();
323
+ return results;
324
+ } finally {
325
+ await stmt.close();
326
+ }
327
+ }
328
+ backup(filename, options) {
329
+ throw new Error("not implemented");
330
+ }
331
+ serialize(options) {
332
+ throw new Error("not implemented");
333
+ }
334
+ function(name, options, fn) {
335
+ throw new Error("not implemented");
336
+ }
337
+ aggregate(name, options) {
338
+ throw new Error("not implemented");
339
+ }
340
+ table(name, factory) {
341
+ throw new Error("not implemented");
342
+ }
343
+ loadExtension(path) {
344
+ throw new Error("not implemented");
345
+ }
346
+ maxWriteReplicationIndex() {
347
+ throw new Error("not implemented");
348
+ }
349
+ async exec(sql, queryOptions) {
350
+ if (!this.open) {
351
+ throw new TypeError("The database connection is not open");
352
+ }
353
+ await this.execLock.acquire();
354
+ const exec = this.db.executor(sql, queryOptions);
355
+ try {
356
+ while (true) {
357
+ const stepResult = exec.stepSync();
358
+ if (stepResult === STEP_IO) {
359
+ await this.io();
360
+ continue;
361
+ }
362
+ if (stepResult === STEP_DONE) {
363
+ break;
364
+ }
365
+ if (stepResult === STEP_ROW) {
366
+ continue;
367
+ }
368
+ }
369
+ } finally {
370
+ exec.reset();
371
+ this.execLock.release();
372
+ }
373
+ }
374
+ interrupt() {
375
+ throw new Error("not implemented");
376
+ }
377
+ defaultSafeIntegers(toggle) {
378
+ this.db.defaultSafeIntegers(toggle);
379
+ }
380
+ async close() {
381
+ this.db.close();
382
+ }
383
+ async io() {
384
+ await this.ioStep();
385
+ }
386
+ }
387
+ function maybePromise(arg) {
388
+ let lazy = arg;
389
+ let promise = null;
390
+ let value = null;
391
+ return {
392
+ apply(fn) {
393
+ let previous = lazy;
394
+ lazy = async () => {
395
+ const result = await previous();
396
+ fn(result);
397
+ return result;
398
+ };
399
+ },
400
+ async resolve() {
401
+ if (promise != null) {
402
+ return await promise;
403
+ }
404
+ let valueResolve, valueReject;
405
+ promise = new Promise((resolve, reject) => {
406
+ valueResolve = (x) => {
407
+ resolve(x);
408
+ value = x;
409
+ };
410
+ valueReject = reject;
411
+ });
412
+ await lazy().then(valueResolve, valueReject);
413
+ return await promise;
414
+ },
415
+ must() {
416
+ if (value == null) {
417
+ throw new Error(`database must be connected before execution the function`);
418
+ }
419
+ return value;
420
+ }
421
+ };
422
+ }
423
+ function maybeValue(value) {
424
+ return {
425
+ apply(fn) {
426
+ fn(value);
427
+ },
428
+ resolve() {
429
+ return Promise.resolve(value);
430
+ },
431
+ must() {
432
+ return value;
433
+ }
434
+ };
435
+ }
436
+
437
+ class Statement {
438
+ stmt;
439
+ db;
440
+ execLock;
441
+ ioStep;
442
+ constructor(stmt, db, execLock, ioStep) {
443
+ this.stmt = stmt;
444
+ this.db = db;
445
+ this.execLock = execLock;
446
+ this.ioStep = ioStep;
447
+ }
448
+ raw(raw) {
449
+ this.stmt.apply((s) => s.raw(raw));
450
+ return this;
451
+ }
452
+ pluck(pluckMode) {
453
+ this.stmt.apply((s) => s.pluck(pluckMode));
454
+ return this;
455
+ }
456
+ safeIntegers(toggle) {
457
+ this.stmt.apply((s) => s.safeIntegers(toggle));
458
+ return this;
459
+ }
460
+ columns() {
461
+ return this.stmt.must().columns();
462
+ }
463
+ get source() {
464
+ throw new Error("not implemented");
465
+ }
466
+ get reader() {
467
+ return this.stmt.must().columns().length > 0;
468
+ }
469
+ get database() {
470
+ return this.db;
471
+ }
472
+ async run(...bindParameters) {
473
+ let stmt = await this.stmt.resolve();
474
+ const { params, queryOptions } = splitBindParameters(bindParameters);
475
+ stmt.setQueryTimeout(queryOptions);
476
+ bindParams(stmt, toBindArgs(params));
477
+ const totalChangesBefore = this.db.totalChanges();
478
+ await this.execLock.acquire();
479
+ try {
480
+ while (true) {
481
+ const stepResult = await stmt.stepSync();
482
+ if (stepResult === STEP_IO) {
483
+ await this.io();
484
+ continue;
485
+ }
486
+ if (stepResult === STEP_DONE) {
487
+ break;
488
+ }
489
+ if (stepResult === STEP_ROW) {
490
+ continue;
491
+ }
492
+ }
493
+ const lastInsertRowid = this.db.lastInsertRowid();
494
+ const changes = this.db.totalChanges() === totalChangesBefore ? 0 : this.db.changes();
495
+ return { changes, lastInsertRowid };
496
+ } finally {
497
+ stmt.reset();
498
+ this.execLock.release();
499
+ }
500
+ }
501
+ async get(...bindParameters) {
502
+ let stmt = await this.stmt.resolve();
503
+ const { params, queryOptions } = splitBindParameters(bindParameters);
504
+ stmt.setQueryTimeout(queryOptions);
505
+ bindParams(stmt, toBindArgs(params));
506
+ await this.execLock.acquire();
507
+ let row = undefined;
508
+ try {
509
+ while (true) {
510
+ const stepResult = await stmt.stepSync();
511
+ if (stepResult === STEP_IO) {
512
+ await this.io();
513
+ continue;
514
+ }
515
+ if (stepResult === STEP_DONE) {
516
+ break;
517
+ }
518
+ if (stepResult === STEP_ROW && row === undefined) {
519
+ row = stmt.row();
520
+ continue;
521
+ }
522
+ }
523
+ return row;
524
+ } finally {
525
+ stmt.reset();
526
+ this.execLock.release();
527
+ }
528
+ }
529
+ async* iterate(...bindParameters) {
530
+ let stmt = await this.stmt.resolve();
531
+ const { params, queryOptions } = splitBindParameters(bindParameters);
532
+ stmt.setQueryTimeout(queryOptions);
533
+ bindParams(stmt, toBindArgs(params));
534
+ await this.execLock.acquire();
535
+ try {
536
+ while (true) {
537
+ const stepResult = await stmt.stepSync();
538
+ if (stepResult === STEP_IO) {
539
+ await this.io();
540
+ continue;
541
+ }
542
+ if (stepResult === STEP_DONE) {
543
+ break;
544
+ }
545
+ if (stepResult === STEP_ROW) {
546
+ yield stmt.row();
547
+ }
548
+ }
549
+ } finally {
550
+ stmt.reset();
551
+ this.execLock.release();
552
+ }
553
+ }
554
+ async all(...bindParameters) {
555
+ let stmt = await this.stmt.resolve();
556
+ const { params, queryOptions } = splitBindParameters(bindParameters);
557
+ stmt.setQueryTimeout(queryOptions);
558
+ bindParams(stmt, toBindArgs(params));
559
+ const rows = [];
560
+ await this.execLock.acquire();
561
+ try {
562
+ while (true) {
563
+ const stepResult = await stmt.stepSync();
564
+ if (stepResult === STEP_IO) {
565
+ await this.io();
566
+ continue;
567
+ }
568
+ if (stepResult === STEP_DONE) {
569
+ break;
570
+ }
571
+ if (stepResult === STEP_ROW) {
572
+ rows.push(stmt.row());
573
+ }
574
+ }
575
+ return rows;
576
+ } finally {
577
+ stmt.reset();
578
+ this.execLock.release();
579
+ }
580
+ }
581
+ async io() {
582
+ await this.ioStep();
583
+ }
584
+ interrupt() {
585
+ throw new Error("not implemented");
586
+ }
587
+ bind(...bindParameters) {
588
+ try {
589
+ bindParams(this.stmt, bindParameters);
590
+ return this;
591
+ } catch (err) {
592
+ throw convertError(err);
593
+ }
594
+ }
595
+ close() {
596
+ let stmt;
597
+ try {
598
+ stmt = this.stmt.must();
599
+ } catch (e) {
600
+ return;
601
+ }
602
+ stmt.finalize();
603
+ }
604
+ }
605
+ var convertibleErrorTypes, CONVERTIBLE_ERROR_PREFIX = "[TURSO_CONVERT_TYPE]";
606
+ var init_promise = __esm(() => {
607
+ init_sqlite_error();
608
+ convertibleErrorTypes = { TypeError };
609
+ });
610
+
611
+ // node_modules/@tursodatabase/database-common/dist/index.js
612
+ var init_dist = __esm(() => {
613
+ init_compat();
614
+ init_promise();
615
+ init_sqlite_error();
616
+ });
617
+
618
+ // node_modules/@tursodatabase/sync-common/dist/run.js
619
+ function trackPromise(p) {
620
+ let status = { promise: null, finished: false };
621
+ status.promise = p.finally(() => status.finished = true);
622
+ return status;
623
+ }
624
+ function timeoutMs(ms) {
625
+ return new Promise((resolve) => setTimeout(resolve, ms));
626
+ }
627
+ function normalizeUrl(url) {
628
+ return url.replace(/^libsql:\/\//, "https://");
629
+ }
630
+ async function process2(opts, io, request) {
631
+ const requestType = request.request();
632
+ const completion = request.completion();
633
+ if (requestType.type == "Http") {
634
+ let url = requestType.url;
635
+ if (typeof opts.url == "function") {
636
+ url = opts.url();
637
+ } else {
638
+ url = opts.url;
639
+ }
640
+ if (url == null) {
641
+ completion.poison(`url is empty - sync is paused`);
642
+ return;
643
+ }
644
+ url = normalizeUrl(url);
645
+ try {
646
+ let headers = typeof opts.headers === "function" ? await opts.headers() : opts.headers;
647
+ if (requestType.headers != null && requestType.headers.length > 0) {
648
+ headers = { ...headers };
649
+ for (let header of requestType.headers) {
650
+ headers[header[0]] = header[1];
651
+ }
652
+ }
653
+ const fetchImpl = opts.fetch ?? fetch;
654
+ const response = await fetchImpl(`${url}${requestType.path}`, {
655
+ method: requestType.method,
656
+ headers,
657
+ body: requestType.body != null ? new Uint8Array(requestType.body) : null
658
+ });
659
+ completion.status(response.status);
660
+ const reader = response.body?.getReader();
661
+ if (reader == null) {
662
+ throw new Error("reader is null");
663
+ }
664
+ while (true) {
665
+ const { done, value } = await reader.read();
666
+ if (done) {
667
+ completion.done();
668
+ break;
669
+ }
670
+ completion.pushBuffer(value);
671
+ }
672
+ } catch (error) {
673
+ completion.poison(`fetch error: ${error}`);
674
+ }
675
+ } else if (requestType.type == "FullRead") {
676
+ try {
677
+ const metadata = await io.read(requestType.path);
678
+ if (metadata != null) {
679
+ completion.pushBuffer(metadata);
680
+ }
681
+ completion.done();
682
+ } catch (error) {
683
+ completion.poison(`metadata read error: ${error}`);
684
+ }
685
+ } else if (requestType.type == "FullWrite") {
686
+ try {
687
+ await io.write(requestType.path, requestType.content);
688
+ completion.done();
689
+ } catch (error) {
690
+ completion.poison(`metadata write error: ${error}`);
691
+ }
692
+ } else if (requestType.type == "Transform") {
693
+ if (opts.transform == null) {
694
+ completion.poison("transform is not set");
695
+ return;
696
+ }
697
+ const results = [];
698
+ for (const mutation of requestType.mutations) {
699
+ const result = opts.transform(mutation);
700
+ if (result == null) {
701
+ results.push({ type: "Keep" });
702
+ } else if (result.operation == "skip") {
703
+ results.push({ type: "Skip" });
704
+ } else if (result.operation == "rewrite") {
705
+ results.push({ type: "Rewrite", stmt: result.stmt });
706
+ } else {
707
+ completion.poison("unexpected transform operation");
708
+ return;
709
+ }
710
+ }
711
+ completion.pushTransform(results);
712
+ completion.done();
713
+ }
714
+ }
715
+ function retryFetch(opts = {}) {
716
+ const attempts = opts.attempts ?? 3;
717
+ const baseDelay = opts.delayMs ?? 500;
718
+ const backoff = opts.backoff ?? 2;
719
+ const underlying = opts.fetch ?? ((input, init) => fetch(input, init));
720
+ if (!Number.isFinite(attempts) || attempts < 1) {
721
+ throw new Error(`retryFetch: attempts must be a finite integer >= 1, got ${attempts}`);
722
+ }
723
+ return async (input, init) => {
724
+ let lastError = null;
725
+ let lastResponse = null;
726
+ let delay = baseDelay;
727
+ for (let i = 0;i < attempts; i++) {
728
+ try {
729
+ const response = await underlying(input, init);
730
+ if (response.status < 500 && response.status !== 429) {
731
+ return response;
732
+ }
733
+ lastResponse = response;
734
+ lastError = null;
735
+ } catch (error) {
736
+ lastError = error;
737
+ lastResponse = null;
738
+ }
739
+ if (i + 1 < attempts) {
740
+ await timeoutMs(delay);
741
+ delay *= backoff;
742
+ }
743
+ }
744
+ if (lastResponse != null) {
745
+ return lastResponse;
746
+ }
747
+ throw lastError ?? new Error("retryFetch: exhausted with no response");
748
+ };
749
+ }
750
+ function runner(opts, io, engine) {
751
+ let tasks = [];
752
+ return {
753
+ async wait() {
754
+ for (let request = engine.protocolIo();request != null; request = engine.protocolIo()) {
755
+ tasks.push(trackPromise(process2(opts, io, request)));
756
+ }
757
+ const tasksRace = tasks.length == 0 ? Promise.resolve() : Promise.race([timeoutMs(opts.preemptionMs), ...tasks.map((t) => t.promise)]);
758
+ await Promise.all([engine.ioLoopAsync(), tasksRace]);
759
+ tasks = tasks.filter((t) => !t.finished);
760
+ engine.protocolIoStep();
761
+ }
762
+ };
763
+ }
764
+ async function run(runner2, generator) {
765
+ while (true) {
766
+ const { type, ...rest } = await generator.resumeAsync(null);
767
+ if (type == "Done") {
768
+ return null;
769
+ }
770
+ if (type == "SyncEngineStats") {
771
+ return rest;
772
+ }
773
+ if (type == "SyncEngineChanges") {
774
+ return rest.changes;
775
+ }
776
+ await runner2.wait();
777
+ }
778
+ }
779
+
780
+ class SyncEngineGuards {
781
+ waitLock;
782
+ pushLock;
783
+ pullLock;
784
+ checkpointLock;
785
+ constructor() {
786
+ this.waitLock = new AsyncLock;
787
+ this.pushLock = new AsyncLock;
788
+ this.pullLock = new AsyncLock;
789
+ this.checkpointLock = new AsyncLock;
790
+ }
791
+ async wait(f) {
792
+ try {
793
+ await this.waitLock.acquire();
794
+ return await f();
795
+ } finally {
796
+ this.waitLock.release();
797
+ }
798
+ }
799
+ async push(f) {
800
+ try {
801
+ await this.pushLock.acquire();
802
+ await this.pullLock.acquire();
803
+ await this.checkpointLock.acquire();
804
+ return await f();
805
+ } finally {
806
+ this.pushLock.release();
807
+ this.pullLock.release();
808
+ this.checkpointLock.release();
809
+ }
810
+ }
811
+ async apply(f) {
812
+ try {
813
+ await this.waitLock.acquire();
814
+ await this.pushLock.acquire();
815
+ await this.pullLock.acquire();
816
+ await this.checkpointLock.acquire();
817
+ return await f();
818
+ } finally {
819
+ this.waitLock.release();
820
+ this.pushLock.release();
821
+ this.pullLock.release();
822
+ this.checkpointLock.release();
823
+ }
824
+ }
825
+ async checkpoint(f) {
826
+ try {
827
+ await this.waitLock.acquire();
828
+ await this.pushLock.acquire();
829
+ await this.pullLock.acquire();
830
+ await this.checkpointLock.acquire();
831
+ return await f();
832
+ } finally {
833
+ this.waitLock.release();
834
+ this.pushLock.release();
835
+ this.pullLock.release();
836
+ this.checkpointLock.release();
837
+ }
838
+ }
839
+ }
840
+ var init_run = __esm(() => {
841
+ init_dist();
842
+ });
843
+ // node_modules/@tursodatabase/serverless/dist/error.js
844
+ var DatabaseError;
845
+ var init_error = __esm(() => {
846
+ DatabaseError = class DatabaseError extends Error {
847
+ constructor(message, code, rawCode, cause) {
848
+ super(message);
849
+ this.name = "DatabaseError";
850
+ this.code = code;
851
+ this.rawCode = rawCode;
852
+ this.cause = cause;
853
+ Object.setPrototypeOf(this, DatabaseError.prototype);
854
+ }
855
+ };
856
+ });
857
+
858
+ // node_modules/@tursodatabase/serverless/dist/protocol.js
859
+ function encodeValue(value) {
860
+ if (value === null || value === undefined) {
861
+ return { type: "null" };
862
+ }
863
+ if (typeof value === "number") {
864
+ if (!Number.isFinite(value)) {
865
+ throw new Error("Only finite numbers (not Infinity or NaN) can be passed as arguments");
866
+ }
867
+ return { type: "float", value };
868
+ }
869
+ if (typeof value === "bigint") {
870
+ return { type: "integer", value: value.toString() };
871
+ }
872
+ if (typeof value === "boolean") {
873
+ return { type: "integer", value: value ? "1" : "0" };
874
+ }
875
+ if (typeof value === "string") {
876
+ return { type: "text", value };
877
+ }
878
+ if (value instanceof ArrayBuffer || value instanceof Uint8Array) {
879
+ const base64 = btoa(String.fromCharCode(...new Uint8Array(value)));
880
+ return { type: "blob", base64 };
881
+ }
882
+ return { type: "text", value: String(value) };
883
+ }
884
+ function decodeValue(value, safeIntegers = false) {
885
+ switch (value.type) {
886
+ case "null":
887
+ return null;
888
+ case "integer":
889
+ if (safeIntegers) {
890
+ return BigInt(value.value);
891
+ }
892
+ return parseInt(value.value, 10);
893
+ case "float":
894
+ return value.value;
895
+ case "text":
896
+ return value.value;
897
+ case "blob":
898
+ if (value.base64) {
899
+ const binaryString = atob(value.base64);
900
+ const bytes = new Uint8Array(binaryString.length);
901
+ for (let i = 0;i < binaryString.length; i++) {
902
+ bytes[i] = binaryString.charCodeAt(i);
903
+ }
904
+ return Buffer.from(bytes);
905
+ }
906
+ return null;
907
+ default:
908
+ return null;
909
+ }
910
+ }
911
+ async function executeCursor(url, authToken, request, remoteEncryptionKey) {
912
+ const headers = {
913
+ "Content-Type": "application/json"
914
+ };
915
+ if (authToken) {
916
+ headers["Authorization"] = `Bearer ${authToken}`;
917
+ }
918
+ if (remoteEncryptionKey) {
919
+ headers[ENCRYPTION_KEY_HEADER] = remoteEncryptionKey;
920
+ }
921
+ const response = await fetch(`${url}/v3/cursor`, {
922
+ method: "POST",
923
+ headers,
924
+ body: JSON.stringify(request)
925
+ });
926
+ if (!response.ok) {
927
+ let errorMessage = `HTTP error! status: ${response.status}`;
928
+ try {
929
+ const errorBody = await response.text();
930
+ const errorData = JSON.parse(errorBody);
931
+ if (errorData.message) {
932
+ errorMessage = errorData.message;
933
+ }
934
+ } catch {}
935
+ throw new DatabaseError(errorMessage);
936
+ }
937
+ const reader = response.body?.getReader();
938
+ if (!reader) {
939
+ throw new DatabaseError("No response body");
940
+ }
941
+ const decoder = new TextDecoder;
942
+ let buffer = "";
943
+ let cursorResponse;
944
+ while (!cursorResponse) {
945
+ const { done, value } = await reader.read();
946
+ if (done)
947
+ break;
948
+ buffer += decoder.decode(value, { stream: true });
949
+ const newlineIndex = buffer.indexOf(`
950
+ `);
951
+ if (newlineIndex !== -1) {
952
+ const line = buffer.slice(0, newlineIndex).trim();
953
+ buffer = buffer.slice(newlineIndex + 1);
954
+ if (line) {
955
+ cursorResponse = JSON.parse(line);
956
+ break;
957
+ }
958
+ }
959
+ }
960
+ if (!cursorResponse) {
961
+ throw new DatabaseError("No cursor response received");
962
+ }
963
+ async function* parseEntries() {
964
+ try {
965
+ let newlineIndex;
966
+ while ((newlineIndex = buffer.indexOf(`
967
+ `)) !== -1) {
968
+ const line = buffer.slice(0, newlineIndex).trim();
969
+ buffer = buffer.slice(newlineIndex + 1);
970
+ if (line) {
971
+ yield JSON.parse(line);
972
+ }
973
+ }
974
+ while (true) {
975
+ const { done, value } = await reader.read();
976
+ if (done)
977
+ break;
978
+ buffer += decoder.decode(value, { stream: true });
979
+ while ((newlineIndex = buffer.indexOf(`
980
+ `)) !== -1) {
981
+ const line = buffer.slice(0, newlineIndex).trim();
982
+ buffer = buffer.slice(newlineIndex + 1);
983
+ if (line) {
984
+ yield JSON.parse(line);
985
+ }
986
+ }
987
+ }
988
+ if (buffer.trim()) {
989
+ yield JSON.parse(buffer.trim());
990
+ }
991
+ } finally {
992
+ reader.releaseLock();
993
+ }
994
+ }
995
+ return { response: cursorResponse, entries: parseEntries() };
996
+ }
997
+ async function executePipeline(url, authToken, request, remoteEncryptionKey) {
998
+ const headers = {
999
+ "Content-Type": "application/json"
1000
+ };
1001
+ if (authToken) {
1002
+ headers["Authorization"] = `Bearer ${authToken}`;
1003
+ }
1004
+ if (remoteEncryptionKey) {
1005
+ headers[ENCRYPTION_KEY_HEADER] = remoteEncryptionKey;
1006
+ }
1007
+ const response = await fetch(`${url}/v3/pipeline`, {
1008
+ method: "POST",
1009
+ headers,
1010
+ body: JSON.stringify(request)
1011
+ });
1012
+ if (!response.ok) {
1013
+ throw new DatabaseError(`HTTP error! status: ${response.status}`);
1014
+ }
1015
+ return response.json();
1016
+ }
1017
+ var ENCRYPTION_KEY_HEADER = "x-turso-encryption-key";
1018
+ var init_protocol = __esm(() => {
1019
+ init_error();
1020
+ });
1021
+
1022
+ // node_modules/@tursodatabase/serverless/dist/session.js
1023
+ function normalizeUrl2(url) {
1024
+ return url.replace(/^libsql:\/\//, "https://");
1025
+ }
1026
+ function isValidIdentifier(str) {
1027
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(str);
1028
+ }
1029
+
1030
+ class Session {
1031
+ constructor(config) {
1032
+ this.baton = null;
1033
+ this.config = config;
1034
+ this.baseUrl = normalizeUrl2(config.url);
1035
+ }
1036
+ async describe(sql) {
1037
+ const request = {
1038
+ baton: this.baton,
1039
+ requests: [{
1040
+ type: "describe",
1041
+ sql
1042
+ }]
1043
+ };
1044
+ const response = await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey);
1045
+ this.baton = response.baton;
1046
+ if (response.base_url) {
1047
+ this.baseUrl = response.base_url;
1048
+ }
1049
+ if (response.results && response.results[0]) {
1050
+ const result = response.results[0];
1051
+ if (result.type === "error") {
1052
+ throw new DatabaseError(result.error?.message || "Describe execution failed", result.error?.code);
1053
+ }
1054
+ if (result.response?.type === "describe" && result.response.result) {
1055
+ return result.response.result;
1056
+ }
1057
+ }
1058
+ throw new DatabaseError("Unexpected describe response");
1059
+ }
1060
+ async execute(sql, args = [], safeIntegers = false) {
1061
+ const { response, entries } = await this.executeRaw(sql, args);
1062
+ const result = await this.processCursorEntries(entries, safeIntegers);
1063
+ return result;
1064
+ }
1065
+ async executeRaw(sql, args = []) {
1066
+ let positionalArgs = [];
1067
+ let namedArgs = [];
1068
+ if (Array.isArray(args)) {
1069
+ positionalArgs = args.map(encodeValue);
1070
+ } else {
1071
+ const keys = Object.keys(args);
1072
+ const isNumericKeys = keys.length > 0 && keys.every((key) => /^\d+$/.test(key));
1073
+ if (isNumericKeys) {
1074
+ const sortedKeys = keys.sort((a, b) => parseInt(a) - parseInt(b));
1075
+ const maxIndex = parseInt(sortedKeys[sortedKeys.length - 1]);
1076
+ positionalArgs = new Array(maxIndex);
1077
+ for (const key of sortedKeys) {
1078
+ const index = parseInt(key) - 1;
1079
+ positionalArgs[index] = encodeValue(args[key]);
1080
+ }
1081
+ for (let i = 0;i < positionalArgs.length; i++) {
1082
+ if (positionalArgs[i] === undefined) {
1083
+ positionalArgs[i] = { type: "null" };
1084
+ }
1085
+ }
1086
+ } else {
1087
+ namedArgs = Object.entries(args).map(([name, value]) => ({
1088
+ name,
1089
+ value: encodeValue(value)
1090
+ }));
1091
+ }
1092
+ }
1093
+ const request = {
1094
+ baton: this.baton,
1095
+ batch: {
1096
+ steps: [{
1097
+ stmt: {
1098
+ sql,
1099
+ args: positionalArgs,
1100
+ named_args: namedArgs,
1101
+ want_rows: true
1102
+ }
1103
+ }]
1104
+ }
1105
+ };
1106
+ const { response, entries } = await executeCursor(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey);
1107
+ this.baton = response.baton;
1108
+ if (response.base_url) {
1109
+ this.baseUrl = response.base_url;
1110
+ }
1111
+ return { response, entries };
1112
+ }
1113
+ async processCursorEntries(entries, safeIntegers = false) {
1114
+ let columns = [];
1115
+ let columnTypes = [];
1116
+ let rows = [];
1117
+ let rowsAffected = 0;
1118
+ let lastInsertRowid;
1119
+ for await (const entry of entries) {
1120
+ switch (entry.type) {
1121
+ case "step_begin":
1122
+ if (entry.cols) {
1123
+ columns = entry.cols.map((col) => col.name);
1124
+ columnTypes = entry.cols.map((col) => col.decltype || "");
1125
+ }
1126
+ break;
1127
+ case "row":
1128
+ if (entry.row) {
1129
+ const decodedRow = entry.row.map((value) => decodeValue(value, safeIntegers));
1130
+ const rowObject = this.createRowObject(decodedRow, columns);
1131
+ rows.push(rowObject);
1132
+ }
1133
+ break;
1134
+ case "step_end":
1135
+ if (entry.affected_row_count !== undefined) {
1136
+ rowsAffected = entry.affected_row_count;
1137
+ }
1138
+ if (entry.last_insert_rowid) {
1139
+ lastInsertRowid = parseInt(entry.last_insert_rowid, 10);
1140
+ }
1141
+ break;
1142
+ case "step_error":
1143
+ case "error":
1144
+ throw new DatabaseError(entry.error?.message || "SQL execution failed", entry.error?.code);
1145
+ }
1146
+ }
1147
+ return {
1148
+ columns,
1149
+ columnTypes,
1150
+ rows,
1151
+ rowsAffected,
1152
+ lastInsertRowid
1153
+ };
1154
+ }
1155
+ createRowObject(values, columns) {
1156
+ const row = [...values];
1157
+ columns.forEach((column, index) => {
1158
+ if (column && isValidIdentifier(column)) {
1159
+ Object.defineProperty(row, column, {
1160
+ value: values[index],
1161
+ enumerable: false,
1162
+ writable: false,
1163
+ configurable: true
1164
+ });
1165
+ }
1166
+ });
1167
+ return row;
1168
+ }
1169
+ async batch(statements) {
1170
+ const request = {
1171
+ baton: this.baton,
1172
+ batch: {
1173
+ steps: statements.map((sql) => ({
1174
+ stmt: {
1175
+ sql,
1176
+ args: [],
1177
+ named_args: [],
1178
+ want_rows: false
1179
+ }
1180
+ }))
1181
+ }
1182
+ };
1183
+ const { response, entries } = await executeCursor(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey);
1184
+ this.baton = response.baton;
1185
+ if (response.base_url) {
1186
+ this.baseUrl = response.base_url;
1187
+ }
1188
+ let totalRowsAffected = 0;
1189
+ let lastInsertRowid;
1190
+ for await (const entry of entries) {
1191
+ switch (entry.type) {
1192
+ case "step_end":
1193
+ if (entry.affected_row_count !== undefined) {
1194
+ totalRowsAffected += entry.affected_row_count;
1195
+ }
1196
+ if (entry.last_insert_rowid) {
1197
+ lastInsertRowid = parseInt(entry.last_insert_rowid, 10);
1198
+ }
1199
+ break;
1200
+ case "step_error":
1201
+ case "error":
1202
+ throw new DatabaseError(entry.error?.message || "Batch execution failed", entry.error?.code);
1203
+ }
1204
+ }
1205
+ return {
1206
+ rowsAffected: totalRowsAffected,
1207
+ lastInsertRowid
1208
+ };
1209
+ }
1210
+ async sequence(sql) {
1211
+ const request = {
1212
+ baton: this.baton,
1213
+ requests: [{
1214
+ type: "sequence",
1215
+ sql
1216
+ }]
1217
+ };
1218
+ const response = await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey);
1219
+ this.baton = response.baton;
1220
+ if (response.base_url) {
1221
+ this.baseUrl = response.base_url;
1222
+ }
1223
+ if (response.results && response.results[0]) {
1224
+ const result = response.results[0];
1225
+ if (result.type === "error") {
1226
+ throw new DatabaseError(result.error?.message || "Sequence execution failed", result.error?.code);
1227
+ }
1228
+ }
1229
+ }
1230
+ async close() {
1231
+ if (this.baton) {
1232
+ try {
1233
+ const request = {
1234
+ baton: this.baton,
1235
+ requests: [{
1236
+ type: "close"
1237
+ }]
1238
+ };
1239
+ await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey);
1240
+ } catch (error) {
1241
+ console.error("Error closing session:", error);
1242
+ }
1243
+ }
1244
+ this.baton = null;
1245
+ this.baseUrl = "";
1246
+ }
1247
+ }
1248
+ var init_session = __esm(() => {
1249
+ init_protocol();
1250
+ init_error();
1251
+ });
1252
+
1253
+ // node_modules/@tursodatabase/serverless/dist/statement.js
1254
+ var init_statement = __esm(() => {
1255
+ init_protocol();
1256
+ init_session();
1257
+ init_error();
1258
+ });
1259
+
1260
+ // node_modules/@tursodatabase/serverless/dist/connection.js
1261
+ var init_connection = __esm(() => {
1262
+ init_session();
1263
+ init_statement();
1264
+ });
1265
+
1266
+ // node_modules/@tursodatabase/serverless/dist/index.js
1267
+ var init_dist2 = __esm(() => {
1268
+ init_connection();
1269
+ init_statement();
1270
+ init_session();
1271
+ init_error();
1272
+ init_protocol();
1273
+ });
1274
+
1275
+ // node_modules/@tursodatabase/sync-common/dist/remote-writer.js
1276
+ class RemoteWriter {
1277
+ session = null;
1278
+ _inRemoteTxn = false;
1279
+ config;
1280
+ constructor(config) {
1281
+ this.config = config;
1282
+ }
1283
+ async resolveAuthToken() {
1284
+ if (typeof this.config.authToken === "function") {
1285
+ return await this.config.authToken();
1286
+ }
1287
+ return this.config.authToken;
1288
+ }
1289
+ async createSession() {
1290
+ const authToken = await this.resolveAuthToken();
1291
+ const sessionConfig = {
1292
+ url: this.config.url,
1293
+ authToken,
1294
+ remoteEncryptionKey: this.config.remoteEncryptionKey
1295
+ };
1296
+ return new Session(sessionConfig);
1297
+ }
1298
+ async execute(sql, args = []) {
1299
+ if (this._inRemoteTxn) {
1300
+ return await this.session.execute(sql, args);
1301
+ }
1302
+ const session = await this.createSession();
1303
+ try {
1304
+ return await session.execute(sql, args);
1305
+ } finally {
1306
+ await session.close();
1307
+ }
1308
+ }
1309
+ async sequence(sql) {
1310
+ if (this._inRemoteTxn) {
1311
+ await this.session.sequence(sql);
1312
+ return;
1313
+ }
1314
+ const session = await this.createSession();
1315
+ try {
1316
+ await session.sequence(sql);
1317
+ } finally {
1318
+ await session.close();
1319
+ }
1320
+ }
1321
+ async beginTransaction(mode) {
1322
+ this.session = await this.createSession();
1323
+ await this.session.sequence("BEGIN " + mode);
1324
+ this._inRemoteTxn = true;
1325
+ }
1326
+ async commitTransaction() {
1327
+ if (!this.session) {
1328
+ throw new Error("No active remote transaction");
1329
+ }
1330
+ try {
1331
+ await this.session.sequence("COMMIT");
1332
+ } finally {
1333
+ this._inRemoteTxn = false;
1334
+ await this.session.close();
1335
+ this.session = null;
1336
+ }
1337
+ }
1338
+ async rollbackTransaction() {
1339
+ if (!this.session) {
1340
+ throw new Error("No active remote transaction");
1341
+ }
1342
+ try {
1343
+ await this.session.sequence("ROLLBACK");
1344
+ } finally {
1345
+ this._inRemoteTxn = false;
1346
+ await this.session.close();
1347
+ this.session = null;
1348
+ }
1349
+ }
1350
+ async execRemote(sql, category) {
1351
+ if (category === "begin") {
1352
+ this.session = await this.createSession();
1353
+ await this.session.sequence(sql);
1354
+ this._inRemoteTxn = true;
1355
+ return { shouldPull: false };
1356
+ }
1357
+ if (category === "commit") {
1358
+ if (!this.session)
1359
+ throw new Error("No active remote transaction");
1360
+ try {
1361
+ await this.session.sequence(sql);
1362
+ } finally {
1363
+ this._inRemoteTxn = false;
1364
+ await this.session.close();
1365
+ this.session = null;
1366
+ }
1367
+ return { shouldPull: true };
1368
+ }
1369
+ if (category === "rollback") {
1370
+ if (!this.session)
1371
+ throw new Error("No active remote transaction");
1372
+ try {
1373
+ await this.session.sequence(sql);
1374
+ } finally {
1375
+ this._inRemoteTxn = false;
1376
+ await this.session.close();
1377
+ this.session = null;
1378
+ }
1379
+ return { shouldPull: false };
1380
+ }
1381
+ await this.sequence(sql);
1382
+ return { shouldPull: !this._inRemoteTxn };
1383
+ }
1384
+ get isInTransaction() {
1385
+ return this._inRemoteTxn;
1386
+ }
1387
+ async close() {
1388
+ if (this.session) {
1389
+ try {
1390
+ if (this._inRemoteTxn) {
1391
+ await this.session.sequence("ROLLBACK");
1392
+ }
1393
+ } catch {}
1394
+ await this.session.close();
1395
+ this.session = null;
1396
+ this._inRemoteTxn = false;
1397
+ }
1398
+ }
1399
+ }
1400
+ var init_remote_writer = __esm(() => {
1401
+ init_dist2();
1402
+ });
1403
+
1404
+ // node_modules/@tursodatabase/sync-common/dist/remote-write-statement.js
1405
+ class RemoteWriteStatement {
1406
+ localStmt;
1407
+ sql;
1408
+ isStmtReadonly;
1409
+ remoteWriter;
1410
+ pullFn;
1411
+ _boundArgs = [];
1412
+ constructor(localStmt, sql, isStmtReadonly, remoteWriter, pullFn) {
1413
+ this.localStmt = localStmt;
1414
+ this.sql = sql;
1415
+ this.isStmtReadonly = isStmtReadonly;
1416
+ this.remoteWriter = remoteWriter;
1417
+ this.pullFn = pullFn;
1418
+ }
1419
+ shouldGoRemote() {
1420
+ return this.remoteWriter.isInTransaction || !this.isStmtReadonly;
1421
+ }
1422
+ shouldPullAfter() {
1423
+ return !this.isStmtReadonly && !this.remoteWriter.isInTransaction;
1424
+ }
1425
+ raw(toggle) {
1426
+ this.localStmt.raw(toggle);
1427
+ return this;
1428
+ }
1429
+ pluck(toggle) {
1430
+ this.localStmt.pluck(toggle);
1431
+ return this;
1432
+ }
1433
+ safeIntegers(toggle) {
1434
+ this.localStmt.safeIntegers(toggle);
1435
+ return this;
1436
+ }
1437
+ columns() {
1438
+ return this.localStmt.columns();
1439
+ }
1440
+ get reader() {
1441
+ return this.localStmt.reader;
1442
+ }
1443
+ bind(...bindParameters) {
1444
+ this._boundArgs = flattenArgs(bindParameters);
1445
+ this.localStmt.bind(...bindParameters);
1446
+ return this;
1447
+ }
1448
+ async run(...bindParameters) {
1449
+ if (!this.shouldGoRemote()) {
1450
+ return await this.localStmt.run(...bindParameters);
1451
+ }
1452
+ const args = bindParameters.length > 0 ? flattenArgs(bindParameters) : this._boundArgs;
1453
+ const result = await this.remoteWriter.execute(this.sql, args);
1454
+ if (this.shouldPullAfter()) {
1455
+ await this.pullFn();
1456
+ }
1457
+ return {
1458
+ changes: result.rowsAffected,
1459
+ lastInsertRowid: result.lastInsertRowid
1460
+ };
1461
+ }
1462
+ async get(...bindParameters) {
1463
+ if (!this.shouldGoRemote()) {
1464
+ return await this.localStmt.get(...bindParameters);
1465
+ }
1466
+ const args = bindParameters.length > 0 ? flattenArgs(bindParameters) : this._boundArgs;
1467
+ const result = await this.remoteWriter.execute(this.sql, args);
1468
+ if (this.shouldPullAfter()) {
1469
+ await this.pullFn();
1470
+ }
1471
+ return result.rows.length > 0 ? result.rows[0] : undefined;
1472
+ }
1473
+ async all(...bindParameters) {
1474
+ if (!this.shouldGoRemote()) {
1475
+ return await this.localStmt.all(...bindParameters);
1476
+ }
1477
+ const args = bindParameters.length > 0 ? flattenArgs(bindParameters) : this._boundArgs;
1478
+ const result = await this.remoteWriter.execute(this.sql, args);
1479
+ if (this.shouldPullAfter()) {
1480
+ await this.pullFn();
1481
+ }
1482
+ return result.rows;
1483
+ }
1484
+ async* iterate(...bindParameters) {
1485
+ if (!this.shouldGoRemote()) {
1486
+ yield* this.localStmt.iterate(...bindParameters);
1487
+ return;
1488
+ }
1489
+ const args = bindParameters.length > 0 ? flattenArgs(bindParameters) : this._boundArgs;
1490
+ const result = await this.remoteWriter.execute(this.sql, args);
1491
+ if (this.shouldPullAfter()) {
1492
+ await this.pullFn();
1493
+ }
1494
+ for (const row of result.rows) {
1495
+ yield row;
1496
+ }
1497
+ }
1498
+ close() {
1499
+ this.localStmt.close();
1500
+ }
1501
+ }
1502
+ function flattenArgs(bindParameters) {
1503
+ if (bindParameters.length === 1 && Array.isArray(bindParameters[0])) {
1504
+ return bindParameters[0];
1505
+ }
1506
+ return bindParameters;
1507
+ }
1508
+
1509
+ // node_modules/@tursodatabase/sync-common/dist/index.js
1510
+ var init_dist3 = __esm(() => {
1511
+ init_run();
1512
+ init_remote_writer();
1513
+ });
1514
+
1515
+ // node_modules/@tursodatabase/sync/index.js
1516
+ import { createRequire } from "module";
1517
+ function requireNative() {
1518
+ if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) {
1519
+ try {
1520
+ nativeBinding = require2(process.env.NAPI_RS_NATIVE_LIBRARY_PATH);
1521
+ } catch (err) {
1522
+ loadErrors.push(err);
1523
+ }
1524
+ } else if (process.platform === "android") {
1525
+ if (process.arch === "arm64") {
1526
+ try {
1527
+ return require2("./sync.android-arm64.node");
1528
+ } catch (e) {
1529
+ loadErrors.push(e);
1530
+ }
1531
+ try {
1532
+ const binding = require2("@tursodatabase/sync-android-arm64");
1533
+ const bindingPackageVersion = require2("@tursodatabase/sync-android-arm64/package.json").version;
1534
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1535
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1536
+ }
1537
+ return binding;
1538
+ } catch (e) {
1539
+ loadErrors.push(e);
1540
+ }
1541
+ } else if (process.arch === "arm") {
1542
+ try {
1543
+ return require2("./sync.android-arm-eabi.node");
1544
+ } catch (e) {
1545
+ loadErrors.push(e);
1546
+ }
1547
+ try {
1548
+ const binding = require2("@tursodatabase/sync-android-arm-eabi");
1549
+ const bindingPackageVersion = require2("@tursodatabase/sync-android-arm-eabi/package.json").version;
1550
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1551
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1552
+ }
1553
+ return binding;
1554
+ } catch (e) {
1555
+ loadErrors.push(e);
1556
+ }
1557
+ } else {
1558
+ loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`));
1559
+ }
1560
+ } else if (process.platform === "win32") {
1561
+ if (process.arch === "x64") {
1562
+ try {
1563
+ return require2("./sync.win32-x64-msvc.node");
1564
+ } catch (e) {
1565
+ loadErrors.push(e);
1566
+ }
1567
+ try {
1568
+ const binding = require2("@tursodatabase/sync-win32-x64-msvc");
1569
+ const bindingPackageVersion = require2("@tursodatabase/sync-win32-x64-msvc/package.json").version;
1570
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1571
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1572
+ }
1573
+ return binding;
1574
+ } catch (e) {
1575
+ loadErrors.push(e);
1576
+ }
1577
+ } else if (process.arch === "ia32") {
1578
+ try {
1579
+ return require2("./sync.win32-ia32-msvc.node");
1580
+ } catch (e) {
1581
+ loadErrors.push(e);
1582
+ }
1583
+ try {
1584
+ const binding = require2("@tursodatabase/sync-win32-ia32-msvc");
1585
+ const bindingPackageVersion = require2("@tursodatabase/sync-win32-ia32-msvc/package.json").version;
1586
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1587
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1588
+ }
1589
+ return binding;
1590
+ } catch (e) {
1591
+ loadErrors.push(e);
1592
+ }
1593
+ } else if (process.arch === "arm64") {
1594
+ try {
1595
+ return require2("./sync.win32-arm64-msvc.node");
1596
+ } catch (e) {
1597
+ loadErrors.push(e);
1598
+ }
1599
+ try {
1600
+ const binding = require2("@tursodatabase/sync-win32-arm64-msvc");
1601
+ const bindingPackageVersion = require2("@tursodatabase/sync-win32-arm64-msvc/package.json").version;
1602
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1603
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1604
+ }
1605
+ return binding;
1606
+ } catch (e) {
1607
+ loadErrors.push(e);
1608
+ }
1609
+ } else {
1610
+ loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`));
1611
+ }
1612
+ } else if (process.platform === "darwin") {
1613
+ try {
1614
+ return require2("./sync.darwin-universal.node");
1615
+ } catch (e) {
1616
+ loadErrors.push(e);
1617
+ }
1618
+ try {
1619
+ const binding = require2("@tursodatabase/sync-darwin-universal");
1620
+ const bindingPackageVersion = require2("@tursodatabase/sync-darwin-universal/package.json").version;
1621
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1622
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1623
+ }
1624
+ return binding;
1625
+ } catch (e) {
1626
+ loadErrors.push(e);
1627
+ }
1628
+ if (process.arch === "x64") {
1629
+ try {
1630
+ return require2("./sync.darwin-x64.node");
1631
+ } catch (e) {
1632
+ loadErrors.push(e);
1633
+ }
1634
+ try {
1635
+ const binding = require2("@tursodatabase/sync-darwin-x64");
1636
+ const bindingPackageVersion = require2("@tursodatabase/sync-darwin-x64/package.json").version;
1637
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1638
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1639
+ }
1640
+ return binding;
1641
+ } catch (e) {
1642
+ loadErrors.push(e);
1643
+ }
1644
+ } else if (process.arch === "arm64") {
1645
+ try {
1646
+ return require2("./sync.darwin-arm64.node");
1647
+ } catch (e) {
1648
+ loadErrors.push(e);
1649
+ }
1650
+ try {
1651
+ const binding = require2("@tursodatabase/sync-darwin-arm64");
1652
+ const bindingPackageVersion = require2("@tursodatabase/sync-darwin-arm64/package.json").version;
1653
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1654
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1655
+ }
1656
+ return binding;
1657
+ } catch (e) {
1658
+ loadErrors.push(e);
1659
+ }
1660
+ } else {
1661
+ loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`));
1662
+ }
1663
+ } else if (process.platform === "freebsd") {
1664
+ if (process.arch === "x64") {
1665
+ try {
1666
+ return require2("./sync.freebsd-x64.node");
1667
+ } catch (e) {
1668
+ loadErrors.push(e);
1669
+ }
1670
+ try {
1671
+ const binding = require2("@tursodatabase/sync-freebsd-x64");
1672
+ const bindingPackageVersion = require2("@tursodatabase/sync-freebsd-x64/package.json").version;
1673
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1674
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1675
+ }
1676
+ return binding;
1677
+ } catch (e) {
1678
+ loadErrors.push(e);
1679
+ }
1680
+ } else if (process.arch === "arm64") {
1681
+ try {
1682
+ return require2("./sync.freebsd-arm64.node");
1683
+ } catch (e) {
1684
+ loadErrors.push(e);
1685
+ }
1686
+ try {
1687
+ const binding = require2("@tursodatabase/sync-freebsd-arm64");
1688
+ const bindingPackageVersion = require2("@tursodatabase/sync-freebsd-arm64/package.json").version;
1689
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1690
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1691
+ }
1692
+ return binding;
1693
+ } catch (e) {
1694
+ loadErrors.push(e);
1695
+ }
1696
+ } else {
1697
+ loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`));
1698
+ }
1699
+ } else if (process.platform === "linux") {
1700
+ if (process.arch === "x64") {
1701
+ if (isMusl()) {
1702
+ try {
1703
+ return require2("./sync.linux-x64-musl.node");
1704
+ } catch (e) {
1705
+ loadErrors.push(e);
1706
+ }
1707
+ try {
1708
+ const binding = require2("@tursodatabase/sync-linux-x64-musl");
1709
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-x64-musl/package.json").version;
1710
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1711
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1712
+ }
1713
+ return binding;
1714
+ } catch (e) {
1715
+ loadErrors.push(e);
1716
+ }
1717
+ } else {
1718
+ try {
1719
+ return require2("./sync.linux-x64-gnu.node");
1720
+ } catch (e) {
1721
+ loadErrors.push(e);
1722
+ }
1723
+ try {
1724
+ const binding = require2("@tursodatabase/sync-linux-x64-gnu");
1725
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-x64-gnu/package.json").version;
1726
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1727
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1728
+ }
1729
+ return binding;
1730
+ } catch (e) {
1731
+ loadErrors.push(e);
1732
+ }
1733
+ }
1734
+ } else if (process.arch === "arm64") {
1735
+ if (isMusl()) {
1736
+ try {
1737
+ return require2("./sync.linux-arm64-musl.node");
1738
+ } catch (e) {
1739
+ loadErrors.push(e);
1740
+ }
1741
+ try {
1742
+ const binding = require2("@tursodatabase/sync-linux-arm64-musl");
1743
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-arm64-musl/package.json").version;
1744
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1745
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1746
+ }
1747
+ return binding;
1748
+ } catch (e) {
1749
+ loadErrors.push(e);
1750
+ }
1751
+ } else {
1752
+ try {
1753
+ return require2("./sync.linux-arm64-gnu.node");
1754
+ } catch (e) {
1755
+ loadErrors.push(e);
1756
+ }
1757
+ try {
1758
+ const binding = require2("@tursodatabase/sync-linux-arm64-gnu");
1759
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-arm64-gnu/package.json").version;
1760
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1761
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1762
+ }
1763
+ return binding;
1764
+ } catch (e) {
1765
+ loadErrors.push(e);
1766
+ }
1767
+ }
1768
+ } else if (process.arch === "arm") {
1769
+ if (isMusl()) {
1770
+ try {
1771
+ return require2("./sync.linux-arm-musleabihf.node");
1772
+ } catch (e) {
1773
+ loadErrors.push(e);
1774
+ }
1775
+ try {
1776
+ const binding = require2("@tursodatabase/sync-linux-arm-musleabihf");
1777
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-arm-musleabihf/package.json").version;
1778
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1779
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1780
+ }
1781
+ return binding;
1782
+ } catch (e) {
1783
+ loadErrors.push(e);
1784
+ }
1785
+ } else {
1786
+ try {
1787
+ return require2("./sync.linux-arm-gnueabihf.node");
1788
+ } catch (e) {
1789
+ loadErrors.push(e);
1790
+ }
1791
+ try {
1792
+ const binding = require2("@tursodatabase/sync-linux-arm-gnueabihf");
1793
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-arm-gnueabihf/package.json").version;
1794
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1795
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1796
+ }
1797
+ return binding;
1798
+ } catch (e) {
1799
+ loadErrors.push(e);
1800
+ }
1801
+ }
1802
+ } else if (process.arch === "riscv64") {
1803
+ if (isMusl()) {
1804
+ try {
1805
+ return require2("./sync.linux-riscv64-musl.node");
1806
+ } catch (e) {
1807
+ loadErrors.push(e);
1808
+ }
1809
+ try {
1810
+ const binding = require2("@tursodatabase/sync-linux-riscv64-musl");
1811
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-riscv64-musl/package.json").version;
1812
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1813
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1814
+ }
1815
+ return binding;
1816
+ } catch (e) {
1817
+ loadErrors.push(e);
1818
+ }
1819
+ } else {
1820
+ try {
1821
+ return require2("./sync.linux-riscv64-gnu.node");
1822
+ } catch (e) {
1823
+ loadErrors.push(e);
1824
+ }
1825
+ try {
1826
+ const binding = require2("@tursodatabase/sync-linux-riscv64-gnu");
1827
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-riscv64-gnu/package.json").version;
1828
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1829
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1830
+ }
1831
+ return binding;
1832
+ } catch (e) {
1833
+ loadErrors.push(e);
1834
+ }
1835
+ }
1836
+ } else if (process.arch === "ppc64") {
1837
+ try {
1838
+ return require2("./sync.linux-ppc64-gnu.node");
1839
+ } catch (e) {
1840
+ loadErrors.push(e);
1841
+ }
1842
+ try {
1843
+ const binding = require2("@tursodatabase/sync-linux-ppc64-gnu");
1844
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-ppc64-gnu/package.json").version;
1845
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1846
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1847
+ }
1848
+ return binding;
1849
+ } catch (e) {
1850
+ loadErrors.push(e);
1851
+ }
1852
+ } else if (process.arch === "s390x") {
1853
+ try {
1854
+ return require2("./sync.linux-s390x-gnu.node");
1855
+ } catch (e) {
1856
+ loadErrors.push(e);
1857
+ }
1858
+ try {
1859
+ const binding = require2("@tursodatabase/sync-linux-s390x-gnu");
1860
+ const bindingPackageVersion = require2("@tursodatabase/sync-linux-s390x-gnu/package.json").version;
1861
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1862
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1863
+ }
1864
+ return binding;
1865
+ } catch (e) {
1866
+ loadErrors.push(e);
1867
+ }
1868
+ } else {
1869
+ loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`));
1870
+ }
1871
+ } else if (process.platform === "openharmony") {
1872
+ if (process.arch === "arm64") {
1873
+ try {
1874
+ return require2("./sync.openharmony-arm64.node");
1875
+ } catch (e) {
1876
+ loadErrors.push(e);
1877
+ }
1878
+ try {
1879
+ const binding = require2("@tursodatabase/sync-openharmony-arm64");
1880
+ const bindingPackageVersion = require2("@tursodatabase/sync-openharmony-arm64/package.json").version;
1881
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1882
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1883
+ }
1884
+ return binding;
1885
+ } catch (e) {
1886
+ loadErrors.push(e);
1887
+ }
1888
+ } else if (process.arch === "x64") {
1889
+ try {
1890
+ return require2("./sync.openharmony-x64.node");
1891
+ } catch (e) {
1892
+ loadErrors.push(e);
1893
+ }
1894
+ try {
1895
+ const binding = require2("@tursodatabase/sync-openharmony-x64");
1896
+ const bindingPackageVersion = require2("@tursodatabase/sync-openharmony-x64/package.json").version;
1897
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1898
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1899
+ }
1900
+ return binding;
1901
+ } catch (e) {
1902
+ loadErrors.push(e);
1903
+ }
1904
+ } else if (process.arch === "arm") {
1905
+ try {
1906
+ return require2("./sync.openharmony-arm.node");
1907
+ } catch (e) {
1908
+ loadErrors.push(e);
1909
+ }
1910
+ try {
1911
+ const binding = require2("@tursodatabase/sync-openharmony-arm");
1912
+ const bindingPackageVersion = require2("@tursodatabase/sync-openharmony-arm/package.json").version;
1913
+ if (bindingPackageVersion !== "0.6.0-pre.22" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
1914
+ throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.22 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
1915
+ }
1916
+ return binding;
1917
+ } catch (e) {
1918
+ loadErrors.push(e);
1919
+ }
1920
+ } else {
1921
+ loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`));
1922
+ }
1923
+ } else {
1924
+ loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`));
1925
+ }
1926
+ }
1927
+ var require2, __dirname2, readFileSync, nativeBinding = null, loadErrors, isMusl = () => {
1928
+ let musl = false;
1929
+ if (process.platform === "linux") {
1930
+ musl = isMuslFromFilesystem();
1931
+ if (musl === null) {
1932
+ musl = isMuslFromReport();
1933
+ }
1934
+ if (musl === null) {
1935
+ musl = isMuslFromChildProcess();
1936
+ }
1937
+ }
1938
+ return musl;
1939
+ }, isFileMusl = (f) => f.includes("libc.musl-") || f.includes("ld-musl-"), isMuslFromFilesystem = () => {
1940
+ try {
1941
+ return readFileSync("/usr/bin/ldd", "utf-8").includes("musl");
1942
+ } catch {
1943
+ return null;
1944
+ }
1945
+ }, isMuslFromReport = () => {
1946
+ let report = null;
1947
+ if (typeof process.report?.getReport === "function") {
1948
+ process.report.excludeNetwork = true;
1949
+ report = process.report.getReport();
1950
+ }
1951
+ if (!report) {
1952
+ return null;
1953
+ }
1954
+ if (report.header && report.header.glibcVersionRuntime) {
1955
+ return false;
1956
+ }
1957
+ if (Array.isArray(report.sharedObjects)) {
1958
+ if (report.sharedObjects.some(isFileMusl)) {
1959
+ return true;
1960
+ }
1961
+ }
1962
+ return false;
1963
+ }, isMuslFromChildProcess = () => {
1964
+ try {
1965
+ return require2("child_process").execSync("ldd --version", { encoding: "utf8" }).includes("musl");
1966
+ } catch (e) {
1967
+ return false;
1968
+ }
1969
+ }, BatchExecutor, Database3, Statement4, EncryptionCipher, GeneratorHolder, JsDataCompletion, JsProtocolIo, JsProtocolRequestBytes, SyncEngine, SyncEngineChanges, DatabaseChangeTypeJs, SyncEngineProtocolVersion;
1970
+ var init_sync = __esm(() => {
1971
+ require2 = createRequire(import.meta.url);
1972
+ __dirname2 = new URL(".", import.meta.url).pathname;
1973
+ ({ readFileSync } = require2("node:fs"));
1974
+ loadErrors = [];
1975
+ nativeBinding = requireNative();
1976
+ if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) {
1977
+ try {
1978
+ nativeBinding = require2("./sync.wasi.cjs");
1979
+ } catch (err) {
1980
+ if (process.env.NAPI_RS_FORCE_WASI) {
1981
+ loadErrors.push(err);
1982
+ }
1983
+ }
1984
+ if (!nativeBinding) {
1985
+ try {
1986
+ nativeBinding = require2("@tursodatabase/sync-wasm32-wasi");
1987
+ } catch (err) {
1988
+ if (process.env.NAPI_RS_FORCE_WASI) {
1989
+ loadErrors.push(err);
1990
+ }
1991
+ }
1992
+ }
1993
+ }
1994
+ if (!nativeBinding) {
1995
+ if (loadErrors.length > 0) {
1996
+ throw new Error(`Cannot find native binding. ` + `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + "Please try `npm i` again after removing both package-lock.json and node_modules directory.", { cause: loadErrors });
1997
+ }
1998
+ throw new Error(`Failed to load native binding`);
1999
+ }
2000
+ ({ BatchExecutor, Database: Database3, Statement: Statement4, EncryptionCipher, GeneratorHolder, JsDataCompletion, JsProtocolIo, JsProtocolRequestBytes, SyncEngine, SyncEngineChanges, DatabaseChangeTypeJs, SyncEngineProtocolVersion } = nativeBinding);
2001
+ });
2002
+
2003
+ // node_modules/@tursodatabase/sync/dist/promise.js
2004
+ var exports_promise = {};
2005
+ __export(exports_promise, {
2006
+ retryFetch: () => retryFetch,
2007
+ connect: () => connect2,
2008
+ Database: () => Database4
2009
+ });
2010
+ import { promises } from "fs";
2011
+ function memoryIO2() {
2012
+ let values = new Map;
2013
+ return {
2014
+ async read(path) {
2015
+ return values.get(path);
2016
+ },
2017
+ async write(path, data) {
2018
+ values.set(path, data);
2019
+ }
2020
+ };
2021
+ }
2022
+ function resolveUrl(url) {
2023
+ if (typeof url === "function") {
2024
+ const resolved = url();
2025
+ if (resolved == null) {
2026
+ throw new Error("remoteWritesExperimental requires a non-null URL");
2027
+ }
2028
+ return resolved;
2029
+ }
2030
+ return url;
2031
+ }
2032
+ async function connect2(opts) {
2033
+ const db = new Database4(opts);
2034
+ await db.connect();
2035
+ return db;
2036
+ }
2037
+ var NodeIO, Database4;
2038
+ var init_promise2 = __esm(() => {
2039
+ init_dist();
2040
+ init_dist3();
2041
+ init_sync();
2042
+ init_dist3();
2043
+ NodeIO = {
2044
+ async read(path) {
2045
+ try {
2046
+ return await promises.readFile(path);
2047
+ } catch (error) {
2048
+ if (error.code === "ENOENT") {
2049
+ return null;
2050
+ }
2051
+ throw error;
2052
+ }
2053
+ },
2054
+ async write(path, data) {
2055
+ const unix = Math.floor(Date.now() / 1000);
2056
+ const nonce = Math.floor(Math.random() * 1e9);
2057
+ const tmp = `${path}.tmp.${unix}.${nonce}`;
2058
+ await promises.writeFile(tmp, new Uint8Array(data));
2059
+ try {
2060
+ await promises.rename(tmp, path);
2061
+ } catch (err) {
2062
+ await promises.unlink(tmp);
2063
+ throw err;
2064
+ }
2065
+ }
2066
+ };
2067
+ Database4 = class Database4 extends Database {
2068
+ #engine;
2069
+ #guards = null;
2070
+ #runner = null;
2071
+ #remoteWriter = null;
2072
+ #db;
2073
+ constructor(opts) {
2074
+ if (opts.url == null) {
2075
+ const db2 = new Database3(opts.path, { tracing: opts.tracing });
2076
+ super(db2);
2077
+ this.#db = db2;
2078
+ this.#engine = null;
2079
+ return;
2080
+ }
2081
+ let partialSyncOpts = undefined;
2082
+ if (opts.partialSyncExperimental != null) {
2083
+ switch (opts.partialSyncExperimental.bootstrapStrategy.kind) {
2084
+ case "prefix":
2085
+ partialSyncOpts = {
2086
+ bootstrapStrategy: { type: "Prefix", length: opts.partialSyncExperimental.bootstrapStrategy.length },
2087
+ segmentSize: opts.partialSyncExperimental.segmentSize,
2088
+ prefetch: opts.partialSyncExperimental.prefetch
2089
+ };
2090
+ break;
2091
+ case "query":
2092
+ partialSyncOpts = {
2093
+ bootstrapStrategy: { type: "Query", query: opts.partialSyncExperimental.bootstrapStrategy.query },
2094
+ segmentSize: opts.partialSyncExperimental.segmentSize,
2095
+ prefetch: opts.partialSyncExperimental.prefetch
2096
+ };
2097
+ break;
2098
+ }
2099
+ }
2100
+ const engine = new SyncEngine({
2101
+ path: opts.path,
2102
+ clientName: opts.clientName,
2103
+ useTransform: opts.transform != null,
2104
+ protocolVersion: "v1",
2105
+ longPollTimeoutMs: opts.longPollTimeoutMs,
2106
+ tracing: opts.tracing,
2107
+ bootstrapIfEmpty: typeof opts.url != "function" || opts.url() != null,
2108
+ remoteEncryptionCipher: opts.remoteEncryption?.cipher,
2109
+ remoteEncryptionKey: opts.remoteEncryption?.key,
2110
+ partialSyncOpts,
2111
+ pushOperationsThreshold: opts.pushOperationsThreshold,
2112
+ pullBytesThreshold: opts.pullBytesThreshold
2113
+ });
2114
+ let headers;
2115
+ if (typeof opts.authToken == "function") {
2116
+ const authToken = opts.authToken;
2117
+ headers = async () => ({
2118
+ ...opts.authToken != null && { Authorization: `Bearer ${await authToken()}` },
2119
+ ...opts.remoteEncryption != null && {
2120
+ "x-turso-encryption-key": opts.remoteEncryption.key,
2121
+ "x-turso-encryption-cipher": opts.remoteEncryption.cipher
2122
+ }
2123
+ });
2124
+ } else {
2125
+ const authToken = opts.authToken;
2126
+ headers = {
2127
+ ...opts.authToken != null && { Authorization: `Bearer ${authToken}` },
2128
+ ...opts.remoteEncryption != null && {
2129
+ "x-turso-encryption-key": opts.remoteEncryption.key,
2130
+ "x-turso-encryption-cipher": opts.remoteEncryption.cipher
2131
+ }
2132
+ };
2133
+ }
2134
+ const runOpts = {
2135
+ url: opts.url,
2136
+ headers,
2137
+ preemptionMs: 1,
2138
+ transform: opts.transform,
2139
+ fetch: opts.fetch
2140
+ };
2141
+ const db = engine.db();
2142
+ const memory = db.memory;
2143
+ const io = memory ? memoryIO2() : NodeIO;
2144
+ const run2 = runner(runOpts, io, engine);
2145
+ super(engine.db(), () => run2.wait());
2146
+ this.#db = engine.db();
2147
+ this.#runner = run2;
2148
+ this.#engine = engine;
2149
+ this.#guards = new SyncEngineGuards;
2150
+ if (opts.remoteWritesExperimental && opts.url) {
2151
+ const url = resolveUrl(opts.url);
2152
+ this.#remoteWriter = new RemoteWriter({
2153
+ url,
2154
+ authToken: opts.authToken,
2155
+ remoteEncryptionKey: opts.remoteEncryption?.key
2156
+ });
2157
+ }
2158
+ }
2159
+ async connect() {
2160
+ if (this.connected) {
2161
+ return;
2162
+ } else if (this.#engine == null) {
2163
+ await super.connect();
2164
+ } else {
2165
+ await run(this.#runner, this.#engine.connect());
2166
+ }
2167
+ this.connected = true;
2168
+ }
2169
+ async pull() {
2170
+ if (this.#engine == null) {
2171
+ throw new Error("sync is disabled as database was opened without sync support");
2172
+ }
2173
+ const changes = await this.#guards.wait(async () => await run(this.#runner, this.#engine.wait()));
2174
+ if (changes.empty()) {
2175
+ return false;
2176
+ }
2177
+ await this.#guards.apply(async () => await run(this.#runner, this.#engine.apply(changes)));
2178
+ return true;
2179
+ }
2180
+ async push() {
2181
+ if (this.#engine == null) {
2182
+ throw new Error("sync is disabled as database was opened without sync support");
2183
+ }
2184
+ await this.#guards.push(async () => await run(this.#runner, this.#engine.push()));
2185
+ }
2186
+ async checkpoint() {
2187
+ if (this.#engine == null) {
2188
+ throw new Error("sync is disabled as database was opened without sync support");
2189
+ }
2190
+ await this.#guards.checkpoint(async () => await run(this.#runner, this.#engine.checkpoint()));
2191
+ }
2192
+ async stats() {
2193
+ if (this.#engine == null) {
2194
+ throw new Error("sync is disabled as database was opened without sync support");
2195
+ }
2196
+ return await run(this.#runner, this.#engine.stats());
2197
+ }
2198
+ async exec(sql) {
2199
+ if (!this.#remoteWriter)
2200
+ return super.exec(sql);
2201
+ const category = this.#db.classifySql(sql);
2202
+ if (this.#remoteWriter.isInTransaction) {
2203
+ const { shouldPull: shouldPull2 } = await this.#remoteWriter.execRemote(sql, category);
2204
+ if (shouldPull2)
2205
+ await this.pull();
2206
+ return;
2207
+ }
2208
+ if (category === "read")
2209
+ return super.exec(sql);
2210
+ const { shouldPull } = await this.#remoteWriter.execRemote(sql, category);
2211
+ if (shouldPull)
2212
+ await this.pull();
2213
+ }
2214
+ async prepare(sql) {
2215
+ const localStmt = await super.prepare(sql);
2216
+ if (!this.#remoteWriter) {
2217
+ return localStmt;
2218
+ }
2219
+ const category = this.#db.classifySql(sql);
2220
+ const isReadonly = category === "read";
2221
+ return new RemoteWriteStatement(localStmt, sql, isReadonly, this.#remoteWriter, () => this.pull());
2222
+ }
2223
+ transaction(fn) {
2224
+ if (typeof fn !== "function")
2225
+ throw new TypeError("Expected first argument to be a function");
2226
+ if (!this.#remoteWriter) {
2227
+ return super.transaction(fn);
2228
+ }
2229
+ const db = this;
2230
+ const remoteWriter = this.#remoteWriter;
2231
+ const wrapTxn = (mode) => {
2232
+ return async (...bindParameters) => {
2233
+ await remoteWriter.beginTransaction(mode);
2234
+ try {
2235
+ const result = await fn(...bindParameters);
2236
+ await remoteWriter.commitTransaction();
2237
+ await db.pull();
2238
+ return result;
2239
+ } catch (err) {
2240
+ await remoteWriter.rollbackTransaction();
2241
+ throw err;
2242
+ }
2243
+ };
2244
+ };
2245
+ const properties = {
2246
+ default: { value: wrapTxn("") },
2247
+ deferred: { value: wrapTxn("DEFERRED") },
2248
+ immediate: { value: wrapTxn("IMMEDIATE") },
2249
+ exclusive: { value: wrapTxn("EXCLUSIVE") },
2250
+ database: { value: this, enumerable: true }
2251
+ };
2252
+ Object.defineProperties(properties.default.value, properties);
2253
+ Object.defineProperties(properties.deferred.value, properties);
2254
+ Object.defineProperties(properties.immediate.value, properties);
2255
+ Object.defineProperties(properties.exclusive.value, properties);
2256
+ return properties.default.value;
2257
+ }
2258
+ async close() {
2259
+ if (this.#remoteWriter) {
2260
+ await this.#remoteWriter.close();
2261
+ }
2262
+ await super.close();
2263
+ if (this.#engine != null) {
2264
+ this.#engine.close();
2265
+ }
2266
+ }
2267
+ };
2268
+ });
2269
+
2270
+ // src/query/conditions.ts
2271
+ function isColumnDef(value) {
2272
+ return value !== null && typeof value === "object" && "__internal" in value;
2273
+ }
2274
+ function eq(left, valueOrColumn) {
2275
+ if (isColumnDef(valueOrColumn)) {
2276
+ return { type: "eqColumn", left, right: valueOrColumn };
2277
+ }
2278
+ return { type: "eq", column: left, value: valueOrColumn };
2279
+ }
2280
+ function and(...conditions) {
2281
+ return { type: "and", conditions };
2282
+ }
2283
+ function or(...conditions) {
2284
+ return { type: "or", conditions };
2285
+ }
2286
+ function isIn(column, values) {
2287
+ return { type: "in", column, values };
2288
+ }
2289
+ function isNotIn(column, values) {
2290
+ return { type: "notIn", column, values };
2291
+ }
2292
+ function isNull(column) {
2293
+ return { type: "isNull", column };
2294
+ }
2295
+ function isNotNull(column) {
2296
+ return { type: "isNotNull", column };
2297
+ }
2298
+ function like(column, pattern) {
2299
+ return { type: "like", column, pattern };
2300
+ }
2301
+ function glob(column, pattern) {
2302
+ return { type: "glob", column, pattern };
2303
+ }
2304
+ function between(column, low, high) {
2305
+ return { type: "between", column, low, high };
2306
+ }
2307
+ function gt(column, value) {
2308
+ return { type: "gt", column, value };
2309
+ }
2310
+ function gte(column, value) {
2311
+ return { type: "gte", column, value };
2312
+ }
2313
+ function lt(column, value) {
2314
+ return { type: "lt", column, value };
2315
+ }
2316
+ function lte(column, value) {
2317
+ return { type: "lte", column, value };
2318
+ }
2319
+ function neq(column, value) {
2320
+ return { type: "neq", column, value };
2321
+ }
2322
+ function compileCondition(cond, params) {
2323
+ switch (cond.type) {
2324
+ case "eq":
2325
+ params.push(cond.column.__internal.encode(cond.value));
2326
+ return `${cond.column.name} = ?`;
2327
+ case "eqColumn": {
2328
+ const leftName = cond.left.__internal.tableName ? `${cond.left.__internal.tableName}.${cond.left.name}` : cond.left.name;
2329
+ const rightName = cond.right.__internal.tableName ? `${cond.right.__internal.tableName}.${cond.right.name}` : cond.right.name;
2330
+ return `${leftName} = ${rightName}`;
2331
+ }
2332
+ case "in": {
2333
+ const encoded = cond.values.map((v) => cond.column.__internal.encode(v));
2334
+ params.push(...encoded);
2335
+ const placeholders = encoded.map(() => "?").join(", ");
2336
+ return `${cond.column.name} IN (${placeholders})`;
2337
+ }
2338
+ case "notIn": {
2339
+ const encoded = cond.values.map((v) => cond.column.__internal.encode(v));
2340
+ params.push(...encoded);
2341
+ const placeholders = encoded.map(() => "?").join(", ");
2342
+ return `${cond.column.name} NOT IN (${placeholders})`;
2343
+ }
2344
+ case "isNull":
2345
+ return `${cond.column.name} IS NULL`;
2346
+ case "isNotNull":
2347
+ return `${cond.column.name} IS NOT NULL`;
2348
+ case "like":
2349
+ params.push(cond.pattern);
2350
+ return `${cond.column.name} LIKE ?`;
2351
+ case "glob":
2352
+ params.push(cond.pattern);
2353
+ return `${cond.column.name} GLOB ?`;
2354
+ case "between":
2355
+ params.push(cond.column.__internal.encode(cond.low));
2356
+ params.push(cond.column.__internal.encode(cond.high));
2357
+ return `${cond.column.name} BETWEEN ? AND ?`;
2358
+ case "gt":
2359
+ params.push(cond.column.__internal.encode(cond.value));
2360
+ return `${cond.column.name} > ?`;
2361
+ case "gte":
2362
+ params.push(cond.column.__internal.encode(cond.value));
2363
+ return `${cond.column.name} >= ?`;
2364
+ case "lt":
2365
+ params.push(cond.column.__internal.encode(cond.value));
2366
+ return `${cond.column.name} < ?`;
2367
+ case "lte":
2368
+ params.push(cond.column.__internal.encode(cond.value));
2369
+ return `${cond.column.name} <= ?`;
2370
+ case "neq":
2371
+ params.push(cond.column.__internal.encode(cond.value));
2372
+ return `${cond.column.name} != ?`;
2373
+ case "and":
2374
+ return cond.conditions.map((c) => compileCondition(c, params)).join(" AND ");
2375
+ case "or":
2376
+ return `(${cond.conditions.map((c) => compileCondition(c, params)).join(" OR ")})`;
2377
+ }
2378
+ }
2379
+ function compileConditions(conditions, params) {
2380
+ if (conditions.length === 0)
2381
+ return "1=1";
2382
+ return conditions.map((c) => compileCondition(c, params)).join(" AND ");
2383
+ }
2384
+
2385
+ // src/errors.ts
2386
+ var FlintError, FlintValidationError, FlintQueryError;
2387
+ var init_errors = __esm(() => {
2388
+ FlintError = class FlintError extends Error {
2389
+ constructor(message) {
2390
+ super(message);
2391
+ this.name = "FlintError";
2392
+ }
2393
+ };
2394
+ FlintValidationError = class FlintValidationError extends FlintError {
2395
+ constructor(message) {
2396
+ super(message);
2397
+ this.name = "FlintValidationError";
2398
+ }
2399
+ };
2400
+ FlintQueryError = class FlintQueryError extends FlintError {
2401
+ originalError;
2402
+ constructor(message, originalError) {
2403
+ super(message);
2404
+ this.name = "FlintQueryError";
2405
+ this.originalError = originalError;
2406
+ }
2407
+ };
2408
+ });
2409
+
2410
+ // src/query/builder.ts
2411
+ function getCol(tbl, key) {
2412
+ const col = tbl[key];
2413
+ if (!col)
2414
+ throw new FlintValidationError(`Column "${key}" not found in table`);
2415
+ return col;
2416
+ }
2417
+ function columnEntries(tbl) {
2418
+ return Object.entries(tbl).filter(([k]) => k !== "_" && k !== "__indexes");
2419
+ }
2420
+ function decodeRow(raw, tbl) {
2421
+ const out = {};
2422
+ for (const [key, col] of columnEntries(tbl)) {
2423
+ out[key] = col.__internal.decode(raw[col.name]);
2424
+ }
2425
+ return out;
2426
+ }
2427
+ function decodeSelectedRow(raw, tbl, keys) {
2428
+ const out = {};
2429
+ for (const key of keys) {
2430
+ const col = getCol(tbl, key);
2431
+ out[key] = col.__internal.decode(raw[col.name]);
2432
+ }
2433
+ return out;
2434
+ }
2435
+ function findPKKey(tbl) {
2436
+ for (const [key, col] of columnEntries(tbl)) {
2437
+ if (col.__internal.isPrimaryKey)
2438
+ return key;
2439
+ }
2440
+ throw new FlintValidationError("Table has no primary key column");
2441
+ }
2442
+ function resolveForeignKeyCondition(parent, parentName, child, childName) {
2443
+ for (const [, col] of columnEntries(child)) {
2444
+ if (col.__internal.referencesTable === parentName && col.__internal.referencesColumn) {
2445
+ const parentCol = getCol(parent, col.__internal.referencesColumn);
2446
+ if (parentCol) {
2447
+ return eq(parentCol, col);
2448
+ }
2449
+ }
2450
+ }
2451
+ throw new FlintValidationError(`No foreign key reference found from "${childName}" to "${parentName}". Use .references() on the child table or provide an explicit condition.`);
2452
+ }
2453
+ function extractColumns(cond) {
2454
+ switch (cond.type) {
2455
+ case "eq":
2456
+ return [cond.column];
2457
+ case "eqColumn":
2458
+ return [cond.left, cond.right];
2459
+ case "in":
2460
+ case "notIn":
2461
+ case "isNull":
2462
+ case "isNotNull":
2463
+ case "like":
2464
+ case "glob":
2465
+ case "between":
2466
+ return [cond.column];
2467
+ case "and":
2468
+ case "or":
2469
+ return cond.conditions.flatMap(extractColumns);
2470
+ default:
2471
+ return [];
2472
+ }
2473
+ }
2474
+ function validateColumnOwnership(conditions, allowedTables, context) {
2475
+ const allowedColumns = new Set(allowedTables.flatMap((t) => columnEntries(t).map(([, c]) => c)));
2476
+ for (const cond of conditions) {
2477
+ const cols = extractColumns(cond);
2478
+ for (const col of cols) {
2479
+ if (!allowedColumns.has(col)) {
2480
+ throw new FlintValidationError(`Column "${col.name}" does not belong to ${context}. ` + `Check that you're using a column from the queried table, not a different table.`);
2481
+ }
2482
+ }
2483
+ }
2484
+ }
2485
+ function resolveColumns(table, selectedColumns, prefix) {
2486
+ if (selectedColumns) {
2487
+ return selectedColumns.map((k) => {
2488
+ const name = getCol(table, k).name;
2489
+ return prefix ? `${prefix}.${name}` : name;
2490
+ }).join(", ");
2491
+ }
2492
+ const entries = columnEntries(table);
2493
+ return entries.map(([, c]) => prefix ? `${prefix}.${c.name}` : c.name).join(", ");
2494
+ }
2495
+
2496
+ class SelectFromBuilder {
2497
+ #executor;
2498
+ #conditions;
2499
+ constructor(executor, conditions = []) {
2500
+ this.#executor = executor;
2501
+ this.#conditions = conditions;
2502
+ }
2503
+ from(table) {
2504
+ return new SelectBuilder(this.#executor, table._.name, table, this.#conditions);
2505
+ }
2506
+ }
2507
+
2508
+ class SelectBuilder {
2509
+ #executor;
2510
+ #tableName;
2511
+ #table;
2512
+ #conditions;
2513
+ #selectedColumns;
2514
+ #orderByClauses;
2515
+ #limitValue;
2516
+ #offsetValue;
2517
+ #distinct;
2518
+ constructor(executor, tableName, table, conditions = [], selectedColumns = null, orderByClauses = [], limitValue = null, offsetValue = null, distinct = false) {
2519
+ this.#executor = executor;
2520
+ this.#tableName = tableName;
2521
+ this.#table = table;
2522
+ this.#conditions = conditions;
2523
+ this.#selectedColumns = selectedColumns;
2524
+ this.#orderByClauses = orderByClauses;
2525
+ this.#limitValue = limitValue;
2526
+ this.#offsetValue = offsetValue;
2527
+ this.#distinct = distinct;
2528
+ }
2529
+ where(condition) {
2530
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct);
2531
+ }
2532
+ columns(keys) {
2533
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, keys, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct);
2534
+ }
2535
+ single() {
2536
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
2537
+ }
2538
+ distinct() {
2539
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, true);
2540
+ }
2541
+ orderBy(key, direction = "asc") {
2542
+ const column = getCol(this.#table, key);
2543
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#limitValue, this.#offsetValue, this.#distinct);
2544
+ }
2545
+ limit(n) {
2546
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue, this.#distinct);
2547
+ }
2548
+ offset(n) {
2549
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n, this.#distinct);
2550
+ }
2551
+ toSQL() {
2552
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
2553
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
2554
+ const params = [];
2555
+ const distinct = this.#distinct ? "DISTINCT " : "";
2556
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
2557
+ const where = compileConditions(this.#conditions, params);
2558
+ if (where !== "1=1")
2559
+ sql += ` WHERE ${where}`;
2560
+ if (this.#orderByClauses.length > 0) {
2561
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
2562
+ sql += ` ORDER BY ${orderClauses}`;
2563
+ }
2564
+ if (this.#limitValue !== null)
2565
+ sql += ` LIMIT ${this.#limitValue}`;
2566
+ if (this.#offsetValue !== null)
2567
+ sql += ` OFFSET ${this.#offsetValue}`;
2568
+ return { sql, params };
2569
+ }
2570
+ async execute() {
2571
+ const { sql, params } = this.toSQL();
2572
+ try {
2573
+ const rows = await this.#executor.all(sql, params);
2574
+ const records = rows;
2575
+ if (this.#selectedColumns) {
2576
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#selectedColumns));
2577
+ }
2578
+ return records.map((r) => decodeRow(r, this.#table));
2579
+ } catch (e) {
2580
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
2581
+ }
2582
+ }
2583
+ }
2584
+
2585
+ class NarrowedSelectBuilder {
2586
+ #executor;
2587
+ #tableName;
2588
+ #table;
2589
+ #conditions;
2590
+ #selectedColumns;
2591
+ #orderByClauses;
2592
+ #limitValue;
2593
+ #offsetValue;
2594
+ #distinct;
2595
+ constructor(executor, tableName, table, conditions, selectedColumns, orderByClauses, limitValue, offsetValue, distinct) {
2596
+ this.#executor = executor;
2597
+ this.#tableName = tableName;
2598
+ this.#table = table;
2599
+ this.#conditions = conditions;
2600
+ this.#selectedColumns = selectedColumns;
2601
+ this.#orderByClauses = orderByClauses;
2602
+ this.#limitValue = limitValue;
2603
+ this.#offsetValue = offsetValue;
2604
+ this.#distinct = distinct;
2605
+ }
2606
+ where(condition) {
2607
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct);
2608
+ }
2609
+ distinct() {
2610
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, true);
2611
+ }
2612
+ single() {
2613
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
2614
+ }
2615
+ orderBy(key, direction = "asc") {
2616
+ const column = getCol(this.#table, key);
2617
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#limitValue, this.#offsetValue, this.#distinct);
2618
+ }
2619
+ limit(n) {
2620
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue, this.#distinct);
2621
+ }
2622
+ offset(n) {
2623
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n, this.#distinct);
2624
+ }
2625
+ toSQL() {
2626
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
2627
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
2628
+ const params = [];
2629
+ const distinct = this.#distinct ? "DISTINCT " : "";
2630
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
2631
+ const where = compileConditions(this.#conditions, params);
2632
+ if (where !== "1=1")
2633
+ sql += ` WHERE ${where}`;
2634
+ if (this.#orderByClauses.length > 0) {
2635
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
2636
+ sql += ` ORDER BY ${orderClauses}`;
2637
+ }
2638
+ if (this.#limitValue !== null)
2639
+ sql += ` LIMIT ${this.#limitValue}`;
2640
+ if (this.#offsetValue !== null)
2641
+ sql += ` OFFSET ${this.#offsetValue}`;
2642
+ return { sql, params };
2643
+ }
2644
+ async execute() {
2645
+ const { sql, params } = this.toSQL();
2646
+ try {
2647
+ const rows = await this.#executor.all(sql, params);
2648
+ return rows.map((r) => decodeSelectedRow(r, this.#table, this.#selectedColumns));
2649
+ } catch (e) {
2650
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
2651
+ }
2652
+ }
2653
+ }
2654
+
2655
+ class SingleSelectBuilder {
2656
+ #executor;
2657
+ #tableName;
2658
+ #table;
2659
+ #conditions;
2660
+ #selectedColumns;
2661
+ #orderByClauses;
2662
+ #offsetValue;
2663
+ #distinct;
2664
+ constructor(executor, tableName, table, conditions, selectedColumns = null, orderByClauses = [], offsetValue = null, distinct = false) {
2665
+ this.#executor = executor;
2666
+ this.#tableName = tableName;
2667
+ this.#table = table;
2668
+ this.#conditions = conditions;
2669
+ this.#selectedColumns = selectedColumns;
2670
+ this.#orderByClauses = orderByClauses;
2671
+ this.#offsetValue = offsetValue;
2672
+ this.#distinct = distinct;
2673
+ }
2674
+ where(condition) {
2675
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
2676
+ }
2677
+ orderBy(key, direction = "asc") {
2678
+ const column = getCol(this.#table, key);
2679
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#offsetValue, this.#distinct);
2680
+ }
2681
+ offset(n) {
2682
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#distinct);
2683
+ }
2684
+ toSQL() {
2685
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
2686
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
2687
+ const params = [];
2688
+ const distinct = this.#distinct ? "DISTINCT " : "";
2689
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
2690
+ const where = compileConditions(this.#conditions, params);
2691
+ if (where !== "1=1")
2692
+ sql += ` WHERE ${where}`;
2693
+ if (this.#orderByClauses.length > 0) {
2694
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
2695
+ sql += ` ORDER BY ${orderClauses}`;
2696
+ }
2697
+ sql += " LIMIT 1";
2698
+ if (this.#offsetValue !== null)
2699
+ sql += ` OFFSET ${this.#offsetValue}`;
2700
+ return { sql, params };
2701
+ }
2702
+ async execute() {
2703
+ const { sql, params } = this.toSQL();
2704
+ try {
2705
+ const row = await this.#executor.get(sql, params);
2706
+ if (!row)
2707
+ return null;
2708
+ const record = row;
2709
+ if (this.#selectedColumns) {
2710
+ return decodeSelectedRow(record, this.#table, this.#selectedColumns);
2711
+ }
2712
+ return decodeRow(record, this.#table);
2713
+ } catch (e) {
2714
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
2715
+ }
2716
+ }
2717
+ }
2718
+
2719
+ class NarrowedSingleSelectBuilder {
2720
+ #executor;
2721
+ #tableName;
2722
+ #table;
2723
+ #conditions;
2724
+ #selectedColumns;
2725
+ #orderByClauses;
2726
+ #offsetValue;
2727
+ #distinct;
2728
+ constructor(executor, tableName, table, conditions, selectedColumns, orderByClauses, offsetValue, distinct) {
2729
+ this.#executor = executor;
2730
+ this.#tableName = tableName;
2731
+ this.#table = table;
2732
+ this.#conditions = conditions;
2733
+ this.#selectedColumns = selectedColumns;
2734
+ this.#orderByClauses = orderByClauses;
2735
+ this.#offsetValue = offsetValue;
2736
+ this.#distinct = distinct;
2737
+ }
2738
+ where(condition) {
2739
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
2740
+ }
2741
+ orderBy(key, direction = "asc") {
2742
+ const column = getCol(this.#table, key);
2743
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#offsetValue, this.#distinct);
2744
+ }
2745
+ offset(n) {
2746
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#distinct);
2747
+ }
2748
+ toSQL() {
2749
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
2750
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
2751
+ const params = [];
2752
+ const distinct = this.#distinct ? "DISTINCT " : "";
2753
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
2754
+ const where = compileConditions(this.#conditions, params);
2755
+ if (where !== "1=1")
2756
+ sql += ` WHERE ${where}`;
2757
+ if (this.#orderByClauses.length > 0) {
2758
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
2759
+ sql += ` ORDER BY ${orderClauses}`;
2760
+ }
2761
+ sql += " LIMIT 1";
2762
+ if (this.#offsetValue !== null)
2763
+ sql += ` OFFSET ${this.#offsetValue}`;
2764
+ return { sql, params };
2765
+ }
2766
+ async execute() {
2767
+ const { sql, params } = this.toSQL();
2768
+ try {
2769
+ const row = await this.#executor.get(sql, params);
2770
+ if (!row)
2771
+ return null;
2772
+ return decodeSelectedRow(row, this.#table, this.#selectedColumns);
2773
+ } catch (e) {
2774
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
2775
+ }
2776
+ }
2777
+ }
2778
+
2779
+ class JoinStage1 {
2780
+ #executor;
2781
+ #parent;
2782
+ #parentName;
2783
+ #joinType;
2784
+ constructor(executor, parent, parentName, joinType) {
2785
+ this.#executor = executor;
2786
+ this.#parent = parent;
2787
+ this.#parentName = parentName;
2788
+ this.#joinType = joinType;
2789
+ }
2790
+ on(child, condition) {
2791
+ const childName = child._.name;
2792
+ const resolvedCondition = condition ?? resolveForeignKeyCondition(this.#parent, this.#parentName, child, childName);
2793
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, [{ table: child, name: childName, condition: resolvedCondition }], this.#joinType);
2794
+ }
2795
+ }
2796
+
2797
+ class JoinBuilderImpl {
2798
+ #executor;
2799
+ #parent;
2800
+ #parentName;
2801
+ #joins;
2802
+ #joinType;
2803
+ #conditions;
2804
+ #selectedColumns;
2805
+ #orderByClauses;
2806
+ #limitValue;
2807
+ #offsetValue;
2808
+ constructor(executor, parent, parentName, joins, joinType, conditions = [], selectedColumns = null, orderByClauses = [], limitValue = null, offsetValue = null) {
2809
+ this.#executor = executor;
2810
+ this.#parent = parent;
2811
+ this.#parentName = parentName;
2812
+ this.#joins = joins;
2813
+ this.#joinType = joinType;
2814
+ this.#conditions = conditions;
2815
+ this.#selectedColumns = selectedColumns;
2816
+ this.#orderByClauses = orderByClauses;
2817
+ this.#limitValue = limitValue;
2818
+ this.#offsetValue = offsetValue;
2819
+ }
2820
+ on(child, condition) {
2821
+ const childName = child._.name;
2822
+ const resolvedCondition = condition ?? resolveForeignKeyCondition(this.#parent, this.#parentName, child, childName);
2823
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, [...this.#joins, { table: child, name: childName, condition: resolvedCondition }], this.#joinType, this.#conditions, this.#selectedColumns);
2824
+ }
2825
+ where(condition) {
2826
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, [...this.#conditions, condition], this.#selectedColumns);
2827
+ }
2828
+ columns(keys) {
2829
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, keys, this.#orderByClauses, this.#limitValue, this.#offsetValue);
2830
+ }
2831
+ orderBy(key, direction = "asc") {
2832
+ const column = getCol(this.#parent, key);
2833
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#limitValue, this.#offsetValue);
2834
+ }
2835
+ limit(n) {
2836
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue);
2837
+ }
2838
+ offset(n) {
2839
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n);
2840
+ }
2841
+ single() {
2842
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue);
2843
+ }
2844
+ toSQL() {
2845
+ const allowedTables = [this.#parent, ...this.#joins.map((j) => j.table)];
2846
+ validateColumnOwnership(this.#conditions, allowedTables, `SELECT from "${this.#parentName}"`);
2847
+ const parentCols = resolveColumns(this.#parent, this.#selectedColumns, this.#parentName);
2848
+ const childCols = [];
2849
+ for (const join of this.#joins) {
2850
+ const entries = columnEntries(join.table);
2851
+ for (const [, c] of entries) {
2852
+ childCols.push(`${join.name}.${c.name} AS ${join.name}_${c.name}`);
2853
+ }
2854
+ }
2855
+ const joinKeyword = this.#joinType === "left" ? "LEFT JOIN" : "INNER JOIN";
2856
+ const joinClauses = [];
2857
+ const joinParams = [];
2858
+ for (const join of this.#joins) {
2859
+ const joinOn = compileConditions([join.condition], joinParams);
2860
+ joinClauses.push(`${joinKeyword} ${join.name} ON ${joinOn}`);
2861
+ }
2862
+ const whereParams = [];
2863
+ const where = compileConditions(this.#conditions, whereParams);
2864
+ let sql = `SELECT ${parentCols}${childCols.length ? ", " + childCols.join(", ") : ""} FROM ${this.#parentName} ${joinClauses.join(" ")}`;
2865
+ if (where !== "1=1")
2866
+ sql += ` WHERE ${where}`;
2867
+ if (this.#orderByClauses.length > 0) {
2868
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
2869
+ sql += ` ORDER BY ${orderClauses}`;
2870
+ }
2871
+ if (this.#limitValue !== null)
2872
+ sql += ` LIMIT ${this.#limitValue}`;
2873
+ if (this.#offsetValue !== null)
2874
+ sql += ` OFFSET ${this.#offsetValue}`;
2875
+ return { sql, params: [...joinParams, ...whereParams] };
2876
+ }
2877
+ async execute() {
2878
+ const { sql, params } = this.toSQL();
2879
+ try {
2880
+ const rows = await this.#executor.all(sql, params);
2881
+ return this.#decodeJoinRows(rows);
2882
+ } catch (e) {
2883
+ if (e instanceof FlintQueryError)
2884
+ throw e;
2885
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
2886
+ }
2887
+ }
2888
+ #decodeJoinRows(rows) {
2889
+ const parentEntries = columnEntries(this.#parent);
2890
+ const pkKey = findPKKey(this.#parent);
2891
+ const pkColName = getCol(this.#parent, pkKey).name;
2892
+ const childEntryMaps = [];
2893
+ for (const j of this.#joins) {
2894
+ childEntryMaps.push({
2895
+ name: j.name,
2896
+ entries: columnEntries(j.table),
2897
+ table: j.table
2898
+ });
2899
+ }
2900
+ const grouped = new Map;
2901
+ for (const row of rows) {
2902
+ const pk = row[pkColName];
2903
+ if (!grouped.has(pk)) {
2904
+ const parentRow = {};
2905
+ for (const [key, col] of parentEntries) {
2906
+ parentRow[key] = row[col.name];
2907
+ }
2908
+ grouped.set(pk, {
2909
+ parent: parentRow,
2910
+ children: childEntryMaps.map(() => [])
2911
+ });
2912
+ }
2913
+ const group = grouped.get(pk);
2914
+ childEntryMaps.forEach((childMap, i) => {
2915
+ const childRow = {};
2916
+ let hasNonNullChild = false;
2917
+ for (const [key, col] of childMap.entries) {
2918
+ const val = row[`${childMap.name}_${col.name}`];
2919
+ childRow[key] = val;
2920
+ if (val != null)
2921
+ hasNonNullChild = true;
2922
+ }
2923
+ if (this.#joinType === "left" && !hasNonNullChild)
2924
+ return;
2925
+ group.children[i].push(childRow);
2926
+ });
2927
+ }
2928
+ const result = [];
2929
+ for (const { parent, children } of grouped.values()) {
2930
+ const decodedParent = this.#selectedColumns ? decodeSelectedRow(parent, this.#parent, this.#selectedColumns) : decodeRow(parent, this.#parent);
2931
+ const nested = { ...decodedParent };
2932
+ childEntryMaps.forEach((childMap, i) => {
2933
+ nested[childMap.name] = children[i].map((c) => decodeRow(c, childMap.table));
2934
+ });
2935
+ result.push(nested);
2936
+ }
2937
+ return result;
2938
+ }
2939
+ }
2940
+
2941
+ class SingleJoinBuilderImpl {
2942
+ #executor;
2943
+ #parent;
2944
+ #parentName;
2945
+ #joins;
2946
+ #joinType;
2947
+ #conditions;
2948
+ #selectedColumns;
2949
+ #orderByClauses;
2950
+ #offsetValue;
2951
+ constructor(executor, parent, parentName, joins, joinType, conditions, selectedColumns = null, orderByClauses = [], offsetValue = null) {
2952
+ this.#executor = executor;
2953
+ this.#parent = parent;
2954
+ this.#parentName = parentName;
2955
+ this.#joins = joins;
2956
+ this.#joinType = joinType;
2957
+ this.#conditions = conditions;
2958
+ this.#selectedColumns = selectedColumns;
2959
+ this.#orderByClauses = orderByClauses;
2960
+ this.#offsetValue = offsetValue;
2961
+ }
2962
+ where(condition) {
2963
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#offsetValue);
2964
+ }
2965
+ orderBy(key, direction = "asc") {
2966
+ const column = getCol(this.#parent, key);
2967
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#offsetValue);
2968
+ }
2969
+ offset(n) {
2970
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, n);
2971
+ }
2972
+ toSQL() {
2973
+ const allowedTables = [this.#parent, ...this.#joins.map((j) => j.table)];
2974
+ validateColumnOwnership(this.#conditions, allowedTables, `SELECT from "${this.#parentName}"`);
2975
+ const parentCols = resolveColumns(this.#parent, this.#selectedColumns, this.#parentName);
2976
+ const childCols = [];
2977
+ for (const join of this.#joins) {
2978
+ const entries = columnEntries(join.table);
2979
+ for (const [, c] of entries) {
2980
+ childCols.push(`${join.name}.${c.name} AS ${join.name}_${c.name}`);
2981
+ }
2982
+ }
2983
+ const joinKeyword = this.#joinType === "left" ? "LEFT JOIN" : "INNER JOIN";
2984
+ const joinClauses = [];
2985
+ const joinParams = [];
2986
+ for (const join of this.#joins) {
2987
+ const joinOn = compileConditions([join.condition], joinParams);
2988
+ joinClauses.push(`${joinKeyword} ${join.name} ON ${joinOn}`);
2989
+ }
2990
+ const whereParams = [];
2991
+ const where = compileConditions(this.#conditions, whereParams);
2992
+ let sql = `SELECT ${parentCols}${childCols.length ? ", " + childCols.join(", ") : ""} FROM ${this.#parentName} ${joinClauses.join(" ")}`;
2993
+ if (where !== "1=1")
2994
+ sql += ` WHERE ${where}`;
2995
+ if (this.#orderByClauses.length > 0) {
2996
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
2997
+ sql += ` ORDER BY ${orderClauses}`;
2998
+ }
2999
+ sql += " LIMIT 1";
3000
+ if (this.#offsetValue !== null)
3001
+ sql += ` OFFSET ${this.#offsetValue}`;
3002
+ return { sql, params: [...joinParams, ...whereParams] };
3003
+ }
3004
+ async execute() {
3005
+ const { sql, params } = this.toSQL();
3006
+ try {
3007
+ const rows = await this.#executor.all(sql, params);
3008
+ const records = rows;
3009
+ if (records.length === 0)
3010
+ return null;
3011
+ return this.#decodeJoinRow(records);
3012
+ } catch (e) {
3013
+ if (e instanceof FlintQueryError)
3014
+ throw e;
3015
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
3016
+ }
3017
+ }
3018
+ #decodeJoinRow(rows) {
3019
+ const parentEntries = columnEntries(this.#parent);
3020
+ const pkKey = findPKKey(this.#parent);
3021
+ const pkColName = getCol(this.#parent, pkKey).name;
3022
+ const childEntryMaps = [];
3023
+ for (const j of this.#joins) {
3024
+ childEntryMaps.push({
3025
+ name: j.name,
3026
+ entries: columnEntries(j.table),
3027
+ table: j.table
3028
+ });
3029
+ }
3030
+ const grouped = new Map;
3031
+ for (const r of rows) {
3032
+ const pk = r[pkColName];
3033
+ if (!grouped.has(pk)) {
3034
+ const parentRow = {};
3035
+ for (const [key, col] of parentEntries) {
3036
+ parentRow[key] = r[col.name];
3037
+ }
3038
+ grouped.set(pk, {
3039
+ parent: parentRow,
3040
+ children: childEntryMaps.map(() => [])
3041
+ });
3042
+ }
3043
+ const group = grouped.get(pk);
3044
+ childEntryMaps.forEach((childMap, i) => {
3045
+ const childRow = {};
3046
+ let hasNonNullChild = false;
3047
+ for (const [key, col] of childMap.entries) {
3048
+ const val = r[`${childMap.name}_${col.name}`];
3049
+ childRow[key] = val;
3050
+ if (val != null)
3051
+ hasNonNullChild = true;
3052
+ }
3053
+ if (this.#joinType === "left" && !hasNonNullChild)
3054
+ return;
3055
+ group.children[i].push(childRow);
3056
+ });
3057
+ }
3058
+ const first = grouped.values().next().value;
3059
+ if (!first)
3060
+ return null;
3061
+ const decodedParent = this.#selectedColumns ? decodeSelectedRow(first.parent, this.#parent, this.#selectedColumns) : decodeRow(first.parent, this.#parent);
3062
+ const nested = { ...decodedParent };
3063
+ childEntryMaps.forEach((childMap, i) => {
3064
+ nested[childMap.name] = first.children[i].map((c) => decodeRow(c, childMap.table));
3065
+ });
3066
+ return nested;
3067
+ }
3068
+ }
3069
+
3070
+ class InsertValuesBuilder {
3071
+ #executor;
3072
+ #tableName;
3073
+ #table;
3074
+ constructor(executor, tableName, table) {
3075
+ this.#executor = executor;
3076
+ this.#tableName = tableName;
3077
+ this.#table = table;
3078
+ }
3079
+ values(rowOrRows) {
3080
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, rowOrRows);
3081
+ }
3082
+ }
3083
+
3084
+ class InsertBuilder {
3085
+ #executor;
3086
+ #tableName;
3087
+ #table;
3088
+ #rows;
3089
+ #returning;
3090
+ #onConflict;
3091
+ constructor(executor, tableName, table, rowOrRows, returning = false, onConflict) {
3092
+ this.#executor = executor;
3093
+ this.#tableName = tableName;
3094
+ this.#table = table;
3095
+ this.#rows = Array.isArray(rowOrRows) ? rowOrRows : [rowOrRows];
3096
+ this.#returning = returning;
3097
+ this.#onConflict = onConflict;
3098
+ }
3099
+ returning(keys) {
3100
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, this.#rows, keys ?? true, this.#onConflict);
3101
+ }
3102
+ onConflictDoNothing() {
3103
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, this.#rows, this.#returning, { mode: "nothing" });
3104
+ }
3105
+ onConflictDoUpdate(options) {
3106
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, this.#rows, this.#returning, {
3107
+ mode: "update",
3108
+ target: options.target,
3109
+ set: options.set
3110
+ });
3111
+ }
3112
+ toSQL() {
3113
+ const entries = columnEntries(this.#table);
3114
+ const inserts = [];
3115
+ for (const [key, c] of entries) {
3116
+ const allUndefined = this.#rows.every((row) => row[key] === undefined);
3117
+ if (allUndefined && (c.__internal.hasDefault || c.__internal.isAutoIncrement)) {
3118
+ continue;
3119
+ }
3120
+ inserts.push([key, c]);
3121
+ }
3122
+ if (inserts.length === 0) {
3123
+ const allDefault = entries.filter(([, c]) => c.__internal.hasDefault || c.__internal.isAutoIncrement || c.__internal.hasDefaultNow);
3124
+ const names2 = allDefault.map(([, c]) => c.name).join(", ");
3125
+ const placeholders = allDefault.map(() => "DEFAULT").join(", ");
3126
+ return {
3127
+ sql: `INSERT INTO ${this.#tableName} (${names2}) VALUES (${placeholders})`,
3128
+ params: []
3129
+ };
3130
+ }
3131
+ const names = inserts.map(([, c]) => c.name).join(", ");
3132
+ const placeholderRow = inserts.map(() => "?").join(", ");
3133
+ const allPlaceholders = this.#rows.map(() => `(${placeholderRow})`).join(", ");
3134
+ const params = [];
3135
+ for (const row of this.#rows) {
3136
+ for (const [key, c] of inserts) {
3137
+ const value = row[key];
3138
+ if (value === undefined && c.__internal.hasDefaultNow) {
3139
+ params.push(c.__internal.encode(new Date));
3140
+ } else {
3141
+ params.push(c.__internal.encode(value));
3142
+ }
3143
+ }
3144
+ }
3145
+ let sql = `INSERT INTO ${this.#tableName} (${names}) VALUES ${allPlaceholders}`;
3146
+ if (this.#onConflict) {
3147
+ if (this.#onConflict.mode === "nothing") {
3148
+ sql += " ON CONFLICT DO NOTHING";
3149
+ } else {
3150
+ const target = this.#onConflict.target;
3151
+ const targetCols = Array.isArray(target) ? target : [target];
3152
+ const targetNames = targetCols.map((c) => c.name).join(", ");
3153
+ const setEntries = Object.entries(this.#onConflict.set);
3154
+ const setClauses = setEntries.map(([key, value]) => {
3155
+ const col = getCol(this.#table, key);
3156
+ if (value === undefined)
3157
+ return null;
3158
+ return `${col.name} = excluded.${col.name}`;
3159
+ }).filter(Boolean);
3160
+ if (setClauses.length > 0) {
3161
+ sql += ` ON CONFLICT (${targetNames}) DO UPDATE SET ${setClauses.join(", ")}`;
3162
+ }
3163
+ }
3164
+ }
3165
+ if (this.#returning) {
3166
+ if (Array.isArray(this.#returning)) {
3167
+ const cols = this.#returning.map((k) => getCol(this.#table, k).name).join(", ");
3168
+ sql += ` RETURNING ${cols}`;
3169
+ } else {
3170
+ sql += " RETURNING *";
3171
+ }
3172
+ }
3173
+ return { sql, params };
3174
+ }
3175
+ async execute() {
3176
+ const { sql, params } = this.toSQL();
3177
+ try {
3178
+ if (this.#returning) {
3179
+ const rows = await this.#executor.all(sql, params);
3180
+ const records = rows;
3181
+ if (Array.isArray(this.#returning)) {
3182
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#returning));
3183
+ }
3184
+ return records.map((r) => decodeRow(r, this.#table));
3185
+ }
3186
+ await this.#executor.run(sql, params);
3187
+ return;
3188
+ } catch (e) {
3189
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
3190
+ }
3191
+ }
3192
+ }
3193
+
3194
+ class UpdateSetBuilder {
3195
+ #executor;
3196
+ #tableName;
3197
+ #table;
3198
+ constructor(executor, tableName, table) {
3199
+ this.#executor = executor;
3200
+ this.#tableName = tableName;
3201
+ this.#table = table;
3202
+ }
3203
+ set(partial) {
3204
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, partial);
3205
+ }
3206
+ }
3207
+
3208
+ class UpdateBuilder {
3209
+ #executor;
3210
+ #tableName;
3211
+ #table;
3212
+ #set;
3213
+ #conditions;
3214
+ #returning;
3215
+ constructor(executor, tableName, table, set, conditions = [], returning = false) {
3216
+ this.#executor = executor;
3217
+ this.#tableName = tableName;
3218
+ this.#table = table;
3219
+ this.#set = set;
3220
+ this.#conditions = conditions;
3221
+ this.#returning = returning;
3222
+ }
3223
+ set(partial) {
3224
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, { ...this.#set, ...partial }, this.#conditions, this.#returning);
3225
+ }
3226
+ where(condition) {
3227
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, this.#set, [...this.#conditions, condition], this.#returning);
3228
+ }
3229
+ returning(keys) {
3230
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, this.#set, this.#conditions, keys ?? true);
3231
+ }
3232
+ toSQL() {
3233
+ validateColumnOwnership(this.#conditions, [this.#table], `UPDATE "${this.#tableName}"`);
3234
+ const params = [];
3235
+ const setClauses = [];
3236
+ for (const key of Object.keys(this.#set)) {
3237
+ const col = getCol(this.#table, key);
3238
+ if (col.__internal.hasOnUpdate) {
3239
+ setClauses.push(`${col.name} = ?`);
3240
+ params.push(col.__internal.encode(new Date));
3241
+ continue;
3242
+ }
3243
+ setClauses.push(`${col.name} = ?`);
3244
+ params.push(col.__internal.encode(this.#set[key]));
3245
+ }
3246
+ let sql = `UPDATE ${this.#tableName} SET ${setClauses.join(", ")}`;
3247
+ const where = compileConditions(this.#conditions, params);
3248
+ if (where !== "1=1")
3249
+ sql += ` WHERE ${where}`;
3250
+ if (this.#returning) {
3251
+ if (Array.isArray(this.#returning)) {
3252
+ const cols = this.#returning.map((k) => getCol(this.#table, k).name).join(", ");
3253
+ sql += ` RETURNING ${cols}`;
3254
+ } else {
3255
+ sql += " RETURNING *";
3256
+ }
3257
+ }
3258
+ return { sql, params };
3259
+ }
3260
+ async execute() {
3261
+ const { sql, params } = this.toSQL();
3262
+ try {
3263
+ if (this.#returning) {
3264
+ const rows = await this.#executor.all(sql, params);
3265
+ const records = rows;
3266
+ if (Array.isArray(this.#returning)) {
3267
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#returning));
3268
+ }
3269
+ return records.map((r) => decodeRow(r, this.#table));
3270
+ }
3271
+ await this.#executor.run(sql, params);
3272
+ return;
3273
+ } catch (e) {
3274
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
3275
+ }
3276
+ }
3277
+ }
3278
+
3279
+ class DeleteBuilder {
3280
+ #executor;
3281
+ #tableName;
3282
+ #table;
3283
+ #conditions;
3284
+ #returning;
3285
+ constructor(executor, tableName, table, conditions = [], returning = false) {
3286
+ this.#executor = executor;
3287
+ this.#tableName = tableName;
3288
+ this.#table = table;
3289
+ this.#conditions = conditions;
3290
+ this.#returning = returning;
3291
+ }
3292
+ where(condition) {
3293
+ return new DeleteBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#returning);
3294
+ }
3295
+ returning(keys) {
3296
+ return new DeleteBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, keys ?? true);
3297
+ }
3298
+ toSQL() {
3299
+ validateColumnOwnership(this.#conditions, [this.#table], `DELETE from "${this.#tableName}"`);
3300
+ const params = [];
3301
+ let sql = `DELETE FROM ${this.#tableName}`;
3302
+ const where = compileConditions(this.#conditions, params);
3303
+ if (where !== "1=1")
3304
+ sql += ` WHERE ${where}`;
3305
+ if (this.#returning) {
3306
+ if (Array.isArray(this.#returning)) {
3307
+ const cols = this.#returning.map((k) => getCol(this.#table, k).name).join(", ");
3308
+ sql += ` RETURNING ${cols}`;
3309
+ } else {
3310
+ sql += " RETURNING *";
3311
+ }
3312
+ }
3313
+ return { sql, params };
3314
+ }
3315
+ async execute() {
3316
+ const { sql, params } = this.toSQL();
3317
+ try {
3318
+ if (this.#returning) {
3319
+ const rows = await this.#executor.all(sql, params);
3320
+ const records = rows;
3321
+ if (Array.isArray(this.#returning)) {
3322
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#returning));
3323
+ }
3324
+ return records.map((r) => decodeRow(r, this.#table));
3325
+ }
3326
+ await this.#executor.run(sql, params);
3327
+ return;
3328
+ } catch (e) {
3329
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
3330
+ }
3331
+ }
3332
+ }
3333
+ var init_builder = __esm(() => {
3334
+ init_errors();
3335
+ });
3336
+
3337
+ // src/query/aggregates.ts
3338
+ function getTableName(table) {
3339
+ return table._.name;
3340
+ }
3341
+ function getColumnName(column) {
3342
+ return column.name;
3343
+ }
3344
+ function compileWhere(condition) {
3345
+ if (!condition) {
3346
+ return { whereSql: "", params: [] };
3347
+ }
3348
+ const params = [];
3349
+ const whereSql = compileCondition(condition, params);
3350
+ return { whereSql: ` WHERE ${whereSql}`, params };
3351
+ }
3352
+ async function count(executor, table, condition) {
3353
+ const tableName = getTableName(table);
3354
+ const { whereSql, params } = compileWhere(condition);
3355
+ const sql = `SELECT count(*) as cnt FROM ${tableName}${whereSql}`;
3356
+ const result = await executor.get(sql, params);
3357
+ return result.cnt;
3358
+ }
3359
+ async function countColumn(executor, table, column, condition) {
3360
+ const tableName = getTableName(table);
3361
+ const columnName = getColumnName(column);
3362
+ const { whereSql, params } = compileWhere(condition);
3363
+ const sql = `SELECT count(${columnName}) as cnt FROM ${tableName}${whereSql}`;
3364
+ const result = await executor.get(sql, params);
3365
+ return result.cnt;
3366
+ }
3367
+ async function sum(executor, table, column, condition) {
3368
+ const tableName = getTableName(table);
3369
+ const columnName = getColumnName(column);
3370
+ const { whereSql, params } = compileWhere(condition);
3371
+ const sql = `SELECT sum(${columnName}) as total FROM ${tableName}${whereSql}`;
3372
+ const result = await executor.get(sql, params);
3373
+ return result.total;
3374
+ }
3375
+ async function avg(executor, table, column, condition) {
3376
+ const tableName = getTableName(table);
3377
+ const columnName = getColumnName(column);
3378
+ const { whereSql, params } = compileWhere(condition);
3379
+ const sql = `SELECT avg(${columnName}) as average FROM ${tableName}${whereSql}`;
3380
+ const result = await executor.get(sql, params);
3381
+ return result.average;
3382
+ }
3383
+ async function min(executor, table, column, condition) {
3384
+ const tableName = getTableName(table);
3385
+ const columnName = getColumnName(column);
3386
+ const { whereSql, params } = compileWhere(condition);
3387
+ const sql = `SELECT min(${columnName}) as minimum FROM ${tableName}${whereSql}`;
3388
+ const result = await executor.get(sql, params);
3389
+ return result.minimum;
3390
+ }
3391
+ async function max(executor, table, column, condition) {
3392
+ const tableName = getTableName(table);
3393
+ const columnName = getColumnName(column);
3394
+ const { whereSql, params } = compileWhere(condition);
3395
+ const sql = `SELECT max(${columnName}) as maximum FROM ${tableName}${whereSql}`;
3396
+ const result = await executor.get(sql, params);
3397
+ return result.maximum;
3398
+ }
3399
+ var init_aggregates = () => {};
3400
+
3401
+ // src/flint.ts
3402
+ function createClient(executor) {
3403
+ return {
3404
+ select: () => new SelectFromBuilder(executor),
3405
+ insert: (table) => new InsertValuesBuilder(executor, table._.name, table),
3406
+ update: (table) => new UpdateSetBuilder(executor, table._.name, table),
3407
+ delete: (table) => new DeleteBuilder(executor, table._.name, table),
3408
+ leftJoin: (parent) => new JoinStage1(executor, parent, parent._.name, "left"),
3409
+ innerJoin: (parent) => new JoinStage1(executor, parent, parent._.name, "inner"),
3410
+ batch: (queries) => {
3411
+ const stmts = queries.map((q) => q.toSQL());
3412
+ return executor.transaction(async () => {
3413
+ for (const stmt of stmts) {
3414
+ await executor.run(stmt.sql, stmt.params);
3415
+ }
3416
+ });
3417
+ },
3418
+ count: (table, condition) => count(executor, table, condition),
3419
+ countColumn: (table, column, condition) => countColumn(executor, table, column, condition),
3420
+ sum: (table, column, condition) => sum(executor, table, column, condition),
3421
+ avg: (table, column, condition) => avg(executor, table, column, condition),
3422
+ min: (table, column, condition) => min(executor, table, column, condition),
3423
+ max: (table, column, condition) => max(executor, table, column, condition),
3424
+ $run(query, ...params) {
3425
+ return executor.run(query, params);
3426
+ },
3427
+ $executor: executor
3428
+ };
3429
+ }
3430
+ function sql(strings, ...values) {
3431
+ let query = "";
3432
+ const params = [];
3433
+ for (let i = 0;i < strings.length; i++) {
3434
+ query += strings[i];
3435
+ if (i < values.length) {
3436
+ query += "?";
3437
+ params.push(values[i]);
3438
+ }
3439
+ }
3440
+ return { sql: query, params };
3441
+ }
3442
+ var init_flint = __esm(() => {
3443
+ init_builder();
3444
+ init_aggregates();
3445
+ });
3446
+
3447
+ // src/drivers/turso-sync.ts
3448
+ var exports_turso_sync = {};
3449
+ __export(exports_turso_sync, {
3450
+ flint: () => flint,
3451
+ TursoSyncExecutor: () => TursoSyncExecutor
3452
+ });
3453
+ import { resolve } from "path";
3454
+ function sanitize(params) {
3455
+ return params.map((p) => p === undefined ? null : p);
3456
+ }
3457
+
3458
+ class TursoSyncExecutor {
3459
+ #db;
3460
+ constructor(db) {
3461
+ this.#db = db;
3462
+ }
3463
+ async all(sql2, params) {
3464
+ return this.#db.all(sql2, ...sanitize(params));
3465
+ }
3466
+ async get(sql2, params) {
3467
+ return this.#db.get(sql2, ...sanitize(params)) ?? null;
3468
+ }
3469
+ async run(sql2, params) {
3470
+ await this.#db.run(sql2, ...sanitize(params));
3471
+ }
3472
+ async transaction(fn) {
3473
+ await this.#db.exec("BEGIN");
3474
+ try {
3475
+ await fn();
3476
+ await this.#db.exec("COMMIT");
3477
+ } catch (e) {
3478
+ await this.#db.exec("ROLLBACK");
3479
+ throw e;
3480
+ }
3481
+ }
3482
+ close() {
3483
+ this.#db.close();
3484
+ }
3485
+ }
3486
+ async function flint(details) {
3487
+ const localPath = details.url.includes("://") ? details.url : resolve(details.url);
3488
+ const db = await connect2({
3489
+ path: localPath,
3490
+ url: details.syncUrl,
3491
+ authToken: details.authToken
3492
+ });
3493
+ return createClient(new TursoSyncExecutor(db));
3494
+ }
3495
+ var init_turso_sync = __esm(() => {
3496
+ init_promise2();
3497
+ init_flint();
3498
+ });
3499
+
3500
+ // src/entries/turso-sync.ts
3501
+ init_turso_sync();
3502
+ export {
3503
+ flint
3504
+ };